@eum-agent/llm-protocol-anthropic 1.0.1 → 1.2.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 +727 -383
  2. package/package.json +4 -4
package/dist/index.js CHANGED
@@ -1,9 +1,30 @@
1
1
  import { z } from "zod";
2
- import Anthropic, { APIConnectionError, APIError } from "@anthropic-ai/sdk";
3
2
  import { createHash } from "node:crypto";
4
3
  import { setImmediate } from "node:timers/promises";
4
+ //#region src/connection-fetch.ts
5
+ function withConnectionHeaders(fetch, headers) {
6
+ const configured = Object.entries(headers ?? {});
7
+ if (configured.length === 0) return fetch;
8
+ return (input, init) => {
9
+ const merged = new Headers(input instanceof Request ? input.headers : void 0);
10
+ for (const [name, value] of new Headers(init?.headers)) merged.set(name, value);
11
+ for (const [name, value] of configured) merged.set(name, value);
12
+ return fetch(input, {
13
+ ...init,
14
+ headers: merged
15
+ });
16
+ };
17
+ }
18
+ //#endregion
19
+ //#region src/logo.ts
20
+ 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";
21
+ //#endregion
22
+ //#region src/protocol/address.ts
23
+ function messagesBaseUrl(baseUrl) {
24
+ return typeof baseUrl === "string" ? baseUrl.replace(/\/+$/, "") : "";
25
+ }
26
+ //#endregion
5
27
  //#region src/protocol/facts.ts
6
- /** Parameter ranges and request limits for this provider wire. */
7
28
  const facts = {
8
29
  outputLimit: {
9
30
  support: "required",
@@ -22,22 +43,32 @@ const facts = {
22
43
  }
23
44
  };
24
45
  //#endregion
46
+ //#region src/protocol/sdk.ts
47
+ let loaded;
48
+ let loading;
49
+ function loadAnthropicSdk() {
50
+ loading ??= import("@anthropic-ai/sdk").then((sdk) => {
51
+ loaded = sdk;
52
+ return sdk;
53
+ }, (error) => {
54
+ loading = void 0;
55
+ throw error;
56
+ });
57
+ return loading;
58
+ }
59
+ function isAnthropicApiError(error) {
60
+ return loaded !== void 0 && error instanceof loaded.APIError;
61
+ }
62
+ function isAnthropicConnectionError(error) {
63
+ return loaded !== void 0 && error instanceof loaded.APIConnectionError;
64
+ }
65
+ //#endregion
25
66
  //#region src/protocol/errors.ts
26
- /**
27
- * SDK exceptions have two consumers: explicit probes retain provider text for
28
- * their credential-redaction boundary, while Agent calls accept only fixed
29
- * templates and allowlisted facts through the host factory.
30
- */
31
- /** Timeouts, conflicts, rate limits and 5xx are worth a second attempt;
32
- * every other status is not — retrying a bad request or an authentication
33
- * failure only spends the backoff budget on a call that will never succeed. */
34
67
  function isRetryableStatus(status) {
35
68
  return status === 408 || status === 409 || status === 429 || status !== void 0 && status >= 500;
36
69
  }
37
- /** The provider's own `retry-after` header, in milliseconds — read for the
38
- * backoff delay only; the header value itself carries no credential. */
39
70
  function retryAfterMs(error) {
40
- if (!(error instanceof APIError)) return void 0;
71
+ if (!isAnthropicApiError(error)) return void 0;
41
72
  const header = error.headers?.get("retry-after");
42
73
  if (!header) return void 0;
43
74
  const seconds = Number(header);
@@ -45,11 +76,6 @@ function retryAfterMs(error) {
45
76
  const milliseconds = seconds * 1e3;
46
77
  return Number.isFinite(milliseconds) ? milliseconds : void 0;
47
78
  }
48
- /** Converts any exception the SDK call can throw into a `ModelCallError`.
49
- * Never reads `error.headers` into the result; the body goes to
50
- * `providerText` alone. */
51
- /** Error types an event stream reports mid-reply that a second attempt can
52
- * get past: the stream carries no status, only this. */
53
79
  const RETRYABLE_TYPES = /* @__PURE__ */ new Set([
54
80
  "overloaded_error",
55
81
  "api_error",
@@ -60,16 +86,20 @@ function streamErrorType(error) {
60
86
  const inner = body?.error?.type ?? body?.type;
61
87
  return typeof inner === "string" ? inner : void 0;
62
88
  }
63
- /** Maps verified SDK classes and factory identities to bounded Agent failure candidates. */
89
+ function exceedsContextWindow(error) {
90
+ if (error.status !== 400 || error.type !== "invalid_request_error") return false;
91
+ const message = error.error?.error?.message;
92
+ return typeof message === "string" && /prompt is too long/i.test(message);
93
+ }
64
94
  function toModelFailure(error, failures) {
65
95
  if (failures.owns(error)) return error;
66
- if (!(error instanceof APIError)) return failures.create({
96
+ if (!isAnthropicApiError(error)) return failures.create({
67
97
  code: "unknown",
68
98
  stage: "unknown",
69
99
  category: "unknown",
70
100
  source: "unknown",
71
101
  retryable: false
72
- });
102
+ }, { cause: error });
73
103
  const rawCode = streamErrorType(error) ?? error.type;
74
104
  const providerCode = typeof rawCode === "string" && (/* @__PURE__ */ new Set([
75
105
  "usage_not_included",
@@ -85,8 +115,24 @@ function toModelFailure(error, failures) {
85
115
  "bio_policy",
86
116
  "misalignment_policy_violation"
87
117
  ])).has(rawCode) ? rawCode : void 0;
88
- const connection = error instanceof APIConnectionError;
118
+ const connection = isAnthropicConnectionError(error);
89
119
  const status = Number.isInteger(error.status) && Number(error.status) >= 100 && Number(error.status) <= 599 ? error.status : void 0;
120
+ const details = {
121
+ ...status === void 0 ? {} : { status },
122
+ ...typeof error.requestID === "string" ? { providerRequestId: error.requestID } : {}
123
+ };
124
+ if (exceedsContextWindow(error)) return failures.create({
125
+ code: "context-window-exceeded",
126
+ stage: "request",
127
+ category: "request-too-large",
128
+ source: "protocol",
129
+ status: 400,
130
+ retryable: false,
131
+ ...providerCode === void 0 ? {} : { providerCode }
132
+ }, {
133
+ cause: error,
134
+ details
135
+ });
90
136
  return failures.create({
91
137
  code: connection ? "stream-interrupted" : status === 413 ? "request-too-large" : status === void 0 ? "provider-error" : "http-error",
92
138
  stage: connection ? "transport" : status === 413 ? "request" : status === void 0 ? "stream" : "transport",
@@ -95,46 +141,93 @@ function toModelFailure(error, failures) {
95
141
  ...status === void 0 ? {} : { status },
96
142
  retryable: connection || isRetryableStatus(status) || status === void 0 && RETRYABLE_TYPES.has(streamErrorType(error) ?? ""),
97
143
  ...providerCode === void 0 ? {} : { providerCode }
144
+ }, {
145
+ cause: error,
146
+ details
98
147
  });
99
148
  }
100
149
  //#endregion
150
+ //#region src/protocol/tool-schema.ts
151
+ const COMPOSITION = [
152
+ "anyOf",
153
+ "oneOf",
154
+ "allOf"
155
+ ];
156
+ function isSchema(value) {
157
+ return typeof value === "object" && value !== null && !Array.isArray(value);
158
+ }
159
+ function isPlaceholder(value) {
160
+ return isSchema(value) && Object.keys(value).length === 0;
161
+ }
162
+ function requiredOf(schema) {
163
+ return Array.isArray(schema.required) ? schema.required.filter((one) => typeof one === "string") : [];
164
+ }
165
+ function objectBranches(alternatives, depth = 0) {
166
+ if (depth > 8 || !Array.isArray(alternatives) || alternatives.length === 0) return void 0;
167
+ const branches = [];
168
+ for (const branch of alternatives) {
169
+ if (!isSchema(branch)) return void 0;
170
+ if (branch.type !== void 0 && branch.type !== "object") return void 0;
171
+ const nested = branch.anyOf ?? branch.oneOf;
172
+ if (nested !== void 0 && branch.properties === void 0 && branch.allOf === void 0) {
173
+ if (branch.anyOf !== void 0 && branch.oneOf !== void 0) return void 0;
174
+ const expanded = objectBranches(nested, depth + 1);
175
+ if (!expanded) return void 0;
176
+ branches.push(...expanded);
177
+ continue;
178
+ }
179
+ if (!isSchema(branch.properties)) return void 0;
180
+ if (COMPOSITION.some((key) => key in branch)) return void 0;
181
+ branches.push(branch);
182
+ }
183
+ return branches;
184
+ }
185
+ function form(branch) {
186
+ const required = new Set(requiredOf(branch));
187
+ return `{${Object.keys(branch.properties).map((key) => required.has(key) ? key : `${key}?`).join(", ")}}`;
188
+ }
189
+ function anthropicInputSchema(schema) {
190
+ if (!isSchema(schema) || schema.allOf !== void 0) return schema;
191
+ if (schema.anyOf !== void 0 && schema.oneOf !== void 0) return schema;
192
+ const branches = objectBranches(schema.anyOf ?? schema.oneOf);
193
+ if (!branches) return schema;
194
+ const rootProperties = isSchema(schema.properties) ? schema.properties : {};
195
+ const definitions = /* @__PURE__ */ new Map();
196
+ for (const branch of branches) for (const [key, definition] of Object.entries(branch.properties)) {
197
+ const seen = definitions.get(key) ?? [];
198
+ if (!isPlaceholder(definition) && !seen.some((one) => JSON.stringify(one) === JSON.stringify(definition))) seen.push(definition);
199
+ definitions.set(key, seen);
200
+ }
201
+ const properties = { ...rootProperties };
202
+ for (const [key, seen] of definitions) {
203
+ const hoisted = rootProperties[key];
204
+ if (hoisted !== void 0 && !isPlaceholder(hoisted)) continue;
205
+ properties[key] = seen.length === 0 ? {} : seen.length === 1 ? seen[0] : { anyOf: seen };
206
+ }
207
+ const required = new Set(requiredOf(schema));
208
+ const [first, ...rest] = branches.map((branch) => new Set(requiredOf(branch)));
209
+ for (const key of first ?? []) if (rest.every((one) => one.has(key)) && key in properties) required.add(key);
210
+ const forms = `Arguments take exactly one of these forms: ${branches.map(form).join(" | ")}.`;
211
+ const { anyOf: _anyOf, oneOf: _oneOf, ...root } = schema;
212
+ return {
213
+ ...root,
214
+ type: "object",
215
+ description: typeof schema.description === "string" ? `${schema.description}\n${forms}` : forms,
216
+ properties,
217
+ ...required.size > 0 ? { required: [...required] } : {},
218
+ ...schema.additionalProperties === void 0 && branches.every((branch) => branch.additionalProperties === false) ? { additionalProperties: false } : {}
219
+ };
220
+ }
221
+ //#endregion
101
222
  //#region src/protocol/request.ts
102
- /**
103
- * `ModelRequest` (kernel's vocabulary, provider-neutral) → Anthropic's
104
- * `MessageCreateParamsStreaming`. Everything this side must fix for the
105
- * outbound request lands here: `system` as the top-level parameter (not a
106
- * message), tool results kept as one message with several `tool_result`
107
- * blocks (the transcript shape, already Anthropic's own), and the thinking
108
- * configuration the port decided. Always streamed — 128K of output without
109
- * streaming risks an HTTP timeout.
110
- *
111
- * **Every request extends the previous one.** A reply's recorded volatile
112
- * notes are rendered just before it, as a text block at the end of the user
113
- * content that precedes it — exactly where the request that produced the
114
- * reply carried them — and the current step's notes go at the very end. So
115
- * the conversation a signature covers, and the prefix a cache entry keys on,
116
- * never change once sent.
117
- *
118
- * A signed `ThinkingPart` is echoed only when its endpoint, model and covered
119
- * non-thinking prefix match. Any mismatch drops the message's whole thinking
120
- * group while preserving its visible text and tool calls. A redacted block
121
- * goes back as the `redacted_thinking` it came as.
122
- */
123
223
  const SUMMARY_THINKING_HEADROOM = 8192;
124
224
  const DEFAULT_MAX_TOKENS = 16e3;
125
225
  const TOOL_ID = /^[a-zA-Z0-9_-]+$/;
126
- /**
127
- * The id Anthropic is sent for one tool call. A legal id goes as it is; any
128
- * other — another endpoint's `functions.name:0` — becomes its legal
129
- * characters plus a hash of the whole, decided by the id alone so a later
130
- * step adding ids never changes how an earlier one was sent.
131
- */
132
226
  function anthropicToolId(id) {
133
227
  if (TOOL_ID.test(id)) return id;
134
228
  const hash = createHash("sha256").update(id).digest("hex").slice(0, 12);
135
229
  return `${id.replace(/[^a-zA-Z0-9_-]/g, "_")}_${hash}`;
136
230
  }
137
- /** A planned file as blocks: the label and the image, or the line in its place. */
138
231
  function fileBlocks(planned, rendering) {
139
232
  const label = {
140
233
  type: "text",
@@ -163,7 +256,7 @@ function toContentBlockParams(part, at, context) {
163
256
  } : {
164
257
  type: "thinking",
165
258
  thinking: part.text,
166
- ...context.unsignedThinking ? part.signature === void 0 ? {} : { signature: part.signature } : { signature: part.signature ?? "" }
259
+ ...context.unsignedThinking ? {} : { signature: part.signature ?? "" }
167
260
  }];
168
261
  case "tool-use": return [{
169
262
  type: "tool_use",
@@ -188,31 +281,14 @@ function toContentBlockParams(part, at, context) {
188
281
  default: throw new Error(`unhandled content part type: ${String(part.type)}`);
189
282
  }
190
283
  }
191
- /**
192
- * Whether this endpoint can send one message's thinking group back.
193
- *
194
- * Two ways it cannot. **No signature**: it was never signed — a transcript
195
- * resumed from an OpenAI-style endpoint, or from before signatures were
196
- * carried — and a fabricated one is worse than none, because Anthropic
197
- * verifies it and answers a modified block with `400 invalid_request_error`,
198
- * failing every continuation. Endpoint, model and prefix attribution must all
199
- * match because a change to any covered input can invalidate the signature.
200
- * One incompatible member drops the whole group so no middle block is removed.
201
- *
202
- * Comparing endpoint ids is deliberately coarser than "same signer": two keys
203
- * against one vendor may share a signer, but replaying a block that cannot be
204
- * verified would reject the entire request.
205
- */
206
284
  function thinkingGroupIsSendable(message, options, prefix) {
207
285
  if (!message.content.some((part) => part.type === "text" && part.text !== "" || part.type === "tool-use")) return false;
208
286
  if (options.reasoningReplay === "omit" || message.outputTruncation?.incompleteThinking) return false;
209
- if (options.reasoningReplay === "unsigned-thinking") return true;
210
287
  const thinking = message.content.filter((part) => part.type === "thinking");
211
288
  if (thinking.length === 0) return true;
212
289
  const model = options.model ?? "";
213
- return thinking.every((part) => part.signature !== void 0 && part.issuer !== void 0 && part.issuer === options.endpoint && part.originModel === model && part.prefix === prefix);
290
+ 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()));
214
291
  }
215
- /** A text block with nothing in it: Anthropic refuses one. */
216
292
  function isEmptyText(part) {
217
293
  return part.type === "text" && part.text === "";
218
294
  }
@@ -222,7 +298,6 @@ function blocksOf(message, index, sendThinking, context) {
222
298
  part: partIndex
223
299
  }, context));
224
300
  }
225
- /** The one text block a set of notes renders as, or nothing. */
226
301
  function noteBlock(notes) {
227
302
  const text = (notes ?? []).map((note) => note.text).join("\n\n");
228
303
  return text === "" ? [] : [{
@@ -230,11 +305,6 @@ function noteBlock(notes) {
230
305
  text
231
306
  }];
232
307
  }
233
- /**
234
- * Appends blocks to the conversation's last user message, or as a user
235
- * message of their own after an assistant one. The Messages API combines
236
- * consecutive messages of one role, so both forms are one user turn.
237
- */
238
308
  function appendUser(messages, blocks) {
239
309
  if (blocks.length === 0) return;
240
310
  const last = messages.at(-1);
@@ -251,14 +321,16 @@ function appendUser(messages, blocks) {
251
321
  content: [...content, ...blocks]
252
322
  };
253
323
  }
254
- /**
255
- * Renders messages in Anthropic's shape, each reply preceded by the notes
256
- * its request appended, then `trailing` at the end. `sendThinking` decides,
257
- * per message index, whether its thinking group goes out.
258
- */
259
324
  function render(messages, trailing, sendThinking, context) {
260
325
  const out = [];
326
+ const updates = new Map(context.effortUpdates?.map((update) => [update.beforeUserMessageId, update.effort]));
261
327
  messages.forEach((message, index) => {
328
+ const effort = updates.get(message.id);
329
+ if (effort !== void 0) out.push({
330
+ role: "system",
331
+ content: [],
332
+ output_config: { effort }
333
+ });
262
334
  if (message.role === "assistant") appendUser(out, noteBlock(message.volatile));
263
335
  const content = blocksOf(message, index, sendThinking(message, index), context);
264
336
  if (content.length === 0) return;
@@ -275,11 +347,9 @@ function toToolParam(tool) {
275
347
  return {
276
348
  name: tool.name,
277
349
  description: tool.description,
278
- input_schema: tool.inputSchema
350
+ input_schema: anthropicInputSchema(tool.inputSchema)
279
351
  };
280
352
  }
281
- /** A copy without cache marks: where a breakpoint sits says nothing about what
282
- * the provider signed, so it must not change the fingerprint. */
283
353
  function unmarked(value) {
284
354
  return JSON.parse(JSON.stringify(value, (key, inner) => key === "cache_control" ? void 0 : inner));
285
355
  }
@@ -299,17 +369,21 @@ function prefixOf(system, tools, messages, support) {
299
369
  messages
300
370
  }));
301
371
  }
302
- /**
303
- * Computes the non-thinking prefix covered by a historical assistant
304
- * signature: everything before that message, its own recorded notes included
305
- * — they ended the request it answered. `messageIndex` names the message.
306
- */
307
- function anthropicPrefixBefore(request, messageIndex, media, support) {
308
- const before = request.messages.slice(0, messageIndex);
309
- const notes = request.messages[messageIndex]?.volatile;
310
- return prefixOf(systemOf(request), toolsOf(request), render(before, notes, () => false, fingerprintContext(request, media, support)), support);
372
+ function prefixReader(request, media, support, effortUpdates) {
373
+ let context;
374
+ const prefixes = /* @__PURE__ */ new Map();
375
+ return (index) => {
376
+ const cached = prefixes.get(index);
377
+ if (cached !== void 0) return cached;
378
+ context ??= {
379
+ ...fingerprintContext(request, media, support),
380
+ effortUpdates
381
+ };
382
+ const prefix = prefixOf(systemOf(request), toolsOf(request), render(request.messages.slice(0, index), request.messages[index]?.volatile, () => false, context), support);
383
+ prefixes.set(index, prefix);
384
+ return prefix;
385
+ };
311
386
  }
312
- /** The send plan, from the options' media context or the permissive default. */
313
387
  function planOf(request, media, support) {
314
388
  return support.planMedia(request, media ?? {
315
389
  acceptsImages: true,
@@ -325,24 +399,41 @@ function fingerprintContext(request, media, support) {
325
399
  rendering: "fingerprint"
326
400
  };
327
401
  }
328
- /**
329
- * Computes the prefix a new reply is signed under: everything the request
330
- * carried, its notes included, rendered the way `anthropicPrefixBefore`
331
- * renders it on the next step and without cache marks.
332
- */
333
- function anthropicRequestPrefix(request, media, support) {
334
- return prefixOf(systemOf(request), toolsOf(request), render(request.messages, request.volatile, () => false, fingerprintContext(request, media, support)), support);
402
+ function anthropicRequestPrefix(request, media, support, effortUpdates) {
403
+ return prefixOf(systemOf(request), toolsOf(request), render(request.messages, request.volatile, () => false, {
404
+ ...fingerprintContext(request, media, support),
405
+ effortUpdates
406
+ }), support);
407
+ }
408
+ function anthropicReplayChoices(request, options) {
409
+ const prefix = prefixReader(request, options.media, options.support, options.effortUpdates);
410
+ const eligibility = /* @__PURE__ */ new Map();
411
+ return (message, index, part) => {
412
+ let selected = eligibility.get(index);
413
+ if (selected === void 0) {
414
+ selected = message.role === "assistant" && thinkingGroupIsSendable(message, options, () => prefix(index));
415
+ eligibility.set(index, selected);
416
+ }
417
+ const unsigned = options.reasoningReplay === "unsigned-thinking";
418
+ return {
419
+ mode: unsigned ? "unsigned-thinking" : part.redacted ? "redacted-thinking" : "signed-thinking",
420
+ textIncluded: selected && (unsigned || !part.redacted) && part.text !== "",
421
+ group: message.id,
422
+ ...selected ? { selectedText: unsigned ? part.text : part.signature } : { reason: "not-applicable" }
423
+ };
424
+ };
335
425
  }
336
- /** Counts provider-retained thinking state that is actually replayed. */
337
426
  function anthropicHiddenInputTokens(request, options) {
427
+ if (options.reasoningReplay === "unsigned-thinking") return 0;
428
+ const prefix = prefixReader(request, options.media, options.support, options.effortUpdates);
338
429
  return request.messages.reduce((total, message, index) => {
339
- if (!thinkingGroupIsSendable(message, options, anthropicPrefixBefore(request, index, options.media, options.support))) return total;
430
+ if (!thinkingGroupIsSendable(message, options, () => prefix(index))) return total;
340
431
  return total + Math.max(0, ...message.content.map((part) => part.type === "thinking" ? part.outputTokens ?? 0 : 0));
341
432
  }, 0);
342
433
  }
343
434
  const EPHEMERAL = { type: "ephemeral" };
344
- /** Marks the last markable block of one message. */
345
435
  function markLast(message) {
436
+ if (message.role === "system") return message;
346
437
  if (typeof message.content === "string") return message;
347
438
  const content = [...message.content];
348
439
  for (let index = content.length - 1; index >= 0; index -= 1) {
@@ -359,12 +450,6 @@ function markLast(message) {
359
450
  }
360
451
  return message;
361
452
  }
362
- /**
363
- * Two conversation breakpoints: the end of this request, which the next step
364
- * repeats, and the end of the previous step's request — the user content
365
- * just before the last reply — whose cache entry this step reads exactly,
366
- * however many blocks the step added since.
367
- */
368
453
  function withConversationBreakpoints(messages) {
369
454
  const out = [...messages];
370
455
  const lastIndex = out.length - 1;
@@ -374,13 +459,13 @@ function withConversationBreakpoints(messages) {
374
459
  if (previous >= 0 && previous !== lastIndex && out[previous]?.role === "user") out[previous] = markLast(out[previous]);
375
460
  return out;
376
461
  }
377
- function toAnthropicRequest(request, options) {
462
+ function toAnthropicRequest(request, options, mediaPlan = planOf(request, options.media, options.support)) {
378
463
  const summary = request.purpose === "summary";
379
464
  if (summary && (!Number.isInteger(request.summaryMaxTokens) || Number(request.summaryMaxTokens) <= 0)) throw new Error("summaryMaxTokens must be a positive integer for a summary request");
380
465
  const ordinaryMaxTokens = options.maxTokens ?? DEFAULT_MAX_TOKENS;
381
466
  const thinkingOn = options.thinking !== void 0 && options.thinking.type !== "disabled";
382
467
  const maxTokens = summary ? Math.min(request.summaryMaxTokens, Number.isInteger(ordinaryMaxTokens) && ordinaryMaxTokens > 0 ? ordinaryMaxTokens : request.summaryMaxTokens) + (thinkingOn ? SUMMARY_THINKING_HEADROOM : 0) : ordinaryMaxTokens;
383
- const system = request.system?.map((text, index, all) => index === all.length - 1 ? {
468
+ const system = request.system?.map((text, index, all) => index === all.length - 1 && options.cacheBreakpoints !== false ? {
384
469
  type: "text",
385
470
  text,
386
471
  cache_control: EPHEMERAL
@@ -389,10 +474,12 @@ function toAnthropicRequest(request, options) {
389
474
  text
390
475
  });
391
476
  const tools = toolsOf(request);
392
- const messages = render(request.messages, request.volatile, (message, index) => thinkingGroupIsSendable(message, options, anthropicPrefixBefore(request, index, options.media, options.support)), {
393
- plan: planOf(request, options.media, options.support),
477
+ const prefix = prefixReader(request, options.media, options.support, options.effortUpdates);
478
+ const messages = render(request.messages, request.volatile, (message, index) => thinkingGroupIsSendable(message, options, () => prefix(index)), {
479
+ plan: mediaPlan,
394
480
  rendering: "wire",
395
- unsignedThinking: options.reasoningReplay === "unsigned-thinking"
481
+ unsignedThinking: options.reasoningReplay === "unsigned-thinking",
482
+ effortUpdates: options.effortUpdates
396
483
  });
397
484
  return {
398
485
  model: options.model ?? "",
@@ -401,27 +488,19 @@ function toAnthropicRequest(request, options) {
401
488
  ...options.effort === void 0 ? {} : { output_config: { effort: options.effort } },
402
489
  ...options.thinking === void 0 ? {} : { thinking: options.thinking },
403
490
  ...options.temperature === void 0 ? {} : { temperature: options.temperature },
404
- messages: withConversationBreakpoints(messages),
491
+ messages: options.cacheBreakpoints === false ? messages : withConversationBreakpoints(messages),
405
492
  ...system === void 0 ? {} : { system },
406
493
  ...tools === void 0 ? {} : { tools },
407
494
  ...request.toolChoice === "none" && tools !== void 0 ? { tool_choice: { type: "none" } } : {},
408
- ...summary ? {} : options.extra
495
+ ...summary && request.summaryShape !== "continuation" ? {} : options.extra,
496
+ ...summary ? { max_tokens: maxTokens } : {},
497
+ ...summary && request.toolChoice === "none" && tools !== void 0 ? { tool_choice: { type: "none" } } : {}
409
498
  };
410
499
  }
411
500
  //#endregion
412
501
  //#region src/protocol/sse-response.ts
413
502
  const MAX_FRAME_BYTES = 8388608;
414
503
  const WORK_PER_TURN = 65536;
415
- /**
416
- * Supplies one complete SSE frame per SDK read at the known messages streaming entrance.
417
- * Every successful body is framed, including suppliers with missing or incorrect MIME headers.
418
- * LF, CRLF and CR line endings are normalized to LF without decoding field bytes.
419
- * Incomplete EOF bytes are retained for the SDK's ordinary final-line handling.
420
- * A normalized frame exceeding 8 MiB is refused before further allocation.
421
- * Buffered input yields to timers and cancellation after at most 64 KiB of work.
422
- * Cancellation and read failure join original-body cancellation before releasing its reader.
423
- * Response metadata and HTTP error bodies are preserved.
424
- */
425
504
  function frameSseResponse(response, signal) {
426
505
  if (!response.ok || response.body === null) return response;
427
506
  const reader = response.body.getReader();
@@ -565,13 +644,9 @@ function toFinishReason(stopReason, support) {
565
644
  category: "protocol",
566
645
  source: "protocol",
567
646
  retryable: false
568
- });
647
+ }, stopReason === null ? void 0 : { details: { finishReason: String(stopReason) } });
569
648
  }
570
649
  }
571
- /** The accumulated `input_json_delta` text as JSON, or `undefined` when it
572
- * will not parse — which is what a tool-use block cut off at `max_tokens`
573
- * looks like. `JSON.parse` never produces `undefined` itself, so it is free
574
- * to stand for "no usable input here". */
575
650
  function parseToolInput(json) {
576
651
  if (json.length === 0) return {};
577
652
  try {
@@ -580,129 +655,154 @@ function parseToolInput(json) {
580
655
  return;
581
656
  }
582
657
  }
583
- /**
584
- * Streams provider deltas and a completed, usable reply with signed reasoning.
585
- * Unknown terminal reasons and replies containing only reasoning fail without retry;
586
- * a stream without message_stop retains interruption semantics.
587
- */
588
- async function* mapAnthropicStream(events, attribution, support) {
658
+ function describeInvalidInput(block) {
659
+ return `tool_use ${block.name} input is not JSON (${block.json.length} chars)`;
660
+ }
661
+ async function* mapAnthropicStream(events, attribution, support, usageReporter) {
589
662
  const blocks = /* @__PURE__ */ new Map();
590
663
  const finalContent = [];
591
664
  const incompleteToolCalls = [];
665
+ const invalidInputs = [];
592
666
  let incompleteThinking = false;
667
+ let reportedInput;
668
+ let reportedOutput;
669
+ let usageSequence = 0;
670
+ let ordinaryInputTokens = 0;
593
671
  let inputTokens = 0;
594
672
  let outputTokens = 0;
595
673
  let cache = {};
596
674
  let stopped = false;
597
675
  let stopReason = null;
598
676
  let refusalCategory;
599
- for await (const event of events) switch (event.type) {
600
- case "message_start": {
601
- const usage = event.message.usage;
602
- inputTokens = usage.input_tokens + (usage.cache_read_input_tokens ?? 0) + (usage.cache_creation_input_tokens ?? 0);
603
- outputTokens = event.message.usage.output_tokens;
604
- cache = {
605
- ...typeof usage.cache_read_input_tokens === "number" ? { cacheReadTokens: usage.cache_read_input_tokens } : {},
606
- ...typeof usage.cache_creation_input_tokens === "number" ? { cacheWriteTokens: usage.cache_creation_input_tokens } : {}
607
- };
608
- break;
609
- }
610
- case "content_block_start": {
611
- const block = event.content_block;
612
- if (block.type === "text") blocks.set(event.index, {
613
- kind: "text",
614
- text: block.text
615
- });
616
- else if (block.type === "tool_use") {
617
- blocks.set(event.index, {
618
- kind: "tool-use",
619
- id: block.id,
620
- name: block.name,
621
- json: ""
622
- });
623
- yield {
624
- kind: "tool-call-delta",
625
- id: block.id,
626
- name: block.name,
627
- inputDelta: ""
628
- };
629
- } else if (block.type === "thinking") blocks.set(event.index, {
630
- kind: "thinking",
631
- text: ""
632
- });
633
- else if (block.type === "redacted_thinking") blocks.set(event.index, {
634
- kind: "redacted",
635
- data: block.data
636
- });
637
- else blocks.set(event.index, { kind: "skipped" });
638
- break;
639
- }
640
- case "content_block_delta": {
641
- const block = blocks.get(event.index);
642
- const delta = event.delta;
643
- if (delta.type === "text_delta") {
644
- if (block?.kind === "text") block.text += delta.text;
645
- yield {
646
- kind: "text-delta",
647
- text: delta.text
648
- };
649
- } else if (delta.type === "thinking_delta") {
650
- if (block?.kind === "thinking") block.text += delta.thinking;
651
- yield {
652
- kind: "thinking-delta",
653
- text: delta.thinking
654
- };
655
- } else if (delta.type === "signature_delta") {
656
- if (block?.kind === "thinking") block.signature = delta.signature;
657
- } else if (delta.type === "input_json_delta" && block?.kind === "tool-use") {
658
- block.json += delta.partial_json;
659
- yield {
660
- kind: "tool-call-delta",
661
- id: block.id,
662
- inputDelta: delta.partial_json
677
+ for await (const event of events) {
678
+ switch (event.type) {
679
+ case "message_start": {
680
+ const usage = event.message.usage;
681
+ ordinaryInputTokens = usage.input_tokens;
682
+ inputTokens = ordinaryInputTokens + (usage.cache_read_input_tokens ?? 0) + (usage.cache_creation_input_tokens ?? 0);
683
+ outputTokens = event.message.usage.output_tokens;
684
+ cache = {
685
+ ...typeof usage.cache_read_input_tokens === "number" ? { cacheReadTokens: usage.cache_read_input_tokens } : {},
686
+ ...typeof usage.cache_creation_input_tokens === "number" ? { cacheWriteTokens: usage.cache_creation_input_tokens } : {}
663
687
  };
688
+ break;
664
689
  }
665
- break;
666
- }
667
- case "content_block_stop": {
668
- const block = blocks.get(event.index);
669
- if (block?.kind === "text") {
670
- if (block.text !== "") finalContent.push({
671
- type: "text",
690
+ case "content_block_start": {
691
+ const block = event.content_block;
692
+ if (block.type === "text") blocks.set(event.index, {
693
+ kind: "text",
672
694
  text: block.text
673
695
  });
674
- } else if (block?.kind === "redacted") finalContent.push({
675
- type: "thinking",
676
- text: "",
677
- signature: block.data,
678
- redacted: true
679
- });
680
- else if (block?.kind === "tool-use") {
681
- const input = parseToolInput(block.json);
682
- if (input === void 0) incompleteToolCalls.push({
683
- id: block.id,
684
- name: block.name
696
+ else if (block.type === "tool_use") {
697
+ blocks.set(event.index, {
698
+ kind: "tool-use",
699
+ id: block.id,
700
+ name: block.name,
701
+ json: ""
702
+ });
703
+ yield {
704
+ kind: "tool-call-delta",
705
+ id: block.id,
706
+ name: block.name,
707
+ inputDelta: ""
708
+ };
709
+ } else if (block.type === "thinking") blocks.set(event.index, {
710
+ kind: "thinking",
711
+ text: ""
685
712
  });
686
- else finalContent.push({
687
- type: "tool-use",
688
- id: block.id,
689
- name: block.name,
690
- input
713
+ else if (block.type === "redacted_thinking") blocks.set(event.index, {
714
+ kind: "redacted",
715
+ data: block.data
691
716
  });
692
- } else if (block?.kind === "thinking") finalContent.push({
693
- type: "thinking",
694
- text: block.text,
695
- ...block.signature === void 0 ? {} : { signature: block.signature }
717
+ else blocks.set(event.index, { kind: "skipped" });
718
+ break;
719
+ }
720
+ case "content_block_delta": {
721
+ const block = blocks.get(event.index);
722
+ const delta = event.delta;
723
+ if (delta.type === "text_delta") {
724
+ if (block?.kind === "text") block.text += delta.text;
725
+ yield {
726
+ kind: "text-delta",
727
+ text: delta.text
728
+ };
729
+ } else if (delta.type === "thinking_delta") {
730
+ if (block?.kind === "thinking") block.text += delta.thinking;
731
+ yield {
732
+ kind: "thinking-delta",
733
+ text: delta.thinking
734
+ };
735
+ } else if (delta.type === "signature_delta") {
736
+ if (block?.kind === "thinking") block.signature = delta.signature;
737
+ } else if (delta.type === "input_json_delta" && block?.kind === "tool-use") {
738
+ block.json += delta.partial_json;
739
+ yield {
740
+ kind: "tool-call-delta",
741
+ id: block.id,
742
+ inputDelta: delta.partial_json
743
+ };
744
+ }
745
+ break;
746
+ }
747
+ case "content_block_stop": {
748
+ const block = blocks.get(event.index);
749
+ if (block?.kind === "text") {
750
+ if (block.text !== "") finalContent.push({
751
+ type: "text",
752
+ text: block.text
753
+ });
754
+ } else if (block?.kind === "redacted") finalContent.push({
755
+ type: "thinking",
756
+ text: "",
757
+ signature: block.data,
758
+ redacted: true
759
+ });
760
+ else if (block?.kind === "tool-use") {
761
+ const input = parseToolInput(block.json);
762
+ if (input === void 0) {
763
+ incompleteToolCalls.push({
764
+ id: block.id,
765
+ name: block.name
766
+ });
767
+ invalidInputs.push(describeInvalidInput(block));
768
+ } else finalContent.push({
769
+ type: "tool-use",
770
+ id: block.id,
771
+ name: block.name,
772
+ input
773
+ });
774
+ } else if (block?.kind === "thinking") finalContent.push({
775
+ type: "thinking",
776
+ text: block.text,
777
+ ...block.signature === void 0 ? {} : { signature: block.signature }
778
+ });
779
+ blocks.delete(event.index);
780
+ break;
781
+ }
782
+ case "message_delta": {
783
+ stopReason = event.delta.stop_reason ?? stopReason;
784
+ if (event.delta.stop_details?.type === "refusal") refusalCategory = event.delta.stop_details.category ?? "unspecified";
785
+ const usage = event.usage;
786
+ if (typeof usage.input_tokens === "number") ordinaryInputTokens = usage.input_tokens;
787
+ if (typeof usage.cache_read_input_tokens === "number") cache.cacheReadTokens = usage.cache_read_input_tokens;
788
+ if (typeof usage.cache_creation_input_tokens === "number") cache.cacheWriteTokens = usage.cache_creation_input_tokens;
789
+ inputTokens = ordinaryInputTokens + (cache.cacheReadTokens ?? 0) + (cache.cacheWriteTokens ?? 0);
790
+ outputTokens = usage.output_tokens;
791
+ break;
792
+ }
793
+ case "message_stop": stopped = true;
794
+ }
795
+ const usage = event.type === "message_start" ? event.message.usage : event.type === "message_delta" ? event.usage : void 0;
796
+ if (usage) {
797
+ if (typeof usage.input_tokens === "number") reportedInput = usage.input_tokens;
798
+ if (typeof usage.output_tokens === "number") reportedOutput = usage.output_tokens;
799
+ usageReporter?.report({
800
+ sequence: ++usageSequence,
801
+ ...reportedInput === void 0 ? {} : { inputTokens: reportedInput + (cache.cacheReadTokens ?? 0) + (cache.cacheWriteTokens ?? 0) },
802
+ ...reportedOutput === void 0 ? {} : { outputTokens: reportedOutput },
803
+ ...cache
696
804
  });
697
- blocks.delete(event.index);
698
- break;
699
805
  }
700
- case "message_delta":
701
- stopReason = event.delta.stop_reason ?? stopReason;
702
- if (event.delta.stop_details?.type === "refusal") refusalCategory = event.delta.stop_details.category ?? "unspecified";
703
- outputTokens = event.usage.output_tokens;
704
- break;
705
- case "message_stop": stopped = true;
706
806
  }
707
807
  if (!stopped) throw support.interruptedFailure();
708
808
  const finishReason = toFinishReason(stopReason, support);
@@ -722,15 +822,19 @@ async function* mapAnthropicStream(events, attribution, support) {
722
822
  name: block.name
723
823
  });
724
824
  else if (block.kind === "redacted") incompleteThinking = true;
725
- } else if (incompleteToolCalls.length > 0 || blocks.size > 0) throw support.failures.create({
726
- code: "response-invalid",
727
- stage: "response-validation",
728
- category: "protocol",
729
- source: "protocol",
730
- retryable: false,
731
- finishReason
732
- });
733
- if (finishReason !== "refusal" && finishReason !== "max-tokens" && !finalContent.some((part) => part.type === "text" || part.type === "tool-use")) throw support.failures.create({
825
+ } else if (blocks.size > 0) {
826
+ const unclosed = [...blocks].map(([index, block]) => block.kind === "tool-use" ? `${index}:tool-use(${block.name})` : `${index}:${block.kind}`);
827
+ throw support.failures.create({
828
+ code: "response-invalid",
829
+ stage: "response-validation",
830
+ category: "protocol",
831
+ source: "protocol",
832
+ retryable: false,
833
+ finishReason
834
+ }, { cause: new Error([...invalidInputs, ...unclosed.length > 0 ? [`blocks without content_block_stop: ${unclosed.join(", ")}`] : []].join("; ")) });
835
+ }
836
+ const droppedToolCalls = finishReason === "max-tokens" ? [] : incompleteToolCalls;
837
+ if (finishReason !== "refusal" && finishReason !== "max-tokens" && droppedToolCalls.length === 0 && !finalContent.some((part) => part.type === "text" || part.type === "tool-use")) throw support.failures.create({
734
838
  code: "response-empty",
735
839
  stage: "response-validation",
736
840
  category: "protocol",
@@ -738,7 +842,7 @@ async function* mapAnthropicStream(events, attribution, support) {
738
842
  retryable: false,
739
843
  finishReason
740
844
  });
741
- const attributedContent = finalContent.map((part) => part.type === "thinking" && part.signature !== void 0 && attribution !== void 0 ? {
845
+ const attributedContent = finalContent.map((part) => part.type === "thinking" && attribution !== void 0 ? {
742
846
  ...part,
743
847
  originModel: attribution.originModel,
744
848
  prefix: attribution.prefix,
@@ -751,10 +855,12 @@ async function* mapAnthropicStream(events, attribution, support) {
751
855
  incompleteToolCalls,
752
856
  ...incompleteThinking ? { incompleteThinking: true } : {}
753
857
  } } : {},
858
+ ...droppedToolCalls.length > 0 ? { droppedToolCalls } : {},
754
859
  usage: {
755
- inputTokens,
756
- outputTokens,
757
- ...cache
860
+ inputTokens: Number.isSafeInteger(inputTokens) && inputTokens >= 0 ? inputTokens : 0,
861
+ outputTokens: Number.isSafeInteger(outputTokens) && outputTokens >= 0 ? outputTokens : 0,
862
+ ...Object.fromEntries(Object.entries(cache).filter(([, value]) => Number.isSafeInteger(value) && value >= 0)),
863
+ ...Number.isSafeInteger(reportedInput) && Number(reportedInput) >= 0 && Number.isSafeInteger(inputTokens) && inputTokens >= 0 && Object.values(cache).every((value) => Number.isSafeInteger(value) && value >= 0) ? {} : { inputTokensReported: false }
758
864
  },
759
865
  ...refusalCategory !== void 0 ? { refusalCategory } : {},
760
866
  message: {
@@ -765,31 +871,11 @@ async function* mapAnthropicStream(events, attribution, support) {
765
871
  }
766
872
  //#endregion
767
873
  //#region src/protocol/port.ts
768
- /**
769
- * Wires request-building (request.ts), stream-mapping (stream.ts) and the
770
- * injected host retry loop into the `ModelPort` the
771
- * kernel's call-model slot dispatches to. Rate limits, overload, server
772
- * errors, dropped connections and stalls are retried with a
773
- * `retry-after`-honouring backoff; a retry after output first retracts what
774
- * streamed. Everything else, and a retryable failure once the budget is
775
- * spent, becomes the error the driver turns into a failed outcome.
776
- */
777
- /** Lets a budget-thinking model think between tool calls. */
778
874
  const INTERLEAVED_THINKING_BETA = "interleaved-thinking-2025-05-14";
779
- /** The budget a budget-thinking model gets when a person set none. */
875
+ const MID_CONVERSATION_EFFORT_BETA = "mid-conversation-output-config-2026-07-01";
780
876
  const DEFAULT_BUDGET = 16e3;
781
877
  const BUDGET_FLOOR = 1024;
782
- /**
783
- * The neutral plan in Anthropic's own spelling.
784
- *
785
- * Thinking on is `adaptive` with a readable summary — current models stream
786
- * empty thinking without `display: 'summarized'` — and the effort; a model
787
- * whose thinking is a token budget gets `enabled` with the stored budget or a
788
- * default one under `max_tokens`, or no thinking at all when `max_tokens`
789
- * leaves no room for the smallest budget. Thinking off is `disabled`. While
790
- * thinking is on no temperature goes out: Anthropic refuses one then.
791
- */
792
- function anthropicOptions(plan, model, budgetOnly = []) {
878
+ function anthropicOptions(plan, model, budgetOnly = [], policy = {}) {
793
879
  const on = plan.thinking === true;
794
880
  const maxTokens = plan.maxTokens;
795
881
  const budget = () => {
@@ -798,43 +884,60 @@ function anthropicOptions(plan, model, budgetOnly = []) {
798
884
  const wanted = plan.budgetTokens ?? Math.min(DEFAULT_BUDGET, Math.floor((maxTokens ?? 0) / 2));
799
885
  return Math.min(Math.max(wanted, BUDGET_FLOOR), ceiling);
800
886
  };
801
- const byBudget = plan.budgetTokens !== void 0 || budgetOnly.some((one) => model.startsWith(one));
887
+ const byBudget = policy.thinkingMode === "budget" || plan.budgetTokens !== void 0 || budgetOnly.some((one) => model.startsWith(one));
802
888
  const tokens = on && byBudget ? budget() : void 0;
803
- const thinking = !on ? plan.thinking === false ? { type: "disabled" } : void 0 : byBudget ? tokens === void 0 ? void 0 : {
889
+ 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 : {
804
890
  type: "enabled",
805
891
  budget_tokens: tokens
806
892
  } : {
807
893
  type: "adaptive",
808
- display: "summarized"
894
+ ...policy.thinkingSummary === false ? {} : { display: "summarized" }
809
895
  };
810
896
  return {
811
- ...plan.effort === void 0 || !on ? {} : { effort: plan.effort },
897
+ ...plan.effort === void 0 || !on || policy.thinkingEffort === false ? {} : { effort: plan.effort },
812
898
  ...plan.temperature === void 0 || on ? {} : { temperature: plan.temperature },
813
899
  ...maxTokens === void 0 ? {} : { maxTokens },
814
900
  ...thinking === void 0 ? {} : { thinking },
815
- ...thinking?.type === "enabled" ? { betas: [INTERLEAVED_THINKING_BETA] } : {}
901
+ ...thinking?.type === "enabled" && policy.thinkingBeta !== false ? { betas: [INTERLEAVED_THINKING_BETA] } : {}
816
902
  };
817
903
  }
818
- /** Creates an Anthropic port with synchronous request inspection and safe stream retries. */
819
904
  function createAnthropicModelPort(options) {
820
- function clientForAttempt(reportProgress) {
821
- return options.client ?? new Anthropic({
822
- apiKey: options.apiKey ?? "",
823
- fetch: async (...args) => frameSseResponse(options.support.observeResponseProgress(await (options.fetch ?? globalThis.fetch)(...args), reportProgress), args[1]?.signal),
905
+ async function clientForAttempt(reportProgress, dispatched) {
906
+ const { default: Anthropic } = await loadAnthropicSdk();
907
+ if (options.client) return options.client;
908
+ const client = new Anthropic({
909
+ apiKey: options.allowUnauthenticated && !options.apiKey ? "not-used" : options.apiKey ?? "",
910
+ ...options.allowUnauthenticated && !options.apiKey ? {
911
+ authToken: null,
912
+ defaultHeaders: {
913
+ "x-api-key": null,
914
+ Authorization: null
915
+ }
916
+ } : {},
917
+ fetch: async (...args) => {
918
+ const pending = (options.fetch ?? globalThis.fetch)(...args);
919
+ dispatched();
920
+ return frameSseResponse(options.support.observeResponseProgress(await pending, reportProgress), args[1]?.signal);
921
+ },
824
922
  baseURL: options.baseURL ?? "",
825
923
  maxRetries: 0
826
924
  });
925
+ return { messages: { create: (body, requestOptions) => client.post("/messages", {
926
+ body,
927
+ ...requestOptions,
928
+ stream: true
929
+ }) } };
827
930
  }
828
931
  function build(request) {
829
- const capacity = options.catalogue?.()?.limit;
830
- const plan = options.params === void 0 ? void 0 : anthropicOptions(options.params(request.params ?? {}), options.model ?? "", options.budgetOnly);
932
+ const capacity = options.support.freezePayload(options.catalogue?.()?.limit ?? {});
933
+ const plan = options.params === void 0 ? void 0 : anthropicOptions(options.params(request.params ?? {}), options.model ?? "", options.budgetOnly, options);
831
934
  const { media: mediaOf, ...rest } = options;
832
935
  const media = mediaOf?.(request.params ?? {});
833
936
  const base = media === void 0 ? rest : {
834
937
  ...rest,
835
938
  media
836
939
  };
837
- const requestOptions = plan === void 0 ? base : {
940
+ let requestOptions = plan === void 0 ? base : {
838
941
  ...base,
839
942
  ...plan,
840
943
  extra: {
@@ -842,58 +945,195 @@ function createAnthropicModelPort(options) {
842
945
  ...options.support.extraParams(request.params ?? {})
843
946
  }
844
947
  };
845
- const betas = plan?.betas;
948
+ const declaredDefault = options.effortCacheModels?.[options.model ?? ""];
949
+ const replay = options.support.planEffortCache({
950
+ request,
951
+ inspection: false,
952
+ effort: requestOptions.effort,
953
+ capability: options.effortCache === false ? {
954
+ status: "unsupported",
955
+ reason: "configuration-updates-unavailable"
956
+ } : requestOptions.thinking?.type !== "adaptive" ? {
957
+ status: "unsupported",
958
+ reason: "adaptive-thinking-required"
959
+ } : {
960
+ status: "supported",
961
+ ...declaredDefault ? { defaultEffort: declaredDefault } : {}
962
+ },
963
+ bindingFingerprint: options.support.inspectionFingerprint({
964
+ connectionFingerprint: options.connectionFingerprint,
965
+ endpoint: options.endpoint,
966
+ baseURL: options.baseURL,
967
+ model: options.model,
968
+ system: request.system,
969
+ tools: request.tools,
970
+ thinking: requestOptions.thinking,
971
+ extra: requestOptions.extra,
972
+ reasoningReplay: requestOptions.reasoningReplay
973
+ })
974
+ });
975
+ requestOptions = {
976
+ ...requestOptions,
977
+ effort: replay.baseEffort,
978
+ effortUpdates: replay.updates
979
+ };
980
+ const betas = [...plan?.betas ?? [], ...replay.updates.length ? [MID_CONVERSATION_EFFORT_BETA] : []];
981
+ const mediaPlan = options.support.planMedia(request, requestOptions.media ?? {
982
+ acceptsImages: true,
983
+ limits: void 0
984
+ });
985
+ const params = options.support.freezePayload(toAnthropicRequest(request, requestOptions, mediaPlan));
986
+ const receipts = new Map(replay.replaySources?.map((source) => [source.messageId, JSON.stringify(source.contribution)]));
987
+ const thinkingChoice = anthropicReplayChoices(request, requestOptions);
988
+ const replaySelections = options.support.prepareReplaySelections(request, ({ message, messageIndex, part }) => part ? thinkingChoice(message, messageIndex, part) : {
989
+ mode: "effort-cache",
990
+ textIncluded: false,
991
+ selectedText: receipts.get(message.id),
992
+ reason: "not-applicable"
993
+ });
994
+ const fields = /* @__PURE__ */ new Map();
995
+ let mediaIndex = 0;
996
+ const block = (value) => {
997
+ if (!value || typeof value !== "object") return;
998
+ const item = value;
999
+ if (item.type === "image") {
1000
+ const source = item.source;
1001
+ const planned = mediaPlan.sent[mediaIndex++];
1002
+ if (!planned || source?.type !== "base64" || source.data !== (planned.data ?? "")) throw new Error("prepared_media_selection_mismatch");
1003
+ const data = planned.data ?? "", hash = createHash("sha256");
1004
+ for (let offset = 0; offset < data.length; offset += 65536) hash.update(data.slice(offset, offset + 65536), "base64");
1005
+ fields.set(source, /* @__PURE__ */ new Map([["data", {
1006
+ kind: "media",
1007
+ value: JSON.stringify({
1008
+ sha256: hash.digest("hex"),
1009
+ byteLength: Buffer.byteLength(data, "base64"),
1010
+ variantId: planned.variantId,
1011
+ mediaType: planned.mediaType,
1012
+ width: planned.width,
1013
+ height: planned.height
1014
+ })
1015
+ }]]));
1016
+ } else if (item.type === "thinking" || item.type === "redacted_thinking") {
1017
+ const key = item.type === "thinking" ? "signature" : "data";
1018
+ const data = item[key];
1019
+ if (typeof data === "string") fields.set(item, /* @__PURE__ */ new Map([[key, {
1020
+ kind: "replay",
1021
+ value: JSON.stringify({
1022
+ sha256: createHash("sha256").update(data).digest("hex"),
1023
+ byteLength: Buffer.byteLength(data),
1024
+ mode: item.type,
1025
+ model: params.model
1026
+ })
1027
+ }]]));
1028
+ } else if (item.type === "tool_result" && Array.isArray(item.content)) for (const child of item.content) block(child);
1029
+ };
1030
+ for (const message of params.messages) if (Array.isArray(message.content)) for (const item of message.content) block(item);
1031
+ if (mediaIndex !== mediaPlan.sent.length) throw new Error("prepared_media_selection_mismatch");
846
1032
  return {
847
- params: toAnthropicRequest(request, requestOptions),
848
- requestOptions,
1033
+ params,
1034
+ replaySelections,
1035
+ fields,
1036
+ request: {
1037
+ ...request,
1038
+ params: options.support.freezePayload(request.params ?? {})
1039
+ },
849
1040
  capacity,
1041
+ hiddenInputTokens: anthropicHiddenInputTokens(request, requestOptions),
1042
+ mediaPlan,
1043
+ mediaTokens: mediaPlan.tokens,
1044
+ prefix: anthropicRequestPrefix(request, requestOptions.media, options.support, requestOptions.effortUpdates),
1045
+ fingerprint: options.support.freezePayload({
1046
+ rendering: "anthropic-messages-v3",
1047
+ baseURL: options.baseURL,
1048
+ endpoint: options.endpoint ?? options.baseURL,
1049
+ model: params.model,
1050
+ purpose: request.purpose,
1051
+ summaryShape: request.summaryShape,
1052
+ settings: {
1053
+ effort: requestOptions.effort,
1054
+ thinking: requestOptions.thinking,
1055
+ temperature: requestOptions.temperature,
1056
+ maxTokens: params.max_tokens,
1057
+ extra: request.purpose === "summary" && request.summaryShape !== "continuation" ? void 0 : requestOptions.extra
1058
+ }
1059
+ }),
1060
+ replayData: replay.replayData,
1061
+ effectiveEffort: replay.effectiveEffort,
850
1062
  headers: betas === void 0 || betas.length === 0 ? void 0 : { "anthropic-beta": betas.join(",") }
851
1063
  };
852
1064
  }
853
- return {
854
- inspect(request) {
855
- const { params, requestOptions, capacity } = build(request);
1065
+ return options.support.createPreparedPort({
1066
+ prepare: build,
1067
+ semantics(payload) {
1068
+ return {
1069
+ replaySelections: payload.replaySelections,
1070
+ mediaSelections: () => options.support.mediaSelections(payload.mediaPlan),
1071
+ format: "request-semantic-v1",
1072
+ protocolId: "anthropic",
1073
+ adapterVersion: "1",
1074
+ rendererVersion: "anthropic-messages-v3",
1075
+ parameters: Object.freeze(Object.fromEntries(Object.entries(payload.params).filter(([key]) => ![
1076
+ "model",
1077
+ "messages",
1078
+ "system",
1079
+ "tools",
1080
+ "stream"
1081
+ ].includes(key)))),
1082
+ toolDefinitions: payload.params.tools ?? Object.freeze([]),
1083
+ frames: () => options.support.semanticFrames(payload.params, {
1084
+ omitRoot: ["stream"],
1085
+ fields: payload.fields
1086
+ })
1087
+ };
1088
+ },
1089
+ async inspect(payload, signal) {
1090
+ signal.throwIfAborted();
1091
+ const started = options.support.performance?.now();
1092
+ const { params, request, capacity, hiddenInputTokens, mediaTokens, fingerprint } = payload;
856
1093
  const outputReserve = Number.isInteger(params.max_tokens) && params.max_tokens > 0 ? params.max_tokens : capacity?.output ?? 0;
857
- return options.support.inspect({
1094
+ options.support.performance?.observe({
1095
+ stage: "model.project",
1096
+ measurementPurpose: "request",
1097
+ durationMs: options.support.performance.now() - started,
1098
+ count: 1
1099
+ });
1100
+ const text = options.support.requestText("messages", params);
1101
+ const inspection = options.support.inspect({
858
1102
  body: params,
859
- textTokens: options.support.measureText(options.support.requestText("messages", params)),
860
- tokenizer: "o200k_base-protocol-text-v2",
1103
+ textTokens: 0,
1104
+ textBytes: Buffer.byteLength(text),
1105
+ tokenizer: "utf8-bytes-quarter-v1",
861
1106
  request,
862
1107
  capacity,
863
1108
  outputReserve,
864
1109
  outputReserveSource: Number.isInteger(params.max_tokens) && params.max_tokens > 0 ? "enforced" : "capacity",
865
- hiddenInputTokens: anthropicHiddenInputTokens(request, requestOptions),
866
- mediaTokens: options.support.planMedia(request, requestOptions.media ?? {
867
- acceptsImages: true,
868
- limits: void 0
869
- }).tokens,
870
- fingerprint: {
871
- rendering: "anthropic-messages-v3",
872
- endpoint: options.endpoint ?? options.baseURL,
873
- model: params.model,
874
- purpose: request.purpose,
875
- contextWindow: request.params?.contextWindow,
876
- capacity,
877
- settings: {
878
- effort: requestOptions.effort,
879
- thinking: requestOptions.thinking,
880
- temperature: requestOptions.temperature,
881
- maxTokens: params.max_tokens,
882
- extra: request.purpose === "summary" ? void 0 : requestOptions.extra
883
- }
884
- }
1110
+ hiddenInputTokens,
1111
+ mediaTokens,
1112
+ fingerprint
885
1113
  });
1114
+ const textTokens = await options.support.measureText(text, signal);
1115
+ signal.throwIfAborted();
1116
+ return {
1117
+ ...inspection,
1118
+ inputTokens: inspection.inputTokens + textTokens
1119
+ };
886
1120
  },
887
- stream(request, signal, observer) {
1121
+ stream(payload, signal, observer, scope) {
888
1122
  signal.throwIfAborted();
889
- const { params, headers, requestOptions } = build(request);
890
- const prefix = anthropicRequestPrefix(request, requestOptions.media, options.support);
1123
+ const { params, headers, prefix, replayData, effectiveEffort } = payload;
891
1124
  return options.support.withChatAttempts({
1125
+ retainCleanup: scope.retainCleanup,
1126
+ beforeAttempt: (_signal, ordinal) => observer?.beforeAttempt?.(ordinal),
1127
+ accountingDispatch: options.accountingDispatch,
1128
+ effective: {
1129
+ outputLimit: params.max_tokens,
1130
+ effort: params.output_config?.effort
1131
+ },
892
1132
  signal,
893
1133
  ...options.maxRetries === void 0 ? {} : { maxRetries: options.maxRetries },
894
1134
  ...options.sleep === void 0 ? {} : { sleep: options.sleep },
895
1135
  ...options.idleMs === void 0 ? {} : { idleMs: options.idleMs },
896
- async *attempt(attemptSignal, reportProgress, attempt) {
1136
+ async *attempt(attemptSignal, reportProgress, attempt, usageReporter) {
897
1137
  const observe = (event) => {
898
1138
  try {
899
1139
  observer?.observe?.(event);
@@ -901,7 +1141,41 @@ function createAnthropicModelPort(options) {
901
1141
  };
902
1142
  const attemptCount = attempt + 1;
903
1143
  let outcome = "unknown";
1144
+ let timeout;
1145
+ const abortedOutcome = () => {
1146
+ const reason = options.support.failures.verified(attemptSignal.reason);
1147
+ if (reason?.code !== "stream-idle-timeout") return "cancelled";
1148
+ timeout = reason;
1149
+ return "timeout";
1150
+ };
904
1151
  let firstResponseFinished = false;
1152
+ let dispatchObserved = false;
1153
+ const markDispatched = () => {
1154
+ if (dispatchObserved) return;
1155
+ dispatchObserved = true;
1156
+ try {
1157
+ const thinking = params.thinking;
1158
+ const effort = effectiveEffort ?? params.output_config?.effort ?? (thinking?.budget_tokens !== void 0 ? `${thinking.budget_tokens} tokens` : thinking?.type === "adaptive" ? "adaptive" : void 0);
1159
+ observer?.dispatched({
1160
+ attempt,
1161
+ presentation: {
1162
+ schema: "chat.dispatch-settings.v1",
1163
+ data: {
1164
+ model: {
1165
+ availability: "resolved",
1166
+ value: params.model,
1167
+ origin: "protocol"
1168
+ },
1169
+ effort: effort ? {
1170
+ availability: "resolved",
1171
+ value: effort,
1172
+ origin: "protocol"
1173
+ } : { availability: "not-applicable" }
1174
+ }
1175
+ }
1176
+ });
1177
+ } catch {}
1178
+ };
905
1179
  observe({
906
1180
  stage: "attempt",
907
1181
  phase: "start",
@@ -912,12 +1186,18 @@ function createAnthropicModelPort(options) {
912
1186
  phase: "start",
913
1187
  attempt: attemptCount
914
1188
  });
1189
+ let sdkIterator;
915
1190
  try {
1191
+ const client = await clientForAttempt(reportProgress, markDispatched);
916
1192
  attemptSignal.throwIfAborted();
917
- const events = await clientForAttempt(reportProgress).messages.create(params, {
1193
+ const pending = client.messages.create(params, {
918
1194
  signal: attemptSignal,
919
1195
  ...headers === void 0 ? {} : { headers }
920
1196
  });
1197
+ if (options.client) markDispatched();
1198
+ const events = await pending;
1199
+ if (options.client) reportProgress();
1200
+ sdkIterator = events[Symbol.asyncIterator]();
921
1201
  firstResponseFinished = true;
922
1202
  observe({
923
1203
  stage: "first-response",
@@ -926,38 +1206,48 @@ function createAnthropicModelPort(options) {
926
1206
  outcome: "ok"
927
1207
  });
928
1208
  attemptSignal.throwIfAborted();
929
- try {
930
- observer?.dispatched({ attempt });
931
- } catch {}
932
- attemptSignal.throwIfAborted();
1209
+ const iterator = sdkIterator;
933
1210
  const observed = (async function* () {
934
- for await (const event of events) {
1211
+ for (;;) {
1212
+ const result = await iterator.next();
1213
+ if (result.done) return;
935
1214
  reportProgress();
936
- yield event;
1215
+ yield result.value;
937
1216
  }
938
1217
  })();
939
1218
  for await (const chunk of mapAnthropicStream(observed, {
940
1219
  originModel: params.model,
941
1220
  prefix
942
- }, options.support)) {
1221
+ }, options.support, usageReporter)) {
943
1222
  if (chunk.kind === "final") outcome = "ok";
944
- yield chunk;
1223
+ yield chunk.kind === "final" && replayData !== void 0 ? {
1224
+ ...chunk,
1225
+ replayData
1226
+ } : chunk;
945
1227
  }
946
1228
  } catch (error) {
947
- outcome = attemptSignal.aborted ? "cancelled" : "error";
1229
+ outcome = attemptSignal.aborted ? abortedOutcome() : "error";
948
1230
  throw error;
949
1231
  } finally {
1232
+ if (sdkIterator) {
1233
+ const iterator = sdkIterator;
1234
+ scope.retainCleanup(async () => {
1235
+ await iterator.return?.();
1236
+ }).catch(() => {});
1237
+ }
950
1238
  if (!firstResponseFinished) observe({
951
1239
  stage: "first-response",
952
1240
  phase: "end",
953
1241
  attempt: attemptCount,
954
- outcome
1242
+ outcome,
1243
+ ...timeout ? { failure: timeout } : {}
955
1244
  });
956
1245
  observe({
957
1246
  stage: "attempt",
958
1247
  phase: "end",
959
1248
  attempt: attemptCount,
960
- outcome
1249
+ outcome,
1250
+ ...timeout ? { failure: timeout } : {}
961
1251
  });
962
1252
  }
963
1253
  },
@@ -971,7 +1261,7 @@ function createAnthropicModelPort(options) {
971
1261
  }
972
1262
  });
973
1263
  }
974
- };
1264
+ });
975
1265
  }
976
1266
  //#endregion
977
1267
  //#region src/protocol/probe.ts
@@ -1010,12 +1300,8 @@ async function readBody(response, maxBytes) {
1010
1300
  }
1011
1301
  }
1012
1302
  function baseUrlOf(probe) {
1013
- const configured = probe.config.baseUrl;
1014
- return (typeof configured === "string" ? configured : "").replace(/\/+$/, "");
1303
+ return messagesBaseUrl(probe.config.baseUrl);
1015
1304
  }
1016
- /** Attaches the status so the runtime can tell an authentication failure from
1017
- * an endpoint that answered something else. The body is passed through as
1018
- * the message; whether any of it reaches a person is not this file's call. */
1019
1305
  async function refuse(response, maxBytes = 8388608) {
1020
1306
  const body = (await readBody(response, maxBytes)).text;
1021
1307
  throw Object.assign(new Error(body === "" ? response.statusText : body), { status: response.status });
@@ -1024,17 +1310,13 @@ async function get(probe, path, fetcher) {
1024
1310
  return fetcher(`${baseUrlOf(probe)}${path}`, {
1025
1311
  method: "GET",
1026
1312
  headers: {
1027
- "x-api-key": probe.secrets.apiKey ?? "",
1313
+ ...probe.options.allowUnauthenticated === true && !probe.secrets.apiKey ? {} : { "x-api-key": probe.secrets.apiKey ?? "" },
1028
1314
  "anthropic-version": VERSION
1029
1315
  },
1030
1316
  signal: probe.signal
1031
1317
  });
1032
1318
  }
1033
- /** Enough pages to carry a catalogue several times the size of the one
1034
- * Anthropic serves, while still ending if an endpoint keeps claiming
1035
- * `has_more` forever. */
1036
1319
  const MAX_PAGES = 20;
1037
- /** The effort levels this endpoint may list, in ascending order. */
1038
1320
  const EFFORT_LEVELS = [
1039
1321
  "minimal",
1040
1322
  "low",
@@ -1049,16 +1331,12 @@ function record(value) {
1049
1331
  function supported(value) {
1050
1332
  return record(value)?.supported === true;
1051
1333
  }
1052
- /** A positive count, or nothing: the endpoint answers `0` or `null` for a
1053
- * limit it does not know. */
1054
1334
  function count(value) {
1055
1335
  return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : void 0;
1056
1336
  }
1057
- /**
1058
- * One listed model as an offer, reading each field only where the entry
1059
- * carries it. `created_at` may be an epoch value when the release date is
1060
- * unknown, so anything before 2000 is read as absent.
1061
- */
1337
+ function strings(value, allowEmpty = false) {
1338
+ return Array.isArray(value) && value.every((one) => typeof one === "string") && (allowEmpty || value.length > 0) ? value : void 0;
1339
+ }
1062
1340
  function offerOf(row, id) {
1063
1341
  const capabilities = record(row.capabilities);
1064
1342
  const effort = record(capabilities?.effort);
@@ -1069,31 +1347,37 @@ function offerOf(row, id) {
1069
1347
  ...supported(capabilities.image_input) ? ["image"] : [],
1070
1348
  ...supported(capabilities.pdf_input) ? ["pdf"] : []
1071
1349
  ];
1350
+ const features = strings(row.supported_features, true);
1351
+ const sampling = strings(row.supported_sampling_parameters, true);
1352
+ const reasoning = typeof thinking?.supported === "boolean" ? thinking.supported : features?.includes("reasoning");
1353
+ const listedInput = typeof record(capabilities?.image_input)?.supported === "boolean" || typeof record(capabilities?.pdf_input)?.supported === "boolean" ? input : strings(row.input_modalities) ?? input;
1354
+ const output = strings(row.output_modalities);
1072
1355
  const released = typeof row.created_at === "string" && row.created_at >= "2000" ? row.created_at.slice(0, 10) : void 0;
1073
- const contextWindow = count(row.max_input_tokens);
1074
- const maxOutput = count(row.max_tokens);
1356
+ const inputLimit = count(row.max_input_tokens);
1357
+ const contextWindow = count(row.context_length);
1358
+ const maxOutput = count(row.max_tokens) ?? count(row.max_output_length);
1075
1359
  return {
1076
1360
  model: id,
1077
1361
  ...typeof row.display_name === "string" ? { name: row.display_name } : {},
1078
1362
  ...contextWindow === void 0 ? {} : { contextWindow },
1363
+ ...inputLimit === void 0 ? {} : { inputLimit },
1079
1364
  ...maxOutput === void 0 ? {} : { maxOutput },
1080
- ...typeof thinking?.supported === "boolean" ? { reasoning: thinking.supported } : {},
1365
+ ...reasoning === void 0 ? {} : { reasoning },
1366
+ ...features === void 0 ? {} : { toolCall: features.includes("tools") },
1367
+ ...sampling === void 0 ? {} : { temperature: sampling.includes("temperature") },
1081
1368
  ...efforts.length === 0 ? {} : { efforts },
1082
- ...input === void 0 ? {} : { input },
1369
+ ...listedInput === void 0 ? {} : { input: listedInput },
1370
+ ...output === void 0 ? {} : { output },
1083
1371
  ...released === void 0 ? {} : { releaseDate: released }
1084
1372
  };
1085
1373
  }
1086
1374
  const probeAnthropic = {
1087
- /** Every model the endpoint lists. `/v1/models` is paged — it answers with
1088
- * one page plus `has_more`/`last_id` — so this walks the pages with
1089
- * `after_id` until the endpoint says there are no more. A mirror that
1090
- * reports neither field answers in one page, as it always did. */
1091
1375
  async listModels(probe, fetcher = globalThis.fetch) {
1092
1376
  const offers = [];
1093
1377
  let afterId;
1094
1378
  let remaining = probe.maxResponseBytes ?? 8388608;
1095
1379
  for (let page = 0; page < MAX_PAGES; page += 1) {
1096
- const response = await get(probe, `/v1/models${afterId === void 0 ? "" : `?after_id=${encodeURIComponent(afterId)}`}`, fetcher);
1380
+ const response = await get(probe, `/models${afterId === void 0 ? "" : `?after_id=${encodeURIComponent(afterId)}`}`, fetcher);
1097
1381
  if (!response.ok) await refuse(response, probe.maxResponseBytes ?? 8388608);
1098
1382
  const received = await readBody(response, remaining);
1099
1383
  remaining -= received.bytes;
@@ -1108,23 +1392,14 @@ const probeAnthropic = {
1108
1392
  }
1109
1393
  return offers;
1110
1394
  },
1111
- /** Listing models is the cheapest request that needs the credential, so it
1112
- * is also the test: an endpoint that answers it has a working key, and one
1113
- * that refuses says why.
1114
- *
1115
- * An endpoint that serves `/v1/messages` alone answers the listing with
1116
- * 404. The test then sends `/v1/messages` an empty body, which no model
1117
- * runs: an unauthenticated refusal (401, 403) is a wrong key, any other
1118
- * client error means the key got through, and a second 404 is an address
1119
- * that serves neither. */
1120
1395
  async testConnection(probe, fetcher = globalThis.fetch) {
1121
- const listed = await get(probe, "/v1/models?limit=1", fetcher);
1396
+ const listed = await get(probe, "/models?limit=1", fetcher);
1122
1397
  if (listed.ok) return;
1123
1398
  if (listed.status !== 404) await refuse(listed);
1124
- const asked = await fetcher(`${baseUrlOf(probe)}/v1/messages`, {
1399
+ const asked = await fetcher(`${baseUrlOf(probe)}/messages`, {
1125
1400
  method: "POST",
1126
1401
  headers: {
1127
- "x-api-key": probe.secrets.apiKey ?? "",
1402
+ ...probe.options.allowUnauthenticated === true && !probe.secrets.apiKey ? {} : { "x-api-key": probe.secrets.apiKey ?? "" },
1128
1403
  "anthropic-version": VERSION,
1129
1404
  "content-type": "application/json"
1130
1405
  },
@@ -1136,21 +1411,72 @@ const probeAnthropic = {
1136
1411
  }
1137
1412
  };
1138
1413
  //#endregion
1414
+ //#region src/support.ts
1415
+ function inputLimit(offer) {
1416
+ return Number.isSafeInteger(offer.inputLimit) && Number(offer.inputLimit) > 0 ? offer.inputLimit : void 0;
1417
+ }
1418
+ function normalizeOffers(input) {
1419
+ return Object.fromEntries(input.offers.map((offer) => [offer.model, {
1420
+ id: offer.model,
1421
+ ...offer.name === void 0 ? {} : { name: offer.name },
1422
+ ...offer.chat === void 0 ? {} : { chat: offer.chat },
1423
+ ...offer.reasoning === void 0 && !offer.efforts?.length ? {} : { reasoning: offer.efforts?.length ? true : offer.reasoning },
1424
+ ...offer.efforts?.length ? { reasoning_options: [{
1425
+ type: "effort",
1426
+ values: [...offer.efforts]
1427
+ }] } : {},
1428
+ ...offer.temperature === void 0 ? {} : { temperature: offer.temperature },
1429
+ ...offer.toolCall === void 0 ? {} : { tool_call: offer.toolCall },
1430
+ ...offer.input === void 0 ? {} : { attachment: offer.input.some((one) => one !== "text") },
1431
+ ...offer.input === void 0 && offer.output === void 0 ? {} : { modalities: {
1432
+ ...offer.input === void 0 ? {} : { input: [...offer.input] },
1433
+ ...offer.output === void 0 ? {} : { output: [...offer.output] }
1434
+ } },
1435
+ ...!offer.contextWindow && inputLimit(offer) === void 0 && !offer.maxOutput ? {} : { limit: {
1436
+ ...offer.contextWindow && offer.contextWindow > 0 ? { context: offer.contextWindow } : {},
1437
+ ...inputLimit(offer) === void 0 ? {} : { input: inputLimit(offer) },
1438
+ ...offer.maxOutput && offer.maxOutput > 0 ? { output: offer.maxOutput } : {}
1439
+ } },
1440
+ ...offer.releaseDate === void 0 ? {} : { release_date: offer.releaseDate }
1441
+ }]));
1442
+ }
1443
+ function lazySupport(read) {
1444
+ return new Proxy({}, { get(_target, key) {
1445
+ if (key === "normalizeListing") return normalizeOffers;
1446
+ const service = read();
1447
+ if (!service) throw new Error("Chat model support is unavailable");
1448
+ const value = Reflect.get(service, key);
1449
+ return typeof value === "function" ? value.bind(service) : value;
1450
+ } });
1451
+ }
1452
+ //#endregion
1139
1453
  //#region src/protocol.ts
1140
- /** Supplier options interpreted by the Messages implementation. */
1141
1454
  const AnthropicProtocolOptions = z.strictObject({
1455
+ allowUnauthenticated: z.boolean().optional(),
1142
1456
  reasoningReplay: z.enum([
1143
1457
  "omit",
1144
1458
  "signed-thinking",
1145
1459
  "unsigned-thinking"
1146
1460
  ]).optional(),
1147
- budgetOnly: z.array(z.string()).optional()
1461
+ effortCache: z.boolean().optional(),
1462
+ cacheBreakpoints: z.boolean().optional(),
1463
+ thinkingMode: z.enum([
1464
+ "adaptive",
1465
+ "budget",
1466
+ "enabled",
1467
+ "omit"
1468
+ ]).optional(),
1469
+ thinkingEffort: z.boolean().optional(),
1470
+ thinkingBeta: z.boolean().optional(),
1471
+ thinkingSummary: z.boolean().optional(),
1472
+ budgetOnly: z.array(z.string()).optional(),
1473
+ effortCacheModels: z.record(z.string(), z.string().min(1)).optional()
1148
1474
  });
1149
- /** Registers request mapping, streaming, inspection and probes with host-owned resources. */
1150
1475
  function anthropicProtocolType(support, fetch) {
1151
1476
  return {
1152
1477
  type: "anthropic",
1153
- label: "Anthropic Messages",
1478
+ label: "Anthropic Messages API",
1479
+ logo: protocolLogo,
1154
1480
  fields: [{
1155
1481
  key: "baseUrl",
1156
1482
  kind: "url",
@@ -1160,19 +1486,37 @@ function anthropicProtocolType(support, fetch) {
1160
1486
  userConfigurable: true,
1161
1487
  optionsSchema: AnthropicProtocolOptions,
1162
1488
  facts,
1489
+ effortCacheCapability(input) {
1490
+ const options = AnthropicProtocolOptions.parse(input.options ?? {});
1491
+ if (options.effortCache === false) return {
1492
+ status: "unsupported",
1493
+ reason: "configuration-updates-unavailable"
1494
+ };
1495
+ const defaultEffort = options.effortCacheModels?.[input.model];
1496
+ if (input.params.thinking === false || input.params.budgetTokens !== void 0) return {
1497
+ status: "unsupported",
1498
+ reason: "adaptive-thinking-required"
1499
+ };
1500
+ return {
1501
+ status: "supported",
1502
+ ...defaultEffort ? { defaultEffort } : {}
1503
+ };
1504
+ },
1163
1505
  prepareParams: (input) => support.prepareParams(input, facts),
1164
- chat: {
1506
+ adapters: { chat: {
1165
1507
  fileKinds: ["image"],
1166
1508
  supportsModel: () => true,
1167
1509
  createPort(call) {
1168
1510
  const options = AnthropicProtocolOptions.parse(call.options);
1169
1511
  return createAnthropicModelPort({
1512
+ accountingDispatch: call.accountingDispatch,
1513
+ connectionFingerprint: call.connectionFingerprint,
1170
1514
  support,
1171
- fetch,
1515
+ fetch: withConnectionHeaders(fetch, call.headers),
1172
1516
  model: call.model,
1173
1517
  endpoint: call.providerId,
1174
1518
  apiKey: call.secrets.apiKey ?? "",
1175
- baseURL: String(call.config.baseUrl ?? ""),
1519
+ baseURL: messagesBaseUrl(call.config.baseUrl),
1176
1520
  ...options,
1177
1521
  catalogue: () => support.catalogue(call.providerId, call.model),
1178
1522
  media: (stored) => support.mediaContextOf({
@@ -1191,23 +1535,23 @@ function anthropicProtocolType(support, fetch) {
1191
1535
  })
1192
1536
  });
1193
1537
  }
1194
- },
1195
- normalizeListing: (input) => support.normalizeListing(input),
1196
- listModels: (probe) => probeAnthropic.listModels(probe, fetch),
1197
- testConnection: (probe) => probeAnthropic.testConnection(probe, fetch)
1538
+ } },
1539
+ normalizeListing: (input) => normalizeOffers(input),
1540
+ listModels: async (probe) => ({ offers: await probeAnthropic.listModels(probe, withConnectionHeaders(fetch, probe.headers)) }),
1541
+ testConnection: (probe) => probeAnthropic.testConnection(probe, withConnectionHeaders(fetch, probe.headers))
1198
1542
  };
1199
1543
  }
1200
1544
  //#endregion
1201
1545
  //#region src/index.ts
1202
- /** Protocol extensions contribute no tools. */
1203
1546
  const TOOL_NAMES = [];
1204
1547
  const plugin = {
1205
1548
  name: "@eum-agent/llm-protocol-anthropic",
1206
- requires: ["model-support", "network"],
1549
+ requires: ["network"],
1550
+ optionalServices: ["model-support"],
1207
1551
  apply(ctx) {
1208
- const support = ctx.services.get("model-support");
1552
+ const support = lazySupport(() => ctx.services.find("model-support"));
1209
1553
  const network = ctx.services.get("network");
1210
- ctx.models.registerProtocol(anthropicProtocolType(support, network.fetch));
1554
+ ctx.modelProtocols.register(anthropicProtocolType(support, network.fetch));
1211
1555
  }
1212
1556
  };
1213
1557
  //#endregion