@eum-agent/llm-protocol-anthropic 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +579 -157
  2. package/package.json +4 -4
package/dist/index.js CHANGED
@@ -1,12 +1,24 @@
1
1
  import { z } from "zod";
2
2
  import Anthropic, { APIConnectionError, APIError } from "@anthropic-ai/sdk";
3
- import { countTokens } from "gpt-tokenizer/encoding/o200k_base";
4
3
  import { createHash } from "node:crypto";
4
+ import { setImmediate } from "node:timers/promises";
5
+ //#region src/logo.ts
6
+ /** Official Anthropic mark reused from the supplier extension's vendored SVG. */
7
+ const protocolLogo = "data:image/svg+xml,%3Csvg%20fill%3D%22currentColor%22%20fill-rule%3D%22evenodd%22%20height%3D%2224%22%20style%3D%22flex%3Anone%3Bline-height%3A1%22%20viewBox%3D%220%200%2024%2024%22%20width%3D%2224%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Ctitle%3EAnthropic%3C%2Ftitle%3E%3Cpath%20d%3D%22M13.827%203.52h3.603L24%2020h-3.603l-6.57-16.48zm-7.258%200h3.767L16.906%2020h-3.674l-1.343-3.461H5.017l-1.344%203.46H0L6.57%203.522zm4.132%209.959L8.453%207.687%206.205%2013.48H10.7z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E";
8
+ //#endregion
9
+ //#region src/protocol/address.ts
10
+ /** Preserves the configured API version and prefix before appending a resource path. */
11
+ function messagesBaseUrl(baseUrl) {
12
+ return typeof baseUrl === "string" ? baseUrl.replace(/\/+$/, "") : "";
13
+ }
14
+ //#endregion
5
15
  //#region src/protocol/facts.ts
6
16
  /** Parameter ranges and request limits for this provider wire. */
7
17
  const facts = {
8
- maxTokensRequired: true,
9
- maxTokensFallback: 8192,
18
+ outputLimit: {
19
+ support: "required",
20
+ ordinary: 16e3
21
+ },
10
22
  temperature: {
11
23
  min: 0,
12
24
  max: 1,
@@ -22,39 +34,10 @@ const facts = {
22
34
  //#endregion
23
35
  //#region src/protocol/errors.ts
24
36
  /**
25
- * SDK exception → port error. `@anthropic-ai/sdk`'s
26
- * `APIError` carries the response `.headers` and the raw `.error` body
27
- * verbatim — either can echo a credential (a misbehaving proxy reflecting
28
- * the `x-api-key`/`Authorization` request header back on an error
29
- * response). The port error is a *fresh* object: its message is built from
30
- * HTTP status and the SDK's own `type` discriminant such as
31
- * `'rate_limit_error'`, the headers object is never attached, and the body
32
- * travels as `providerText`, which the runtime's guard redacts against the
33
- * endpoint's credentials before showing it.
37
+ * SDK exceptions have two consumers: explicit probes retain provider text for
38
+ * their credential-redaction boundary, while Agent calls accept only fixed
39
+ * templates and allowlisted facts through the host factory.
34
40
  */
35
- /** Thrown by `stream()` once retries are exhausted (or the failure was
36
- * never retryable to begin with) — the one error shape the call-model
37
- * effect ever surfaces to the kernel. A plain `Error` subclass: the driver
38
- * (kernel's driver.ts) only ever reads `.message` off whatever an effect
39
- * handler throws, so `.message` alone is what has to stay both informative
40
- * and credential-free. */
41
- var ModelCallError = class extends Error {
42
- status;
43
- retryable;
44
- /** The endpoint's own error body, unredacted. The runtime's guard removes
45
- * every credential of the endpoint from it before it reaches a reason. */
46
- providerText;
47
- /** What the status alone says the refusal is (`failureKindOf`). */
48
- kind;
49
- constructor(message, options) {
50
- super(message);
51
- this.name = "ModelCallError";
52
- this.status = options.status;
53
- this.retryable = options.retryable;
54
- this.providerText = options.providerText;
55
- this.kind = options.status === 413 ? "request-too-large" : void 0;
56
- }
57
- };
58
41
  /** Timeouts, conflicts, rate limits and 5xx are worth a second attempt;
59
42
  * every other status is not — retrying a bad request or an authentication
60
43
  * failure only spends the backoff budget on a call that will never succeed. */
@@ -68,8 +51,9 @@ function retryAfterMs(error) {
68
51
  const header = error.headers?.get("retry-after");
69
52
  if (!header) return void 0;
70
53
  const seconds = Number(header);
71
- if (!Number.isFinite(seconds)) return void 0;
72
- return seconds * 1e3;
54
+ if (!Number.isFinite(seconds) || seconds < 0) return void 0;
55
+ const milliseconds = seconds * 1e3;
56
+ return Number.isFinite(milliseconds) ? milliseconds : void 0;
73
57
  }
74
58
  /** Converts any exception the SDK call can throw into a `ModelCallError`.
75
59
  * Never reads `error.headers` into the result; the body goes to
@@ -86,24 +70,42 @@ function streamErrorType(error) {
86
70
  const inner = body?.error?.type ?? body?.type;
87
71
  return typeof inner === "string" ? inner : void 0;
88
72
  }
89
- function toPortError(error) {
90
- if (error instanceof APIError) {
91
- const status = error.status;
92
- const retryable = error instanceof APIConnectionError || isRetryableStatus(status) || status === void 0 && RETRYABLE_TYPES.has(streamErrorType(error) ?? "");
93
- const type = error.type;
94
- return new ModelCallError(`Anthropic API error (status ${status ?? "unknown"}${type ? `, type ${type}` : ""})`, {
95
- status,
96
- retryable,
97
- providerText: providerTextOf(error)
98
- });
99
- }
100
- return new ModelCallError(`Anthropic call failed: ${error instanceof Error ? error.message : String(error)}`, { retryable: false });
101
- }
102
- /** The parsed error body when the SDK parsed one, else the SDK's message,
103
- * which carries the raw body text. Never the headers. */
104
- function providerTextOf(error) {
105
- const text = error.error === void 0 ? error.message : JSON.stringify(error.error);
106
- return text === void 0 || text.trim() === "" ? void 0 : text;
73
+ /** Maps verified SDK classes and factory identities to bounded Agent failure candidates. */
74
+ function toModelFailure(error, failures) {
75
+ if (failures.owns(error)) return error;
76
+ if (!(error instanceof APIError)) return failures.create({
77
+ code: "unknown",
78
+ stage: "unknown",
79
+ category: "unknown",
80
+ source: "unknown",
81
+ retryable: false
82
+ });
83
+ const rawCode = streamErrorType(error) ?? error.type;
84
+ const providerCode = typeof rawCode === "string" && (/* @__PURE__ */ new Set([
85
+ "usage_not_included",
86
+ "usage_limit_reached",
87
+ "insufficient_quota",
88
+ "context_length_exceeded",
89
+ "rate_limit_exceeded",
90
+ "overloaded_error",
91
+ "api_error",
92
+ "rate_limit_error",
93
+ "cyber_policy",
94
+ "invalid_prompt",
95
+ "bio_policy",
96
+ "misalignment_policy_violation"
97
+ ])).has(rawCode) ? rawCode : void 0;
98
+ const connection = error instanceof APIConnectionError;
99
+ const status = Number.isInteger(error.status) && Number(error.status) >= 100 && Number(error.status) <= 599 ? error.status : void 0;
100
+ return failures.create({
101
+ code: connection ? "stream-interrupted" : status === 413 ? "request-too-large" : status === void 0 ? "provider-error" : "http-error",
102
+ stage: connection ? "transport" : status === 413 ? "request" : status === void 0 ? "stream" : "transport",
103
+ category: connection ? "network" : status === 413 ? "request-too-large" : "provider",
104
+ source: connection ? "transport" : "protocol",
105
+ ...status === void 0 ? {} : { status },
106
+ retryable: connection || isRetryableStatus(status) || status === void 0 && RETRYABLE_TYPES.has(streamErrorType(error) ?? ""),
107
+ ...providerCode === void 0 ? {} : { providerCode }
108
+ });
107
109
  }
108
110
  //#endregion
109
111
  //#region src/protocol/request.ts
@@ -129,7 +131,7 @@ function providerTextOf(error) {
129
131
  * goes back as the `redacted_thinking` it came as.
130
132
  */
131
133
  const SUMMARY_THINKING_HEADROOM = 8192;
132
- const DEFAULT_MAX_TOKENS = 8192;
134
+ const DEFAULT_MAX_TOKENS = 16e3;
133
135
  const TOOL_ID = /^[a-zA-Z0-9_-]+$/;
134
136
  /**
135
137
  * The id Anthropic is sent for one tool call. A legal id goes as it is; any
@@ -171,7 +173,7 @@ function toContentBlockParams(part, at, context) {
171
173
  } : {
172
174
  type: "thinking",
173
175
  thinking: part.text,
174
- signature: part.signature ?? ""
176
+ ...context.unsignedThinking ? {} : { signature: part.signature ?? "" }
175
177
  }];
176
178
  case "tool-use": return [{
177
179
  type: "tool_use",
@@ -199,12 +201,10 @@ function toContentBlockParams(part, at, context) {
199
201
  /**
200
202
  * Whether this endpoint can send one message's thinking group back.
201
203
  *
202
- * Two ways it cannot. **No signature**: it was never signed — a transcript
203
- * resumed from an OpenAI-style endpoint, or from before signatures were
204
- * carried — and a fabricated one is worse than none, because Anthropic
205
- * verifies it and answers a modified block with `400 invalid_request_error`,
206
- * failing every continuation. Endpoint, model and prefix attribution must all
207
- * match because a change to any covered input can invalidate the signature.
204
+ * Signed replay requires a signature and matching endpoint, model and prefix.
205
+ * Unsigned replay accepts optional returned proof but sends only visible text;
206
+ * issuer and model attribution still must match. Incomplete history is omitted.
207
+ * Signed mode never fabricates proof that the server cannot verify.
208
208
  * One incompatible member drops the whole group so no middle block is removed.
209
209
  *
210
210
  * Comparing endpoint ids is deliberately coarser than "same signer": two keys
@@ -212,10 +212,12 @@ function toContentBlockParams(part, at, context) {
212
212
  * verified would reject the entire request.
213
213
  */
214
214
  function thinkingGroupIsSendable(message, options, prefix) {
215
+ if (!message.content.some((part) => part.type === "text" && part.text !== "" || part.type === "tool-use")) return false;
216
+ if (options.reasoningReplay === "omit" || message.outputTruncation?.incompleteThinking) return false;
215
217
  const thinking = message.content.filter((part) => part.type === "thinking");
216
218
  if (thinking.length === 0) return true;
217
219
  const model = options.model ?? "";
218
- return thinking.every((part) => part.signature !== void 0 && part.issuer !== void 0 && part.issuer === options.endpoint && part.originModel === model && part.prefix === prefix);
220
+ return thinking.every((part) => (options.reasoningReplay === "unsigned-thinking" || part.signature !== void 0) && part.issuer !== void 0 && part.issuer === options.endpoint && part.originModel === model && (options.reasoningReplay === "unsigned-thinking" || part.prefix === prefix));
219
221
  }
220
222
  /** A text block with nothing in it: Anthropic refuses one. */
221
223
  function isEmptyText(part) {
@@ -235,11 +237,6 @@ function noteBlock(notes) {
235
237
  text
236
238
  }];
237
239
  }
238
- /**
239
- * Appends blocks to the conversation's last user message, or as a user
240
- * message of their own after an assistant one. The Messages API combines
241
- * consecutive messages of one role, so both forms are one user turn.
242
- */
243
240
  function appendUser(messages, blocks) {
244
241
  if (blocks.length === 0) return;
245
242
  const last = messages.at(-1);
@@ -263,7 +260,14 @@ function appendUser(messages, blocks) {
263
260
  */
264
261
  function render(messages, trailing, sendThinking, context) {
265
262
  const out = [];
263
+ const updates = new Map(context.effortUpdates?.map((update) => [update.beforeUserMessageId, update.effort]));
266
264
  messages.forEach((message, index) => {
265
+ const effort = updates.get(message.id);
266
+ if (effort !== void 0) out.push({
267
+ role: "system",
268
+ content: [],
269
+ output_config: { effort }
270
+ });
267
271
  if (message.role === "assistant") appendUser(out, noteBlock(message.volatile));
268
272
  const content = blocksOf(message, index, sendThinking(message, index), context);
269
273
  if (content.length === 0) return;
@@ -309,10 +313,13 @@ function prefixOf(system, tools, messages, support) {
309
313
  * signature: everything before that message, its own recorded notes included
310
314
  * — they ended the request it answered. `messageIndex` names the message.
311
315
  */
312
- function anthropicPrefixBefore(request, messageIndex, media, support) {
316
+ function anthropicPrefixBefore(request, messageIndex, media, support, effortUpdates) {
313
317
  const before = request.messages.slice(0, messageIndex);
314
318
  const notes = request.messages[messageIndex]?.volatile;
315
- return prefixOf(systemOf(request), toolsOf(request), render(before, notes, () => false, fingerprintContext(request, media, support)), support);
319
+ return prefixOf(systemOf(request), toolsOf(request), render(before, notes, () => false, {
320
+ ...fingerprintContext(request, media, support),
321
+ effortUpdates
322
+ }), support);
316
323
  }
317
324
  /** The send plan, from the options' media context or the permissive default. */
318
325
  function planOf(request, media, support) {
@@ -335,19 +342,24 @@ function fingerprintContext(request, media, support) {
335
342
  * carried, its notes included, rendered the way `anthropicPrefixBefore`
336
343
  * renders it on the next step and without cache marks.
337
344
  */
338
- function anthropicRequestPrefix(request, media, support) {
339
- return prefixOf(systemOf(request), toolsOf(request), render(request.messages, request.volatile, () => false, fingerprintContext(request, media, support)), support);
345
+ function anthropicRequestPrefix(request, media, support, effortUpdates) {
346
+ return prefixOf(systemOf(request), toolsOf(request), render(request.messages, request.volatile, () => false, {
347
+ ...fingerprintContext(request, media, support),
348
+ effortUpdates
349
+ }), support);
340
350
  }
341
351
  /** Counts provider-retained thinking state that is actually replayed. */
342
352
  function anthropicHiddenInputTokens(request, options) {
353
+ if (options.reasoningReplay === "unsigned-thinking") return 0;
343
354
  return request.messages.reduce((total, message, index) => {
344
- if (!thinkingGroupIsSendable(message, options, anthropicPrefixBefore(request, index, options.media, options.support))) return total;
355
+ if (!thinkingGroupIsSendable(message, options, anthropicPrefixBefore(request, index, options.media, options.support, options.effortUpdates))) return total;
345
356
  return total + Math.max(0, ...message.content.map((part) => part.type === "thinking" ? part.outputTokens ?? 0 : 0));
346
357
  }, 0);
347
358
  }
348
359
  const EPHEMERAL = { type: "ephemeral" };
349
360
  /** Marks the last markable block of one message. */
350
361
  function markLast(message) {
362
+ if (message.role === "system") return message;
351
363
  if (typeof message.content === "string") return message;
352
364
  const content = [...message.content];
353
365
  for (let index = content.length - 1; index >= 0; index -= 1) {
@@ -385,7 +397,7 @@ function toAnthropicRequest(request, options) {
385
397
  const ordinaryMaxTokens = options.maxTokens ?? DEFAULT_MAX_TOKENS;
386
398
  const thinkingOn = options.thinking !== void 0 && options.thinking.type !== "disabled";
387
399
  const maxTokens = summary ? Math.min(request.summaryMaxTokens, Number.isInteger(ordinaryMaxTokens) && ordinaryMaxTokens > 0 ? ordinaryMaxTokens : request.summaryMaxTokens) + (thinkingOn ? SUMMARY_THINKING_HEADROOM : 0) : ordinaryMaxTokens;
388
- const system = request.system?.map((text, index, all) => index === all.length - 1 ? {
400
+ const system = request.system?.map((text, index, all) => index === all.length - 1 && options.cacheBreakpoints !== false ? {
389
401
  type: "text",
390
402
  text,
391
403
  cache_control: EPHEMERAL
@@ -394,9 +406,11 @@ function toAnthropicRequest(request, options) {
394
406
  text
395
407
  });
396
408
  const tools = toolsOf(request);
397
- const messages = render(request.messages, request.volatile, (message, index) => thinkingGroupIsSendable(message, options, anthropicPrefixBefore(request, index, options.media, options.support)), {
409
+ const messages = render(request.messages, request.volatile, (message, index) => thinkingGroupIsSendable(message, options, anthropicPrefixBefore(request, index, options.media, options.support, options.effortUpdates)), {
398
410
  plan: planOf(request, options.media, options.support),
399
- rendering: "wire"
411
+ rendering: "wire",
412
+ unsignedThinking: options.reasoningReplay === "unsigned-thinking",
413
+ effortUpdates: options.effortUpdates
400
414
  });
401
415
  return {
402
416
  model: options.model ?? "",
@@ -405,7 +419,7 @@ function toAnthropicRequest(request, options) {
405
419
  ...options.effort === void 0 ? {} : { output_config: { effort: options.effort } },
406
420
  ...options.thinking === void 0 ? {} : { thinking: options.thinking },
407
421
  ...options.temperature === void 0 ? {} : { temperature: options.temperature },
408
- messages: withConversationBreakpoints(messages),
422
+ messages: options.cacheBreakpoints === false ? messages : withConversationBreakpoints(messages),
409
423
  ...system === void 0 ? {} : { system },
410
424
  ...tools === void 0 ? {} : { tools },
411
425
  ...request.toolChoice === "none" && tools !== void 0 ? { tool_choice: { type: "none" } } : {},
@@ -413,14 +427,163 @@ function toAnthropicRequest(request, options) {
413
427
  };
414
428
  }
415
429
  //#endregion
430
+ //#region src/protocol/sse-response.ts
431
+ const MAX_FRAME_BYTES = 8388608;
432
+ const WORK_PER_TURN = 65536;
433
+ /**
434
+ * Supplies one complete SSE frame per SDK read at the known messages streaming entrance.
435
+ * Every successful body is framed, including suppliers with missing or incorrect MIME headers.
436
+ * LF, CRLF and CR line endings are normalized to LF without decoding field bytes.
437
+ * Incomplete EOF bytes are retained for the SDK's ordinary final-line handling.
438
+ * A normalized frame exceeding 8 MiB is refused before further allocation.
439
+ * Buffered input yields to timers and cancellation after at most 64 KiB of work.
440
+ * Cancellation and read failure join original-body cancellation before releasing its reader.
441
+ * Response metadata and HTTP error bodies are preserved.
442
+ */
443
+ function frameSseResponse(response, signal) {
444
+ if (!response.ok || response.body === null) return response;
445
+ const reader = response.body.getReader();
446
+ let buffer = /* @__PURE__ */ new Uint8Array(1024);
447
+ let length = 0;
448
+ let lineLength = 0;
449
+ let skipLf = false;
450
+ let chunk;
451
+ let offset = 0;
452
+ let work = 0;
453
+ let stopped = false;
454
+ let cancellation;
455
+ let abort;
456
+ function release() {
457
+ buffer = /* @__PURE__ */ new Uint8Array();
458
+ chunk = void 0;
459
+ if (abort !== void 0) signal?.removeEventListener("abort", abort);
460
+ reader.releaseLock();
461
+ }
462
+ function cancel(reason) {
463
+ if (cancellation !== void 0) return cancellation;
464
+ if (stopped) return Promise.resolve();
465
+ stopped = true;
466
+ cancellation = (async () => {
467
+ try {
468
+ await reader.cancel(reason);
469
+ } finally {
470
+ release();
471
+ }
472
+ })();
473
+ return cancellation;
474
+ }
475
+ function append(byte) {
476
+ if (length === MAX_FRAME_BYTES) throw new RangeError("SSE frame exceeds 8 MiB");
477
+ if (length === buffer.length) {
478
+ const grown = new Uint8Array(Math.min(MAX_FRAME_BYTES, Math.max(1024, buffer.length * 2)));
479
+ grown.set(buffer);
480
+ buffer = grown;
481
+ }
482
+ buffer[length++] = byte;
483
+ }
484
+ const body = new ReadableStream({
485
+ start(controller) {
486
+ abort = () => {
487
+ const reason = signal?.reason ?? new DOMException("The request was aborted", "AbortError");
488
+ cancel(reason).then(() => controller.error(reason), (cleanup) => controller.error(new AggregateError([reason, cleanup], "SSE cancellation failed")));
489
+ };
490
+ signal?.addEventListener("abort", abort, { once: true });
491
+ if (signal?.aborted) abort();
492
+ },
493
+ async pull(controller) {
494
+ try {
495
+ while (!stopped) {
496
+ if (chunk === void 0 || offset === chunk.length) {
497
+ work += 1;
498
+ if (work >= WORK_PER_TURN) {
499
+ work = 0;
500
+ await setImmediate();
501
+ if (stopped) return;
502
+ }
503
+ const next = await reader.read();
504
+ if (stopped) return;
505
+ if (next.done) {
506
+ if (length > 0) controller.enqueue(buffer.slice(0, length));
507
+ stopped = true;
508
+ release();
509
+ controller.close();
510
+ return;
511
+ }
512
+ chunk = next.value;
513
+ offset = 0;
514
+ }
515
+ const current = chunk;
516
+ if (current === void 0) continue;
517
+ while (offset < current.length) {
518
+ work += 1;
519
+ if (work >= WORK_PER_TURN) {
520
+ work = 0;
521
+ await setImmediate();
522
+ if (stopped) return;
523
+ }
524
+ const byte = current[offset++];
525
+ if (skipLf) {
526
+ skipLf = false;
527
+ if (byte === 10) continue;
528
+ }
529
+ if (byte === 13 || byte === 10) {
530
+ append(10);
531
+ skipLf = byte === 13;
532
+ if (lineLength === 0) {
533
+ controller.enqueue(buffer.slice(0, length));
534
+ length = 0;
535
+ return;
536
+ }
537
+ lineLength = 0;
538
+ } else {
539
+ append(byte);
540
+ lineLength += 1;
541
+ }
542
+ }
543
+ }
544
+ } catch (error) {
545
+ if (stopped) return;
546
+ try {
547
+ await cancel(error);
548
+ } catch (cleanup) {
549
+ controller.error(cleanup === error ? error : new AggregateError([error, cleanup], "SSE read cleanup failed"));
550
+ return;
551
+ }
552
+ controller.error(error);
553
+ }
554
+ },
555
+ cancel
556
+ }, { highWaterMark: 0 });
557
+ const framed = new Response(body, {
558
+ status: response.status,
559
+ statusText: response.statusText,
560
+ headers: response.headers
561
+ });
562
+ for (const key of [
563
+ "url",
564
+ "redirected",
565
+ "type"
566
+ ]) Object.defineProperty(framed, key, { value: response[key] });
567
+ return framed;
568
+ }
569
+ //#endregion
416
570
  //#region src/protocol/stream.ts
417
- function toFinishReason(stopReason) {
571
+ function toFinishReason(stopReason, support) {
418
572
  switch (stopReason) {
419
573
  case "tool_use": return "tool-calls";
420
574
  case "max_tokens":
421
575
  case "model_context_window_exceeded": return "max-tokens";
422
576
  case "refusal": return "refusal";
423
- default: return "stop";
577
+ case "end_turn":
578
+ case "stop_sequence":
579
+ case "pause_turn": return "stop";
580
+ default: throw support.failures.create({
581
+ code: stopReason === null ? "finish-reason-missing" : "finish-reason-unsupported",
582
+ stage: "response-validation",
583
+ category: "protocol",
584
+ source: "protocol",
585
+ retryable: false
586
+ });
424
587
  }
425
588
  }
426
589
  /** The accumulated `input_json_delta` text as JSON, or `undefined` when it
@@ -436,20 +599,16 @@ function parseToolInput(json) {
436
599
  }
437
600
  }
438
601
  /**
439
- * What a reply that was nothing but a cut-off tool call says instead.
440
- *
441
- * The call is dropped, and with nothing else in the reply that would leave an
442
- * assistant message with no content — which reads as a model that had nothing
443
- * to say and ends the turn as an ordinary completion. This sentence is the
444
- * adapter's own, not the endpoint's, and it goes where both the person and the
445
- * next turn read it. The `openai` member carries the same one for the same
446
- * reason.
602
+ * Streams provider deltas and a completed, usable reply with signed reasoning.
603
+ * Unknown terminal reasons and replies containing only reasoning fail without retry;
604
+ * a stream without message_stop retains interruption semantics.
447
605
  */
448
- const CUT_OFF_NOTICE = "[The reply was cut off while a tool call was still being written; none of it could be used.]";
449
606
  async function* mapAnthropicStream(events, attribution, support) {
450
607
  const blocks = /* @__PURE__ */ new Map();
451
608
  const finalContent = [];
452
- let cutOff = false;
609
+ const incompleteToolCalls = [];
610
+ let incompleteThinking = false;
611
+ let ordinaryInputTokens = 0;
453
612
  let inputTokens = 0;
454
613
  let outputTokens = 0;
455
614
  let cache = {};
@@ -459,7 +618,8 @@ async function* mapAnthropicStream(events, attribution, support) {
459
618
  for await (const event of events) switch (event.type) {
460
619
  case "message_start": {
461
620
  const usage = event.message.usage;
462
- inputTokens = usage.input_tokens + (usage.cache_read_input_tokens ?? 0) + (usage.cache_creation_input_tokens ?? 0);
621
+ ordinaryInputTokens = usage.input_tokens;
622
+ inputTokens = ordinaryInputTokens + (usage.cache_read_input_tokens ?? 0) + (usage.cache_creation_input_tokens ?? 0);
463
623
  outputTokens = event.message.usage.output_tokens;
464
624
  cache = {
465
625
  ...typeof usage.cache_read_input_tokens === "number" ? { cacheReadTokens: usage.cache_read_input_tokens } : {},
@@ -471,7 +631,7 @@ async function* mapAnthropicStream(events, attribution, support) {
471
631
  const block = event.content_block;
472
632
  if (block.type === "text") blocks.set(event.index, {
473
633
  kind: "text",
474
- text: ""
634
+ text: block.text
475
635
  });
476
636
  else if (block.type === "tool_use") {
477
637
  blocks.set(event.index, {
@@ -539,7 +699,10 @@ async function* mapAnthropicStream(events, attribution, support) {
539
699
  });
540
700
  else if (block?.kind === "tool-use") {
541
701
  const input = parseToolInput(block.json);
542
- if (input === void 0) cutOff = true;
702
+ if (input === void 0) incompleteToolCalls.push({
703
+ id: block.id,
704
+ name: block.name
705
+ });
543
706
  else finalContent.push({
544
707
  type: "tool-use",
545
708
  id: block.id,
@@ -551,21 +714,57 @@ async function* mapAnthropicStream(events, attribution, support) {
551
714
  text: block.text,
552
715
  ...block.signature === void 0 ? {} : { signature: block.signature }
553
716
  });
717
+ blocks.delete(event.index);
554
718
  break;
555
719
  }
556
- case "message_delta":
720
+ case "message_delta": {
557
721
  stopReason = event.delta.stop_reason ?? stopReason;
558
722
  if (event.delta.stop_details?.type === "refusal") refusalCategory = event.delta.stop_details.category ?? "unspecified";
559
- outputTokens = event.usage.output_tokens;
723
+ const usage = event.usage;
724
+ if (typeof usage.input_tokens === "number") ordinaryInputTokens = usage.input_tokens;
725
+ if (typeof usage.cache_read_input_tokens === "number") cache.cacheReadTokens = usage.cache_read_input_tokens;
726
+ if (typeof usage.cache_creation_input_tokens === "number") cache.cacheWriteTokens = usage.cache_creation_input_tokens;
727
+ inputTokens = ordinaryInputTokens + (cache.cacheReadTokens ?? 0) + (cache.cacheWriteTokens ?? 0);
728
+ outputTokens = usage.output_tokens;
560
729
  break;
730
+ }
561
731
  case "message_stop": stopped = true;
562
732
  }
563
733
  if (!stopped) throw support.interruptedFailure();
564
- if (finalContent.length === 0 && cutOff) finalContent.push({
565
- type: "text",
566
- text: CUT_OFF_NOTICE
734
+ const finishReason = toFinishReason(stopReason, support);
735
+ if (finishReason === "max-tokens") {
736
+ for (const block of blocks.values()) if (block.kind === "text" && block.text !== "") finalContent.push({
737
+ type: "text",
738
+ text: block.text
739
+ });
740
+ else if (block.kind === "thinking") {
741
+ finalContent.push({
742
+ type: "thinking",
743
+ text: block.text
744
+ });
745
+ incompleteThinking = true;
746
+ } else if (block.kind === "tool-use") incompleteToolCalls.push({
747
+ id: block.id,
748
+ name: block.name
749
+ });
750
+ else if (block.kind === "redacted") incompleteThinking = true;
751
+ } else if (incompleteToolCalls.length > 0 || blocks.size > 0) throw support.failures.create({
752
+ code: "response-invalid",
753
+ stage: "response-validation",
754
+ category: "protocol",
755
+ source: "protocol",
756
+ retryable: false,
757
+ finishReason
758
+ });
759
+ if (finishReason !== "refusal" && finishReason !== "max-tokens" && !finalContent.some((part) => part.type === "text" || part.type === "tool-use")) throw support.failures.create({
760
+ code: "response-empty",
761
+ stage: "response-validation",
762
+ category: "protocol",
763
+ source: "protocol",
764
+ retryable: false,
765
+ finishReason
567
766
  });
568
- const attributedContent = finalContent.map((part) => part.type === "thinking" && part.signature !== void 0 && attribution !== void 0 ? {
767
+ const attributedContent = finalContent.map((part) => part.type === "thinking" && attribution !== void 0 ? {
569
768
  ...part,
570
769
  originModel: attribution.originModel,
571
770
  prefix: attribution.prefix,
@@ -573,7 +772,11 @@ async function* mapAnthropicStream(events, attribution, support) {
573
772
  } : part);
574
773
  yield {
575
774
  kind: "final",
576
- finishReason: toFinishReason(stopReason),
775
+ finishReason,
776
+ ...finishReason === "max-tokens" ? { outputTruncation: {
777
+ incompleteToolCalls,
778
+ ...incompleteThinking ? { incompleteThinking: true } : {}
779
+ } } : {},
577
780
  usage: {
578
781
  inputTokens,
579
782
  outputTokens,
@@ -599,6 +802,8 @@ async function* mapAnthropicStream(events, attribution, support) {
599
802
  */
600
803
  /** Lets a budget-thinking model think between tool calls. */
601
804
  const INTERLEAVED_THINKING_BETA = "interleaved-thinking-2025-05-14";
805
+ /** Enables effort-only system messages on declared supporting models. */
806
+ const MID_CONVERSATION_EFFORT_BETA = "mid-conversation-output-config-2026-07-01";
602
807
  /** The budget a budget-thinking model gets when a person set none. */
603
808
  const DEFAULT_BUDGET = 16e3;
604
809
  const BUDGET_FLOOR = 1024;
@@ -611,8 +816,10 @@ const BUDGET_FLOOR = 1024;
611
816
  * default one under `max_tokens`, or no thinking at all when `max_tokens`
612
817
  * leaves no room for the smallest budget. Thinking off is `disabled`. While
613
818
  * thinking is on no temperature goes out: Anthropic refuses one then.
819
+ * Endpoint policies can instead omit thinking, enable it without a budget,
820
+ * or suppress native effort, display and beta extensions.
614
821
  */
615
- function anthropicOptions(plan, model, budgetOnly = []) {
822
+ function anthropicOptions(plan, model, budgetOnly = [], policy = {}) {
616
823
  const on = plan.thinking === true;
617
824
  const maxTokens = plan.maxTokens;
618
825
  const budget = () => {
@@ -621,43 +828,56 @@ function anthropicOptions(plan, model, budgetOnly = []) {
621
828
  const wanted = plan.budgetTokens ?? Math.min(DEFAULT_BUDGET, Math.floor((maxTokens ?? 0) / 2));
622
829
  return Math.min(Math.max(wanted, BUDGET_FLOOR), ceiling);
623
830
  };
624
- const byBudget = plan.budgetTokens !== void 0 || budgetOnly.some((one) => model.startsWith(one));
831
+ const byBudget = policy.thinkingMode === "budget" || plan.budgetTokens !== void 0 || budgetOnly.some((one) => model.startsWith(one));
625
832
  const tokens = on && byBudget ? budget() : void 0;
626
- const thinking = !on ? plan.thinking === false ? { type: "disabled" } : void 0 : byBudget ? tokens === void 0 ? void 0 : {
833
+ const thinking = policy.thinkingMode === "omit" ? void 0 : !on ? plan.thinking === false ? { type: "disabled" } : void 0 : policy.thinkingMode === "enabled" ? { type: "enabled" } : byBudget ? tokens === void 0 ? void 0 : {
627
834
  type: "enabled",
628
835
  budget_tokens: tokens
629
836
  } : {
630
837
  type: "adaptive",
631
- display: "summarized"
838
+ ...policy.thinkingSummary === false ? {} : { display: "summarized" }
632
839
  };
633
840
  return {
634
- ...plan.effort === void 0 || !on ? {} : { effort: plan.effort },
841
+ ...plan.effort === void 0 || !on || policy.thinkingEffort === false ? {} : { effort: plan.effort },
635
842
  ...plan.temperature === void 0 || on ? {} : { temperature: plan.temperature },
636
843
  ...maxTokens === void 0 ? {} : { maxTokens },
637
844
  ...thinking === void 0 ? {} : { thinking },
638
- ...thinking?.type === "enabled" ? { betas: [INTERLEAVED_THINKING_BETA] } : {}
845
+ ...thinking?.type === "enabled" && policy.thinkingBeta !== false ? { betas: [INTERLEAVED_THINKING_BETA] } : {}
639
846
  };
640
847
  }
641
848
  /** Creates an Anthropic port with synchronous request inspection and safe stream retries. */
642
849
  function createAnthropicModelPort(options) {
643
850
  function clientForAttempt(reportProgress) {
644
- return options.client ?? new Anthropic({
645
- apiKey: options.apiKey ?? "",
646
- fetch: async (...args) => options.support.observeResponseProgress(await (options.fetch ?? globalThis.fetch)(...args), reportProgress),
851
+ if (options.client) return options.client;
852
+ const client = new Anthropic({
853
+ apiKey: options.allowUnauthenticated && !options.apiKey ? "not-used" : options.apiKey ?? "",
854
+ ...options.allowUnauthenticated && !options.apiKey ? {
855
+ authToken: null,
856
+ defaultHeaders: {
857
+ "x-api-key": null,
858
+ Authorization: null
859
+ }
860
+ } : {},
861
+ fetch: async (...args) => frameSseResponse(options.support.observeResponseProgress(await (options.fetch ?? globalThis.fetch)(...args), reportProgress), args[1]?.signal),
647
862
  baseURL: options.baseURL ?? "",
648
863
  maxRetries: 0
649
864
  });
865
+ return { messages: { create: (body, requestOptions) => client.post("/messages", {
866
+ body,
867
+ ...requestOptions,
868
+ stream: true
869
+ }) } };
650
870
  }
651
- function build(request) {
871
+ function build(request, inspection = false) {
652
872
  const capacity = options.catalogue?.()?.limit;
653
- const plan = options.params === void 0 ? void 0 : anthropicOptions(options.params(request.params ?? {}), options.model ?? "", options.budgetOnly);
873
+ const plan = options.params === void 0 ? void 0 : anthropicOptions(options.params(request.params ?? {}), options.model ?? "", options.budgetOnly, options);
654
874
  const { media: mediaOf, ...rest } = options;
655
875
  const media = mediaOf?.(request.params ?? {});
656
876
  const base = media === void 0 ? rest : {
657
877
  ...rest,
658
878
  media
659
879
  };
660
- const requestOptions = plan === void 0 ? base : {
880
+ let requestOptions = plan === void 0 ? base : {
661
881
  ...base,
662
882
  ...plan,
663
883
  extra: {
@@ -665,22 +885,55 @@ function createAnthropicModelPort(options) {
665
885
  ...options.support.extraParams(request.params ?? {})
666
886
  }
667
887
  };
668
- const betas = plan?.betas;
888
+ const declaredDefault = options.effortCacheModels?.[options.model ?? ""];
889
+ const replay = options.support.planEffortCache({
890
+ request,
891
+ inspection,
892
+ effort: requestOptions.effort,
893
+ capability: options.effortCache === false ? {
894
+ status: "unsupported",
895
+ reason: "configuration-updates-unavailable"
896
+ } : requestOptions.thinking?.type !== "adaptive" ? {
897
+ status: "unsupported",
898
+ reason: "adaptive-thinking-required"
899
+ } : {
900
+ status: "supported",
901
+ ...declaredDefault ? { defaultEffort: declaredDefault } : {}
902
+ },
903
+ bindingFingerprint: options.support.inspectionFingerprint({
904
+ connectionFingerprint: options.connectionFingerprint,
905
+ endpoint: options.endpoint,
906
+ baseURL: options.baseURL,
907
+ model: options.model,
908
+ system: request.system,
909
+ tools: request.tools,
910
+ thinking: requestOptions.thinking,
911
+ extra: requestOptions.extra,
912
+ reasoningReplay: requestOptions.reasoningReplay
913
+ })
914
+ });
915
+ requestOptions = {
916
+ ...requestOptions,
917
+ effort: replay.baseEffort,
918
+ effortUpdates: replay.updates
919
+ };
920
+ const betas = [...plan?.betas ?? [], ...replay.updates.length ? [MID_CONVERSATION_EFFORT_BETA] : []];
669
921
  return {
670
922
  params: toAnthropicRequest(request, requestOptions),
671
923
  requestOptions,
672
924
  capacity,
925
+ replayData: replay.replayData,
673
926
  headers: betas === void 0 || betas.length === 0 ? void 0 : { "anthropic-beta": betas.join(",") }
674
927
  };
675
928
  }
676
929
  return {
677
930
  inspect(request) {
678
- const { params, requestOptions, capacity } = build(request);
931
+ const { params, requestOptions, capacity } = build(request, true);
679
932
  const outputReserve = Number.isInteger(params.max_tokens) && params.max_tokens > 0 ? params.max_tokens : capacity?.output ?? 0;
680
933
  return options.support.inspect({
681
934
  body: params,
682
- textTokens: countTokens(JSON.stringify(params), { disallowedSpecial: /* @__PURE__ */ new Set() }),
683
- tokenizer: "o200k_base-json-v1",
935
+ textTokens: options.support.measureText(options.support.requestText("messages", params)),
936
+ tokenizer: "o200k_base-protocol-text-v2",
684
937
  request,
685
938
  capacity,
686
939
  outputReserve,
@@ -692,6 +945,7 @@ function createAnthropicModelPort(options) {
692
945
  }).tokens,
693
946
  fingerprint: {
694
947
  rendering: "anthropic-messages-v3",
948
+ baseURL: options.baseURL,
695
949
  endpoint: options.endpoint ?? options.baseURL,
696
950
  model: params.model,
697
951
  purpose: request.purpose,
@@ -707,34 +961,91 @@ function createAnthropicModelPort(options) {
707
961
  }
708
962
  });
709
963
  },
710
- stream(request, signal) {
711
- const { params, headers, requestOptions } = build(request);
712
- const prefix = anthropicRequestPrefix(request, requestOptions.media, options.support);
964
+ stream(request, signal, observer) {
965
+ signal.throwIfAborted();
966
+ const { params, headers, requestOptions, replayData } = build(request);
967
+ const prefix = anthropicRequestPrefix(request, requestOptions.media, options.support, requestOptions.effortUpdates);
713
968
  return options.support.withChatAttempts({
714
969
  signal,
715
970
  ...options.maxRetries === void 0 ? {} : { maxRetries: options.maxRetries },
716
971
  ...options.sleep === void 0 ? {} : { sleep: options.sleep },
717
972
  ...options.idleMs === void 0 ? {} : { idleMs: options.idleMs },
718
- async *attempt(attemptSignal, reportProgress) {
719
- const events = await clientForAttempt(reportProgress).messages.create(params, {
720
- signal: attemptSignal,
721
- ...headers === void 0 ? {} : { headers }
973
+ async *attempt(attemptSignal, reportProgress, attempt) {
974
+ const observe = (event) => {
975
+ try {
976
+ observer?.observe?.(event);
977
+ } catch {}
978
+ };
979
+ const attemptCount = attempt + 1;
980
+ let outcome = "unknown";
981
+ let firstResponseFinished = false;
982
+ observe({
983
+ stage: "attempt",
984
+ phase: "start",
985
+ attempt: attemptCount
986
+ });
987
+ observe({
988
+ stage: "first-response",
989
+ phase: "start",
990
+ attempt: attemptCount
722
991
  });
723
- yield* mapAnthropicStream((async function* () {
724
- for await (const event of events) {
725
- reportProgress();
726
- yield event;
992
+ try {
993
+ attemptSignal.throwIfAborted();
994
+ const events = await clientForAttempt(reportProgress).messages.create(params, {
995
+ signal: attemptSignal,
996
+ ...headers === void 0 ? {} : { headers }
997
+ });
998
+ firstResponseFinished = true;
999
+ observe({
1000
+ stage: "first-response",
1001
+ phase: "end",
1002
+ attempt: attemptCount,
1003
+ outcome: "ok"
1004
+ });
1005
+ attemptSignal.throwIfAborted();
1006
+ try {
1007
+ observer?.dispatched({ attempt });
1008
+ } catch {}
1009
+ attemptSignal.throwIfAborted();
1010
+ const observed = (async function* () {
1011
+ for await (const event of events) {
1012
+ reportProgress();
1013
+ yield event;
1014
+ }
1015
+ })();
1016
+ for await (const chunk of mapAnthropicStream(observed, {
1017
+ originModel: params.model,
1018
+ prefix
1019
+ }, options.support)) {
1020
+ if (chunk.kind === "final") outcome = "ok";
1021
+ yield chunk.kind === "final" && replayData !== void 0 ? {
1022
+ ...chunk,
1023
+ replayData
1024
+ } : chunk;
727
1025
  }
728
- })(), {
729
- originModel: params.model,
730
- prefix
731
- }, options.support);
1026
+ } catch (error) {
1027
+ outcome = attemptSignal.aborted ? "cancelled" : "error";
1028
+ throw error;
1029
+ } finally {
1030
+ if (!firstResponseFinished) observe({
1031
+ stage: "first-response",
1032
+ phase: "end",
1033
+ attempt: attemptCount,
1034
+ outcome
1035
+ });
1036
+ observe({
1037
+ stage: "attempt",
1038
+ phase: "end",
1039
+ attempt: attemptCount,
1040
+ outcome
1041
+ });
1042
+ }
732
1043
  },
733
1044
  classify(error) {
734
- const portError = toPortError(error);
1045
+ const portError = toModelFailure(error, options.support.failures);
735
1046
  return {
736
1047
  error: portError,
737
- retryable: portError.retryable,
1048
+ retryable: portError.retryable === true,
738
1049
  retryAfterMs: retryAfterMs(error)
739
1050
  };
740
1051
  }
@@ -745,22 +1056,54 @@ function createAnthropicModelPort(options) {
745
1056
  //#endregion
746
1057
  //#region src/protocol/probe.ts
747
1058
  const VERSION = "2023-06-01";
1059
+ async function readBody(response, maxBytes) {
1060
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) throw new Error("invalid response budget");
1061
+ const declared = response.headers.get("content-length");
1062
+ if (declared !== null && /^\d+$/.test(declared) && Number(declared) > maxBytes) {
1063
+ await response.body?.cancel();
1064
+ throw new Error("read-limit: provider response exceeds its member budget");
1065
+ }
1066
+ if (!response.body) return {
1067
+ text: "",
1068
+ bytes: 0
1069
+ };
1070
+ const reader = response.body.getReader();
1071
+ const decoder = new TextDecoder();
1072
+ let bytes = 0, text = "";
1073
+ try {
1074
+ for (;;) {
1075
+ const next = await reader.read();
1076
+ if (next.done) break;
1077
+ bytes += next.value.byteLength;
1078
+ if (bytes > maxBytes) {
1079
+ await reader.cancel();
1080
+ throw new Error("read-limit: provider response exceeds its member budget");
1081
+ }
1082
+ text += decoder.decode(next.value, { stream: true });
1083
+ }
1084
+ return {
1085
+ text: text + decoder.decode(),
1086
+ bytes
1087
+ };
1088
+ } finally {
1089
+ reader.releaseLock();
1090
+ }
1091
+ }
748
1092
  function baseUrlOf(probe) {
749
- const configured = probe.config.baseUrl;
750
- return (typeof configured === "string" ? configured : "").replace(/\/+$/, "");
1093
+ return messagesBaseUrl(probe.config.baseUrl);
751
1094
  }
752
1095
  /** Attaches the status so the runtime can tell an authentication failure from
753
1096
  * an endpoint that answered something else. The body is passed through as
754
1097
  * the message; whether any of it reaches a person is not this file's call. */
755
- async function refuse(response) {
756
- const body = await response.text().catch(() => "");
1098
+ async function refuse(response, maxBytes = 8388608) {
1099
+ const body = (await readBody(response, maxBytes)).text;
757
1100
  throw Object.assign(new Error(body === "" ? response.statusText : body), { status: response.status });
758
1101
  }
759
1102
  async function get(probe, path, fetcher) {
760
1103
  return fetcher(`${baseUrlOf(probe)}${path}`, {
761
1104
  method: "GET",
762
1105
  headers: {
763
- "x-api-key": probe.secrets.apiKey ?? "",
1106
+ ...probe.options.allowUnauthenticated === true && !probe.secrets.apiKey ? {} : { "x-api-key": probe.secrets.apiKey ?? "" },
764
1107
  "anthropic-version": VERSION
765
1108
  },
766
1109
  signal: probe.signal
@@ -820,22 +1163,26 @@ function offerOf(row, id) {
820
1163
  };
821
1164
  }
822
1165
  const probeAnthropic = {
823
- /** Every model the endpoint lists. `/v1/models` is paged — it answers with
1166
+ /** Every model the endpoint lists. `/models` is paged — it answers with
824
1167
  * one page plus `has_more`/`last_id` — so this walks the pages with
825
1168
  * `after_id` until the endpoint says there are no more. A mirror that
826
1169
  * reports neither field answers in one page, as it always did. */
827
1170
  async listModels(probe, fetcher = globalThis.fetch) {
828
1171
  const offers = [];
829
1172
  let afterId;
1173
+ let remaining = probe.maxResponseBytes ?? 8388608;
830
1174
  for (let page = 0; page < MAX_PAGES; page += 1) {
831
- const response = await get(probe, `/v1/models${afterId === void 0 ? "" : `?after_id=${encodeURIComponent(afterId)}`}`, fetcher);
832
- if (!response.ok) await refuse(response);
833
- const body = await response.json();
1175
+ const response = await get(probe, `/models${afterId === void 0 ? "" : `?after_id=${encodeURIComponent(afterId)}`}`, fetcher);
1176
+ if (!response.ok) await refuse(response, probe.maxResponseBytes ?? 8388608);
1177
+ const received = await readBody(response, remaining);
1178
+ remaining -= received.bytes;
1179
+ const body = JSON.parse(received.text);
834
1180
  for (const row of body.data ?? []) {
835
1181
  if (typeof row.id !== "string") continue;
836
1182
  offers.push(offerOf(row, row.id));
837
1183
  }
838
1184
  if (body.has_more !== true || typeof body.last_id !== "string") break;
1185
+ if (remaining < 1) throw new Error("read-limit: provider listing exhausted its member budget");
839
1186
  afterId = body.last_id;
840
1187
  }
841
1188
  return offers;
@@ -844,19 +1191,19 @@ const probeAnthropic = {
844
1191
  * is also the test: an endpoint that answers it has a working key, and one
845
1192
  * that refuses says why.
846
1193
  *
847
- * An endpoint that serves `/v1/messages` alone answers the listing with
848
- * 404. The test then sends `/v1/messages` an empty body, which no model
1194
+ * An endpoint that serves `/messages` alone answers the listing with
1195
+ * 404. The test then sends `/messages` an empty body, which no model
849
1196
  * runs: an unauthenticated refusal (401, 403) is a wrong key, any other
850
1197
  * client error means the key got through, and a second 404 is an address
851
1198
  * that serves neither. */
852
1199
  async testConnection(probe, fetcher = globalThis.fetch) {
853
- const listed = await get(probe, "/v1/models?limit=1", fetcher);
1200
+ const listed = await get(probe, "/models?limit=1", fetcher);
854
1201
  if (listed.ok) return;
855
1202
  if (listed.status !== 404) await refuse(listed);
856
- const asked = await fetcher(`${baseUrlOf(probe)}/v1/messages`, {
1203
+ const asked = await fetcher(`${baseUrlOf(probe)}/messages`, {
857
1204
  method: "POST",
858
1205
  headers: {
859
- "x-api-key": probe.secrets.apiKey ?? "",
1206
+ ...probe.options.allowUnauthenticated === true && !probe.secrets.apiKey ? {} : { "x-api-key": probe.secrets.apiKey ?? "" },
860
1207
  "anthropic-version": VERSION,
861
1208
  "content-type": "application/json"
862
1209
  },
@@ -868,14 +1215,71 @@ const probeAnthropic = {
868
1215
  }
869
1216
  };
870
1217
  //#endregion
1218
+ //#region src/support.ts
1219
+ /** Normalizes official facts without requiring an installed Chat capability. */
1220
+ function normalizeOffers(input) {
1221
+ return Object.fromEntries(input.offers.map((offer) => [offer.model, {
1222
+ id: offer.model,
1223
+ ...offer.name === void 0 ? {} : { name: offer.name },
1224
+ ...offer.reasoning === void 0 && !offer.efforts?.length ? {} : { reasoning: offer.efforts?.length ? true : offer.reasoning },
1225
+ ...offer.efforts?.length ? { reasoning_options: [{
1226
+ type: "effort",
1227
+ values: [...offer.efforts]
1228
+ }] } : {},
1229
+ ...offer.temperature === void 0 ? {} : { temperature: offer.temperature },
1230
+ ...offer.toolCall === void 0 ? {} : { tool_call: offer.toolCall },
1231
+ ...offer.input === void 0 ? {} : { attachment: offer.input.some((one) => one !== "text") },
1232
+ ...offer.input === void 0 && offer.output === void 0 ? {} : { modalities: {
1233
+ ...offer.input === void 0 ? {} : { input: [...offer.input] },
1234
+ ...offer.output === void 0 ? {} : { output: [...offer.output] }
1235
+ } },
1236
+ ...!offer.contextWindow && !offer.maxOutput ? {} : { limit: {
1237
+ ...offer.contextWindow && offer.contextWindow > 0 ? { context: offer.contextWindow } : {},
1238
+ ...offer.maxOutput && offer.maxOutput > 0 ? { output: offer.maxOutput } : {}
1239
+ } },
1240
+ ...offer.releaseDate === void 0 ? {} : { release_date: offer.releaseDate }
1241
+ }]));
1242
+ }
1243
+ /** The owner-qualified accessor is read per operation; withdrawal never exposes an old service. */
1244
+ function lazySupport(read) {
1245
+ return new Proxy({}, { get(_target, key) {
1246
+ if (key === "normalizeListing") return normalizeOffers;
1247
+ const service = read();
1248
+ if (!service) throw new Error("Chat model support is unavailable");
1249
+ const value = Reflect.get(service, key);
1250
+ return typeof value === "function" ? value.bind(service) : value;
1251
+ } });
1252
+ }
1253
+ //#endregion
871
1254
  //#region src/protocol.ts
872
1255
  /** Supplier options interpreted by the Messages implementation. */
873
- const AnthropicProtocolOptions = z.strictObject({ budgetOnly: z.array(z.string()).optional() });
1256
+ const AnthropicProtocolOptions = z.strictObject({
1257
+ allowUnauthenticated: z.boolean().optional(),
1258
+ reasoningReplay: z.enum([
1259
+ "omit",
1260
+ "signed-thinking",
1261
+ "unsigned-thinking"
1262
+ ]).optional(),
1263
+ effortCache: z.boolean().optional(),
1264
+ cacheBreakpoints: z.boolean().optional(),
1265
+ thinkingMode: z.enum([
1266
+ "adaptive",
1267
+ "budget",
1268
+ "enabled",
1269
+ "omit"
1270
+ ]).optional(),
1271
+ thinkingEffort: z.boolean().optional(),
1272
+ thinkingBeta: z.boolean().optional(),
1273
+ thinkingSummary: z.boolean().optional(),
1274
+ budgetOnly: z.array(z.string()).optional(),
1275
+ effortCacheModels: z.record(z.string(), z.string().min(1)).optional()
1276
+ });
874
1277
  /** Registers request mapping, streaming, inspection and probes with host-owned resources. */
875
1278
  function anthropicProtocolType(support, fetch) {
876
1279
  return {
877
1280
  type: "anthropic",
878
- label: "Anthropic Messages",
1281
+ label: "Anthropic Messages API",
1282
+ logo: protocolLogo,
879
1283
  fields: [{
880
1284
  key: "baseUrl",
881
1285
  kind: "url",
@@ -885,19 +1289,36 @@ function anthropicProtocolType(support, fetch) {
885
1289
  userConfigurable: true,
886
1290
  optionsSchema: AnthropicProtocolOptions,
887
1291
  facts,
1292
+ effortCacheCapability(input) {
1293
+ const options = AnthropicProtocolOptions.parse(input.options ?? {});
1294
+ if (options.effortCache === false) return {
1295
+ status: "unsupported",
1296
+ reason: "configuration-updates-unavailable"
1297
+ };
1298
+ const defaultEffort = options.effortCacheModels?.[input.model];
1299
+ if (input.params.thinking === false || input.params.budgetTokens !== void 0) return {
1300
+ status: "unsupported",
1301
+ reason: "adaptive-thinking-required"
1302
+ };
1303
+ return {
1304
+ status: "supported",
1305
+ ...defaultEffort ? { defaultEffort } : {}
1306
+ };
1307
+ },
888
1308
  prepareParams: (input) => support.prepareParams(input, facts),
889
- chat: {
1309
+ adapters: { chat: {
890
1310
  fileKinds: ["image"],
891
1311
  supportsModel: () => true,
892
1312
  createPort(call) {
893
1313
  const options = AnthropicProtocolOptions.parse(call.options);
894
1314
  return createAnthropicModelPort({
1315
+ connectionFingerprint: call.connectionFingerprint,
895
1316
  support,
896
1317
  fetch,
897
1318
  model: call.model,
898
1319
  endpoint: call.providerId,
899
1320
  apiKey: call.secrets.apiKey ?? "",
900
- baseURL: String(call.config.baseUrl ?? ""),
1321
+ baseURL: messagesBaseUrl(call.config.baseUrl),
901
1322
  ...options,
902
1323
  catalogue: () => support.catalogue(call.providerId, call.model),
903
1324
  media: (stored) => support.mediaContextOf({
@@ -916,9 +1337,9 @@ function anthropicProtocolType(support, fetch) {
916
1337
  })
917
1338
  });
918
1339
  }
919
- },
920
- normalizeListing: (input) => support.normalizeListing(input),
921
- listModels: (probe) => probeAnthropic.listModels(probe, fetch),
1340
+ } },
1341
+ normalizeListing: (input) => normalizeOffers(input),
1342
+ listModels: async (probe) => ({ offers: await probeAnthropic.listModels(probe, fetch) }),
922
1343
  testConnection: (probe) => probeAnthropic.testConnection(probe, fetch)
923
1344
  };
924
1345
  }
@@ -928,11 +1349,12 @@ function anthropicProtocolType(support, fetch) {
928
1349
  const TOOL_NAMES = [];
929
1350
  const plugin = {
930
1351
  name: "@eum-agent/llm-protocol-anthropic",
931
- requires: ["model-support", "network"],
1352
+ requires: ["network"],
1353
+ optionalServices: ["model-support"],
932
1354
  apply(ctx) {
933
- const support = ctx.services.get("model-support");
1355
+ const support = lazySupport(() => ctx.services.find("model-support"));
934
1356
  const network = ctx.services.get("network");
935
- ctx.models.registerProtocol(anthropicProtocolType(support, network.fetch));
1357
+ ctx.modelProtocols.register(anthropicProtocolType(support, network.fetch));
936
1358
  }
937
1359
  };
938
1360
  //#endregion
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "en-US": "Anthropic Model Protocol",
5
5
  "zh-CN": "模型协议 · Anthropic"
6
6
  },
7
- "version": "1.0.0",
7
+ "version": "1.1.0",
8
8
  "type": "module",
9
9
  "description": "Public Anthropic model communication protocol",
10
10
  "license": "MIT",
@@ -17,7 +17,7 @@
17
17
  "dist"
18
18
  ],
19
19
  "devDependencies": {
20
- "@eum-agent/plugin": "1.0.0"
20
+ "@eum-agent/plugin": "1.1.0"
21
21
  },
22
22
  "dependencies": {
23
23
  "zod": "^4.4.3",
@@ -27,10 +27,10 @@
27
27
  "yaoguang": {
28
28
  "kind": "extension",
29
29
  "dependencies": {
30
- "@eum-agent/llm-management": "1.0.0"
30
+ "@eum-agent/llm-management": "1.1.0"
31
31
  },
32
32
  "foundationDependencies": {
33
- "@eum-agent/infra-local": "1.0.0"
33
+ "@eum-agent/infra-local": "1.0.1"
34
34
  },
35
35
  "description": {
36
36
  "en-US": "Public Anthropic model communication protocol",