@warlock.js/ai-anthropic 5.31.0 → 5.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/cjs/index.cjs +33 -7
  3. package/cjs/index.cjs.map +1 -1
  4. package/esm/config.type.d.mts +22 -16
  5. package/esm/config.type.d.mts.map +1 -1
  6. package/esm/index.d.mts +3 -2
  7. package/esm/index.mjs +2 -2
  8. package/esm/known-pricing.d.mts +12 -7
  9. package/esm/known-pricing.d.mts.map +1 -1
  10. package/esm/known-pricing.mjs +8 -1
  11. package/esm/known-pricing.mjs.map +1 -1
  12. package/esm/model.d.mts +1 -3
  13. package/esm/model.d.mts.map +1 -1
  14. package/esm/model.mjs +7 -3
  15. package/esm/model.mjs.map +1 -1
  16. package/esm/request.type.d.mts +4 -6
  17. package/esm/request.type.d.mts.map +1 -1
  18. package/esm/sdk.d.mts +1 -3
  19. package/esm/sdk.d.mts.map +1 -1
  20. package/esm/thinking-mode.d.mts +2 -3
  21. package/esm/thinking-mode.d.mts.map +1 -1
  22. package/esm/thinking-mode.mjs +1 -1
  23. package/esm/utils/index.d.mts +4 -1
  24. package/esm/utils/index.mjs +1 -1
  25. package/esm/utils/map-stop-reason.d.mts +1 -1
  26. package/esm/utils/provider-blocks.d.mts +3 -5
  27. package/esm/utils/provider-blocks.d.mts.map +1 -1
  28. package/esm/utils/provider-blocks.mjs +3 -3
  29. package/esm/utils/provider-blocks.mjs.map +1 -1
  30. package/esm/utils/server-tool-usage.mjs +17 -0
  31. package/esm/utils/server-tool-usage.mjs.map +1 -0
  32. package/esm/utils/to-anthropic-messages.d.mts +3 -5
  33. package/esm/utils/to-anthropic-messages.d.mts.map +1 -1
  34. package/esm/utils/to-anthropic-tools.d.mts +1 -3
  35. package/esm/utils/to-anthropic-tools.d.mts.map +1 -1
  36. package/llms-full.txt +34 -0
  37. package/package.json +3 -3
  38. package/skills/setup-anthropic/SKILL.md +34 -0
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 { 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 { 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 // 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 // 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 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 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);\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 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(anthropic: AnthropicCallOptions): ContextEdit[] {\n const edits: ContextEdit[] = [];\n const { clearThinking, clearToolUses } = anthropic.contextManagement ?? {};\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 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) : {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WA,SAAS,yBAAyB,KAA+B;CAC/D,MAAM,SAA0B;EAAE,OAAO;EAAG,QAAQ;EAAG,WAAW;EAAG,YAAY;CAAE;CACnF,MAAM,aAAc,KAAqD;CAEzE,IAAI,CAAC,MAAM,QAAQ,UAAU,GAC3B,OAAO;CAGT,KAAK,MAAM,SAAS,YAAyB;EAC3C,MAAM,YAAY;EAElB,IAAI,WAAW,SAAS,cACtB;EAGF,OAAO,SAAS,aAAa,UAAU,YAAY;EACnD,OAAO,UAAU,aAAa,UAAU,aAAa;EACrD,OAAO,aAAa,aAAa,UAAU,uBAAuB;EAClE,OAAO,cAAc,aAAa,UAAU,2BAA2B;CACzE;CAEA,OAAO;AACT;AAEA,SAAS,aAAa,OAAwB;CAC5C,OAAO,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,IAAI,QAAQ;AACvE;AAEA,SAAS,eAAe,OAAc,OAA8B;CAClE,IAAI,MAAM,YAAY,GACpB,MAAM,gBAAgB,MAAM,gBAAgB,KAAK,MAAM;CAGzD,IAAI,MAAM,aAAa,GACrB,MAAM,oBAAoB,MAAM,oBAAoB,KAAK,MAAM;AAEnE;;AAGA,SAAS,wBAAwB,SAA6D;CAC5F,MAAM,MAAM,SAAS,iBAAiB;CAEtC,OAAO,OAAO,QAAQ,YAAY,QAAQ,OAAQ,MAA+B,CAAC;AACpF"}
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 { 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 // 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 // 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);\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(anthropic: AnthropicCallOptions): ContextEdit[] {\n const edits: ContextEdit[] = [];\n const { clearThinking, clearToolUses } = anthropic.contextManagement ?? {};\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 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"],"mappings":";;;;;;;;;;;;;;;;AAoDA,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;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MAAM,SAAS,YAAyB;EAC3C,MAAM,YAAY;EAElB,IAAI,WAAW,SAAS,cACtB;EAGF,OAAO,SAAS,aAAa,UAAU,YAAY;EACnD,OAAO,UAAU,aAAa,UAAU,aAAa;EACrD,OAAO,aAAa,aAAa,UAAU,uBAAuB;EAClE,OAAO,cAAc,aAAa,UAAU,2BAA2B;CACzE;CAEA,OAAO;AACT;AAEA,SAAS,aAAa,OAAwB;CAC5C,OAAO,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,IAAI,QAAQ;AACvE;AAEA,SAAS,eAAe,OAAc,OAA8B;CAClE,IAAI,MAAM,YAAY,GACpB,MAAM,gBAAgB,MAAM,gBAAgB,KAAK,MAAM;CAGzD,IAAI,MAAM,aAAa,GACrB,MAAM,oBAAoB,MAAM,oBAAoB,KAAK,MAAM;AAEnE;;AAGA,SAAS,wBAAwB,SAA6D;CAC5F,MAAM,MAAM,SAAS,iBAAiB;CAEtC,OAAO,OAAO,QAAQ,YAAY,QAAQ,OAAQ,MAA+B,CAAC;AACpF"}
@@ -1,25 +1,23 @@
1
1
  import { StreamChunkOptions } from "@warlock.js/ai";
2
-
3
2
  //#region ../../packages/ai-anthropic/src/request.type.d.ts
4
3
  /** A detached Messages API body and the SDK endpoint and beta headers used to send it. */
5
- type AnthropicRequest<Streaming extends boolean = boolean> = {
4
+ export type AnthropicRequest<Streaming extends boolean = boolean> = {
6
5
  endpoint: "messages" | "beta.messages";
7
6
  body: Record<string, unknown> & {
8
7
  stream: Streaming;
9
8
  };
10
9
  betas: string[];
11
10
  };
12
- type AnthropicStreamingRequest = AnthropicRequest<true>;
13
- type AnthropicNonStreamingRequest = AnthropicRequest<false>;
11
+ export type AnthropicStreamingRequest = AnthropicRequest<true>;
12
+ export type AnthropicNonStreamingRequest = AnthropicRequest<false>;
14
13
  /**
15
14
  * Transport options are separate from the request body being audited.
16
15
  * `streamChunks` picks the optional stream chunks (`reasoning`,
17
16
  * `tool-args`, `usage`) a streaming send yields; it never touches the body.
18
17
  */
19
- type AnthropicRequestOptions = {
18
+ export type AnthropicRequestOptions = {
20
19
  signal?: AbortSignal;
21
20
  streamChunks?: StreamChunkOptions;
22
21
  };
23
22
  //#endregion
24
- export { AnthropicNonStreamingRequest, AnthropicRequest, AnthropicRequestOptions, AnthropicStreamingRequest };
25
23
  //# sourceMappingURL=request.type.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"request.type.d.mts","names":[],"sources":["../../../../../../../packages/ai-anthropic/src/request.type.ts"],"mappings":";;;;KAGY,gBAAA;EACV,QAAA;EACA,IAAA,EAAM,MAAA;IAA4B,MAAA,EAAQ,SAAS;EAAA;EACnD,KAAA;AAAA;AAAA,KAGU,yBAAA,GAA4B,gBAAgB;AAAA,KAC5C,4BAAA,GAA+B,gBAAgB;;;;;AAJpD;KAWK,uBAAA;EAA4B,MAAA,GAAS,WAAA;EAAa,YAAA,GAAe,kBAAkB;AAAA"}
1
+ {"version":3,"file":"request.type.d.mts","names":[],"sources":["../../../../../../../packages/ai-anthropic/src/request.type.ts"],"mappings":";;;YAGY,iBAAiB;EAC3B;EACA,MAAM;IAA4B,QAAQ;;EAC1C;;YAGU,4BAA4B;YAC5B,+BAA+B;;;;;;YAO/B;EAA4B,SAAS;EAAa,eAAe"}
package/esm/sdk.d.mts CHANGED
@@ -1,7 +1,6 @@
1
1
  import { AnthropicModelConfig, AnthropicSDKConfig } from "./config.type.mjs";
2
2
  import { AnthropicModel } from "./model.mjs";
3
3
  import { SDKAdapterContract } from "@warlock.js/ai";
4
-
5
4
  //#region ../../packages/ai-anthropic/src/sdk.d.ts
6
5
  /**
7
6
  * Anthropic-backed implementation of `SDKAdapterContract`.
@@ -37,7 +36,7 @@ import { SDKAdapterContract } from "@warlock.js/ai";
37
36
  * const ai = { agent, tool, systemPrompt, anthropic: new AnthropicSDK({ apiKey }) };
38
37
  * const myAgent = ai.agent({ model: ai.anthropic.model({ name: "claude-haiku-4-5" }) });
39
38
  */
40
- declare class AnthropicSDK implements SDKAdapterContract {
39
+ export declare class AnthropicSDK implements SDKAdapterContract {
41
40
  private readonly client;
42
41
  private readonly provider;
43
42
  private readonly pricing?;
@@ -67,5 +66,4 @@ declare class AnthropicSDK implements SDKAdapterContract {
67
66
  count(text: string, _model?: string): Promise<number>;
68
67
  }
69
68
  //#endregion
70
- export { AnthropicSDK };
71
69
  //# sourceMappingURL=sdk.d.mts.map
package/esm/sdk.d.mts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"sdk.d.mts","names":[],"sources":["../../../../../../../packages/ai-anthropic/src/sdk.ts"],"mappings":";;;;;;;AAwCA;;;;;;;;;;;;;;;;;;;;;;;;;;AA8C4D;;;;;;cA9C/C,YAAA,YAAwB,kBAAA;EAAA,iBAClB,MAAA;EAAA,iBACA,QAAA;EAAA,iBACA,OAAA;cAEE,MAAA,EAAQ,kBAAA;;;;;;;;;;;;;EAwBpB,KAAA,CAAM,MAAA,EAAQ,oBAAA,GAAuB,cAAA;;;;;;;;;;EAiB/B,KAAA,CAAM,IAAA,UAAc,MAAA,YAAkB,OAAA;AAAA"}
1
+ {"version":3,"file":"sdk.d.mts","names":[],"sources":["../../../../../../../packages/ai-anthropic/src/sdk.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAwCa,wBAAwB;mBAClB;mBACA;mBACA;EAEjB,YAAmB,QAAQ;;;;;;;;;;;;;EAwBpB,MAAM,QAAQ,uBAAuB;;;;;;;;;;EAiB/B,MAAM,cAAc,kBAAkB"}
@@ -11,7 +11,7 @@
11
11
  * (`ThinkingConfigEnabled`, `messages.d.ts:1078-1090`). Required on
12
12
  * Haiku 4.5 and older models.
13
13
  */
14
- type AnthropicThinkingMode = "adaptive" | "budget";
14
+ export type AnthropicThinkingMode = "adaptive" | "budget";
15
15
  /**
16
16
  * Whether this model binds a replayed thinking block to the exact
17
17
  * conversation before it (preserved thinking). Unknown and future ids are
@@ -24,7 +24,6 @@ type AnthropicThinkingMode = "adaptive" | "budget";
24
24
  * inferPreservedThinking("claude-opus-5"); // → false
25
25
  * inferPreservedThinking("claude-opus-4-8"); // → false
26
26
  */
27
- declare function inferPreservedThinking(modelName: string): boolean;
27
+ export declare function inferPreservedThinking(modelName: string): boolean;
28
28
  //#endregion
29
- export { AnthropicThinkingMode, inferPreservedThinking };
30
29
  //# sourceMappingURL=thinking-mode.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"thinking-mode.d.mts","names":[],"sources":["../../../../../../../packages/ai-anthropic/src/thinking-mode.ts"],"mappings":";;AAYA;;;;AAAiC;AA8RjC;;;;AAAwD;;KA9R5C,qBAAA;;;;;;;;;;;;;iBA8RI,sBAAA,CAAuB,SAAiB"}
1
+ {"version":3,"file":"thinking-mode.d.mts","names":[],"sources":["../../../../../../../packages/ai-anthropic/src/thinking-mode.ts"],"mappings":";;;;;;;;;;;;;YAYY;;;;;;;;;;;;;wBA8RI,uBAAuB"}
@@ -203,5 +203,5 @@ function inferPreservedThinking(modelName) {
203
203
  }
204
204
 
205
205
  //#endregion
206
- export { acceptsTemperature, inferPreservedThinking, inferThinkingMode, matchesReleaseRoot, noReasoningForm };
206
+ export { acceptsBetweenTools, acceptsTemperature, inferPreservedThinking, inferThinkingMode, matchesReleaseRoot, noReasoningForm };
207
207
  //# sourceMappingURL=thinking-mode.mjs.map
@@ -1,3 +1,6 @@
1
+ import "./map-stop-reason.mjs";
1
2
  import { ANTHROPIC_BLOCK_FORMAT, fromProviderBlocks, toProviderBlocks } from "./provider-blocks.mjs";
2
3
  import { AnthropicMessages, ToAnthropicMessagesOptions, toAnthropicMessages } from "./to-anthropic-messages.mjs";
3
- import { toAnthropicTools } from "./to-anthropic-tools.mjs";
4
+ import { toAnthropicTools } from "./to-anthropic-tools.mjs";
5
+ import "./wrap-anthropic-error.mjs";
6
+ export { ANTHROPIC_BLOCK_FORMAT, type AnthropicMessages, type ToAnthropicMessagesOptions, fromProviderBlocks, toAnthropicMessages, toAnthropicTools, toProviderBlocks };
@@ -4,4 +4,4 @@ import { toAnthropicMessages } from "./to-anthropic-messages.mjs";
4
4
  import { toAnthropicTools } from "./to-anthropic-tools.mjs";
5
5
  import { wrapAnthropicError } from "./wrap-anthropic-error.mjs";
6
6
 
7
- export { };
7
+ export { ANTHROPIC_BLOCK_FORMAT, fromProviderBlocks, mapStopReason, toAnthropicMessages, toAnthropicTools, toProviderBlocks, wrapAnthropicError };
@@ -1 +1 @@
1
- export { };
1
+ import "@warlock.js/ai";
@@ -1,9 +1,8 @@
1
1
  import Anthropic from "@anthropic-ai/sdk";
2
2
  import { ModelToolCallRequest, ProviderContentBlock } from "@warlock.js/ai";
3
-
4
3
  //#region ../../packages/ai-anthropic/src/utils/provider-blocks.d.ts
5
4
  /** The `ProviderContentBlock.provider` value this adapter writes and replays. */
6
- declare const ANTHROPIC_BLOCK_FORMAT = "anthropic";
5
+ export declare const ANTHROPIC_BLOCK_FORMAT = "anthropic";
7
6
  /**
8
7
  * Wrap an assistant turn's content blocks as `ProviderContentBlock`s, or
9
8
  * return `undefined` when the neutral fields already carry the whole turn
@@ -17,7 +16,7 @@ declare const ANTHROPIC_BLOCK_FORMAT = "anthropic";
17
16
  * toProviderBlocks([{ type: "thinking", thinking: "", signature: "s" }, { type: "text", text: "hi" }]);
18
17
  * // [{ provider: "anthropic", type: "thinking", data: {...} }, { provider: "anthropic", type: "text", data: {...} }]
19
18
  */
20
- declare function toProviderBlocks(content: ReadonlyArray<{
19
+ export declare function toProviderBlocks(content: ReadonlyArray<{
21
20
  type: string;
22
21
  }>): ProviderContentBlock[] | undefined;
23
22
  /**
@@ -33,7 +32,6 @@ declare function toProviderBlocks(content: ReadonlyArray<{
33
32
  * results that follow). The checks matter when a transcript comes from
34
33
  * outside the process (a client, a store): the block data is sent as is.
35
34
  */
36
- declare function fromProviderBlocks(blocks: ProviderContentBlock[] | undefined, toolCalls: ModelToolCallRequest[] | undefined): Anthropic.ContentBlockParam[] | undefined;
35
+ export declare function fromProviderBlocks(blocks: ProviderContentBlock[] | undefined, toolCalls: ModelToolCallRequest[] | undefined): Anthropic.ContentBlockParam[] | undefined;
37
36
  //#endregion
38
- export { ANTHROPIC_BLOCK_FORMAT, fromProviderBlocks, toProviderBlocks };
39
37
  //# sourceMappingURL=provider-blocks.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"provider-blocks.d.mts","names":[],"sources":["../../../../../../../../packages/ai-anthropic/src/utils/provider-blocks.ts"],"mappings":";;;;;cAIa,sBAAA;AAAb;;;;AAAmC;AA0CnC;;;;;;;;AA1CA,iBA0CgB,gBAAA,CACd,OAAA,EAAS,aAAA;EAAgB,IAAA;AAAA,KACxB,oBAAoB;;;;;;;;;;;;;;iBAyBP,kBAAA,CACd,MAAA,EAAQ,oBAAA,gBACR,SAAA,EAAW,oBAAA,iBACV,SAAA,CAAU,iBAAA"}
1
+ {"version":3,"file":"provider-blocks.d.mts","names":[],"sources":["../../../../../../../../packages/ai-anthropic/src/utils/provider-blocks.ts"],"mappings":";;;;qBAIa;;;;;;;;;;;;;;wBA0CG,iBACd,SAAS;EAAgB;KACxB;;;;;;;;;;;;;;wBAyBa,mBACd,QAAQ,oCACR,WAAW,qCACV,UAAU"}
@@ -2,9 +2,9 @@
2
2
  /** The `ProviderContentBlock.provider` value this adapter writes and replays. */
3
3
  const ANTHROPIC_BLOCK_FORMAT = "anthropic";
4
4
  /** Block types the neutral `content` + `toolCalls` fields already carry losslessly. */
5
- const NEUTRAL_BLOCK_TYPES = new Set(["text", "tool_use"]);
5
+ const NEUTRAL_BLOCK_TYPES = /* @__PURE__ */ new Set(["text", "tool_use"]);
6
6
  /** Block types that carry a model-requested call whose id must match `toolCalls`. */
7
- const TOOL_USE_BLOCK_TYPES = new Set(["tool_use"]);
7
+ const TOOL_USE_BLOCK_TYPES = /* @__PURE__ */ new Set(["tool_use"]);
8
8
  /**
9
9
  * Assistant-turn block types that may be sent back verbatim. Server-tool
10
10
  * results all end in `_tool_result` (`web_search_tool_result`,
@@ -12,7 +12,7 @@ const TOOL_USE_BLOCK_TYPES = new Set(["tool_use"]);
12
12
  * else (an unknown or user-side type such as `image`, `document` or a
13
13
  * client `tool_result`) is not replayed.
14
14
  */
15
- const REPLAYABLE_BLOCK_TYPES = new Set([
15
+ const REPLAYABLE_BLOCK_TYPES = /* @__PURE__ */ new Set([
16
16
  "text",
17
17
  "thinking",
18
18
  "redacted_thinking",
@@ -1 +1 @@
1
- {"version":3,"file":"provider-blocks.mjs","names":[],"sources":["../../../../../../../../packages/ai-anthropic/src/utils/provider-blocks.ts"],"sourcesContent":["import type { ModelToolCallRequest, ProviderContentBlock } from \"@warlock.js/ai\";\nimport type Anthropic from \"@anthropic-ai/sdk\";\n\n/** The `ProviderContentBlock.provider` value this adapter writes and replays. */\nexport const ANTHROPIC_BLOCK_FORMAT = \"anthropic\";\n\n/** Block types the neutral `content` + `toolCalls` fields already carry losslessly. */\nconst NEUTRAL_BLOCK_TYPES = new Set([\"text\", \"tool_use\"]);\n\n/** Block types that carry a model-requested call whose id must match `toolCalls`. */\nconst TOOL_USE_BLOCK_TYPES = new Set([\"tool_use\"]);\n\n/**\n * Assistant-turn block types that may be sent back verbatim. Server-tool\n * results all end in `_tool_result` (`web_search_tool_result`,\n * `code_execution_tool_result`, …) and are matched by suffix; anything\n * else (an unknown or user-side type such as `image`, `document` or a\n * client `tool_result`) is not replayed.\n */\nconst REPLAYABLE_BLOCK_TYPES: ReadonlySet<string> = new Set([\n \"text\",\n \"thinking\",\n \"redacted_thinking\",\n \"tool_use\",\n \"server_tool_use\",\n \"mcp_tool_use\",\n \"mcp_tool_result\",\n \"container_upload\",\n \"compaction\",\n]);\n\nconst SERVER_TOOL_RESULT_TYPE = /^[a-z][a-z0-9_]*_tool_result$/;\n\n/**\n * Wrap an assistant turn's content blocks as `ProviderContentBlock`s, or\n * return `undefined` when the neutral fields already carry the whole turn\n * (only plain text and `tool_use` blocks). Any other block — thinking,\n * redacted thinking, compaction, server-tool use/results, cited text —\n * makes the full ordered list worth keeping so the next request can\n * replay the turn verbatim.\n *\n * @example\n * toProviderBlocks([{ type: \"text\", text: \"hi\", citations: null }]); // undefined\n * toProviderBlocks([{ type: \"thinking\", thinking: \"\", signature: \"s\" }, { type: \"text\", text: \"hi\" }]);\n * // [{ provider: \"anthropic\", type: \"thinking\", data: {...} }, { provider: \"anthropic\", type: \"text\", data: {...} }]\n */\nexport function toProviderBlocks(\n content: ReadonlyArray<{ type: string }>,\n): ProviderContentBlock[] | undefined {\n if (!content.some(needsVerbatimReplay)) {\n return undefined;\n }\n\n return content.map((block) => ({\n provider: ANTHROPIC_BLOCK_FORMAT,\n type: block.type,\n data: { ...(block as Record<string, unknown>) },\n }));\n}\n\n/**\n * Rebuild an assistant turn's Anthropic content from stored blocks.\n * Returns `undefined` — so the caller falls back to `content` +\n * `toolCalls` — when there are no blocks, when any block belongs to\n * another provider's format, when a block is not a well-formed\n * assistant-turn block (its `data.type` must equal its `type`, and the\n * type must be one Anthropic returns on an assistant turn), or when the\n * blocks' `tool_use` ids differ from the message's `toolCalls` (the turn\n * was edited after the response, e.g. by a middleware or a recovered\n * stream call, so a verbatim replay would no longer match the tool\n * results that follow). The checks matter when a transcript comes from\n * outside the process (a client, a store): the block data is sent as is.\n */\nexport function fromProviderBlocks(\n blocks: ProviderContentBlock[] | undefined,\n toolCalls: ModelToolCallRequest[] | undefined,\n): Anthropic.ContentBlockParam[] | undefined {\n if (!blocks || blocks.length === 0) {\n return undefined;\n }\n\n if (!blocks.every((block) => block.provider === ANTHROPIC_BLOCK_FORMAT && isReplayable(block))) {\n return undefined;\n }\n\n const blockToolIds = blocks\n .filter((block) => TOOL_USE_BLOCK_TYPES.has(block.type))\n .map((block) => block.data.id);\n const requestedIds = (toolCalls ?? []).map((toolCall) => toolCall.id);\n\n if (\n blockToolIds.length !== requestedIds.length ||\n blockToolIds.some((id, index) => id !== requestedIds[index])\n ) {\n return undefined;\n }\n\n return blocks.map((block) => ({ ...block.data }) as unknown as Anthropic.ContentBlockParam);\n}\n\nfunction needsVerbatimReplay(block: { type: string }): boolean {\n if (!NEUTRAL_BLOCK_TYPES.has(block.type)) {\n return true;\n }\n\n const citations = (block as { citations?: unknown }).citations;\n\n return Array.isArray(citations) && citations.length > 0;\n}\n\nfunction isReplayable(block: ProviderContentBlock): boolean {\n const data = block.data as unknown;\n\n if (data === null || typeof data !== \"object\" || Array.isArray(data)) {\n return false;\n }\n\n if ((data as { type?: unknown }).type !== block.type) {\n return false;\n }\n\n return REPLAYABLE_BLOCK_TYPES.has(block.type) || SERVER_TOOL_RESULT_TYPE.test(block.type);\n}\n"],"mappings":";;AAIA,MAAa,yBAAyB;;AAGtC,MAAM,sBAAsB,IAAI,IAAI,CAAC,QAAQ,UAAU,CAAC;;AAGxD,MAAM,uBAAuB,IAAI,IAAI,CAAC,UAAU,CAAC;;;;;;;;AASjD,MAAM,yBAA8C,IAAI,IAAI;CAC1D;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,MAAM,0BAA0B;;;;;;;;;;;;;;AAehC,SAAgB,iBACd,SACoC;CACpC,IAAI,CAAC,QAAQ,KAAK,mBAAmB,GACnC;CAGF,OAAO,QAAQ,KAAK,WAAW;EAC7B,UAAU;EACV,MAAM,MAAM;EACZ,MAAM,EAAE,GAAI,MAAkC;CAChD,EAAE;AACJ;;;;;;;;;;;;;;AAeA,SAAgB,mBACd,QACA,WAC2C;CAC3C,IAAI,CAAC,UAAU,OAAO,WAAW,GAC/B;CAGF,IAAI,CAAC,OAAO,OAAO,UAAU,MAAM,4BAAuC,aAAa,KAAK,CAAC,GAC3F;CAGF,MAAM,eAAe,OAClB,QAAQ,UAAU,qBAAqB,IAAI,MAAM,IAAI,CAAC,CAAC,CACvD,KAAK,UAAU,MAAM,KAAK,EAAE;CAC/B,MAAM,gBAAgB,aAAa,CAAC,EAAC,CAAE,KAAK,aAAa,SAAS,EAAE;CAEpE,IACE,aAAa,WAAW,aAAa,UACrC,aAAa,MAAM,IAAI,UAAU,OAAO,aAAa,MAAM,GAE3D;CAGF,OAAO,OAAO,KAAK,WAAW,EAAE,GAAG,MAAM,KAAK,EAA4C;AAC5F;AAEA,SAAS,oBAAoB,OAAkC;CAC7D,IAAI,CAAC,oBAAoB,IAAI,MAAM,IAAI,GACrC,OAAO;CAGT,MAAM,YAAa,MAAkC;CAErD,OAAO,MAAM,QAAQ,SAAS,KAAK,UAAU,SAAS;AACxD;AAEA,SAAS,aAAa,OAAsC;CAC1D,MAAM,OAAO,MAAM;CAEnB,IAAI,SAAS,QAAQ,OAAO,SAAS,YAAY,MAAM,QAAQ,IAAI,GACjE,OAAO;CAGT,IAAK,KAA4B,SAAS,MAAM,MAC9C,OAAO;CAGT,OAAO,uBAAuB,IAAI,MAAM,IAAI,KAAK,wBAAwB,KAAK,MAAM,IAAI;AAC1F"}
1
+ {"version":3,"file":"provider-blocks.mjs","names":[],"sources":["../../../../../../../../packages/ai-anthropic/src/utils/provider-blocks.ts"],"sourcesContent":["import type { ModelToolCallRequest, ProviderContentBlock } from \"@warlock.js/ai\";\nimport type Anthropic from \"@anthropic-ai/sdk\";\n\n/** The `ProviderContentBlock.provider` value this adapter writes and replays. */\nexport const ANTHROPIC_BLOCK_FORMAT = \"anthropic\";\n\n/** Block types the neutral `content` + `toolCalls` fields already carry losslessly. */\nconst NEUTRAL_BLOCK_TYPES = new Set([\"text\", \"tool_use\"]);\n\n/** Block types that carry a model-requested call whose id must match `toolCalls`. */\nconst TOOL_USE_BLOCK_TYPES = new Set([\"tool_use\"]);\n\n/**\n * Assistant-turn block types that may be sent back verbatim. Server-tool\n * results all end in `_tool_result` (`web_search_tool_result`,\n * `code_execution_tool_result`, …) and are matched by suffix; anything\n * else (an unknown or user-side type such as `image`, `document` or a\n * client `tool_result`) is not replayed.\n */\nconst REPLAYABLE_BLOCK_TYPES: ReadonlySet<string> = new Set([\n \"text\",\n \"thinking\",\n \"redacted_thinking\",\n \"tool_use\",\n \"server_tool_use\",\n \"mcp_tool_use\",\n \"mcp_tool_result\",\n \"container_upload\",\n \"compaction\",\n]);\n\nconst SERVER_TOOL_RESULT_TYPE = /^[a-z][a-z0-9_]*_tool_result$/;\n\n/**\n * Wrap an assistant turn's content blocks as `ProviderContentBlock`s, or\n * return `undefined` when the neutral fields already carry the whole turn\n * (only plain text and `tool_use` blocks). Any other block — thinking,\n * redacted thinking, compaction, server-tool use/results, cited text —\n * makes the full ordered list worth keeping so the next request can\n * replay the turn verbatim.\n *\n * @example\n * toProviderBlocks([{ type: \"text\", text: \"hi\", citations: null }]); // undefined\n * toProviderBlocks([{ type: \"thinking\", thinking: \"\", signature: \"s\" }, { type: \"text\", text: \"hi\" }]);\n * // [{ provider: \"anthropic\", type: \"thinking\", data: {...} }, { provider: \"anthropic\", type: \"text\", data: {...} }]\n */\nexport function toProviderBlocks(\n content: ReadonlyArray<{ type: string }>,\n): ProviderContentBlock[] | undefined {\n if (!content.some(needsVerbatimReplay)) {\n return undefined;\n }\n\n return content.map((block) => ({\n provider: ANTHROPIC_BLOCK_FORMAT,\n type: block.type,\n data: { ...(block as Record<string, unknown>) },\n }));\n}\n\n/**\n * Rebuild an assistant turn's Anthropic content from stored blocks.\n * Returns `undefined` — so the caller falls back to `content` +\n * `toolCalls` — when there are no blocks, when any block belongs to\n * another provider's format, when a block is not a well-formed\n * assistant-turn block (its `data.type` must equal its `type`, and the\n * type must be one Anthropic returns on an assistant turn), or when the\n * blocks' `tool_use` ids differ from the message's `toolCalls` (the turn\n * was edited after the response, e.g. by a middleware or a recovered\n * stream call, so a verbatim replay would no longer match the tool\n * results that follow). The checks matter when a transcript comes from\n * outside the process (a client, a store): the block data is sent as is.\n */\nexport function fromProviderBlocks(\n blocks: ProviderContentBlock[] | undefined,\n toolCalls: ModelToolCallRequest[] | undefined,\n): Anthropic.ContentBlockParam[] | undefined {\n if (!blocks || blocks.length === 0) {\n return undefined;\n }\n\n if (!blocks.every((block) => block.provider === ANTHROPIC_BLOCK_FORMAT && isReplayable(block))) {\n return undefined;\n }\n\n const blockToolIds = blocks\n .filter((block) => TOOL_USE_BLOCK_TYPES.has(block.type))\n .map((block) => block.data.id);\n const requestedIds = (toolCalls ?? []).map((toolCall) => toolCall.id);\n\n if (\n blockToolIds.length !== requestedIds.length ||\n blockToolIds.some((id, index) => id !== requestedIds[index])\n ) {\n return undefined;\n }\n\n return blocks.map((block) => ({ ...block.data }) as unknown as Anthropic.ContentBlockParam);\n}\n\nfunction needsVerbatimReplay(block: { type: string }): boolean {\n if (!NEUTRAL_BLOCK_TYPES.has(block.type)) {\n return true;\n }\n\n const citations = (block as { citations?: unknown }).citations;\n\n return Array.isArray(citations) && citations.length > 0;\n}\n\nfunction isReplayable(block: ProviderContentBlock): boolean {\n const data = block.data as unknown;\n\n if (data === null || typeof data !== \"object\" || Array.isArray(data)) {\n return false;\n }\n\n if ((data as { type?: unknown }).type !== block.type) {\n return false;\n }\n\n return REPLAYABLE_BLOCK_TYPES.has(block.type) || SERVER_TOOL_RESULT_TYPE.test(block.type);\n}\n"],"mappings":";;AAIA,MAAa,yBAAyB;;AAGtC,MAAM,sCAAsB,IAAI,IAAI,CAAC,QAAQ,UAAU,CAAC;;AAGxD,MAAM,uCAAuB,IAAI,IAAI,CAAC,UAAU,CAAC;;;;;;;;AASjD,MAAM,yCAA8C,IAAI,IAAI;CAC1D;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,MAAM,0BAA0B;;;;;;;;;;;;;;AAehC,SAAgB,iBACd,SACoC;CACpC,IAAI,CAAC,QAAQ,KAAK,mBAAmB,GACnC;CAGF,OAAO,QAAQ,KAAK,WAAW;EAC7B,UAAU;EACV,MAAM,MAAM;EACZ,MAAM,EAAE,GAAI,MAAkC;CAChD,EAAE;AACJ;;;;;;;;;;;;;;AAeA,SAAgB,mBACd,QACA,WAC2C;CAC3C,IAAI,CAAC,UAAU,OAAO,WAAW,GAC/B;CAGF,IAAI,CAAC,OAAO,OAAO,UAAU,MAAM,4BAAuC,aAAa,KAAK,CAAC,GAC3F;CAGF,MAAM,eAAe,OAClB,QAAQ,UAAU,qBAAqB,IAAI,MAAM,IAAI,CAAC,CAAC,CACvD,KAAK,UAAU,MAAM,KAAK,EAAE;CAC/B,MAAM,gBAAgB,aAAa,CAAC,EAAC,CAAE,KAAK,aAAa,SAAS,EAAE;CAEpE,IACE,aAAa,WAAW,aAAa,UACrC,aAAa,MAAM,IAAI,UAAU,OAAO,aAAa,MAAM,GAE3D;CAGF,OAAO,OAAO,KAAK,WAAW,EAAE,GAAG,MAAM,KAAK,EAA4C;AAC5F;AAEA,SAAS,oBAAoB,OAAkC;CAC7D,IAAI,CAAC,oBAAoB,IAAI,MAAM,IAAI,GACrC,OAAO;CAGT,MAAM,YAAa,MAAkC;CAErD,OAAO,MAAM,QAAQ,SAAS,KAAK,UAAU,SAAS;AACxD;AAEA,SAAS,aAAa,OAAsC;CAC1D,MAAM,OAAO,MAAM;CAEnB,IAAI,SAAS,QAAQ,OAAO,SAAS,YAAY,MAAM,QAAQ,IAAI,GACjE,OAAO;CAGT,IAAK,KAA4B,SAAS,MAAM,MAC9C,OAAO;CAGT,OAAO,uBAAuB,IAAI,MAAM,IAAI,KAAK,wBAAwB,KAAK,MAAM,IAAI;AAC1F"}
@@ -0,0 +1,17 @@
1
+ //#region ../../packages/ai-anthropic/src/utils/server-tool-usage.ts
2
+ /** Installed @anthropic-ai/sdk 0.129.0 ServerToolUsage and MessageDeltaUsage use the same cumulative counters.
3
+ * https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool
4
+ * https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-fetch-tool
5
+ * No code-execution request counter is reported: never count content blocks instead. */
6
+ function applyServerToolUsage(usage, raw) {
7
+ if (!raw) return;
8
+ usage.serverToolUse = {
9
+ ...usage.serverToolUse,
10
+ ...raw.web_search_requests !== void 0 ? { webSearchRequests: raw.web_search_requests } : {},
11
+ ...raw.web_fetch_requests !== void 0 ? { webFetchRequests: raw.web_fetch_requests } : {}
12
+ };
13
+ }
14
+
15
+ //#endregion
16
+ export { applyServerToolUsage };
17
+ //# sourceMappingURL=server-tool-usage.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server-tool-usage.mjs","names":[],"sources":["../../../../../../../../packages/ai-anthropic/src/utils/server-tool-usage.ts"],"sourcesContent":["import type Anthropic from \"@anthropic-ai/sdk\";\nimport type { Usage } from \"@warlock.js/ai\";\n\n/** Installed @anthropic-ai/sdk 0.129.0 ServerToolUsage and MessageDeltaUsage use the same cumulative counters.\n * https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool\n * https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-fetch-tool\n * No code-execution request counter is reported: never count content blocks instead. */\nexport function applyServerToolUsage(\n usage: Usage,\n raw: Partial<Anthropic.ServerToolUsage> | null | undefined,\n): void {\n if (!raw) return;\n usage.serverToolUse = {\n ...usage.serverToolUse,\n ...(raw.web_search_requests !== undefined\n ? { webSearchRequests: raw.web_search_requests }\n : {}),\n ...(raw.web_fetch_requests !== undefined ? { webFetchRequests: raw.web_fetch_requests } : {}),\n };\n}\n"],"mappings":";;;;;AAOA,SAAgB,qBACd,OACA,KACM;CACN,IAAI,CAAC,KAAK;CACV,MAAM,gBAAgB;EACpB,GAAG,MAAM;EACT,GAAI,IAAI,wBAAwB,SAC5B,EAAE,mBAAmB,IAAI,oBAAoB,IAC7C,CAAC;EACL,GAAI,IAAI,uBAAuB,SAAY,EAAE,kBAAkB,IAAI,mBAAmB,IAAI,CAAC;CAC7F;AACF"}