@buildanagent/gateway 0.0.0-stage → 0.1.0-alpha.1

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 (126) hide show
  1. package/LICENSE +52 -0
  2. package/LICENSE-APACHE +202 -0
  3. package/LICENSE-MIT +21 -0
  4. package/README.md +305 -2
  5. package/dist/adapters/anthropic/adapter.d.ts +25 -0
  6. package/dist/adapters/anthropic/adapter.js +183 -0
  7. package/dist/adapters/anthropic/adapter.js.map +1 -0
  8. package/dist/adapters/anthropic/failure.d.ts +27 -0
  9. package/dist/adapters/anthropic/failure.js +53 -0
  10. package/dist/adapters/anthropic/failure.js.map +1 -0
  11. package/dist/adapters/anthropic/index.d.ts +3 -0
  12. package/dist/adapters/anthropic/index.js +3 -0
  13. package/dist/adapters/anthropic/index.js.map +1 -0
  14. package/dist/adapters/anthropic/request.d.ts +53 -0
  15. package/dist/adapters/anthropic/request.js +250 -0
  16. package/dist/adapters/anthropic/request.js.map +1 -0
  17. package/dist/adapters/anthropic/response.d.ts +38 -0
  18. package/dist/adapters/anthropic/response.js +237 -0
  19. package/dist/adapters/anthropic/response.js.map +1 -0
  20. package/dist/adapters/anthropic/usage.d.ts +26 -0
  21. package/dist/adapters/anthropic/usage.js +39 -0
  22. package/dist/adapters/anthropic/usage.js.map +1 -0
  23. package/dist/adapters/openai-chat/adapter.d.ts +18 -0
  24. package/dist/adapters/openai-chat/adapter.js +86 -0
  25. package/dist/adapters/openai-chat/adapter.js.map +1 -0
  26. package/dist/adapters/openai-chat/compat.d.ts +58 -0
  27. package/dist/adapters/openai-chat/compat.js +19 -0
  28. package/dist/adapters/openai-chat/compat.js.map +1 -0
  29. package/dist/adapters/openai-chat/failure.d.ts +32 -0
  30. package/dist/adapters/openai-chat/failure.js +40 -0
  31. package/dist/adapters/openai-chat/failure.js.map +1 -0
  32. package/dist/adapters/openai-chat/index.d.ts +4 -0
  33. package/dist/adapters/openai-chat/index.js +3 -0
  34. package/dist/adapters/openai-chat/index.js.map +1 -0
  35. package/dist/adapters/openai-chat/request.d.ts +47 -0
  36. package/dist/adapters/openai-chat/request.js +227 -0
  37. package/dist/adapters/openai-chat/request.js.map +1 -0
  38. package/dist/adapters/openai-chat/response.d.ts +22 -0
  39. package/dist/adapters/openai-chat/response.js +203 -0
  40. package/dist/adapters/openai-chat/response.js.map +1 -0
  41. package/dist/adapters/openai-chat/usage.d.ts +22 -0
  42. package/dist/adapters/openai-chat/usage.js +25 -0
  43. package/dist/adapters/openai-chat/usage.js.map +1 -0
  44. package/dist/adapters/strict-schema.d.ts +67 -0
  45. package/dist/adapters/strict-schema.js +269 -0
  46. package/dist/adapters/strict-schema.js.map +1 -0
  47. package/dist/adapters/wire.d.ts +98 -0
  48. package/dist/adapters/wire.js +187 -0
  49. package/dist/adapters/wire.js.map +1 -0
  50. package/dist/catalog.d.ts +65 -0
  51. package/dist/catalog.js +145 -0
  52. package/dist/catalog.js.map +1 -0
  53. package/dist/catalog.json +120 -0
  54. package/dist/classify.d.ts +25 -0
  55. package/dist/classify.js +37 -0
  56. package/dist/classify.js.map +1 -0
  57. package/dist/complete.d.ts +9 -0
  58. package/dist/complete.js +13 -0
  59. package/dist/complete.js.map +1 -0
  60. package/dist/cost.d.ts +44 -0
  61. package/dist/cost.js +132 -0
  62. package/dist/cost.js.map +1 -0
  63. package/dist/create-model.d.ts +7 -0
  64. package/dist/create-model.js +81 -0
  65. package/dist/create-model.js.map +1 -0
  66. package/dist/errors.d.ts +17 -0
  67. package/dist/errors.js +24 -0
  68. package/dist/errors.js.map +1 -0
  69. package/dist/index.d.ts +19 -0
  70. package/dist/index.js +17 -0
  71. package/dist/index.js.map +1 -0
  72. package/dist/middleware.d.ts +11 -0
  73. package/dist/middleware.js +22 -0
  74. package/dist/middleware.js.map +1 -0
  75. package/dist/names.d.ts +72 -0
  76. package/dist/names.js +175 -0
  77. package/dist/names.js.map +1 -0
  78. package/dist/provider-config.d.ts +15 -0
  79. package/dist/provider-config.js +23 -0
  80. package/dist/provider-config.js.map +1 -0
  81. package/dist/request-dump.d.ts +28 -0
  82. package/dist/request-dump.js +52 -0
  83. package/dist/request-dump.js.map +1 -0
  84. package/dist/request-policy.d.ts +18 -0
  85. package/dist/request-policy.js +27 -0
  86. package/dist/request-policy.js.map +1 -0
  87. package/dist/retry.d.ts +33 -0
  88. package/dist/retry.js +219 -0
  89. package/dist/retry.js.map +1 -0
  90. package/dist/runtime-types.d.ts +112 -0
  91. package/dist/runtime-types.js +2 -0
  92. package/dist/runtime-types.js.map +1 -0
  93. package/dist/spec.d.ts +67 -0
  94. package/dist/spec.js +2 -0
  95. package/dist/spec.js.map +1 -0
  96. package/dist/sse.d.ts +15 -0
  97. package/dist/sse.js +73 -0
  98. package/dist/sse.js.map +1 -0
  99. package/dist/stream-contract.d.ts +23 -0
  100. package/dist/stream-contract.js +101 -0
  101. package/dist/stream-contract.js.map +1 -0
  102. package/dist/testing/guards.d.ts +16 -0
  103. package/dist/testing/guards.js +48 -0
  104. package/dist/testing/guards.js.map +1 -0
  105. package/dist/testing/index.d.ts +12 -0
  106. package/dist/testing/index.js +13 -0
  107. package/dist/testing/index.js.map +1 -0
  108. package/dist/testing/mock-transport.d.ts +49 -0
  109. package/dist/testing/mock-transport.js +101 -0
  110. package/dist/testing/mock-transport.js.map +1 -0
  111. package/dist/testing/random.d.ts +3 -0
  112. package/dist/testing/random.js +13 -0
  113. package/dist/testing/random.js.map +1 -0
  114. package/dist/testing/setup.d.ts +1 -0
  115. package/dist/testing/setup.js +12 -0
  116. package/dist/testing/setup.js.map +1 -0
  117. package/dist/transform-messages.d.ts +32 -0
  118. package/dist/transform-messages.js +291 -0
  119. package/dist/transform-messages.js.map +1 -0
  120. package/dist/types.d.ts +143 -0
  121. package/dist/types.js +6 -0
  122. package/dist/types.js.map +1 -0
  123. package/dist/usage.d.ts +16 -0
  124. package/dist/usage.js +31 -0
  125. package/dist/usage.js.map +1 -0
  126. package/package.json +50 -3
@@ -0,0 +1,250 @@
1
+ /**
2
+ * Builds the Messages API request body from a `ModelContext` (Messages API reference,
3
+ * https://platform.claude.com/docs/en/api/messages/create, as of November 2026).
4
+ *
5
+ * - Messages pass through `transformMessages()` first; tool results become `tool_result` blocks in a user message,
6
+ * all results of one turn in one message, as the tool-use docs ask. `caps.reasoning` decides only whether the body
7
+ * asks for thinking: signed Anthropic thinking is replayed either way, because the API checks it against its
8
+ * signature rather than the model's caps, and dropping it would lose a turn's reasoning for a model the catalog
9
+ * merely doesn't mark as reasoning.
10
+ * - Tool names go through the run's `ToolNameMap`; tools are sent strict when their schema can be
11
+ * (`../strict-schema.ts`).
12
+ * - Caching puts at most three `cache_control` breakpoints, on the system prompt, the last tool and the last block
13
+ * of the last user message, below the API's limit of 4 (Prompt caching,
14
+ * https://platform.claude.com/docs/en/build-with-claude/prompt-caching, as of November 2026).
15
+ * - `temperature`, `top_p` and `top_k` are never sent: on API version 2026-10-21 any of them is a 400 "even at the
16
+ * parameter's default value" (https://platform.claude.com/docs/en/api/migration-2026-10-21, as of November 2026).
17
+ */
18
+ import { createToolNameMap, TOOL_NAME_RULES } from "../../names.js";
19
+ import { transformMessages } from "../../transform-messages.js";
20
+ import { lowerToStrict } from "../strict-schema.js";
21
+ import { isObject } from "../wire.js";
22
+ /** A prefix on an `OpaqueToken` value that marks a `redacted_thinking` block's `data`, not a thinking signature. */
23
+ export const REDACTED_THINKING_PREFIX = "redacted_thinking:";
24
+ const SAMPLING_PARAMETERS = ["temperature", "top_p", "top_k"];
25
+ // Strict tool use keeps optional properties optional and takes these string formats (Structured outputs, "JSON Schema
26
+ // limitations"); the request-wide limits are from its "Schema complexity limits" section.
27
+ const STRICT_DIALECT = {
28
+ optional: "keep",
29
+ formats: new Set(["date-time", "time", "date", "duration", "email", "hostname", "uri", "ipv4", "ipv6", "uuid"]),
30
+ objectRoot: false,
31
+ };
32
+ /** The request-wide limits on strict schemas: strict tools, optional properties and union-typed parameters. */
33
+ const STRICT_LIMITS = { tools: 20, optional: 24, unions: 16 };
34
+ /** Reads `providerOptions.anthropic`, ignoring fields of the wrong type. */
35
+ export function anthropicOptions(options) {
36
+ const raw = options.providerOptions?.anthropic;
37
+ if (!isObject(raw))
38
+ return {};
39
+ return {
40
+ ...(typeof raw.conversationId === "string" ? { conversationId: raw.conversationId } : {}),
41
+ ...(isObject(raw.extraBody) ? { extraBody: raw.extraBody } : {}),
42
+ };
43
+ }
44
+ function cacheControlFor(retention) {
45
+ if (retention === "none")
46
+ return undefined;
47
+ return retention === "long" ? { type: "ephemeral", ttl: "1h" } : { type: "ephemeral" };
48
+ }
49
+ // Content blocks ------------------------------------------------------------------------------------------------------
50
+ function imageBlock(block) {
51
+ return { type: "image", source: { type: "base64", media_type: block.mediaType, data: block.data } };
52
+ }
53
+ function userBlock(block) {
54
+ if (block.type === "text")
55
+ return block.text === "" ? [] : [{ type: "text", text: block.text }];
56
+ if (block.type === "image")
57
+ return [imageBlock(block)];
58
+ return [];
59
+ }
60
+ function reasoningBlock(block) {
61
+ // An unsigned block cannot pass Anthropic's signature check; transformMessages already drops them for this target.
62
+ const value = block.signature?.value;
63
+ if (value === undefined)
64
+ return [];
65
+ if (value.startsWith(REDACTED_THINKING_PREFIX)) {
66
+ return [{ type: "redacted_thinking", data: value.slice(REDACTED_THINKING_PREFIX.length) }];
67
+ }
68
+ return [{ type: "thinking", thinking: block.text, signature: value }];
69
+ }
70
+ function assistantBlock(block, names) {
71
+ switch (block.type) {
72
+ case "text":
73
+ return block.text === "" ? [] : [{ type: "text", text: block.text }];
74
+ case "reasoning":
75
+ return reasoningBlock(block);
76
+ case "tool_call":
77
+ // A call cut off by the output limit holds its partial JSON as a string; the wire needs an object.
78
+ return [
79
+ {
80
+ type: "tool_use",
81
+ id: block.callId,
82
+ name: names.sanitize(block.name),
83
+ input: isObject(block.input) ? block.input : {},
84
+ },
85
+ ];
86
+ case "image":
87
+ return [];
88
+ }
89
+ }
90
+ function toolResultBlock(message) {
91
+ const content = message.content.flatMap((block) => userBlock(block));
92
+ return {
93
+ type: "tool_result",
94
+ tool_use_id: message.callId,
95
+ ...(content.length > 0 ? { content } : {}),
96
+ ...(message.isError ? { is_error: true } : {}),
97
+ };
98
+ }
99
+ // Messages -----------------------------------------------------------------------------------------------------------
100
+ function appendUserBlocks(out, blocks) {
101
+ if (blocks.length === 0)
102
+ return;
103
+ const last = out.at(-1);
104
+ if (last?.role === "user" && Array.isArray(last.content))
105
+ last.content.push(...blocks);
106
+ else
107
+ out.push({ role: "user", content: blocks });
108
+ }
109
+ function encodeMessages(messages, names) {
110
+ const out = [];
111
+ for (const message of messages) {
112
+ if (message.role === "assistant") {
113
+ const content = message.content.flatMap((block) => assistantBlock(block, names));
114
+ if (content.length > 0)
115
+ out.push({ role: "assistant", content });
116
+ }
117
+ else {
118
+ appendUserBlocks(out, message.role === "tool" ? [toolResultBlock(message)] : message.content.flatMap(userBlock));
119
+ }
120
+ }
121
+ return out;
122
+ }
123
+ function markLastUserBlock(messages, cacheControl) {
124
+ const lastUser = messages.findLast((message) => message.role === "user");
125
+ const content = lastUser?.content;
126
+ const block = Array.isArray(content) ? content.at(-1) : undefined;
127
+ if (isObject(block))
128
+ block.cache_control = cacheControl;
129
+ }
130
+ // Tools --------------------------------------------------------------------------------------------------------------
131
+ function encodeTools(tools, names, cacheControl) {
132
+ const used = { tools: 0, optional: 0, unions: 0 };
133
+ const encoded = tools.map((tool) => {
134
+ const base = {
135
+ name: names.sanitize(tool.name),
136
+ ...(tool.description ? { description: tool.description } : {}),
137
+ };
138
+ const strict = lowerToStrict(tool.inputSchema, STRICT_DIALECT);
139
+ const fits = strict !== undefined &&
140
+ used.tools < STRICT_LIMITS.tools &&
141
+ used.optional + strict.optional <= STRICT_LIMITS.optional &&
142
+ used.unions + strict.unions <= STRICT_LIMITS.unions;
143
+ // A tool past the request-wide limits goes without `strict`, so one large schema cannot fail the whole request.
144
+ if (!fits || strict === undefined)
145
+ return { ...base, input_schema: tool.inputSchema };
146
+ used.tools += 1;
147
+ used.optional += strict.optional;
148
+ used.unions += strict.unions;
149
+ return { ...base, input_schema: strict.schema, strict: true };
150
+ });
151
+ const last = encoded.at(-1);
152
+ if (last && cacheControl)
153
+ last.cache_control = cacheControl;
154
+ return encoded;
155
+ }
156
+ // The body -----------------------------------------------------------------------------------------------------------
157
+ function toolNames(context, messages) {
158
+ const called = messages.flatMap((message) => message.role === "assistant" ? message.content.flatMap((b) => (b.type === "tool_call" ? [b.name] : [])) : []);
159
+ return [...context.tools.map((tool) => tool.name), ...called];
160
+ }
161
+ /** Splits the sampling fields off `extra`, and returns the rest with the names of the fields it dropped. */
162
+ function withoutSampling(extra) {
163
+ const rest = {};
164
+ const dropped = [];
165
+ for (const [key, value] of Object.entries(extra)) {
166
+ if (SAMPLING_PARAMETERS.includes(key))
167
+ dropped.push(key);
168
+ else
169
+ rest[key] = value;
170
+ }
171
+ return { rest, dropped };
172
+ }
173
+ function samplingWarning(dropped) {
174
+ if (dropped.length === 0)
175
+ return [];
176
+ return [
177
+ {
178
+ type: "warning",
179
+ code: "unsupported_option",
180
+ message: "Anthropic API version 2026-10-21 rejects temperature, top_p and top_k at any value, " +
181
+ `so the request was sent without ${dropped.join(", ")}.`,
182
+ },
183
+ ];
184
+ }
185
+ // Body fields the adapter always sets from the context and options, so an `extraBody` field of the same name is
186
+ // ignored. `thinking` is owned only when the caps ask for it, and then only its `type`.
187
+ const ADAPTER_FIELDS = ["model", "max_tokens", "stream", "system", "messages", "tools"];
188
+ /**
189
+ * The adapter's own fields over the caller's extras, and the names of the extras they overrode. A caller's `thinking`
190
+ * keeps its other fields, such as `display`, under the adapter's `type: "adaptive"`.
191
+ */
192
+ function mergeExtras(own, extras, ownsThinking) {
193
+ const overridden = ADAPTER_FIELDS.filter((key) => key in extras);
194
+ const body = { ...extras, ...own };
195
+ for (const key of ADAPTER_FIELDS)
196
+ if (!(key in own))
197
+ delete body[key];
198
+ if (ownsThinking) {
199
+ const extra = extras.thinking;
200
+ if (extra !== undefined && !(isObject(extra) && (extra.type === undefined || extra.type === "adaptive"))) {
201
+ overridden.push("thinking.type");
202
+ }
203
+ body.thinking = { ...(isObject(extra) ? extra : {}), type: "adaptive" };
204
+ }
205
+ return { body, overridden };
206
+ }
207
+ function overrideWarning(overridden) {
208
+ if (overridden.length === 0)
209
+ return [];
210
+ return [
211
+ {
212
+ type: "warning",
213
+ code: "unsupported_option",
214
+ message: `providerOptions.anthropic.extraBody cannot set ${overridden.join(", ")}, ` +
215
+ "which the adapter sets itself, so the request was sent with the adapter's value.",
216
+ },
217
+ ];
218
+ }
219
+ /** Builds one call's request body. The adapter adds the thinking-binding setting to it before each HTTP request. */
220
+ export function buildRequest(model, context, options, caps) {
221
+ // Replay keeps signed thinking whatever caps.reasoning says; the caps decide only the `thinking` field below.
222
+ const messages = transformMessages(context.messages, model, { ...caps, reasoning: true });
223
+ const names = createToolNameMap(TOOL_NAME_RULES.anthropicMessages, toolNames(context, messages));
224
+ const cacheControl = cacheControlFor(options.cacheRetention);
225
+ const wireMessages = encodeMessages(messages, names);
226
+ if (cacheControl)
227
+ markLastUserBlock(wireMessages, cacheControl);
228
+ const tools = encodeTools(context.tools, names, cacheControl);
229
+ const system = context.system === ""
230
+ ? undefined
231
+ : [{ type: "text", text: context.system, ...(cacheControl ? { cache_control: cacheControl } : {}) }];
232
+ const { rest, dropped } = withoutSampling(anthropicOptions(options).extraBody ?? {});
233
+ const own = {
234
+ model: model.id,
235
+ max_tokens: options.maxOutputTokens ?? caps.maxOutputTokens,
236
+ stream: true,
237
+ ...(system ? { system } : {}),
238
+ messages: wireMessages,
239
+ ...(tools.length > 0 ? { tools } : {}),
240
+ };
241
+ const { body, overridden } = mergeExtras(own, rest, caps.reasoning);
242
+ const droppedAll = options.temperature === undefined ? dropped : ["temperature", ...dropped.filter((d) => d !== "temperature")];
243
+ return {
244
+ body,
245
+ warnings: [...samplingWarning(droppedAll), ...overrideWarning(overridden)],
246
+ names,
247
+ cacheTtl: options.cacheRetention === "long" ? "1h" : "5m",
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,CAAC,CAAC,CAAC,EAAE,CAAC;KACvC,CAAC;IACF,MAAM,EAAE,IAAI,EAAE,UAAU,EAAE,GAAG,WAAW,CAAC,GAAG,EAAE,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC;IACpE,MAAM,UAAU,GACd,OAAO,CAAC,WAAW,KAAK,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,aAAa,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,aAAa,CAAC,CAAC,CAAC;IAC/G,OAAO;QACL,IAAI;QACJ,QAAQ,EAAE,CAAC,GAAG,eAAe,CAAC,UAAU,CAAC,EAAE,GAAG,eAAe,CAAC,UAAU,CAAC,CAAC;QAC1E,KAAK;QACL,QAAQ,EAAE,OAAO,CAAC,cAAc,KAAK,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI;KAC1D,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Builds the Messages API request body from a `ModelContext` (Messages API reference,\n * https://platform.claude.com/docs/en/api/messages/create, as of November 2026).\n *\n * - Messages pass through `transformMessages()` first; tool results become `tool_result` blocks in a user message,\n * all results of one turn in one message, as the tool-use docs ask. `caps.reasoning` decides only whether the body\n * asks for thinking: signed Anthropic thinking is replayed either way, because the API checks it against its\n * signature rather than the model's caps, and dropping it would lose a turn's reasoning for a model the catalog\n * merely doesn't mark as reasoning.\n * - Tool names go through the run's `ToolNameMap`; tools are sent strict when their schema can be\n * (`../strict-schema.ts`).\n * - Caching puts at most three `cache_control` breakpoints, on the system prompt, the last tool and the last block\n * of the last user message, below the API's limit of 4 (Prompt caching,\n * https://platform.claude.com/docs/en/build-with-claude/prompt-caching, as of November 2026).\n * - `temperature`, `top_p` and `top_k` are never sent: on API version 2026-10-21 any of them is a 400 \"even at the\n * parameter's default value\" (https://platform.claude.com/docs/en/api/migration-2026-10-21, as of November 2026).\n */\nimport { createToolNameMap, TOOL_NAME_RULES, type ToolNameMap } from \"../../names.js\";\nimport type { ModelEvent, StreamOptions } from \"../../spec.js\";\nimport { transformMessages } from \"../../transform-messages.js\";\nimport type { ContentBlock, Message, ModelCaps, ModelContent, ModelContext, ModelRef, WireTool } from \"../../types.js\";\nimport { lowerToStrict, type StrictDialect } from \"../strict-schema.js\";\nimport { isObject, type Json } from \"../wire.js\";\n\ntype Warning = Extract<ModelEvent, { type: \"warning\" }>;\n\n/** A prefix on an `OpaqueToken` value that marks a `redacted_thinking` block's `data`, not a thinking signature. */\nexport const REDACTED_THINKING_PREFIX = \"redacted_thinking:\";\n\nconst SAMPLING_PARAMETERS = [\"temperature\", \"top_p\", \"top_k\"] as const;\n\n// Strict tool use keeps optional properties optional and takes these string formats (Structured outputs, \"JSON Schema\n// limitations\"); the request-wide limits are from its \"Schema complexity limits\" section.\nconst STRICT_DIALECT: StrictDialect = {\n optional: \"keep\",\n formats: new Set([\"date-time\", \"time\", \"date\", \"duration\", \"email\", \"hostname\", \"uri\", \"ipv4\", \"ipv6\", \"uuid\"]),\n objectRoot: false,\n};\n/** The request-wide limits on strict schemas: strict tools, optional properties and union-typed parameters. */\nconst STRICT_LIMITS = { tools: 20, optional: 24, unions: 16 } as const;\n\n/** What the adapter reads from `providerOptions.anthropic`. */\nexport interface AnthropicProviderOptions {\n /**\n * Names the conversation, so the adapter can remember a choice that must hold for its later requests. Without it,\n * the adapter recognises a conversation by its system prompt and first message.\n */\n readonly conversationId?: string;\n /**\n * Extra fields for the request body, such as `output_config` or `thinking: { display: \"summarized\" }`. The fields\n * the adapter sets itself (`model`, `max_tokens`, `stream`, `system`, `messages`, `tools`, and `thinking.type` for a\n * reasoning model) win over these, and sampling fields are dropped; either streams an `unsupported_option` warning.\n */\n readonly extraBody?: Readonly<Record<string, unknown>>;\n}\n\n/** One request's body and what reading its response needs. */\nexport interface RequestPlan {\n readonly body: Json;\n readonly warnings: readonly Warning[];\n readonly names: ToolNameMap;\n /** The TTL the breakpoints asked for, used when a response reports cache writes without their split. */\n readonly cacheTtl: \"5m\" | \"1h\";\n}\n\n/** Reads `providerOptions.anthropic`, ignoring fields of the wrong type. */\nexport function anthropicOptions(options: StreamOptions): AnthropicProviderOptions {\n const raw = options.providerOptions?.anthropic;\n if (!isObject(raw)) return {};\n return {\n ...(typeof raw.conversationId === \"string\" ? { conversationId: raw.conversationId } : {}),\n ...(isObject(raw.extraBody) ? { extraBody: raw.extraBody } : {}),\n };\n}\n\nfunction cacheControlFor(retention: StreamOptions[\"cacheRetention\"]): Json | undefined {\n if (retention === \"none\") return undefined;\n return retention === \"long\" ? { type: \"ephemeral\", ttl: \"1h\" } : { type: \"ephemeral\" };\n}\n\n// Content blocks ------------------------------------------------------------------------------------------------------\n\nfunction imageBlock(block: Extract<ContentBlock, { type: \"image\" }>): Json {\n return { type: \"image\", source: { type: \"base64\", media_type: block.mediaType, data: block.data } };\n}\n\nfunction userBlock(block: ContentBlock): Json[] {\n if (block.type === \"text\") return block.text === \"\" ? [] : [{ type: \"text\", text: block.text }];\n if (block.type === \"image\") return [imageBlock(block)];\n return [];\n}\n\nfunction reasoningBlock(block: Extract<ContentBlock, { type: \"reasoning\" }>): Json[] {\n // An unsigned block cannot pass Anthropic's signature check; transformMessages already drops them for this target.\n const value = block.signature?.value;\n if (value === undefined) return [];\n if (value.startsWith(REDACTED_THINKING_PREFIX)) {\n return [{ type: \"redacted_thinking\", data: value.slice(REDACTED_THINKING_PREFIX.length) }];\n }\n return [{ type: \"thinking\", thinking: block.text, signature: value }];\n}\n\nfunction assistantBlock(block: ContentBlock, names: ToolNameMap): Json[] {\n switch (block.type) {\n case \"text\":\n return block.text === \"\" ? [] : [{ type: \"text\", text: block.text }];\n case \"reasoning\":\n return reasoningBlock(block);\n case \"tool_call\":\n // A call cut off by the output limit holds its partial JSON as a string; the wire needs an object.\n return [\n {\n type: \"tool_use\",\n id: block.callId,\n name: names.sanitize(block.name),\n input: isObject(block.input) ? block.input : {},\n },\n ];\n case \"image\":\n return [];\n }\n}\n\nfunction toolResultBlock(message: Extract<Message, { role: \"tool\" }>): Json {\n const content = message.content.flatMap((block: ModelContent) => userBlock(block));\n return {\n type: \"tool_result\",\n tool_use_id: message.callId,\n ...(content.length > 0 ? { content } : {}),\n ...(message.isError ? { is_error: true } : {}),\n };\n}\n\n// Messages -----------------------------------------------------------------------------------------------------------\n\nfunction appendUserBlocks(out: Json[], blocks: Json[]): void {\n if (blocks.length === 0) return;\n const last = out.at(-1);\n if (last?.role === \"user\" && Array.isArray(last.content)) last.content.push(...blocks);\n else out.push({ role: \"user\", content: blocks });\n}\n\nfunction encodeMessages(messages: readonly Message[], names: ToolNameMap): Json[] {\n const out: Json[] = [];\n for (const message of messages) {\n if (message.role === \"assistant\") {\n const content = message.content.flatMap((block) => assistantBlock(block, names));\n if (content.length > 0) out.push({ role: \"assistant\", content });\n } else {\n appendUserBlocks(out, message.role === \"tool\" ? [toolResultBlock(message)] : message.content.flatMap(userBlock));\n }\n }\n return out;\n}\n\nfunction markLastUserBlock(messages: Json[], cacheControl: Json): void {\n const lastUser = messages.findLast((message) => message.role === \"user\");\n const content = lastUser?.content;\n const block = Array.isArray(content) ? content.at(-1) : undefined;\n if (isObject(block)) block.cache_control = cacheControl;\n}\n\n// Tools --------------------------------------------------------------------------------------------------------------\n\nfunction encodeTools(tools: readonly WireTool[], names: ToolNameMap, cacheControl: Json | undefined): Json[] {\n const used = { tools: 0, optional: 0, unions: 0 };\n const encoded = tools.map((tool): Json => {\n const base: Json = {\n name: names.sanitize(tool.name),\n ...(tool.description ? { description: tool.description } : {}),\n };\n const strict = lowerToStrict(tool.inputSchema, STRICT_DIALECT);\n const fits =\n strict !== undefined &&\n used.tools < STRICT_LIMITS.tools &&\n used.optional + strict.optional <= STRICT_LIMITS.optional &&\n used.unions + strict.unions <= STRICT_LIMITS.unions;\n // A tool past the request-wide limits goes without `strict`, so one large schema cannot fail the whole request.\n if (!fits || strict === undefined) return { ...base, input_schema: tool.inputSchema };\n used.tools += 1;\n used.optional += strict.optional;\n used.unions += strict.unions;\n return { ...base, input_schema: strict.schema, strict: true };\n });\n const last = encoded.at(-1);\n if (last && cacheControl) last.cache_control = cacheControl;\n return encoded;\n}\n\n// The body -----------------------------------------------------------------------------------------------------------\n\nfunction toolNames(context: ModelContext, messages: readonly Message[]): string[] {\n const called = messages.flatMap((message) =>\n message.role === \"assistant\" ? message.content.flatMap((b) => (b.type === \"tool_call\" ? [b.name] : [])) : [],\n );\n return [...context.tools.map((tool) => tool.name), ...called];\n}\n\n/** Splits the sampling fields off `extra`, and returns the rest with the names of the fields it dropped. */\nfunction withoutSampling(extra: Readonly<Json>): { rest: Json; dropped: string[] } {\n const rest: Json = {};\n const dropped: string[] = [];\n for (const [key, value] of Object.entries(extra)) {\n if ((SAMPLING_PARAMETERS as readonly string[]).includes(key)) dropped.push(key);\n else rest[key] = value;\n }\n return { rest, dropped };\n}\n\nfunction samplingWarning(dropped: readonly string[]): Warning[] {\n if (dropped.length === 0) return [];\n return [\n {\n type: \"warning\",\n code: \"unsupported_option\",\n message:\n \"Anthropic API version 2026-10-21 rejects temperature, top_p and top_k at any value, \" +\n `so the request was sent without ${dropped.join(\", \")}.`,\n },\n ];\n}\n\n// Body fields the adapter always sets from the context and options, so an `extraBody` field of the same name is\n// ignored. `thinking` is owned only when the caps ask for it, and then only its `type`.\nconst ADAPTER_FIELDS = [\"model\", \"max_tokens\", \"stream\", \"system\", \"messages\", \"tools\"] as const;\n\n/**\n * The adapter's own fields over the caller's extras, and the names of the extras they overrode. A caller's `thinking`\n * keeps its other fields, such as `display`, under the adapter's `type: \"adaptive\"`.\n */\nfunction mergeExtras(own: Json, extras: Json, ownsThinking: boolean): { body: Json; overridden: string[] } {\n const overridden: string[] = ADAPTER_FIELDS.filter((key) => key in extras);\n const body: Json = { ...extras, ...own };\n for (const key of ADAPTER_FIELDS) if (!(key in own)) delete body[key];\n if (ownsThinking) {\n const extra = extras.thinking;\n if (extra !== undefined && !(isObject(extra) && (extra.type === undefined || extra.type === \"adaptive\"))) {\n overridden.push(\"thinking.type\");\n }\n body.thinking = { ...(isObject(extra) ? extra : {}), type: \"adaptive\" };\n }\n return { body, overridden };\n}\n\nfunction overrideWarning(overridden: readonly string[]): Warning[] {\n if (overridden.length === 0) return [];\n return [\n {\n type: \"warning\",\n code: \"unsupported_option\",\n message:\n `providerOptions.anthropic.extraBody cannot set ${overridden.join(\", \")}, ` +\n \"which the adapter sets itself, so the request was sent with the adapter's value.\",\n },\n ];\n}\n\n/** Builds one call's request body. The adapter adds the thinking-binding setting to it before each HTTP request. */\nexport function buildRequest(\n model: ModelRef,\n context: ModelContext,\n options: StreamOptions,\n caps: ModelCaps,\n): RequestPlan {\n // Replay keeps signed thinking whatever caps.reasoning says; the caps decide only the `thinking` field below.\n const messages = transformMessages(context.messages, model, { ...caps, reasoning: true });\n const names = createToolNameMap(TOOL_NAME_RULES.anthropicMessages, toolNames(context, messages));\n const cacheControl = cacheControlFor(options.cacheRetention);\n const wireMessages = encodeMessages(messages, names);\n if (cacheControl) markLastUserBlock(wireMessages, cacheControl);\n const tools = encodeTools(context.tools, names, cacheControl);\n const system =\n context.system === \"\"\n ? undefined\n : [{ type: \"text\", text: context.system, ...(cacheControl ? { cache_control: cacheControl } : {}) }];\n const { rest, dropped } = withoutSampling(anthropicOptions(options).extraBody ?? {});\n const own: Json = {\n model: model.id,\n max_tokens: options.maxOutputTokens ?? caps.maxOutputTokens,\n stream: true,\n ...(system ? { system } : {}),\n messages: wireMessages,\n ...(tools.length > 0 ? { tools } : {}),\n };\n const { body, overridden } = mergeExtras(own, rest, caps.reasoning);\n const droppedAll =\n options.temperature === undefined ? dropped : [\"temperature\", ...dropped.filter((d) => d !== \"temperature\")];\n return {\n body,\n warnings: [...samplingWarning(droppedAll), ...overrideWarning(overridden)],\n names,\n cacheTtl: options.cacheRetention === \"long\" ? \"1h\" : \"5m\",\n };\n}\n"]}
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Turns the Messages API's stream events into `ModelEvent`s (Streaming messages,
3
+ * https://platform.claude.com/docs/en/build-with-claude/streaming, as of November 2026). A stream runs
4
+ * `message_start`, then each content block as `content_block_start`, its `content_block_delta`s and
5
+ * `content_block_stop`, then one or more `message_delta`s with cumulative usage, then `message_stop`. `ping` events
6
+ * and event types the adapter does not know are skipped, as the versioning policy asks.
7
+ *
8
+ * Text blocks become text, `thinking` and `redacted_thinking` blocks become reasoning with an Anthropic signature,
9
+ * and `tool_use` blocks become tool calls. Server-tool blocks carry nothing this transcript can replay, so they are
10
+ * skipped.
11
+ *
12
+ * Usage arrives on `message_start` and, with the authoritative output count, on the final `message_delta`. The usage
13
+ * is `unreported` when that count is missing: for a stream that sent no usage, for a finished reply whose
14
+ * `message_delta`s reported no `output_tokens`, and for a stream that breaks off or sends an `error` event after a
15
+ * content block began. Such usage keeps the counts `message_start` reported. A stream that fails before any content
16
+ * block keeps those counts as reported, because no output was made after them.
17
+ */
18
+ import type { ToolNameMap } from "../../names.js";
19
+ import type { ModelEvent } from "../../spec.js";
20
+ import type { ServerSentEvent } from "../../sse.js";
21
+ import type { ContentBlock, ModelRef, Usage } from "../../types.js";
22
+ import { type StreamReader } from "../wire.js";
23
+ /** One stream's state: the blocks so far, the usage and the stop reason. */
24
+ export declare class MessageAssembler implements StreamReader {
25
+ #private;
26
+ constructor(model: ModelRef, names: ToolNameMap, cacheTtl: "5m" | "1h");
27
+ /** The events one server-sent event produces. The last one is the terminal when the stream has ended. */
28
+ handle(sse: ServerSentEvent): ModelEvent[];
29
+ /** No status and no terminal: the connection closed early, which a retry may fix. */
30
+ ended(): ModelEvent[];
31
+ /** The content and usage so far, open blocks included, for an `error` terminal. */
32
+ partial(): {
33
+ content: ContentBlock[];
34
+ usage: Usage;
35
+ };
36
+ /** The usage so far: `unreported` when output began and no `message_delta` has reported its final count yet. */
37
+ usage(): Usage;
38
+ }
@@ -0,0 +1,237 @@
1
+ import { unreportedUsage } from "../../usage.js";
2
+ import { isObject, parseToolInput, str, terminalMessage } from "../wire.js";
3
+ import { failureEvent, failureFrom } from "./failure.js";
4
+ import { REDACTED_THINKING_PREFIX } from "./request.js";
5
+ import { anthropicUsage, mergeUsage } from "./usage.js";
6
+ // Each wire stop reason as the gateway's. `refusal` is handled apart, as a failure.
7
+ const STOP_REASONS = {
8
+ end_turn: "stop",
9
+ stop_sequence: "stop",
10
+ pause_turn: "stop",
11
+ tool_use: "tool_calls",
12
+ max_tokens: "length",
13
+ model_context_window_exceeded: "length",
14
+ };
15
+ /** One stream's state: the blocks so far, the usage and the stop reason. */
16
+ export class MessageAssembler {
17
+ #model;
18
+ #names;
19
+ #cacheTtl;
20
+ #open = new Map();
21
+ #closed = new Map();
22
+ #transformations = new Set();
23
+ #usage = {};
24
+ // Whether any event carried a usage object, whether a content block began after `message_start`'s output count,
25
+ // and whether a `message_delta` reported the final output count.
26
+ #usageSeen = false;
27
+ #outputSeen = false;
28
+ #finalUsageSeen = false;
29
+ #stopReason = "";
30
+ #stopDetails;
31
+ constructor(model, names, cacheTtl) {
32
+ this.#model = model;
33
+ this.#names = names;
34
+ this.#cacheTtl = cacheTtl;
35
+ }
36
+ /** The events one server-sent event produces. The last one is the terminal when the stream has ended. */
37
+ handle(sse) {
38
+ const data = JSON.parse(sse.data);
39
+ if (!isObject(data))
40
+ return [];
41
+ return this.#dispatch(typeof data.type === "string" ? data.type : sse.event, data);
42
+ }
43
+ /** No status and no terminal: the connection closed early, which a retry may fix. */
44
+ ended() {
45
+ return [failureEvent(this.#model, { message: "the stream ended before message_stop" }, this.partial())];
46
+ }
47
+ #dispatch(type, data) {
48
+ if (type === "content_block_start" || type === "content_block_delta")
49
+ this.#outputSeen = true;
50
+ switch (type) {
51
+ case "message_start":
52
+ return this.#messageStart(data);
53
+ case "content_block_start":
54
+ return this.#blockStart(data);
55
+ case "content_block_delta":
56
+ return this.#blockDelta(data);
57
+ case "content_block_stop":
58
+ return this.#blockStop(data);
59
+ case "message_delta":
60
+ return this.#messageDelta(data);
61
+ case "message_stop":
62
+ return this.#messageStop();
63
+ case "error":
64
+ return [failureEvent(this.#model, failureFrom(data, undefined, "stream error"), this.partial())];
65
+ default:
66
+ return [];
67
+ }
68
+ }
69
+ /** The content and usage so far, open blocks included, for an `error` terminal. */
70
+ partial() {
71
+ const open = [...this.#open].map(([index, block]) => [index, this.#finish(block)]);
72
+ const content = [...this.#closed, ...open].sort(([a], [b]) => a - b).map(([, block]) => block);
73
+ return { content, usage: this.usage() };
74
+ }
75
+ /** The usage so far: `unreported` when output began and no `message_delta` has reported its final count yet. */
76
+ usage() {
77
+ return this.#usageWith(this.#outputSeen);
78
+ }
79
+ #usageWith(outputMade) {
80
+ if (!this.#usageSeen)
81
+ return unreportedUsage();
82
+ const counted = anthropicUsage(this.#usage, this.#cacheTtl);
83
+ // Without the final count, the output is the one `message_start` sent before any output was made.
84
+ return this.#finalUsageSeen || !outputMade ? counted : { ...counted, unreported: true };
85
+ }
86
+ #messageStart(data) {
87
+ const message = isObject(data.message) ? data.message : {};
88
+ if (isObject(message.usage))
89
+ this.#usageSeen = true;
90
+ this.#usage = mergeUsage({}, message.usage);
91
+ return this.#transformationWarnings(message.input_transformations);
92
+ }
93
+ // Under the thinking-binding beta, `message_start` carries `input_transformations`, and the final `message_delta`
94
+ // carries it again after a mid-stream fallback (Streaming, "Event types"). Each entry is warned about once.
95
+ #transformationWarnings(entries) {
96
+ if (!Array.isArray(entries))
97
+ return [];
98
+ return entries.flatMap((entry) => {
99
+ if (!isObject(entry) || entry.type !== "thinking_mismatch_allowed")
100
+ return [];
101
+ const key = `${str(entry.path)}|${str(entry.reason)}`;
102
+ if (this.#transformations.has(key))
103
+ return [];
104
+ this.#transformations.add(key);
105
+ return [
106
+ {
107
+ type: "warning",
108
+ code: "thinking_mismatch_allowed",
109
+ message: `${str(entry.path)}: a thinking block failed the prefix check (${str(entry.reason)}) and reached the model`,
110
+ },
111
+ ];
112
+ });
113
+ }
114
+ #blockStart(data) {
115
+ const index = typeof data.index === "number" ? data.index : -1;
116
+ const block = isObject(data.content_block) ? data.content_block : {};
117
+ const open = this.#openBlock(block);
118
+ if (open === undefined || index < 0 || this.#open.has(index) || this.#closed.has(index))
119
+ return [];
120
+ this.#open.set(index, open);
121
+ const startEvent = { type: `${open.kind}_start`, index };
122
+ // A redacted block arrives whole, with no deltas, so it ends where it starts.
123
+ return open.redacted === undefined ? [startEvent] : [startEvent, ...this.#close(index)];
124
+ }
125
+ #openBlock(block) {
126
+ switch (block.type) {
127
+ case "text":
128
+ return { kind: "text", text: str(block.text) };
129
+ case "thinking":
130
+ return { kind: "reasoning", text: str(block.thinking), signature: str(block.signature) };
131
+ case "redacted_thinking":
132
+ return { kind: "reasoning", text: "", redacted: str(block.data) };
133
+ case "tool_use":
134
+ return { kind: "tool_input", text: "", callId: str(block.id), name: str(block.name), startInput: block.input };
135
+ default:
136
+ return undefined;
137
+ }
138
+ }
139
+ #blockDelta(data) {
140
+ const index = typeof data.index === "number" ? data.index : -1;
141
+ const open = this.#open.get(index);
142
+ const delta = isObject(data.delta) ? data.delta : {};
143
+ if (open === undefined)
144
+ return [];
145
+ if (delta.type === "signature_delta") {
146
+ open.signature = (open.signature ?? "") + str(delta.signature);
147
+ return [];
148
+ }
149
+ const text = str(delta.type === "thinking_delta"
150
+ ? delta.thinking
151
+ : delta.type === "input_json_delta"
152
+ ? delta.partial_json
153
+ : delta.text);
154
+ const fits = (open.kind === "text" && delta.type === "text_delta") ||
155
+ (open.kind === "reasoning" && delta.type === "thinking_delta") ||
156
+ (open.kind === "tool_input" && delta.type === "input_json_delta");
157
+ // An empty delta adds nothing; a citations delta or another kind of delta has no place in this transcript.
158
+ if (!fits || text === "")
159
+ return [];
160
+ open.text += text;
161
+ return [{ type: `${open.kind}_delta`, index, delta: text }];
162
+ }
163
+ #blockStop(data) {
164
+ return typeof data.index === "number" ? this.#close(data.index) : [];
165
+ }
166
+ #close(index) {
167
+ const open = this.#open.get(index);
168
+ if (open === undefined)
169
+ return [];
170
+ this.#open.delete(index);
171
+ const block = this.#finish(open);
172
+ this.#closed.set(index, block);
173
+ return [{ type: `${open.kind}_end`, index, block }];
174
+ }
175
+ #finish(open) {
176
+ if (open.kind === "text")
177
+ return { type: "text", text: open.text };
178
+ if (open.kind === "tool_input") {
179
+ const wire = open.name ?? "";
180
+ return {
181
+ type: "tool_call",
182
+ callId: open.callId ?? "",
183
+ name: this.#names.restore(wire) ?? wire,
184
+ input: parseToolInput(open.text, open.startInput ?? {}),
185
+ };
186
+ }
187
+ const value = open.redacted === undefined ? open.signature : `${REDACTED_THINKING_PREFIX}${open.redacted}`;
188
+ const { api, provider, id } = this.#model;
189
+ return value
190
+ ? { type: "reasoning", text: open.text, signature: { api, provider, model: id, value } }
191
+ : { type: "reasoning", text: open.text };
192
+ }
193
+ #messageDelta(data) {
194
+ const delta = isObject(data.delta) ? data.delta : {};
195
+ if (typeof delta.stop_reason === "string")
196
+ this.#stopReason = delta.stop_reason;
197
+ if (delta.stop_details !== undefined)
198
+ this.#stopDetails = delta.stop_details;
199
+ if (isObject(data.usage)) {
200
+ this.#usageSeen = true;
201
+ if (typeof data.usage.output_tokens === "number")
202
+ this.#finalUsageSeen = true;
203
+ }
204
+ this.#usage = mergeUsage(this.#usage, data.usage);
205
+ return this.#transformationWarnings(data.input_transformations ?? delta.input_transformations);
206
+ }
207
+ #messageStop() {
208
+ // The output limit can end a stream with a block still open; the block ends here with what arrived.
209
+ const closing = [...this.#open.keys()].sort((a, b) => a - b).flatMap((index) => this.#close(index));
210
+ return [...closing, ...this.#terminal()];
211
+ }
212
+ #terminal() {
213
+ // A finished reply always needs the final count, even one that streamed no content block.
214
+ const { content } = this.partial();
215
+ const usage = this.#usageWith(true);
216
+ if (this.#stopReason === "refusal") {
217
+ const details = isObject(this.#stopDetails) ? this.#stopDetails : {};
218
+ const category = str(details.category) || "no category";
219
+ const message = `refusal (${category}): ${str(details.explanation) || "the model declined the request"}`;
220
+ // No `type`: failureEvent prefixes the type to the message, which already starts with "refusal".
221
+ return [failureEvent(this.#model, { message, kind: "fatal" }, { content, usage })];
222
+ }
223
+ const stopReason = STOP_REASONS[this.#stopReason] ?? "stop";
224
+ const warnings = this.#stopReason === "pause_turn"
225
+ ? [
226
+ {
227
+ type: "warning",
228
+ code: "pause_turn",
229
+ message: "The provider paused a long-running server-tool turn. This adapter dropped the turn's server-tool " +
230
+ "blocks, so it cannot resume the paused turn; the reply holds only the content before the pause.",
231
+ },
232
+ ]
233
+ : [];
234
+ return [...warnings, { type: "done", message: terminalMessage(this.#model, { content, usage }, stopReason) }];
235
+ }
236
+ }
237
+ //# sourceMappingURL=response.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"response.js","sourceRoot":"","sources":["../../../src/adapters/anthropic/response.ts"],"names":[],"mappings":"AAqBA,OAAO,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AACjD,OAAO,EAAE,QAAQ,EAAa,cAAc,EAAqB,GAAG,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAC1G,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AACzD,OAAO,EAAE,wBAAwB,EAAE,MAAM,cAAc,CAAC;AACxD,OAAO,EAAE,cAAc,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAcxD,oFAAoF;AACpF,MAAM,YAAY,GAA6D;IAC7E,QAAQ,EAAE,MAAM;IAChB,aAAa,EAAE,MAAM;IACrB,UAAU,EAAE,MAAM;IAClB,QAAQ,EAAE,YAAY;IACtB,UAAU,EAAE,QAAQ;IACpB,6BAA6B,EAAE,QAAQ;CACxC,CAAC;AAEF,4EAA4E;AAC5E,MAAM,OAAO,gBAAgB;IAClB,MAAM,CAAW;IACjB,MAAM,CAAc;IACpB,SAAS,CAAc;IACvB,KAAK,GAAG,IAAI,GAAG,EAAqB,CAAC;IACrC,OAAO,GAAG,IAAI,GAAG,EAAwB,CAAC;IAC1C,gBAAgB,GAAG,IAAI,GAAG,EAAU,CAAC;IAC9C,MAAM,GAAS,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,EAAE,eAAe,CAAC,IAAI,CAAC,MAAM,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,EAAE,UAAU,CAAC,EAAE,CAAC,CAAC;IAChH,CAAC;CACF","sourcesContent":["/**\n * Turns the Messages API's stream events into `ModelEvent`s (Streaming messages,\n * https://platform.claude.com/docs/en/build-with-claude/streaming, as of November 2026). A stream runs\n * `message_start`, then each content block as `content_block_start`, its `content_block_delta`s and\n * `content_block_stop`, then one or more `message_delta`s with cumulative usage, then `message_stop`. `ping` events\n * and event types the adapter does not know are skipped, as the versioning policy asks.\n *\n * Text blocks become text, `thinking` and `redacted_thinking` blocks become reasoning with an Anthropic signature,\n * and `tool_use` blocks become tool calls. Server-tool blocks carry nothing this transcript can replay, so they are\n * skipped.\n *\n * Usage arrives on `message_start` and, with the authoritative output count, on the final `message_delta`. The usage\n * is `unreported` when that count is missing: for a stream that sent no usage, for a finished reply whose\n * `message_delta`s reported no `output_tokens`, and for a stream that breaks off or sends an `error` event after a\n * content block began. Such usage keeps the counts `message_start` reported. A stream that fails before any content\n * block keeps those counts as reported, because no output was made after them.\n */\nimport type { ToolNameMap } from \"../../names.js\";\nimport type { ModelEvent } from \"../../spec.js\";\nimport type { ServerSentEvent } from \"../../sse.js\";\nimport type { AssistantMessage, ContentBlock, ModelRef, Usage } from \"../../types.js\";\nimport { unreportedUsage } from \"../../usage.js\";\nimport { isObject, type Json, parseToolInput, type StreamReader, str, terminalMessage } from \"../wire.js\";\nimport { failureEvent, failureFrom } from \"./failure.js\";\nimport { REDACTED_THINKING_PREFIX } from \"./request.js\";\nimport { anthropicUsage, mergeUsage } from \"./usage.js\";\n\ntype Warning = Extract<ModelEvent, { type: \"warning\" }>;\n\ninterface OpenBlock {\n readonly kind: \"text\" | \"reasoning\" | \"tool_input\";\n text: string;\n signature?: string;\n redacted?: string;\n callId?: string;\n name?: string;\n startInput?: unknown;\n}\n\n// Each wire stop reason as the gateway's. `refusal` is handled apart, as a failure.\nconst STOP_REASONS: Readonly<Record<string, AssistantMessage[\"stopReason\"]>> = {\n end_turn: \"stop\",\n stop_sequence: \"stop\",\n pause_turn: \"stop\",\n tool_use: \"tool_calls\",\n max_tokens: \"length\",\n model_context_window_exceeded: \"length\",\n};\n\n/** One stream's state: the blocks so far, the usage and the stop reason. */\nexport class MessageAssembler implements StreamReader {\n readonly #model: ModelRef;\n readonly #names: ToolNameMap;\n readonly #cacheTtl: \"5m\" | \"1h\";\n readonly #open = new Map<number, OpenBlock>();\n readonly #closed = new Map<number, ContentBlock>();\n readonly #transformations = new Set<string>();\n #usage: Json = {};\n // Whether any event carried a usage object, whether a content block began after `message_start`'s output count,\n // and whether a `message_delta` reported the final output count.\n #usageSeen = false;\n #outputSeen = false;\n #finalUsageSeen = false;\n #stopReason = \"\";\n #stopDetails: unknown;\n\n constructor(model: ModelRef, names: ToolNameMap, cacheTtl: \"5m\" | \"1h\") {\n this.#model = model;\n this.#names = names;\n this.#cacheTtl = cacheTtl;\n }\n\n /** The events one server-sent event produces. The last one is the terminal when the stream has ended. */\n handle(sse: ServerSentEvent): ModelEvent[] {\n const data: unknown = JSON.parse(sse.data);\n if (!isObject(data)) return [];\n return this.#dispatch(typeof data.type === \"string\" ? data.type : sse.event, data);\n }\n\n /** No status and no terminal: the connection closed early, which a retry may fix. */\n ended(): ModelEvent[] {\n return [failureEvent(this.#model, { message: \"the stream ended before message_stop\" }, this.partial())];\n }\n\n #dispatch(type: string, data: Json): ModelEvent[] {\n if (type === \"content_block_start\" || type === \"content_block_delta\") this.#outputSeen = true;\n switch (type) {\n case \"message_start\":\n return this.#messageStart(data);\n case \"content_block_start\":\n return this.#blockStart(data);\n case \"content_block_delta\":\n return this.#blockDelta(data);\n case \"content_block_stop\":\n return this.#blockStop(data);\n case \"message_delta\":\n return this.#messageDelta(data);\n case \"message_stop\":\n return this.#messageStop();\n case \"error\":\n return [failureEvent(this.#model, failureFrom(data, undefined, \"stream error\"), this.partial())];\n default:\n return [];\n }\n }\n\n /** The content and usage so far, open blocks included, for an `error` terminal. */\n partial(): { content: ContentBlock[]; usage: Usage } {\n const open = [...this.#open].map(([index, block]) => [index, this.#finish(block)] as const);\n const content = [...this.#closed, ...open].sort(([a], [b]) => a - b).map(([, block]) => block);\n return { content, usage: this.usage() };\n }\n\n /** The usage so far: `unreported` when output began and no `message_delta` has reported its final count yet. */\n usage(): Usage {\n return this.#usageWith(this.#outputSeen);\n }\n\n #usageWith(outputMade: boolean): Usage {\n if (!this.#usageSeen) return unreportedUsage();\n const counted = anthropicUsage(this.#usage, this.#cacheTtl);\n // Without the final count, the output is the one `message_start` sent before any output was made.\n return this.#finalUsageSeen || !outputMade ? counted : { ...counted, unreported: true };\n }\n\n #messageStart(data: Json): ModelEvent[] {\n const message = isObject(data.message) ? data.message : {};\n if (isObject(message.usage)) this.#usageSeen = true;\n this.#usage = mergeUsage({}, message.usage);\n return this.#transformationWarnings(message.input_transformations);\n }\n\n // Under the thinking-binding beta, `message_start` carries `input_transformations`, and the final `message_delta`\n // carries it again after a mid-stream fallback (Streaming, \"Event types\"). Each entry is warned about once.\n #transformationWarnings(entries: unknown): Warning[] {\n if (!Array.isArray(entries)) return [];\n return entries.flatMap((entry): Warning[] => {\n if (!isObject(entry) || entry.type !== \"thinking_mismatch_allowed\") return [];\n const key = `${str(entry.path)}|${str(entry.reason)}`;\n if (this.#transformations.has(key)) return [];\n this.#transformations.add(key);\n return [\n {\n type: \"warning\",\n code: \"thinking_mismatch_allowed\",\n message: `${str(entry.path)}: a thinking block failed the prefix check (${str(entry.reason)}) and reached the model`,\n },\n ];\n });\n }\n\n #blockStart(data: Json): ModelEvent[] {\n const index = typeof data.index === \"number\" ? data.index : -1;\n const block = isObject(data.content_block) ? data.content_block : {};\n const open = this.#openBlock(block);\n if (open === undefined || index < 0 || this.#open.has(index) || this.#closed.has(index)) return [];\n this.#open.set(index, open);\n const startEvent: ModelEvent = { type: `${open.kind}_start`, index };\n // A redacted block arrives whole, with no deltas, so it ends where it starts.\n return open.redacted === undefined ? [startEvent] : [startEvent, ...this.#close(index)];\n }\n\n #openBlock(block: Json): OpenBlock | undefined {\n switch (block.type) {\n case \"text\":\n return { kind: \"text\", text: str(block.text) };\n case \"thinking\":\n return { kind: \"reasoning\", text: str(block.thinking), signature: str(block.signature) };\n case \"redacted_thinking\":\n return { kind: \"reasoning\", text: \"\", redacted: str(block.data) };\n case \"tool_use\":\n return { kind: \"tool_input\", text: \"\", callId: str(block.id), name: str(block.name), startInput: block.input };\n default:\n return undefined;\n }\n }\n\n #blockDelta(data: Json): ModelEvent[] {\n const index = typeof data.index === \"number\" ? data.index : -1;\n const open = this.#open.get(index);\n const delta = isObject(data.delta) ? data.delta : {};\n if (open === undefined) return [];\n if (delta.type === \"signature_delta\") {\n open.signature = (open.signature ?? \"\") + str(delta.signature);\n return [];\n }\n const text = str(\n delta.type === \"thinking_delta\"\n ? delta.thinking\n : delta.type === \"input_json_delta\"\n ? delta.partial_json\n : delta.text,\n );\n const fits =\n (open.kind === \"text\" && delta.type === \"text_delta\") ||\n (open.kind === \"reasoning\" && delta.type === \"thinking_delta\") ||\n (open.kind === \"tool_input\" && delta.type === \"input_json_delta\");\n // An empty delta adds nothing; a citations delta or another kind of delta has no place in this transcript.\n if (!fits || text === \"\") return [];\n open.text += text;\n return [{ type: `${open.kind}_delta`, index, delta: text }];\n }\n\n #blockStop(data: Json): ModelEvent[] {\n return typeof data.index === \"number\" ? this.#close(data.index) : [];\n }\n\n #close(index: number): ModelEvent[] {\n const open = this.#open.get(index);\n if (open === undefined) return [];\n this.#open.delete(index);\n const block = this.#finish(open);\n this.#closed.set(index, block);\n return [{ type: `${open.kind}_end`, index, block }];\n }\n\n #finish(open: OpenBlock): ContentBlock {\n if (open.kind === \"text\") return { type: \"text\", text: open.text };\n if (open.kind === \"tool_input\") {\n const wire = open.name ?? \"\";\n return {\n type: \"tool_call\",\n callId: open.callId ?? \"\",\n name: this.#names.restore(wire) ?? wire,\n input: parseToolInput(open.text, open.startInput ?? {}),\n };\n }\n const value = open.redacted === undefined ? open.signature : `${REDACTED_THINKING_PREFIX}${open.redacted}`;\n const { api, provider, id } = this.#model;\n return value\n ? { type: \"reasoning\", text: open.text, signature: { api, provider, model: id, value } }\n : { type: \"reasoning\", text: open.text };\n }\n\n #messageDelta(data: Json): ModelEvent[] {\n const delta = isObject(data.delta) ? data.delta : {};\n if (typeof delta.stop_reason === \"string\") this.#stopReason = delta.stop_reason;\n if (delta.stop_details !== undefined) this.#stopDetails = delta.stop_details;\n if (isObject(data.usage)) {\n this.#usageSeen = true;\n if (typeof data.usage.output_tokens === \"number\") this.#finalUsageSeen = true;\n }\n this.#usage = mergeUsage(this.#usage, data.usage);\n return this.#transformationWarnings(data.input_transformations ?? delta.input_transformations);\n }\n\n #messageStop(): ModelEvent[] {\n // The output limit can end a stream with a block still open; the block ends here with what arrived.\n const closing = [...this.#open.keys()].sort((a, b) => a - b).flatMap((index) => this.#close(index));\n return [...closing, ...this.#terminal()];\n }\n\n #terminal(): ModelEvent[] {\n // A finished reply always needs the final count, even one that streamed no content block.\n const { content } = this.partial();\n const usage = this.#usageWith(true);\n if (this.#stopReason === \"refusal\") {\n const details = isObject(this.#stopDetails) ? this.#stopDetails : {};\n const category = str(details.category) || \"no category\";\n const message = `refusal (${category}): ${str(details.explanation) || \"the model declined the request\"}`;\n // No `type`: failureEvent prefixes the type to the message, which already starts with \"refusal\".\n return [failureEvent(this.#model, { message, kind: \"fatal\" }, { content, usage })];\n }\n const stopReason = STOP_REASONS[this.#stopReason] ?? \"stop\";\n const warnings: Warning[] =\n this.#stopReason === \"pause_turn\"\n ? [\n {\n type: \"warning\",\n code: \"pause_turn\",\n message:\n \"The provider paused a long-running server-tool turn. This adapter dropped the turn's server-tool \" +\n \"blocks, so it cannot resume the paused turn; the reply holds only the content before the pause.\",\n },\n ]\n : [];\n return [...warnings, { type: \"done\", message: terminalMessage(this.#model, { content, usage }, stopReason) }];\n }\n}\n"]}