@warlock.js/ai-anthropic 5.44.0 → 5.46.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.
@@ -2,8 +2,24 @@ import { matchesReleaseRoot } from "./thinking-mode.mjs";
2
2
 
3
3
  //#region ../../packages/ai-anthropic/src/known-context-windows.ts
4
4
  const RELEASE_CONTEXT_WINDOWS = [
5
+ ["claude-fable-5-1", 1e6],
6
+ ["claude-fable-5", 1e6],
7
+ ["claude-mythos-5-1", 1e6],
8
+ ["claude-mythos-5", 1e6],
9
+ ["claude-opus-5-5", 1e6],
10
+ ["claude-opus-5", 1e6],
11
+ ["claude-opus-4-8", 1e6],
12
+ ["claude-opus-4-7", 1e6],
13
+ ["claude-opus-4-6", 1e6],
5
14
  ["claude-opus-4-5", 2e5],
15
+ ["claude-opus-4-1", 2e5],
16
+ ["claude-opus-4", 2e5],
17
+ ["claude-sonnet-5-5", 1e6],
18
+ ["claude-sonnet-5", 1e6],
19
+ ["claude-sonnet-4-6", 1e6],
6
20
  ["claude-sonnet-4-5", 2e5],
21
+ ["claude-sonnet-4", 2e5],
22
+ ["claude-haiku-5-5", 1e6],
7
23
  ["claude-haiku-4-5", 2e5],
8
24
  ["claude-3-7-sonnet", 2e5],
9
25
  ["claude-3-5-sonnet", 2e5],
@@ -1 +1 @@
1
- {"version":3,"file":"known-context-windows.mjs","names":[],"sources":["../../../../../../../packages/ai-anthropic/src/known-context-windows.ts"],"sourcesContent":["import { matchesReleaseRoot } from \"./thinking-mode\";\n\n/*\n * Context windows (input + output tokens) of Claude models whose standard\n * window is documented as 200K. Models not listed here (including releases\n * with an optional larger window) resolve to `undefined`, so a window-relative\n * trigger stays inert until the window is set with\n * `anthropic.model({ name, contextWindow })`.\n */\nconst RELEASE_CONTEXT_WINDOWS: ReadonlyArray<readonly [root: string, window: number]> = [\n [\"claude-opus-4-5\", 200_000],\n [\"claude-sonnet-4-5\", 200_000],\n [\"claude-haiku-4-5\", 200_000],\n [\"claude-3-7-sonnet\", 200_000],\n [\"claude-3-5-sonnet\", 200_000],\n [\"claude-3-5-haiku\", 200_000],\n [\"claude-3-opus\", 200_000],\n [\"claude-3-haiku\", 200_000],\n];\n\n/**\n * The known context window of a Claude model, or `undefined` for an id that\n * is not in the table. Platform prefixes before `claude-` and dated or `@`\n * snapshot suffixes are accepted.\n *\n * @example\n * inferContextWindow(\"claude-haiku-4-5-20251001\"); // → 200000\n * inferContextWindow(\"my-gateway/model\"); // → undefined\n */\nexport function inferContextWindow(modelName: string): number | undefined {\n const lowered = modelName.toLowerCase();\n const start = lowered.indexOf(\"claude-\");\n\n if (start === -1) {\n return undefined;\n }\n\n const normalized = lowered.slice(start);\n\n for (const [root, window] of RELEASE_CONTEXT_WINDOWS) {\n if (matchesReleaseRoot(normalized, root)) {\n return window;\n }\n }\n\n return undefined;\n}\n"],"mappings":";;;AASA,MAAM,0BAAkF;CACtF,CAAC,mBAAmB,GAAO;CAC3B,CAAC,qBAAqB,GAAO;CAC7B,CAAC,oBAAoB,GAAO;CAC5B,CAAC,qBAAqB,GAAO;CAC7B,CAAC,qBAAqB,GAAO;CAC7B,CAAC,oBAAoB,GAAO;CAC5B,CAAC,iBAAiB,GAAO;CACzB,CAAC,kBAAkB,GAAO;AAC5B;;;;;;;;;;AAWA,SAAgB,mBAAmB,WAAuC;CACxE,MAAM,UAAU,UAAU,YAAY;CACtC,MAAM,QAAQ,QAAQ,QAAQ,SAAS;CAEvC,IAAI,UAAU,IACZ;CAGF,MAAM,aAAa,QAAQ,MAAM,KAAK;CAEtC,KAAK,MAAM,CAAC,MAAM,WAAW,yBAC3B,IAAI,mBAAmB,YAAY,IAAI,GACrC,OAAO;AAKb"}
1
+ {"version":3,"file":"known-context-windows.mjs","names":[],"sources":["../../../../../../../packages/ai-anthropic/src/known-context-windows.ts"],"sourcesContent":["import { matchesReleaseRoot } from \"./thinking-mode\";\n\n/*\n * Context windows (input + output tokens) of Claude chat models, from\n * Anthropic's model overview. Releases from the 4.6 line on, and every\n * Claude 5 family, document a 1M window; earlier releases a 200K standard\n * window (the optional larger window of some of them is not assumed). Models\n * not listed here resolve to `undefined`, so a window-relative trigger stays\n * inert until the window is set with `anthropic.model({ name, contextWindow })`.\n * More specific roots come before the roots they extend.\n */\nconst RELEASE_CONTEXT_WINDOWS: ReadonlyArray<readonly [root: string, window: number]> = [\n [\"claude-fable-5-1\", 1_000_000],\n [\"claude-fable-5\", 1_000_000],\n [\"claude-mythos-5-1\", 1_000_000],\n [\"claude-mythos-5\", 1_000_000],\n [\"claude-opus-5-5\", 1_000_000],\n [\"claude-opus-5\", 1_000_000],\n [\"claude-opus-4-8\", 1_000_000],\n [\"claude-opus-4-7\", 1_000_000],\n [\"claude-opus-4-6\", 1_000_000],\n [\"claude-opus-4-5\", 200_000],\n [\"claude-opus-4-1\", 200_000],\n [\"claude-opus-4\", 200_000],\n [\"claude-sonnet-5-5\", 1_000_000],\n [\"claude-sonnet-5\", 1_000_000],\n [\"claude-sonnet-4-6\", 1_000_000],\n [\"claude-sonnet-4-5\", 200_000],\n [\"claude-sonnet-4\", 200_000],\n [\"claude-haiku-5-5\", 1_000_000],\n [\"claude-haiku-4-5\", 200_000],\n [\"claude-3-7-sonnet\", 200_000],\n [\"claude-3-5-sonnet\", 200_000],\n [\"claude-3-5-haiku\", 200_000],\n [\"claude-3-opus\", 200_000],\n [\"claude-3-haiku\", 200_000],\n];\n\n/**\n * The known context window of a Claude model, or `undefined` for an id that\n * is not in the table. Platform prefixes before `claude-` and dated or `@`\n * snapshot suffixes are accepted.\n *\n * @example\n * inferContextWindow(\"claude-haiku-4-5-20251001\"); // → 200000\n * inferContextWindow(\"my-gateway/model\"); // → undefined\n */\nexport function inferContextWindow(modelName: string): number | undefined {\n const lowered = modelName.toLowerCase();\n const start = lowered.indexOf(\"claude-\");\n\n if (start === -1) {\n return undefined;\n }\n\n const normalized = lowered.slice(start);\n\n for (const [root, window] of RELEASE_CONTEXT_WINDOWS) {\n if (matchesReleaseRoot(normalized, root)) {\n return window;\n }\n }\n\n return undefined;\n}\n"],"mappings":";;;AAWA,MAAM,0BAAkF;CACtF,CAAC,oBAAoB,GAAS;CAC9B,CAAC,kBAAkB,GAAS;CAC5B,CAAC,qBAAqB,GAAS;CAC/B,CAAC,mBAAmB,GAAS;CAC7B,CAAC,mBAAmB,GAAS;CAC7B,CAAC,iBAAiB,GAAS;CAC3B,CAAC,mBAAmB,GAAS;CAC7B,CAAC,mBAAmB,GAAS;CAC7B,CAAC,mBAAmB,GAAS;CAC7B,CAAC,mBAAmB,GAAO;CAC3B,CAAC,mBAAmB,GAAO;CAC3B,CAAC,iBAAiB,GAAO;CACzB,CAAC,qBAAqB,GAAS;CAC/B,CAAC,mBAAmB,GAAS;CAC7B,CAAC,qBAAqB,GAAS;CAC/B,CAAC,qBAAqB,GAAO;CAC7B,CAAC,mBAAmB,GAAO;CAC3B,CAAC,oBAAoB,GAAS;CAC9B,CAAC,oBAAoB,GAAO;CAC5B,CAAC,qBAAqB,GAAO;CAC7B,CAAC,qBAAqB,GAAO;CAC7B,CAAC,oBAAoB,GAAO;CAC5B,CAAC,iBAAiB,GAAO;CACzB,CAAC,kBAAkB,GAAO;AAC5B;;;;;;;;;;AAWA,SAAgB,mBAAmB,WAAuC;CACxE,MAAM,UAAU,UAAU,YAAY;CACtC,MAAM,QAAQ,QAAQ,QAAQ,SAAS;CAEvC,IAAI,UAAU,IACZ;CAGF,MAAM,aAAa,QAAQ,MAAM,KAAK;CAEtC,KAAK,MAAM,CAAC,MAAM,WAAW,yBAC3B,IAAI,mBAAmB,YAAY,IAAI,GACrC,OAAO;AAKb"}
@@ -1 +1 @@
1
- {"version":3,"file":"model.d.mts","names":[],"sources":["../../../../../../../packages/ai-anthropic/src/model.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAqNa,0BAA0B;WACrB;WACA;WACA,cAAc;WACd,UAAU;mBAET;mBACA;mBACA;;mBAEA;mBAC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,UAAU,WACV,UAAU;IAAqB;MAC9B;EACI,aACL,UAAU,WACV,UAAU;IAAqB;MAC9B;;;;;;;;UAmBK;;EA+BD,KACL,SAAS,8BACT,UAAU,0BACT,QAAQ;EACJ,KACL,SAAS,2BACT,UAAU,0BACT,cAAc;EACV,KACL,SAAS,kBACT,UAAU,0BACT,QAAQ,iBAAiB,cAAc;UAqB5B;;;;;;;;;;;;EA0CD,YAAY,UAAU,WAAW,UAAU,mBAAmB;;;;;;;;;;;;;EAyC7D,OACZ,UAAU,WACV,UAAU,mBACT,cAAc;UAOF;;;;;;;UAwMP;;UAoDA;;;;;;;UAkBA;;;;;;;;;;UAgCA;;;;;;;;;UA+EA;;;;;;;;;;;;;UAsCA;;;;;;;;;;;;;;UA2DA;;;;;;;;;;;;;UAsBA;;;;;;UA0BA;;;;;;UAeA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UA+CA;;;;;UAwCA;;;;;;;;;;;;;;UA8BA;;;;;;;;;UAyCA;;;;;;;;;;;;;UA8BA;;;;;;UAmBA;;;;;;UAYA;;;;;UAuBA;;;;;;;;;;;;;;;UA6BA;;;;;;UAiCA"}
package/esm/model.mjs CHANGED
@@ -144,6 +144,7 @@ var AnthropicModel = class {
144
144
  this.capabilities = {
145
145
  structuredOutput: config.structuredOutput ?? true,
146
146
  vision: config.vision ?? inferVisionCapability(config.name),
147
+ toolResultImages: true,
147
148
  reasoning: config.reasoning ?? true,
148
149
  ...windowCapability(config.contextWindow ?? inferContextWindow(config.name)),
149
150
  promptCaching: true,
@@ -891,7 +892,8 @@ function neutralClearToolUses(neutral) {
891
892
  return {
892
893
  ...rule.afterTokens !== void 0 ? { trigger: { inputTokens: rule.afterTokens } } : {},
893
894
  ...rule.keep !== void 0 ? { keep: rule.keep } : {},
894
- ...rule.exclude?.length ? { excludeTools: rule.exclude } : {}
895
+ ...rule.exclude?.length ? { excludeTools: rule.exclude } : {},
896
+ ...rule.clearAtLeast !== void 0 ? { clearAtLeast: rule.clearAtLeast } : {}
895
897
  };
896
898
  }
897
899
  function clearThinkingEdit(options) {
package/esm/model.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"model.mjs","names":[],"sources":["../../../../../../../packages/ai-anthropic/src/model.ts"],"sourcesContent":["import {\n AIError,\n computeCost,\n InvalidRequestError,\n resolveStreamChunks,\n safeJsonParse,\n selectProviderTools,\n type Message,\n type ModelCallOptions,\n type ModelCapabilities,\n type ModelContract,\n type ModelPricing,\n type ModelResponse,\n type ModelStreamChunk,\n type ModelToolCallRequest,\n type ReasoningEffort,\n type Usage,\n} from \"@warlock.js/ai\";\nimport { log, type Logger } from \"@warlock.js/logger\";\nimport type Anthropic from \"@anthropic-ai/sdk\";\nimport type {\n AnthropicCallOptions,\n AnthropicClearThinking,\n AnthropicClearToolUses,\n AnthropicModelConfig,\n} from \"./config.type\";\nimport type {\n AnthropicRequest,\n AnthropicRequestOptions,\n AnthropicStreamingRequest,\n AnthropicNonStreamingRequest,\n} from \"./request.type\";\nimport { anthropicPricingFor, withAnthropicCacheWriteRates } from \"./known-pricing\";\nimport { inferContextWindow } from \"./known-context-windows\";\nimport { inferMaxOutputTokens } from \"./known-output-limits\";\nimport { inferVisionCapability } from \"./known-vision-models\";\nimport {\n acceptsTemperature,\n inferPreservedThinking,\n inferThinkingMode,\n type AnthropicThinkingMode,\n noReasoningForm,\n} from \"./thinking-mode\";\nimport { applyServerToolUsage } from \"./utils/server-tool-usage\";\nimport { applyAnthropicCacheUsage, requestCacheTtl } from \"./utils/cache-usage\";\nimport {\n mapStopReason,\n toAnthropicMessages,\n toAnthropicTools,\n toProviderBlocks,\n wrapAnthropicError,\n} from \"./utils\";\n\nconst LOG_MODULE = \"ai.anthropic\";\n\n/** `provider` value of `ai.providerTool()` entries this adapter sends verbatim. */\nconst ANTHROPIC_WIRE_FORMAT = \"anthropic\";\n\n/**\n * Anthropic requires `max_tokens` on every request (unlike OpenAI,\n * where it is optional). When neither the per-call option nor the model\n * config supplies one, the adapter picks a default large enough for agent\n * work (see `resolveDefaultMaxTokens`):\n *\n * - streaming: the model's documented max output (`known-output-limits.ts`,\n * or `config.maxOutputTokens`), else this value;\n * - non-streaming: this value, capped by the model's max output. The\n * installed `@anthropic-ai/sdk` (0.129.0, `calculateNonstreamingTimeout`)\n * refuses a non-streaming request whose `max_tokens` implies more than\n * ten minutes (above ~21,333 tokens) unless the client sets a `timeout`,\n * so the non-streaming default stays below that.\n */\nconst DEFAULT_MAX_TOKENS = 16_384;\n\n/**\n * Answer room kept on top of a thinking budget when the default\n * `max_tokens` is sized: thinking counts toward `max_tokens` (installed\n * SDK `ThinkingConfigParam` docs, `messages.d.ts:1105`), and in budget\n * mode `max_tokens` must exceed `budget_tokens`.\n */\nconst MIN_ANSWER_TOKENS = 4096;\n\n/**\n * Anthropic rejects an extended-thinking budget below 1024 tokens, so\n * any resolved budget is floored at this minimum before it reaches the\n * wire.\n */\nconst MIN_THINKING_BUDGET = 1024;\n\ntype ThinkingEffort = Exclude<ReasoningEffort, \"none\">;\n\n/**\n * Effort used when the caller asks for reasoning with only\n * `reasoning.maxTokens` and no `effort`. `\"medium\"` is what the adapter\n * has always assumed (the budget lookup fell back to\n * `EFFORT_THINKING_BUDGET.medium`), so adaptive models get the same tier.\n */\nconst DEFAULT_THINKING_EFFORT: ThinkingEffort = \"medium\";\n\n/**\n * Map the neutral `ReasoningEffort` level to a thinking token count.\n *\n * - Budget-mode models: sent as `thinking.budget_tokens` when the caller\n * doesn't pass an explicit `reasoning.maxTokens`.\n * - Both modes: when the caller sets no `maxTokens`, the default\n * `max_tokens` keeps at least this budget plus `MIN_ANSWER_TOKENS`,\n * because thinking counts toward `max_tokens` (installed SDK\n * `ThinkingConfigParam` docs, `messages.d.ts:1105`).\n */\nconst EFFORT_THINKING_BUDGET: Record<ThinkingEffort, number> = {\n // Anthropic's adaptive output config has no `minimal`; keep the minimum\n // budget for it in legacy budget mode too.\n minimal: 1024,\n low: 1024,\n medium: 4096,\n high: 12000,\n // Keep the tiers monotonic for older budget-mode models. Explicit\n // reasoning.maxTokens still wins and the existing max_tokens validation\n // remains authoritative.\n xhigh: 24000,\n max: 32000,\n};\n\n/**\n * Map the neutral `ReasoningEffort` level to Anthropic's\n * `output_config.effort` for adaptive-mode models. The installed SDK\n * accepts `low | medium | high | xhigh | max` (`OutputConfig.effort`,\n * `messages.ts:2767`); map every supported value 1:1 and clamp `minimal` to\n * the nearest accepted value, `low`.\n */\nconst EFFORT_TO_OUTPUT_EFFORT: Record<\n ThinkingEffort,\n NonNullable<Anthropic.OutputConfig[\"effort\"]>\n> = {\n minimal: \"low\",\n low: \"low\",\n medium: \"medium\",\n high: \"high\",\n xhigh: \"xhigh\",\n max: \"max\",\n};\n\ntype AnthropicThinkingBlock = Anthropic.ThinkingBlock | Anthropic.RedactedThinkingBlock;\n\n/**\n * The SDK's `messages.create` (or `beta.messages.create`) seen through a\n * loose signature: provider-option body fields and beta flags are merged\n * in untyped, and the response is narrowed by the caller.\n */\ntype LooseCreate = (\n body: Record<string, unknown>,\n options?: { signal?: AbortSignal },\n) => Promise<unknown>;\n\n/** Content-block types whose input arrives as `input_json_delta` while streaming. */\nconst STREAMED_INPUT_BLOCK_TYPES = new Set([\"tool_use\", \"server_tool_use\", \"mcp_tool_use\"]);\n\n/** One content block being assembled from stream events. */\ntype StreamedBlock = { block: Record<string, unknown>; json?: string };\n\n/**\n * Resolved thinking settings for one request.\n *\n * - `thinking`: the wire `thinking` field (absent = send nothing).\n * - `effort`: `output_config.effort`, set for adaptive-mode models only.\n * - `reservedTokens`: thinking tokens the default `max_tokens` must leave\n * room for (plus `MIN_ANSWER_TOKENS`) when the caller configured no\n * `maxTokens`.\n */\ntype ThinkingRequest = {\n thinking?: Anthropic.ThinkingConfigParam;\n effort?: Anthropic.OutputConfig[\"effort\"];\n reservedTokens?: number;\n};\n\n/**\n * Anthropic-backed implementation of `ModelContract`.\n *\n * **Role.** The provider-facing bridge between the vendor-neutral\n * `@warlock.js/ai` agent runtime and the official `@anthropic-ai/sdk`\n * Messages API. Agents, workflows, and supervisors never talk to\n * Anthropic directly — they hold a `ModelContract`, and this class is\n * what makes that contract concrete for Claude models.\n *\n * **Responsibility.**\n * - Owns: a long-lived `Anthropic` client + frozen `ModelConfig`\n * (name, temperature, maxTokens) used as defaults for every call.\n * - Owns: translating vendor-neutral `Message[]` / `ToolConfig[]` into\n * Anthropic wire shapes (system hoisting, `tool_use` / `tool_result`\n * blocks) on the way out, and translating Anthropic's content-block\n * response (text, tool calls, stop reason, usage) back into the\n * neutral shapes on the way in.\n * - Does NOT own: dispatching tools, deciding whether to loop, tracking\n * conversation history, or retrying on failure — those are agent\n * concerns. The model is a stateless (per-call) protocol adapter.\n *\n * Because it holds a live client and shared defaults, it is modeled as\n * a class (see §4.2 of code-style.md — \"long-lived state across\n * calls\").\n *\n * @example\n * import Anthropic from \"@anthropic-ai/sdk\";\n * const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });\n * const model = new AnthropicModel(client, { name: \"claude-sonnet-4-6\" });\n *\n * const myAgent = agent({\n * model,\n * systemPrompt: \"You are a helpful assistant.\",\n * tools: [searchTool],\n * });\n *\n * const result = await myAgent.execute(\"Summarize today's news.\");\n */\nexport class AnthropicModel implements ModelContract {\n public readonly name: string;\n public readonly provider: string;\n public readonly capabilities: ModelCapabilities;\n public readonly pricing?: ModelPricing;\n\n private readonly client: Anthropic;\n private readonly config: AnthropicModelConfig;\n private readonly thinkingMode: AnthropicThinkingMode;\n /** Documented max output tokens of this model, when known. Sizes the default `max_tokens`. */\n private readonly maxOutputTokens?: number;\n private readonly preservedThinking: boolean;\n private readonly logger: Logger = log;\n\n public constructor(\n client: Anthropic,\n config: AnthropicModelConfig,\n provider: string = \"anthropic\",\n ) {\n this.client = client;\n this.config = config;\n this.name = config.name;\n this.provider = provider;\n // Explicit pricing (per-model, or the SDK registry) wins over the\n // built-in Claude list prices; either way the Anthropic cache-write\n // multipliers fill any write rate the entry leaves out.\n this.pricing = withAnthropicCacheWriteRates(config.pricing ?? anthropicPricingFor(config.name));\n // Adaptive vs budget thinking — also decides whether `temperature` is\n // accepted. Explicit config wins over name inference, like `vision`.\n this.thinkingMode = config.thinkingMode ?? inferThinkingMode(config.name);\n this.maxOutputTokens = config.maxOutputTokens ?? inferMaxOutputTokens(config.name);\n // Budget-mode models predate preserved thinking; explicit config wins.\n this.preservedThinking =\n config.preservedThinking ??\n (this.thinkingMode === \"adaptive\" && inferPreservedThinking(config.name));\n this.capabilities = {\n structuredOutput: config.structuredOutput ?? true,\n vision: config.vision ?? inferVisionCapability(config.name),\n // Every modern Claude model accepts Anthropic extended thinking\n // (adaptive or `budget_tokens`, per `thinkingMode`). Advertise the\n // reasoning channel so the agent forwards `reasoning` options;\n // explicit config override wins for proxied/legacy targets.\n reasoning: config.reasoning ?? true,\n ...windowCapability(config.contextWindow ?? inferContextWindow(config.name)),\n // Anthropic prompt caching is caller-driven via `cache_control`\n // breakpoints. The adapter both places those breakpoints (tools\n // when `config.promptCaching`, system when\n // `options.cacheControl.breakpoints`) and reports the read/write\n // accounting (`cachedTokens` / `cacheWriteTokens`), so advertise\n // the capability unconditionally.\n promptCaching: true,\n // `ModelCallOptions.contextEditing.clearToolResults` maps to the\n // `clear_tool_uses` context edit (see `resolveContextManagement`).\n nativeContextEditing: true,\n // The Messages API accepts PDF/document content blocks\n // (`DocumentBlockParam`) on vision-capable Claude models.\n pdf: true,\n // Anthropic has no audio input content block, so `audio` stays\n // absent (treated as false) and the agent rejects audio\n // attachments upfront rather than dropping them at the wire layer.\n };\n }\n\n /**\n * Single-shot completion. Sends the full message list to the Messages\n * endpoint, waits for the terminal response, and reshapes it into a\n * vendor-neutral `ModelResponse`. Per-call `options` override the\n * instance's `ModelConfig` defaults for this call only.\n */\n public async complete(messages: Message[], options?: ModelCallOptions): Promise<ModelResponse> {\n return this.send(this.buildLoggedRequest(messages, { ...options, stream: false }), {\n signal: options?.signal,\n });\n }\n\n /** Build a detached request snapshot without sending it to Anthropic. */\n public buildRequest(\n messages: Message[],\n options: ModelCallOptions & { stream: true },\n ): AnthropicStreamingRequest;\n public buildRequest(\n messages: Message[],\n options?: ModelCallOptions & { stream?: false },\n ): AnthropicNonStreamingRequest;\n public buildRequest(\n messages: Message[],\n options?: ModelCallOptions & { stream?: boolean },\n ): AnthropicRequest;\n public buildRequest(\n messages: Message[],\n options?: ModelCallOptions & { stream?: boolean },\n ): AnthropicRequest {\n const built = this.buildBody(messages, options);\n const betas = [...new Set([...(resolveAnthropicOptions(options).betas ?? []), ...built.betas])];\n const body = structuredClone({ ...built.body, stream: options?.stream ?? false });\n\n return { endpoint: betas.length > 0 ? \"beta.messages\" : \"messages\", body, betas };\n }\n\n /**\n * `buildRequest()` for the adapter's own calls: a build failure (a reserved\n * body key, a `providerOptions.anthropic.body` value `structuredClone`\n * cannot copy) is logged like a send failure and rejects as an `AIError`.\n * Errors that are not already an `AIError` become an `InvalidRequestError`,\n * since nothing reached Anthropic and retrying cannot help.\n */\n private buildLoggedRequest(\n messages: Message[],\n options: ModelCallOptions & { stream: true },\n ): AnthropicStreamingRequest;\n private buildLoggedRequest(\n messages: Message[],\n options: ModelCallOptions & { stream: false },\n ): AnthropicNonStreamingRequest;\n private buildLoggedRequest(\n messages: Message[],\n options: ModelCallOptions & { stream: boolean },\n ): AnthropicRequest;\n private buildLoggedRequest(\n messages: Message[],\n options: ModelCallOptions & { stream: boolean },\n ): AnthropicRequest {\n try {\n return this.buildRequest(messages, options);\n } catch (thrown) {\n throw this.logAndWrap(\n thrown instanceof AIError\n ? thrown\n : new InvalidRequestError(\n `Could not build the Anthropic request: ${thrown instanceof Error ? thrown.message : String(thrown)}`,\n { cause: thrown },\n ),\n );\n }\n }\n\n /** Send a built request without rebuilding its body or applying model defaults. */\n public send(\n request: AnthropicNonStreamingRequest,\n options?: AnthropicRequestOptions,\n ): Promise<ModelResponse>;\n public send(\n request: AnthropicStreamingRequest,\n options?: AnthropicRequestOptions,\n ): AsyncIterable<ModelStreamChunk>;\n public send(\n request: AnthropicRequest,\n options?: AnthropicRequestOptions,\n ): Promise<ModelResponse> | AsyncIterable<ModelStreamChunk>;\n public send(\n request: AnthropicRequest,\n options?: AnthropicRequestOptions,\n ): Promise<ModelResponse> | AsyncIterable<ModelStreamChunk> {\n const message = request.body.stream\n ? \"Starting streaming call to messages.create\"\n : \"Starting call to messages.create\";\n\n this.logger.debug(LOG_MODULE, \"request\", message, {\n model: request.body.model,\n messageCount: Array.isArray(request.body.messages) ? request.body.messages.length : 0,\n streaming: request.body.stream,\n toolCount: Array.isArray(request.body.tools) ? request.body.tools.length : 0,\n });\n\n return request.body.stream\n ? this.streamRequest(request, options)\n : this.completeRequest(request, options);\n }\n\n private async completeRequest(\n request: AnthropicRequest,\n options?: AnthropicRequestOptions,\n ): Promise<ModelResponse> {\n let response: Anthropic.Message;\n\n try {\n response = (await this.dispatch(request, options, \"create\")) as Anthropic.Message;\n } catch (thrown) {\n throw this.logAndWrap(thrown);\n }\n\n const finishReason = mapStopReason(response.stop_reason);\n const usage = this.extractUsage(response.usage, requestCacheTtl(request.body));\n const toolCalls = this.extractToolCalls(response.content);\n const blocks = toProviderBlocks(response.content);\n\n this.logger.debug(LOG_MODULE, \"response\", \"call to messages.create succeeded\", {\n finishReason,\n usage,\n });\n\n return {\n content: this.extractText(response.content),\n finishReason,\n usage,\n toolCalls,\n ...(blocks ? { blocks } : {}),\n };\n }\n\n /**\n * Count the input tokens a request would use, through Anthropic's\n * `messages.countTokens` endpoint (a network call; no tokens are\n * generated or billed as output). Takes the same messages and options\n * as `complete()` — system prompt, tools, thinking and\n * `providerOptions.anthropic.betas` are counted exactly as they would be\n * sent. For an offline estimate use `AnthropicSDK.count()`.\n *\n * @example\n * const tokens = await model.countTokens(messages, { tools });\n */\n public async countTokens(messages: Message[], options?: ModelCallOptions): Promise<number> {\n const request = this.buildLoggedRequest(messages, {\n ...options,\n stream: options?.stream === true,\n });\n const body = request.body;\n const countBody: Record<string, unknown> = {};\n\n for (const key of COUNT_TOKENS_FIELDS) {\n if (body[key] !== undefined) {\n countBody[key] = body[key];\n }\n }\n\n try {\n const result = (await this.dispatch(\n { ...request, body: countBody },\n options,\n \"countTokens\",\n )) as {\n input_tokens: number;\n };\n\n return result.input_tokens;\n } catch (thrown) {\n throw this.logAndWrap(thrown);\n }\n }\n\n /**\n * Incremental streaming completion. Yields neutral `ModelStreamChunk`s\n * — `delta` for text tokens, `tool-call` once a `tool_use` block's\n * arguments have fully accumulated, and a terminal `done` carrying the\n * final finish reason + usage totals. Callers consume it with\n * `for await`.\n *\n * With `options.streamChunks` it also yields `reasoning` for every\n * non-empty `thinking_delta`, `tool-args` for every `input_json_delta`\n * of a client `tool_use` block, and `usage` after `message_start` and\n * each `message_delta` (whose counts are cumulative).\n */\n public async *stream(\n messages: Message[],\n options?: ModelCallOptions,\n ): AsyncIterable<ModelStreamChunk> {\n yield* this.send(this.buildLoggedRequest(messages, { ...options, stream: true }), {\n signal: options?.signal,\n streamChunks: options?.streamChunks,\n });\n }\n\n private async *streamRequest(\n request: AnthropicRequest,\n options?: AnthropicRequestOptions,\n ): AsyncIterable<ModelStreamChunk> {\n let stream: AsyncIterable<Anthropic.RawMessageStreamEvent>;\n\n try {\n stream = (await this.dispatch(\n request,\n options,\n \"create\",\n )) as AsyncIterable<Anthropic.RawMessageStreamEvent>;\n } catch (thrown) {\n throw this.logAndWrap(thrown);\n }\n\n let rawStopReason: string | null = null;\n let compaction = compactionIterationUsage(undefined);\n const usage: Usage = { input: 0, output: 0, total: 0, inputIncludesCache: false };\n const cacheTtl = requestCacheTtl(request.body);\n const want = resolveStreamChunks(options);\n const toolBlocks = new Map<number, { id: string; name: string; json: string }>();\n const thinkingBlocks = new Map<number, AnthropicThinkingBlock>();\n // Every content block of the turn, by index, so the full ordered turn\n // can be returned as `blocks` (thinking, compaction, server tools…).\n const streamedBlocks = new Map<number, StreamedBlock>();\n\n try {\n for await (const event of stream) {\n this.trackStreamedBlock(streamedBlocks, event);\n\n if (event.type === \"message_start\") {\n usage.input = event.message.usage.input_tokens ?? 0;\n\n const thinkingTokens = event.message.usage.output_tokens_details?.thinking_tokens;\n\n if (thinkingTokens !== null && thinkingTokens !== undefined) {\n usage.reasoningTokens = thinkingTokens;\n }\n\n applyServerToolUsage(usage, event.message.usage.server_tool_use);\n applyAnthropicCacheUsage(usage, event.message.usage, cacheTtl);\n\n if (want.usage) {\n yield { type: \"usage\", usage: { ...usage, total: usage.input + usage.output } };\n }\n\n continue;\n }\n\n if (event.type === \"content_block_start\") {\n const block = event.content_block;\n\n if (block.type === \"tool_use\") {\n toolBlocks.set(event.index, { id: block.id, name: block.name, json: \"\" });\n } else if (block.type === \"thinking\") {\n thinkingBlocks.set(event.index, { ...block });\n } else if (block.type === \"redacted_thinking\") {\n thinkingBlocks.set(event.index, { ...block });\n }\n\n continue;\n }\n\n if (event.type === \"content_block_delta\") {\n if (event.delta.type === \"text_delta\") {\n yield { type: \"delta\", content: event.delta.text };\n } else if (event.delta.type === \"input_json_delta\") {\n const accumulator = toolBlocks.get(event.index);\n\n if (accumulator) {\n accumulator.json += event.delta.partial_json;\n\n // Only client `tool_use` blocks: a `server_tool_use` input\n // (e.g. a web search query) never becomes a `tool-call`.\n if (want.toolArgs && event.delta.partial_json !== \"\") {\n yield {\n type: \"tool-args\",\n callId: accumulator.id,\n name: accumulator.name,\n delta: event.delta.partial_json,\n };\n }\n }\n } else if (event.delta.type === \"thinking_delta\") {\n const thinking = thinkingBlocks.get(event.index);\n\n if (thinking?.type === \"thinking\") {\n thinking.thinking += event.delta.thinking;\n }\n\n // `display: \"omitted\"` streams one empty `thinking_delta`.\n if (want.reasoning && event.delta.thinking !== \"\") {\n yield { type: \"reasoning\", delta: event.delta.thinking };\n }\n } else if (event.delta.type === \"signature_delta\") {\n const thinking = thinkingBlocks.get(event.index);\n\n if (thinking?.type === \"thinking\") {\n thinking.signature += event.delta.signature;\n }\n }\n\n continue;\n }\n\n if (event.type === \"content_block_stop\") {\n const accumulator = toolBlocks.get(event.index);\n\n if (accumulator) {\n yield {\n type: \"tool-call\",\n id: accumulator.id,\n name: accumulator.name,\n input: safeJsonParse<Record<string, unknown>>(accumulator.json, {}),\n ...this.buildThinkingMetadata(\n Array.from(thinkingBlocks.entries())\n .sort(([left], [right]) => left - right)\n .map(([, block]) => block),\n ),\n };\n\n toolBlocks.delete(event.index);\n }\n\n continue;\n }\n\n if (event.type === \"message_delta\") {\n rawStopReason = event.delta.stop_reason ?? rawStopReason;\n // The final delta carries every iteration of the request.\n if (Array.isArray((event.usage as { iterations?: unknown }).iterations)) {\n compaction = compactionIterationUsage(event.usage);\n }\n applyServerToolUsage(usage, event.usage.server_tool_use);\n usage.output = event.usage.output_tokens ?? usage.output;\n\n const thinkingTokens = event.usage.output_tokens_details?.thinking_tokens;\n\n if (thinkingTokens !== null && thinkingTokens !== undefined) {\n usage.reasoningTokens = thinkingTokens;\n }\n\n // `message_delta.usage` carries the cumulative cache counts —\n // prefer them over the `message_start` snapshot when present\n // and non-zero so the terminal `done` reflects the final tally.\n // It has no per-lifetime breakdown, so a 1-hour share already\n // read from `message_start` is kept.\n applyAnthropicCacheUsage(\n usage,\n {\n cache_read_input_tokens: event.usage.cache_read_input_tokens,\n cache_creation_input_tokens: event.usage.cache_creation_input_tokens,\n cache_creation:\n usage.cacheWrite1hTokens !== undefined\n ? { ephemeral_1h_input_tokens: usage.cacheWrite1hTokens }\n : undefined,\n },\n cacheTtl,\n );\n\n // `message_delta.usage` counts are cumulative (Anthropic streaming\n // docs), so this is the running total so far.\n if (want.usage) {\n yield { type: \"usage\", usage: { ...usage, total: usage.input + usage.output } };\n }\n }\n }\n } catch (thrown) {\n throw this.logAndWrap(thrown);\n }\n\n usage.input += compaction.input;\n usage.output += compaction.output;\n addCacheCounts(usage, compaction);\n usage.total = usage.input + usage.output;\n\n const cost = computeCost(usage, this.pricing);\n\n if (cost) {\n usage.cost = cost;\n }\n\n const finishReason = mapStopReason(rawStopReason);\n const blocks = toProviderBlocks(this.finishStreamedBlocks(streamedBlocks));\n\n this.logger.debug(LOG_MODULE, \"response\", \"Streaming call to messages.create succeeded\", {\n finishReason,\n usage,\n });\n\n yield { type: \"done\", finishReason, usage, ...(blocks ? { blocks } : {}) };\n }\n\n /**\n * Fold one stream event into the per-index block accumulator. Unknown\n * block and delta types (beta `compaction`, future additions) are kept\n * as their start payload plus whatever their delta carries, so they\n * round-trip without the adapter knowing their shape.\n */\n private trackStreamedBlock(\n blocks: Map<number, StreamedBlock>,\n event: Anthropic.RawMessageStreamEvent,\n ): void {\n if (event.type === \"content_block_start\") {\n const block = { ...(event.content_block as unknown as Record<string, unknown>) };\n\n blocks.set(event.index, {\n block,\n ...(STREAMED_INPUT_BLOCK_TYPES.has(String(block.type)) ? { json: \"\" } : {}),\n });\n\n return;\n }\n\n if (event.type !== \"content_block_delta\") {\n return;\n }\n\n const entry = blocks.get(event.index);\n\n if (!entry) {\n return;\n }\n\n const delta = event.delta as unknown as Record<string, unknown> & { type: string };\n const block = entry.block;\n\n if (delta.type === \"text_delta\") {\n block.text = String(block.text ?? \"\") + String(delta.text ?? \"\");\n } else if (delta.type === \"thinking_delta\") {\n block.thinking = String(block.thinking ?? \"\") + String(delta.thinking ?? \"\");\n } else if (delta.type === \"signature_delta\") {\n block.signature = String(block.signature ?? \"\") + String(delta.signature ?? \"\");\n } else if (delta.type === \"input_json_delta\") {\n entry.json = (entry.json ?? \"\") + String(delta.partial_json ?? \"\");\n } else if (delta.type === \"citations_delta\") {\n block.citations = [\n ...(Array.isArray(block.citations) ? block.citations : []),\n delta.citation,\n ];\n } else {\n // e.g. beta `compaction_delta` — carries the block's final fields.\n for (const [key, value] of Object.entries(delta)) {\n if (key !== \"type\") {\n block[key] = value;\n }\n }\n }\n }\n\n /** Close the accumulated stream blocks into an ordered content array. */\n private finishStreamedBlocks(blocks: Map<number, StreamedBlock>): Array<{ type: string }> {\n return Array.from(blocks.entries())\n .sort(([left], [right]) => left - right)\n .map(([, { block, json }]) => {\n if (json !== undefined) {\n block.input = safeJsonParse<Record<string, unknown>>(json, {});\n }\n\n return block as { type: string };\n });\n }\n\n /**\n * Send a request through the SDK. With `providerOptions.anthropic.betas`\n * the call goes to `client.beta.messages` (which takes the `betas` list\n * and the beta-only body fields); otherwise to `client.messages`. The\n * cancellation signal rides in the request options, as before.\n */\n private dispatch(\n request: {\n endpoint: AnthropicRequest[\"endpoint\"];\n body: Record<string, unknown>;\n betas: string[];\n },\n options: AnthropicRequestOptions | undefined,\n method: \"create\" | \"countTokens\",\n ): Promise<unknown> {\n const requestOptions = options?.signal ? { signal: options.signal } : undefined;\n const api =\n request.endpoint === \"beta.messages\" ? this.client.beta.messages : this.client.messages;\n const call = api[method] as unknown as LooseCreate;\n\n return call.call(\n api,\n request.endpoint === \"beta.messages\"\n ? { ...request.body, betas: request.betas }\n : request.body,\n requestOptions,\n );\n }\n\n /**\n * The full request body and the beta flags it needs: the adapter-built\n * params, then `thinking.display` when thinking is sent on an adaptive\n * model, the typed `thinkingBlockBinding`, `contextManagement` and\n * `serverCompaction` options, then `providerOptions.anthropic.body`\n * merged last (caller fields win). The body may add fields the adapter\n * does not build (`fallbacks`, …) but may not replace the conversation or\n * the model — see {@link RESERVED_BODY_FIELDS}.\n */\n private buildBody(\n messages: Message[],\n options: (ModelCallOptions & { stream?: boolean }) | undefined,\n ): { body: Record<string, unknown>; betas: string[] } {\n const anthropic = resolveAnthropicOptions(options);\n const betas: string[] = [];\n // Kept turns after a client-written summary carry thinking signed\n // against the replaced history. Leave it out on models that check the\n // conversation, unless the caller chose how the API handles it.\n const body: Record<string, unknown> = {\n ...this.buildParams(messages, options, {\n dropRetainedThinking:\n this.preservedThinking && anthropic.thinkingBlockBinding === undefined,\n }),\n };\n\n // `display` belongs to adaptive thinking only; `between_tools` takes\n // no other field and 400s with one.\n if (\n anthropic.thinkingDisplay &&\n this.thinkingMode === \"adaptive\" &&\n (body.thinking as { type?: string } | undefined)?.type === \"adaptive\"\n ) {\n body.thinking = {\n ...(body.thinking as Record<string, unknown>),\n display: anthropic.thinkingDisplay,\n };\n }\n\n if (anthropic.thinkingBlockBinding) {\n this.applyBlockBinding(body, anthropic.thinkingBlockBinding, betas);\n }\n\n const edits = buildContextEdits(anthropic, options?.contextEditing);\n\n if (edits.length > 0) {\n if (anthropic.body?.context_management !== undefined) {\n throw new InvalidRequestError(\n \"providerOptions.anthropic.contextManagement / serverCompaction cannot be combined with \" +\n \"body.context_management: set the edits in one place.\",\n { context: { fields: [\"context_management\"] } },\n );\n }\n\n body.context_management = { edits };\n\n if (edits.some((edit) => edit.type !== \"compact_20260112\")) {\n betas.push(CONTEXT_MANAGEMENT_BETA);\n }\n\n if (edits.some((edit) => edit.type === \"compact_20260112\")) {\n betas.push(COMPACTION_BETA);\n }\n }\n\n const reserved = Object.keys(anthropic.body ?? {}).filter((key) =>\n RESERVED_BODY_FIELDS.has(key),\n );\n\n if (reserved.length > 0) {\n throw new InvalidRequestError(\n `providerOptions.anthropic.body cannot set ${reserved.map((key) => `\"${key}\"`).join(\", \")}: ` +\n \"the adapter builds these from the call's messages, tools and model. \" +\n \"Use the agent/model options instead.\",\n { context: { fields: reserved } },\n );\n }\n\n return { body: { ...body, ...anthropic.body }, betas };\n }\n\n /**\n * Set `thinking.block_binding.prefix_mismatch_behavior`. It rides on\n * adaptive or budget (`enabled`) thinking. A model that runs adaptive\n * thinking when `thinking` is omitted (every preserved-thinking model) gets\n * an explicit `{ type: \"adaptive\" }`, which is the same request. Any other\n * shape (`between_tools`, `disabled`) takes no extra field, so the option\n * is skipped with a debug log.\n */\n private applyBlockBinding(\n body: Record<string, unknown>,\n behavior: \"error\" | \"drop_block\",\n betas: string[],\n ): void {\n const thinking = body.thinking as { type?: string } | undefined;\n const type = thinking?.type ?? (this.preservedThinking ? \"adaptive\" : undefined);\n\n if (type !== \"adaptive\" && type !== \"enabled\") {\n this.logger.debug(\n LOG_MODULE,\n \"thinking-block-binding.ignored\",\n \"thinkingBlockBinding needs adaptive or budget thinking on this request; not sent\",\n { model: this.name, thinking: thinking?.type ?? \"none\" },\n );\n\n return;\n }\n\n body.thinking = {\n ...(thinking ?? { type }),\n block_binding: { prefix_mismatch_behavior: behavior },\n };\n betas.push(THINKING_BINDING_BETA);\n }\n\n /**\n * Assemble the Anthropic request body shared by `complete()` and\n * `stream()` (each adds its own `stream` literal so the SDK's create\n * overload resolves to the right return type). Hoists the system\n * prompt out of `messages`, resolves `max_tokens` (required by\n * Anthropic) with the documented default, and conditionally attaches\n * temperature, tools, native structured output, extended thinking\n * (`reasoning`), and automatic or explicit prompt-cache control.\n * Temperature is dropped when thinking is enabled, since Anthropic\n * rejects the two together, and always for adaptive-mode models, which\n * reject any explicit temperature (see `acceptsTemperature`).\n */\n private buildParams(\n messages: Message[],\n options: (ModelCallOptions & { stream?: boolean }) | undefined,\n conversion: { dropRetainedThinking: boolean },\n ): Omit<Anthropic.MessageCreateParamsNonStreaming, \"stream\"> {\n const { system, messages: anthropicMessages } = toAnthropicMessages(messages, conversion);\n const thinking = this.buildThinking(options?.reasoning);\n const temperature = options?.temperature ?? this.config.temperature;\n const configuredMaxTokens = options?.maxTokens ?? this.config.maxTokens;\n const thinkingBudget =\n thinking.thinking?.type === \"enabled\" ? thinking.thinking.budget_tokens : undefined;\n const maxTokens =\n configuredMaxTokens ??\n this.resolveDefaultMaxTokens(options?.stream === true, thinking.reservedTokens);\n // Extended thinking pins sampling to the default temperature —\n // Anthropic 400s when `thinking` is enabled alongside any explicit\n // `temperature`. Models released after Opus 4.6 (adaptive mode) reject\n // an explicit temperature outright (installed SDK\n // `MessageCreateParamsBase.temperature`, `messages.d.ts:2036-2040`).\n // Drop it in both cases rather than letting the request fail.\n const sendTemperature =\n temperature !== undefined && !thinking.thinking && acceptsTemperature(this.thinkingMode);\n\n if (\n thinkingBudget !== undefined &&\n configuredMaxTokens !== undefined &&\n configuredMaxTokens <= thinkingBudget\n ) {\n throw new Error(\n `Anthropic maxTokens (${configuredMaxTokens}) must be greater than thinking budget_tokens (${thinkingBudget})`,\n );\n }\n\n return {\n model: this.name,\n max_tokens: maxTokens,\n messages: anthropicMessages,\n ...this.buildAutomaticCacheControl(options?.cacheControl),\n ...this.buildSystem(system, options?.cacheControl),\n ...(sendTemperature ? { temperature } : {}),\n ...this.buildTools(options, options?.cacheControl),\n ...this.buildOutputConfig(options?.responseSchema, thinking.effort),\n ...(thinking.thinking ? { thinking: thinking.thinking } : {}),\n };\n }\n\n /**\n * The `max_tokens` sent when neither the call nor the model config sets\n * `maxTokens`:\n *\n * - streaming: the model's documented max output, or\n * `DEFAULT_MAX_TOKENS` (16384) for an unknown id;\n * - non-streaming: `DEFAULT_MAX_TOKENS`, capped by the model's max output\n * (the SDK requires streaming for larger non-streaming requests unless\n * the client sets a `timeout`; see `DEFAULT_MAX_TOKENS`).\n *\n * With thinking on, the value is raised to at least the thinking budget\n * plus `MIN_ANSWER_TOKENS`, and never exceeds the model's max output.\n */\n private resolveDefaultMaxTokens(stream: boolean, reservedTokens: number | undefined): number {\n const limit = this.maxOutputTokens;\n const fallback = limit === undefined ? DEFAULT_MAX_TOKENS : Math.min(limit, DEFAULT_MAX_TOKENS);\n const base = stream ? (limit ?? DEFAULT_MAX_TOKENS) : fallback;\n const withThinking =\n reservedTokens === undefined ? base : Math.max(base, reservedTokens + MIN_ANSWER_TOKENS);\n\n return limit === undefined ? withThinking : Math.min(withThinking, limit);\n }\n\n /**\n * Spread-friendly `system` fragment. Returns an empty object when no\n * system prompt was hoisted out of the messages.\n *\n * When a per-call `cacheControl.breakpoints` hint is present (≥ 1),\n * the system prompt is emitted as a single `TextBlockParam` carrying\n * `cache_control: ephemeral` — the system prompt is the longest stable\n * prefix on a turn, so one breakpoint there lets multi-turn agents\n * read it back at the ~0.1x cache-read rate. Without the hint the\n * system prompt stays a plain string (left uncached) so a one-shot\n * call never pays the ~1.25x cache-write surcharge.\n */\n private buildSystem(\n system: string | undefined,\n cacheControl: ModelCallOptions[\"cacheControl\"],\n ): { system?: string | Anthropic.TextBlockParam[] } {\n if (!system) {\n return {};\n }\n\n const breakpoints = cacheControl?.breakpoints ?? 0;\n\n if (this.capabilities.promptCaching && breakpoints > 0) {\n return {\n system: [\n { type: \"text\", text: system, cache_control: this.cacheControl(cacheControl?.ttl) },\n ],\n };\n }\n\n return { system };\n }\n\n /**\n * Let Anthropic select the last cacheable block when caching is enabled\n * without a caller-selected breakpoint. An explicit breakpoint remains\n * authoritative, so the request-level form is deliberately omitted then.\n */\n private buildAutomaticCacheControl(cacheControl: ModelCallOptions[\"cacheControl\"]): {\n cache_control?: Anthropic.CacheControlEphemeral;\n } {\n const breakpoints = cacheControl?.breakpoints ?? 0;\n\n return this.config.promptCaching && breakpoints <= 0\n ? { cache_control: this.cacheControl(cacheControl?.ttl) }\n : {};\n }\n\n /**\n * Build a typed cache-control marker. The per-call\n * `cacheControl.ttl` wins over the model's `promptCacheTtl`; with\n * neither, TTL is omitted for Anthropic's 5-minute default.\n */\n private cacheControl(callTtl?: \"5m\" | \"1h\"): Anthropic.CacheControlEphemeral {\n const ttl = callTtl ?? this.config.promptCacheTtl;\n\n return {\n type: \"ephemeral\",\n ...(ttl ? { ttl } : {}),\n };\n }\n\n /**\n * Translate the neutral `reasoning` option into Anthropic's thinking\n * settings, in the shape this model accepts (`thinkingMode`). Emitted\n * only when the model declares the `reasoning` capability AND a\n * reasoning option is supplied; otherwise returns an empty object.\n *\n * - Adaptive mode (Opus 4.7+, Sonnet 5+, Fable 5+, unknown ids):\n * `thinking: { type: \"adaptive\" }` (installed SDK\n * `ThinkingConfigAdaptive`, `messages.d.ts:1065`) plus\n * `output_config.effort` from the neutral effort, defaulting to\n * `\"medium\"`. `budget_tokens` is never sent — these models 400 on it\n * (claude-api ref). `reasoning.maxTokens` only sizes the default\n * `max_tokens` headroom.\n * - Budget mode (Haiku 4.5, Opus/Sonnet 4.6, older):\n * `thinking: { type: \"enabled\", budget_tokens }`. An explicit\n * `reasoning.maxTokens` wins; otherwise the effort maps to a tiered\n * budget. `budget_tokens` must be ≥ 1024 (`ThinkingConfigEnabled`,\n * `messages.d.ts:1084`), so the budget is floored at that minimum.\n *\n * The neutral `effort: \"none\"` (\"run without reasoning\") is mapped per\n * model by `noReasoningForm` (see `thinking-mode.ts` for the sources):\n * - Claude Sonnet 5.5: `thinking: { type: \"between_tools\" }`, its only\n * thinking-off form. It is sent alone — no `output_config.effort` (the\n * model default, `high`, is within the `high`-or-below range it\n * requires) and no `display`, both of which the API rejects alongside it.\n * - Claude Sonnet 5 and Claude Haiku 5.5: `thinking: { type: \"disabled\" }`\n * with no effort and no `display`. Haiku 5.5 accepts `disabled` only at\n * effort `high` or below; its default (`medium`) applies.\n * - Claude Opus 5: adaptive thinking at `output_config.effort: \"low\"`.\n * Opus 5 accepts `disabled`, but with it the model can write a tool call\n * as plain text (the call never runs) and leak thinking tags; the lowest\n * effort is the documented alternative.\n * - Opus 5.5 and Fable 5/5.1: no `thinking` field. These models have no\n * thinking-off form (`disabled` and `budget_tokens` are a 400 at every\n * effort), so thinking still runs at the model's default effort. Pass\n * `effort: \"low\"` to spend less.\n * - Every other model: no `thinking` field, as before.\n */\n private buildThinking(reasoning: ModelCallOptions[\"reasoning\"]): ThinkingRequest {\n if (!this.capabilities.reasoning || !reasoning) {\n return {};\n }\n\n // `effort: \"none\"` is an explicit \"run without reasoning\", in the form\n // this model accepts. (This also short-circuits the\n // `EFFORT_THINKING_BUDGET[\"none\"]` → `undefined` → `NaN` budget path.)\n if (reasoning.effort === \"none\") {\n return this.buildNoReasoning();\n }\n\n if (reasoning.maxTokens === undefined && reasoning.effort === undefined) {\n return {};\n }\n\n const effort = reasoning.effort ?? DEFAULT_THINKING_EFFORT;\n const budget = Math.max(\n MIN_THINKING_BUDGET,\n reasoning.maxTokens ?? EFFORT_THINKING_BUDGET[effort],\n );\n\n if (this.thinkingMode === \"adaptive\") {\n return {\n thinking: { type: \"adaptive\" },\n effort: EFFORT_TO_OUTPUT_EFFORT[effort],\n reservedTokens: budget,\n };\n }\n\n return {\n thinking: { type: \"enabled\", budget_tokens: budget },\n reservedTokens: budget,\n };\n }\n\n /**\n * The thinking settings for `reasoning: { effort: \"none\" }`, per\n * `noReasoningForm(this.name)` (documented on `buildThinking`).\n */\n private buildNoReasoning(): ThinkingRequest {\n switch (noReasoningForm(this.name)) {\n case \"between_tools\":\n return { thinking: { type: \"between_tools\" } };\n case \"disabled\":\n return { thinking: { type: \"disabled\" } };\n case \"lowest-effort\":\n return {\n thinking: { type: \"adaptive\" },\n effort: EFFORT_TO_OUTPUT_EFFORT.low,\n reservedTokens: EFFORT_THINKING_BUDGET.low,\n };\n case \"omit\":\n return {};\n }\n }\n\n /**\n * Spread-friendly tools fragment. Returns an empty object when no\n * tools were supplied so the caller can unconditionally spread it.\n *\n * When `config.promptCaching` is on, marks the LAST tool with\n * `cache_control: ephemeral` — Anthropic caches the whole prefix up\n * to a breakpoint, and tools sit before `system` in that prefix, so\n * one breakpoint on the final tool caches every tool definition.\n * Reads bill at ~0.1x after the first write. The system prompt is\n * deliberately left uncached: it carries per-turn placeholders, so a\n * breakpoint there would pay the ~1.25x write surcharge every turn\n * with no reads.\n */\n private buildTools(\n options: ModelCallOptions | undefined,\n cacheControl: ModelCallOptions[\"cacheControl\"],\n ): { tools?: Anthropic.ToolUnion[] } {\n const { tools, definitions } = selectProviderTools(options, {\n // The wire format, plus the provider label when a gateway sets one.\n accepts: [ANTHROPIC_WIRE_FORMAT, this.provider],\n module: LOG_MODULE,\n model: this.name,\n logger: this.logger,\n });\n const mapped = toAnthropicTools(tools);\n // Provider-defined tools (`web_search_20250305`, `bash_20250124`, …) go\n // first and verbatim; the cache breakpoint stays on the last function\n // tool so it still covers every definition before it.\n const providerDefined = definitions as unknown as Anthropic.ToolUnion[];\n\n if (!mapped) {\n return providerDefined.length > 0 ? { tools: providerDefined } : {};\n }\n\n if (this.config.promptCaching && mapped.length > 0) {\n const last = mapped.length - 1;\n const lastTool = mapped[last];\n\n if (lastTool) {\n mapped[last] = { ...lastTool, cache_control: this.cacheControl(cacheControl?.ttl) };\n }\n }\n\n return { tools: [...providerDefined, ...mapped] };\n }\n\n /**\n * Spread-friendly `output_config` fragment carrying both the native\n * structured-output `format` and the adaptive-thinking `effort`, merged\n * into one object (both live under `OutputConfig`, installed SDK\n * `messages.d.ts:796-806`). Returns an empty object when neither applies,\n * so budget-mode requests carry `output_config` only when a schema asks\n * for it.\n */\n private buildOutputConfig(\n responseSchema: Record<string, unknown> | undefined,\n effort: Anthropic.OutputConfig[\"effort\"],\n ): { output_config?: Anthropic.OutputConfig } {\n const format = this.buildStructuredOutputFormat(responseSchema);\n\n if (!format && !effort) {\n return {};\n }\n\n return {\n output_config: {\n ...(format ? { format } : {}),\n ...(effort ? { effort } : {}),\n },\n };\n }\n\n /**\n * Translate the neutral `responseSchema` option into Anthropic's\n * native `output_config.format` (JSON-schema structured outputs).\n *\n * Only returned when the model declares the `structuredOutput`\n * capability AND the schema is a proper root-object JSON Schema —\n * Anthropic rejects non-object roots. When the capability is off\n * (config override) or the schema is non-object, returns `undefined`:\n * the agent has already injected a soft schema hint into the system\n * prompt as the fallback, and client-side `validate()` still enforces\n * shape.\n */\n private buildStructuredOutputFormat(\n responseSchema: Record<string, unknown> | undefined,\n ): Anthropic.JSONOutputFormat | undefined {\n if (!responseSchema || !this.capabilities.structuredOutput) {\n return undefined;\n }\n\n if (responseSchema.type !== \"object\" || typeof responseSchema.properties !== \"object\") {\n return undefined;\n }\n\n return { type: \"json_schema\", schema: responseSchema };\n }\n\n /**\n * Concatenate every `text` content block into the single neutral\n * `content` string. `tool_use` and other block types are ignored\n * here — tool calls are surfaced separately via `extractToolCalls`.\n */\n private extractText(content: Anthropic.ContentBlock[]): string {\n return content\n .filter((block): block is Anthropic.TextBlock => block.type === \"text\")\n .map((block) => block.text)\n .join(\"\");\n }\n\n /**\n * Reshape Anthropic's `tool_use` content blocks into the neutral\n * `ModelToolCallRequest[]`. Returns `undefined` when the model\n * requested no tools so callers can branch on presence.\n */\n private extractToolCalls(content: Anthropic.ContentBlock[]): ModelToolCallRequest[] | undefined {\n const toolUses = content.filter(\n (block): block is Anthropic.ToolUseBlock => block.type === \"tool_use\",\n );\n\n if (toolUses.length === 0) {\n return undefined;\n }\n\n const thinkingMetadata = this.buildThinkingMetadata(content);\n\n return toolUses.map((block) => ({\n id: block.id,\n name: block.name,\n input: (block.input ?? {}) as Record<string, unknown>,\n ...thinkingMetadata,\n }));\n }\n\n /**\n * Preserve Anthropic's opaque extended-thinking blocks beside a tool\n * request so the next assistant turn can replay their signatures exactly.\n */\n private buildThinkingMetadata(blocks: Iterable<Anthropic.ContentBlock>): {\n providerMetadata?: Record<string, unknown>;\n } {\n const thinkingBlocks = Array.from(blocks).filter(\n (block): block is AnthropicThinkingBlock =>\n block.type === \"thinking\" || block.type === \"redacted_thinking\",\n );\n\n if (thinkingBlocks.length === 0) {\n return {};\n }\n\n return { providerMetadata: { anthropic: { thinkingBlocks } } };\n }\n\n /**\n * Normalize Anthropic's `usage` block into the neutral `Usage` shape.\n * Anthropic reports `input_tokens` / `output_tokens` separately with\n * no pre-summed total, so `total` is computed. `input_tokens` is the\n * uncached remainder only — cache reads (`cachedTokens`) and writes\n * (`cacheWriteTokens`, with the 1-hour share in `cacheWrite1hTokens`)\n * come on top of it — so the usage is marked\n * `inputIncludesCache: false`. Anthropic also reports\n * `output_tokens_details.thinking_tokens` as the reasoning subset of\n * its inclusive `output_tokens`; it is surfaced as `reasoningTokens`\n * when present, without changing the billing total. Server-side\n * compaction iterations are added in (see {@link compactionIterationUsage}).\n * `cost` is attached when the model is priced.\n */\n private extractUsage(raw: Anthropic.Usage, cacheTtl: ReturnType<typeof requestCacheTtl>): Usage {\n const compaction = compactionIterationUsage(raw);\n const input = (raw.input_tokens ?? 0) + compaction.input;\n const output = (raw.output_tokens ?? 0) + compaction.output;\n const thinkingTokens = raw.output_tokens_details?.thinking_tokens;\n const usage: Usage = {\n input,\n output,\n total: input + output,\n inputIncludesCache: false,\n ...(thinkingTokens !== null && thinkingTokens !== undefined\n ? { reasoningTokens: thinkingTokens }\n : {}),\n };\n\n applyServerToolUsage(usage, raw.server_tool_use);\n applyAnthropicCacheUsage(usage, raw, cacheTtl);\n addCacheCounts(usage, compaction);\n\n const cost = computeCost(usage, this.pricing);\n\n if (cost) {\n usage.cost = cost;\n }\n\n return usage;\n }\n\n /**\n * Wrap a thrown provider error into the typed `AIError` hierarchy and\n * emit the standard error log line before it propagates. Shared by\n * every catch site so the log shape stays identical.\n */\n private logAndWrap(thrown: unknown) {\n const wrapped = wrapAnthropicError(thrown);\n\n this.logger.error(LOG_MODULE, \"error\", wrapped.message, {\n code: wrapped.code,\n context: wrapped.context,\n });\n\n return wrapped;\n }\n}\n\n/**\n * Request fields `providerOptions.anthropic.body` may not set: they carry\n * the conversation, the model and the tool surface the agent registered,\n * so an override would silently replace the agent's input (or let the\n * model call tools the agent never registered). `stream` is chosen per\n * call by `complete()` / `stream()`.\n */\nconst RESERVED_BODY_FIELDS: ReadonlySet<string> = new Set([\n \"model\",\n \"messages\",\n \"system\",\n \"tools\",\n \"mcp_servers\",\n \"stream\",\n]);\n\n/** Body fields `messages.countTokens` accepts, copied from the full request body. */\nconst COUNT_TOKENS_FIELDS = [\n \"model\",\n \"messages\",\n \"system\",\n \"tools\",\n \"tool_choice\",\n \"thinking\",\n \"output_config\",\n \"cache_control\",\n \"context_management\",\n \"mcp_servers\",\n] as const;\n\n/** Beta flag for typed context editing (Anthropic docs, \"Context editing\", read 2026-10-17). */\nconst CONTEXT_MANAGEMENT_BETA = \"context-management-2025-06-27\";\n\n/** Beta flag for threshold compaction (Anthropic docs, \"Compaction at a token threshold\"). */\nconst COMPACTION_BETA = \"compact-2026-01-12\";\n\n/** Beta flag for `thinking.block_binding` (Anthropic docs, \"Preserved thinking\"). */\nconst THINKING_BINDING_BETA = \"thinking-binding-controls-2026-08-01\";\n\n/** The API rejects a compaction trigger below 50,000 input tokens. */\nconst MIN_COMPACTION_TRIGGER = 50_000;\n\ntype ContextEdit = { type: string } & Record<string, unknown>;\n\n/**\n * Translate the typed `contextManagement` / `serverCompaction` options into\n * `context_management.edits`. `clear_thinking_20251015` must come first\n * when strategies are combined (Anthropic docs, \"Context editing\").\n */\nfunction buildContextEdits(\n anthropic: AnthropicCallOptions,\n neutral?: ModelCallOptions[\"contextEditing\"],\n): ContextEdit[] {\n const edits: ContextEdit[] = [];\n const { clearThinking } = anthropic.contextManagement ?? {};\n // The vendor-neutral hint fills in only what the typed Anthropic options\n // leave unset, so an explicit `contextManagement.clearToolUses` wins.\n const clearToolUses: true | AnthropicClearToolUses | undefined =\n anthropic.contextManagement?.clearToolUses ?? neutralClearToolUses(neutral);\n\n if (clearThinking) {\n edits.push(clearThinkingEdit(clearThinking === true ? {} : clearThinking));\n }\n\n if (clearToolUses) {\n edits.push(clearToolUsesEdit(clearToolUses === true ? {} : clearToolUses));\n }\n\n if (anthropic.serverCompaction) {\n const compaction = anthropic.serverCompaction === true ? {} : anthropic.serverCompaction;\n\n if (compaction.triggerTokens !== undefined) {\n assertCount(\n \"serverCompaction.triggerTokens\",\n compaction.triggerTokens,\n MIN_COMPACTION_TRIGGER,\n );\n }\n\n edits.push({\n type: \"compact_20260112\",\n ...(compaction.triggerTokens !== undefined\n ? { trigger: { type: \"input_tokens\", value: compaction.triggerTokens } }\n : {}),\n ...(compaction.instructions ? { instructions: compaction.instructions } : {}),\n });\n }\n\n return edits;\n}\n\nfunction neutralClearToolUses(\n neutral: ModelCallOptions[\"contextEditing\"],\n): AnthropicClearToolUses | undefined {\n const rule = neutral?.clearToolResults;\n\n if (!rule) return undefined;\n\n return {\n ...(rule.afterTokens !== undefined ? { trigger: { inputTokens: rule.afterTokens } } : {}),\n ...(rule.keep !== undefined ? { keep: rule.keep } : {}),\n ...(rule.exclude?.length ? { excludeTools: rule.exclude } : {}),\n };\n}\n\nfunction clearThinkingEdit(options: AnthropicClearThinking): ContextEdit {\n if (options.keep === undefined || options.keep === \"all\") {\n return { type: \"clear_thinking_20251015\", ...(options.keep ? { keep: \"all\" } : {}) };\n }\n\n assertCount(\"contextManagement.clearThinking.keep\", options.keep, 1);\n\n return {\n type: \"clear_thinking_20251015\",\n keep: { type: \"thinking_turns\", value: options.keep },\n };\n}\n\nfunction clearToolUsesEdit(options: AnthropicClearToolUses): ContextEdit {\n const edit: ContextEdit = { type: \"clear_tool_uses_20250919\" };\n\n if (options.trigger) {\n const trigger =\n \"inputTokens\" in options.trigger\n ? { type: \"input_tokens\", value: options.trigger.inputTokens }\n : { type: \"tool_uses\", value: options.trigger.toolUses };\n\n assertCount(\"contextManagement.clearToolUses.trigger\", trigger.value, 1);\n edit.trigger = trigger;\n }\n\n if (options.keep !== undefined) {\n assertCount(\"contextManagement.clearToolUses.keep\", options.keep, 0);\n edit.keep = { type: \"tool_uses\", value: options.keep };\n }\n\n if (options.clearAtLeast !== undefined) {\n assertCount(\"contextManagement.clearToolUses.clearAtLeast\", options.clearAtLeast, 1);\n edit.clear_at_least = { type: \"input_tokens\", value: options.clearAtLeast };\n }\n\n if (options.excludeTools !== undefined) {\n edit.exclude_tools = [...options.excludeTools];\n }\n\n if (options.clearToolInputs !== undefined) {\n edit.clear_tool_inputs = Array.isArray(options.clearToolInputs)\n ? [...options.clearToolInputs]\n : options.clearToolInputs;\n }\n\n return edit;\n}\n\nfunction assertCount(field: string, value: number, minimum: number): void {\n if (!Number.isSafeInteger(value) || value < minimum) {\n throw new InvalidRequestError(\n `providerOptions.anthropic.${field} must be an integer of at least ${minimum}; got ${value}.`,\n { context: { field } },\n );\n }\n}\n\ntype IterationTotals = { input: number; output: number; cacheRead: number; cacheWrite: number };\n\n/**\n * Tokens of the `compaction` entries in a beta response's `usage.iterations`.\n * With server-side compaction the top-level `input_tokens` / `output_tokens`\n * cover only the non-compaction iterations; the billed total is the sum\n * over every iteration (Anthropic docs, \"Compaction at a token threshold\" →\n * \"Understanding usage\", read 2026-10-17). Zeros when there are none.\n */\nfunction compactionIterationUsage(raw: unknown): IterationTotals {\n const totals: IterationTotals = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };\n const iterations = (raw as { iterations?: unknown } | null | undefined)?.iterations;\n\n if (!Array.isArray(iterations)) {\n return totals;\n }\n\n for (const entry of iterations as unknown[]) {\n const iteration = entry as Record<string, unknown> | null;\n\n if (iteration?.type !== \"compaction\") {\n continue;\n }\n\n totals.input += numberOrZero(iteration.input_tokens);\n totals.output += numberOrZero(iteration.output_tokens);\n totals.cacheRead += numberOrZero(iteration.cache_read_input_tokens);\n totals.cacheWrite += numberOrZero(iteration.cache_creation_input_tokens);\n }\n\n return totals;\n}\n\nfunction numberOrZero(value: unknown): number {\n return typeof value === \"number\" && Number.isFinite(value) ? value : 0;\n}\n\nfunction addCacheCounts(usage: Usage, extra: IterationTotals): void {\n if (extra.cacheRead > 0) {\n usage.cachedTokens = (usage.cachedTokens ?? 0) + extra.cacheRead;\n }\n\n if (extra.cacheWrite > 0) {\n usage.cacheWriteTokens = (usage.cacheWriteTokens ?? 0) + extra.cacheWrite;\n }\n}\n\n/** Read `providerOptions.anthropic`, tolerating its absence or a wrong shape. */\nfunction resolveAnthropicOptions(options: ModelCallOptions | undefined): AnthropicCallOptions {\n const raw = options?.providerOptions?.anthropic;\n\n return typeof raw === \"object\" && raw !== null ? (raw as AnthropicCallOptions) : {};\n}\n\nfunction windowCapability(window: number | undefined): { contextWindow?: number } {\n return window === undefined ? {} : { contextWindow: window };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAqDA,MAAM,aAAa;;AAGnB,MAAM,wBAAwB;;;;;;;;;;;;;;;AAgB9B,MAAM,qBAAqB;;;;;;;AAQ3B,MAAM,oBAAoB;;;;;;AAO1B,MAAM,sBAAsB;;;;;;;AAU5B,MAAM,0BAA0C;;;;;;;;;;;AAYhD,MAAM,yBAAyD;CAG7D,SAAS;CACT,KAAK;CACL,QAAQ;CACR,MAAM;CAIN,OAAO;CACP,KAAK;AACP;;;;;;;;AASA,MAAM,0BAGF;CACF,SAAS;CACT,KAAK;CACL,QAAQ;CACR,MA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idRequestError,\n resolveStreamChunks,\n safeJsonParse,\n selectProviderTools,\n type Message,\n type ModelCallOptions,\n type ModelCapabilities,\n type ModelContract,\n type ModelPricing,\n type ModelResponse,\n type ModelStreamChunk,\n type ModelToolCallRequest,\n type ReasoningEffort,\n type Usage,\n} from \"@warlock.js/ai\";\nimport { log, type Logger } from \"@warlock.js/logger\";\nimport type Anthropic from \"@anthropic-ai/sdk\";\nimport type {\n AnthropicCallOptions,\n AnthropicClearThinking,\n AnthropicClearToolUses,\n AnthropicModelConfig,\n} from \"./config.type\";\nimport type {\n AnthropicRequest,\n AnthropicRequestOptions,\n AnthropicStreamingRequest,\n AnthropicNonStreamingRequest,\n} from \"./request.type\";\nimport { anthropicPricingFor, withAnthropicCacheWriteRates } from \"./known-pricing\";\nimport { inferContextWindow } from \"./known-context-windows\";\nimport { inferMaxOutputTokens } from \"./known-output-limits\";\nimport { inferVisionCapability } from \"./known-vision-models\";\nimport {\n acceptsTemperature,\n inferPreservedThinking,\n inferThinkingMode,\n type AnthropicThinkingMode,\n noReasoningForm,\n} from \"./thinking-mode\";\nimport { applyServerToolUsage } from \"./utils/server-tool-usage\";\nimport { applyAnthropicCacheUsage, requestCacheTtl } from \"./utils/cache-usage\";\nimport {\n mapStopReason,\n toAnthropicMessages,\n toAnthropicTools,\n toProviderBlocks,\n wrapAnthropicError,\n} from \"./utils\";\n\nconst LOG_MODULE = \"ai.anthropic\";\n\n/** `provider` value of `ai.providerTool()` entries this adapter sends verbatim. */\nconst ANTHROPIC_WIRE_FORMAT = \"anthropic\";\n\n/**\n * Anthropic requires `max_tokens` on every request (unlike OpenAI,\n * where it is optional). When neither the per-call option nor the model\n * config supplies one, the adapter picks a default large enough for agent\n * work (see `resolveDefaultMaxTokens`):\n *\n * - streaming: the model's documented max output (`known-output-limits.ts`,\n * or `config.maxOutputTokens`), else this value;\n * - non-streaming: this value, capped by the model's max output. The\n * installed `@anthropic-ai/sdk` (0.129.0, `calculateNonstreamingTimeout`)\n * refuses a non-streaming request whose `max_tokens` implies more than\n * ten minutes (above ~21,333 tokens) unless the client sets a `timeout`,\n * so the non-streaming default stays below that.\n */\nconst DEFAULT_MAX_TOKENS = 16_384;\n\n/**\n * Answer room kept on top of a thinking budget when the default\n * `max_tokens` is sized: thinking counts toward `max_tokens` (installed\n * SDK `ThinkingConfigParam` docs, `messages.d.ts:1105`), and in budget\n * mode `max_tokens` must exceed `budget_tokens`.\n */\nconst MIN_ANSWER_TOKENS = 4096;\n\n/**\n * Anthropic rejects an extended-thinking budget below 1024 tokens, so\n * any resolved budget is floored at this minimum before it reaches the\n * wire.\n */\nconst MIN_THINKING_BUDGET = 1024;\n\ntype ThinkingEffort = Exclude<ReasoningEffort, \"none\">;\n\n/**\n * Effort used when the caller asks for reasoning with only\n * `reasoning.maxTokens` and no `effort`. `\"medium\"` is what the adapter\n * has always assumed (the budget lookup fell back to\n * `EFFORT_THINKING_BUDGET.medium`), so adaptive models get the same tier.\n */\nconst DEFAULT_THINKING_EFFORT: ThinkingEffort = \"medium\";\n\n/**\n * Map the neutral `ReasoningEffort` level to a thinking token count.\n *\n * - Budget-mode models: sent as `thinking.budget_tokens` when the caller\n * doesn't pass an explicit `reasoning.maxTokens`.\n * - Both modes: when the caller sets no `maxTokens`, the default\n * `max_tokens` keeps at least this budget plus `MIN_ANSWER_TOKENS`,\n * because thinking counts toward `max_tokens` (installed SDK\n * `ThinkingConfigParam` docs, `messages.d.ts:1105`).\n */\nconst EFFORT_THINKING_BUDGET: Record<ThinkingEffort, number> = {\n // Anthropic's adaptive output config has no `minimal`; keep the minimum\n // budget for it in legacy budget mode too.\n minimal: 1024,\n low: 1024,\n medium: 4096,\n high: 12000,\n // Keep the tiers monotonic for older budget-mode models. Explicit\n // reasoning.maxTokens still wins and the existing max_tokens validation\n // remains authoritative.\n xhigh: 24000,\n max: 32000,\n};\n\n/**\n * Map the neutral `ReasoningEffort` level to Anthropic's\n * `output_config.effort` for adaptive-mode models. The installed SDK\n * accepts `low | medium | high | xhigh | max` (`OutputConfig.effort`,\n * `messages.ts:2767`); map every supported value 1:1 and clamp `minimal` to\n * the nearest accepted value, `low`.\n */\nconst EFFORT_TO_OUTPUT_EFFORT: Record<\n ThinkingEffort,\n NonNullable<Anthropic.OutputConfig[\"effort\"]>\n> = {\n minimal: \"low\",\n low: \"low\",\n medium: \"medium\",\n high: \"high\",\n xhigh: \"xhigh\",\n max: \"max\",\n};\n\ntype AnthropicThinkingBlock = Anthropic.ThinkingBlock | Anthropic.RedactedThinkingBlock;\n\n/**\n * The SDK's `messages.create` (or `beta.messages.create`) seen through a\n * loose signature: provider-option body fields and beta flags are merged\n * in untyped, and the response is narrowed by the caller.\n */\ntype LooseCreate = (\n body: Record<string, unknown>,\n options?: { signal?: AbortSignal },\n) => Promise<unknown>;\n\n/** Content-block types whose input arrives as `input_json_delta` while streaming. */\nconst STREAMED_INPUT_BLOCK_TYPES = new Set([\"tool_use\", \"server_tool_use\", \"mcp_tool_use\"]);\n\n/** One content block being assembled from stream events. */\ntype StreamedBlock = { block: Record<string, unknown>; json?: string };\n\n/**\n * Resolved thinking settings for one request.\n *\n * - `thinking`: the wire `thinking` field (absent = send nothing).\n * - `effort`: `output_config.effort`, set for adaptive-mode models only.\n * - `reservedTokens`: thinking tokens the default `max_tokens` must leave\n * room for (plus `MIN_ANSWER_TOKENS`) when the caller configured no\n * `maxTokens`.\n */\ntype ThinkingRequest = {\n thinking?: Anthropic.ThinkingConfigParam;\n effort?: Anthropic.OutputConfig[\"effort\"];\n reservedTokens?: number;\n};\n\n/**\n * Anthropic-backed implementation of `ModelContract`.\n *\n * **Role.** The provider-facing bridge between the vendor-neutral\n * `@warlock.js/ai` agent runtime and the official `@anthropic-ai/sdk`\n * Messages API. Agents, workflows, and supervisors never talk to\n * Anthropic directly — they hold a `ModelContract`, and this class is\n * what makes that contract concrete for Claude models.\n *\n * **Responsibility.**\n * - Owns: a long-lived `Anthropic` client + frozen `ModelConfig`\n * (name, temperature, maxTokens) used as defaults for every call.\n * - Owns: translating vendor-neutral `Message[]` / `ToolConfig[]` into\n * Anthropic wire shapes (system hoisting, `tool_use` / `tool_result`\n * blocks) on the way out, and translating Anthropic's content-block\n * response (text, tool calls, stop reason, usage) back into the\n * neutral shapes on the way in.\n * - Does NOT own: dispatching tools, deciding whether to loop, tracking\n * conversation history, or retrying on failure — those are agent\n * concerns. The model is a stateless (per-call) protocol adapter.\n *\n * Because it holds a live client and shared defaults, it is modeled as\n * a class (see §4.2 of code-style.md — \"long-lived state across\n * calls\").\n *\n * @example\n * import Anthropic from \"@anthropic-ai/sdk\";\n * const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });\n * const model = new AnthropicModel(client, { name: \"claude-sonnet-4-6\" });\n *\n * const myAgent = agent({\n * model,\n * systemPrompt: \"You are a helpful assistant.\",\n * tools: [searchTool],\n * });\n *\n * const result = await myAgent.execute(\"Summarize today's news.\");\n */\nexport class AnthropicModel implements ModelContract {\n public readonly name: string;\n public readonly provider: string;\n public readonly capabilities: ModelCapabilities;\n public readonly pricing?: ModelPricing;\n\n private readonly client: Anthropic;\n private readonly config: AnthropicModelConfig;\n private readonly thinkingMode: AnthropicThinkingMode;\n /** Documented max output tokens of this model, when known. Sizes the default `max_tokens`. */\n private readonly maxOutputTokens?: number;\n private readonly preservedThinking: boolean;\n private readonly logger: Logger = log;\n\n public constructor(\n client: Anthropic,\n config: AnthropicModelConfig,\n provider: string = \"anthropic\",\n ) {\n this.client = client;\n this.config = config;\n this.name = config.name;\n this.provider = provider;\n // Explicit pricing (per-model, or the SDK registry) wins over the\n // built-in Claude list prices; either way the Anthropic cache-write\n // multipliers fill any write rate the entry leaves out.\n this.pricing = withAnthropicCacheWriteRates(config.pricing ?? anthropicPricingFor(config.name));\n // Adaptive vs budget thinking — also decides whether `temperature` is\n // accepted. Explicit config wins over name inference, like `vision`.\n this.thinkingMode = config.thinkingMode ?? inferThinkingMode(config.name);\n this.maxOutputTokens = config.maxOutputTokens ?? inferMaxOutputTokens(config.name);\n // Budget-mode models predate preserved thinking; explicit config wins.\n this.preservedThinking =\n config.preservedThinking ??\n (this.thinkingMode === \"adaptive\" && inferPreservedThinking(config.name));\n this.capabilities = {\n structuredOutput: config.structuredOutput ?? true,\n vision: config.vision ?? inferVisionCapability(config.name),\n // Tool results carry `image` blocks.\n toolResultImages: true,\n // Every modern Claude model accepts Anthropic extended thinking\n // (adaptive or `budget_tokens`, per `thinkingMode`). Advertise the\n // reasoning channel so the agent forwards `reasoning` options;\n // explicit config override wins for proxied/legacy targets.\n reasoning: config.reasoning ?? true,\n ...windowCapability(config.contextWindow ?? inferContextWindow(config.name)),\n // Anthropic prompt caching is caller-driven via `cache_control`\n // breakpoints. The adapter both places those breakpoints (tools\n // when `config.promptCaching`, system when\n // `options.cacheControl.breakpoints`) and reports the read/write\n // accounting (`cachedTokens` / `cacheWriteTokens`), so advertise\n // the capability unconditionally.\n promptCaching: true,\n // `ModelCallOptions.contextEditing.clearToolResults` maps to the\n // `clear_tool_uses` context edit (see `resolveContextManagement`).\n nativeContextEditing: true,\n // The Messages API accepts PDF/document content blocks\n // (`DocumentBlockParam`) on vision-capable Claude models.\n pdf: true,\n // Anthropic has no audio input content block, so `audio` stays\n // absent (treated as false) and the agent rejects audio\n // attachments upfront rather than dropping them at the wire layer.\n };\n }\n\n /**\n * Single-shot completion. Sends the full message list to the Messages\n * endpoint, waits for the terminal response, and reshapes it into a\n * vendor-neutral `ModelResponse`. Per-call `options` override the\n * instance's `ModelConfig` defaults for this call only.\n */\n public async complete(messages: Message[], options?: ModelCallOptions): Promise<ModelResponse> {\n return this.send(this.buildLoggedRequest(messages, { ...options, stream: false }), {\n signal: options?.signal,\n });\n }\n\n /** Build a detached request snapshot without sending it to Anthropic. */\n public buildRequest(\n messages: Message[],\n options: ModelCallOptions & { stream: true },\n ): AnthropicStreamingRequest;\n public buildRequest(\n messages: Message[],\n options?: ModelCallOptions & { stream?: false },\n ): AnthropicNonStreamingRequest;\n public buildRequest(\n messages: Message[],\n options?: ModelCallOptions & { stream?: boolean },\n ): AnthropicRequest;\n public buildRequest(\n messages: Message[],\n options?: ModelCallOptions & { stream?: boolean },\n ): AnthropicRequest {\n const built = this.buildBody(messages, options);\n const betas = [...new Set([...(resolveAnthropicOptions(options).betas ?? []), ...built.betas])];\n const body = structuredClone({ ...built.body, stream: options?.stream ?? false });\n\n return { endpoint: betas.length > 0 ? \"beta.messages\" : \"messages\", body, betas };\n }\n\n /**\n * `buildRequest()` for the adapter's own calls: a build failure (a reserved\n * body key, a `providerOptions.anthropic.body` value `structuredClone`\n * cannot copy) is logged like a send failure and rejects as an `AIError`.\n * Errors that are not already an `AIError` become an `InvalidRequestError`,\n * since nothing reached Anthropic and retrying cannot help.\n */\n private buildLoggedRequest(\n messages: Message[],\n options: ModelCallOptions & { stream: true },\n ): AnthropicStreamingRequest;\n private buildLoggedRequest(\n messages: Message[],\n options: ModelCallOptions & { stream: false },\n ): AnthropicNonStreamingRequest;\n private buildLoggedRequest(\n messages: Message[],\n options: ModelCallOptions & { stream: boolean },\n ): AnthropicRequest;\n private buildLoggedRequest(\n messages: Message[],\n options: ModelCallOptions & { stream: boolean },\n ): AnthropicRequest {\n try {\n return this.buildRequest(messages, options);\n } catch (thrown) {\n throw this.logAndWrap(\n thrown instanceof AIError\n ? thrown\n : new InvalidRequestError(\n `Could not build the Anthropic request: ${thrown instanceof Error ? thrown.message : String(thrown)}`,\n { cause: thrown },\n ),\n );\n }\n }\n\n /** Send a built request without rebuilding its body or applying model defaults. */\n public send(\n request: AnthropicNonStreamingRequest,\n options?: AnthropicRequestOptions,\n ): Promise<ModelResponse>;\n public send(\n request: AnthropicStreamingRequest,\n options?: AnthropicRequestOptions,\n ): AsyncIterable<ModelStreamChunk>;\n public send(\n request: AnthropicRequest,\n options?: AnthropicRequestOptions,\n ): Promise<ModelResponse> | AsyncIterable<ModelStreamChunk>;\n public send(\n request: AnthropicRequest,\n options?: AnthropicRequestOptions,\n ): Promise<ModelResponse> | AsyncIterable<ModelStreamChunk> {\n const message = request.body.stream\n ? \"Starting streaming call to messages.create\"\n : \"Starting call to messages.create\";\n\n this.logger.debug(LOG_MODULE, \"request\", message, {\n model: request.body.model,\n messageCount: Array.isArray(request.body.messages) ? request.body.messages.length : 0,\n streaming: request.body.stream,\n toolCount: Array.isArray(request.body.tools) ? request.body.tools.length : 0,\n });\n\n return request.body.stream\n ? this.streamRequest(request, options)\n : this.completeRequest(request, options);\n }\n\n private async completeRequest(\n request: AnthropicRequest,\n options?: AnthropicRequestOptions,\n ): Promise<ModelResponse> {\n let response: Anthropic.Message;\n\n try {\n response = (await this.dispatch(request, options, \"create\")) as Anthropic.Message;\n } catch (thrown) {\n throw this.logAndWrap(thrown);\n }\n\n const finishReason = mapStopReason(response.stop_reason);\n const usage = this.extractUsage(response.usage, requestCacheTtl(request.body));\n const toolCalls = this.extractToolCalls(response.content);\n const blocks = toProviderBlocks(response.content);\n\n this.logger.debug(LOG_MODULE, \"response\", \"call to messages.create succeeded\", {\n finishReason,\n usage,\n });\n\n return {\n content: this.extractText(response.content),\n finishReason,\n usage,\n toolCalls,\n ...(blocks ? { blocks } : {}),\n };\n }\n\n /**\n * Count the input tokens a request would use, through Anthropic's\n * `messages.countTokens` endpoint (a network call; no tokens are\n * generated or billed as output). Takes the same messages and options\n * as `complete()` — system prompt, tools, thinking and\n * `providerOptions.anthropic.betas` are counted exactly as they would be\n * sent. For an offline estimate use `AnthropicSDK.count()`.\n *\n * @example\n * const tokens = await model.countTokens(messages, { tools });\n */\n public async countTokens(messages: Message[], options?: ModelCallOptions): Promise<number> {\n const request = this.buildLoggedRequest(messages, {\n ...options,\n stream: options?.stream === true,\n });\n const body = request.body;\n const countBody: Record<string, unknown> = {};\n\n for (const key of COUNT_TOKENS_FIELDS) {\n if (body[key] !== undefined) {\n countBody[key] = body[key];\n }\n }\n\n try {\n const result = (await this.dispatch(\n { ...request, body: countBody },\n options,\n \"countTokens\",\n )) as {\n input_tokens: number;\n };\n\n return result.input_tokens;\n } catch (thrown) {\n throw this.logAndWrap(thrown);\n }\n }\n\n /**\n * Incremental streaming completion. Yields neutral `ModelStreamChunk`s\n * — `delta` for text tokens, `tool-call` once a `tool_use` block's\n * arguments have fully accumulated, and a terminal `done` carrying the\n * final finish reason + usage totals. Callers consume it with\n * `for await`.\n *\n * With `options.streamChunks` it also yields `reasoning` for every\n * non-empty `thinking_delta`, `tool-args` for every `input_json_delta`\n * of a client `tool_use` block, and `usage` after `message_start` and\n * each `message_delta` (whose counts are cumulative).\n */\n public async *stream(\n messages: Message[],\n options?: ModelCallOptions,\n ): AsyncIterable<ModelStreamChunk> {\n yield* this.send(this.buildLoggedRequest(messages, { ...options, stream: true }), {\n signal: options?.signal,\n streamChunks: options?.streamChunks,\n });\n }\n\n private async *streamRequest(\n request: AnthropicRequest,\n options?: AnthropicRequestOptions,\n ): AsyncIterable<ModelStreamChunk> {\n let stream: AsyncIterable<Anthropic.RawMessageStreamEvent>;\n\n try {\n stream = (await this.dispatch(\n request,\n options,\n \"create\",\n )) as AsyncIterable<Anthropic.RawMessageStreamEvent>;\n } catch (thrown) {\n throw this.logAndWrap(thrown);\n }\n\n let rawStopReason: string | null = null;\n let compaction = compactionIterationUsage(undefined);\n const usage: Usage = { input: 0, output: 0, total: 0, inputIncludesCache: false };\n const cacheTtl = requestCacheTtl(request.body);\n const want = resolveStreamChunks(options);\n const toolBlocks = new Map<number, { id: string; name: string; json: string }>();\n const thinkingBlocks = new Map<number, AnthropicThinkingBlock>();\n // Every content block of the turn, by index, so the full ordered turn\n // can be returned as `blocks` (thinking, compaction, server tools…).\n const streamedBlocks = new Map<number, StreamedBlock>();\n\n try {\n for await (const event of stream) {\n this.trackStreamedBlock(streamedBlocks, event);\n\n if (event.type === \"message_start\") {\n usage.input = event.message.usage.input_tokens ?? 0;\n\n const thinkingTokens = event.message.usage.output_tokens_details?.thinking_tokens;\n\n if (thinkingTokens !== null && thinkingTokens !== undefined) {\n usage.reasoningTokens = thinkingTokens;\n }\n\n applyServerToolUsage(usage, event.message.usage.server_tool_use);\n applyAnthropicCacheUsage(usage, event.message.usage, cacheTtl);\n\n if (want.usage) {\n yield { type: \"usage\", usage: { ...usage, total: usage.input + usage.output } };\n }\n\n continue;\n }\n\n if (event.type === \"content_block_start\") {\n const block = event.content_block;\n\n if (block.type === \"tool_use\") {\n toolBlocks.set(event.index, { id: block.id, name: block.name, json: \"\" });\n } else if (block.type === \"thinking\") {\n thinkingBlocks.set(event.index, { ...block });\n } else if (block.type === \"redacted_thinking\") {\n thinkingBlocks.set(event.index, { ...block });\n }\n\n continue;\n }\n\n if (event.type === \"content_block_delta\") {\n if (event.delta.type === \"text_delta\") {\n yield { type: \"delta\", content: event.delta.text };\n } else if (event.delta.type === \"input_json_delta\") {\n const accumulator = toolBlocks.get(event.index);\n\n if (accumulator) {\n accumulator.json += event.delta.partial_json;\n\n // Only client `tool_use` blocks: a `server_tool_use` input\n // (e.g. a web search query) never becomes a `tool-call`.\n if (want.toolArgs && event.delta.partial_json !== \"\") {\n yield {\n type: \"tool-args\",\n callId: accumulator.id,\n name: accumulator.name,\n delta: event.delta.partial_json,\n };\n }\n }\n } else if (event.delta.type === \"thinking_delta\") {\n const thinking = thinkingBlocks.get(event.index);\n\n if (thinking?.type === \"thinking\") {\n thinking.thinking += event.delta.thinking;\n }\n\n // `display: \"omitted\"` streams one empty `thinking_delta`.\n if (want.reasoning && event.delta.thinking !== \"\") {\n yield { type: \"reasoning\", delta: event.delta.thinking };\n }\n } else if (event.delta.type === \"signature_delta\") {\n const thinking = thinkingBlocks.get(event.index);\n\n if (thinking?.type === \"thinking\") {\n thinking.signature += event.delta.signature;\n }\n }\n\n continue;\n }\n\n if (event.type === \"content_block_stop\") {\n const accumulator = toolBlocks.get(event.index);\n\n if (accumulator) {\n yield {\n type: \"tool-call\",\n id: accumulator.id,\n name: accumulator.name,\n input: safeJsonParse<Record<string, unknown>>(accumulator.json, {}),\n ...this.buildThinkingMetadata(\n Array.from(thinkingBlocks.entries())\n .sort(([left], [right]) => left - right)\n .map(([, block]) => block),\n ),\n };\n\n toolBlocks.delete(event.index);\n }\n\n continue;\n }\n\n if (event.type === \"message_delta\") {\n rawStopReason = event.delta.stop_reason ?? rawStopReason;\n // The final delta carries every iteration of the request.\n if (Array.isArray((event.usage as { iterations?: unknown }).iterations)) {\n compaction = compactionIterationUsage(event.usage);\n }\n applyServerToolUsage(usage, event.usage.server_tool_use);\n usage.output = event.usage.output_tokens ?? usage.output;\n\n const thinkingTokens = event.usage.output_tokens_details?.thinking_tokens;\n\n if (thinkingTokens !== null && thinkingTokens !== undefined) {\n usage.reasoningTokens = thinkingTokens;\n }\n\n // `message_delta.usage` carries the cumulative cache counts —\n // prefer them over the `message_start` snapshot when present\n // and non-zero so the terminal `done` reflects the final tally.\n // It has no per-lifetime breakdown, so a 1-hour share already\n // read from `message_start` is kept.\n applyAnthropicCacheUsage(\n usage,\n {\n cache_read_input_tokens: event.usage.cache_read_input_tokens,\n cache_creation_input_tokens: event.usage.cache_creation_input_tokens,\n cache_creation:\n usage.cacheWrite1hTokens !== undefined\n ? { ephemeral_1h_input_tokens: usage.cacheWrite1hTokens }\n : undefined,\n },\n cacheTtl,\n );\n\n // `message_delta.usage` counts are cumulative (Anthropic streaming\n // docs), so this is the running total so far.\n if (want.usage) {\n yield { type: \"usage\", usage: { ...usage, total: usage.input + usage.output } };\n }\n }\n }\n } catch (thrown) {\n throw this.logAndWrap(thrown);\n }\n\n usage.input += compaction.input;\n usage.output += compaction.output;\n addCacheCounts(usage, compaction);\n usage.total = usage.input + usage.output;\n\n const cost = computeCost(usage, this.pricing);\n\n if (cost) {\n usage.cost = cost;\n }\n\n const finishReason = mapStopReason(rawStopReason);\n const blocks = toProviderBlocks(this.finishStreamedBlocks(streamedBlocks));\n\n this.logger.debug(LOG_MODULE, \"response\", \"Streaming call to messages.create succeeded\", {\n finishReason,\n usage,\n });\n\n yield { type: \"done\", finishReason, usage, ...(blocks ? { blocks } : {}) };\n }\n\n /**\n * Fold one stream event into the per-index block accumulator. Unknown\n * block and delta types (beta `compaction`, future additions) are kept\n * as their start payload plus whatever their delta carries, so they\n * round-trip without the adapter knowing their shape.\n */\n private trackStreamedBlock(\n blocks: Map<number, StreamedBlock>,\n event: Anthropic.RawMessageStreamEvent,\n ): void {\n if (event.type === \"content_block_start\") {\n const block = { ...(event.content_block as unknown as Record<string, unknown>) };\n\n blocks.set(event.index, {\n block,\n ...(STREAMED_INPUT_BLOCK_TYPES.has(String(block.type)) ? { json: \"\" } : {}),\n });\n\n return;\n }\n\n if (event.type !== \"content_block_delta\") {\n return;\n }\n\n const entry = blocks.get(event.index);\n\n if (!entry) {\n return;\n }\n\n const delta = event.delta as unknown as Record<string, unknown> & { type: string };\n const block = entry.block;\n\n if (delta.type === \"text_delta\") {\n block.text = String(block.text ?? \"\") + String(delta.text ?? \"\");\n } else if (delta.type === \"thinking_delta\") {\n block.thinking = String(block.thinking ?? \"\") + String(delta.thinking ?? \"\");\n } else if (delta.type === \"signature_delta\") {\n block.signature = String(block.signature ?? \"\") + String(delta.signature ?? \"\");\n } else if (delta.type === \"input_json_delta\") {\n entry.json = (entry.json ?? \"\") + String(delta.partial_json ?? \"\");\n } else if (delta.type === \"citations_delta\") {\n block.citations = [\n ...(Array.isArray(block.citations) ? block.citations : []),\n delta.citation,\n ];\n } else {\n // e.g. beta `compaction_delta` — carries the block's final fields.\n for (const [key, value] of Object.entries(delta)) {\n if (key !== \"type\") {\n block[key] = value;\n }\n }\n }\n }\n\n /** Close the accumulated stream blocks into an ordered content array. */\n private finishStreamedBlocks(blocks: Map<number, StreamedBlock>): Array<{ type: string }> {\n return Array.from(blocks.entries())\n .sort(([left], [right]) => left - right)\n .map(([, { block, json }]) => {\n if (json !== undefined) {\n block.input = safeJsonParse<Record<string, unknown>>(json, {});\n }\n\n return block as { type: string };\n });\n }\n\n /**\n * Send a request through the SDK. With `providerOptions.anthropic.betas`\n * the call goes to `client.beta.messages` (which takes the `betas` list\n * and the beta-only body fields); otherwise to `client.messages`. The\n * cancellation signal rides in the request options, as before.\n */\n private dispatch(\n request: {\n endpoint: AnthropicRequest[\"endpoint\"];\n body: Record<string, unknown>;\n betas: string[];\n },\n options: AnthropicRequestOptions | undefined,\n method: \"create\" | \"countTokens\",\n ): Promise<unknown> {\n const requestOptions = options?.signal ? { signal: options.signal } : undefined;\n const api =\n request.endpoint === \"beta.messages\" ? this.client.beta.messages : this.client.messages;\n const call = api[method] as unknown as LooseCreate;\n\n return call.call(\n api,\n request.endpoint === \"beta.messages\"\n ? { ...request.body, betas: request.betas }\n : request.body,\n requestOptions,\n );\n }\n\n /**\n * The full request body and the beta flags it needs: the adapter-built\n * params, then `thinking.display` when thinking is sent on an adaptive\n * model, the typed `thinkingBlockBinding`, `contextManagement` and\n * `serverCompaction` options, then `providerOptions.anthropic.body`\n * merged last (caller fields win). The body may add fields the adapter\n * does not build (`fallbacks`, …) but may not replace the conversation or\n * the model — see {@link RESERVED_BODY_FIELDS}.\n */\n private buildBody(\n messages: Message[],\n options: (ModelCallOptions & { stream?: boolean }) | undefined,\n ): { body: Record<string, unknown>; betas: string[] } {\n const anthropic = resolveAnthropicOptions(options);\n const betas: string[] = [];\n // Kept turns after a client-written summary carry thinking signed\n // against the replaced history. Leave it out on models that check the\n // conversation, unless the caller chose how the API handles it.\n const body: Record<string, unknown> = {\n ...this.buildParams(messages, options, {\n dropRetainedThinking:\n this.preservedThinking && anthropic.thinkingBlockBinding === undefined,\n }),\n };\n\n // `display` belongs to adaptive thinking only; `between_tools` takes\n // no other field and 400s with one.\n if (\n anthropic.thinkingDisplay &&\n this.thinkingMode === \"adaptive\" &&\n (body.thinking as { type?: string } | undefined)?.type === \"adaptive\"\n ) {\n body.thinking = {\n ...(body.thinking as Record<string, unknown>),\n display: anthropic.thinkingDisplay,\n };\n }\n\n if (anthropic.thinkingBlockBinding) {\n this.applyBlockBinding(body, anthropic.thinkingBlockBinding, betas);\n }\n\n const edits = buildContextEdits(anthropic, options?.contextEditing);\n\n if (edits.length > 0) {\n if (anthropic.body?.context_management !== undefined) {\n throw new InvalidRequestError(\n \"providerOptions.anthropic.contextManagement / serverCompaction cannot be combined with \" +\n \"body.context_management: set the edits in one place.\",\n { context: { fields: [\"context_management\"] } },\n );\n }\n\n body.context_management = { edits };\n\n if (edits.some((edit) => edit.type !== \"compact_20260112\")) {\n betas.push(CONTEXT_MANAGEMENT_BETA);\n }\n\n if (edits.some((edit) => edit.type === \"compact_20260112\")) {\n betas.push(COMPACTION_BETA);\n }\n }\n\n const reserved = Object.keys(anthropic.body ?? {}).filter((key) =>\n RESERVED_BODY_FIELDS.has(key),\n );\n\n if (reserved.length > 0) {\n throw new InvalidRequestError(\n `providerOptions.anthropic.body cannot set ${reserved.map((key) => `\"${key}\"`).join(\", \")}: ` +\n \"the adapter builds these from the call's messages, tools and model. \" +\n \"Use the agent/model options instead.\",\n { context: { fields: reserved } },\n );\n }\n\n return { body: { ...body, ...anthropic.body }, betas };\n }\n\n /**\n * Set `thinking.block_binding.prefix_mismatch_behavior`. It rides on\n * adaptive or budget (`enabled`) thinking. A model that runs adaptive\n * thinking when `thinking` is omitted (every preserved-thinking model) gets\n * an explicit `{ type: \"adaptive\" }`, which is the same request. Any other\n * shape (`between_tools`, `disabled`) takes no extra field, so the option\n * is skipped with a debug log.\n */\n private applyBlockBinding(\n body: Record<string, unknown>,\n behavior: \"error\" | \"drop_block\",\n betas: string[],\n ): void {\n const thinking = body.thinking as { type?: string } | undefined;\n const type = thinking?.type ?? (this.preservedThinking ? \"adaptive\" : undefined);\n\n if (type !== \"adaptive\" && type !== \"enabled\") {\n this.logger.debug(\n LOG_MODULE,\n \"thinking-block-binding.ignored\",\n \"thinkingBlockBinding needs adaptive or budget thinking on this request; not sent\",\n { model: this.name, thinking: thinking?.type ?? \"none\" },\n );\n\n return;\n }\n\n body.thinking = {\n ...(thinking ?? { type }),\n block_binding: { prefix_mismatch_behavior: behavior },\n };\n betas.push(THINKING_BINDING_BETA);\n }\n\n /**\n * Assemble the Anthropic request body shared by `complete()` and\n * `stream()` (each adds its own `stream` literal so the SDK's create\n * overload resolves to the right return type). Hoists the system\n * prompt out of `messages`, resolves `max_tokens` (required by\n * Anthropic) with the documented default, and conditionally attaches\n * temperature, tools, native structured output, extended thinking\n * (`reasoning`), and automatic or explicit prompt-cache control.\n * Temperature is dropped when thinking is enabled, since Anthropic\n * rejects the two together, and always for adaptive-mode models, which\n * reject any explicit temperature (see `acceptsTemperature`).\n */\n private buildParams(\n messages: Message[],\n options: (ModelCallOptions & { stream?: boolean }) | undefined,\n conversion: { dropRetainedThinking: boolean },\n ): Omit<Anthropic.MessageCreateParamsNonStreaming, \"stream\"> {\n const { system, messages: anthropicMessages } = toAnthropicMessages(messages, conversion);\n const thinking = this.buildThinking(options?.reasoning);\n const temperature = options?.temperature ?? this.config.temperature;\n const configuredMaxTokens = options?.maxTokens ?? this.config.maxTokens;\n const thinkingBudget =\n thinking.thinking?.type === \"enabled\" ? thinking.thinking.budget_tokens : undefined;\n const maxTokens =\n configuredMaxTokens ??\n this.resolveDefaultMaxTokens(options?.stream === true, thinking.reservedTokens);\n // Extended thinking pins sampling to the default temperature —\n // Anthropic 400s when `thinking` is enabled alongside any explicit\n // `temperature`. Models released after Opus 4.6 (adaptive mode) reject\n // an explicit temperature outright (installed SDK\n // `MessageCreateParamsBase.temperature`, `messages.d.ts:2036-2040`).\n // Drop it in both cases rather than letting the request fail.\n const sendTemperature =\n temperature !== undefined && !thinking.thinking && acceptsTemperature(this.thinkingMode);\n\n if (\n thinkingBudget !== undefined &&\n configuredMaxTokens !== undefined &&\n configuredMaxTokens <= thinkingBudget\n ) {\n throw new Error(\n `Anthropic maxTokens (${configuredMaxTokens}) must be greater than thinking budget_tokens (${thinkingBudget})`,\n );\n }\n\n return {\n model: this.name,\n max_tokens: maxTokens,\n messages: anthropicMessages,\n ...this.buildAutomaticCacheControl(options?.cacheControl),\n ...this.buildSystem(system, options?.cacheControl),\n ...(sendTemperature ? { temperature } : {}),\n ...this.buildTools(options, options?.cacheControl),\n ...this.buildOutputConfig(options?.responseSchema, thinking.effort),\n ...(thinking.thinking ? { thinking: thinking.thinking } : {}),\n };\n }\n\n /**\n * The `max_tokens` sent when neither the call nor the model config sets\n * `maxTokens`:\n *\n * - streaming: the model's documented max output, or\n * `DEFAULT_MAX_TOKENS` (16384) for an unknown id;\n * - non-streaming: `DEFAULT_MAX_TOKENS`, capped by the model's max output\n * (the SDK requires streaming for larger non-streaming requests unless\n * the client sets a `timeout`; see `DEFAULT_MAX_TOKENS`).\n *\n * With thinking on, the value is raised to at least the thinking budget\n * plus `MIN_ANSWER_TOKENS`, and never exceeds the model's max output.\n */\n private resolveDefaultMaxTokens(stream: boolean, reservedTokens: number | undefined): number {\n const limit = this.maxOutputTokens;\n const fallback = limit === undefined ? DEFAULT_MAX_TOKENS : Math.min(limit, DEFAULT_MAX_TOKENS);\n const base = stream ? (limit ?? DEFAULT_MAX_TOKENS) : fallback;\n const withThinking =\n reservedTokens === undefined ? base : Math.max(base, reservedTokens + MIN_ANSWER_TOKENS);\n\n return limit === undefined ? withThinking : Math.min(withThinking, limit);\n }\n\n /**\n * Spread-friendly `system` fragment. Returns an empty object when no\n * system prompt was hoisted out of the messages.\n *\n * When a per-call `cacheControl.breakpoints` hint is present (≥ 1),\n * the system prompt is emitted as a single `TextBlockParam` carrying\n * `cache_control: ephemeral` — the system prompt is the longest stable\n * prefix on a turn, so one breakpoint there lets multi-turn agents\n * read it back at the ~0.1x cache-read rate. Without the hint the\n * system prompt stays a plain string (left uncached) so a one-shot\n * call never pays the ~1.25x cache-write surcharge.\n */\n private buildSystem(\n system: string | undefined,\n cacheControl: ModelCallOptions[\"cacheControl\"],\n ): { system?: string | Anthropic.TextBlockParam[] } {\n if (!system) {\n return {};\n }\n\n const breakpoints = cacheControl?.breakpoints ?? 0;\n\n if (this.capabilities.promptCaching && breakpoints > 0) {\n return {\n system: [\n { type: \"text\", text: system, cache_control: this.cacheControl(cacheControl?.ttl) },\n ],\n };\n }\n\n return { system };\n }\n\n /**\n * Let Anthropic select the last cacheable block when caching is enabled\n * without a caller-selected breakpoint. An explicit breakpoint remains\n * authoritative, so the request-level form is deliberately omitted then.\n */\n private buildAutomaticCacheControl(cacheControl: ModelCallOptions[\"cacheControl\"]): {\n cache_control?: Anthropic.CacheControlEphemeral;\n } {\n const breakpoints = cacheControl?.breakpoints ?? 0;\n\n return this.config.promptCaching && breakpoints <= 0\n ? { cache_control: this.cacheControl(cacheControl?.ttl) }\n : {};\n }\n\n /**\n * Build a typed cache-control marker. The per-call\n * `cacheControl.ttl` wins over the model's `promptCacheTtl`; with\n * neither, TTL is omitted for Anthropic's 5-minute default.\n */\n private cacheControl(callTtl?: \"5m\" | \"1h\"): Anthropic.CacheControlEphemeral {\n const ttl = callTtl ?? this.config.promptCacheTtl;\n\n return {\n type: \"ephemeral\",\n ...(ttl ? { ttl } : {}),\n };\n }\n\n /**\n * Translate the neutral `reasoning` option into Anthropic's thinking\n * settings, in the shape this model accepts (`thinkingMode`). Emitted\n * only when the model declares the `reasoning` capability AND a\n * reasoning option is supplied; otherwise returns an empty object.\n *\n * - Adaptive mode (Opus 4.7+, Sonnet 5+, Fable 5+, unknown ids):\n * `thinking: { type: \"adaptive\" }` (installed SDK\n * `ThinkingConfigAdaptive`, `messages.d.ts:1065`) plus\n * `output_config.effort` from the neutral effort, defaulting to\n * `\"medium\"`. `budget_tokens` is never sent — these models 400 on it\n * (claude-api ref). `reasoning.maxTokens` only sizes the default\n * `max_tokens` headroom.\n * - Budget mode (Haiku 4.5, Opus/Sonnet 4.6, older):\n * `thinking: { type: \"enabled\", budget_tokens }`. An explicit\n * `reasoning.maxTokens` wins; otherwise the effort maps to a tiered\n * budget. `budget_tokens` must be ≥ 1024 (`ThinkingConfigEnabled`,\n * `messages.d.ts:1084`), so the budget is floored at that minimum.\n *\n * The neutral `effort: \"none\"` (\"run without reasoning\") is mapped per\n * model by `noReasoningForm` (see `thinking-mode.ts` for the sources):\n * - Claude Sonnet 5.5: `thinking: { type: \"between_tools\" }`, its only\n * thinking-off form. It is sent alone — no `output_config.effort` (the\n * model default, `high`, is within the `high`-or-below range it\n * requires) and no `display`, both of which the API rejects alongside it.\n * - Claude Sonnet 5 and Claude Haiku 5.5: `thinking: { type: \"disabled\" }`\n * with no effort and no `display`. Haiku 5.5 accepts `disabled` only at\n * effort `high` or below; its default (`medium`) applies.\n * - Claude Opus 5: adaptive thinking at `output_config.effort: \"low\"`.\n * Opus 5 accepts `disabled`, but with it the model can write a tool call\n * as plain text (the call never runs) and leak thinking tags; the lowest\n * effort is the documented alternative.\n * - Opus 5.5 and Fable 5/5.1: no `thinking` field. These models have no\n * thinking-off form (`disabled` and `budget_tokens` are a 400 at every\n * effort), so thinking still runs at the model's default effort. Pass\n * `effort: \"low\"` to spend less.\n * - Every other model: no `thinking` field, as before.\n */\n private buildThinking(reasoning: ModelCallOptions[\"reasoning\"]): ThinkingRequest {\n if (!this.capabilities.reasoning || !reasoning) {\n return {};\n }\n\n // `effort: \"none\"` is an explicit \"run without reasoning\", in the form\n // this model accepts. (This also short-circuits the\n // `EFFORT_THINKING_BUDGET[\"none\"]` → `undefined` → `NaN` budget path.)\n if (reasoning.effort === \"none\") {\n return this.buildNoReasoning();\n }\n\n if (reasoning.maxTokens === undefined && reasoning.effort === undefined) {\n return {};\n }\n\n const effort = reasoning.effort ?? DEFAULT_THINKING_EFFORT;\n const budget = Math.max(\n MIN_THINKING_BUDGET,\n reasoning.maxTokens ?? EFFORT_THINKING_BUDGET[effort],\n );\n\n if (this.thinkingMode === \"adaptive\") {\n return {\n thinking: { type: \"adaptive\" },\n effort: EFFORT_TO_OUTPUT_EFFORT[effort],\n reservedTokens: budget,\n };\n }\n\n return {\n thinking: { type: \"enabled\", budget_tokens: budget },\n reservedTokens: budget,\n };\n }\n\n /**\n * The thinking settings for `reasoning: { effort: \"none\" }`, per\n * `noReasoningForm(this.name)` (documented on `buildThinking`).\n */\n private buildNoReasoning(): ThinkingRequest {\n switch (noReasoningForm(this.name)) {\n case \"between_tools\":\n return { thinking: { type: \"between_tools\" } };\n case \"disabled\":\n return { thinking: { type: \"disabled\" } };\n case \"lowest-effort\":\n return {\n thinking: { type: \"adaptive\" },\n effort: EFFORT_TO_OUTPUT_EFFORT.low,\n reservedTokens: EFFORT_THINKING_BUDGET.low,\n };\n case \"omit\":\n return {};\n }\n }\n\n /**\n * Spread-friendly tools fragment. Returns an empty object when no\n * tools were supplied so the caller can unconditionally spread it.\n *\n * When `config.promptCaching` is on, marks the LAST tool with\n * `cache_control: ephemeral` — Anthropic caches the whole prefix up\n * to a breakpoint, and tools sit before `system` in that prefix, so\n * one breakpoint on the final tool caches every tool definition.\n * Reads bill at ~0.1x after the first write. The system prompt is\n * deliberately left uncached: it carries per-turn placeholders, so a\n * breakpoint there would pay the ~1.25x write surcharge every turn\n * with no reads.\n */\n private buildTools(\n options: ModelCallOptions | undefined,\n cacheControl: ModelCallOptions[\"cacheControl\"],\n ): { tools?: Anthropic.ToolUnion[] } {\n const { tools, definitions } = selectProviderTools(options, {\n // The wire format, plus the provider label when a gateway sets one.\n accepts: [ANTHROPIC_WIRE_FORMAT, this.provider],\n module: LOG_MODULE,\n model: this.name,\n logger: this.logger,\n });\n const mapped = toAnthropicTools(tools);\n // Provider-defined tools (`web_search_20250305`, `bash_20250124`, …) go\n // first and verbatim; the cache breakpoint stays on the last function\n // tool so it still covers every definition before it.\n const providerDefined = definitions as unknown as Anthropic.ToolUnion[];\n\n if (!mapped) {\n return providerDefined.length > 0 ? { tools: providerDefined } : {};\n }\n\n if (this.config.promptCaching && mapped.length > 0) {\n const last = mapped.length - 1;\n const lastTool = mapped[last];\n\n if (lastTool) {\n mapped[last] = { ...lastTool, cache_control: this.cacheControl(cacheControl?.ttl) };\n }\n }\n\n return { tools: [...providerDefined, ...mapped] };\n }\n\n /**\n * Spread-friendly `output_config` fragment carrying both the native\n * structured-output `format` and the adaptive-thinking `effort`, merged\n * into one object (both live under `OutputConfig`, installed SDK\n * `messages.d.ts:796-806`). Returns an empty object when neither applies,\n * so budget-mode requests carry `output_config` only when a schema asks\n * for it.\n */\n private buildOutputConfig(\n responseSchema: Record<string, unknown> | undefined,\n effort: Anthropic.OutputConfig[\"effort\"],\n ): { output_config?: Anthropic.OutputConfig } {\n const format = this.buildStructuredOutputFormat(responseSchema);\n\n if (!format && !effort) {\n return {};\n }\n\n return {\n output_config: {\n ...(format ? { format } : {}),\n ...(effort ? { effort } : {}),\n },\n };\n }\n\n /**\n * Translate the neutral `responseSchema` option into Anthropic's\n * native `output_config.format` (JSON-schema structured outputs).\n *\n * Only returned when the model declares the `structuredOutput`\n * capability AND the schema is a proper root-object JSON Schema —\n * Anthropic rejects non-object roots. When the capability is off\n * (config override) or the schema is non-object, returns `undefined`:\n * the agent has already injected a soft schema hint into the system\n * prompt as the fallback, and client-side `validate()` still enforces\n * shape.\n */\n private buildStructuredOutputFormat(\n responseSchema: Record<string, unknown> | undefined,\n ): Anthropic.JSONOutputFormat | undefined {\n if (!responseSchema || !this.capabilities.structuredOutput) {\n return undefined;\n }\n\n if (responseSchema.type !== \"object\" || typeof responseSchema.properties !== \"object\") {\n return undefined;\n }\n\n return { type: \"json_schema\", schema: responseSchema };\n }\n\n /**\n * Concatenate every `text` content block into the single neutral\n * `content` string. `tool_use` and other block types are ignored\n * here — tool calls are surfaced separately via `extractToolCalls`.\n */\n private extractText(content: Anthropic.ContentBlock[]): string {\n return content\n .filter((block): block is Anthropic.TextBlock => block.type === \"text\")\n .map((block) => block.text)\n .join(\"\");\n }\n\n /**\n * Reshape Anthropic's `tool_use` content blocks into the neutral\n * `ModelToolCallRequest[]`. Returns `undefined` when the model\n * requested no tools so callers can branch on presence.\n */\n private extractToolCalls(content: Anthropic.ContentBlock[]): ModelToolCallRequest[] | undefined {\n const toolUses = content.filter(\n (block): block is Anthropic.ToolUseBlock => block.type === \"tool_use\",\n );\n\n if (toolUses.length === 0) {\n return undefined;\n }\n\n const thinkingMetadata = this.buildThinkingMetadata(content);\n\n return toolUses.map((block) => ({\n id: block.id,\n name: block.name,\n input: (block.input ?? {}) as Record<string, unknown>,\n ...thinkingMetadata,\n }));\n }\n\n /**\n * Preserve Anthropic's opaque extended-thinking blocks beside a tool\n * request so the next assistant turn can replay their signatures exactly.\n */\n private buildThinkingMetadata(blocks: Iterable<Anthropic.ContentBlock>): {\n providerMetadata?: Record<string, unknown>;\n } {\n const thinkingBlocks = Array.from(blocks).filter(\n (block): block is AnthropicThinkingBlock =>\n block.type === \"thinking\" || block.type === \"redacted_thinking\",\n );\n\n if (thinkingBlocks.length === 0) {\n return {};\n }\n\n return { providerMetadata: { anthropic: { thinkingBlocks } } };\n }\n\n /**\n * Normalize Anthropic's `usage` block into the neutral `Usage` shape.\n * Anthropic reports `input_tokens` / `output_tokens` separately with\n * no pre-summed total, so `total` is computed. `input_tokens` is the\n * uncached remainder only — cache reads (`cachedTokens`) and writes\n * (`cacheWriteTokens`, with the 1-hour share in `cacheWrite1hTokens`)\n * come on top of it — so the usage is marked\n * `inputIncludesCache: false`. Anthropic also reports\n * `output_tokens_details.thinking_tokens` as the reasoning subset of\n * its inclusive `output_tokens`; it is surfaced as `reasoningTokens`\n * when present, without changing the billing total. Server-side\n * compaction iterations are added in (see {@link compactionIterationUsage}).\n * `cost` is attached when the model is priced.\n */\n private extractUsage(raw: Anthropic.Usage, cacheTtl: ReturnType<typeof requestCacheTtl>): Usage {\n const compaction = compactionIterationUsage(raw);\n const input = (raw.input_tokens ?? 0) + compaction.input;\n const output = (raw.output_tokens ?? 0) + compaction.output;\n const thinkingTokens = raw.output_tokens_details?.thinking_tokens;\n const usage: Usage = {\n input,\n output,\n total: input + output,\n inputIncludesCache: false,\n ...(thinkingTokens !== null && thinkingTokens !== undefined\n ? { reasoningTokens: thinkingTokens }\n : {}),\n };\n\n applyServerToolUsage(usage, raw.server_tool_use);\n applyAnthropicCacheUsage(usage, raw, cacheTtl);\n addCacheCounts(usage, compaction);\n\n const cost = computeCost(usage, this.pricing);\n\n if (cost) {\n usage.cost = cost;\n }\n\n return usage;\n }\n\n /**\n * Wrap a thrown provider error into the typed `AIError` hierarchy and\n * emit the standard error log line before it propagates. Shared by\n * every catch site so the log shape stays identical.\n */\n private logAndWrap(thrown: unknown) {\n const wrapped = wrapAnthropicError(thrown);\n\n this.logger.error(LOG_MODULE, \"error\", wrapped.message, {\n code: wrapped.code,\n context: wrapped.context,\n });\n\n return wrapped;\n }\n}\n\n/**\n * Request fields `providerOptions.anthropic.body` may not set: they carry\n * the conversation, the model and the tool surface the agent registered,\n * so an override would silently replace the agent's input (or let the\n * model call tools the agent never registered). `stream` is chosen per\n * call by `complete()` / `stream()`.\n */\nconst RESERVED_BODY_FIELDS: ReadonlySet<string> = new Set([\n \"model\",\n \"messages\",\n \"system\",\n \"tools\",\n \"mcp_servers\",\n \"stream\",\n]);\n\n/** Body fields `messages.countTokens` accepts, copied from the full request body. */\nconst COUNT_TOKENS_FIELDS = [\n \"model\",\n \"messages\",\n \"system\",\n \"tools\",\n \"tool_choice\",\n \"thinking\",\n \"output_config\",\n \"cache_control\",\n \"context_management\",\n \"mcp_servers\",\n] as const;\n\n/** Beta flag for typed context editing (Anthropic docs, \"Context editing\", read 2026-10-17). */\nconst CONTEXT_MANAGEMENT_BETA = \"context-management-2025-06-27\";\n\n/** Beta flag for threshold compaction (Anthropic docs, \"Compaction at a token threshold\"). */\nconst COMPACTION_BETA = \"compact-2026-01-12\";\n\n/** Beta flag for `thinking.block_binding` (Anthropic docs, \"Preserved thinking\"). */\nconst THINKING_BINDING_BETA = \"thinking-binding-controls-2026-08-01\";\n\n/** The API rejects a compaction trigger below 50,000 input tokens. */\nconst MIN_COMPACTION_TRIGGER = 50_000;\n\ntype ContextEdit = { type: string } & Record<string, unknown>;\n\n/**\n * Translate the typed `contextManagement` / `serverCompaction` options into\n * `context_management.edits`. `clear_thinking_20251015` must come first\n * when strategies are combined (Anthropic docs, \"Context editing\").\n */\nfunction buildContextEdits(\n anthropic: AnthropicCallOptions,\n neutral?: ModelCallOptions[\"contextEditing\"],\n): ContextEdit[] {\n const edits: ContextEdit[] = [];\n const { clearThinking } = anthropic.contextManagement ?? {};\n // The vendor-neutral hint fills in only what the typed Anthropic options\n // leave unset, so an explicit `contextManagement.clearToolUses` wins.\n const clearToolUses: true | AnthropicClearToolUses | undefined =\n anthropic.contextManagement?.clearToolUses ?? neutralClearToolUses(neutral);\n\n if (clearThinking) {\n edits.push(clearThinkingEdit(clearThinking === true ? {} : clearThinking));\n }\n\n if (clearToolUses) {\n edits.push(clearToolUsesEdit(clearToolUses === true ? {} : clearToolUses));\n }\n\n if (anthropic.serverCompaction) {\n const compaction = anthropic.serverCompaction === true ? {} : anthropic.serverCompaction;\n\n if (compaction.triggerTokens !== undefined) {\n assertCount(\n \"serverCompaction.triggerTokens\",\n compaction.triggerTokens,\n MIN_COMPACTION_TRIGGER,\n );\n }\n\n edits.push({\n type: \"compact_20260112\",\n ...(compaction.triggerTokens !== undefined\n ? { trigger: { type: \"input_tokens\", value: compaction.triggerTokens } }\n : {}),\n ...(compaction.instructions ? { instructions: compaction.instructions } : {}),\n });\n }\n\n return edits;\n}\n\nfunction neutralClearToolUses(\n neutral: ModelCallOptions[\"contextEditing\"],\n): AnthropicClearToolUses | undefined {\n const rule = neutral?.clearToolResults;\n\n if (!rule) return undefined;\n\n return {\n ...(rule.afterTokens !== undefined ? { trigger: { inputTokens: rule.afterTokens } } : {}),\n ...(rule.keep !== undefined ? { keep: rule.keep } : {}),\n ...(rule.exclude?.length ? { excludeTools: rule.exclude } : {}),\n ...(rule.clearAtLeast !== undefined ? { clearAtLeast: rule.clearAtLeast } : {}),\n };\n}\n\nfunction clearThinkingEdit(options: AnthropicClearThinking): ContextEdit {\n if (options.keep === undefined || options.keep === \"all\") {\n return { type: \"clear_thinking_20251015\", ...(options.keep ? { keep: \"all\" } : {}) };\n }\n\n assertCount(\"contextManagement.clearThinking.keep\", options.keep, 1);\n\n return {\n type: \"clear_thinking_20251015\",\n keep: { type: \"thinking_turns\", value: options.keep },\n };\n}\n\nfunction clearToolUsesEdit(options: AnthropicClearToolUses): ContextEdit {\n const edit: ContextEdit = { type: \"clear_tool_uses_20250919\" };\n\n if (options.trigger) {\n const trigger =\n \"inputTokens\" in options.trigger\n ? { type: \"input_tokens\", value: options.trigger.inputTokens }\n : { type: \"tool_uses\", value: options.trigger.toolUses };\n\n assertCount(\"contextManagement.clearToolUses.trigger\", trigger.value, 1);\n edit.trigger = trigger;\n }\n\n if (options.keep !== undefined) {\n assertCount(\"contextManagement.clearToolUses.keep\", options.keep, 0);\n edit.keep = { type: \"tool_uses\", value: options.keep };\n }\n\n if (options.clearAtLeast !== undefined) {\n assertCount(\"contextManagement.clearToolUses.clearAtLeast\", options.clearAtLeast, 1);\n edit.clear_at_least = { type: \"input_tokens\", value: options.clearAtLeast };\n }\n\n if (options.excludeTools !== undefined) {\n edit.exclude_tools = [...options.excludeTools];\n }\n\n if (options.clearToolInputs !== undefined) {\n edit.clear_tool_inputs = Array.isArray(options.clearToolInputs)\n ? [...options.clearToolInputs]\n : options.clearToolInputs;\n }\n\n return edit;\n}\n\nfunction assertCount(field: string, value: number, minimum: number): void {\n if (!Number.isSafeInteger(value) || value < minimum) {\n throw new InvalidRequestError(\n `providerOptions.anthropic.${field} must be an integer of at least ${minimum}; got ${value}.`,\n { context: { field } },\n );\n }\n}\n\ntype IterationTotals = { input: number; output: number; cacheRead: number; cacheWrite: number };\n\n/**\n * Tokens of the `compaction` entries in a beta response's `usage.iterations`.\n * With server-side compaction the top-level `input_tokens` / `output_tokens`\n * cover only the non-compaction iterations; the billed total is the sum\n * over every iteration (Anthropic docs, \"Compaction at a token threshold\" →\n * \"Understanding usage\", read 2026-10-17). Zeros when there are none.\n */\nfunction compactionIterationUsage(raw: unknown): IterationTotals {\n const totals: IterationTotals = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };\n const iterations = (raw as { iterations?: unknown } | null | undefined)?.iterations;\n\n if (!Array.isArray(iterations)) {\n return totals;\n }\n\n for (const entry of iterations as unknown[]) {\n const iteration = entry as Record<string, unknown> | null;\n\n if (iteration?.type !== \"compaction\") {\n continue;\n }\n\n totals.input += numberOrZero(iteration.input_tokens);\n totals.output += numberOrZero(iteration.output_tokens);\n totals.cacheRead += numberOrZero(iteration.cache_read_input_tokens);\n totals.cacheWrite += numberOrZero(iteration.cache_creation_input_tokens);\n }\n\n return totals;\n}\n\nfunction numberOrZero(value: unknown): number {\n return typeof value === \"number\" && Number.isFinite(value) ? value : 0;\n}\n\nfunction addCacheCounts(usage: Usage, extra: IterationTotals): void {\n if (extra.cacheRead > 0) {\n usage.cachedTokens = (usage.cachedTokens ?? 0) + extra.cacheRead;\n }\n\n if (extra.cacheWrite > 0) {\n usage.cacheWriteTokens = (usage.cacheWriteTokens ?? 0) + extra.cacheWrite;\n }\n}\n\n/** Read `providerOptions.anthropic`, tolerating its absence or a wrong shape. */\nfunction resolveAnthropicOptions(options: ModelCallOptions | undefined): AnthropicCallOptions {\n const raw = options?.providerOptions?.anthropic;\n\n return typeof raw === \"object\" && raw !== null ? (raw as AnthropicCallOptions) : {};\n}\n\nfunction windowCapability(window: number | undefined): { contextWindow?: number } {\n return window === undefined ? {} : { contextWindow: window };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAqDA,MAAM,aAAa;;AAGnB,MAAM,wBAAwB;;;;;;;;;;;;;;;AAgB9B,MAAM,qBAAqB;;;;;;;AAQ3B,MAAM,oBAAoB;;;;;;AAO1B,MAAM,sBAAsB;;;;;;;AAU5B,MAAM,0BAA0C;;;;;;;;;;;AAYhD,MAAM,yBAAyD;CAG7D,SAAS;CACT,KAAK;CACL,QAAQ;CACR,MAAM;CAIN,OAAO;CACP,KAAK;AACP;;;;;;;;AASA,MAAM,0BAGF;CACF,SAAS;CACT,KAAK;CACL,QAAQ;CACR,MAAM;CACN,OAAO;CACP,KAAK;AACP;;AAeA,MAAM,6CAA6B,IAAI,IAAI;CAAC;CAAY;CAAmB;AAAc,CAAC;;;;;;;;;;;;;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Y;EACV;EACA,UAAU,UAAU;;;YAIV;;;;;;;;;;EAUV;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;wBA+Cc,oBACd,UAAU,WACV,UAAS,6BACR"}
1
+ {"version":3,"file":"to-anthropic-messages.d.mts","names":[],"sources":["../../../../../../../../packages/ai-anthropic/src/utils/to-anthropic-messages.ts"],"mappings":";;;;;;;;;YAeY;EACV;EACA,UAAU,UAAU;;;YAIV;;;;;;;;;;EAUV;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;wBA+Cc,oBACd,UAAU,WACV,UAAS,6BACR"}
@@ -1,4 +1,5 @@
1
1
  import { fromProviderBlocks } from "./provider-blocks.mjs";
2
+ import { TOOL_RESULT_IMAGE_PLACEHOLDER } from "@warlock.js/ai";
2
3
 
3
4
  //#region ../../packages/ai-anthropic/src/utils/to-anthropic-messages.ts
4
5
  /**
@@ -53,7 +54,7 @@ function toAnthropicMessages(messages, options = {}) {
53
54
  const toolResult = {
54
55
  type: "tool_result",
55
56
  tool_use_id: message.toolCallId ?? "",
56
- content: stringifyContent(message.content)
57
+ content: toToolResultContent(message.content)
57
58
  };
58
59
  const previous = mapped[mapped.length - 1];
59
60
  if (previous && previous.role === "user" && isToolResultTurn(previous)) previous.content.push(toolResult);
@@ -161,6 +162,33 @@ function stringifyContent(content) {
161
162
  return content.filter((part) => part.type === "text").map((part) => part.text).join("");
162
163
  }
163
164
  /**
165
+ * A tool result's `content`: the plain string, or text and `image` blocks
166
+ * when the tool returned content parts. A `url` image cannot appear here
167
+ * (tool images are inline base64) but degrades to the placeholder text.
168
+ */
169
+ function toToolResultContent(content) {
170
+ if (typeof content === "string") return content;
171
+ if (!content.some((part) => part.type === "image")) return stringifyContent(content);
172
+ const blocks = [];
173
+ for (const part of content) if (part.type === "text") blocks.push({
174
+ type: "text",
175
+ text: part.text
176
+ });
177
+ else if (part.type === "image" && "base64" in part.source) blocks.push({
178
+ type: "image",
179
+ source: {
180
+ type: "base64",
181
+ media_type: part.source.mediaType,
182
+ data: part.source.base64
183
+ }
184
+ });
185
+ else blocks.push({
186
+ type: "text",
187
+ text: TOOL_RESULT_IMAGE_PLACEHOLDER
188
+ });
189
+ return blocks;
190
+ }
191
+ /**
164
192
  * Map a single resolved `ContentPart` to an Anthropic content block.
165
193
  * Text passes straight through; images become an `image` block with a
166
194
  * `url` source (remote) or a `base64` source (inlined bytes). The
@@ -1 +1 @@
1
- {"version":3,"file":"to-anthropic-messages.mjs","names":[],"sources":["../../../../../../../../packages/ai-anthropic/src/utils/to-anthropic-messages.ts"],"sourcesContent":["import type { ContentPart, Message, ModelToolCallRequest } from \"@warlock.js/ai\";\nimport type Anthropic from \"@anthropic-ai/sdk\";\nimport { fromProviderBlocks } from \"./provider-blocks\";\n\n/**\n * Result of splitting a vendor-neutral `Message[]` for the Anthropic\n * Messages API: the system prompt is hoisted to a top-level `system`\n * string (Anthropic has no `\"system\"` role inside `messages`), and the\n * remaining turns are mapped to `MessageParam[]`.\n */\nexport type AnthropicMessages = {\n system: string | undefined;\n messages: Anthropic.MessageParam[];\n};\n\n/** Options for {@link toAnthropicMessages}. */\nexport type ToAnthropicMessagesOptions = {\n /**\n * Leave out the `thinking` / `redacted_thinking` blocks of assistant turns\n * marked `compaction: \"retained\"` — turns kept verbatim after a\n * client-written summary. On models that run the preserved-thinking\n * conversation check those blocks were produced against the replaced\n * history, so replaying them is a 400 (or a server-side drop). Text and\n * tool-use blocks stay. Removing them is the no-beta path Anthropic\n * documents for compaction that keeps recent turns.\n */\n dropRetainedThinking?: boolean;\n};\n\nconst ANTHROPIC_IMAGE_MEDIA_TYPES = [\"image/jpeg\", \"image/png\", \"image/gif\", \"image/webp\"] as const;\n\ntype AnthropicImageMediaType = (typeof ANTHROPIC_IMAGE_MEDIA_TYPES)[number];\n\n/**\n * Convert vendor-neutral `Message[]` into Anthropic's request shape.\n *\n * Anthropic differs from the OpenAI Chat protocol in three ways this\n * function absorbs:\n *\n * 1. **No `system` role.** System messages are concatenated (newline-\n * separated) and returned separately as the top-level `system`\n * parameter.\n * 2. **Tool results are `user` turns.** A neutral `tool` message becomes\n * a `tool_result` block keyed by `tool_use_id`. Consecutive tool\n * messages (the results of one parallel tool-use turn) are grouped\n * into a single `user` message, as Anthropic expects — splitting them\n * across messages teaches the model to stop calling tools in parallel.\n * 3. **Tool calls are `tool_use` content blocks.** An assistant message\n * carrying `toolCalls` becomes an `assistant` message whose content\n * is an optional leading `text` block followed by one `tool_use`\n * block per call.\n *\n * An assistant message that carries Anthropic `blocks` (thinking,\n * redacted thinking, compaction, server-tool blocks — see\n * `ProviderContentBlock`) is replayed verbatim from those blocks, which\n * keeps signed thinking and compaction state valid. Blocks from another\n * provider, or blocks whose `tool_use` ids no longer match `toolCalls`,\n * are ignored and the turn is rebuilt from `content` + `toolCalls`.\n *\n * With `dropRetainedThinking`, a turn marked `compaction: \"retained\"` is\n * replayed without its thinking blocks (see {@link ToAnthropicMessagesOptions}).\n *\n * Other consecutive same-role turns are left as-is — the Messages API\n * merges them server-side.\n *\n * @example\n * const { system, messages } = toAnthropicMessages([\n * { role: \"system\", content: \"Be concise.\" },\n * { role: \"user\", content: \"Hi\" },\n * ]);\n * // system === \"Be concise.\"\n * // messages === [{ role: \"user\", content: \"Hi\" }]\n */\nexport function toAnthropicMessages(\n messages: Message[],\n options: ToAnthropicMessagesOptions = {},\n): AnthropicMessages {\n const systemParts: string[] = [];\n const mapped: Anthropic.MessageParam[] = [];\n\n for (const message of messages) {\n if (message.role === \"system\") {\n systemParts.push(stringifyContent(message.content));\n\n continue;\n }\n\n if (message.role === \"tool\") {\n const toolResult: Anthropic.ToolResultBlockParam = {\n type: \"tool_result\",\n tool_use_id: message.toolCallId ?? \"\",\n content: stringifyContent(message.content),\n };\n const previous = mapped[mapped.length - 1];\n\n if (previous && previous.role === \"user\" && isToolResultTurn(previous)) {\n previous.content.push(toolResult);\n } else {\n mapped.push({ role: \"user\", content: [toolResult] });\n }\n\n continue;\n }\n\n const dropThinking = options.dropRetainedThinking === true && message.compaction === \"retained\";\n\n if (message.role === \"assistant\") {\n const replayed = fromProviderBlocks(message.blocks, message.toolCalls);\n const content = dropThinking\n ? replayed?.filter((block) => !isThinkingBlock(block))\n : replayed;\n\n if (content && content.length > 0) {\n mapped.push({ role: \"assistant\", content });\n\n continue;\n }\n }\n\n if (message.role === \"assistant\" && message.toolCalls && message.toolCalls.length > 0) {\n const blocks: Anthropic.ContentBlockParam[] = dropThinking\n ? []\n : extractThinkingBlocks(message.toolCalls);\n const text = stringifyContent(message.content);\n\n if (text) {\n blocks.push({ type: \"text\", text });\n }\n\n for (const toolCall of message.toolCalls) {\n blocks.push({\n type: \"tool_use\",\n id: toolCall.id,\n name: toolCall.name,\n input: toolCall.input ?? {},\n });\n }\n\n mapped.push({ role: \"assistant\", content: blocks });\n\n continue;\n }\n\n if (message.role === \"user\" && Array.isArray(message.content)) {\n mapped.push({\n role: \"user\",\n content: message.content.map(toAnthropicContentBlock),\n });\n\n continue;\n }\n\n mapped.push({\n role: message.role === \"assistant\" ? \"assistant\" : \"user\",\n content: stringifyContent(message.content),\n });\n }\n\n return {\n system: systemParts.length > 0 ? systemParts.join(\"\\n\\n\") : undefined,\n messages: mapped,\n };\n}\n\nfunction isThinkingBlock(block: Anthropic.ContentBlockParam): boolean {\n return block.type === \"thinking\" || block.type === \"redacted_thinking\";\n}\n\n/**\n * Recover signed extended-thinking blocks stored by this adapter on a tool\n * request. Anthropic requires these blocks to be replayed before the\n * assistant's text and tool uses on the following request.\n */\nfunction extractThinkingBlocks(toolCalls: ModelToolCallRequest[]): Anthropic.ContentBlockParam[] {\n for (const toolCall of toolCalls) {\n const anthropic = toolCall.providerMetadata?.anthropic;\n\n if (!isRecord(anthropic) || !Array.isArray(anthropic.thinkingBlocks)) {\n continue;\n }\n\n return anthropic.thinkingBlocks.flatMap(toAnthropicThinkingBlock);\n }\n\n return [];\n}\n\nfunction toAnthropicThinkingBlock(block: unknown): Anthropic.ContentBlockParam[] {\n if (!isRecord(block) || typeof block.type !== \"string\") {\n return [];\n }\n\n if (\n block.type === \"thinking\" &&\n typeof block.thinking === \"string\" &&\n typeof block.signature === \"string\"\n ) {\n return [{ type: \"thinking\", thinking: block.thinking, signature: block.signature }];\n }\n\n if (block.type === \"redacted_thinking\" && typeof block.data === \"string\") {\n return [{ type: \"redacted_thinking\", data: block.data }];\n }\n\n return [];\n}\n\n/**\n * A `user` turn this function built from tool results — its content is a\n * non-empty array made only of `tool_result` blocks. Later tool results\n * of the same tool-use turn are appended to it.\n */\nfunction isToolResultTurn(\n message: Anthropic.MessageParam,\n): message is Anthropic.MessageParam & { content: Anthropic.ContentBlockParam[] } {\n return (\n Array.isArray(message.content) &&\n message.content.length > 0 &&\n message.content.every((block) => block.type === \"tool_result\")\n );\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\n/**\n * Multipart content is only meaningful on user messages — for any other\n * role collapse a `ContentPart[]` to its concatenated text so the wire\n * format stays valid. Plain strings pass through unchanged.\n */\nfunction stringifyContent(content: string | ContentPart[]): string {\n if (typeof content === \"string\") {\n return content;\n }\n\n return content\n .filter((part): part is { type: \"text\"; text: string } => part.type === \"text\")\n .map((part) => part.text)\n .join(\"\");\n}\n\n/**\n * Map a single resolved `ContentPart` to an Anthropic content block.\n * Text passes straight through; images become an `image` block with a\n * `url` source (remote) or a `base64` source (inlined bytes). The\n * agent has already resolved every attachment before it reaches here,\n * so this never reads files or fetches URLs.\n */\nfunction toAnthropicContentBlock(part: ContentPart): Anthropic.ContentBlockParam {\n if (part.type === \"text\") {\n return { type: \"text\", text: part.text };\n }\n\n // PDF → Anthropic `document` block (A2). The Messages API accepts a\n // url or base64 `application/pdf` source on PDF-capable Claude models.\n if (part.type === \"pdf\") {\n const source =\n \"url\" in part.source\n ? { type: \"url\", url: part.source.url }\n : { type: \"base64\", media_type: \"application/pdf\", data: part.source.base64 };\n return { type: \"document\", source } as unknown as Anthropic.ContentBlockParam;\n }\n\n // Anthropic has no audio content block; the agent's capability gate\n // normally prevents this, but stay loud rather than mis-map it.\n if (part.type === \"audio\") {\n throw new Error(\"Anthropic adapter: audio attachments are not supported\");\n }\n\n if (\"url\" in part.source) {\n return { type: \"image\", source: { type: \"url\", url: part.source.url } };\n }\n\n return {\n type: \"image\",\n source: {\n type: \"base64\",\n media_type: part.source.mediaType as AnthropicImageMediaType,\n data: part.source.base64,\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyEA,SAAgB,oBACd,UACA,UAAsC,CAAC,GACpB;CACnB,MAAM,cAAwB,CAAC;CAC/B,MAAM,SAAmC,CAAC;CAE1C,KAAK,MAAM,WAAW,UAAU;EAC9B,IAAI,QAAQ,SAAS,UAAU;GAC7B,YAAY,KAAK,iBAAiB,QAAQ,OAAO,CAAC;GAElD;EACF;EAEA,IAAI,QAAQ,SAAS,QAAQ;GAC3B,MAAM,aAA6C;IACjD,MAAM;IACN,aAAa,QAAQ,cAAc;IACnC,SAAS,iBAAiB,QAAQ,OAAO;GAC3C;GACA,MAAM,WAAW,OAAO,OAAO,SAAS;GAExC,IAAI,YAAY,SAAS,SAAS,UAAU,iBAAiB,QAAQ,GACnE,SAAS,QAAQ,KAAK,UAAU;QAEhC,OAAO,KAAK;IAAE,MAAM;IAAQ,SAAS,CAAC,UAAU;GAAE,CAAC;GAGrD;EACF;EAEA,MAAM,eAAe,QAAQ,yBAAyB,QAAQ,QAAQ,eAAe;EAErF,IAAI,QAAQ,SAAS,aAAa;GAChC,MAAM,WAAW,mBAAmB,QAAQ,QAAQ,QAAQ,SAAS;GACrE,MAAM,UAAU,eACZ,UAAU,QAAQ,UAAU,CAAC,gBAAgB,KAAK,CAAC,IACnD;GAEJ,IAAI,WAAW,QAAQ,SAAS,GAAG;IACjC,OAAO,KAAK;KAAE,MAAM;KAAa;IAAQ,CAAC;IAE1C;GACF;EACF;EAEA,IAAI,QAAQ,S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+ {"version":3,"file":"to-anthropic-messages.mjs","names":[],"sources":["../../../../../../../../packages/ai-anthropic/src/utils/to-anthropic-messages.ts"],"sourcesContent":["import {\n TOOL_RESULT_IMAGE_PLACEHOLDER,\n type ContentPart,\n type Message,\n type ModelToolCallRequest,\n} from \"@warlock.js/ai\";\nimport type Anthropic from \"@anthropic-ai/sdk\";\nimport { fromProviderBlocks } from \"./provider-blocks\";\n\n/**\n * Result of splitting a vendor-neutral `Message[]` for the Anthropic\n * Messages API: the system prompt is hoisted to a top-level `system`\n * string (Anthropic has no `\"system\"` role inside `messages`), and the\n * remaining turns are mapped to `MessageParam[]`.\n */\nexport type AnthropicMessages = {\n system: string | undefined;\n messages: Anthropic.MessageParam[];\n};\n\n/** Options for {@link toAnthropicMessages}. */\nexport type ToAnthropicMessagesOptions = {\n /**\n * Leave out the `thinking` / `redacted_thinking` blocks of assistant turns\n * marked `compaction: \"retained\"` — turns kept verbatim after a\n * client-written summary. On models that run the preserved-thinking\n * conversation check those blocks were produced against the replaced\n * history, so replaying them is a 400 (or a server-side drop). Text and\n * tool-use blocks stay. Removing them is the no-beta path Anthropic\n * documents for compaction that keeps recent turns.\n */\n dropRetainedThinking?: boolean;\n};\n\nconst ANTHROPIC_IMAGE_MEDIA_TYPES = [\"image/jpeg\", \"image/png\", \"image/gif\", \"image/webp\"] as const;\n\ntype AnthropicImageMediaType = (typeof ANTHROPIC_IMAGE_MEDIA_TYPES)[number];\n\n/**\n * Convert vendor-neutral `Message[]` into Anthropic's request shape.\n *\n * Anthropic differs from the OpenAI Chat protocol in three ways this\n * function absorbs:\n *\n * 1. **No `system` role.** System messages are concatenated (newline-\n * separated) and returned separately as the top-level `system`\n * parameter.\n * 2. **Tool results are `user` turns.** A neutral `tool` message becomes\n * a `tool_result` block keyed by `tool_use_id`. Consecutive tool\n * messages (the results of one parallel tool-use turn) are grouped\n * into a single `user` message, as Anthropic expects — splitting them\n * across messages teaches the model to stop calling tools in parallel.\n * 3. **Tool calls are `tool_use` content blocks.** An assistant message\n * carrying `toolCalls` becomes an `assistant` message whose content\n * is an optional leading `text` block followed by one `tool_use`\n * block per call.\n *\n * An assistant message that carries Anthropic `blocks` (thinking,\n * redacted thinking, compaction, server-tool blocks — see\n * `ProviderContentBlock`) is replayed verbatim from those blocks, which\n * keeps signed thinking and compaction state valid. Blocks from another\n * provider, or blocks whose `tool_use` ids no longer match `toolCalls`,\n * are ignored and the turn is rebuilt from `content` + `toolCalls`.\n *\n * With `dropRetainedThinking`, a turn marked `compaction: \"retained\"` is\n * replayed without its thinking blocks (see {@link ToAnthropicMessagesOptions}).\n *\n * Other consecutive same-role turns are left as-is — the Messages API\n * merges them server-side.\n *\n * @example\n * const { system, messages } = toAnthropicMessages([\n * { role: \"system\", content: \"Be concise.\" },\n * { role: \"user\", content: \"Hi\" },\n * ]);\n * // system === \"Be concise.\"\n * // messages === [{ role: \"user\", content: \"Hi\" }]\n */\nexport function toAnthropicMessages(\n messages: Message[],\n options: ToAnthropicMessagesOptions = {},\n): AnthropicMessages {\n const systemParts: string[] = [];\n const mapped: Anthropic.MessageParam[] = [];\n\n for (const message of messages) {\n if (message.role === \"system\") {\n systemParts.push(stringifyContent(message.content));\n\n continue;\n }\n\n if (message.role === \"tool\") {\n const toolResult: Anthropic.ToolResultBlockParam = {\n type: \"tool_result\",\n tool_use_id: message.toolCallId ?? \"\",\n content: toToolResultContent(message.content),\n };\n const previous = mapped[mapped.length - 1];\n\n if (previous && previous.role === \"user\" && isToolResultTurn(previous)) {\n previous.content.push(toolResult);\n } else {\n mapped.push({ role: \"user\", content: [toolResult] });\n }\n\n continue;\n }\n\n const dropThinking = options.dropRetainedThinking === true && message.compaction === \"retained\";\n\n if (message.role === \"assistant\") {\n const replayed = fromProviderBlocks(message.blocks, message.toolCalls);\n const content = dropThinking\n ? replayed?.filter((block) => !isThinkingBlock(block))\n : replayed;\n\n if (content && content.length > 0) {\n mapped.push({ role: \"assistant\", content });\n\n continue;\n }\n }\n\n if (message.role === \"assistant\" && message.toolCalls && message.toolCalls.length > 0) {\n const blocks: Anthropic.ContentBlockParam[] = dropThinking\n ? []\n : extractThinkingBlocks(message.toolCalls);\n const text = stringifyContent(message.content);\n\n if (text) {\n blocks.push({ type: \"text\", text });\n }\n\n for (const toolCall of message.toolCalls) {\n blocks.push({\n type: \"tool_use\",\n id: toolCall.id,\n name: toolCall.name,\n input: toolCall.input ?? {},\n });\n }\n\n mapped.push({ role: \"assistant\", content: blocks });\n\n continue;\n }\n\n if (message.role === \"user\" && Array.isArray(message.content)) {\n mapped.push({\n role: \"user\",\n content: message.content.map(toAnthropicContentBlock),\n });\n\n continue;\n }\n\n mapped.push({\n role: message.role === \"assistant\" ? \"assistant\" : \"user\",\n content: stringifyContent(message.content),\n });\n }\n\n return {\n system: systemParts.length > 0 ? systemParts.join(\"\\n\\n\") : undefined,\n messages: mapped,\n };\n}\n\nfunction isThinkingBlock(block: Anthropic.ContentBlockParam): boolean {\n return block.type === \"thinking\" || block.type === \"redacted_thinking\";\n}\n\n/**\n * Recover signed extended-thinking blocks stored by this adapter on a tool\n * request. Anthropic requires these blocks to be replayed before the\n * assistant's text and tool uses on the following request.\n */\nfunction extractThinkingBlocks(toolCalls: ModelToolCallRequest[]): Anthropic.ContentBlockParam[] {\n for (const toolCall of toolCalls) {\n const anthropic = toolCall.providerMetadata?.anthropic;\n\n if (!isRecord(anthropic) || !Array.isArray(anthropic.thinkingBlocks)) {\n continue;\n }\n\n return anthropic.thinkingBlocks.flatMap(toAnthropicThinkingBlock);\n }\n\n return [];\n}\n\nfunction toAnthropicThinkingBlock(block: unknown): Anthropic.ContentBlockParam[] {\n if (!isRecord(block) || typeof block.type !== \"string\") {\n return [];\n }\n\n if (\n block.type === \"thinking\" &&\n typeof block.thinking === \"string\" &&\n typeof block.signature === \"string\"\n ) {\n return [{ type: \"thinking\", thinking: block.thinking, signature: block.signature }];\n }\n\n if (block.type === \"redacted_thinking\" && typeof block.data === \"string\") {\n return [{ type: \"redacted_thinking\", data: block.data }];\n }\n\n return [];\n}\n\n/**\n * A `user` turn this function built from tool results — its content is a\n * non-empty array made only of `tool_result` blocks. Later tool results\n * of the same tool-use turn are appended to it.\n */\nfunction isToolResultTurn(\n message: Anthropic.MessageParam,\n): message is Anthropic.MessageParam & { content: Anthropic.ContentBlockParam[] } {\n return (\n Array.isArray(message.content) &&\n message.content.length > 0 &&\n message.content.every((block) => block.type === \"tool_result\")\n );\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\n/**\n * Multipart content is only meaningful on user messages — for any other\n * role collapse a `ContentPart[]` to its concatenated text so the wire\n * format stays valid. Plain strings pass through unchanged.\n */\nfunction stringifyContent(content: string | ContentPart[]): string {\n if (typeof content === \"string\") {\n return content;\n }\n\n return content\n .filter((part): part is { type: \"text\"; text: string } => part.type === \"text\")\n .map((part) => part.text)\n .join(\"\");\n}\n\n/**\n * A tool result's `content`: the plain string, or text and `image` blocks\n * when the tool returned content parts. A `url` image cannot appear here\n * (tool images are inline base64) but degrades to the placeholder text.\n */\nfunction toToolResultContent(\n content: string | ContentPart[],\n): string | Array<Anthropic.TextBlockParam | Anthropic.ImageBlockParam> {\n if (typeof content === \"string\") return content;\n\n // Text-only parts keep the plain string form.\n if (!content.some((part) => part.type === \"image\")) return stringifyContent(content);\n\n const blocks: Array<Anthropic.TextBlockParam | Anthropic.ImageBlockParam> = [];\n\n for (const part of content) {\n if (part.type === \"text\") {\n blocks.push({ type: \"text\", text: part.text });\n } else if (part.type === \"image\" && \"base64\" in part.source) {\n blocks.push({\n type: \"image\",\n source: {\n type: \"base64\",\n media_type: part.source.mediaType as AnthropicImageMediaType,\n data: part.source.base64,\n },\n });\n } else {\n blocks.push({ type: \"text\", text: TOOL_RESULT_IMAGE_PLACEHOLDER });\n }\n }\n\n return blocks;\n}\n\n/**\n * Map a single resolved `ContentPart` to an Anthropic content block.\n * Text passes straight through; images become an `image` block with a\n * `url` source (remote) or a `base64` source (inlined bytes). The\n * agent has already resolved every attachment before it reaches here,\n * so this never reads files or fetches URLs.\n */\nfunction toAnthropicContentBlock(part: ContentPart): Anthropic.ContentBlockParam {\n if (part.type === \"text\") {\n return { type: \"text\", text: part.text };\n }\n\n // PDF → Anthropic `document` block (A2). The Messages API accepts a\n // url or base64 `application/pdf` source on PDF-capable Claude models.\n if (part.type === \"pdf\") {\n const source =\n \"url\" in part.source\n ? { type: \"url\", url: part.source.url }\n : { type: \"base64\", media_type: \"application/pdf\", data: part.source.base64 };\n return { type: \"document\", source } as unknown as Anthropic.ContentBlockParam;\n }\n\n // Anthropic has no audio content block; the agent's capability gate\n // normally prevents this, but stay loud rather than mis-map it.\n if (part.type === \"audio\") {\n throw new Error(\"Anthropic adapter: audio attachments are not supported\");\n }\n\n if (\"url\" in part.source) {\n return { type: \"image\", source: { type: \"url\", url: part.source.url } };\n }\n\n return {\n type: \"image\",\n source: {\n type: \"base64\",\n media_type: part.source.mediaType as AnthropicImageMediaType,\n data: part.source.base64,\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8EA,SAAgB,oBACd,UACA,UAAsC,CAAC,GACpB;CACnB,MAAM,cAAwB,CAAC;CAC/B,MAAM,SAAmC,CAAC;CAE1C,KAAK,MAAM,WAAW,UAAU;EAC9B,IAAI,QAAQ,SAAS,UAAU;GAC7B,YAAY,KAAK,iBAAiB,QAAQ,OAAO,CAAC;GAElD;EACF;EAEA,IAAI,QAAQ,SAAS,QAAQ;GAC3B,MAAM,aAA6C;IACjD,MAAM;IACN,aAAa,QAAQ,cAAc;IACnC,SAAS,oBAAoB,QAAQ,OAAO;GAC9C;GACA,MAAM,WAAW,OAAO,OAAO,SAAS;GAExC,IAAI,YAAY,SAAS,SAAS,UAAU,iBAAiB,QAAQ,GACnE,SAAS,QAAQ,KAAK,UAAU;QAEhC,OAAO,KAAK;IAAE,MAAM;IAAQ,SAAS,CAAC,UAAU;GAAE,CAAC;GAGrD;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KAAK;EAAE,MAAM;EAAQ,MAAM,KAAK;CAAK,CAAC;MACxC,IAAI,KAAK,SAAS,WAAW,YAAY,KAAK,QACnD,OAAO,KAAK;EACV,MAAM;EACN,QAAQ;GACN,MAAM;GACN,YAAY,KAAK,OAAO;GACxB,MAAM,KAAK,OAAO;EACpB;CACF,CAAC;MAED,OAAO,KAAK;EAAE,MAAM;EAAQ,MAAM;CAA8B,CAAC;CAIrE,OAAO;AACT;;;;;;;;AASA,SAAS,wBAAwB,MAAgD;CAC/E,IAAI,KAAK,SAAS,QAChB,OAAO;EAAE,MAAM;EAAQ,MAAM,KAAK;CAAK;CAKzC,IAAI,KAAK,SAAS,OAKhB,OAAO;EAAE,MAAM;EAAY,QAHzB,SAAS,KAAK,SACV;GAAE,MAAM;GAAO,KAAK,KAAK,OAAO;EAAI,IACpC;GAAE,MAAM;GAAU,YAAY;GAAmB,MAAM,KAAK,OAAO;EAAO;CAC9C;CAKpC,IAAI,KAAK,SAAS,SAChB,MAAM,IAAI,MAAM,wDAAwD;CAG1E,IAAI,SAAS,KAAK,QAChB,OAAO;EAAE,MAAM;EAAS,QAAQ;GAAE,MAAM;GAAO,KAAK,KAAK,OAAO;EAAI;CAAE;CAGxE,OAAO;EACL,MAAM;EACN,QAAQ;GACN,MAAM;GACN,YAAY,KAAK,OAAO;GACxB,MAAM,KAAK,OAAO;EACpB;CACF;AACF"}
package/llms-full.txt CHANGED
@@ -512,4 +512,8 @@ and [fee reservations](https://warlock.js.org/v/latest/ai/recipes/cost-budgets-a
512
512
 
513
513
  `await anthropic.models()` returns `ModelInfo[]` from `GET /v1/models` (release date as `created`, `contextWindow` / `maxOutputTokens` when reported).
514
514
 
515
+ ## Context window
516
+
517
+ Every known Claude release reports `capabilities.contextWindow` (1M for the 4.6 line and the Claude 5 families, 200K for earlier ones); `anthropic.model({ name, contextWindow })` wins and covers unlisted ids.
518
+
515
519
 
package/package.json CHANGED
@@ -15,13 +15,13 @@
15
15
  "directory": "packages/ai-anthropic"
16
16
  },
17
17
  "peerDependencies": {
18
- "@warlock.js/ai": "5.44.0"
18
+ "@warlock.js/ai": "5.46.0"
19
19
  },
20
20
  "dependencies": {
21
21
  "@anthropic-ai/sdk": "^0.129.0",
22
- "@warlock.js/logger": "5.44.0"
22
+ "@warlock.js/logger": "5.46.0"
23
23
  },
24
- "version": "5.44.0",
24
+ "version": "5.46.0",
25
25
  "main": "./cjs/index.cjs",
26
26
  "module": "./esm/index.mjs",
27
27
  "types": "./esm/index.d.mts",