@warlock.js/ai-anthropic 5.29.0 → 5.30.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 +25 -0
- package/cjs/index.cjs +346 -52
- package/cjs/index.cjs.map +1 -1
- package/esm/config.type.d.mts +67 -3
- package/esm/config.type.d.mts.map +1 -1
- package/esm/index.d.mts +3 -2
- package/esm/index.mjs +2 -1
- package/esm/known-vision-models.mjs +1 -1
- package/esm/known-vision-models.mjs.map +1 -1
- package/esm/model.d.mts +250 -0
- package/esm/model.d.mts.map +1 -0
- package/esm/model.mjs +175 -22
- package/esm/model.mjs.map +1 -1
- package/esm/sdk.d.mts +7 -6
- package/esm/sdk.d.mts.map +1 -1
- package/esm/sdk.mjs +4 -4
- package/esm/sdk.mjs.map +1 -1
- package/esm/thinking-mode.d.mts +1 -1
- package/esm/thinking-mode.d.mts.map +1 -1
- package/esm/thinking-mode.mjs +28 -2
- package/esm/thinking-mode.mjs.map +1 -1
- package/esm/utils/index.mjs +1 -0
- package/esm/utils/map-stop-reason.mjs +17 -13
- package/esm/utils/map-stop-reason.mjs.map +1 -1
- package/esm/utils/provider-blocks.mjs +83 -0
- package/esm/utils/provider-blocks.mjs.map +1 -0
- package/esm/utils/to-anthropic-messages.mjs +43 -11
- package/esm/utils/to-anthropic-messages.mjs.map +1 -1
- package/esm/utils/to-anthropic-tools.mjs +1 -1
- package/esm/utils/to-anthropic-tools.mjs.map +1 -1
- package/esm/utils/wrap-anthropic-error.mjs +1 -1
- package/esm/utils/wrap-anthropic-error.mjs.map +1 -1
- package/llms-full.txt +70 -6
- package/llms.txt +1 -1
- package/package.json +5 -4
- package/skills/setup-anthropic/SKILL.md +70 -6
package/esm/model.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"model.mjs","names":[],"sources":["../../../../../../ai-anthropic/src/model.ts"],"sourcesContent":["import {\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 { AnthropicModelConfig } from \"./config.type\";\nimport { inferVisionCapability } from \"./known-vision-models\";\nimport { acceptsTemperature, inferThinkingMode, type AnthropicThinkingMode } from \"./thinking-mode\";\nimport { mapStopReason, toAnthropicMessages, toAnthropicTools, wrapAnthropicError } 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 * 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.client.messages.create(\n { ...this.buildParams(messages, options), stream: false },\n options?.signal ? { signal: options.signal } : undefined,\n );\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\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 };\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: Awaited<ReturnType<Anthropic[\"messages\"][\"create\"]>>;\n\n try {\n stream = await this.client.messages.create(\n { ...this.buildParams(messages, options), stream: true },\n options?.signal ? { signal: options.signal } : undefined,\n );\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\n try {\n for await (const event of stream as AsyncIterable<Anthropic.RawMessageStreamEvent>) {\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\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 };\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),\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: [{ type: \"text\", text: system, cache_control: this.cacheControl() }],\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() }\n : {};\n }\n\n /** Build a typed cache-control marker, omitting TTL for Anthropic's 5-minute default. */\n private cacheControl(): Anthropic.CacheControlEphemeral {\n return {\n type: \"ephemeral\",\n ...(this.config.promptCacheTtl ? { ttl: this.config.promptCacheTtl } : {}),\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\") maps to no\n * `thinking` field at all in both modes.\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\". Anthropic\n // has no reasoning-off effort knob — extended thinking is opt-in — so\n // we simply omit the `thinking` block. (This also short-circuits the\n // `EFFORT_THINKING_BUDGET[\"none\"]` → `undefined` → `NaN` budget path.)\n if (reasoning.effort === \"none\") {\n return {};\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(tools: ModelCallOptions[\"tools\"]): { 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() };\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"],"mappings":";;;;;;;;;;;AAoBA,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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,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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AC;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"}
|
|
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,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,WAAW,GAC5B,OAAO,CAAC;EAGV,OAAO,EAAE,kBAAkB,EAAE,WAAW,EAAE,eAAe,EAAE,EAAE;CAC/D;;;;;;;;;;;CAYA,AAAQ,aAAa,KAA6B;EAChD,MAAM,QAAQ,IAAI,gBAAgB;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"}
|
package/esm/sdk.d.mts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { AnthropicModelConfig, AnthropicSDKConfig } from "./config.type.mjs";
|
|
2
|
-
import {
|
|
2
|
+
import { AnthropicModel } from "./model.mjs";
|
|
3
|
+
import { SDKAdapterContract } from "@warlock.js/ai";
|
|
3
4
|
|
|
4
|
-
//#region
|
|
5
|
+
//#region ../../packages/ai-anthropic/src/sdk.d.ts
|
|
5
6
|
/**
|
|
6
7
|
* Anthropic-backed implementation of `SDKAdapterContract`.
|
|
7
8
|
*
|
|
@@ -53,14 +54,14 @@ declare class AnthropicSDK implements SDKAdapterContract {
|
|
|
53
54
|
* SDK-level registry entry keyed by `config.name`; otherwise
|
|
54
55
|
* `undefined` (no cost computed).
|
|
55
56
|
*/
|
|
56
|
-
model(config: AnthropicModelConfig):
|
|
57
|
+
model(config: AnthropicModelConfig): AnthropicModel;
|
|
57
58
|
/**
|
|
58
59
|
* Rough token-count estimate for a given text. Uses the
|
|
59
60
|
* character-heuristic (`approximateTokenCount`) from the core package
|
|
60
61
|
* — good enough for budgeting and quota guards, not for billing.
|
|
61
|
-
*
|
|
62
|
-
*
|
|
63
|
-
* synchronous-cost. The optional model id is reserved for future
|
|
62
|
+
* For an exact count use `AnthropicModel.countTokens()`, which calls
|
|
63
|
+
* Anthropic's `messages.countTokens` endpoint (a network round-trip);
|
|
64
|
+
* `count()` is intentionally offline and synchronous-cost. The optional model id is reserved for future
|
|
64
65
|
* per-model tokenizer dispatch; currently ignored.
|
|
65
66
|
*/
|
|
66
67
|
count(text: string, _model?: string): Promise<number>;
|
package/esm/sdk.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sdk.d.mts","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"sdk.d.mts","names":[],"sources":["../../../../../../../packages/ai-anthropic/src/sdk.ts"],"mappings":";;;;;;;AAwCA;;;;;;;;;;;;;;;;;;;;;;;;;;AA8C4D;;;;;;cA9C/C,YAAA,YAAwB,kBAAA;EAAA,iBAClB,MAAA;EAAA,iBACA,QAAA;EAAA,iBACA,OAAA;cAEE,MAAA,EAAQ,kBAAA;;;;;;;;;;;;;EAwBpB,KAAA,CAAM,MAAA,EAAQ,oBAAA,GAAuB,cAAA;;;;;;;;;;EAiB/B,KAAA,CAAM,IAAA,UAAc,MAAA,YAAkB,OAAA;AAAA"}
|
package/esm/sdk.mjs
CHANGED
|
@@ -2,7 +2,7 @@ import { AnthropicModel } from "./model.mjs";
|
|
|
2
2
|
import Anthropic from "@anthropic-ai/sdk";
|
|
3
3
|
import { approximateTokenCount } from "@warlock.js/ai";
|
|
4
4
|
|
|
5
|
-
//#region
|
|
5
|
+
//#region ../../packages/ai-anthropic/src/sdk.ts
|
|
6
6
|
/**
|
|
7
7
|
* Anthropic-backed implementation of `SDKAdapterContract`.
|
|
8
8
|
*
|
|
@@ -68,9 +68,9 @@ var AnthropicSDK = class {
|
|
|
68
68
|
* Rough token-count estimate for a given text. Uses the
|
|
69
69
|
* character-heuristic (`approximateTokenCount`) from the core package
|
|
70
70
|
* — good enough for budgeting and quota guards, not for billing.
|
|
71
|
-
*
|
|
72
|
-
*
|
|
73
|
-
* synchronous-cost. The optional model id is reserved for future
|
|
71
|
+
* For an exact count use `AnthropicModel.countTokens()`, which calls
|
|
72
|
+
* Anthropic's `messages.countTokens` endpoint (a network round-trip);
|
|
73
|
+
* `count()` is intentionally offline and synchronous-cost. The optional model id is reserved for future
|
|
74
74
|
* per-model tokenizer dispatch; currently ignored.
|
|
75
75
|
*/
|
|
76
76
|
async count(text, _model) {
|
package/esm/sdk.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sdk.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"sdk.mjs","names":[],"sources":["../../../../../../../packages/ai-anthropic/src/sdk.ts"],"sourcesContent":["import Anthropic from \"@anthropic-ai/sdk\";\nimport type { ModelPricing, SDKAdapterContract } from \"@warlock.js/ai\";\nimport { approximateTokenCount } from \"@warlock.js/ai\";\nimport type { AnthropicModelConfig, AnthropicSDKConfig } from \"./config.type\";\nimport { AnthropicModel } from \"./model\";\n\n/**\n * Anthropic-backed implementation of `SDKAdapterContract`.\n *\n * **Role.** The package entry point for Claude models via the official\n * `@anthropic-ai/sdk`. A single `AnthropicSDK` instance holds one live\n * `Anthropic` client, shared by every `ModelContract` it produces via\n * `model()`. Users construct one SDK per account and reuse it across\n * all agents, workflows, and supervisors that target Anthropic.\n *\n * **Responsibility.**\n * - Owns: a long-lived `Anthropic` client (authentication, base URL)\n * and its lifetime scope. Factory for `AnthropicModel` instances —\n * each model call gets a reference to the same client.\n * - Does NOT own: anything per-call (tool execution, message history,\n * streaming loop) — those live in `AnthropicModel` and the agent\n * runtime. Does NOT implement `embedder()`: Anthropic ships no\n * first-party embeddings API (the contract marks it optional).\n *\n * Modeled as a class (see §4.2 of code-style.md — \"long-lived state\n * across many calls\"): the `Anthropic` client is heavy to construct\n * and designed to be reused; keeping it on `this` makes that reuse\n * explicit and aligns with the `new Anthropic(...)` upstream\n * convention.\n *\n * @example\n * const anthropic = new AnthropicSDK({ apiKey: process.env.ANTHROPIC_API_KEY! });\n * const model = anthropic.model({ name: \"claude-sonnet-4-6\", temperature: 0.7 });\n * const tokens = await anthropic.count(\"Hello world\");\n *\n * @example\n * // Compose into an `ai.anthropic` namespace for ergonomic agent wiring\n * const ai = { agent, tool, systemPrompt, anthropic: new AnthropicSDK({ apiKey }) };\n * const myAgent = ai.agent({ model: ai.anthropic.model({ name: \"claude-haiku-4-5\" }) });\n */\nexport class AnthropicSDK implements SDKAdapterContract {\n private readonly client: Anthropic;\n private readonly provider: string;\n private readonly pricing?: Record<string, ModelPricing>;\n\n public constructor(config: AnthropicSDKConfig) {\n // Peel off the framework-only keys and forward every other upstream\n // `ClientOptions` (timeout, maxRetries, defaultHeaders, fetch, …) verbatim\n // — they type-check, so dropping them is a silent footgun. Mirrors the\n // Bedrock/Google/Ollama adapters.\n const { provider, pricing, ...clientOptions } = config;\n\n this.client = new Anthropic(clientOptions);\n this.provider = provider ?? \"anthropic\";\n this.pricing = pricing;\n }\n\n /**\n * Build an `AnthropicModel` bound to this SDK's client. Each call\n * returns a fresh model instance, but all instances share the\n * underlying `Anthropic` client — connection pools, rate limits, and\n * authentication stay unified across every model produced here. The\n * SDK's `provider` label is forwarded so every model self-identifies\n * as coming from the same upstream.\n *\n * Pricing resolution: per-model `config.pricing` wins; otherwise the\n * SDK-level registry entry keyed by `config.name`; otherwise\n * `undefined` (no cost computed).\n */\n public model(config: AnthropicModelConfig): AnthropicModel {\n const resolvedPricing = config.pricing ?? this.pricing?.[config.name];\n const resolvedConfig: AnthropicModelConfig =\n resolvedPricing === config.pricing ? config : { ...config, pricing: resolvedPricing };\n\n return new AnthropicModel(this.client, resolvedConfig, this.provider);\n }\n\n /**\n * Rough token-count estimate for a given text. Uses the\n * character-heuristic (`approximateTokenCount`) from the core package\n * — good enough for budgeting and quota guards, not for billing.\n * For an exact count use `AnthropicModel.countTokens()`, which calls\n * Anthropic's `messages.countTokens` endpoint (a network round-trip);\n * `count()` is intentionally offline and synchronous-cost. The optional model id is reserved for future\n * per-model tokenizer dispatch; currently ignored.\n */\n public async count(text: string, _model?: string): Promise<number> {\n return approximateTokenCount(text);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,IAAa,eAAb,MAAwD;CAKtD,AAAO,YAAY,QAA4B;EAK7C,MAAM,EAAE,UAAU,SAAS,GAAG,kBAAkB;EAEhD,KAAK,SAAS,IAAI,UAAU,aAAa;EACzC,KAAK,WAAW,YAAY;EAC5B,KAAK,UAAU;CACjB;;;;;;;;;;;;;CAcA,AAAO,MAAM,QAA8C;EACzD,MAAM,kBAAkB,OAAO,WAAW,KAAK,UAAU,OAAO;EAChE,MAAM,iBACJ,oBAAoB,OAAO,UAAU,SAAS;GAAE,GAAG;GAAQ,SAAS;EAAgB;EAEtF,OAAO,IAAI,eAAe,KAAK,QAAQ,gBAAgB,KAAK,QAAQ;CACtE;;;;;;;;;;CAWA,MAAa,MAAM,MAAc,QAAkC;EACjE,OAAO,sBAAsB,IAAI;CACnC;AACF"}
|
package/esm/thinking-mode.d.mts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"thinking-mode.d.mts","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"thinking-mode.d.mts","names":[],"sources":["../../../../../../../packages/ai-anthropic/src/thinking-mode.ts"],"mappings":";;AAYA;;;;AAAiC;;;;;;;KAArB,qBAAA"}
|
package/esm/thinking-mode.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//#region
|
|
1
|
+
//#region ../../packages/ai-anthropic/src/thinking-mode.ts
|
|
2
2
|
/**
|
|
3
3
|
* Family prefixes that are budget-mode in their entirety — plain
|
|
4
4
|
* `startsWith` match (dated and `-latest` variants included).
|
|
@@ -75,7 +75,33 @@ function inferThinkingMode(modelName) {
|
|
|
75
75
|
function acceptsTemperature(mode) {
|
|
76
76
|
return mode === "budget";
|
|
77
77
|
}
|
|
78
|
+
/**
|
|
79
|
+
* Model release roots that accept `thinking: { type: "between_tools" }`,
|
|
80
|
+
* the only way to turn thinking off on them. Source: claude-api ref,
|
|
81
|
+
* "Thinking & Effort" per-model table (cached 2026-10-06): Claude Sonnet
|
|
82
|
+
* 5.5 returns a 400 on `{ type: "disabled" }` and takes `between_tools`
|
|
83
|
+
* instead (no other field alongside it, effort `high` or below). No other
|
|
84
|
+
* current model is documented to accept it. Opus 5.5 and Fable 5/5.1 have
|
|
85
|
+
* no thinking-off form at all: `disabled` and `budget_tokens` are a 400 at
|
|
86
|
+
* every effort, so the lowest they go is `effort: "low"`.
|
|
87
|
+
*/
|
|
88
|
+
const BETWEEN_TOOLS_RELEASE_ROOTS = ["claude-sonnet-5-5"];
|
|
89
|
+
/**
|
|
90
|
+
* Whether `effort: "none"` can turn thinking off on this model with
|
|
91
|
+
* `thinking: { type: "between_tools" }`. Matches the release id with or
|
|
92
|
+
* without a platform prefix (`anthropic.claude-sonnet-5-5` on Bedrock)
|
|
93
|
+
* and with dated or tagged suffixes, but not a later minor release.
|
|
94
|
+
*
|
|
95
|
+
* @example
|
|
96
|
+
* acceptsBetweenTools("claude-sonnet-5-5"); // → true
|
|
97
|
+
* acceptsBetweenTools("claude-opus-5-5"); // → false
|
|
98
|
+
*/
|
|
99
|
+
function acceptsBetweenTools(modelName) {
|
|
100
|
+
const normalized = modelName.toLowerCase();
|
|
101
|
+
const id = normalized.slice(normalized.lastIndexOf(".") + 1);
|
|
102
|
+
return BETWEEN_TOOLS_RELEASE_ROOTS.some((root) => matchesReleaseRoot(id, root));
|
|
103
|
+
}
|
|
78
104
|
|
|
79
105
|
//#endregion
|
|
80
|
-
export { acceptsTemperature, inferThinkingMode };
|
|
106
|
+
export { acceptsBetweenTools, acceptsTemperature, inferThinkingMode };
|
|
81
107
|
//# sourceMappingURL=thinking-mode.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"thinking-mode.mjs","names":[],"sources":["
|
|
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"}
|
package/esm/utils/index.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { mapStopReason } from "./map-stop-reason.mjs";
|
|
2
|
+
import { ANTHROPIC_BLOCK_FORMAT, fromProviderBlocks, toProviderBlocks } from "./provider-blocks.mjs";
|
|
2
3
|
import { toAnthropicMessages } from "./to-anthropic-messages.mjs";
|
|
3
4
|
import { toAnthropicTools } from "./to-anthropic-tools.mjs";
|
|
4
5
|
import { wrapAnthropicError } from "./wrap-anthropic-error.mjs";
|
|
@@ -1,27 +1,31 @@
|
|
|
1
|
-
//#region
|
|
1
|
+
//#region ../../packages/ai-anthropic/src/utils/map-stop-reason.ts
|
|
2
2
|
const stopReasonMap = {
|
|
3
3
|
end_turn: "stop",
|
|
4
4
|
stop_sequence: "stop",
|
|
5
|
+
compaction: "stop",
|
|
5
6
|
max_tokens: "length",
|
|
6
|
-
model_context_window_exceeded: "
|
|
7
|
+
model_context_window_exceeded: "context_exceeded",
|
|
8
|
+
pause_turn: "pause_turn",
|
|
9
|
+
refusal: "refusal",
|
|
7
10
|
tool_use: "tool_calls"
|
|
8
11
|
};
|
|
9
12
|
/**
|
|
10
13
|
* Map Anthropic's `stop_reason` to the normalized `FinishReason` union.
|
|
11
14
|
*
|
|
12
|
-
* `end_turn` / `stop_sequence` are
|
|
13
|
-
* `
|
|
14
|
-
* `
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
15
|
+
* `end_turn` / `stop_sequence` (and beta `compaction`) are natural stops,
|
|
16
|
+
* `max_tokens` maps to `length`, `tool_use` to `tool_calls`.
|
|
17
|
+
* `model_context_window_exceeded`, `pause_turn` and `refusal` keep their
|
|
18
|
+
* own reasons (`context_exceeded`, `pause_turn`, `refusal`) because each
|
|
19
|
+
* needs a different reaction: compact the history, send the turn back to
|
|
20
|
+
* resume, or fall back to another model. `null` and any value a future
|
|
21
|
+
* API version adds fall through to `"error"`.
|
|
19
22
|
*
|
|
20
23
|
* @example
|
|
21
|
-
* mapStopReason("end_turn");
|
|
22
|
-
* mapStopReason("tool_use");
|
|
23
|
-
* mapStopReason("refusal");
|
|
24
|
-
* mapStopReason(
|
|
24
|
+
* mapStopReason("end_turn"); // "stop"
|
|
25
|
+
* mapStopReason("tool_use"); // "tool_calls"
|
|
26
|
+
* mapStopReason("refusal"); // "refusal"
|
|
27
|
+
* mapStopReason("pause_turn"); // "pause_turn"
|
|
28
|
+
* mapStopReason(null); // "error"
|
|
25
29
|
*/
|
|
26
30
|
function mapStopReason(raw) {
|
|
27
31
|
return stopReasonMap[raw ?? ""] ?? "error";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"map-stop-reason.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"map-stop-reason.mjs","names":[],"sources":["../../../../../../../../packages/ai-anthropic/src/utils/map-stop-reason.ts"],"sourcesContent":["import type { FinishReason } from \"@warlock.js/ai\";\n\nconst stopReasonMap: Record<string, FinishReason> = {\n end_turn: \"stop\",\n stop_sequence: \"stop\",\n // Beta compaction (`compact-2026-09-04`): the turn ends with a signed\n // `compaction` block and nothing is sampled after it. A clean stop —\n // the block itself is on `ModelResponse.blocks`.\n compaction: \"stop\",\n max_tokens: \"length\",\n model_context_window_exceeded: \"context_exceeded\",\n pause_turn: \"pause_turn\",\n refusal: \"refusal\",\n tool_use: \"tool_calls\",\n};\n\n/**\n * Map Anthropic's `stop_reason` to the normalized `FinishReason` union.\n *\n * `end_turn` / `stop_sequence` (and beta `compaction`) are natural stops,\n * `max_tokens` maps to `length`, `tool_use` to `tool_calls`.\n * `model_context_window_exceeded`, `pause_turn` and `refusal` keep their\n * own reasons (`context_exceeded`, `pause_turn`, `refusal`) because each\n * needs a different reaction: compact the history, send the turn back to\n * resume, or fall back to another model. `null` and any value a future\n * API version adds fall through to `\"error\"`.\n *\n * @example\n * mapStopReason(\"end_turn\"); // \"stop\"\n * mapStopReason(\"tool_use\"); // \"tool_calls\"\n * mapStopReason(\"refusal\"); // \"refusal\"\n * mapStopReason(\"pause_turn\"); // \"pause_turn\"\n * mapStopReason(null); // \"error\"\n */\nexport function mapStopReason(raw: string | null | undefined): FinishReason {\n return stopReasonMap[raw ?? \"\"] ?? \"error\";\n}\n"],"mappings":";AAEA,MAAM,gBAA8C;CAClD,UAAU;CACV,eAAe;CAIf,YAAY;CACZ,YAAY;CACZ,+BAA+B;CAC/B,YAAY;CACZ,SAAS;CACT,UAAU;AACZ;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,cAAc,KAA8C;CAC1E,OAAO,cAAc,OAAO,OAAO;AACrC"}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
//#region ../../packages/ai-anthropic/src/utils/provider-blocks.ts
|
|
2
|
+
/** The `ProviderContentBlock.provider` value this adapter writes and replays. */
|
|
3
|
+
const ANTHROPIC_BLOCK_FORMAT = "anthropic";
|
|
4
|
+
/** Block types the neutral `content` + `toolCalls` fields already carry losslessly. */
|
|
5
|
+
const NEUTRAL_BLOCK_TYPES = new Set(["text", "tool_use"]);
|
|
6
|
+
/** Block types that carry a model-requested call whose id must match `toolCalls`. */
|
|
7
|
+
const TOOL_USE_BLOCK_TYPES = new Set(["tool_use"]);
|
|
8
|
+
/**
|
|
9
|
+
* Assistant-turn block types that may be sent back verbatim. Server-tool
|
|
10
|
+
* results all end in `_tool_result` (`web_search_tool_result`,
|
|
11
|
+
* `code_execution_tool_result`, …) and are matched by suffix; anything
|
|
12
|
+
* else (an unknown or user-side type such as `image`, `document` or a
|
|
13
|
+
* client `tool_result`) is not replayed.
|
|
14
|
+
*/
|
|
15
|
+
const REPLAYABLE_BLOCK_TYPES = new Set([
|
|
16
|
+
"text",
|
|
17
|
+
"thinking",
|
|
18
|
+
"redacted_thinking",
|
|
19
|
+
"tool_use",
|
|
20
|
+
"server_tool_use",
|
|
21
|
+
"mcp_tool_use",
|
|
22
|
+
"mcp_tool_result",
|
|
23
|
+
"container_upload",
|
|
24
|
+
"compaction"
|
|
25
|
+
]);
|
|
26
|
+
const SERVER_TOOL_RESULT_TYPE = /^[a-z][a-z0-9_]*_tool_result$/;
|
|
27
|
+
/**
|
|
28
|
+
* Wrap an assistant turn's content blocks as `ProviderContentBlock`s, or
|
|
29
|
+
* return `undefined` when the neutral fields already carry the whole turn
|
|
30
|
+
* (only plain text and `tool_use` blocks). Any other block — thinking,
|
|
31
|
+
* redacted thinking, compaction, server-tool use/results, cited text —
|
|
32
|
+
* makes the full ordered list worth keeping so the next request can
|
|
33
|
+
* replay the turn verbatim.
|
|
34
|
+
*
|
|
35
|
+
* @example
|
|
36
|
+
* toProviderBlocks([{ type: "text", text: "hi", citations: null }]); // undefined
|
|
37
|
+
* toProviderBlocks([{ type: "thinking", thinking: "", signature: "s" }, { type: "text", text: "hi" }]);
|
|
38
|
+
* // [{ provider: "anthropic", type: "thinking", data: {...} }, { provider: "anthropic", type: "text", data: {...} }]
|
|
39
|
+
*/
|
|
40
|
+
function toProviderBlocks(content) {
|
|
41
|
+
if (!content.some(needsVerbatimReplay)) return;
|
|
42
|
+
return content.map((block) => ({
|
|
43
|
+
provider: ANTHROPIC_BLOCK_FORMAT,
|
|
44
|
+
type: block.type,
|
|
45
|
+
data: { ...block }
|
|
46
|
+
}));
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Rebuild an assistant turn's Anthropic content from stored blocks.
|
|
50
|
+
* Returns `undefined` — so the caller falls back to `content` +
|
|
51
|
+
* `toolCalls` — when there are no blocks, when any block belongs to
|
|
52
|
+
* another provider's format, when a block is not a well-formed
|
|
53
|
+
* assistant-turn block (its `data.type` must equal its `type`, and the
|
|
54
|
+
* type must be one Anthropic returns on an assistant turn), or when the
|
|
55
|
+
* blocks' `tool_use` ids differ from the message's `toolCalls` (the turn
|
|
56
|
+
* was edited after the response, e.g. by a middleware or a recovered
|
|
57
|
+
* stream call, so a verbatim replay would no longer match the tool
|
|
58
|
+
* results that follow). The checks matter when a transcript comes from
|
|
59
|
+
* outside the process (a client, a store): the block data is sent as is.
|
|
60
|
+
*/
|
|
61
|
+
function fromProviderBlocks(blocks, toolCalls) {
|
|
62
|
+
if (!blocks || blocks.length === 0) return;
|
|
63
|
+
if (!blocks.every((block) => block.provider === "anthropic" && isReplayable(block))) return;
|
|
64
|
+
const blockToolIds = blocks.filter((block) => TOOL_USE_BLOCK_TYPES.has(block.type)).map((block) => block.data.id);
|
|
65
|
+
const requestedIds = (toolCalls ?? []).map((toolCall) => toolCall.id);
|
|
66
|
+
if (blockToolIds.length !== requestedIds.length || blockToolIds.some((id, index) => id !== requestedIds[index])) return;
|
|
67
|
+
return blocks.map((block) => ({ ...block.data }));
|
|
68
|
+
}
|
|
69
|
+
function needsVerbatimReplay(block) {
|
|
70
|
+
if (!NEUTRAL_BLOCK_TYPES.has(block.type)) return true;
|
|
71
|
+
const citations = block.citations;
|
|
72
|
+
return Array.isArray(citations) && citations.length > 0;
|
|
73
|
+
}
|
|
74
|
+
function isReplayable(block) {
|
|
75
|
+
const data = block.data;
|
|
76
|
+
if (data === null || typeof data !== "object" || Array.isArray(data)) return false;
|
|
77
|
+
if (data.type !== block.type) return false;
|
|
78
|
+
return REPLAYABLE_BLOCK_TYPES.has(block.type) || SERVER_TOOL_RESULT_TYPE.test(block.type);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
//#endregion
|
|
82
|
+
export { ANTHROPIC_BLOCK_FORMAT, fromProviderBlocks, toProviderBlocks };
|
|
83
|
+
//# sourceMappingURL=provider-blocks.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"provider-blocks.mjs","names":[],"sources":["../../../../../../../../packages/ai-anthropic/src/utils/provider-blocks.ts"],"sourcesContent":["import type { ModelToolCallRequest, ProviderContentBlock } from \"@warlock.js/ai\";\nimport type Anthropic from \"@anthropic-ai/sdk\";\n\n/** The `ProviderContentBlock.provider` value this adapter writes and replays. */\nexport const ANTHROPIC_BLOCK_FORMAT = \"anthropic\";\n\n/** Block types the neutral `content` + `toolCalls` fields already carry losslessly. */\nconst NEUTRAL_BLOCK_TYPES = new Set([\"text\", \"tool_use\"]);\n\n/** Block types that carry a model-requested call whose id must match `toolCalls`. */\nconst TOOL_USE_BLOCK_TYPES = new Set([\"tool_use\"]);\n\n/**\n * Assistant-turn block types that may be sent back verbatim. Server-tool\n * results all end in `_tool_result` (`web_search_tool_result`,\n * `code_execution_tool_result`, …) and are matched by suffix; anything\n * else (an unknown or user-side type such as `image`, `document` or a\n * client `tool_result`) is not replayed.\n */\nconst REPLAYABLE_BLOCK_TYPES: ReadonlySet<string> = new Set([\n \"text\",\n \"thinking\",\n \"redacted_thinking\",\n \"tool_use\",\n \"server_tool_use\",\n \"mcp_tool_use\",\n \"mcp_tool_result\",\n \"container_upload\",\n \"compaction\",\n]);\n\nconst SERVER_TOOL_RESULT_TYPE = /^[a-z][a-z0-9_]*_tool_result$/;\n\n/**\n * Wrap an assistant turn's content blocks as `ProviderContentBlock`s, or\n * return `undefined` when the neutral fields already carry the whole turn\n * (only plain text and `tool_use` blocks). Any other block — thinking,\n * redacted thinking, compaction, server-tool use/results, cited text —\n * makes the full ordered list worth keeping so the next request can\n * replay the turn verbatim.\n *\n * @example\n * toProviderBlocks([{ type: \"text\", text: \"hi\", citations: null }]); // undefined\n * toProviderBlocks([{ type: \"thinking\", thinking: \"\", signature: \"s\" }, { type: \"text\", text: \"hi\" }]);\n * // [{ provider: \"anthropic\", type: \"thinking\", data: {...} }, { provider: \"anthropic\", type: \"text\", data: {...} }]\n */\nexport function toProviderBlocks(\n content: ReadonlyArray<{ type: string }>,\n): ProviderContentBlock[] | undefined {\n if (!content.some(needsVerbatimReplay)) {\n return undefined;\n }\n\n return content.map((block) => ({\n provider: ANTHROPIC_BLOCK_FORMAT,\n type: block.type,\n data: { ...(block as Record<string, unknown>) },\n }));\n}\n\n/**\n * Rebuild an assistant turn's Anthropic content from stored blocks.\n * Returns `undefined` — so the caller falls back to `content` +\n * `toolCalls` — when there are no blocks, when any block belongs to\n * another provider's format, when a block is not a well-formed\n * assistant-turn block (its `data.type` must equal its `type`, and the\n * type must be one Anthropic returns on an assistant turn), or when the\n * blocks' `tool_use` ids differ from the message's `toolCalls` (the turn\n * was edited after the response, e.g. by a middleware or a recovered\n * stream call, so a verbatim replay would no longer match the tool\n * results that follow). The checks matter when a transcript comes from\n * outside the process (a client, a store): the block data is sent as is.\n */\nexport function fromProviderBlocks(\n blocks: ProviderContentBlock[] | undefined,\n toolCalls: ModelToolCallRequest[] | undefined,\n): Anthropic.ContentBlockParam[] | undefined {\n if (!blocks || blocks.length === 0) {\n return undefined;\n }\n\n if (!blocks.every((block) => block.provider === ANTHROPIC_BLOCK_FORMAT && isReplayable(block))) {\n return undefined;\n }\n\n const blockToolIds = blocks\n .filter((block) => TOOL_USE_BLOCK_TYPES.has(block.type))\n .map((block) => block.data.id);\n const requestedIds = (toolCalls ?? []).map((toolCall) => toolCall.id);\n\n if (\n blockToolIds.length !== requestedIds.length ||\n blockToolIds.some((id, index) => id !== requestedIds[index])\n ) {\n return undefined;\n }\n\n return blocks.map((block) => ({ ...block.data }) as unknown as Anthropic.ContentBlockParam);\n}\n\nfunction needsVerbatimReplay(block: { type: string }): boolean {\n if (!NEUTRAL_BLOCK_TYPES.has(block.type)) {\n return true;\n }\n\n const citations = (block as { citations?: unknown }).citations;\n\n return Array.isArray(citations) && citations.length > 0;\n}\n\nfunction isReplayable(block: ProviderContentBlock): boolean {\n const data = block.data as unknown;\n\n if (data === null || typeof data !== \"object\" || Array.isArray(data)) {\n return false;\n }\n\n if ((data as { type?: unknown }).type !== block.type) {\n return false;\n }\n\n return REPLAYABLE_BLOCK_TYPES.has(block.type) || SERVER_TOOL_RESULT_TYPE.test(block.type);\n}\n"],"mappings":";;AAIA,MAAa,yBAAyB;;AAGtC,MAAM,sBAAsB,IAAI,IAAI,CAAC,QAAQ,UAAU,CAAC;;AAGxD,MAAM,uBAAuB,IAAI,IAAI,CAAC,UAAU,CAAC;;;;;;;;AASjD,MAAM,yBAA8C,IAAI,IAAI;CAC1D;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,MAAM,0BAA0B;;;;;;;;;;;;;;AAehC,SAAgB,iBACd,SACoC;CACpC,IAAI,CAAC,QAAQ,KAAK,mBAAmB,GACnC;CAGF,OAAO,QAAQ,KAAK,WAAW;EAC7B,UAAU;EACV,MAAM,MAAM;EACZ,MAAM,EAAE,GAAI,MAAkC;CAChD,EAAE;AACJ;;;;;;;;;;;;;;AAeA,SAAgB,mBACd,QACA,WAC2C;CAC3C,IAAI,CAAC,UAAU,OAAO,WAAW,GAC/B;CAGF,IAAI,CAAC,OAAO,OAAO,UAAU,MAAM,4BAAuC,aAAa,KAAK,CAAC,GAC3F;CAGF,MAAM,eAAe,OAClB,QAAQ,UAAU,qBAAqB,IAAI,MAAM,IAAI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