@eum-agent/llm-protocol-anthropic 1.1.0 → 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 +558 -361
  2. package/package.json +4 -4
package/dist/index.js CHANGED
@@ -1,19 +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
5
19
  //#region src/logo.ts
6
- /** Official Anthropic mark reused from the supplier extension's vendored SVG. */
7
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";
8
21
  //#endregion
9
22
  //#region src/protocol/address.ts
10
- /** Preserves the configured API version and prefix before appending a resource path. */
11
23
  function messagesBaseUrl(baseUrl) {
12
24
  return typeof baseUrl === "string" ? baseUrl.replace(/\/+$/, "") : "";
13
25
  }
14
26
  //#endregion
15
27
  //#region src/protocol/facts.ts
16
- /** Parameter ranges and request limits for this provider wire. */
17
28
  const facts = {
18
29
  outputLimit: {
19
30
  support: "required",
@@ -32,22 +43,32 @@ const facts = {
32
43
  }
33
44
  };
34
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
35
66
  //#region src/protocol/errors.ts
36
- /**
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.
40
- */
41
- /** Timeouts, conflicts, rate limits and 5xx are worth a second attempt;
42
- * every other status is not — retrying a bad request or an authentication
43
- * failure only spends the backoff budget on a call that will never succeed. */
44
67
  function isRetryableStatus(status) {
45
68
  return status === 408 || status === 409 || status === 429 || status !== void 0 && status >= 500;
46
69
  }
47
- /** The provider's own `retry-after` header, in milliseconds — read for the
48
- * backoff delay only; the header value itself carries no credential. */
49
70
  function retryAfterMs(error) {
50
- if (!(error instanceof APIError)) return void 0;
71
+ if (!isAnthropicApiError(error)) return void 0;
51
72
  const header = error.headers?.get("retry-after");
52
73
  if (!header) return void 0;
53
74
  const seconds = Number(header);
@@ -55,11 +76,6 @@ function retryAfterMs(error) {
55
76
  const milliseconds = seconds * 1e3;
56
77
  return Number.isFinite(milliseconds) ? milliseconds : void 0;
57
78
  }
58
- /** Converts any exception the SDK call can throw into a `ModelCallError`.
59
- * Never reads `error.headers` into the result; the body goes to
60
- * `providerText` alone. */
61
- /** Error types an event stream reports mid-reply that a second attempt can
62
- * get past: the stream carries no status, only this. */
63
79
  const RETRYABLE_TYPES = /* @__PURE__ */ new Set([
64
80
  "overloaded_error",
65
81
  "api_error",
@@ -70,16 +86,20 @@ function streamErrorType(error) {
70
86
  const inner = body?.error?.type ?? body?.type;
71
87
  return typeof inner === "string" ? inner : void 0;
72
88
  }
73
- /** 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
+ }
74
94
  function toModelFailure(error, failures) {
75
95
  if (failures.owns(error)) return error;
76
- if (!(error instanceof APIError)) return failures.create({
96
+ if (!isAnthropicApiError(error)) return failures.create({
77
97
  code: "unknown",
78
98
  stage: "unknown",
79
99
  category: "unknown",
80
100
  source: "unknown",
81
101
  retryable: false
82
- });
102
+ }, { cause: error });
83
103
  const rawCode = streamErrorType(error) ?? error.type;
84
104
  const providerCode = typeof rawCode === "string" && (/* @__PURE__ */ new Set([
85
105
  "usage_not_included",
@@ -95,8 +115,24 @@ function toModelFailure(error, failures) {
95
115
  "bio_policy",
96
116
  "misalignment_policy_violation"
97
117
  ])).has(rawCode) ? rawCode : void 0;
98
- const connection = error instanceof APIConnectionError;
118
+ const connection = isAnthropicConnectionError(error);
99
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
+ });
100
136
  return failures.create({
101
137
  code: connection ? "stream-interrupted" : status === 413 ? "request-too-large" : status === void 0 ? "provider-error" : "http-error",
102
138
  stage: connection ? "transport" : status === 413 ? "request" : status === void 0 ? "stream" : "transport",
@@ -105,46 +141,93 @@ function toModelFailure(error, failures) {
105
141
  ...status === void 0 ? {} : { status },
106
142
  retryable: connection || isRetryableStatus(status) || status === void 0 && RETRYABLE_TYPES.has(streamErrorType(error) ?? ""),
107
143
  ...providerCode === void 0 ? {} : { providerCode }
144
+ }, {
145
+ cause: error,
146
+ details
108
147
  });
109
148
  }
110
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
111
222
  //#region src/protocol/request.ts
112
- /**
113
- * `ModelRequest` (kernel's vocabulary, provider-neutral) → Anthropic's
114
- * `MessageCreateParamsStreaming`. Everything this side must fix for the
115
- * outbound request lands here: `system` as the top-level parameter (not a
116
- * message), tool results kept as one message with several `tool_result`
117
- * blocks (the transcript shape, already Anthropic's own), and the thinking
118
- * configuration the port decided. Always streamed — 128K of output without
119
- * streaming risks an HTTP timeout.
120
- *
121
- * **Every request extends the previous one.** A reply's recorded volatile
122
- * notes are rendered just before it, as a text block at the end of the user
123
- * content that precedes it — exactly where the request that produced the
124
- * reply carried them — and the current step's notes go at the very end. So
125
- * the conversation a signature covers, and the prefix a cache entry keys on,
126
- * never change once sent.
127
- *
128
- * A signed `ThinkingPart` is echoed only when its endpoint, model and covered
129
- * non-thinking prefix match. Any mismatch drops the message's whole thinking
130
- * group while preserving its visible text and tool calls. A redacted block
131
- * goes back as the `redacted_thinking` it came as.
132
- */
133
223
  const SUMMARY_THINKING_HEADROOM = 8192;
134
224
  const DEFAULT_MAX_TOKENS = 16e3;
135
225
  const TOOL_ID = /^[a-zA-Z0-9_-]+$/;
136
- /**
137
- * The id Anthropic is sent for one tool call. A legal id goes as it is; any
138
- * other — another endpoint's `functions.name:0` — becomes its legal
139
- * characters plus a hash of the whole, decided by the id alone so a later
140
- * step adding ids never changes how an earlier one was sent.
141
- */
142
226
  function anthropicToolId(id) {
143
227
  if (TOOL_ID.test(id)) return id;
144
228
  const hash = createHash("sha256").update(id).digest("hex").slice(0, 12);
145
229
  return `${id.replace(/[^a-zA-Z0-9_-]/g, "_")}_${hash}`;
146
230
  }
147
- /** A planned file as blocks: the label and the image, or the line in its place. */
148
231
  function fileBlocks(planned, rendering) {
149
232
  const label = {
150
233
  type: "text",
@@ -198,28 +281,14 @@ function toContentBlockParams(part, at, context) {
198
281
  default: throw new Error(`unhandled content part type: ${String(part.type)}`);
199
282
  }
200
283
  }
201
- /**
202
- * Whether this endpoint can send one message's thinking group back.
203
- *
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
- * One incompatible member drops the whole group so no middle block is removed.
209
- *
210
- * Comparing endpoint ids is deliberately coarser than "same signer": two keys
211
- * against one vendor may share a signer, but replaying a block that cannot be
212
- * verified would reject the entire request.
213
- */
214
284
  function thinkingGroupIsSendable(message, options, prefix) {
215
285
  if (!message.content.some((part) => part.type === "text" && part.text !== "" || part.type === "tool-use")) return false;
216
286
  if (options.reasoningReplay === "omit" || message.outputTruncation?.incompleteThinking) return false;
217
287
  const thinking = message.content.filter((part) => part.type === "thinking");
218
288
  if (thinking.length === 0) return true;
219
289
  const model = options.model ?? "";
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));
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()));
221
291
  }
222
- /** A text block with nothing in it: Anthropic refuses one. */
223
292
  function isEmptyText(part) {
224
293
  return part.type === "text" && part.text === "";
225
294
  }
@@ -229,7 +298,6 @@ function blocksOf(message, index, sendThinking, context) {
229
298
  part: partIndex
230
299
  }, context));
231
300
  }
232
- /** The one text block a set of notes renders as, or nothing. */
233
301
  function noteBlock(notes) {
234
302
  const text = (notes ?? []).map((note) => note.text).join("\n\n");
235
303
  return text === "" ? [] : [{
@@ -253,11 +321,6 @@ function appendUser(messages, blocks) {
253
321
  content: [...content, ...blocks]
254
322
  };
255
323
  }
256
- /**
257
- * Renders messages in Anthropic's shape, each reply preceded by the notes
258
- * its request appended, then `trailing` at the end. `sendThinking` decides,
259
- * per message index, whether its thinking group goes out.
260
- */
261
324
  function render(messages, trailing, sendThinking, context) {
262
325
  const out = [];
263
326
  const updates = new Map(context.effortUpdates?.map((update) => [update.beforeUserMessageId, update.effort]));
@@ -284,11 +347,9 @@ function toToolParam(tool) {
284
347
  return {
285
348
  name: tool.name,
286
349
  description: tool.description,
287
- input_schema: tool.inputSchema
350
+ input_schema: anthropicInputSchema(tool.inputSchema)
288
351
  };
289
352
  }
290
- /** A copy without cache marks: where a breakpoint sits says nothing about what
291
- * the provider signed, so it must not change the fingerprint. */
292
353
  function unmarked(value) {
293
354
  return JSON.parse(JSON.stringify(value, (key, inner) => key === "cache_control" ? void 0 : inner));
294
355
  }
@@ -308,20 +369,21 @@ function prefixOf(system, tools, messages, support) {
308
369
  messages
309
370
  }));
310
371
  }
311
- /**
312
- * Computes the non-thinking prefix covered by a historical assistant
313
- * signature: everything before that message, its own recorded notes included
314
- * — they ended the request it answered. `messageIndex` names the message.
315
- */
316
- function anthropicPrefixBefore(request, messageIndex, media, support, effortUpdates) {
317
- const before = request.messages.slice(0, messageIndex);
318
- const notes = request.messages[messageIndex]?.volatile;
319
- return prefixOf(systemOf(request), toolsOf(request), render(before, notes, () => false, {
320
- ...fingerprintContext(request, media, support),
321
- effortUpdates
322
- }), 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
+ };
323
386
  }
324
- /** The send plan, from the options' media context or the permissive default. */
325
387
  function planOf(request, media, support) {
326
388
  return support.planMedia(request, media ?? {
327
389
  acceptsImages: true,
@@ -337,27 +399,39 @@ function fingerprintContext(request, media, support) {
337
399
  rendering: "fingerprint"
338
400
  };
339
401
  }
340
- /**
341
- * Computes the prefix a new reply is signed under: everything the request
342
- * carried, its notes included, rendered the way `anthropicPrefixBefore`
343
- * renders it on the next step and without cache marks.
344
- */
345
402
  function anthropicRequestPrefix(request, media, support, effortUpdates) {
346
403
  return prefixOf(systemOf(request), toolsOf(request), render(request.messages, request.volatile, () => false, {
347
404
  ...fingerprintContext(request, media, support),
348
405
  effortUpdates
349
406
  }), support);
350
407
  }
351
- /** Counts provider-retained thinking state that is actually replayed. */
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
+ };
425
+ }
352
426
  function anthropicHiddenInputTokens(request, options) {
353
427
  if (options.reasoningReplay === "unsigned-thinking") return 0;
428
+ const prefix = prefixReader(request, options.media, options.support, options.effortUpdates);
354
429
  return request.messages.reduce((total, message, index) => {
355
- if (!thinkingGroupIsSendable(message, options, anthropicPrefixBefore(request, index, options.media, options.support, options.effortUpdates))) return total;
430
+ if (!thinkingGroupIsSendable(message, options, () => prefix(index))) return total;
356
431
  return total + Math.max(0, ...message.content.map((part) => part.type === "thinking" ? part.outputTokens ?? 0 : 0));
357
432
  }, 0);
358
433
  }
359
434
  const EPHEMERAL = { type: "ephemeral" };
360
- /** Marks the last markable block of one message. */
361
435
  function markLast(message) {
362
436
  if (message.role === "system") return message;
363
437
  if (typeof message.content === "string") return message;
@@ -376,12 +450,6 @@ function markLast(message) {
376
450
  }
377
451
  return message;
378
452
  }
379
- /**
380
- * Two conversation breakpoints: the end of this request, which the next step
381
- * repeats, and the end of the previous step's request — the user content
382
- * just before the last reply — whose cache entry this step reads exactly,
383
- * however many blocks the step added since.
384
- */
385
453
  function withConversationBreakpoints(messages) {
386
454
  const out = [...messages];
387
455
  const lastIndex = out.length - 1;
@@ -391,7 +459,7 @@ function withConversationBreakpoints(messages) {
391
459
  if (previous >= 0 && previous !== lastIndex && out[previous]?.role === "user") out[previous] = markLast(out[previous]);
392
460
  return out;
393
461
  }
394
- function toAnthropicRequest(request, options) {
462
+ function toAnthropicRequest(request, options, mediaPlan = planOf(request, options.media, options.support)) {
395
463
  const summary = request.purpose === "summary";
396
464
  if (summary && (!Number.isInteger(request.summaryMaxTokens) || Number(request.summaryMaxTokens) <= 0)) throw new Error("summaryMaxTokens must be a positive integer for a summary request");
397
465
  const ordinaryMaxTokens = options.maxTokens ?? DEFAULT_MAX_TOKENS;
@@ -406,8 +474,9 @@ function toAnthropicRequest(request, options) {
406
474
  text
407
475
  });
408
476
  const tools = toolsOf(request);
409
- const messages = render(request.messages, request.volatile, (message, index) => thinkingGroupIsSendable(message, options, anthropicPrefixBefore(request, index, options.media, options.support, options.effortUpdates)), {
410
- 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,
411
480
  rendering: "wire",
412
481
  unsignedThinking: options.reasoningReplay === "unsigned-thinking",
413
482
  effortUpdates: options.effortUpdates
@@ -423,23 +492,15 @@ function toAnthropicRequest(request, options) {
423
492
  ...system === void 0 ? {} : { system },
424
493
  ...tools === void 0 ? {} : { tools },
425
494
  ...request.toolChoice === "none" && tools !== void 0 ? { tool_choice: { type: "none" } } : {},
426
- ...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" } } : {}
427
498
  };
428
499
  }
429
500
  //#endregion
430
501
  //#region src/protocol/sse-response.ts
431
502
  const MAX_FRAME_BYTES = 8388608;
432
503
  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
504
  function frameSseResponse(response, signal) {
444
505
  if (!response.ok || response.body === null) return response;
445
506
  const reader = response.body.getReader();
@@ -583,13 +644,9 @@ function toFinishReason(stopReason, support) {
583
644
  category: "protocol",
584
645
  source: "protocol",
585
646
  retryable: false
586
- });
647
+ }, stopReason === null ? void 0 : { details: { finishReason: String(stopReason) } });
587
648
  }
588
649
  }
589
- /** The accumulated `input_json_delta` text as JSON, or `undefined` when it
590
- * will not parse — which is what a tool-use block cut off at `max_tokens`
591
- * looks like. `JSON.parse` never produces `undefined` itself, so it is free
592
- * to stand for "no usable input here". */
593
650
  function parseToolInput(json) {
594
651
  if (json.length === 0) return {};
595
652
  try {
@@ -598,16 +655,18 @@ function parseToolInput(json) {
598
655
  return;
599
656
  }
600
657
  }
601
- /**
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.
605
- */
606
- 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) {
607
662
  const blocks = /* @__PURE__ */ new Map();
608
663
  const finalContent = [];
609
664
  const incompleteToolCalls = [];
665
+ const invalidInputs = [];
610
666
  let incompleteThinking = false;
667
+ let reportedInput;
668
+ let reportedOutput;
669
+ let usageSequence = 0;
611
670
  let ordinaryInputTokens = 0;
612
671
  let inputTokens = 0;
613
672
  let outputTokens = 0;
@@ -615,120 +674,135 @@ async function* mapAnthropicStream(events, attribution, support) {
615
674
  let stopped = false;
616
675
  let stopReason = null;
617
676
  let refusalCategory;
618
- for await (const event of events) switch (event.type) {
619
- case "message_start": {
620
- const usage = event.message.usage;
621
- ordinaryInputTokens = usage.input_tokens;
622
- inputTokens = ordinaryInputTokens + (usage.cache_read_input_tokens ?? 0) + (usage.cache_creation_input_tokens ?? 0);
623
- outputTokens = event.message.usage.output_tokens;
624
- cache = {
625
- ...typeof usage.cache_read_input_tokens === "number" ? { cacheReadTokens: usage.cache_read_input_tokens } : {},
626
- ...typeof usage.cache_creation_input_tokens === "number" ? { cacheWriteTokens: usage.cache_creation_input_tokens } : {}
627
- };
628
- break;
629
- }
630
- case "content_block_start": {
631
- const block = event.content_block;
632
- if (block.type === "text") blocks.set(event.index, {
633
- kind: "text",
634
- text: block.text
635
- });
636
- else if (block.type === "tool_use") {
637
- blocks.set(event.index, {
638
- kind: "tool-use",
639
- id: block.id,
640
- name: block.name,
641
- json: ""
642
- });
643
- yield {
644
- kind: "tool-call-delta",
645
- id: block.id,
646
- name: block.name,
647
- inputDelta: ""
648
- };
649
- } else if (block.type === "thinking") blocks.set(event.index, {
650
- kind: "thinking",
651
- text: ""
652
- });
653
- else if (block.type === "redacted_thinking") blocks.set(event.index, {
654
- kind: "redacted",
655
- data: block.data
656
- });
657
- else blocks.set(event.index, { kind: "skipped" });
658
- break;
659
- }
660
- case "content_block_delta": {
661
- const block = blocks.get(event.index);
662
- const delta = event.delta;
663
- if (delta.type === "text_delta") {
664
- if (block?.kind === "text") block.text += delta.text;
665
- yield {
666
- kind: "text-delta",
667
- text: delta.text
668
- };
669
- } else if (delta.type === "thinking_delta") {
670
- if (block?.kind === "thinking") block.text += delta.thinking;
671
- yield {
672
- kind: "thinking-delta",
673
- text: delta.thinking
674
- };
675
- } else if (delta.type === "signature_delta") {
676
- if (block?.kind === "thinking") block.signature = delta.signature;
677
- } else if (delta.type === "input_json_delta" && block?.kind === "tool-use") {
678
- block.json += delta.partial_json;
679
- yield {
680
- kind: "tool-call-delta",
681
- id: block.id,
682
- 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 } : {}
683
687
  };
688
+ break;
684
689
  }
685
- break;
686
- }
687
- case "content_block_stop": {
688
- const block = blocks.get(event.index);
689
- if (block?.kind === "text") {
690
- if (block.text !== "") finalContent.push({
691
- 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",
692
694
  text: block.text
693
695
  });
694
- } else if (block?.kind === "redacted") finalContent.push({
695
- type: "thinking",
696
- text: "",
697
- signature: block.data,
698
- redacted: true
699
- });
700
- else if (block?.kind === "tool-use") {
701
- const input = parseToolInput(block.json);
702
- if (input === void 0) incompleteToolCalls.push({
703
- id: block.id,
704
- 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: ""
705
712
  });
706
- else finalContent.push({
707
- type: "tool-use",
708
- id: block.id,
709
- name: block.name,
710
- input
713
+ else if (block.type === "redacted_thinking") blocks.set(event.index, {
714
+ kind: "redacted",
715
+ data: block.data
711
716
  });
712
- } else if (block?.kind === "thinking") finalContent.push({
713
- type: "thinking",
714
- text: block.text,
715
- ...block.signature === void 0 ? {} : { signature: block.signature }
716
- });
717
- blocks.delete(event.index);
718
- break;
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;
719
794
  }
720
- case "message_delta": {
721
- stopReason = event.delta.stop_reason ?? stopReason;
722
- if (event.delta.stop_details?.type === "refusal") refusalCategory = event.delta.stop_details.category ?? "unspecified";
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;
729
- break;
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
804
+ });
730
805
  }
731
- case "message_stop": stopped = true;
732
806
  }
733
807
  if (!stopped) throw support.interruptedFailure();
734
808
  const finishReason = toFinishReason(stopReason, support);
@@ -748,15 +822,19 @@ async function* mapAnthropicStream(events, attribution, support) {
748
822
  name: block.name
749
823
  });
750
824
  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({
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({
760
838
  code: "response-empty",
761
839
  stage: "response-validation",
762
840
  category: "protocol",
@@ -777,10 +855,12 @@ async function* mapAnthropicStream(events, attribution, support) {
777
855
  incompleteToolCalls,
778
856
  ...incompleteThinking ? { incompleteThinking: true } : {}
779
857
  } } : {},
858
+ ...droppedToolCalls.length > 0 ? { droppedToolCalls } : {},
780
859
  usage: {
781
- inputTokens,
782
- outputTokens,
783
- ...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 }
784
864
  },
785
865
  ...refusalCategory !== void 0 ? { refusalCategory } : {},
786
866
  message: {
@@ -791,34 +871,10 @@ async function* mapAnthropicStream(events, attribution, support) {
791
871
  }
792
872
  //#endregion
793
873
  //#region src/protocol/port.ts
794
- /**
795
- * Wires request-building (request.ts), stream-mapping (stream.ts) and the
796
- * injected host retry loop into the `ModelPort` the
797
- * kernel's call-model slot dispatches to. Rate limits, overload, server
798
- * errors, dropped connections and stalls are retried with a
799
- * `retry-after`-honouring backoff; a retry after output first retracts what
800
- * streamed. Everything else, and a retryable failure once the budget is
801
- * spent, becomes the error the driver turns into a failed outcome.
802
- */
803
- /** Lets a budget-thinking model think between tool calls. */
804
874
  const INTERLEAVED_THINKING_BETA = "interleaved-thinking-2025-05-14";
805
- /** Enables effort-only system messages on declared supporting models. */
806
875
  const MID_CONVERSATION_EFFORT_BETA = "mid-conversation-output-config-2026-07-01";
807
- /** The budget a budget-thinking model gets when a person set none. */
808
876
  const DEFAULT_BUDGET = 16e3;
809
877
  const BUDGET_FLOOR = 1024;
810
- /**
811
- * The neutral plan in Anthropic's own spelling.
812
- *
813
- * Thinking on is `adaptive` with a readable summary — current models stream
814
- * empty thinking without `display: 'summarized'` — and the effort; a model
815
- * whose thinking is a token budget gets `enabled` with the stored budget or a
816
- * default one under `max_tokens`, or no thinking at all when `max_tokens`
817
- * leaves no room for the smallest budget. Thinking off is `disabled`. While
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.
821
- */
822
878
  function anthropicOptions(plan, model, budgetOnly = [], policy = {}) {
823
879
  const on = plan.thinking === true;
824
880
  const maxTokens = plan.maxTokens;
@@ -845,9 +901,9 @@ function anthropicOptions(plan, model, budgetOnly = [], policy = {}) {
845
901
  ...thinking?.type === "enabled" && policy.thinkingBeta !== false ? { betas: [INTERLEAVED_THINKING_BETA] } : {}
846
902
  };
847
903
  }
848
- /** Creates an Anthropic port with synchronous request inspection and safe stream retries. */
849
904
  function createAnthropicModelPort(options) {
850
- function clientForAttempt(reportProgress) {
905
+ async function clientForAttempt(reportProgress, dispatched) {
906
+ const { default: Anthropic } = await loadAnthropicSdk();
851
907
  if (options.client) return options.client;
852
908
  const client = new Anthropic({
853
909
  apiKey: options.allowUnauthenticated && !options.apiKey ? "not-used" : options.apiKey ?? "",
@@ -858,7 +914,11 @@ function createAnthropicModelPort(options) {
858
914
  Authorization: null
859
915
  }
860
916
  } : {},
861
- fetch: async (...args) => frameSseResponse(options.support.observeResponseProgress(await (options.fetch ?? globalThis.fetch)(...args), reportProgress), args[1]?.signal),
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
+ },
862
922
  baseURL: options.baseURL ?? "",
863
923
  maxRetries: 0
864
924
  });
@@ -868,8 +928,8 @@ function createAnthropicModelPort(options) {
868
928
  stream: true
869
929
  }) } };
870
930
  }
871
- function build(request, inspection = false) {
872
- const capacity = options.catalogue?.()?.limit;
931
+ function build(request) {
932
+ const capacity = options.support.freezePayload(options.catalogue?.()?.limit ?? {});
873
933
  const plan = options.params === void 0 ? void 0 : anthropicOptions(options.params(request.params ?? {}), options.model ?? "", options.budgetOnly, options);
874
934
  const { media: mediaOf, ...rest } = options;
875
935
  const media = mediaOf?.(request.params ?? {});
@@ -888,7 +948,7 @@ function createAnthropicModelPort(options) {
888
948
  const declaredDefault = options.effortCacheModels?.[options.model ?? ""];
889
949
  const replay = options.support.planEffortCache({
890
950
  request,
891
- inspection,
951
+ inspection: false,
892
952
  effort: requestOptions.effort,
893
953
  capability: options.effortCache === false ? {
894
954
  status: "unsupported",
@@ -918,59 +978,162 @@ function createAnthropicModelPort(options) {
918
978
  effortUpdates: replay.updates
919
979
  };
920
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");
921
1032
  return {
922
- params: toAnthropicRequest(request, requestOptions),
923
- requestOptions,
1033
+ params,
1034
+ replaySelections,
1035
+ fields,
1036
+ request: {
1037
+ ...request,
1038
+ params: options.support.freezePayload(request.params ?? {})
1039
+ },
924
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
+ }),
925
1060
  replayData: replay.replayData,
1061
+ effectiveEffort: replay.effectiveEffort,
926
1062
  headers: betas === void 0 || betas.length === 0 ? void 0 : { "anthropic-beta": betas.join(",") }
927
1063
  };
928
1064
  }
929
- return {
930
- inspect(request) {
931
- const { params, requestOptions, capacity } = build(request, true);
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;
932
1093
  const outputReserve = Number.isInteger(params.max_tokens) && params.max_tokens > 0 ? params.max_tokens : capacity?.output ?? 0;
933
- 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({
934
1102
  body: params,
935
- textTokens: options.support.measureText(options.support.requestText("messages", params)),
936
- tokenizer: "o200k_base-protocol-text-v2",
1103
+ textTokens: 0,
1104
+ textBytes: Buffer.byteLength(text),
1105
+ tokenizer: "utf8-bytes-quarter-v1",
937
1106
  request,
938
1107
  capacity,
939
1108
  outputReserve,
940
1109
  outputReserveSource: Number.isInteger(params.max_tokens) && params.max_tokens > 0 ? "enforced" : "capacity",
941
- hiddenInputTokens: anthropicHiddenInputTokens(request, requestOptions),
942
- mediaTokens: options.support.planMedia(request, requestOptions.media ?? {
943
- acceptsImages: true,
944
- limits: void 0
945
- }).tokens,
946
- fingerprint: {
947
- rendering: "anthropic-messages-v3",
948
- baseURL: options.baseURL,
949
- endpoint: options.endpoint ?? options.baseURL,
950
- model: params.model,
951
- purpose: request.purpose,
952
- contextWindow: request.params?.contextWindow,
953
- capacity,
954
- settings: {
955
- effort: requestOptions.effort,
956
- thinking: requestOptions.thinking,
957
- temperature: requestOptions.temperature,
958
- maxTokens: params.max_tokens,
959
- extra: request.purpose === "summary" ? void 0 : requestOptions.extra
960
- }
961
- }
1110
+ hiddenInputTokens,
1111
+ mediaTokens,
1112
+ fingerprint
962
1113
  });
1114
+ const textTokens = await options.support.measureText(text, signal);
1115
+ signal.throwIfAborted();
1116
+ return {
1117
+ ...inspection,
1118
+ inputTokens: inspection.inputTokens + textTokens
1119
+ };
963
1120
  },
964
- stream(request, signal, observer) {
1121
+ stream(payload, signal, observer, scope) {
965
1122
  signal.throwIfAborted();
966
- const { params, headers, requestOptions, replayData } = build(request);
967
- const prefix = anthropicRequestPrefix(request, requestOptions.media, options.support, requestOptions.effortUpdates);
1123
+ const { params, headers, prefix, replayData, effectiveEffort } = payload;
968
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
+ },
969
1132
  signal,
970
1133
  ...options.maxRetries === void 0 ? {} : { maxRetries: options.maxRetries },
971
1134
  ...options.sleep === void 0 ? {} : { sleep: options.sleep },
972
1135
  ...options.idleMs === void 0 ? {} : { idleMs: options.idleMs },
973
- async *attempt(attemptSignal, reportProgress, attempt) {
1136
+ async *attempt(attemptSignal, reportProgress, attempt, usageReporter) {
974
1137
  const observe = (event) => {
975
1138
  try {
976
1139
  observer?.observe?.(event);
@@ -978,7 +1141,41 @@ function createAnthropicModelPort(options) {
978
1141
  };
979
1142
  const attemptCount = attempt + 1;
980
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
+ };
981
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
+ };
982
1179
  observe({
983
1180
  stage: "attempt",
984
1181
  phase: "start",
@@ -989,12 +1186,18 @@ function createAnthropicModelPort(options) {
989
1186
  phase: "start",
990
1187
  attempt: attemptCount
991
1188
  });
1189
+ let sdkIterator;
992
1190
  try {
1191
+ const client = await clientForAttempt(reportProgress, markDispatched);
993
1192
  attemptSignal.throwIfAborted();
994
- const events = await clientForAttempt(reportProgress).messages.create(params, {
1193
+ const pending = client.messages.create(params, {
995
1194
  signal: attemptSignal,
996
1195
  ...headers === void 0 ? {} : { headers }
997
1196
  });
1197
+ if (options.client) markDispatched();
1198
+ const events = await pending;
1199
+ if (options.client) reportProgress();
1200
+ sdkIterator = events[Symbol.asyncIterator]();
998
1201
  firstResponseFinished = true;
999
1202
  observe({
1000
1203
  stage: "first-response",
@@ -1003,20 +1206,19 @@ function createAnthropicModelPort(options) {
1003
1206
  outcome: "ok"
1004
1207
  });
1005
1208
  attemptSignal.throwIfAborted();
1006
- try {
1007
- observer?.dispatched({ attempt });
1008
- } catch {}
1009
- attemptSignal.throwIfAborted();
1209
+ const iterator = sdkIterator;
1010
1210
  const observed = (async function* () {
1011
- for await (const event of events) {
1211
+ for (;;) {
1212
+ const result = await iterator.next();
1213
+ if (result.done) return;
1012
1214
  reportProgress();
1013
- yield event;
1215
+ yield result.value;
1014
1216
  }
1015
1217
  })();
1016
1218
  for await (const chunk of mapAnthropicStream(observed, {
1017
1219
  originModel: params.model,
1018
1220
  prefix
1019
- }, options.support)) {
1221
+ }, options.support, usageReporter)) {
1020
1222
  if (chunk.kind === "final") outcome = "ok";
1021
1223
  yield chunk.kind === "final" && replayData !== void 0 ? {
1022
1224
  ...chunk,
@@ -1024,20 +1226,28 @@ function createAnthropicModelPort(options) {
1024
1226
  } : chunk;
1025
1227
  }
1026
1228
  } catch (error) {
1027
- outcome = attemptSignal.aborted ? "cancelled" : "error";
1229
+ outcome = attemptSignal.aborted ? abortedOutcome() : "error";
1028
1230
  throw error;
1029
1231
  } finally {
1232
+ if (sdkIterator) {
1233
+ const iterator = sdkIterator;
1234
+ scope.retainCleanup(async () => {
1235
+ await iterator.return?.();
1236
+ }).catch(() => {});
1237
+ }
1030
1238
  if (!firstResponseFinished) observe({
1031
1239
  stage: "first-response",
1032
1240
  phase: "end",
1033
1241
  attempt: attemptCount,
1034
- outcome
1242
+ outcome,
1243
+ ...timeout ? { failure: timeout } : {}
1035
1244
  });
1036
1245
  observe({
1037
1246
  stage: "attempt",
1038
1247
  phase: "end",
1039
1248
  attempt: attemptCount,
1040
- outcome
1249
+ outcome,
1250
+ ...timeout ? { failure: timeout } : {}
1041
1251
  });
1042
1252
  }
1043
1253
  },
@@ -1051,7 +1261,7 @@ function createAnthropicModelPort(options) {
1051
1261
  }
1052
1262
  });
1053
1263
  }
1054
- };
1264
+ });
1055
1265
  }
1056
1266
  //#endregion
1057
1267
  //#region src/protocol/probe.ts
@@ -1092,9 +1302,6 @@ async function readBody(response, maxBytes) {
1092
1302
  function baseUrlOf(probe) {
1093
1303
  return messagesBaseUrl(probe.config.baseUrl);
1094
1304
  }
1095
- /** Attaches the status so the runtime can tell an authentication failure from
1096
- * an endpoint that answered something else. The body is passed through as
1097
- * the message; whether any of it reaches a person is not this file's call. */
1098
1305
  async function refuse(response, maxBytes = 8388608) {
1099
1306
  const body = (await readBody(response, maxBytes)).text;
1100
1307
  throw Object.assign(new Error(body === "" ? response.statusText : body), { status: response.status });
@@ -1109,11 +1316,7 @@ async function get(probe, path, fetcher) {
1109
1316
  signal: probe.signal
1110
1317
  });
1111
1318
  }
1112
- /** Enough pages to carry a catalogue several times the size of the one
1113
- * Anthropic serves, while still ending if an endpoint keeps claiming
1114
- * `has_more` forever. */
1115
1319
  const MAX_PAGES = 20;
1116
- /** The effort levels this endpoint may list, in ascending order. */
1117
1320
  const EFFORT_LEVELS = [
1118
1321
  "minimal",
1119
1322
  "low",
@@ -1128,16 +1331,12 @@ function record(value) {
1128
1331
  function supported(value) {
1129
1332
  return record(value)?.supported === true;
1130
1333
  }
1131
- /** A positive count, or nothing: the endpoint answers `0` or `null` for a
1132
- * limit it does not know. */
1133
1334
  function count(value) {
1134
1335
  return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : void 0;
1135
1336
  }
1136
- /**
1137
- * One listed model as an offer, reading each field only where the entry
1138
- * carries it. `created_at` may be an epoch value when the release date is
1139
- * unknown, so anything before 2000 is read as absent.
1140
- */
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
+ }
1141
1340
  function offerOf(row, id) {
1142
1341
  const capabilities = record(row.capabilities);
1143
1342
  const effort = record(capabilities?.effort);
@@ -1148,25 +1347,31 @@ function offerOf(row, id) {
1148
1347
  ...supported(capabilities.image_input) ? ["image"] : [],
1149
1348
  ...supported(capabilities.pdf_input) ? ["pdf"] : []
1150
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);
1151
1355
  const released = typeof row.created_at === "string" && row.created_at >= "2000" ? row.created_at.slice(0, 10) : void 0;
1152
- const contextWindow = count(row.max_input_tokens);
1153
- 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);
1154
1359
  return {
1155
1360
  model: id,
1156
1361
  ...typeof row.display_name === "string" ? { name: row.display_name } : {},
1157
1362
  ...contextWindow === void 0 ? {} : { contextWindow },
1363
+ ...inputLimit === void 0 ? {} : { inputLimit },
1158
1364
  ...maxOutput === void 0 ? {} : { maxOutput },
1159
- ...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") },
1160
1368
  ...efforts.length === 0 ? {} : { efforts },
1161
- ...input === void 0 ? {} : { input },
1369
+ ...listedInput === void 0 ? {} : { input: listedInput },
1370
+ ...output === void 0 ? {} : { output },
1162
1371
  ...released === void 0 ? {} : { releaseDate: released }
1163
1372
  };
1164
1373
  }
1165
1374
  const probeAnthropic = {
1166
- /** Every model the endpoint lists. `/models` is paged — it answers with
1167
- * one page plus `has_more`/`last_id` — so this walks the pages with
1168
- * `after_id` until the endpoint says there are no more. A mirror that
1169
- * reports neither field answers in one page, as it always did. */
1170
1375
  async listModels(probe, fetcher = globalThis.fetch) {
1171
1376
  const offers = [];
1172
1377
  let afterId;
@@ -1187,15 +1392,6 @@ const probeAnthropic = {
1187
1392
  }
1188
1393
  return offers;
1189
1394
  },
1190
- /** Listing models is the cheapest request that needs the credential, so it
1191
- * is also the test: an endpoint that answers it has a working key, and one
1192
- * that refuses says why.
1193
- *
1194
- * An endpoint that serves `/messages` alone answers the listing with
1195
- * 404. The test then sends `/messages` an empty body, which no model
1196
- * runs: an unauthenticated refusal (401, 403) is a wrong key, any other
1197
- * client error means the key got through, and a second 404 is an address
1198
- * that serves neither. */
1199
1395
  async testConnection(probe, fetcher = globalThis.fetch) {
1200
1396
  const listed = await get(probe, "/models?limit=1", fetcher);
1201
1397
  if (listed.ok) return;
@@ -1216,11 +1412,14 @@ const probeAnthropic = {
1216
1412
  };
1217
1413
  //#endregion
1218
1414
  //#region src/support.ts
1219
- /** Normalizes official facts without requiring an installed Chat capability. */
1415
+ function inputLimit(offer) {
1416
+ return Number.isSafeInteger(offer.inputLimit) && Number(offer.inputLimit) > 0 ? offer.inputLimit : void 0;
1417
+ }
1220
1418
  function normalizeOffers(input) {
1221
1419
  return Object.fromEntries(input.offers.map((offer) => [offer.model, {
1222
1420
  id: offer.model,
1223
1421
  ...offer.name === void 0 ? {} : { name: offer.name },
1422
+ ...offer.chat === void 0 ? {} : { chat: offer.chat },
1224
1423
  ...offer.reasoning === void 0 && !offer.efforts?.length ? {} : { reasoning: offer.efforts?.length ? true : offer.reasoning },
1225
1424
  ...offer.efforts?.length ? { reasoning_options: [{
1226
1425
  type: "effort",
@@ -1233,14 +1432,14 @@ function normalizeOffers(input) {
1233
1432
  ...offer.input === void 0 ? {} : { input: [...offer.input] },
1234
1433
  ...offer.output === void 0 ? {} : { output: [...offer.output] }
1235
1434
  } },
1236
- ...!offer.contextWindow && !offer.maxOutput ? {} : { limit: {
1435
+ ...!offer.contextWindow && inputLimit(offer) === void 0 && !offer.maxOutput ? {} : { limit: {
1237
1436
  ...offer.contextWindow && offer.contextWindow > 0 ? { context: offer.contextWindow } : {},
1437
+ ...inputLimit(offer) === void 0 ? {} : { input: inputLimit(offer) },
1238
1438
  ...offer.maxOutput && offer.maxOutput > 0 ? { output: offer.maxOutput } : {}
1239
1439
  } },
1240
1440
  ...offer.releaseDate === void 0 ? {} : { release_date: offer.releaseDate }
1241
1441
  }]));
1242
1442
  }
1243
- /** The owner-qualified accessor is read per operation; withdrawal never exposes an old service. */
1244
1443
  function lazySupport(read) {
1245
1444
  return new Proxy({}, { get(_target, key) {
1246
1445
  if (key === "normalizeListing") return normalizeOffers;
@@ -1252,7 +1451,6 @@ function lazySupport(read) {
1252
1451
  }
1253
1452
  //#endregion
1254
1453
  //#region src/protocol.ts
1255
- /** Supplier options interpreted by the Messages implementation. */
1256
1454
  const AnthropicProtocolOptions = z.strictObject({
1257
1455
  allowUnauthenticated: z.boolean().optional(),
1258
1456
  reasoningReplay: z.enum([
@@ -1274,7 +1472,6 @@ const AnthropicProtocolOptions = z.strictObject({
1274
1472
  budgetOnly: z.array(z.string()).optional(),
1275
1473
  effortCacheModels: z.record(z.string(), z.string().min(1)).optional()
1276
1474
  });
1277
- /** Registers request mapping, streaming, inspection and probes with host-owned resources. */
1278
1475
  function anthropicProtocolType(support, fetch) {
1279
1476
  return {
1280
1477
  type: "anthropic",
@@ -1312,9 +1509,10 @@ function anthropicProtocolType(support, fetch) {
1312
1509
  createPort(call) {
1313
1510
  const options = AnthropicProtocolOptions.parse(call.options);
1314
1511
  return createAnthropicModelPort({
1512
+ accountingDispatch: call.accountingDispatch,
1315
1513
  connectionFingerprint: call.connectionFingerprint,
1316
1514
  support,
1317
- fetch,
1515
+ fetch: withConnectionHeaders(fetch, call.headers),
1318
1516
  model: call.model,
1319
1517
  endpoint: call.providerId,
1320
1518
  apiKey: call.secrets.apiKey ?? "",
@@ -1339,13 +1537,12 @@ function anthropicProtocolType(support, fetch) {
1339
1537
  }
1340
1538
  } },
1341
1539
  normalizeListing: (input) => normalizeOffers(input),
1342
- listModels: async (probe) => ({ offers: await probeAnthropic.listModels(probe, fetch) }),
1343
- testConnection: (probe) => probeAnthropic.testConnection(probe, fetch)
1540
+ listModels: async (probe) => ({ offers: await probeAnthropic.listModels(probe, withConnectionHeaders(fetch, probe.headers)) }),
1541
+ testConnection: (probe) => probeAnthropic.testConnection(probe, withConnectionHeaders(fetch, probe.headers))
1344
1542
  };
1345
1543
  }
1346
1544
  //#endregion
1347
1545
  //#region src/index.ts
1348
- /** Protocol extensions contribute no tools. */
1349
1546
  const TOOL_NAMES = [];
1350
1547
  const plugin = {
1351
1548
  name: "@eum-agent/llm-protocol-anthropic",