@supersolutions/super-chat-core 0.0.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,454 @@
1
+ import {
2
+ AgentError,
3
+ collectAnsweredIds,
4
+ dropUnanswered,
5
+ errorFromResponse,
6
+ filterNativeTools,
7
+ foreignFileText,
8
+ parseSSEJson,
9
+ repairToolArguments,
10
+ toAgentError,
11
+ withDefaultTimeout,
12
+ withRetry
13
+ } from "./chunk-32DPF33V.js";
14
+
15
+ // src/providers/anthropic/map-in.ts
16
+ var DEFAULT_MAX_TOKENS = 4096;
17
+ function toBlocks(part, providerId) {
18
+ switch (part.type) {
19
+ case "text":
20
+ return part.text ? { type: "text", text: part.text } : null;
21
+ case "reasoning":
22
+ if (part.redacted && part.signature) return { type: "redacted_thinking", data: part.signature };
23
+ if (part.signature) return { type: "thinking", thinking: part.text, signature: part.signature };
24
+ return null;
25
+ case "image": {
26
+ const s = part.source;
27
+ if (s.kind === "url") return { type: "image", source: { type: "url", url: s.url } };
28
+ if (s.kind === "base64") {
29
+ return { type: "image", source: { type: "base64", media_type: part.mediaType ?? "image/png", data: s.data } };
30
+ }
31
+ if (s.provider !== providerId) return { type: "text", text: foreignFileText("image", void 0, s) };
32
+ return { type: "image", source: { type: "file", file_id: s.id } };
33
+ }
34
+ case "file": {
35
+ const s = part.source;
36
+ if (s.kind === "url") return { type: "document", source: { type: "url", url: s.url }, ...part.filename ? { title: part.filename } : {} };
37
+ if (s.kind === "base64") {
38
+ return {
39
+ type: "document",
40
+ source: { type: "base64", media_type: part.mediaType, data: s.data },
41
+ ...part.filename ? { title: part.filename } : {}
42
+ };
43
+ }
44
+ if (s.provider !== providerId) return { type: "text", text: foreignFileText("file", part.filename, s) };
45
+ return { type: "document", source: { type: "file", file_id: s.id }, ...part.filename ? { title: part.filename } : {} };
46
+ }
47
+ case "audio":
48
+ return part.transcript ? { type: "text", text: part.transcript } : null;
49
+ case "tool-call":
50
+ return {
51
+ type: "tool_use",
52
+ id: part.callId,
53
+ name: part.name,
54
+ input: typeof part.input === "string" ? tryParse(part.input) : part.input ?? {}
55
+ };
56
+ case "tool-result":
57
+ return {
58
+ type: "tool_result",
59
+ tool_use_id: part.callId,
60
+ content: typeof part.output === "string" ? part.output : JSON.stringify(part.output ?? null),
61
+ ...part.failure ? { is_error: true } : {}
62
+ };
63
+ default:
64
+ return null;
65
+ }
66
+ }
67
+ var tryParse = (s) => {
68
+ try {
69
+ return JSON.parse(s);
70
+ } catch {
71
+ return {};
72
+ }
73
+ };
74
+ function toAnthropicMessages(messages, providerId = "anthropic") {
75
+ const out = [];
76
+ for (const m of messages) {
77
+ if (m.role === "system") continue;
78
+ const role = m.role === "assistant" ? "assistant" : "user";
79
+ const blocks = m.parts.map((p) => toBlocks(p, providerId)).filter((b) => b !== null);
80
+ if (!blocks.length) continue;
81
+ const last = out[out.length - 1];
82
+ if (last && last.role === role) last.content.push(...blocks);
83
+ else out.push({ role, content: blocks });
84
+ }
85
+ return dropOrphanToolUses(out);
86
+ }
87
+ function dropOrphanToolUses(messages) {
88
+ const answered = collectAnsweredIds(
89
+ messages.flatMap((m) => m.content),
90
+ (b) => b.type === "tool_result" ? b.tool_use_id : void 0
91
+ );
92
+ return messages.map((m) => ({
93
+ ...m,
94
+ content: dropUnanswered(m.content, answered, (b) => b.type === "tool_use" ? b.id : void 0)
95
+ })).filter((m) => m.content.length > 0);
96
+ }
97
+ function toAnthropicTools(tools) {
98
+ return tools.map((t) => ({
99
+ name: t.name,
100
+ description: t.description,
101
+ input_schema: t.parameters,
102
+ ...t.strict ? { strict: true } : {}
103
+ }));
104
+ }
105
+ function toToolChoice(req, parallel) {
106
+ const noParallel = parallel ? {} : { disable_parallel_tool_use: true };
107
+ if (req.activeTools?.length === 1 && req.tools && req.tools.length > 1) {
108
+ return { type: "tool", name: req.activeTools[0], ...noParallel };
109
+ }
110
+ if (req.activeTools?.length === 0) return { type: "none" };
111
+ switch (req.toolChoice?.type) {
112
+ case "none":
113
+ return { type: "none" };
114
+ case "required":
115
+ return { type: "any", ...noParallel };
116
+ case "tool":
117
+ return { type: "tool", name: req.toolChoice.name, ...noParallel };
118
+ default:
119
+ return parallel ? { type: "auto" } : { type: "auto", disable_parallel_tool_use: true };
120
+ }
121
+ }
122
+ var EFFORT = {
123
+ minimal: "low",
124
+ low: "low",
125
+ medium: "medium",
126
+ high: "high"
127
+ };
128
+ function buildAnthropicRequest(req, opts = {}) {
129
+ const providerId = opts.providerId ?? "anthropic";
130
+ const systemFromMessages = req.messages.filter((m) => m.role === "system").flatMap((m) => m.parts.filter((p) => p.type === "text").map((p) => p.text)).join("\n\n");
131
+ const system = [req.system, systemFromMessages].filter(Boolean).join("\n\n") || void 0;
132
+ const out = {
133
+ model: req.model,
134
+ max_tokens: req.maxOutputTokens ?? opts.defaultMaxTokens ?? DEFAULT_MAX_TOKENS,
135
+ messages: toAnthropicMessages(req.messages, providerId)
136
+ };
137
+ if (system) out.system = system;
138
+ const nativeTools = filterNativeTools(req.providerTools?.[providerId]);
139
+ if (req.tools?.length || nativeTools.length) {
140
+ out.tools = [...req.tools?.length ? toAnthropicTools(req.tools) : [], ...nativeTools];
141
+ if (req.tools?.length) {
142
+ const choice = toToolChoice(req, opts.parallelToolCalls !== false);
143
+ if (choice) out.tool_choice = choice;
144
+ }
145
+ }
146
+ if (req.reasoning) {
147
+ out.thinking = {
148
+ type: "adaptive",
149
+ ...req.reasoning.summary && req.reasoning.summary !== "none" ? { display: "summarized" } : {}
150
+ };
151
+ const effort = req.reasoning.effort ? EFFORT[req.reasoning.effort] : void 0;
152
+ if (effort) out.output_config = { ...out.output_config ?? {}, effort };
153
+ }
154
+ if (req.responseFormat?.type === "json_schema") {
155
+ out.output_config = {
156
+ ...out.output_config ?? {},
157
+ format: { type: "json_schema", schema: req.responseFormat.schema }
158
+ };
159
+ }
160
+ if (req.temperature != null) out.temperature = req.temperature;
161
+ if (req.topP != null) out.top_p = req.topP;
162
+ if (req.stopSequences?.length) out.stop_sequences = req.stopSequences;
163
+ if (opts.stream) out.stream = true;
164
+ const extra = req.providerOptions?.[providerId];
165
+ if (extra) Object.assign(out, extra);
166
+ return out;
167
+ }
168
+
169
+ // src/providers/anthropic/map-out.ts
170
+ function partsFromAnthropic(response) {
171
+ const parts = [];
172
+ for (const block of response.content) {
173
+ switch (block.type) {
174
+ case "text":
175
+ parts.push({ type: "text", text: block.text });
176
+ break;
177
+ case "thinking":
178
+ parts.push({ type: "reasoning", text: block.thinking, ...block.signature ? { signature: block.signature } : {} });
179
+ break;
180
+ case "redacted_thinking":
181
+ parts.push({ type: "reasoning", text: "", signature: block.data, redacted: true });
182
+ break;
183
+ case "tool_use":
184
+ parts.push({ type: "tool-call", callId: block.id, name: block.name, input: block.input, status: "pending" });
185
+ break;
186
+ default: {
187
+ const record = block;
188
+ if (record.type === "tool_result") break;
189
+ parts.push({
190
+ type: "artifact",
191
+ id: record.id ?? `${record.type}_${parts.length}`,
192
+ kind: `provider-tool:${record.type}`,
193
+ data: record
194
+ });
195
+ break;
196
+ }
197
+ }
198
+ }
199
+ return parts;
200
+ }
201
+ function finishFromAnthropic(reason) {
202
+ switch (reason) {
203
+ case "end_turn":
204
+ case "stop_sequence":
205
+ case "pause_turn":
206
+ return "stop";
207
+ case "max_tokens":
208
+ case "model_context_window_exceeded":
209
+ return "length";
210
+ case "tool_use":
211
+ return "tool-calls";
212
+ case "refusal":
213
+ return "content-filter";
214
+ default:
215
+ return "unknown";
216
+ }
217
+ }
218
+ function usageFromAnthropic(usage) {
219
+ if (!usage) return {};
220
+ const input = usage.input_tokens ?? 0;
221
+ const output = usage.output_tokens ?? 0;
222
+ return {
223
+ inputTokens: input,
224
+ outputTokens: output,
225
+ totalTokens: input + output,
226
+ ...usage.cache_read_input_tokens != null ? { cachedInputTokens: usage.cache_read_input_tokens } : {}
227
+ };
228
+ }
229
+
230
+ // src/providers/anthropic/stream.ts
231
+ async function* streamAnthropic(body) {
232
+ const toolsByIndex = /* @__PURE__ */ new Map();
233
+ let inputUsage;
234
+ let outputUsage;
235
+ let stopReason = null;
236
+ for await (const frame of parseSSEJson(body)) {
237
+ const event = frame.data;
238
+ switch (event.type) {
239
+ case "message_start":
240
+ inputUsage = event.message.usage;
241
+ yield { type: "start", responseId: event.message.id, modelId: event.message.model };
242
+ break;
243
+ case "content_block_start": {
244
+ if (event.content_block.type === "tool_use") {
245
+ const pending = {
246
+ callId: event.content_block.id,
247
+ name: event.content_block.name,
248
+ // `input` on the start block is {} — args stream via input_json_delta.
249
+ args: ""
250
+ };
251
+ toolsByIndex.set(event.index, pending);
252
+ yield { type: "tool-call-start", callId: pending.callId, name: pending.name };
253
+ }
254
+ break;
255
+ }
256
+ case "content_block_delta": {
257
+ const delta = event.delta;
258
+ if (delta.type === "text_delta") {
259
+ yield { type: "text-delta", delta: delta.text };
260
+ } else if (delta.type === "thinking_delta") {
261
+ yield { type: "reasoning-delta", delta: delta.thinking };
262
+ } else if (delta.type === "signature_delta") {
263
+ yield { type: "reasoning-delta", delta: "", signature: delta.signature };
264
+ } else if (delta.type === "input_json_delta") {
265
+ const pending = toolsByIndex.get(event.index);
266
+ if (pending) {
267
+ pending.args += delta.partial_json;
268
+ yield { type: "tool-call-delta", callId: pending.callId, argsDelta: delta.partial_json };
269
+ }
270
+ }
271
+ break;
272
+ }
273
+ case "content_block_stop": {
274
+ const pending = toolsByIndex.get(event.index);
275
+ if (pending) {
276
+ const { value, repaired } = repairToolArguments(pending.args || "{}");
277
+ yield { type: "tool-call-end", callId: pending.callId, name: pending.name, input: value, repaired };
278
+ toolsByIndex.delete(event.index);
279
+ }
280
+ break;
281
+ }
282
+ case "message_delta":
283
+ if (event.delta.stop_reason) stopReason = event.delta.stop_reason;
284
+ if (event.usage) outputUsage = event.usage;
285
+ break;
286
+ case "message_stop": {
287
+ const usage2 = usageFromAnthropic({ ...inputUsage ?? {}, ...outputUsage ?? {} });
288
+ yield { type: "usage", usage: usage2 };
289
+ yield { type: "finish", finishReason: finishFromAnthropic(stopReason), usage: usage2 };
290
+ return;
291
+ }
292
+ case "error":
293
+ yield { type: "error", error: new Error(event.error.message) };
294
+ return;
295
+ default:
296
+ break;
297
+ }
298
+ }
299
+ for (const pending of toolsByIndex.values()) {
300
+ const { value, repaired } = repairToolArguments(pending.args || "{}");
301
+ yield { type: "tool-call-end", callId: pending.callId, name: pending.name, input: value, repaired };
302
+ }
303
+ const usage = usageFromAnthropic({ ...inputUsage ?? {}, ...outputUsage ?? {} });
304
+ yield { type: "usage", usage };
305
+ yield { type: "finish", finishReason: finishFromAnthropic(stopReason), usage };
306
+ }
307
+
308
+ // src/providers/anthropic/adapter.ts
309
+ var ANTHROPIC_CAPS = {
310
+ streaming: true,
311
+ backgroundJobs: false,
312
+ resumableStreams: false,
313
+ tools: true,
314
+ parallelToolCalls: true,
315
+ images: true,
316
+ files: true,
317
+ // document blocks (PDF etc.)
318
+ audio: false,
319
+ reasoning: true,
320
+ strictJsonSchema: true,
321
+ serverSideHistory: false,
322
+ fileUpload: false
323
+ // Files API is beta; not implemented here
324
+ };
325
+ var ANTHROPIC_MODELS = [
326
+ { id: "claude-opus-5", label: "Claude Opus 5", contextWindow: 1e6, maxOutputTokens: 128e3 },
327
+ { id: "claude-sonnet-5", label: "Claude Sonnet 5", contextWindow: 1e6, maxOutputTokens: 128e3 },
328
+ { id: "claude-haiku-4-5", label: "Claude Haiku 4.5", contextWindow: 2e5, maxOutputTokens: 64e3 }
329
+ ];
330
+ function createAnthropicProvider(config) {
331
+ const id = config.id ?? "anthropic";
332
+ const version = config.version ?? "2023-06-01";
333
+ const capabilities = { ...ANTHROPIC_CAPS, ...config.capabilities };
334
+ async function call(body, opts, extra = {}) {
335
+ const signal = withDefaultTimeout(opts?.signal);
336
+ return withRetry(
337
+ async () => {
338
+ const res = await config.transport.fetch({
339
+ provider: id,
340
+ path: "/messages",
341
+ method: "POST",
342
+ body,
343
+ stream: extra.stream,
344
+ headers: {
345
+ "anthropic-version": version,
346
+ ...extra.betas?.length ? { "anthropic-beta": extra.betas.join(",") } : {},
347
+ ...opts?.headers
348
+ },
349
+ signal
350
+ });
351
+ if (!res.ok) throw await errorFromResponse(res, id);
352
+ return res;
353
+ },
354
+ { policy: config.retry, signal, provider: id }
355
+ );
356
+ }
357
+ function scanRequest(req) {
358
+ let hasImage = false;
359
+ let hasSilentAudio = false;
360
+ let usesOwnFiles = false;
361
+ for (const m of req.messages) {
362
+ for (const p of m.parts) {
363
+ if (p.type === "image") {
364
+ hasImage = true;
365
+ if (p.source.kind === "providerFile" && p.source.provider === id) usesOwnFiles = true;
366
+ } else if (p.type === "file") {
367
+ if (p.source.kind === "providerFile" && p.source.provider === id) usesOwnFiles = true;
368
+ } else if (p.type === "audio" && !p.transcript) {
369
+ hasSilentAudio = true;
370
+ }
371
+ }
372
+ }
373
+ return { hasImage, hasSilentAudio, usesOwnFiles };
374
+ }
375
+ function guardRequest(req, scan) {
376
+ if (req.background) {
377
+ throw new AgentError("not-supported", `Provider "${id}" has no background mode. Use streaming or sync.`, {
378
+ provider: id
379
+ });
380
+ }
381
+ if (req.responseFormat && req.responseFormat.type === "json") {
382
+ throw new AgentError(
383
+ "not-supported",
384
+ `Provider "${id}" supports responseFormat "json_schema", not bare "json". Provide a schema.`,
385
+ { provider: id }
386
+ );
387
+ }
388
+ if (!capabilities.images && scan.hasImage) {
389
+ throw new AgentError("not-supported", `Provider "${id}" does not accept image parts.`, { provider: id });
390
+ }
391
+ if (!capabilities.audio && scan.hasSilentAudio) {
392
+ throw new AgentError("not-supported", `Provider "${id}" does not accept audio parts.`, { provider: id });
393
+ }
394
+ }
395
+ const buildOpts = (stream) => ({
396
+ ...stream ? { stream: true } : {},
397
+ providerId: id,
398
+ parallelToolCalls: capabilities.parallelToolCalls,
399
+ defaultMaxTokens: config.defaultMaxTokens
400
+ });
401
+ const applyCapabilities = (req) => capabilities.strictJsonSchema || !req.tools?.some((t) => t.strict) ? req : { ...req, tools: req.tools.map(({ strict: _strict, ...t }) => t) };
402
+ const betasFor = (scan) => scan.usesOwnFiles ? ["files-api-2025-04-14"] : [];
403
+ return {
404
+ id,
405
+ label: config.label ?? "Anthropic",
406
+ capabilities,
407
+ transport: config.transport,
408
+ async generate(rawReq, opts) {
409
+ const scan = scanRequest(rawReq);
410
+ guardRequest(rawReq, scan);
411
+ const req = applyCapabilities(rawReq);
412
+ const res = await call(buildAnthropicRequest(req, buildOpts()), opts, { betas: betasFor(scan) });
413
+ const json = await res.json();
414
+ return {
415
+ parts: partsFromAnthropic(json),
416
+ finishReason: finishFromAnthropic(json.stop_reason),
417
+ usage: usageFromAnthropic(json.usage),
418
+ responseId: json.id,
419
+ modelId: json.model,
420
+ raw: json
421
+ };
422
+ },
423
+ async *stream(rawReq, opts) {
424
+ const scan = scanRequest(rawReq);
425
+ guardRequest(rawReq, scan);
426
+ const req = applyCapabilities(rawReq);
427
+ try {
428
+ const res = await call(buildAnthropicRequest(req, buildOpts(true)), opts, {
429
+ stream: true,
430
+ betas: betasFor(scan)
431
+ });
432
+ if (!res.body) throw new AgentError("network", "Response had no body to stream.", { provider: id });
433
+ yield* streamAnthropic(res.body);
434
+ } catch (e) {
435
+ yield { type: "error", error: toAgentError(e, id) };
436
+ }
437
+ },
438
+ async listModels() {
439
+ return config.models ?? ANTHROPIC_MODELS;
440
+ }
441
+ };
442
+ }
443
+
444
+ export {
445
+ toAnthropicMessages,
446
+ dropOrphanToolUses,
447
+ buildAnthropicRequest,
448
+ partsFromAnthropic,
449
+ finishFromAnthropic,
450
+ usageFromAnthropic,
451
+ streamAnthropic,
452
+ createAnthropicProvider
453
+ };
454
+ //# sourceMappingURL=chunk-JMM3X3GB.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/providers/anthropic/map-in.ts","../src/providers/anthropic/map-out.ts","../src/providers/anthropic/stream.ts","../src/providers/anthropic/adapter.ts"],"sourcesContent":["// Normalized request → Anthropic Messages wire.\n//\n// Structural differences from the OpenAI builders that matter here:\n// • Tool CALLS are `tool_use` blocks inside the assistant message; tool\n// RESULTS are `tool_result` blocks inside the FOLLOWING USER message.\n// • Thinking replays as a `thinking` block with its `signature` — and only\n// with one; a reasoning part without a signature is display-only.\n// • `max_tokens` is required and caps thinking + text together.\n\nimport type { ContentPart, Message } from \"../../content/types.js\";\nimport type { NormalizedRequest, ToolSpec } from \"../types.js\";\nimport { collectAnsweredIds, dropUnanswered, filterNativeTools, foreignFileText } from \"../shared.js\";\nimport type {\n AnthropicContentBlock,\n AnthropicMessage,\n AnthropicRequest,\n AnthropicTool,\n AnthropicToolChoice,\n} from \"./wire.js\";\n\nexport type AnthropicBuildOptions = {\n stream?: boolean;\n providerId?: string;\n parallelToolCalls?: boolean;\n /** Applied when the request carries no maxOutputTokens (`max_tokens` is required). */\n defaultMaxTokens?: number;\n};\n\nconst DEFAULT_MAX_TOKENS = 4096;\n\nfunction toBlocks(part: ContentPart, providerId: string): AnthropicContentBlock | null {\n switch (part.type) {\n case \"text\":\n return part.text ? { type: \"text\", text: part.text } : null;\n case \"reasoning\":\n // Replayable only with its signature; redacted blocks round-trip via the\n // signature field where the opaque payload was stashed on the way out.\n if (part.redacted && part.signature) return { type: \"redacted_thinking\", data: part.signature };\n if (part.signature) return { type: \"thinking\", thinking: part.text, signature: part.signature };\n return null;\n case \"image\": {\n const s = part.source;\n if (s.kind === \"url\") return { type: \"image\", source: { type: \"url\", url: s.url } };\n if (s.kind === \"base64\") {\n return { type: \"image\", source: { type: \"base64\", media_type: part.mediaType ?? \"image/png\", data: s.data } };\n }\n if (s.provider !== providerId) return { type: \"text\", text: foreignFileText(\"image\", undefined, s) };\n return { type: \"image\", source: { type: \"file\", file_id: s.id } };\n }\n case \"file\": {\n const s = part.source;\n if (s.kind === \"url\") return { type: \"document\", source: { type: \"url\", url: s.url }, ...(part.filename ? { title: part.filename } : {}) };\n if (s.kind === \"base64\") {\n return {\n type: \"document\",\n source: { type: \"base64\", media_type: part.mediaType, data: s.data },\n ...(part.filename ? { title: part.filename } : {}),\n };\n }\n if (s.provider !== providerId) return { type: \"text\", text: foreignFileText(\"file\", part.filename, s) };\n return { type: \"document\", source: { type: \"file\", file_id: s.id }, ...(part.filename ? { title: part.filename } : {}) };\n }\n case \"audio\":\n // No audio input on the Messages API; surface the transcript.\n return part.transcript ? { type: \"text\", text: part.transcript } : null;\n case \"tool-call\":\n return {\n type: \"tool_use\",\n id: part.callId,\n name: part.name,\n input: typeof part.input === \"string\" ? tryParse(part.input) : (part.input ?? {}),\n };\n case \"tool-result\":\n return {\n type: \"tool_result\",\n tool_use_id: part.callId,\n content: typeof part.output === \"string\" ? part.output : JSON.stringify(part.output ?? null),\n ...(part.failure ? { is_error: true } : {}),\n };\n default:\n return null; // artifact parts are UI-only\n }\n}\n\nconst tryParse = (s: string): unknown => {\n try {\n return JSON.parse(s);\n } catch {\n return {};\n }\n};\n\n/**\n * Fold normalized messages into Anthropic's user/assistant alternation.\n * System messages are hoisted by the caller; `tool` role messages become USER\n * messages carrying tool_result blocks (the wire has no tool role). Adjacent\n * same-role messages merge — cheap, and robust to strict-alternation servers.\n */\nexport function toAnthropicMessages(messages: readonly Message[], providerId = \"anthropic\"): AnthropicMessage[] {\n const out: AnthropicMessage[] = [];\n\n for (const m of messages) {\n if (m.role === \"system\") continue;\n const role: \"user\" | \"assistant\" = m.role === \"assistant\" ? \"assistant\" : \"user\";\n const blocks = m.parts.map((p) => toBlocks(p, providerId)).filter((b): b is AnthropicContentBlock => b !== null);\n if (!blocks.length) continue;\n\n const last = out[out.length - 1];\n if (last && last.role === role) last.content.push(...blocks);\n else out.push({ role, content: blocks });\n }\n\n return dropOrphanToolUses(out);\n}\n\n/**\n * Same orphan rule as OpenAI: a `tool_use` with no `tool_result` in the next\n * user message 400s the whole request. A cancelled turn leaves exactly that in\n * persisted history, so prune rather than letting one lost step poison the\n * thread forever.\n */\nexport function dropOrphanToolUses(messages: AnthropicMessage[]): AnthropicMessage[] {\n const answered = collectAnsweredIds(\n messages.flatMap((m) => m.content),\n (b) => (b.type === \"tool_result\" ? b.tool_use_id : undefined),\n );\n return messages\n .map((m) => ({\n ...m,\n content: dropUnanswered(m.content, answered, (b) => (b.type === \"tool_use\" ? b.id : undefined)),\n }))\n .filter((m) => m.content.length > 0);\n}\n\nfunction toAnthropicTools(tools: readonly ToolSpec[]): AnthropicTool[] {\n return tools.map((t) => ({\n name: t.name,\n description: t.description,\n input_schema: t.parameters as Record<string, unknown>,\n ...(t.strict ? { strict: true } : {}),\n }));\n}\n\nfunction toToolChoice(req: NormalizedRequest, parallel: boolean): AnthropicToolChoice | undefined {\n const noParallel = parallel ? {} : { disable_parallel_tool_use: true };\n // `activeTools` narrows like the OpenAI builder: a single active tool forces it.\n if (req.activeTools?.length === 1 && req.tools && req.tools.length > 1) {\n return { type: \"tool\", name: req.activeTools[0]!, ...noParallel };\n }\n if (req.activeTools?.length === 0) return { type: \"none\" };\n switch (req.toolChoice?.type) {\n case \"none\":\n return { type: \"none\" };\n case \"required\":\n return { type: \"any\", ...noParallel };\n case \"tool\":\n return { type: \"tool\", name: req.toolChoice.name, ...noParallel };\n default:\n return parallel ? { type: \"auto\" } : { type: \"auto\", disable_parallel_tool_use: true };\n }\n}\n\nconst EFFORT: Record<string, NonNullable<AnthropicRequest[\"output_config\"]>[\"effort\"]> = {\n minimal: \"low\",\n low: \"low\",\n medium: \"medium\",\n high: \"high\",\n};\n\nexport function buildAnthropicRequest(req: NormalizedRequest, opts: AnthropicBuildOptions = {}): AnthropicRequest {\n const providerId = opts.providerId ?? \"anthropic\";\n\n const systemFromMessages = req.messages\n .filter((m) => m.role === \"system\")\n .flatMap((m) => m.parts.filter((p) => p.type === \"text\").map((p) => (p as { text: string }).text))\n .join(\"\\n\\n\");\n const system = [req.system, systemFromMessages].filter(Boolean).join(\"\\n\\n\") || undefined;\n\n const out: AnthropicRequest = {\n model: req.model,\n max_tokens: req.maxOutputTokens ?? opts.defaultMaxTokens ?? DEFAULT_MAX_TOKENS,\n messages: toAnthropicMessages(req.messages, providerId),\n };\n if (system) out.system = system;\n\n // Provider-hosted tools (web search, code execution) share the tools array\n // with function tools and are appended verbatim — the vendor owns the shape.\n const nativeTools = filterNativeTools(req.providerTools?.[providerId]);\n if (req.tools?.length || nativeTools.length) {\n out.tools = [...(req.tools?.length ? toAnthropicTools(req.tools) : []), ...nativeTools] as AnthropicTool[];\n if (req.tools?.length) {\n const choice = toToolChoice(req, opts.parallelToolCalls !== false);\n if (choice) out.tool_choice = choice;\n }\n }\n\n if (req.reasoning) {\n // Current models: adaptive thinking + effort — never budget_tokens (400s\n // on Opus 4.7+). `summary` opt-in maps to display: \"summarized\" so hosts\n // that render reasoning actually receive text.\n out.thinking = {\n type: \"adaptive\",\n ...(req.reasoning.summary && req.reasoning.summary !== \"none\" ? { display: \"summarized\" as const } : {}),\n };\n const effort = req.reasoning.effort ? EFFORT[req.reasoning.effort] : undefined;\n if (effort) out.output_config = { ...(out.output_config ?? {}), effort };\n }\n\n if (req.responseFormat?.type === \"json_schema\") {\n out.output_config = {\n ...(out.output_config ?? {}),\n format: { type: \"json_schema\", schema: req.responseFormat.schema as Record<string, unknown> },\n };\n }\n\n // Sampling params are caller-set pass-throughs. NOTE: models from Opus 4.7\n // on REJECT them — leave unset unless the target model accepts them.\n if (req.temperature != null) out.temperature = req.temperature;\n if (req.topP != null) out.top_p = req.topP;\n if (req.stopSequences?.length) out.stop_sequences = req.stopSequences;\n if (opts.stream) out.stream = true;\n\n const extra = req.providerOptions?.[providerId];\n if (extra) Object.assign(out, extra);\n return out;\n}\n\n/** Whether any message references a providerFile minted by THIS provider (needs the Files beta header). */\nexport function usesOwnFiles(req: NormalizedRequest, providerId: string): boolean {\n return req.messages.some((m) =>\n m.parts.some(\n (p) =>\n (p.type === \"file\" || p.type === \"image\") &&\n p.source.kind === \"providerFile\" &&\n p.source.provider === providerId,\n ),\n );\n}\n","// Anthropic wire → normalized parts.\n\nimport type { ContentPart, FinishReason, Usage } from \"../../content/types.js\";\nimport type { AnthropicResponse, AnthropicStopReason, AnthropicUsage } from \"./wire.js\";\n\nexport function partsFromAnthropic(response: AnthropicResponse): ContentPart[] {\n const parts: ContentPart[] = [];\n for (const block of response.content) {\n switch (block.type) {\n case \"text\":\n parts.push({ type: \"text\", text: block.text });\n break;\n case \"thinking\":\n // The signature is the replay token — without it the block can never\n // be echoed back, so keep it on the part.\n parts.push({ type: \"reasoning\", text: block.thinking, ...(block.signature ? { signature: block.signature } : {}) });\n break;\n case \"redacted_thinking\":\n // Opaque payload rides in `signature` so map-in can round-trip it.\n parts.push({ type: \"reasoning\", text: \"\", signature: block.data, redacted: true });\n break;\n case \"tool_use\":\n parts.push({ type: \"tool-call\", callId: block.id, name: block.name, input: block.input, status: \"pending\" });\n break;\n default: {\n // `tool_result` never appears in an assistant response, so anything\n // else here is a PROVIDER-HOSTED tool record (server_tool_use,\n // web_search_tool_result, …): work done provider-side with no call for\n // us to execute. Surface it as a UI-only artifact so the transcript\n // shows the search happened; it is stripped before the next request.\n const record = block as { type: string; id?: string };\n if (record.type === \"tool_result\") break;\n parts.push({\n type: \"artifact\",\n id: record.id ?? `${record.type}_${parts.length}`,\n kind: `provider-tool:${record.type}`,\n data: record,\n });\n break;\n }\n }\n }\n return parts;\n}\n\nexport function finishFromAnthropic(reason: AnthropicStopReason | null | undefined): FinishReason {\n switch (reason) {\n case \"end_turn\":\n case \"stop_sequence\":\n case \"pause_turn\":\n return \"stop\";\n case \"max_tokens\":\n case \"model_context_window_exceeded\":\n return \"length\";\n case \"tool_use\":\n return \"tool-calls\";\n case \"refusal\":\n return \"content-filter\";\n default:\n return \"unknown\";\n }\n}\n\nexport function usageFromAnthropic(usage: AnthropicUsage | undefined): Usage {\n if (!usage) return {};\n const input = usage.input_tokens ?? 0;\n const output = usage.output_tokens ?? 0;\n return {\n inputTokens: input,\n outputTokens: output,\n totalTokens: input + output,\n ...(usage.cache_read_input_tokens != null ? { cachedInputTokens: usage.cache_read_input_tokens } : {}),\n };\n}\n","// Anthropic SSE dialect → normalized StreamEvents.\n//\n// Shape of the stream: message_start, then per content block a\n// content_block_start / *_delta / *_stop trio (indexed), then message_delta\n// (stop_reason + output usage) and message_stop. Deltas are typed:\n// text_delta, thinking_delta, signature_delta (the thinking replay token,\n// arriving at the END of a thinking block), input_json_delta (tool args).\n\nimport { parseSSEJson } from \"../../transport/sse.js\";\nimport { repairToolArguments } from \"../../tools/repair.js\";\nimport type { StreamEvent } from \"../types.js\";\nimport { finishFromAnthropic, usageFromAnthropic } from \"./map-out.js\";\nimport type { AnthropicStreamEvent, AnthropicUsage } from \"./wire.js\";\n\nexport async function* streamAnthropic(body: ReadableStream<Uint8Array>): AsyncGenerator<StreamEvent> {\n type PendingTool = { callId: string; name: string; args: string };\n const toolsByIndex = new Map<number, PendingTool>();\n let inputUsage: AnthropicUsage | undefined;\n let outputUsage: AnthropicUsage | undefined;\n let stopReason: Parameters<typeof finishFromAnthropic>[0] = null;\n\n for await (const frame of parseSSEJson<AnthropicStreamEvent>(body)) {\n const event = frame.data;\n switch (event.type) {\n case \"message_start\":\n inputUsage = event.message.usage;\n yield { type: \"start\", responseId: event.message.id, modelId: event.message.model };\n break;\n\n case \"content_block_start\": {\n if (event.content_block.type === \"tool_use\") {\n const pending: PendingTool = {\n callId: event.content_block.id,\n name: event.content_block.name,\n // `input` on the start block is {} — args stream via input_json_delta.\n args: \"\",\n };\n toolsByIndex.set(event.index, pending);\n yield { type: \"tool-call-start\", callId: pending.callId, name: pending.name };\n }\n break;\n }\n\n case \"content_block_delta\": {\n const delta = event.delta;\n if (delta.type === \"text_delta\") {\n yield { type: \"text-delta\", delta: delta.text };\n } else if (delta.type === \"thinking_delta\") {\n yield { type: \"reasoning-delta\", delta: delta.thinking };\n } else if (delta.type === \"signature_delta\") {\n // The replay token arrives at the end of the thinking block. Emit an\n // empty reasoning delta carrying it — the collector stamps it onto\n // the accumulated reasoning part.\n yield { type: \"reasoning-delta\", delta: \"\", signature: delta.signature };\n } else if (delta.type === \"input_json_delta\") {\n const pending = toolsByIndex.get(event.index);\n if (pending) {\n pending.args += delta.partial_json;\n yield { type: \"tool-call-delta\", callId: pending.callId, argsDelta: delta.partial_json };\n }\n }\n break;\n }\n\n case \"content_block_stop\": {\n const pending = toolsByIndex.get(event.index);\n if (pending) {\n const { value, repaired } = repairToolArguments(pending.args || \"{}\");\n yield { type: \"tool-call-end\", callId: pending.callId, name: pending.name, input: value, repaired };\n toolsByIndex.delete(event.index);\n }\n break;\n }\n\n case \"message_delta\":\n if (event.delta.stop_reason) stopReason = event.delta.stop_reason;\n if (event.usage) outputUsage = event.usage;\n break;\n\n case \"message_stop\": {\n // Input tokens arrive on message_start, output tokens on message_delta —\n // merge before reporting, or every streamed turn meters as zero input.\n const usage = usageFromAnthropic({ ...(inputUsage ?? {}), ...(outputUsage ?? {}) });\n yield { type: \"usage\", usage };\n yield { type: \"finish\", finishReason: finishFromAnthropic(stopReason), usage };\n return;\n }\n\n case \"error\":\n yield { type: \"error\", error: new Error(event.error.message) };\n return;\n\n default:\n break; // ping and future event types\n }\n }\n\n // Stream ended without message_stop (dropped connection). Close out what we\n // have rather than leaving the consumer's reducer half-applied.\n for (const pending of toolsByIndex.values()) {\n const { value, repaired } = repairToolArguments(pending.args || \"{}\");\n yield { type: \"tool-call-end\", callId: pending.callId, name: pending.name, input: value, repaired };\n }\n const usage = usageFromAnthropic({ ...(inputUsage ?? {}), ...(outputUsage ?? {}) });\n yield { type: \"usage\", usage };\n yield { type: \"finish\", finishReason: finishFromAnthropic(stopReason), usage };\n}\n","// The Anthropic provider — the second adapter, and the real test of whether\n// the normalized content model holds up (HANDOFF said it would be).\n//\n// Everything speaks POST /messages. There is no background mode, no\n// server-side history, no /files upload here (the Files API is beta and out of\n// scope) — the capabilities object says so instead of the adapter pretending.\n//\n// Auth note: Anthropic wants `x-api-key` (not `Authorization: Bearer`) plus an\n// `anthropic-version` header on every call. The version header is attached\n// per-request below; the key belongs to the transport — use\n// `authStyle: \"x-api-key\"` on a direct transport or proxy provider entry.\n\nimport { AgentError, toAgentError } from \"../../errors.js\";\nimport { errorFromResponse, withRetry } from \"../../transport/retry.js\";\nimport type { RetryPolicy, Transport } from \"../../transport/types.js\";\nimport { withDefaultTimeout } from \"../shared.js\";\nimport type {\n CallOptions,\n GenerateResult,\n ModelInfo,\n NormalizedRequest,\n Provider,\n ProviderCapabilities,\n StreamEvent,\n} from \"../types.js\";\nimport { buildAnthropicRequest } from \"./map-in.js\";\nimport { finishFromAnthropic, partsFromAnthropic, usageFromAnthropic } from \"./map-out.js\";\nimport { streamAnthropic } from \"./stream.js\";\nimport type { AnthropicResponse } from \"./wire.js\";\n\nexport type AnthropicProviderConfig = {\n transport: Transport;\n /** Provider id, so several instances can coexist. Defaults to \"anthropic\". */\n id?: string;\n label?: string;\n retry?: RetryPolicy;\n capabilities?: Partial<ProviderCapabilities>;\n models?: ModelInfo[];\n /** `anthropic-version` header value. */\n version?: string;\n /** `max_tokens` is REQUIRED on this wire; applied when the request has none. */\n defaultMaxTokens?: number;\n};\n\nconst ANTHROPIC_CAPS: ProviderCapabilities = {\n streaming: true,\n backgroundJobs: false,\n resumableStreams: false,\n tools: true,\n parallelToolCalls: true,\n images: true,\n files: true, // document blocks (PDF etc.)\n audio: false,\n reasoning: true,\n strictJsonSchema: true,\n serverSideHistory: false,\n fileUpload: false, // Files API is beta; not implemented here\n};\n\nconst ANTHROPIC_MODELS: ModelInfo[] = [\n { id: \"claude-opus-5\", label: \"Claude Opus 5\", contextWindow: 1_000_000, maxOutputTokens: 128_000 },\n { id: \"claude-sonnet-5\", label: \"Claude Sonnet 5\", contextWindow: 1_000_000, maxOutputTokens: 128_000 },\n { id: \"claude-haiku-4-5\", label: \"Claude Haiku 4.5\", contextWindow: 200_000, maxOutputTokens: 64_000 },\n];\n\nexport function createAnthropicProvider(config: AnthropicProviderConfig): Provider {\n const id = config.id ?? \"anthropic\";\n const version = config.version ?? \"2023-06-01\";\n const capabilities: ProviderCapabilities = { ...ANTHROPIC_CAPS, ...config.capabilities };\n\n async function call(\n body: unknown,\n opts: CallOptions | undefined,\n extra: { stream?: boolean; betas?: string[] } = {},\n ): Promise<Response> {\n // A caller that never passes (or triggers) its own signal must not hang\n // forever on a stalled connection — the default timeout is a floor, not a\n // ceiling: whichever of the two signals fires first wins.\n const signal = withDefaultTimeout(opts?.signal);\n return withRetry(\n async () => {\n const res = await config.transport.fetch({\n provider: id,\n path: \"/messages\",\n method: \"POST\",\n body,\n stream: extra.stream,\n headers: {\n \"anthropic-version\": version,\n ...(extra.betas?.length ? { \"anthropic-beta\": extra.betas.join(\",\") } : {}),\n ...opts?.headers,\n },\n signal,\n });\n if (!res.ok) throw await errorFromResponse(res, id);\n return res;\n },\n { policy: config.retry, signal, provider: id },\n );\n }\n\n /** Everything `guardRequest` and `betasFor` need, computed in one pass over every part. */\n type MediaScan = { hasImage: boolean; hasSilentAudio: boolean; usesOwnFiles: boolean };\n\n /**\n * `guardRequest`'s per-type capability checks and `betasFor`'s \"does this\n * request reference a file this provider instance minted\" check used to\n * each rescan the whole message list independently — up to three full\n * walks of the same parts per call. One pass computes all of it together.\n */\n function scanRequest(req: NormalizedRequest): MediaScan {\n let hasImage = false;\n let hasSilentAudio = false;\n let usesOwnFiles = false;\n for (const m of req.messages) {\n for (const p of m.parts) {\n if (p.type === \"image\") {\n hasImage = true;\n if (p.source.kind === \"providerFile\" && p.source.provider === id) usesOwnFiles = true;\n } else if (p.type === \"file\") {\n if (p.source.kind === \"providerFile\" && p.source.provider === id) usesOwnFiles = true;\n } else if (p.type === \"audio\" && !p.transcript) {\n hasSilentAudio = true;\n }\n }\n }\n return { hasImage, hasSilentAudio, usesOwnFiles };\n }\n\n function guardRequest(req: NormalizedRequest, scan: MediaScan) {\n if (req.background) {\n throw new AgentError(\"not-supported\", `Provider \"${id}\" has no background mode. Use streaming or sync.`, {\n provider: id,\n });\n }\n if (req.responseFormat && req.responseFormat.type === \"json\") {\n throw new AgentError(\n \"not-supported\",\n `Provider \"${id}\" supports responseFormat \"json_schema\", not bare \"json\". Provide a schema.`,\n { provider: id },\n );\n }\n if (!capabilities.images && scan.hasImage) {\n throw new AgentError(\"not-supported\", `Provider \"${id}\" does not accept image parts.`, { provider: id });\n }\n // Audio degrades to transcript text in the builder; only refuse when\n // there is a part with nothing to degrade to.\n if (!capabilities.audio && scan.hasSilentAudio) {\n throw new AgentError(\"not-supported\", `Provider \"${id}\" does not accept audio parts.`, { provider: id });\n }\n }\n\n const buildOpts = (stream?: boolean) => ({\n ...(stream ? { stream: true } : {}),\n providerId: id,\n parallelToolCalls: capabilities.parallelToolCalls,\n defaultMaxTokens: config.defaultMaxTokens,\n });\n\n const applyCapabilities = (req: NormalizedRequest): NormalizedRequest =>\n capabilities.strictJsonSchema || !req.tools?.some((t) => t.strict)\n ? req\n : { ...req, tools: req.tools!.map(({ strict: _strict, ...t }) => t) };\n\n const betasFor = (scan: MediaScan): string[] => (scan.usesOwnFiles ? [\"files-api-2025-04-14\"] : []);\n\n return {\n id,\n label: config.label ?? \"Anthropic\",\n capabilities,\n transport: config.transport,\n\n async generate(rawReq, opts): Promise<GenerateResult> {\n const scan = scanRequest(rawReq);\n guardRequest(rawReq, scan);\n const req = applyCapabilities(rawReq);\n const res = await call(buildAnthropicRequest(req, buildOpts()), opts, { betas: betasFor(scan) });\n const json = (await res.json()) as AnthropicResponse;\n return {\n parts: partsFromAnthropic(json),\n finishReason: finishFromAnthropic(json.stop_reason),\n usage: usageFromAnthropic(json.usage),\n responseId: json.id,\n modelId: json.model,\n raw: json,\n };\n },\n\n async *stream(rawReq, opts): AsyncIterable<StreamEvent> {\n const scan = scanRequest(rawReq);\n guardRequest(rawReq, scan);\n const req = applyCapabilities(rawReq);\n try {\n const res = await call(buildAnthropicRequest(req, buildOpts(true)), opts, {\n stream: true,\n betas: betasFor(scan),\n });\n if (!res.body) throw new AgentError(\"network\", \"Response had no body to stream.\", { provider: id });\n yield* streamAnthropic(res.body);\n } catch (e) {\n yield { type: \"error\", error: toAgentError(e, id) };\n }\n },\n\n async listModels(): Promise<ModelInfo[]> {\n // /models exists but adds an allowlist entry for little gain; a static\n // list mirrors the OpenAI adapter's offline fallback behavior.\n return config.models ?? ANTHROPIC_MODELS;\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;AA4BA,IAAM,qBAAqB;AAE3B,SAAS,SAAS,MAAmB,YAAkD;AACrF,UAAQ,KAAK,MAAM;AAAA,IACjB,KAAK;AACH,aAAO,KAAK,OAAO,EAAE,MAAM,QAAQ,MAAM,KAAK,KAAK,IAAI;AAAA,IACzD,KAAK;AAGH,UAAI,KAAK,YAAY,KAAK,UAAW,QAAO,EAAE,MAAM,qBAAqB,MAAM,KAAK,UAAU;AAC9F,UAAI,KAAK,UAAW,QAAO,EAAE,MAAM,YAAY,UAAU,KAAK,MAAM,WAAW,KAAK,UAAU;AAC9F,aAAO;AAAA,IACT,KAAK,SAAS;AACZ,YAAM,IAAI,KAAK;AACf,UAAI,EAAE,SAAS,MAAO,QAAO,EAAE,MAAM,SAAS,QAAQ,EAAE,MAAM,OAAO,KAAK,EAAE,IAAI,EAAE;AAClF,UAAI,EAAE,SAAS,UAAU;AACvB,eAAO,EAAE,MAAM,SAAS,QAAQ,EAAE,MAAM,UAAU,YAAY,KAAK,aAAa,aAAa,MAAM,EAAE,KAAK,EAAE;AAAA,MAC9G;AACA,UAAI,EAAE,aAAa,WAAY,QAAO,EAAE,MAAM,QAAQ,MAAM,gBAAgB,SAAS,QAAW,CAAC,EAAE;AACnG,aAAO,EAAE,MAAM,SAAS,QAAQ,EAAE,MAAM,QAAQ,SAAS,EAAE,GAAG,EAAE;AAAA,IAClE;AAAA,IACA,KAAK,QAAQ;AACX,YAAM,IAAI,KAAK;AACf,UAAI,EAAE,SAAS,MAAO,QAAO,EAAE,MAAM,YAAY,QAAQ,EAAE,MAAM,OAAO,KAAK,EAAE,IAAI,GAAG,GAAI,KAAK,WAAW,EAAE,OAAO,KAAK,SAAS,IAAI,CAAC,EAAG;AACzI,UAAI,EAAE,SAAS,UAAU;AAC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