@warlock.js/ai-anthropic 5.30.0 → 5.31.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.
- package/CHANGELOG.md +44 -6
- package/cjs/index.cjs +815 -132
- package/cjs/index.cjs.map +1 -1
- package/esm/config.type.d.mts +107 -4
- package/esm/config.type.d.mts.map +1 -1
- package/esm/index.d.mts +8 -3
- package/esm/index.mjs +7 -1
- package/esm/known-output-limits.mjs +46 -0
- package/esm/known-output-limits.mjs.map +1 -0
- package/esm/known-pricing.d.mts +58 -0
- package/esm/known-pricing.d.mts.map +1 -0
- package/esm/known-pricing.mjs +165 -0
- package/esm/known-pricing.mjs.map +1 -0
- package/esm/model.d.mts +89 -17
- package/esm/model.d.mts.map +1 -1
- package/esm/model.mjs +383 -86
- package/esm/model.mjs.map +1 -1
- package/esm/request.type.d.mts +25 -0
- package/esm/request.type.d.mts.map +1 -0
- package/esm/thinking-mode.d.mts +14 -1
- package/esm/thinking-mode.d.mts.map +1 -1
- package/esm/thinking-mode.mjs +102 -2
- package/esm/thinking-mode.mjs.map +1 -1
- package/esm/utils/cache-usage.mjs +62 -0
- package/esm/utils/cache-usage.mjs.map +1 -0
- package/esm/utils/index.d.mts +3 -0
- package/esm/utils/map-stop-reason.d.mts +1 -0
- package/esm/utils/provider-blocks.d.mts +39 -0
- package/esm/utils/provider-blocks.d.mts.map +1 -0
- package/esm/utils/to-anthropic-messages.d.mts +71 -0
- package/esm/utils/to-anthropic-messages.d.mts.map +1 -0
- package/esm/utils/to-anthropic-messages.mjs +12 -4
- package/esm/utils/to-anthropic-messages.mjs.map +1 -1
- package/esm/utils/to-anthropic-tools.d.mts +19 -0
- package/esm/utils/to-anthropic-tools.d.mts.map +1 -0
- package/esm/utils/wrap-anthropic-error.d.mts +1 -0
- package/esm/utils/wrap-anthropic-error.mjs +6 -1
- package/esm/utils/wrap-anthropic-error.mjs.map +1 -1
- package/llms-full.txt +214 -32
- package/llms.txt +1 -1
- package/package.json +3 -3
- package/skills/README.md +1 -1
- package/skills/setup-anthropic/SKILL.md +214 -32
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 InvalidRequestError,\n safeJsonParse,\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 { AnthropicCallOptions, AnthropicModelConfig } from \"./config.type\";\nimport { inferVisionCapability } from \"./known-vision-models\";\nimport {\n acceptsBetweenTools,\n acceptsTemperature,\n inferThinkingMode,\n type AnthropicThinkingMode,\n} from \"./thinking-mode\";\nimport {\n mapStopReason,\n toAnthropicMessages,\n toAnthropicTools,\n toProviderBlocks,\n wrapAnthropicError,\n} from \"./utils\";\n\nconst LOG_MODULE = \"ai.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\n * model config supplies one, fall back to a generous default so a\n * caller who never thought about token caps still gets a complete\n * answer instead of a 400.\n */\nconst DEFAULT_MAX_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: reserved on top of `DEFAULT_MAX_TOKENS` when the caller\n * sets no `maxTokens`, because thinking counts toward `max_tokens`\n * (installed SDK `ThinkingConfigParam` docs, `messages.d.ts:1105`).\n * Adaptive models therefore get the same `max_tokens` the budget path\n * has always produced.\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 to reserve on top of\n * `DEFAULT_MAX_TOKENS` when the caller configured no `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 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 this.pricing = config.pricing;\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.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 this.logger.debug(LOG_MODULE, \"request\", \"Starting call to messages.create\", {\n model: this.name,\n messageCount: messages.length,\n streaming: false,\n toolCount: options?.tools?.length ?? 0,\n });\n\n let response: Anthropic.Message;\n\n try {\n response = (await this.send(\n { ...this.buildBody(messages, options), stream: false },\n options,\n \"create\",\n )) 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);\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 body = this.buildBody(messages, options);\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.send(countBody, options, \"countTokens\")) 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 public async *stream(\n messages: Message[],\n options?: ModelCallOptions,\n ): AsyncIterable<ModelStreamChunk> {\n this.logger.debug(LOG_MODULE, \"request\", \"Starting streaming call to messages.create\", {\n model: this.name,\n messageCount: messages.length,\n streaming: true,\n toolCount: options?.tools?.length ?? 0,\n });\n\n let stream: AsyncIterable<Anthropic.RawMessageStreamEvent>;\n\n try {\n stream = (await this.send(\n { ...this.buildBody(messages, options), stream: true },\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 const usage: Usage = { input: 0, output: 0, total: 0 };\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 const cacheRead = event.message.usage.cache_read_input_tokens;\n\n if (cacheRead !== null && cacheRead !== undefined && cacheRead > 0) {\n usage.cachedTokens = cacheRead;\n }\n\n const cacheWrite = event.message.usage.cache_creation_input_tokens;\n\n if (cacheWrite !== null && cacheWrite !== undefined && cacheWrite > 0) {\n usage.cacheWriteTokens = cacheWrite;\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 } 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 } 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 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 const cacheRead = event.usage.cache_read_input_tokens;\n\n if (cacheRead !== null && cacheRead !== undefined && cacheRead > 0) {\n usage.cachedTokens = cacheRead;\n }\n\n const cacheWrite = event.usage.cache_creation_input_tokens;\n\n if (cacheWrite !== null && cacheWrite !== undefined && cacheWrite > 0) {\n usage.cacheWriteTokens = cacheWrite;\n }\n }\n }\n } catch (thrown) {\n throw this.logAndWrap(thrown);\n }\n\n usage.total = usage.input + usage.output;\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 send(\n body: Record<string, unknown>,\n options: ModelCallOptions | undefined,\n method: \"create\" | \"countTokens\",\n ): Promise<unknown> {\n const betas = resolveAnthropicOptions(options).betas;\n const requestOptions = options?.signal ? { signal: options.signal } : undefined;\n const api = betas && betas.length > 0 ? this.client.beta.messages : this.client.messages;\n const call = api[method] as unknown as LooseCreate;\n\n return call.call(api, betas && betas.length > 0 ? { ...body, betas } : body, requestOptions);\n }\n\n /**\n * The full request body: the adapter-built params, then\n * `thinking.display` when thinking is sent on an adaptive model, then\n * `providerOptions.anthropic.body` merged last (caller fields win). The\n * body may add fields the adapter does not build (`context_management`,\n * `fallbacks`, …) but may not replace the conversation or the model —\n * see {@link RESERVED_BODY_FIELDS}.\n */\n private buildBody(\n messages: Message[],\n options: ModelCallOptions | undefined,\n ): Record<string, unknown> {\n const anthropic = resolveAnthropicOptions(options);\n const body: Record<string, unknown> = { ...this.buildParams(messages, options) };\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 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, ...anthropic.body };\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 | undefined,\n ): Omit<Anthropic.MessageCreateParamsNonStreaming, \"stream\"> {\n const { system, messages: anthropicMessages } = toAnthropicMessages(messages);\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 (thinking.reservedTokens !== undefined\n ? thinking.reservedTokens + DEFAULT_MAX_TOKENS\n : DEFAULT_MAX_TOKENS);\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?.tools, options?.cacheControl),\n ...this.buildOutputConfig(options?.responseSchema, thinking.effort),\n ...(thinking.thinking ? { thinking: thinking.thinking } : {}),\n };\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:\n * - Claude Sonnet 5.5 (`acceptsBetweenTools`): `thinking: { type:\n * \"between_tools\" }`, its only thinking-off form. It is sent alone —\n * no `output_config.effort` (the model default, `high`, is within the\n * `high`-or-below range it requires) and no `display`, both of which\n * the API rejects alongside it.\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\". Sonnet 5.5\n // turns thinking off only through `between_tools`; elsewhere we omit\n // the `thinking` block. (This also short-circuits the\n // `EFFORT_THINKING_BUDGET[\"none\"]` → `undefined` → `NaN` budget path.)\n if (reasoning.effort === \"none\") {\n return acceptsBetweenTools(this.name) ? { thinking: { type: \"between_tools\" } } : {};\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 * 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 tools: ModelCallOptions[\"tools\"],\n cacheControl: ModelCallOptions[\"cacheControl\"],\n ): { tools?: Anthropic.Tool[] } {\n const mapped = toAnthropicTools(tools);\n\n if (!mapped) {\n return {};\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: 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. Cache-read tokens are\n * surfaced as `cachedTokens` and cache-write tokens as\n * `cacheWriteTokens`, each only when non-zero. 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.\n */\n private extractUsage(raw: Anthropic.Usage): Usage {\n const input = raw.input_tokens ?? 0;\n const output = raw.output_tokens ?? 0;\n const cacheRead = raw.cache_read_input_tokens;\n const cacheWrite = raw.cache_creation_input_tokens;\n const thinkingTokens = raw.output_tokens_details?.thinking_tokens;\n\n return {\n input,\n output,\n total: input + output,\n ...(cacheRead !== null && cacheRead !== undefined && cacheRead > 0\n ? { cachedTokens: cacheRead }\n : {}),\n ...(cacheWrite !== null && cacheWrite !== undefined && cacheWrite > 0\n ? { cacheWriteTokens: cacheWrite }\n : {}),\n ...(thinkingTokens !== null && thinkingTokens !== undefined\n ? { reasoningTokens: thinkingTokens }\n : {}),\n };\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/** 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":";;;;;;;;;;;;AAgCA,MAAM,aAAa;;;;;;;;AASnB,MAAM,qBAAqB;;;;;;AAO3B,MAAM,sBAAsB;;;;;;;AAU5B,MAAM,0BAA0C;;;;;;;;;;;;AAahD,MAAM,yBAAyD;CAG7D,SAAS;CACT,KAAK;CACL,QAAQ;CACR,MAAM;CAIN,OAAO;CACP,KAAK;AACP;;;;;;;;AASA,MAAM,0BAGF;CACF,SAAS;CACT,KAAK;CACL,QAAQ;CACR,MAAM;CACN,OAAO;CACP,KAAK;AACP;;AAeA,MAAM,6BAA6B,IAAI,IAAI;CAAC;CAAY;CAAmB;AAAc,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyD1F,IAAa,iBAAb,MAAqD;CAWnD,AAAO,YACL,QACA,QACA,WAAmB,aACnB;gBANgC;EAOhC,KAAK,SAAS;EACd,KAAK,SAAS;EACd,KAAK,OAAO,OAAO;EACnB,KAAK,WAAW;EAChB,KAAK,UAAU,OAAO;EAGtB,KAAK,eAAe,OAAO,gBAAgB,kBAAkB,OAAO,IAAI;EACxE,KAAK,eAAe;GAClB,kBAAkB,OAAO,oBAAoB;GAC7C,QAAQ,OAAO,UAAU,sBAAsB,OAAO,IAAI;GAK1D,WAAW,OAAO,aAAa;GAO/B,eAAe;GAGf,KAAK;EAIP;CACF;;;;;;;CAQA,MAAa,SAAS,UAAqB,SAAoD;EAC7F,KAAK,OAAO,MAAM,YAAY,WAAW,o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B;EAClC,MAAM,SAAS,IAAI,iBAAiB;EACpC,MAAM,YAAY,IAAI;EACtB,MAAM,aAAa,IAAI;EACvB,MAAM,iBAAiB,IAAI,uBAAuB;EAElD,OAAO;GACL;GACA;GACA,OAAO,QAAQ;GACf,GAAI,cAAc,QAAQ,cAAc,UAAa,YAAY,IAC7D,EAAE,cAAc,UAAU,IAC1B,CAAC;GACL,GAAI,eAAe,QAAQ,eAAe,UAAa,aAAa,IAChE,EAAE,kBAAkB,WAAW,IAC/B,CAAC;GACL,GAAI,mBAAmB,QAAQ,mBAAmB,SAC9C,EAAE,iBAAiB,eAAe,IAClC,CAAC;EACP;CACF;;;;;;CAOA,AAAQ,WAAW,QAAiB;EAClC,MAAM,UAAU,mBAAmB,MAAM;EAEzC,KAAK,OAAO,MAAM,YAAY,SAAS,QAAQ,SAAS;GACtD,MAAM,QAAQ;GACd,SAAS,QAAQ;EACnB,CAAC;EAED,OAAO;CACT;AACF;;;;;;;;AASA,MAAM,uBAA4C,IAAI,IAAI;CACxD;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;AAGD,MAAM,sBAAsB;CAC1B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;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 { 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) : {};\n}\n"],"mappings":";;;;;;;;;;;;;;;AAmDA,MAAM,aAAa;;AAGnB,MAAM,wBAAwB;;;;;;;;;;;;;;;AAgB9B,MAAM,qBAAqB;;;;;;;AAQ3B,MAAM,oBAAoB;;;;;;AAO1B,MAAM,sBAAsB;;;;;;;AAU5B,MAAM,0BAA0C;;;;;;;;;;;AAYhD,MAAM,yBAAyD;CAG7D,SAAS;CACT,KAAK;CACL,QAAQ;CACR,MAAM;CAIN,OAAO;CACP,KAAK;AACP;;;;;;;;AASA,MAAM,0BAGF;CACF,SAAS;CACT,KAAK;CACL,QAAQ;CACR,MAAM;CACN,OAAO;CACP,K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,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"}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { StreamChunkOptions } from "@warlock.js/ai";
|
|
2
|
+
|
|
3
|
+
//#region ../../packages/ai-anthropic/src/request.type.d.ts
|
|
4
|
+
/** A detached Messages API body and the SDK endpoint and beta headers used to send it. */
|
|
5
|
+
type AnthropicRequest<Streaming extends boolean = boolean> = {
|
|
6
|
+
endpoint: "messages" | "beta.messages";
|
|
7
|
+
body: Record<string, unknown> & {
|
|
8
|
+
stream: Streaming;
|
|
9
|
+
};
|
|
10
|
+
betas: string[];
|
|
11
|
+
};
|
|
12
|
+
type AnthropicStreamingRequest = AnthropicRequest<true>;
|
|
13
|
+
type AnthropicNonStreamingRequest = AnthropicRequest<false>;
|
|
14
|
+
/**
|
|
15
|
+
* Transport options are separate from the request body being audited.
|
|
16
|
+
* `streamChunks` picks the optional stream chunks (`reasoning`,
|
|
17
|
+
* `tool-args`, `usage`) a streaming send yields; it never touches the body.
|
|
18
|
+
*/
|
|
19
|
+
type AnthropicRequestOptions = {
|
|
20
|
+
signal?: AbortSignal;
|
|
21
|
+
streamChunks?: StreamChunkOptions;
|
|
22
|
+
};
|
|
23
|
+
//#endregion
|
|
24
|
+
export { AnthropicNonStreamingRequest, AnthropicRequest, AnthropicRequestOptions, AnthropicStreamingRequest };
|
|
25
|
+
//# sourceMappingURL=request.type.d.mts.map
|
|
@@ -0,0 +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"}
|
package/esm/thinking-mode.d.mts
CHANGED
|
@@ -12,6 +12,19 @@
|
|
|
12
12
|
* Haiku 4.5 and older models.
|
|
13
13
|
*/
|
|
14
14
|
type AnthropicThinkingMode = "adaptive" | "budget";
|
|
15
|
+
/**
|
|
16
|
+
* Whether this model binds a replayed thinking block to the exact
|
|
17
|
+
* conversation before it (preserved thinking). Unknown and future ids are
|
|
18
|
+
* assumed to run the check — the safe direction: reasoning a kept turn
|
|
19
|
+
* can't use is left out instead of risking a 400. Matches the id with or
|
|
20
|
+
* without a platform prefix and with dated or tagged suffixes.
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* inferPreservedThinking("claude-opus-5-5"); // → true
|
|
24
|
+
* inferPreservedThinking("claude-opus-5"); // → false
|
|
25
|
+
* inferPreservedThinking("claude-opus-4-8"); // → false
|
|
26
|
+
*/
|
|
27
|
+
declare function inferPreservedThinking(modelName: string): boolean;
|
|
15
28
|
//#endregion
|
|
16
|
-
export { AnthropicThinkingMode };
|
|
29
|
+
export { AnthropicThinkingMode, inferPreservedThinking };
|
|
17
30
|
//# 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
|
|
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"}
|
package/esm/thinking-mode.mjs
CHANGED
|
@@ -33,6 +33,11 @@ const BUDGET_RELEASE_ROOTS = [
|
|
|
33
33
|
* Dates (`-20250514`) and tags (`-latest`, `-v1`) are not minor versions.
|
|
34
34
|
*/
|
|
35
35
|
const NEXT_MINOR_VERSION = /^-\d{1,2}(?!\d)/;
|
|
36
|
+
/**
|
|
37
|
+
* Whether a lower-cased model id is the release `root` itself, or a dated /
|
|
38
|
+
* tagged / `@` snapshot of it — but not a later minor version of the same
|
|
39
|
+
* line (`claude-opus-4` matches `claude-opus-4-20250514`, not `claude-opus-4-7`).
|
|
40
|
+
*/
|
|
36
41
|
function matchesReleaseRoot(name, root) {
|
|
37
42
|
if (!name.startsWith(root)) return false;
|
|
38
43
|
const rest = name.slice(root.length);
|
|
@@ -97,11 +102,106 @@ const BETWEEN_TOOLS_RELEASE_ROOTS = ["claude-sonnet-5-5"];
|
|
|
97
102
|
* acceptsBetweenTools("claude-opus-5-5"); // → false
|
|
98
103
|
*/
|
|
99
104
|
function acceptsBetweenTools(modelName) {
|
|
105
|
+
return matchesAnyRelease(modelName, BETWEEN_TOOLS_RELEASE_ROOTS);
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Whether the model id — lower-cased, with any platform prefix
|
|
109
|
+
* (`anthropic.`, `us.anthropic.` on Bedrock) removed — is one of these
|
|
110
|
+
* releases, dated or tagged, but not a later minor release.
|
|
111
|
+
*/
|
|
112
|
+
function matchesAnyRelease(modelName, roots) {
|
|
113
|
+
const normalized = modelName.toLowerCase();
|
|
114
|
+
const id = normalized.slice(normalized.lastIndexOf(".") + 1);
|
|
115
|
+
return roots.some((root) => matchesReleaseRoot(id, root));
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Releases that accept `thinking: { type: "disabled" }` and run reliably
|
|
119
|
+
* with it. Source: claude-api ref, "Thinking & Effort" per-model table
|
|
120
|
+
* (cached 2026-10-06): Claude Sonnet 5 accepts `disabled`; Claude Haiku 5.5
|
|
121
|
+
* accepts it at effort `low`, `medium` and `high` (a 400 at `xhigh` /
|
|
122
|
+
* `max`). No effort is sent alongside it, so Haiku 5.5 runs at its default,
|
|
123
|
+
* `medium`, which is inside the accepted range.
|
|
124
|
+
*/
|
|
125
|
+
const DISABLED_THINKING_RELEASE_ROOTS = ["claude-sonnet-5", "claude-haiku-5-5"];
|
|
126
|
+
/**
|
|
127
|
+
* Releases that accept `disabled` but are kept on adaptive thinking at the
|
|
128
|
+
* lowest effort instead. Claude Opus 5 accepts `disabled` at effort `high`
|
|
129
|
+
* or below, but the claude-api ref ("Two failure modes when thinking is
|
|
130
|
+
* disabled", cached 2026-10-06) documents that with thinking disabled it
|
|
131
|
+
* occasionally writes a tool call into its visible text instead of a
|
|
132
|
+
* `tool_use` block — the call never runs and no error is raised — and can
|
|
133
|
+
* leak `<thinking>` tags into the response. The ref's primary
|
|
134
|
+
* recommendation is to keep thinking on and lower `effort`, so the adapter
|
|
135
|
+
* does exactly that.
|
|
136
|
+
*/
|
|
137
|
+
const LOWEST_EFFORT_RELEASE_ROOTS = ["claude-opus-5"];
|
|
138
|
+
/**
|
|
139
|
+
* The wire form for `reasoning: { effort: "none" }` on this model:
|
|
140
|
+
*
|
|
141
|
+
* | Model | Form |
|
|
142
|
+
* |----------------------------------------|-------------------|
|
|
143
|
+
* | Claude Sonnet 5.5 | `between_tools` |
|
|
144
|
+
* | Claude Sonnet 5, Claude Haiku 5.5 | `disabled` |
|
|
145
|
+
* | Claude Opus 5 | `lowest-effort` |
|
|
146
|
+
* | Opus 5.5, Fable 5/5.1, everything else | `omit` |
|
|
147
|
+
*
|
|
148
|
+
* Opus 5.5 and Fable 5/5.1 have no thinking-off form (`disabled` and
|
|
149
|
+
* `budget_tokens` are a 400 at every effort), so nothing is sent and the
|
|
150
|
+
* model runs at its default effort; older models run without thinking when
|
|
151
|
+
* the field is absent.
|
|
152
|
+
*
|
|
153
|
+
* @example
|
|
154
|
+
* noReasoningForm("claude-sonnet-5"); // → "disabled"
|
|
155
|
+
* noReasoningForm("claude-opus-5"); // → "lowest-effort"
|
|
156
|
+
* noReasoningForm("claude-opus-5-5"); // → "omit"
|
|
157
|
+
*/
|
|
158
|
+
function noReasoningForm(modelName) {
|
|
159
|
+
if (acceptsBetweenTools(modelName)) return "between_tools";
|
|
160
|
+
if (matchesAnyRelease(modelName, DISABLED_THINKING_RELEASE_ROOTS)) return "disabled";
|
|
161
|
+
if (matchesAnyRelease(modelName, LOWEST_EFFORT_RELEASE_ROOTS)) return "lowest-effort";
|
|
162
|
+
return "omit";
|
|
163
|
+
}
|
|
164
|
+
const PREFIX_CHECK_RELEASE_ROOTS = [
|
|
165
|
+
"claude-fable-5-1",
|
|
166
|
+
"claude-opus-5-5",
|
|
167
|
+
"claude-sonnet-5-5",
|
|
168
|
+
"claude-haiku-5-5"
|
|
169
|
+
];
|
|
170
|
+
/** Releases documented not to run the conversation check. */
|
|
171
|
+
const NO_PREFIX_CHECK_RELEASE_ROOTS = [
|
|
172
|
+
"claude-mythos-5-1",
|
|
173
|
+
"claude-mythos-5",
|
|
174
|
+
"claude-mythos-preview",
|
|
175
|
+
"claude-fable-5",
|
|
176
|
+
"claude-opus-5",
|
|
177
|
+
"claude-sonnet-5"
|
|
178
|
+
];
|
|
179
|
+
/** Families released before Claude Fable 5.1 in their entirety. */
|
|
180
|
+
const NO_PREFIX_CHECK_FAMILY_PREFIXES = [
|
|
181
|
+
...BUDGET_FAMILY_PREFIXES,
|
|
182
|
+
"claude-opus-4",
|
|
183
|
+
"claude-sonnet-4"
|
|
184
|
+
];
|
|
185
|
+
/**
|
|
186
|
+
* Whether this model binds a replayed thinking block to the exact
|
|
187
|
+
* conversation before it (preserved thinking). Unknown and future ids are
|
|
188
|
+
* assumed to run the check — the safe direction: reasoning a kept turn
|
|
189
|
+
* can't use is left out instead of risking a 400. Matches the id with or
|
|
190
|
+
* without a platform prefix and with dated or tagged suffixes.
|
|
191
|
+
*
|
|
192
|
+
* @example
|
|
193
|
+
* inferPreservedThinking("claude-opus-5-5"); // → true
|
|
194
|
+
* inferPreservedThinking("claude-opus-5"); // → false
|
|
195
|
+
* inferPreservedThinking("claude-opus-4-8"); // → false
|
|
196
|
+
*/
|
|
197
|
+
function inferPreservedThinking(modelName) {
|
|
100
198
|
const normalized = modelName.toLowerCase();
|
|
101
199
|
const id = normalized.slice(normalized.lastIndexOf(".") + 1);
|
|
102
|
-
|
|
200
|
+
if (PREFIX_CHECK_RELEASE_ROOTS.some((root) => matchesReleaseRoot(id, root))) return true;
|
|
201
|
+
if (NO_PREFIX_CHECK_RELEASE_ROOTS.some((root) => matchesReleaseRoot(id, root)) || NO_PREFIX_CHECK_FAMILY_PREFIXES.some((prefix) => id.startsWith(prefix))) return false;
|
|
202
|
+
return true;
|
|
103
203
|
}
|
|
104
204
|
|
|
105
205
|
//#endregion
|
|
106
|
-
export {
|
|
206
|
+
export { acceptsTemperature, inferPreservedThinking, inferThinkingMode, matchesReleaseRoot, noReasoningForm };
|
|
107
207
|
//# sourceMappingURL=thinking-mode.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"thinking-mode.mjs","names":[],"sources":["../../../../../../../packages/ai-anthropic/src/thinking-mode.ts"],"sourcesContent":["/**\n * How a Claude model accepts extended thinking on the Messages API.\n *\n * - `\"adaptive\"` — `thinking: { type: \"adaptive\" }`, with depth steered by\n * `output_config.effort`. Sending `budget_tokens` to these models is a\n * 400. Installed SDK: `ThinkingConfigAdaptive`\n * (`@anthropic-ai/sdk/resources/messages/messages.d.ts:1065`) and\n * `OutputConfig.effort` (`messages.d.ts:796-800`).\n * - `\"budget\"` — the legacy `thinking: { type: \"enabled\", budget_tokens }`\n * (`ThinkingConfigEnabled`, `messages.d.ts:1078-1090`). Required on\n * Haiku 4.5 and older models.\n */\nexport type AnthropicThinkingMode = \"adaptive\" | \"budget\";\n\n/*\n * Model-family table (source: claude-api ref, \"Thinking & Effort\" per-model\n * table, cached 2026-09-25; summarised in `releases/5.26-ai-sdk-review.md` §A):\n *\n * | Model ids | Mode | `budget_tokens` | `temperature` |\n * |----------------------------------------------|------------|-------------------------|--------------------|\n * | claude-fable-5, claude-fable-5-1 (+ mythos) | adaptive | removed (400) | removed (400) |\n * | claude-opus-5-5, claude-opus-5 | adaptive | removed (400) | removed (400) |\n * | claude-opus-4-8, claude-opus-4-7 | adaptive | removed (400) | removed (400) |\n * | claude-sonnet-5-5, claude-sonnet-5 | adaptive | removed (400) | 400 (5.5: non-1.0) |\n * | claude-opus-4-6, claude-sonnet-4-6 | budget (*) | deprecated, still works | allowed |\n * | claude-haiku-4-5 and every older model | budget | required for thinking | allowed |\n * | anything not listed (future / unknown ids) | adaptive | — | — |\n *\n * (*) The 4.6 pair accepts both shapes; the claude-api ref recommends\n * adaptive there but keeps `budget_tokens` functional as a transitional\n * path. It stays on `budget` so 4.6 callers see no behaviour change (their\n * `reasoning.maxTokens` is still honoured as a hard budget) and so that\n * the `budget` set is exactly the set that still accepts `temperature`\n * (see `acceptsTemperature`). Opt 4.6 into adaptive with\n * `anthropic.model({ name, thinkingMode: \"adaptive\" })`.\n *\n * Unknown ids default to adaptive because that is the current API\n * direction: every model released after Opus 4.6 rejects `budget_tokens`.\n */\n\n/**\n * Family prefixes that are budget-mode in their entirety — plain\n * `startsWith` match (dated and `-latest` variants included).\n */\nconst BUDGET_FAMILY_PREFIXES = [\n // Claude 3 / 3.5 / 3.7 legacy naming (claude-3-haiku-…, claude-3-5-sonnet-…).\n \"claude-3\",\n // Pre-3 text models: no thinking support at all, never adaptive.\n \"claude-2\",\n \"claude-instant\",\n // Haiku 4.x: Haiku 4.5 still requires budget_tokens (claude-api ref).\n \"claude-haiku-4\",\n];\n\n/**\n * Individual pre-4.7 releases in the `claude-<tier>-4-*` naming. Matched\n * as a release root: the id must equal the root or continue with a\n * separator that is not a new minor version number, so `claude-opus-4`\n * matches `claude-opus-4-20250514` but NOT `claude-opus-4-7`. Ids from the\n * installed SDK `Model` union (`messages.d.ts:795`) plus the 4.6 pair.\n */\nconst BUDGET_RELEASE_ROOTS = [\n \"claude-opus-4\",\n \"claude-opus-4-0\",\n \"claude-opus-4-1\",\n \"claude-opus-4-5\",\n \"claude-opus-4-6\",\n \"claude-sonnet-4\",\n \"claude-sonnet-4-0\",\n \"claude-sonnet-4-5\",\n \"claude-sonnet-4-6\",\n];\n\n/**\n * A remainder that starts a new minor version (`-7`, `-10`) — used to\n * stop a release root from swallowing a later release of the same line.\n * Dates (`-20250514`) and tags (`-latest`, `-v1`) are not minor versions.\n */\nconst NEXT_MINOR_VERSION = /^-\\d{1,2}(?!\\d)/;\n\nfunction matchesReleaseRoot(name: string, root: string): boolean {\n if (!name.startsWith(root)) {\n return false;\n }\n\n const rest = name.slice(root.length);\n\n if (rest === \"\") {\n return true;\n }\n\n return (rest.startsWith(\"-\") || rest.startsWith(\"@\")) && !NEXT_MINOR_VERSION.test(rest);\n}\n\n/**\n * Infer the thinking mode for a Claude model id. Budget for Haiku 4.5, the\n * 4.6 pair, and every older family; adaptive for everything else,\n * including unknown and future ids. Explicit per-model config\n * (`AnthropicModelConfig.thinkingMode`) always wins over this inference.\n *\n * @example\n * inferThinkingMode(\"claude-opus-5-5\"); // → \"adaptive\"\n * inferThinkingMode(\"claude-haiku-4-5\"); // → \"budget\"\n * inferThinkingMode(\"claude-opus-9\"); // → \"adaptive\" (unknown → current API direction)\n */\nexport function inferThinkingMode(modelName: string): AnthropicThinkingMode {\n const normalized = modelName.toLowerCase();\n\n if (BUDGET_FAMILY_PREFIXES.some((prefix) => normalized.startsWith(prefix))) {\n return \"budget\";\n }\n\n if (BUDGET_RELEASE_ROOTS.some((root) => matchesReleaseRoot(normalized, root))) {\n return \"budget\";\n }\n\n return \"adaptive\";\n}\n\n/**\n * Whether a model of this thinking mode accepts an explicit `temperature`.\n *\n * Installed SDK, `MessageCreateParamsBase.temperature`\n * (`messages.d.ts:2036-2040`): \"Models released after Claude Opus 4.6 do\n * not support setting temperature. A value of 1.0 will be accepted for\n * backwards compatibility, all other values will be rejected with a 400\n * error.\" The claude-api ref's per-model table agrees: sampling is\n * \"Removed - 400\" on Fable 5/5.1, Opus 5.5/5/4.8/4.7 and Sonnet 5, and\n * \"Non-default values - 400\" on Sonnet 5.5; \"Allowed\" on Opus 4.6,\n * Sonnet 4.6, Haiku 4.5 and older.\n *\n * That split is exactly the adaptive/budget split in the table above\n * (adaptive = released after Opus 4.6; budget = Opus 4.6 and earlier), so\n * the thinking mode doubles as the sampling-parameter classification.\n */\nexport function acceptsTemperature(mode: AnthropicThinkingMode): boolean {\n return mode === \"budget\";\n}\n\n/**\n * Model release roots that accept `thinking: { type: \"between_tools\" }`,\n * the only way to turn thinking off on them. Source: claude-api ref,\n * \"Thinking & Effort\" per-model table (cached 2026-10-06): Claude Sonnet\n * 5.5 returns a 400 on `{ type: \"disabled\" }` and takes `between_tools`\n * instead (no other field alongside it, effort `high` or below). No other\n * current model is documented to accept it. Opus 5.5 and Fable 5/5.1 have\n * no thinking-off form at all: `disabled` and `budget_tokens` are a 400 at\n * every effort, so the lowest they go is `effort: \"low\"`.\n */\nconst BETWEEN_TOOLS_RELEASE_ROOTS = [\"claude-sonnet-5-5\"];\n\n/**\n * Whether `effort: \"none\"` can turn thinking off on this model with\n * `thinking: { type: \"between_tools\" }`. Matches the release id with or\n * without a platform prefix (`anthropic.claude-sonnet-5-5` on Bedrock)\n * and with dated or tagged suffixes, but not a later minor release.\n *\n * @example\n * acceptsBetweenTools(\"claude-sonnet-5-5\"); // → true\n * acceptsBetweenTools(\"claude-opus-5-5\"); // → false\n */\nexport function acceptsBetweenTools(modelName: string): boolean {\n const normalized = modelName.toLowerCase();\n const id = normalized.slice(normalized.lastIndexOf(\".\") + 1);\n\n return BETWEEN_TOOLS_RELEASE_ROOTS.some((root) => matchesReleaseRoot(id, root));\n}\n"],"mappings":";;;;;AA4CA,MAAM,yBAAyB;CAE7B;CAEA;CACA;CAEA;AACF;;;;;;;;AASA,MAAM,uBAAuB;CAC3B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;AAOA,MAAM,qBAAqB;AAE3B,SAAS,mBAAmB,MAAc,MAAuB;CAC/D,IAAI,CAAC,KAAK,WAAW,IAAI,GACvB,OAAO;CAGT,MAAM,OAAO,KAAK,MAAM,KAAK,MAAM;CAEnC,IAAI,SAAS,IACX,OAAO;CAGT,QAAQ,KAAK,WAAW,GAAG,KAAK,KAAK,WAAW,GAAG,MAAM,CAAC,mBAAmB,KAAK,IAAI;AACxF;;;;;;;;;;;;AAaA,SAAgB,kBAAkB,WAA0C;CAC1E,MAAM,aAAa,UAAU,YAAY;CAEzC,IAAI,uBAAuB,MAAM,WAAW,WAAW,WAAW,MAAM,CAAC,GACvE,OAAO;CAGT,IAAI,qBAAqB,MAAM,SAAS,mBAAmB,YAAY,IAAI,CAAC,GAC1E,OAAO;CAGT,OAAO;AACT;;;;;;;;;;;;;;;;;AAkBA,SAAgB,mBAAmB,MAAsC;CACvE,OAAO,SAAS;AAClB;;;;;;;;;;;AAYA,MAAM,8BAA8B,CAAC,mBAAmB;;;;;;;;;;;AAYxD,SAAgB,oBAAoB,WAA4B;CAC9D,MAAM,aAAa,UAAU,YAAY;CACzC,MAAM,KAAK,WAAW,MAAM,WAAW,YAAY,GAAG,IAAI,CAAC;CAE3D,OAAO,4BAA4B,MAAM,SAAS,mBAAmB,IAAI,IAAI,CAAC;AAChF"}
|
|
1
|
+
{"version":3,"file":"thinking-mode.mjs","names":[],"sources":["../../../../../../../packages/ai-anthropic/src/thinking-mode.ts"],"sourcesContent":["/**\n * How a Claude model accepts extended thinking on the Messages API.\n *\n * - `\"adaptive\"` — `thinking: { type: \"adaptive\" }`, with depth steered by\n * `output_config.effort`. Sending `budget_tokens` to these models is a\n * 400. Installed SDK: `ThinkingConfigAdaptive`\n * (`@anthropic-ai/sdk/resources/messages/messages.d.ts:1065`) and\n * `OutputConfig.effort` (`messages.d.ts:796-800`).\n * - `\"budget\"` — the legacy `thinking: { type: \"enabled\", budget_tokens }`\n * (`ThinkingConfigEnabled`, `messages.d.ts:1078-1090`). Required on\n * Haiku 4.5 and older models.\n */\nexport type AnthropicThinkingMode = \"adaptive\" | \"budget\";\n\n/*\n * Model-family table (source: claude-api ref, \"Thinking & Effort\" per-model\n * table, cached 2026-09-25; summarised in `releases/5.26-ai-sdk-review.md` §A):\n *\n * | Model ids | Mode | `budget_tokens` | `temperature` |\n * |----------------------------------------------|------------|-------------------------|--------------------|\n * | claude-fable-5, claude-fable-5-1 (+ mythos) | adaptive | removed (400) | removed (400) |\n * | claude-opus-5-5, claude-opus-5 | adaptive | removed (400) | removed (400) |\n * | claude-opus-4-8, claude-opus-4-7 | adaptive | removed (400) | removed (400) |\n * | claude-sonnet-5-5, claude-sonnet-5 | adaptive | removed (400) | 400 (5.5: non-1.0) |\n * | claude-opus-4-6, claude-sonnet-4-6 | budget (*) | deprecated, still works | allowed |\n * | claude-haiku-4-5 and every older model | budget | required for thinking | allowed |\n * | anything not listed (future / unknown ids) | adaptive | — | — |\n *\n * (*) The 4.6 pair accepts both shapes; the claude-api ref recommends\n * adaptive there but keeps `budget_tokens` functional as a transitional\n * path. It stays on `budget` so 4.6 callers see no behaviour change (their\n * `reasoning.maxTokens` is still honoured as a hard budget) and so that\n * the `budget` set is exactly the set that still accepts `temperature`\n * (see `acceptsTemperature`). Opt 4.6 into adaptive with\n * `anthropic.model({ name, thinkingMode: \"adaptive\" })`.\n *\n * Unknown ids default to adaptive because that is the current API\n * direction: every model released after Opus 4.6 rejects `budget_tokens`.\n */\n\n/**\n * Family prefixes that are budget-mode in their entirety — plain\n * `startsWith` match (dated and `-latest` variants included).\n */\nconst BUDGET_FAMILY_PREFIXES = [\n // Claude 3 / 3.5 / 3.7 legacy naming (claude-3-haiku-…, claude-3-5-sonnet-…).\n \"claude-3\",\n // Pre-3 text models: no thinking support at all, never adaptive.\n \"claude-2\",\n \"claude-instant\",\n // Haiku 4.x: Haiku 4.5 still requires budget_tokens (claude-api ref).\n \"claude-haiku-4\",\n];\n\n/**\n * Individual pre-4.7 releases in the `claude-<tier>-4-*` naming. Matched\n * as a release root: the id must equal the root or continue with a\n * separator that is not a new minor version number, so `claude-opus-4`\n * matches `claude-opus-4-20250514` but NOT `claude-opus-4-7`. Ids from the\n * installed SDK `Model` union (`messages.d.ts:795`) plus the 4.6 pair.\n */\nconst BUDGET_RELEASE_ROOTS = [\n \"claude-opus-4\",\n \"claude-opus-4-0\",\n \"claude-opus-4-1\",\n \"claude-opus-4-5\",\n \"claude-opus-4-6\",\n \"claude-sonnet-4\",\n \"claude-sonnet-4-0\",\n \"claude-sonnet-4-5\",\n \"claude-sonnet-4-6\",\n];\n\n/**\n * A remainder that starts a new minor version (`-7`, `-10`) — used to\n * stop a release root from swallowing a later release of the same line.\n * Dates (`-20250514`) and tags (`-latest`, `-v1`) are not minor versions.\n */\nconst NEXT_MINOR_VERSION = /^-\\d{1,2}(?!\\d)/;\n\n/**\n * Whether a lower-cased model id is the release `root` itself, or a dated /\n * tagged / `@` snapshot of it — but not a later minor version of the same\n * line (`claude-opus-4` matches `claude-opus-4-20250514`, not `claude-opus-4-7`).\n */\nexport function matchesReleaseRoot(name: string, root: string): boolean {\n if (!name.startsWith(root)) {\n return false;\n }\n\n const rest = name.slice(root.length);\n\n if (rest === \"\") {\n return true;\n }\n\n return (rest.startsWith(\"-\") || rest.startsWith(\"@\")) && !NEXT_MINOR_VERSION.test(rest);\n}\n\n/**\n * Infer the thinking mode for a Claude model id. Budget for Haiku 4.5, the\n * 4.6 pair, and every older family; adaptive for everything else,\n * including unknown and future ids. Explicit per-model config\n * (`AnthropicModelConfig.thinkingMode`) always wins over this inference.\n *\n * @example\n * inferThinkingMode(\"claude-opus-5-5\"); // → \"adaptive\"\n * inferThinkingMode(\"claude-haiku-4-5\"); // → \"budget\"\n * inferThinkingMode(\"claude-opus-9\"); // → \"adaptive\" (unknown → current API direction)\n */\nexport function inferThinkingMode(modelName: string): AnthropicThinkingMode {\n const normalized = modelName.toLowerCase();\n\n if (BUDGET_FAMILY_PREFIXES.some((prefix) => normalized.startsWith(prefix))) {\n return \"budget\";\n }\n\n if (BUDGET_RELEASE_ROOTS.some((root) => matchesReleaseRoot(normalized, root))) {\n return \"budget\";\n }\n\n return \"adaptive\";\n}\n\n/**\n * Whether a model of this thinking mode accepts an explicit `temperature`.\n *\n * Installed SDK, `MessageCreateParamsBase.temperature`\n * (`messages.d.ts:2036-2040`): \"Models released after Claude Opus 4.6 do\n * not support setting temperature. A value of 1.0 will be accepted for\n * backwards compatibility, all other values will be rejected with a 400\n * error.\" The claude-api ref's per-model table agrees: sampling is\n * \"Removed - 400\" on Fable 5/5.1, Opus 5.5/5/4.8/4.7 and Sonnet 5, and\n * \"Non-default values - 400\" on Sonnet 5.5; \"Allowed\" on Opus 4.6,\n * Sonnet 4.6, Haiku 4.5 and older.\n *\n * That split is exactly the adaptive/budget split in the table above\n * (adaptive = released after Opus 4.6; budget = Opus 4.6 and earlier), so\n * the thinking mode doubles as the sampling-parameter classification.\n */\nexport function acceptsTemperature(mode: AnthropicThinkingMode): boolean {\n return mode === \"budget\";\n}\n\n/**\n * Model release roots that accept `thinking: { type: \"between_tools\" }`,\n * the only way to turn thinking off on them. Source: claude-api ref,\n * \"Thinking & Effort\" per-model table (cached 2026-10-06): Claude Sonnet\n * 5.5 returns a 400 on `{ type: \"disabled\" }` and takes `between_tools`\n * instead (no other field alongside it, effort `high` or below). No other\n * current model is documented to accept it. Opus 5.5 and Fable 5/5.1 have\n * no thinking-off form at all: `disabled` and `budget_tokens` are a 400 at\n * every effort, so the lowest they go is `effort: \"low\"`.\n */\nconst BETWEEN_TOOLS_RELEASE_ROOTS = [\"claude-sonnet-5-5\"];\n\n/**\n * Whether `effort: \"none\"` can turn thinking off on this model with\n * `thinking: { type: \"between_tools\" }`. Matches the release id with or\n * without a platform prefix (`anthropic.claude-sonnet-5-5` on Bedrock)\n * and with dated or tagged suffixes, but not a later minor release.\n *\n * @example\n * acceptsBetweenTools(\"claude-sonnet-5-5\"); // → true\n * acceptsBetweenTools(\"claude-opus-5-5\"); // → false\n */\nexport function acceptsBetweenTools(modelName: string): boolean {\n return matchesAnyRelease(modelName, BETWEEN_TOOLS_RELEASE_ROOTS);\n}\n\n/**\n * Whether the model id — lower-cased, with any platform prefix\n * (`anthropic.`, `us.anthropic.` on Bedrock) removed — is one of these\n * releases, dated or tagged, but not a later minor release.\n */\nfunction matchesAnyRelease(modelName: string, roots: readonly string[]): boolean {\n const normalized = modelName.toLowerCase();\n const id = normalized.slice(normalized.lastIndexOf(\".\") + 1);\n\n return roots.some((root) => matchesReleaseRoot(id, root));\n}\n\n/**\n * How a model is asked to run without reasoning when the caller passes the\n * neutral `reasoning: { effort: \"none\" }`.\n *\n * - `\"between_tools\"` — send `thinking: { type: \"between_tools\" }` alone.\n * - `\"disabled\"` — send `thinking: { type: \"disabled\" }` with no effort.\n * - `\"lowest-effort\"` — keep adaptive thinking on and send the lowest\n * `output_config.effort` (`\"low\"`).\n * - `\"omit\"` — send no `thinking` field at all.\n */\nexport type AnthropicNoReasoningForm = \"between_tools\" | \"disabled\" | \"lowest-effort\" | \"omit\";\n\n/**\n * Releases that accept `thinking: { type: \"disabled\" }` and run reliably\n * with it. Source: claude-api ref, \"Thinking & Effort\" per-model table\n * (cached 2026-10-06): Claude Sonnet 5 accepts `disabled`; Claude Haiku 5.5\n * accepts it at effort `low`, `medium` and `high` (a 400 at `xhigh` /\n * `max`). No effort is sent alongside it, so Haiku 5.5 runs at its default,\n * `medium`, which is inside the accepted range.\n */\nconst DISABLED_THINKING_RELEASE_ROOTS = [\"claude-sonnet-5\", \"claude-haiku-5-5\"];\n\n/**\n * Releases that accept `disabled` but are kept on adaptive thinking at the\n * lowest effort instead. Claude Opus 5 accepts `disabled` at effort `high`\n * or below, but the claude-api ref (\"Two failure modes when thinking is\n * disabled\", cached 2026-10-06) documents that with thinking disabled it\n * occasionally writes a tool call into its visible text instead of a\n * `tool_use` block — the call never runs and no error is raised — and can\n * leak `<thinking>` tags into the response. The ref's primary\n * recommendation is to keep thinking on and lower `effort`, so the adapter\n * does exactly that.\n */\nconst LOWEST_EFFORT_RELEASE_ROOTS = [\"claude-opus-5\"];\n\n/**\n * The wire form for `reasoning: { effort: \"none\" }` on this model:\n *\n * | Model | Form |\n * |----------------------------------------|-------------------|\n * | Claude Sonnet 5.5 | `between_tools` |\n * | Claude Sonnet 5, Claude Haiku 5.5 | `disabled` |\n * | Claude Opus 5 | `lowest-effort` |\n * | Opus 5.5, Fable 5/5.1, everything else | `omit` |\n *\n * Opus 5.5 and Fable 5/5.1 have no thinking-off form (`disabled` and\n * `budget_tokens` are a 400 at every effort), so nothing is sent and the\n * model runs at its default effort; older models run without thinking when\n * the field is absent.\n *\n * @example\n * noReasoningForm(\"claude-sonnet-5\"); // → \"disabled\"\n * noReasoningForm(\"claude-opus-5\"); // → \"lowest-effort\"\n * noReasoningForm(\"claude-opus-5-5\"); // → \"omit\"\n */\nexport function noReasoningForm(modelName: string): AnthropicNoReasoningForm {\n if (acceptsBetweenTools(modelName)) {\n return \"between_tools\";\n }\n\n if (matchesAnyRelease(modelName, DISABLED_THINKING_RELEASE_ROOTS)) {\n return \"disabled\";\n }\n\n if (matchesAnyRelease(modelName, LOWEST_EFFORT_RELEASE_ROOTS)) {\n return \"lowest-effort\";\n }\n\n return \"omit\";\n}\n\n/*\n * Preserved thinking (Anthropic docs, \"Thinking\" → \"Preserved thinking\" and\n * the \"Preserved thinking\" page, read 2026-10-17): the API checks that the\n * `system` prompt, `tools` and every message before a replayed thinking\n * block are unchanged since the block was produced, on Claude Fable 5.1,\n * Claude Opus 5.5, Claude Sonnet 5.5 and Claude Haiku 5.5. Claude Mythos 5.1\n * and every model released before Claude Fable 5.1 don't run that check, so\n * a thinking block kept after a client-written summary stays valid there.\n */\nconst PREFIX_CHECK_RELEASE_ROOTS = [\n \"claude-fable-5-1\",\n \"claude-opus-5-5\",\n \"claude-sonnet-5-5\",\n \"claude-haiku-5-5\",\n];\n\n/** Releases documented not to run the conversation check. */\nconst NO_PREFIX_CHECK_RELEASE_ROOTS = [\n \"claude-mythos-5-1\",\n \"claude-mythos-5\",\n \"claude-mythos-preview\",\n \"claude-fable-5\",\n \"claude-opus-5\",\n \"claude-sonnet-5\",\n];\n\n/** Families released before Claude Fable 5.1 in their entirety. */\nconst NO_PREFIX_CHECK_FAMILY_PREFIXES = [\n ...BUDGET_FAMILY_PREFIXES,\n \"claude-opus-4\",\n \"claude-sonnet-4\",\n];\n\n/**\n * Whether this model binds a replayed thinking block to the exact\n * conversation before it (preserved thinking). Unknown and future ids are\n * assumed to run the check — the safe direction: reasoning a kept turn\n * can't use is left out instead of risking a 400. Matches the id with or\n * without a platform prefix and with dated or tagged suffixes.\n *\n * @example\n * inferPreservedThinking(\"claude-opus-5-5\"); // → true\n * inferPreservedThinking(\"claude-opus-5\"); // → false\n * inferPreservedThinking(\"claude-opus-4-8\"); // → false\n */\nexport function inferPreservedThinking(modelName: string): boolean {\n const normalized = modelName.toLowerCase();\n const id = normalized.slice(normalized.lastIndexOf(\".\") + 1);\n\n if (PREFIX_CHECK_RELEASE_ROOTS.some((root) => matchesReleaseRoot(id, root))) {\n return true;\n }\n\n if (\n NO_PREFIX_CHECK_RELEASE_ROOTS.some((root) => matchesReleaseRoot(id, root)) ||\n NO_PREFIX_CHECK_FAMILY_PREFIXES.some((prefix) => id.startsWith(prefix))\n ) {\n return false;\n }\n\n return true;\n}\n"],"mappings":";;;;;AA4CA,MAAM,yBAAyB;CAE7B;CAEA;CACA;CAEA;AACF;;;;;;;;AASA,MAAM,uBAAuB;CAC3B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;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AACT;AAWA,MAAM,6BAA6B;CACjC;CACA;CACA;CACA;AACF;;AAGA,MAAM,gCAAgC;CACpC;CACA;CACA;CACA;CACA;CACA;AACF;;AAGA,MAAM,kCAAkC;CACtC,GAAG;CACH;CACA;AACF;;;;;;;;;;;;;AAcA,SAAgB,uBAAuB,WAA4B;CACjE,MAAM,aAAa,UAAU,YAAY;CACzC,MAAM,KAAK,WAAW,MAAM,WAAW,YAAY,GAAG,IAAI,CAAC;CAE3D,IAAI,2BAA2B,MAAM,SAAS,mBAAmB,IAAI,IAAI,CAAC,GACxE,OAAO;CAGT,IACE,8BAA8B,MAAM,SAAS,mBAAmB,IAAI,IAAI,CAAC,KACzE,gCAAgC,MAAM,WAAW,GAAG,WAAW,MAAM,CAAC,GAEtE,OAAO;CAGT,OAAO;AACT"}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
//#region ../../packages/ai-anthropic/src/utils/cache-usage.ts
|
|
2
|
+
/**
|
|
3
|
+
* Copy Anthropic's cache counters onto a neutral `Usage`.
|
|
4
|
+
*
|
|
5
|
+
* - `cache_read_input_tokens` → `cachedTokens`
|
|
6
|
+
* - `cache_creation_input_tokens` → `cacheWriteTokens`
|
|
7
|
+
* - `cache_creation.ephemeral_1h_input_tokens` → `cacheWrite1hTokens`
|
|
8
|
+
* (the 1-hour writes, billed at 2x input instead of 1.25x)
|
|
9
|
+
*
|
|
10
|
+
* When Anthropic omits the per-lifetime breakdown, `requestTtl` decides:
|
|
11
|
+
* a request whose every cache marker asked for `"1h"` wrote only 1-hour
|
|
12
|
+
* entries. Counters are set only when positive, so an absent channel
|
|
13
|
+
* stays undefined. Anthropic's `input_tokens` excludes all of these, so
|
|
14
|
+
* the caller marks the usage `inputIncludesCache: false`.
|
|
15
|
+
*/
|
|
16
|
+
function applyAnthropicCacheUsage(usage, raw, requestTtl) {
|
|
17
|
+
const cacheRead = raw.cache_read_input_tokens;
|
|
18
|
+
if (typeof cacheRead === "number" && cacheRead > 0) usage.cachedTokens = cacheRead;
|
|
19
|
+
const cacheWrite = raw.cache_creation_input_tokens;
|
|
20
|
+
if (typeof cacheWrite !== "number" || cacheWrite <= 0) return;
|
|
21
|
+
usage.cacheWriteTokens = cacheWrite;
|
|
22
|
+
const reported1h = raw.cache_creation?.ephemeral_1h_input_tokens;
|
|
23
|
+
const writes1h = typeof reported1h === "number" ? reported1h : requestTtl === "1h" ? cacheWrite : 0;
|
|
24
|
+
if (writes1h > 0) usage.cacheWrite1hTokens = Math.min(writes1h, cacheWrite);
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Scan a request body (top level, system, tools, messages) for
|
|
28
|
+
* `cache_control` markers and report the lifetime they request. Used only
|
|
29
|
+
* as a fallback when the response lacks Anthropic's per-lifetime
|
|
30
|
+
* cache-write breakdown.
|
|
31
|
+
*
|
|
32
|
+
* @example
|
|
33
|
+
* requestCacheTtl({ cache_control: { type: "ephemeral", ttl: "1h" } }); // "1h"
|
|
34
|
+
*/
|
|
35
|
+
function requestCacheTtl(body) {
|
|
36
|
+
let found;
|
|
37
|
+
const visit = (value, depth) => {
|
|
38
|
+
if (depth > 8 || typeof value !== "object" || value === null) return;
|
|
39
|
+
if (Array.isArray(value)) {
|
|
40
|
+
for (const item of value) visit(item, depth + 1);
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
const record = value;
|
|
44
|
+
const marker = record.cache_control;
|
|
45
|
+
if (typeof marker === "object" && marker !== null) {
|
|
46
|
+
const ttl = marker.ttl === "1h" ? "1h" : "5m";
|
|
47
|
+
found = found === void 0 || found === ttl ? ttl : "mixed";
|
|
48
|
+
}
|
|
49
|
+
for (const key of [
|
|
50
|
+
"system",
|
|
51
|
+
"tools",
|
|
52
|
+
"messages",
|
|
53
|
+
"content"
|
|
54
|
+
]) if (key in record) visit(record[key], depth + 1);
|
|
55
|
+
};
|
|
56
|
+
visit(body, 0);
|
|
57
|
+
return found;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
//#endregion
|
|
61
|
+
export { applyAnthropicCacheUsage, requestCacheTtl };
|
|
62
|
+
//# sourceMappingURL=cache-usage.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cache-usage.mjs","names":[],"sources":["../../../../../../../../packages/ai-anthropic/src/utils/cache-usage.ts"],"sourcesContent":["import type { Usage } from \"@warlock.js/ai\";\n\n/** The cache-related fields of an Anthropic usage block (final or streamed). */\nexport type AnthropicCacheUsage = {\n cache_read_input_tokens?: number | null;\n cache_creation_input_tokens?: number | null;\n cache_creation?: {\n ephemeral_1h_input_tokens?: number | null;\n ephemeral_5m_input_tokens?: number | null;\n } | null;\n};\n\n/**\n * Copy Anthropic's cache counters onto a neutral `Usage`.\n *\n * - `cache_read_input_tokens` → `cachedTokens`\n * - `cache_creation_input_tokens` → `cacheWriteTokens`\n * - `cache_creation.ephemeral_1h_input_tokens` → `cacheWrite1hTokens`\n * (the 1-hour writes, billed at 2x input instead of 1.25x)\n *\n * When Anthropic omits the per-lifetime breakdown, `requestTtl` decides:\n * a request whose every cache marker asked for `\"1h\"` wrote only 1-hour\n * entries. Counters are set only when positive, so an absent channel\n * stays undefined. Anthropic's `input_tokens` excludes all of these, so\n * the caller marks the usage `inputIncludesCache: false`.\n */\nexport function applyAnthropicCacheUsage(\n usage: Usage,\n raw: AnthropicCacheUsage,\n requestTtl: RequestCacheTtl,\n): void {\n const cacheRead = raw.cache_read_input_tokens;\n\n if (typeof cacheRead === \"number\" && cacheRead > 0) {\n usage.cachedTokens = cacheRead;\n }\n\n const cacheWrite = raw.cache_creation_input_tokens;\n\n if (typeof cacheWrite !== \"number\" || cacheWrite <= 0) {\n return;\n }\n\n usage.cacheWriteTokens = cacheWrite;\n\n const reported1h = raw.cache_creation?.ephemeral_1h_input_tokens;\n const writes1h =\n typeof reported1h === \"number\" ? reported1h : requestTtl === \"1h\" ? cacheWrite : 0;\n\n if (writes1h > 0) {\n usage.cacheWrite1hTokens = Math.min(writes1h, cacheWrite);\n }\n}\n\n/**\n * The cache lifetime a request body asked for: `\"1h\"` when every\n * `cache_control` marker in it says `ttl: \"1h\"`, `\"5m\"` when every marker\n * uses the default lifetime, `\"mixed\"` when both appear, and `undefined`\n * when the body carries no marker.\n */\nexport type RequestCacheTtl = \"1h\" | \"5m\" | \"mixed\" | undefined;\n\n/**\n * Scan a request body (top level, system, tools, messages) for\n * `cache_control` markers and report the lifetime they request. Used only\n * as a fallback when the response lacks Anthropic's per-lifetime\n * cache-write breakdown.\n *\n * @example\n * requestCacheTtl({ cache_control: { type: \"ephemeral\", ttl: \"1h\" } }); // \"1h\"\n */\nexport function requestCacheTtl(body: unknown): RequestCacheTtl {\n let found: RequestCacheTtl;\n\n const visit = (value: unknown, depth: number): void => {\n if (depth > 8 || typeof value !== \"object\" || value === null) {\n return;\n }\n\n if (Array.isArray(value)) {\n for (const item of value) {\n visit(item, depth + 1);\n }\n\n return;\n }\n\n const record = value as Record<string, unknown>;\n const marker = record.cache_control;\n\n if (typeof marker === \"object\" && marker !== null) {\n const ttl = (marker as { ttl?: unknown }).ttl === \"1h\" ? \"1h\" : \"5m\";\n found = found === undefined || found === ttl ? ttl : \"mixed\";\n }\n\n for (const key of [\"system\", \"tools\", \"messages\", \"content\"] as const) {\n if (key in record) {\n visit(record[key], depth + 1);\n }\n }\n };\n\n visit(body, 0);\n\n return found;\n}\n"],"mappings":";;;;;;;;;;;;;;;AA0BA,SAAgB,yBACd,OACA,KACA,YACM;CACN,MAAM,YAAY,IAAI;CAEtB,IAAI,OAAO,cAAc,YAAY,YAAY,GAC/C,MAAM,eAAe;CAGvB,MAAM,aAAa,IAAI;CAEvB,IAAI,OAAO,eAAe,YAAY,cAAc,GAClD;CAGF,MAAM,mBAAmB;CAEzB,MAAM,aAAa,IAAI,gBAAgB;CACvC,MAAM,WACJ,OAAO,eAAe,WAAW,aAAa,eAAe,OAAO,aAAa;CAEnF,IAAI,WAAW,GACb,MAAM,qBAAqB,KAAK,IAAI,UAAU,UAAU;AAE5D;;;;;;;;;;AAmBA,SAAgB,gBAAgB,MAAgC;CAC9D,IAAI;CAEJ,MAAM,SAAS,OAAgB,UAAwB;EACrD,IAAI,QAAQ,KAAK,OAAO,UAAU,YAAY,UAAU,MACtD;EAGF,IAAI,MAAM,QAAQ,KAAK,GAAG;GACxB,KAAK,MAAM,QAAQ,OACjB,MAAM,MAAM,QAAQ,CAAC;GAGvB;EACF;EAEA,MAAM,SAAS;EACf,MAAM,SAAS,OAAO;EAEtB,IAAI,OAAO,WAAW,YAAY,WAAW,MAAM;GACjD,MAAM,MAAO,OAA6B,QAAQ,OAAO,OAAO;GAChE,QAAQ,UAAU,UAAa,UAAU,MAAM,MAAM;EACvD;EAEA,KAAK,MAAM,OAAO;GAAC;GAAU;GAAS;GAAY;EAAS,GACzD,IAAI,OAAO,QACT,MAAM,OAAO,MAAM,QAAQ,CAAC;CAGlC;CAEA,MAAM,MAAM,CAAC;CAEb,OAAO;AACT"}
|