@warlock.js/ai-anthropic 5.31.0 → 5.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/cjs/index.cjs +33 -7
  3. package/cjs/index.cjs.map +1 -1
  4. package/esm/config.type.d.mts +22 -16
  5. package/esm/config.type.d.mts.map +1 -1
  6. package/esm/index.d.mts +3 -2
  7. package/esm/index.mjs +2 -2
  8. package/esm/known-pricing.d.mts +12 -7
  9. package/esm/known-pricing.d.mts.map +1 -1
  10. package/esm/known-pricing.mjs +8 -1
  11. package/esm/known-pricing.mjs.map +1 -1
  12. package/esm/model.d.mts +1 -3
  13. package/esm/model.d.mts.map +1 -1
  14. package/esm/model.mjs +7 -3
  15. package/esm/model.mjs.map +1 -1
  16. package/esm/request.type.d.mts +4 -6
  17. package/esm/request.type.d.mts.map +1 -1
  18. package/esm/sdk.d.mts +1 -3
  19. package/esm/sdk.d.mts.map +1 -1
  20. package/esm/thinking-mode.d.mts +2 -3
  21. package/esm/thinking-mode.d.mts.map +1 -1
  22. package/esm/thinking-mode.mjs +1 -1
  23. package/esm/utils/index.d.mts +4 -1
  24. package/esm/utils/index.mjs +1 -1
  25. package/esm/utils/map-stop-reason.d.mts +1 -1
  26. package/esm/utils/provider-blocks.d.mts +3 -5
  27. package/esm/utils/provider-blocks.d.mts.map +1 -1
  28. package/esm/utils/provider-blocks.mjs +3 -3
  29. package/esm/utils/provider-blocks.mjs.map +1 -1
  30. package/esm/utils/server-tool-usage.mjs +17 -0
  31. package/esm/utils/server-tool-usage.mjs.map +1 -0
  32. package/esm/utils/to-anthropic-messages.d.mts +3 -5
  33. package/esm/utils/to-anthropic-messages.d.mts.map +1 -1
  34. package/esm/utils/to-anthropic-tools.d.mts +1 -3
  35. package/esm/utils/to-anthropic-tools.d.mts.map +1 -1
  36. package/llms-full.txt +34 -0
  37. package/package.json +3 -3
  38. package/skills/setup-anthropic/SKILL.md +34 -0
package/cjs/index.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["AIError","ProviderTimeoutError","ProviderAuthError","QuotaExceededError","ProviderRateLimitError","ProviderOverloadedError","ContextLengthExceededError","InvalidRequestError","ProviderError","APIError","APIConnectionTimeoutError","log","AIError","InvalidRequestError","Anthropic"],"sources":["../../../../../../../packages/ai-anthropic/src/known-pricing.ts","../../../../../../../packages/ai-anthropic/src/thinking-mode.ts","../../../../../../../packages/ai-anthropic/src/known-output-limits.ts","../../../../../../../packages/ai-anthropic/src/known-vision-models.ts","../../../../../../../packages/ai-anthropic/src/utils/cache-usage.ts","../../../../../../../packages/ai-anthropic/src/utils/map-stop-reason.ts","../../../../../../../packages/ai-anthropic/src/utils/provider-blocks.ts","../../../../../../../packages/ai-anthropic/src/utils/to-anthropic-messages.ts","../../../../../../../packages/ai-anthropic/src/utils/to-anthropic-tools.ts","../../../../../../../packages/ai-anthropic/src/utils/wrap-anthropic-error.ts","../../../../../../../packages/ai-anthropic/src/model.ts","../../../../../../../packages/ai-anthropic/src/sdk.ts"],"sourcesContent":["import type { ModelPricing } from \"@warlock.js/ai\";\n\n/**\n * Anthropic's prompt-cache write multipliers, relative to the base input\n * rate: a 5-minute write costs 1.25x, a 1-hour write 2x. They hold for\n * every Claude model on Anthropic's price list.\n *\n * Source: https://platform.claude.com/docs/en/about-claude/pricing\n * (fetched 2026-10-17).\n */\nexport const ANTHROPIC_CACHE_WRITE_MULTIPLIER = 1.25;\nexport const ANTHROPIC_CACHE_WRITE_1H_MULTIPLIER = 2;\n\n/**\n * Built-in Claude API list prices, USD per 1,000,000 tokens, keyed by\n * model id. `cachedInput` is the cache-hit rate, `cacheWrite` the\n * 5-minute write rate and `cacheWrite1h` the 1-hour write rate.\n *\n * Source: https://platform.claude.com/docs/en/about-claude/pricing,\n * \"Model pricing\" table, fetched 2026-10-17. Standard (global) routing,\n * non-batch. Not covered, so pass `pricing` yourself when you need them:\n *\n * - Claude Haiku 5.5 — priced by prompt length (higher rates above\n * 100,000 prompt tokens), which a flat `ModelPricing` cannot express.\n * - US-only inference (`inference_geo: \"us\"`, 1.1x), fast mode, the Batch\n * API, and Claude on Bedrock / Vertex AI (partner-priced).\n * - Limited-availability models (Mythos) and retired models.\n *\n * Dated snapshot ids (`claude-haiku-4-5-20251001`) resolve to their alias\n * entry through {@link anthropicPricingFor}.\n */\nexport const ANTHROPIC_MODEL_PRICING: Readonly<Record<string, ModelPricing>> = {\n \"claude-fable-5-1\": {\n input: 10,\n output: 50,\n cachedInput: 0.25,\n cacheWrite: 12.5,\n cacheWrite1h: 20,\n },\n \"claude-fable-5\": { input: 10, output: 50, cachedInput: 1, cacheWrite: 12.5, cacheWrite1h: 20 },\n \"claude-opus-5-5\": { input: 4, output: 20, cachedInput: 0.2, cacheWrite: 5, cacheWrite1h: 8 },\n \"claude-opus-5\": { input: 5, output: 25, cachedInput: 0.5, cacheWrite: 6.25, cacheWrite1h: 10 },\n \"claude-opus-4-8\": { input: 5, output: 25, cachedInput: 0.5, cacheWrite: 6.25, cacheWrite1h: 10 },\n \"claude-opus-4-7\": { input: 5, output: 25, cachedInput: 0.5, cacheWrite: 6.25, cacheWrite1h: 10 },\n \"claude-opus-4-6\": { input: 5, output: 25, cachedInput: 0.5, cacheWrite: 6.25, cacheWrite1h: 10 },\n \"claude-opus-4-5\": { input: 5, output: 25, cachedInput: 0.5, cacheWrite: 6.25, cacheWrite1h: 10 },\n \"claude-sonnet-5-5\": { input: 2, output: 10, cachedInput: 0.1, cacheWrite: 2.5, cacheWrite1h: 4 },\n \"claude-sonnet-5\": { input: 2, output: 10, cachedInput: 0.2, cacheWrite: 2.5, cacheWrite1h: 4 },\n \"claude-sonnet-4-6\": {\n input: 3,\n output: 15,\n cachedInput: 0.3,\n cacheWrite: 3.75,\n cacheWrite1h: 6,\n },\n \"claude-sonnet-4-5\": {\n input: 3,\n output: 15,\n cachedInput: 0.3,\n cacheWrite: 3.75,\n cacheWrite1h: 6,\n },\n \"claude-haiku-4-5\": { input: 1, output: 5, cachedInput: 0.1, cacheWrite: 1.25, cacheWrite1h: 2 },\n};\n\n/** A trailing `-YYYYMMDD` snapshot date on a Claude model id. */\nconst SNAPSHOT_SUFFIX = /-\\d{8}$/;\n\n/**\n * Look up the built-in list price for a Claude model id. Accepts the\n * alias (`claude-sonnet-4-5`) or a dated snapshot\n * (`claude-sonnet-4-5-20250929`). Returns `undefined` for any id not in\n * {@link ANTHROPIC_MODEL_PRICING}, so cost stays unknown rather than wrong.\n *\n * @example\n * anthropicPricingFor(\"claude-haiku-4-5-20251001\"); // { input: 1, output: 5, … }\n * anthropicPricingFor(\"claude-haiku-5-5\"); // undefined (prompt-length tiers)\n */\nexport function anthropicPricingFor(modelName: string): ModelPricing | undefined {\n const exact = ANTHROPIC_MODEL_PRICING[modelName];\n\n if (exact) {\n return exact;\n }\n\n return ANTHROPIC_MODEL_PRICING[modelName.replace(SNAPSHOT_SUFFIX, \"\")];\n}\n\n/**\n * Fill the cache-write rates Anthropic derives from the input rate\n * (5-minute writes 1.25x, 1-hour writes 2x) into a pricing entry that\n * omits them, so a caller who supplies only `{ input, output }` is no\n * longer billed nothing for cache writes. Explicit rates always win; the\n * cache-read rate is left alone because it differs per model.\n *\n * @example\n * withAnthropicCacheWriteRates({ input: 3, output: 15 });\n * // { input: 3, output: 15, cacheWrite: 3.75, cacheWrite1h: 6 }\n */\nexport function withAnthropicCacheWriteRates(\n pricing: ModelPricing | undefined,\n): ModelPricing | undefined {\n if (!pricing) {\n return undefined;\n }\n\n const cacheWrite =\n pricing.cacheWrite ?? pricing.cachedOutput ?? pricing.input * ANTHROPIC_CACHE_WRITE_MULTIPLIER;\n const cacheWrite1h = pricing.cacheWrite1h ?? pricing.input * ANTHROPIC_CACHE_WRITE_1H_MULTIPLIER;\n\n if (pricing.cacheWrite === cacheWrite && pricing.cacheWrite1h === cacheWrite1h) {\n return pricing;\n }\n\n return { ...pricing, cacheWrite, cacheWrite1h };\n}\n","/**\n * How a Claude model accepts extended thinking on the Messages API.\n *\n * - `\"adaptive\"` — `thinking: { type: \"adaptive\" }`, with depth steered by\n * `output_config.effort`. Sending `budget_tokens` to these models is a\n * 400. Installed SDK: `ThinkingConfigAdaptive`\n * (`@anthropic-ai/sdk/resources/messages/messages.d.ts:1065`) and\n * `OutputConfig.effort` (`messages.d.ts:796-800`).\n * - `\"budget\"` — the legacy `thinking: { type: \"enabled\", budget_tokens }`\n * (`ThinkingConfigEnabled`, `messages.d.ts:1078-1090`). Required on\n * Haiku 4.5 and older models.\n */\nexport type AnthropicThinkingMode = \"adaptive\" | \"budget\";\n\n/*\n * Model-family table (source: claude-api ref, \"Thinking & Effort\" per-model\n * table, cached 2026-09-25; summarised in `releases/5.26-ai-sdk-review.md` §A):\n *\n * | Model ids | Mode | `budget_tokens` | `temperature` |\n * |----------------------------------------------|------------|-------------------------|--------------------|\n * | claude-fable-5, claude-fable-5-1 (+ mythos) | adaptive | removed (400) | removed (400) |\n * | claude-opus-5-5, claude-opus-5 | adaptive | removed (400) | removed (400) |\n * | claude-opus-4-8, claude-opus-4-7 | adaptive | removed (400) | removed (400) |\n * | claude-sonnet-5-5, claude-sonnet-5 | adaptive | removed (400) | 400 (5.5: non-1.0) |\n * | claude-opus-4-6, claude-sonnet-4-6 | budget (*) | deprecated, still works | allowed |\n * | claude-haiku-4-5 and every older model | budget | required for thinking | allowed |\n * | anything not listed (future / unknown ids) | adaptive | — | — |\n *\n * (*) The 4.6 pair accepts both shapes; the claude-api ref recommends\n * adaptive there but keeps `budget_tokens` functional as a transitional\n * path. It stays on `budget` so 4.6 callers see no behaviour change (their\n * `reasoning.maxTokens` is still honoured as a hard budget) and so that\n * the `budget` set is exactly the set that still accepts `temperature`\n * (see `acceptsTemperature`). Opt 4.6 into adaptive with\n * `anthropic.model({ name, thinkingMode: \"adaptive\" })`.\n *\n * Unknown ids default to adaptive because that is the current API\n * direction: every model released after Opus 4.6 rejects `budget_tokens`.\n */\n\n/**\n * Family prefixes that are budget-mode in their entirety — plain\n * `startsWith` match (dated and `-latest` variants included).\n */\nconst BUDGET_FAMILY_PREFIXES = [\n // Claude 3 / 3.5 / 3.7 legacy naming (claude-3-haiku-…, claude-3-5-sonnet-…).\n \"claude-3\",\n // Pre-3 text models: no thinking support at all, never adaptive.\n \"claude-2\",\n \"claude-instant\",\n // Haiku 4.x: Haiku 4.5 still requires budget_tokens (claude-api ref).\n \"claude-haiku-4\",\n];\n\n/**\n * Individual pre-4.7 releases in the `claude-<tier>-4-*` naming. Matched\n * as a release root: the id must equal the root or continue with a\n * separator that is not a new minor version number, so `claude-opus-4`\n * matches `claude-opus-4-20250514` but NOT `claude-opus-4-7`. Ids from the\n * installed SDK `Model` union (`messages.d.ts:795`) plus the 4.6 pair.\n */\nconst BUDGET_RELEASE_ROOTS = [\n \"claude-opus-4\",\n \"claude-opus-4-0\",\n \"claude-opus-4-1\",\n \"claude-opus-4-5\",\n \"claude-opus-4-6\",\n \"claude-sonnet-4\",\n \"claude-sonnet-4-0\",\n \"claude-sonnet-4-5\",\n \"claude-sonnet-4-6\",\n];\n\n/**\n * A remainder that starts a new minor version (`-7`, `-10`) — used to\n * stop a release root from swallowing a later release of the same line.\n * Dates (`-20250514`) and tags (`-latest`, `-v1`) are not minor versions.\n */\nconst NEXT_MINOR_VERSION = /^-\\d{1,2}(?!\\d)/;\n\n/**\n * Whether a lower-cased model id is the release `root` itself, or a dated /\n * tagged / `@` snapshot of it — but not a later minor version of the same\n * line (`claude-opus-4` matches `claude-opus-4-20250514`, not `claude-opus-4-7`).\n */\nexport function matchesReleaseRoot(name: string, root: string): boolean {\n if (!name.startsWith(root)) {\n return false;\n }\n\n const rest = name.slice(root.length);\n\n if (rest === \"\") {\n return true;\n }\n\n return (rest.startsWith(\"-\") || rest.startsWith(\"@\")) && !NEXT_MINOR_VERSION.test(rest);\n}\n\n/**\n * Infer the thinking mode for a Claude model id. Budget for Haiku 4.5, the\n * 4.6 pair, and every older family; adaptive for everything else,\n * including unknown and future ids. Explicit per-model config\n * (`AnthropicModelConfig.thinkingMode`) always wins over this inference.\n *\n * @example\n * inferThinkingMode(\"claude-opus-5-5\"); // → \"adaptive\"\n * inferThinkingMode(\"claude-haiku-4-5\"); // → \"budget\"\n * inferThinkingMode(\"claude-opus-9\"); // → \"adaptive\" (unknown → current API direction)\n */\nexport function inferThinkingMode(modelName: string): AnthropicThinkingMode {\n const normalized = modelName.toLowerCase();\n\n if (BUDGET_FAMILY_PREFIXES.some((prefix) => normalized.startsWith(prefix))) {\n return \"budget\";\n }\n\n if (BUDGET_RELEASE_ROOTS.some((root) => matchesReleaseRoot(normalized, root))) {\n return \"budget\";\n }\n\n return \"adaptive\";\n}\n\n/**\n * Whether a model of this thinking mode accepts an explicit `temperature`.\n *\n * Installed SDK, `MessageCreateParamsBase.temperature`\n * (`messages.d.ts:2036-2040`): \"Models released after Claude Opus 4.6 do\n * not support setting temperature. A value of 1.0 will be accepted for\n * backwards compatibility, all other values will be rejected with a 400\n * error.\" The claude-api ref's per-model table agrees: sampling is\n * \"Removed - 400\" on Fable 5/5.1, Opus 5.5/5/4.8/4.7 and Sonnet 5, and\n * \"Non-default values - 400\" on Sonnet 5.5; \"Allowed\" on Opus 4.6,\n * Sonnet 4.6, Haiku 4.5 and older.\n *\n * That split is exactly the adaptive/budget split in the table above\n * (adaptive = released after Opus 4.6; budget = Opus 4.6 and earlier), so\n * the thinking mode doubles as the sampling-parameter classification.\n */\nexport function acceptsTemperature(mode: AnthropicThinkingMode): boolean {\n return mode === \"budget\";\n}\n\n/**\n * Model release roots that accept `thinking: { type: \"between_tools\" }`,\n * the only way to turn thinking off on them. Source: claude-api ref,\n * \"Thinking & Effort\" per-model table (cached 2026-10-06): Claude Sonnet\n * 5.5 returns a 400 on `{ type: \"disabled\" }` and takes `between_tools`\n * instead (no other field alongside it, effort `high` or below). No other\n * current model is documented to accept it. Opus 5.5 and Fable 5/5.1 have\n * no thinking-off form at all: `disabled` and `budget_tokens` are a 400 at\n * every effort, so the lowest they go is `effort: \"low\"`.\n */\nconst BETWEEN_TOOLS_RELEASE_ROOTS = [\"claude-sonnet-5-5\"];\n\n/**\n * Whether `effort: \"none\"` can turn thinking off on this model with\n * `thinking: { type: \"between_tools\" }`. Matches the release id with or\n * without a platform prefix (`anthropic.claude-sonnet-5-5` on Bedrock)\n * and with dated or tagged suffixes, but not a later minor release.\n *\n * @example\n * acceptsBetweenTools(\"claude-sonnet-5-5\"); // → true\n * acceptsBetweenTools(\"claude-opus-5-5\"); // → false\n */\nexport function acceptsBetweenTools(modelName: string): boolean {\n return matchesAnyRelease(modelName, BETWEEN_TOOLS_RELEASE_ROOTS);\n}\n\n/**\n * Whether the model id — lower-cased, with any platform prefix\n * (`anthropic.`, `us.anthropic.` on Bedrock) removed — is one of these\n * releases, dated or tagged, but not a later minor release.\n */\nfunction matchesAnyRelease(modelName: string, roots: readonly string[]): boolean {\n const normalized = modelName.toLowerCase();\n const id = normalized.slice(normalized.lastIndexOf(\".\") + 1);\n\n return roots.some((root) => matchesReleaseRoot(id, root));\n}\n\n/**\n * How a model is asked to run without reasoning when the caller passes the\n * neutral `reasoning: { effort: \"none\" }`.\n *\n * - `\"between_tools\"` — send `thinking: { type: \"between_tools\" }` alone.\n * - `\"disabled\"` — send `thinking: { type: \"disabled\" }` with no effort.\n * - `\"lowest-effort\"` — keep adaptive thinking on and send the lowest\n * `output_config.effort` (`\"low\"`).\n * - `\"omit\"` — send no `thinking` field at all.\n */\nexport type AnthropicNoReasoningForm = \"between_tools\" | \"disabled\" | \"lowest-effort\" | \"omit\";\n\n/**\n * Releases that accept `thinking: { type: \"disabled\" }` and run reliably\n * with it. Source: claude-api ref, \"Thinking & Effort\" per-model table\n * (cached 2026-10-06): Claude Sonnet 5 accepts `disabled`; Claude Haiku 5.5\n * accepts it at effort `low`, `medium` and `high` (a 400 at `xhigh` /\n * `max`). No effort is sent alongside it, so Haiku 5.5 runs at its default,\n * `medium`, which is inside the accepted range.\n */\nconst DISABLED_THINKING_RELEASE_ROOTS = [\"claude-sonnet-5\", \"claude-haiku-5-5\"];\n\n/**\n * Releases that accept `disabled` but are kept on adaptive thinking at the\n * lowest effort instead. Claude Opus 5 accepts `disabled` at effort `high`\n * or below, but the claude-api ref (\"Two failure modes when thinking is\n * disabled\", cached 2026-10-06) documents that with thinking disabled it\n * occasionally writes a tool call into its visible text instead of a\n * `tool_use` block — the call never runs and no error is raised — and can\n * leak `<thinking>` tags into the response. The ref's primary\n * recommendation is to keep thinking on and lower `effort`, so the adapter\n * does exactly that.\n */\nconst LOWEST_EFFORT_RELEASE_ROOTS = [\"claude-opus-5\"];\n\n/**\n * The wire form for `reasoning: { effort: \"none\" }` on this model:\n *\n * | Model | Form |\n * |----------------------------------------|-------------------|\n * | Claude Sonnet 5.5 | `between_tools` |\n * | Claude Sonnet 5, Claude Haiku 5.5 | `disabled` |\n * | Claude Opus 5 | `lowest-effort` |\n * | Opus 5.5, Fable 5/5.1, everything else | `omit` |\n *\n * Opus 5.5 and Fable 5/5.1 have no thinking-off form (`disabled` and\n * `budget_tokens` are a 400 at every effort), so nothing is sent and the\n * model runs at its default effort; older models run without thinking when\n * the field is absent.\n *\n * @example\n * noReasoningForm(\"claude-sonnet-5\"); // → \"disabled\"\n * noReasoningForm(\"claude-opus-5\"); // → \"lowest-effort\"\n * noReasoningForm(\"claude-opus-5-5\"); // → \"omit\"\n */\nexport function noReasoningForm(modelName: string): AnthropicNoReasoningForm {\n if (acceptsBetweenTools(modelName)) {\n return \"between_tools\";\n }\n\n if (matchesAnyRelease(modelName, DISABLED_THINKING_RELEASE_ROOTS)) {\n return \"disabled\";\n }\n\n if (matchesAnyRelease(modelName, LOWEST_EFFORT_RELEASE_ROOTS)) {\n return \"lowest-effort\";\n }\n\n return \"omit\";\n}\n\n/*\n * Preserved thinking (Anthropic docs, \"Thinking\" → \"Preserved thinking\" and\n * the \"Preserved thinking\" page, read 2026-10-17): the API checks that the\n * `system` prompt, `tools` and every message before a replayed thinking\n * block are unchanged since the block was produced, on Claude Fable 5.1,\n * Claude Opus 5.5, Claude Sonnet 5.5 and Claude Haiku 5.5. Claude Mythos 5.1\n * and every model released before Claude Fable 5.1 don't run that check, so\n * a thinking block kept after a client-written summary stays valid there.\n */\nconst PREFIX_CHECK_RELEASE_ROOTS = [\n \"claude-fable-5-1\",\n \"claude-opus-5-5\",\n \"claude-sonnet-5-5\",\n \"claude-haiku-5-5\",\n];\n\n/** Releases documented not to run the conversation check. */\nconst NO_PREFIX_CHECK_RELEASE_ROOTS = [\n \"claude-mythos-5-1\",\n \"claude-mythos-5\",\n \"claude-mythos-preview\",\n \"claude-fable-5\",\n \"claude-opus-5\",\n \"claude-sonnet-5\",\n];\n\n/** Families released before Claude Fable 5.1 in their entirety. */\nconst NO_PREFIX_CHECK_FAMILY_PREFIXES = [\n ...BUDGET_FAMILY_PREFIXES,\n \"claude-opus-4\",\n \"claude-sonnet-4\",\n];\n\n/**\n * Whether this model binds a replayed thinking block to the exact\n * conversation before it (preserved thinking). Unknown and future ids are\n * assumed to run the check — the safe direction: reasoning a kept turn\n * can't use is left out instead of risking a 400. Matches the id with or\n * without a platform prefix and with dated or tagged suffixes.\n *\n * @example\n * inferPreservedThinking(\"claude-opus-5-5\"); // → true\n * inferPreservedThinking(\"claude-opus-5\"); // → false\n * inferPreservedThinking(\"claude-opus-4-8\"); // → false\n */\nexport function inferPreservedThinking(modelName: string): boolean {\n const normalized = modelName.toLowerCase();\n const id = normalized.slice(normalized.lastIndexOf(\".\") + 1);\n\n if (PREFIX_CHECK_RELEASE_ROOTS.some((root) => matchesReleaseRoot(id, root))) {\n return true;\n }\n\n if (\n NO_PREFIX_CHECK_RELEASE_ROOTS.some((root) => matchesReleaseRoot(id, root)) ||\n NO_PREFIX_CHECK_FAMILY_PREFIXES.some((prefix) => id.startsWith(prefix))\n ) {\n return false;\n }\n\n return true;\n}\n","import { matchesReleaseRoot } from \"./thinking-mode\";\n\n/*\n * Documented maximum output tokens (`max_tokens`) on the synchronous\n * Messages API. Source: Anthropic's model pages and models overview,\n * platform.claude.com/docs/en/about-claude/models/overview and\n * …/models/{opus-4-5,sonnet-4-5,haiku-4-5}/overview, checked 2026-10-17.\n *\n * | Model ids | Max output |\n * |--------------------------------------------------------------|------------|\n * | Claude 5 family: fable-5 / 5.1, mythos-5 / 5.1, opus-5 / 5.5, | 128K |\n * | sonnet-5 / 5.5, haiku-5-5 | |\n * | claude-opus-4-8, claude-opus-4-7, claude-opus-4-6, | 128K |\n * | claude-sonnet-4-6 | |\n * | claude-opus-4-5, claude-sonnet-4-5, claude-haiku-4-5 | 64K |\n *\n * Older models (Claude 3.x, Opus 4 / 4.1, Sonnet 4) are retired and have no\n * entry; like any id not listed they fall back to the adapter default.\n */\n\n/** Family prefixes whose every release has a 128K output limit. */\nconst FAMILY_128K_PREFIXES = [\n \"claude-fable-5\",\n \"claude-mythos-5\",\n \"claude-opus-5\",\n \"claude-sonnet-5\",\n \"claude-haiku-5\",\n];\n\n/** Individual releases, matched as a release root (dated / `@` variants included). */\nconst RELEASE_OUTPUT_LIMITS: ReadonlyArray<readonly [root: string, limit: number]> = [\n [\"claude-opus-4-8\", 128_000],\n [\"claude-opus-4-7\", 128_000],\n [\"claude-opus-4-6\", 128_000],\n [\"claude-sonnet-4-6\", 128_000],\n [\"claude-opus-4-5\", 64_000],\n [\"claude-sonnet-4-5\", 64_000],\n [\"claude-haiku-4-5\", 64_000],\n];\n\n/**\n * The documented maximum output tokens of a Claude model, or `undefined`\n * when the id is not a known Claude model. Platform prefixes before\n * `claude-` (`anthropic.`, `us.anthropic.`) and dated or `@` snapshot\n * suffixes are accepted, so the Bedrock / Google Cloud ids of a known\n * model resolve too. Override per model with\n * `anthropic.model({ name, maxOutputTokens })`.\n *\n * @example\n * inferMaxOutputTokens(\"claude-opus-5-5\"); // → 128000\n * inferMaxOutputTokens(\"claude-haiku-4-5-20251001\"); // → 64000\n * inferMaxOutputTokens(\"my-gateway/model\"); // → undefined\n */\nexport function inferMaxOutputTokens(modelName: string): number | undefined {\n const lowered = modelName.toLowerCase();\n const start = lowered.indexOf(\"claude-\");\n\n if (start === -1) {\n return undefined;\n }\n\n const normalized = lowered.slice(start);\n\n if (FAMILY_128K_PREFIXES.some((prefix) => normalized.startsWith(prefix))) {\n return 128_000;\n }\n\n for (const [root, limit] of RELEASE_OUTPUT_LIMITS) {\n if (matchesReleaseRoot(normalized, root)) {\n return limit;\n }\n }\n\n return undefined;\n}\n","/**\n * Model-name prefixes for Claude families that accept image input\n * (vision) on the Messages API.\n *\n * Every Claude 3, Claude 3.5/3.7, Claude 4 and Claude 5 family model is\n * multimodal, so the list covers both the dotted legacy naming\n * (`claude-3-haiku-...`, `claude-3-5-sonnet-...`) and the current\n * `claude-<tier>-4-*` naming (`claude-opus-4-7`, `claude-sonnet-4-6`,\n * `claude-haiku-4-5`). Pre-3 families (`claude-2`, `claude-instant`)\n * are text-only and intentionally absent.\n *\n * The Claude 5 series is multimodal too (claude-api ref, cached\n * 2026-09-25): its vision examples use `claude-opus-5-5`; the models list\n * credits Claude Fable 5.1 with vision and Claude Sonnet 5 with\n * high-resolution vision; Claude Mythos 5.1 has \"same capabilities\" as\n * Fable 5.1. The tier-5 prefixes cover every 5.x release\n * (`claude-opus-5`, `claude-opus-5-5`, `claude-sonnet-5-5`,\n * `claude-fable-5-1`, …). Opus/Sonnet 4.6–4.8 are already covered by the\n * tier-4 prefixes.\n *\n * Matched as a prefix so dated variants (`claude-opus-4-20250514`) are\n * covered without listing every release tag. Devs can always override\n * per-model via `anthropic.model({ name, vision: true | false })` —\n * explicit config wins over inference in either direction.\n */\nconst VISION_CAPABLE_PREFIXES = [\n \"claude-3\",\n \"claude-4\",\n \"claude-opus-4\",\n \"claude-sonnet-4\",\n \"claude-haiku-4\",\n \"claude-opus-5\",\n \"claude-sonnet-5\",\n \"claude-fable-5\",\n \"claude-mythos-5\",\n];\n\n/**\n * Infer whether a given Claude model name supports vision based on the\n * known-prefix list. Unknown models default to `false` so that passing\n * an image attachment to an unsupported model surfaces a clear,\n * agent-side capability error instead of an opaque Anthropic 400.\n *\n * @example\n * inferVisionCapability(\"claude-sonnet-4-6\"); // → true\n * inferVisionCapability(\"claude-3-5-sonnet-latest\"); // → true\n * inferVisionCapability(\"claude-2.1\"); // → false\n * inferVisionCapability(\"custom-proxy-llm\"); // → false\n */\nexport function inferVisionCapability(modelName: string): boolean {\n const normalized = modelName.toLowerCase();\n\n return VISION_CAPABLE_PREFIXES.some((prefix) => normalized.startsWith(prefix));\n}\n","import type { Usage } from \"@warlock.js/ai\";\n\n/** The cache-related fields of an Anthropic usage block (final or streamed). */\nexport type AnthropicCacheUsage = {\n cache_read_input_tokens?: number | null;\n cache_creation_input_tokens?: number | null;\n cache_creation?: {\n ephemeral_1h_input_tokens?: number | null;\n ephemeral_5m_input_tokens?: number | null;\n } | null;\n};\n\n/**\n * Copy Anthropic's cache counters onto a neutral `Usage`.\n *\n * - `cache_read_input_tokens` → `cachedTokens`\n * - `cache_creation_input_tokens` → `cacheWriteTokens`\n * - `cache_creation.ephemeral_1h_input_tokens` → `cacheWrite1hTokens`\n * (the 1-hour writes, billed at 2x input instead of 1.25x)\n *\n * When Anthropic omits the per-lifetime breakdown, `requestTtl` decides:\n * a request whose every cache marker asked for `\"1h\"` wrote only 1-hour\n * entries. Counters are set only when positive, so an absent channel\n * stays undefined. Anthropic's `input_tokens` excludes all of these, so\n * the caller marks the usage `inputIncludesCache: false`.\n */\nexport function applyAnthropicCacheUsage(\n usage: Usage,\n raw: AnthropicCacheUsage,\n requestTtl: RequestCacheTtl,\n): void {\n const cacheRead = raw.cache_read_input_tokens;\n\n if (typeof cacheRead === \"number\" && cacheRead > 0) {\n usage.cachedTokens = cacheRead;\n }\n\n const cacheWrite = raw.cache_creation_input_tokens;\n\n if (typeof cacheWrite !== \"number\" || cacheWrite <= 0) {\n return;\n }\n\n usage.cacheWriteTokens = cacheWrite;\n\n const reported1h = raw.cache_creation?.ephemeral_1h_input_tokens;\n const writes1h =\n typeof reported1h === \"number\" ? reported1h : requestTtl === \"1h\" ? cacheWrite : 0;\n\n if (writes1h > 0) {\n usage.cacheWrite1hTokens = Math.min(writes1h, cacheWrite);\n }\n}\n\n/**\n * The cache lifetime a request body asked for: `\"1h\"` when every\n * `cache_control` marker in it says `ttl: \"1h\"`, `\"5m\"` when every marker\n * uses the default lifetime, `\"mixed\"` when both appear, and `undefined`\n * when the body carries no marker.\n */\nexport type RequestCacheTtl = \"1h\" | \"5m\" | \"mixed\" | undefined;\n\n/**\n * Scan a request body (top level, system, tools, messages) for\n * `cache_control` markers and report the lifetime they request. Used only\n * as a fallback when the response lacks Anthropic's per-lifetime\n * cache-write breakdown.\n *\n * @example\n * requestCacheTtl({ cache_control: { type: \"ephemeral\", ttl: \"1h\" } }); // \"1h\"\n */\nexport function requestCacheTtl(body: unknown): RequestCacheTtl {\n let found: RequestCacheTtl;\n\n const visit = (value: unknown, depth: number): void => {\n if (depth > 8 || typeof value !== \"object\" || value === null) {\n return;\n }\n\n if (Array.isArray(value)) {\n for (const item of value) {\n visit(item, depth + 1);\n }\n\n return;\n }\n\n const record = value as Record<string, unknown>;\n const marker = record.cache_control;\n\n if (typeof marker === \"object\" && marker !== null) {\n const ttl = (marker as { ttl?: unknown }).ttl === \"1h\" ? \"1h\" : \"5m\";\n found = found === undefined || found === ttl ? ttl : \"mixed\";\n }\n\n for (const key of [\"system\", \"tools\", \"messages\", \"content\"] as const) {\n if (key in record) {\n visit(record[key], depth + 1);\n }\n }\n };\n\n visit(body, 0);\n\n return found;\n}\n","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","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","import type { ContentPart, Message, ModelToolCallRequest } from \"@warlock.js/ai\";\nimport type Anthropic from \"@anthropic-ai/sdk\";\nimport { fromProviderBlocks } from \"./provider-blocks\";\n\n/**\n * Result of splitting a vendor-neutral `Message[]` for the Anthropic\n * Messages API: the system prompt is hoisted to a top-level `system`\n * string (Anthropic has no `\"system\"` role inside `messages`), and the\n * remaining turns are mapped to `MessageParam[]`.\n */\nexport type AnthropicMessages = {\n system: string | undefined;\n messages: Anthropic.MessageParam[];\n};\n\n/** Options for {@link toAnthropicMessages}. */\nexport type ToAnthropicMessagesOptions = {\n /**\n * Leave out the `thinking` / `redacted_thinking` blocks of assistant turns\n * marked `compaction: \"retained\"` — turns kept verbatim after a\n * client-written summary. On models that run the preserved-thinking\n * conversation check those blocks were produced against the replaced\n * history, so replaying them is a 400 (or a server-side drop). Text and\n * tool-use blocks stay. Removing them is the no-beta path Anthropic\n * documents for compaction that keeps recent turns.\n */\n dropRetainedThinking?: boolean;\n};\n\nconst ANTHROPIC_IMAGE_MEDIA_TYPES = [\"image/jpeg\", \"image/png\", \"image/gif\", \"image/webp\"] as const;\n\ntype AnthropicImageMediaType = (typeof ANTHROPIC_IMAGE_MEDIA_TYPES)[number];\n\n/**\n * Convert vendor-neutral `Message[]` into Anthropic's request shape.\n *\n * Anthropic differs from the OpenAI Chat protocol in three ways this\n * function absorbs:\n *\n * 1. **No `system` role.** System messages are concatenated (newline-\n * separated) and returned separately as the top-level `system`\n * parameter.\n * 2. **Tool results are `user` turns.** A neutral `tool` message becomes\n * a `tool_result` block keyed by `tool_use_id`. Consecutive tool\n * messages (the results of one parallel tool-use turn) are grouped\n * into a single `user` message, as Anthropic expects — splitting them\n * across messages teaches the model to stop calling tools in parallel.\n * 3. **Tool calls are `tool_use` content blocks.** An assistant message\n * carrying `toolCalls` becomes an `assistant` message whose content\n * is an optional leading `text` block followed by one `tool_use`\n * block per call.\n *\n * An assistant message that carries Anthropic `blocks` (thinking,\n * redacted thinking, compaction, server-tool blocks — see\n * `ProviderContentBlock`) is replayed verbatim from those blocks, which\n * keeps signed thinking and compaction state valid. Blocks from another\n * provider, or blocks whose `tool_use` ids no longer match `toolCalls`,\n * are ignored and the turn is rebuilt from `content` + `toolCalls`.\n *\n * With `dropRetainedThinking`, a turn marked `compaction: \"retained\"` is\n * replayed without its thinking blocks (see {@link ToAnthropicMessagesOptions}).\n *\n * Other consecutive same-role turns are left as-is — the Messages API\n * merges them server-side.\n *\n * @example\n * const { system, messages } = toAnthropicMessages([\n * { role: \"system\", content: \"Be concise.\" },\n * { role: \"user\", content: \"Hi\" },\n * ]);\n * // system === \"Be concise.\"\n * // messages === [{ role: \"user\", content: \"Hi\" }]\n */\nexport function toAnthropicMessages(\n messages: Message[],\n options: ToAnthropicMessagesOptions = {},\n): AnthropicMessages {\n const systemParts: string[] = [];\n const mapped: Anthropic.MessageParam[] = [];\n\n for (const message of messages) {\n if (message.role === \"system\") {\n systemParts.push(stringifyContent(message.content));\n\n continue;\n }\n\n if (message.role === \"tool\") {\n const toolResult: Anthropic.ToolResultBlockParam = {\n type: \"tool_result\",\n tool_use_id: message.toolCallId ?? \"\",\n content: stringifyContent(message.content),\n };\n const previous = mapped[mapped.length - 1];\n\n if (previous && previous.role === \"user\" && isToolResultTurn(previous)) {\n previous.content.push(toolResult);\n } else {\n mapped.push({ role: \"user\", content: [toolResult] });\n }\n\n continue;\n }\n\n const dropThinking = options.dropRetainedThinking === true && message.compaction === \"retained\";\n\n if (message.role === \"assistant\") {\n const replayed = fromProviderBlocks(message.blocks, message.toolCalls);\n const content = dropThinking\n ? replayed?.filter((block) => !isThinkingBlock(block))\n : replayed;\n\n if (content && content.length > 0) {\n mapped.push({ role: \"assistant\", content });\n\n continue;\n }\n }\n\n if (message.role === \"assistant\" && message.toolCalls && message.toolCalls.length > 0) {\n const blocks: Anthropic.ContentBlockParam[] = dropThinking\n ? []\n : extractThinkingBlocks(message.toolCalls);\n const text = stringifyContent(message.content);\n\n if (text) {\n blocks.push({ type: \"text\", text });\n }\n\n for (const toolCall of message.toolCalls) {\n blocks.push({\n type: \"tool_use\",\n id: toolCall.id,\n name: toolCall.name,\n input: toolCall.input ?? {},\n });\n }\n\n mapped.push({ role: \"assistant\", content: blocks });\n\n continue;\n }\n\n if (message.role === \"user\" && Array.isArray(message.content)) {\n mapped.push({\n role: \"user\",\n content: message.content.map(toAnthropicContentBlock),\n });\n\n continue;\n }\n\n mapped.push({\n role: message.role === \"assistant\" ? \"assistant\" : \"user\",\n content: stringifyContent(message.content),\n });\n }\n\n return {\n system: systemParts.length > 0 ? systemParts.join(\"\\n\\n\") : undefined,\n messages: mapped,\n };\n}\n\nfunction isThinkingBlock(block: Anthropic.ContentBlockParam): boolean {\n return block.type === \"thinking\" || block.type === \"redacted_thinking\";\n}\n\n/**\n * Recover signed extended-thinking blocks stored by this adapter on a tool\n * request. Anthropic requires these blocks to be replayed before the\n * assistant's text and tool uses on the following request.\n */\nfunction extractThinkingBlocks(toolCalls: ModelToolCallRequest[]): Anthropic.ContentBlockParam[] {\n for (const toolCall of toolCalls) {\n const anthropic = toolCall.providerMetadata?.anthropic;\n\n if (!isRecord(anthropic) || !Array.isArray(anthropic.thinkingBlocks)) {\n continue;\n }\n\n return anthropic.thinkingBlocks.flatMap(toAnthropicThinkingBlock);\n }\n\n return [];\n}\n\nfunction toAnthropicThinkingBlock(block: unknown): Anthropic.ContentBlockParam[] {\n if (!isRecord(block) || typeof block.type !== \"string\") {\n return [];\n }\n\n if (\n block.type === \"thinking\" &&\n typeof block.thinking === \"string\" &&\n typeof block.signature === \"string\"\n ) {\n return [{ type: \"thinking\", thinking: block.thinking, signature: block.signature }];\n }\n\n if (block.type === \"redacted_thinking\" && typeof block.data === \"string\") {\n return [{ type: \"redacted_thinking\", data: block.data }];\n }\n\n return [];\n}\n\n/**\n * A `user` turn this function built from tool results — its content is a\n * non-empty array made only of `tool_result` blocks. Later tool results\n * of the same tool-use turn are appended to it.\n */\nfunction isToolResultTurn(\n message: Anthropic.MessageParam,\n): message is Anthropic.MessageParam & { content: Anthropic.ContentBlockParam[] } {\n return (\n Array.isArray(message.content) &&\n message.content.length > 0 &&\n message.content.every((block) => block.type === \"tool_result\")\n );\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\n/**\n * Multipart content is only meaningful on user messages — for any other\n * role collapse a `ContentPart[]` to its concatenated text so the wire\n * format stays valid. Plain strings pass through unchanged.\n */\nfunction stringifyContent(content: string | ContentPart[]): string {\n if (typeof content === \"string\") {\n return content;\n }\n\n return content\n .filter((part): part is { type: \"text\"; text: string } => part.type === \"text\")\n .map((part) => part.text)\n .join(\"\");\n}\n\n/**\n * Map a single resolved `ContentPart` to an Anthropic content block.\n * Text passes straight through; images become an `image` block with a\n * `url` source (remote) or a `base64` source (inlined bytes). The\n * agent has already resolved every attachment before it reaches here,\n * so this never reads files or fetches URLs.\n */\nfunction toAnthropicContentBlock(part: ContentPart): Anthropic.ContentBlockParam {\n if (part.type === \"text\") {\n return { type: \"text\", text: part.text };\n }\n\n // PDF → Anthropic `document` block (A2). The Messages API accepts a\n // url or base64 `application/pdf` source on PDF-capable Claude models.\n if (part.type === \"pdf\") {\n const source =\n \"url\" in part.source\n ? { type: \"url\", url: part.source.url }\n : { type: \"base64\", media_type: \"application/pdf\", data: part.source.base64 };\n return { type: \"document\", source } as unknown as Anthropic.ContentBlockParam;\n }\n\n // Anthropic has no audio content block; the agent's capability gate\n // normally prevents this, but stay loud rather than mis-map it.\n if (part.type === \"audio\") {\n throw new Error(\"Anthropic adapter: audio attachments are not supported\");\n }\n\n if (\"url\" in part.source) {\n return { type: \"image\", source: { type: \"url\", url: part.source.url } };\n }\n\n return {\n type: \"image\",\n source: {\n type: \"base64\",\n media_type: part.source.mediaType as AnthropicImageMediaType,\n data: part.source.base64,\n },\n };\n}\n","import { extractJsonSchema, type ToolConfig } from \"@warlock.js/ai\";\nimport type Anthropic from \"@anthropic-ai/sdk\";\n\n/**\n * Convert vendor-neutral `ToolConfig[]` into Anthropic's `tools` array.\n * Uses the shared `extractJsonSchema` helper; Anthropic requires the\n * input schema to be a JSON-Schema object, so a non-object extraction\n * is coerced into an empty-object schema rather than rejected — the\n * tool still registers and the model simply sees no parameters.\n *\n * @example\n * const tools = toAnthropicTools([weatherTool, calculatorTool]);\n * await client.messages.create({ model, max_tokens, messages, tools });\n */\nexport function toAnthropicTools(\n tools: ToolConfig<unknown, unknown>[] | undefined,\n): Anthropic.Tool[] | undefined {\n if (!tools || tools.length === 0) {\n return undefined;\n }\n\n return tools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n input_schema: toInputSchema(tool.input),\n }));\n}\n\n/**\n * Coerce the extracted JSON Schema into Anthropic's `Tool.InputSchema`\n * shape (root must be `{ type: \"object\" }`). Anything that isn't an\n * object schema degrades to a parameterless object so registration\n * never fails on a malformed extractor result.\n */\nfunction toInputSchema(input: ToolConfig<unknown, unknown>[\"input\"]): Anthropic.Tool.InputSchema {\n const schema = extractJsonSchema(input);\n\n if (schema && schema.type === \"object\") {\n return schema as Anthropic.Tool.InputSchema;\n }\n\n return { type: \"object\" };\n}\n","import {\n AIError,\n ContextLengthExceededError,\n InvalidRequestError,\n ProviderAuthError,\n ProviderError,\n ProviderOverloadedError,\n ProviderRateLimitError,\n ProviderTimeoutError,\n QuotaExceededError,\n} from \"@warlock.js/ai\";\nimport { APIConnectionTimeoutError, APIError } from \"@anthropic-ai/sdk\";\n\n/**\n * Raw-error fields the wrapper reads off an Anthropic SDK error.\n *\n * `APIError` exposes `status`, `type` (the `error.type` from the\n * response body, e.g. `\"rate_limit_error\"`), `message`, `headers`, and\n * `requestID`. We duck-type because wrapped retries, proxied errors,\n * and custom subclasses sometimes lose the `instanceof` relationship.\n */\ntype AnthropicErrorShape = {\n status?: number;\n type?: string | null;\n message?: string;\n headers?: HeaderBag | undefined;\n name?: string;\n requestId?: string;\n};\n\n/** Either a fetch `Headers` instance or a plain record (duck-typed tests). */\ntype HeaderBag = Headers | Record<string, string>;\n\n/**\n * Wrap any thrown value caught inside the Anthropic adapter into the\n * appropriate `@warlock.js/ai` `AIError` subclass.\n *\n * **Dispatch strategy.** Anthropic has no per-error machine `code`; the\n * stable identifier is `error.type` on the response body (surfaced as\n * `APIError.type`). Dispatch prefers `type`, falls back to `status`\n * when the body was stripped (common with proxies). Name-based\n * detection catches transport-layer timeouts that never produced an\n * HTTP response. The `invalid_request_error` branch additionally\n * sniffs the message for Anthropic's \"prompt is too long\" phrasing,\n * which is the only signal that a 400 was a context-length overflow.\n *\n * `AIError` instances pass through unchanged so `catch/throw wrap(e)`\n * pipelines never double-wrap.\n *\n * @example\n * try {\n * return await this.client.messages.create(...);\n * } catch (thrown) {\n * throw wrapAnthropicError(thrown);\n * }\n */\nexport function wrapAnthropicError(thrown: unknown): AIError {\n if (thrown instanceof AIError) {\n return thrown;\n }\n\n const shape = toShape(thrown);\n const context = buildContext(shape);\n const message = shape.message ?? (thrown instanceof Error ? thrown.message : String(thrown));\n\n if (isTimeout(thrown, shape)) {\n return new ProviderTimeoutError(message, { cause: thrown, context });\n }\n\n if (shape.type === \"authentication_error\" || shape.type === \"permission_error\") {\n return new ProviderAuthError(message, { cause: thrown, context });\n }\n\n if (shape.status === 401 || shape.status === 403) {\n return new ProviderAuthError(message, { cause: thrown, context });\n }\n\n if (shape.type === \"billing_error\") {\n return new QuotaExceededError(message, { cause: thrown, context });\n }\n\n if (shape.type === \"rate_limit_error\" || shape.status === 429) {\n return new ProviderRateLimitError(message, {\n cause: thrown,\n context,\n retryAfter: parseRetryAfter(shape.headers),\n });\n }\n\n // HTTP 529 / `overloaded_error` — also delivered as a mid-stream SSE\n // `error` event, where no status exists.\n if (shape.type === \"overloaded_error\" || shape.status === 529) {\n return new ProviderOverloadedError(message, {\n cause: thrown,\n context,\n retryAfter: parseRetryAfter(shape.headers),\n });\n }\n\n if (shape.type === \"invalid_request_error\" || isClientStatus(shape.status)) {\n if (/prompt is too long/i.test(message)) {\n return new ContextLengthExceededError(message, { cause: thrown, context });\n }\n\n return new InvalidRequestError(message, { cause: thrown, context });\n }\n\n return new ProviderError(message, { cause: thrown, context });\n}\n\n/**\n * Read the raw error shape without depending on `instanceof APIError`\n * — proxies and re-wrappers strip the prototype chain. Duck-typing on\n * the visible fields is resilient to both.\n */\nfunction toShape(thrown: unknown): AnthropicErrorShape {\n if (thrown instanceof APIError) {\n return {\n status: typeof thrown.status === \"number\" ? thrown.status : undefined,\n type: thrown.type,\n message: thrown.message,\n headers: thrown.headers,\n name: thrown.name,\n requestId: thrown.requestID ?? undefined,\n };\n }\n\n if (typeof thrown === \"object\" && thrown !== null) {\n const raw = thrown as Record<string, unknown>;\n\n return {\n status: typeof raw.status === \"number\" ? raw.status : undefined,\n type: typeof raw.type === \"string\" ? raw.type : undefined,\n message: typeof raw.message === \"string\" ? raw.message : undefined,\n headers: isHeaderBag(raw.headers) ? raw.headers : undefined,\n name: typeof raw.name === \"string\" ? raw.name : undefined,\n requestId: readRequestId(raw),\n };\n }\n\n return {};\n}\n\n/**\n * Decide whether the thrown value represents a timeout. The Anthropic\n * SDK throws `APIConnectionTimeoutError` for transport-level timeouts;\n * Node surfaces `ETIMEDOUT` / `ECONNABORTED` on the socket layer.\n * Either signal counts.\n */\nfunction isTimeout(thrown: unknown, shape: AnthropicErrorShape): boolean {\n if (thrown instanceof APIConnectionTimeoutError) {\n return true;\n }\n\n if (shape.name === \"APIConnectionTimeoutError\") {\n return true;\n }\n\n if (typeof thrown === \"object\" && thrown !== null) {\n const code = (thrown as Record<string, unknown>).code;\n\n if (code === \"ETIMEDOUT\" || code === \"ECONNABORTED\") {\n return true;\n }\n }\n\n return false;\n}\n\n/** True for HTTP 4xx — a client-side request problem, not a server fault. */\nfunction isClientStatus(status: number | undefined): boolean {\n return typeof status === \"number\" && status >= 400 && status < 500;\n}\n\n/**\n * Attach the raw diagnostic fields to `error.context` so consumers\n * have everything the provider surfaced without each subclass having\n * to redeclare them. Never includes `cause` — that lives on\n * `error.cause`.\n */\nfunction buildContext(shape: AnthropicErrorShape): Record<string, unknown> {\n const context: Record<string, unknown> = {};\n\n if (shape.status !== undefined) {\n context.status = shape.status;\n }\n\n if (shape.type) {\n context.type = shape.type;\n }\n\n if (shape.requestId) {\n context.requestId = shape.requestId;\n }\n\n return context;\n}\n\n/** Anthropic exposes the request id as `requestID`; some proxies use `request_id`. */\nfunction readRequestId(raw: Record<string, unknown>): string | undefined {\n if (typeof raw.requestID === \"string\") {\n return raw.requestID;\n }\n\n if (typeof raw.request_id === \"string\") {\n return raw.request_id;\n }\n\n return undefined;\n}\n\nfunction isHeaderBag(value: unknown): value is HeaderBag {\n return typeof value === \"object\" && value !== null;\n}\n\n/** Read a header value from either a `Headers` instance or a plain record. */\nfunction readHeader(headers: HeaderBag, name: string): string | undefined {\n if (typeof (headers as Headers).get === \"function\") {\n return (headers as Headers).get(name) ?? undefined;\n }\n\n const record = headers as Record<string, string>;\n\n return record[name] ?? record[name.toLowerCase()];\n}\n\n/**\n * Parse the `Retry-After` response header (seconds per HTTP spec) into\n * milliseconds so consumers can feed it straight to `setTimeout`.\n * Returns `undefined` when missing or unparseable.\n */\nfunction parseRetryAfter(headers: HeaderBag | undefined): number | undefined {\n if (!headers) {\n return undefined;\n }\n\n const raw = readHeader(headers, \"retry-after\") ?? readHeader(headers, \"Retry-After\");\n\n if (!raw) {\n return undefined;\n }\n\n const seconds = Number(raw);\n\n if (!Number.isFinite(seconds) || seconds < 0) {\n return undefined;\n }\n\n return Math.round(seconds * 1000);\n}\n","import {\n AIError,\n computeCost,\n InvalidRequestError,\n resolveStreamChunks,\n safeJsonParse,\n selectProviderTools,\n type Message,\n type ModelCallOptions,\n type ModelCapabilities,\n type ModelContract,\n type ModelPricing,\n type ModelResponse,\n type ModelStreamChunk,\n type ModelToolCallRequest,\n type ReasoningEffort,\n type Usage,\n} from \"@warlock.js/ai\";\nimport { log, type Logger } from \"@warlock.js/logger\";\nimport type Anthropic from \"@anthropic-ai/sdk\";\nimport type {\n AnthropicCallOptions,\n AnthropicClearThinking,\n AnthropicClearToolUses,\n AnthropicModelConfig,\n} from \"./config.type\";\nimport type {\n AnthropicRequest,\n AnthropicRequestOptions,\n AnthropicStreamingRequest,\n AnthropicNonStreamingRequest,\n} from \"./request.type\";\nimport { anthropicPricingFor, withAnthropicCacheWriteRates } from \"./known-pricing\";\nimport { inferMaxOutputTokens } from \"./known-output-limits\";\nimport { inferVisionCapability } from \"./known-vision-models\";\nimport {\n acceptsTemperature,\n inferPreservedThinking,\n inferThinkingMode,\n type AnthropicThinkingMode,\n noReasoningForm,\n} from \"./thinking-mode\";\nimport { applyAnthropicCacheUsage, requestCacheTtl } from \"./utils/cache-usage\";\nimport {\n mapStopReason,\n toAnthropicMessages,\n toAnthropicTools,\n toProviderBlocks,\n wrapAnthropicError,\n} from \"./utils\";\n\nconst LOG_MODULE = \"ai.anthropic\";\n\n/** `provider` value of `ai.providerTool()` entries this adapter sends verbatim. */\nconst ANTHROPIC_WIRE_FORMAT = \"anthropic\";\n\n/**\n * Anthropic requires `max_tokens` on every request (unlike OpenAI,\n * where it is optional). When neither the per-call option nor the model\n * config supplies one, the adapter picks a default large enough for agent\n * work (see `resolveDefaultMaxTokens`):\n *\n * - streaming: the model's documented max output (`known-output-limits.ts`,\n * or `config.maxOutputTokens`), else this value;\n * - non-streaming: this value, capped by the model's max output. The\n * installed `@anthropic-ai/sdk` (0.129.0, `calculateNonstreamingTimeout`)\n * refuses a non-streaming request whose `max_tokens` implies more than\n * ten minutes (above ~21,333 tokens) unless the client sets a `timeout`,\n * so the non-streaming default stays below that.\n */\nconst DEFAULT_MAX_TOKENS = 16_384;\n\n/**\n * Answer room kept on top of a thinking budget when the default\n * `max_tokens` is sized: thinking counts toward `max_tokens` (installed\n * SDK `ThinkingConfigParam` docs, `messages.d.ts:1105`), and in budget\n * mode `max_tokens` must exceed `budget_tokens`.\n */\nconst MIN_ANSWER_TOKENS = 4096;\n\n/**\n * Anthropic rejects an extended-thinking budget below 1024 tokens, so\n * any resolved budget is floored at this minimum before it reaches the\n * wire.\n */\nconst MIN_THINKING_BUDGET = 1024;\n\ntype ThinkingEffort = Exclude<ReasoningEffort, \"none\">;\n\n/**\n * Effort used when the caller asks for reasoning with only\n * `reasoning.maxTokens` and no `effort`. `\"medium\"` is what the adapter\n * has always assumed (the budget lookup fell back to\n * `EFFORT_THINKING_BUDGET.medium`), so adaptive models get the same tier.\n */\nconst DEFAULT_THINKING_EFFORT: ThinkingEffort = \"medium\";\n\n/**\n * Map the neutral `ReasoningEffort` level to a thinking token count.\n *\n * - Budget-mode models: sent as `thinking.budget_tokens` when the caller\n * doesn't pass an explicit `reasoning.maxTokens`.\n * - Both modes: when the caller sets no `maxTokens`, the default\n * `max_tokens` keeps at least this budget plus `MIN_ANSWER_TOKENS`,\n * because thinking counts toward `max_tokens` (installed SDK\n * `ThinkingConfigParam` docs, `messages.d.ts:1105`).\n */\nconst EFFORT_THINKING_BUDGET: Record<ThinkingEffort, number> = {\n // Anthropic's adaptive output config has no `minimal`; keep the minimum\n // budget for it in legacy budget mode too.\n minimal: 1024,\n low: 1024,\n medium: 4096,\n high: 12000,\n // Keep the tiers monotonic for older budget-mode models. Explicit\n // reasoning.maxTokens still wins and the existing max_tokens validation\n // remains authoritative.\n xhigh: 24000,\n max: 32000,\n};\n\n/**\n * Map the neutral `ReasoningEffort` level to Anthropic's\n * `output_config.effort` for adaptive-mode models. The installed SDK\n * accepts `low | medium | high | xhigh | max` (`OutputConfig.effort`,\n * `messages.ts:2767`); map every supported value 1:1 and clamp `minimal` to\n * the nearest accepted value, `low`.\n */\nconst EFFORT_TO_OUTPUT_EFFORT: Record<\n ThinkingEffort,\n NonNullable<Anthropic.OutputConfig[\"effort\"]>\n> = {\n minimal: \"low\",\n low: \"low\",\n medium: \"medium\",\n high: \"high\",\n xhigh: \"xhigh\",\n max: \"max\",\n};\n\ntype AnthropicThinkingBlock = Anthropic.ThinkingBlock | Anthropic.RedactedThinkingBlock;\n\n/**\n * The SDK's `messages.create` (or `beta.messages.create`) seen through a\n * loose signature: provider-option body fields and beta flags are merged\n * in untyped, and the response is narrowed by the caller.\n */\ntype LooseCreate = (\n body: Record<string, unknown>,\n options?: { signal?: AbortSignal },\n) => Promise<unknown>;\n\n/** Content-block types whose input arrives as `input_json_delta` while streaming. */\nconst STREAMED_INPUT_BLOCK_TYPES = new Set([\"tool_use\", \"server_tool_use\", \"mcp_tool_use\"]);\n\n/** One content block being assembled from stream events. */\ntype StreamedBlock = { block: Record<string, unknown>; json?: string };\n\n/**\n * Resolved thinking settings for one request.\n *\n * - `thinking`: the wire `thinking` field (absent = send nothing).\n * - `effort`: `output_config.effort`, set for adaptive-mode models only.\n * - `reservedTokens`: thinking tokens the default `max_tokens` must leave\n * room for (plus `MIN_ANSWER_TOKENS`) when the caller configured no\n * `maxTokens`.\n */\ntype ThinkingRequest = {\n thinking?: Anthropic.ThinkingConfigParam;\n effort?: Anthropic.OutputConfig[\"effort\"];\n reservedTokens?: number;\n};\n\n/**\n * Anthropic-backed implementation of `ModelContract`.\n *\n * **Role.** The provider-facing bridge between the vendor-neutral\n * `@warlock.js/ai` agent runtime and the official `@anthropic-ai/sdk`\n * Messages API. Agents, workflows, and supervisors never talk to\n * Anthropic directly — they hold a `ModelContract`, and this class is\n * what makes that contract concrete for Claude models.\n *\n * **Responsibility.**\n * - Owns: a long-lived `Anthropic` client + frozen `ModelConfig`\n * (name, temperature, maxTokens) used as defaults for every call.\n * - Owns: translating vendor-neutral `Message[]` / `ToolConfig[]` into\n * Anthropic wire shapes (system hoisting, `tool_use` / `tool_result`\n * blocks) on the way out, and translating Anthropic's content-block\n * response (text, tool calls, stop reason, usage) back into the\n * neutral shapes on the way in.\n * - Does NOT own: dispatching tools, deciding whether to loop, tracking\n * conversation history, or retrying on failure — those are agent\n * concerns. The model is a stateless (per-call) protocol adapter.\n *\n * Because it holds a live client and shared defaults, it is modeled as\n * a class (see §4.2 of code-style.md — \"long-lived state across\n * calls\").\n *\n * @example\n * import Anthropic from \"@anthropic-ai/sdk\";\n * const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });\n * const model = new AnthropicModel(client, { name: \"claude-sonnet-4-6\" });\n *\n * const myAgent = agent({\n * model,\n * systemPrompt: \"You are a helpful assistant.\",\n * tools: [searchTool],\n * });\n *\n * const result = await myAgent.execute(\"Summarize today's news.\");\n */\nexport class AnthropicModel implements ModelContract {\n public readonly name: string;\n public readonly provider: string;\n public readonly capabilities: ModelCapabilities;\n public readonly pricing?: ModelPricing;\n\n private readonly client: Anthropic;\n private readonly config: AnthropicModelConfig;\n private readonly thinkingMode: AnthropicThinkingMode;\n /** Documented max output tokens of this model, when known. Sizes the default `max_tokens`. */\n private readonly maxOutputTokens?: number;\n private readonly preservedThinking: boolean;\n private readonly logger: Logger = log;\n\n public constructor(\n client: Anthropic,\n config: AnthropicModelConfig,\n provider: string = \"anthropic\",\n ) {\n this.client = client;\n this.config = config;\n this.name = config.name;\n this.provider = provider;\n // Explicit pricing (per-model, or the SDK registry) wins over the\n // built-in Claude list prices; either way the Anthropic cache-write\n // multipliers fill any write rate the entry leaves out.\n this.pricing = withAnthropicCacheWriteRates(config.pricing ?? anthropicPricingFor(config.name));\n // Adaptive vs budget thinking — also decides whether `temperature` is\n // accepted. Explicit config wins over name inference, like `vision`.\n this.thinkingMode = config.thinkingMode ?? inferThinkingMode(config.name);\n this.maxOutputTokens = config.maxOutputTokens ?? inferMaxOutputTokens(config.name);\n // Budget-mode models predate preserved thinking; explicit config wins.\n this.preservedThinking =\n config.preservedThinking ??\n (this.thinkingMode === \"adaptive\" && inferPreservedThinking(config.name));\n this.capabilities = {\n structuredOutput: config.structuredOutput ?? true,\n vision: config.vision ?? inferVisionCapability(config.name),\n // Every modern Claude model accepts Anthropic extended thinking\n // (adaptive or `budget_tokens`, per `thinkingMode`). Advertise the\n // reasoning channel so the agent forwards `reasoning` options;\n // explicit config override wins for proxied/legacy targets.\n reasoning: config.reasoning ?? true,\n // Anthropic prompt caching is caller-driven via `cache_control`\n // breakpoints. The adapter both places those breakpoints (tools\n // when `config.promptCaching`, system when\n // `options.cacheControl.breakpoints`) and reports the read/write\n // accounting (`cachedTokens` / `cacheWriteTokens`), so advertise\n // the capability unconditionally.\n promptCaching: true,\n // The Messages API accepts PDF/document content blocks\n // (`DocumentBlockParam`) on vision-capable Claude models.\n pdf: true,\n // Anthropic has no audio input content block, so `audio` stays\n // absent (treated as false) and the agent rejects audio\n // attachments upfront rather than dropping them at the wire layer.\n };\n }\n\n /**\n * Single-shot completion. Sends the full message list to the Messages\n * endpoint, waits for the terminal response, and reshapes it into a\n * vendor-neutral `ModelResponse`. Per-call `options` override the\n * instance's `ModelConfig` defaults for this call only.\n */\n public async complete(messages: Message[], options?: ModelCallOptions): Promise<ModelResponse> {\n return this.send(this.buildLoggedRequest(messages, { ...options, stream: false }), {\n signal: options?.signal,\n });\n }\n\n /** Build a detached request snapshot without sending it to Anthropic. */\n public buildRequest(\n messages: Message[],\n options: ModelCallOptions & { stream: true },\n ): AnthropicStreamingRequest;\n public buildRequest(\n messages: Message[],\n options?: ModelCallOptions & { stream?: false },\n ): AnthropicNonStreamingRequest;\n public buildRequest(\n messages: Message[],\n options?: ModelCallOptions & { stream?: boolean },\n ): AnthropicRequest;\n public buildRequest(\n messages: Message[],\n options?: ModelCallOptions & { stream?: boolean },\n ): AnthropicRequest {\n const built = this.buildBody(messages, options);\n const betas = [...new Set([...(resolveAnthropicOptions(options).betas ?? []), ...built.betas])];\n const body = structuredClone({ ...built.body, stream: options?.stream ?? false });\n\n return { endpoint: betas.length > 0 ? \"beta.messages\" : \"messages\", body, betas };\n }\n\n /**\n * `buildRequest()` for the adapter's own calls: a build failure (a reserved\n * body key, a `providerOptions.anthropic.body` value `structuredClone`\n * cannot copy) is logged like a send failure and rejects as an `AIError`.\n * Errors that are not already an `AIError` become an `InvalidRequestError`,\n * since nothing reached Anthropic and retrying cannot help.\n */\n private buildLoggedRequest(\n messages: Message[],\n options: ModelCallOptions & { stream: true },\n ): AnthropicStreamingRequest;\n private buildLoggedRequest(\n messages: Message[],\n options: ModelCallOptions & { stream: false },\n ): AnthropicNonStreamingRequest;\n private buildLoggedRequest(\n messages: Message[],\n options: ModelCallOptions & { stream: boolean },\n ): AnthropicRequest;\n private buildLoggedRequest(\n messages: Message[],\n options: ModelCallOptions & { stream: boolean },\n ): AnthropicRequest {\n try {\n return this.buildRequest(messages, options);\n } catch (thrown) {\n throw this.logAndWrap(\n thrown instanceof AIError\n ? thrown\n : new InvalidRequestError(\n `Could not build the Anthropic request: ${thrown instanceof Error ? thrown.message : String(thrown)}`,\n { cause: thrown },\n ),\n );\n }\n }\n\n /** Send a built request without rebuilding its body or applying model defaults. */\n public send(\n request: AnthropicNonStreamingRequest,\n options?: AnthropicRequestOptions,\n ): Promise<ModelResponse>;\n public send(\n request: AnthropicStreamingRequest,\n options?: AnthropicRequestOptions,\n ): AsyncIterable<ModelStreamChunk>;\n public send(\n request: AnthropicRequest,\n options?: AnthropicRequestOptions,\n ): Promise<ModelResponse> | AsyncIterable<ModelStreamChunk>;\n public send(\n request: AnthropicRequest,\n options?: AnthropicRequestOptions,\n ): Promise<ModelResponse> | AsyncIterable<ModelStreamChunk> {\n const message = request.body.stream\n ? \"Starting streaming call to messages.create\"\n : \"Starting call to messages.create\";\n\n this.logger.debug(LOG_MODULE, \"request\", message, {\n model: request.body.model,\n messageCount: Array.isArray(request.body.messages) ? request.body.messages.length : 0,\n streaming: request.body.stream,\n toolCount: Array.isArray(request.body.tools) ? request.body.tools.length : 0,\n });\n\n return request.body.stream\n ? this.streamRequest(request, options)\n : this.completeRequest(request, options);\n }\n\n private async completeRequest(\n request: AnthropicRequest,\n options?: AnthropicRequestOptions,\n ): Promise<ModelResponse> {\n let response: Anthropic.Message;\n\n try {\n response = (await this.dispatch(request, options, \"create\")) as Anthropic.Message;\n } catch (thrown) {\n throw this.logAndWrap(thrown);\n }\n\n const finishReason = mapStopReason(response.stop_reason);\n const usage = this.extractUsage(response.usage, requestCacheTtl(request.body));\n const toolCalls = this.extractToolCalls(response.content);\n const blocks = toProviderBlocks(response.content);\n\n this.logger.debug(LOG_MODULE, \"response\", \"call to messages.create succeeded\", {\n finishReason,\n usage,\n });\n\n return {\n content: this.extractText(response.content),\n finishReason,\n usage,\n toolCalls,\n ...(blocks ? { blocks } : {}),\n };\n }\n\n /**\n * Count the input tokens a request would use, through Anthropic's\n * `messages.countTokens` endpoint (a network call; no tokens are\n * generated or billed as output). Takes the same messages and options\n * as `complete()` — system prompt, tools, thinking and\n * `providerOptions.anthropic.betas` are counted exactly as they would be\n * sent. For an offline estimate use `AnthropicSDK.count()`.\n *\n * @example\n * const tokens = await model.countTokens(messages, { tools });\n */\n public async countTokens(messages: Message[], options?: ModelCallOptions): Promise<number> {\n const request = this.buildLoggedRequest(messages, {\n ...options,\n stream: options?.stream === true,\n });\n const body = request.body;\n const countBody: Record<string, unknown> = {};\n\n for (const key of COUNT_TOKENS_FIELDS) {\n if (body[key] !== undefined) {\n countBody[key] = body[key];\n }\n }\n\n try {\n const result = (await this.dispatch(\n { ...request, body: countBody },\n options,\n \"countTokens\",\n )) as {\n input_tokens: number;\n };\n\n return result.input_tokens;\n } catch (thrown) {\n throw this.logAndWrap(thrown);\n }\n }\n\n /**\n * Incremental streaming completion. Yields neutral `ModelStreamChunk`s\n * — `delta` for text tokens, `tool-call` once a `tool_use` block's\n * arguments have fully accumulated, and a terminal `done` carrying the\n * final finish reason + usage totals. Callers consume it with\n * `for await`.\n *\n * With `options.streamChunks` it also yields `reasoning` for every\n * non-empty `thinking_delta`, `tool-args` for every `input_json_delta`\n * of a client `tool_use` block, and `usage` after `message_start` and\n * each `message_delta` (whose counts are cumulative).\n */\n public async *stream(\n messages: Message[],\n options?: ModelCallOptions,\n ): AsyncIterable<ModelStreamChunk> {\n yield* this.send(this.buildLoggedRequest(messages, { ...options, stream: true }), {\n signal: options?.signal,\n streamChunks: options?.streamChunks,\n });\n }\n\n private async *streamRequest(\n request: AnthropicRequest,\n options?: AnthropicRequestOptions,\n ): AsyncIterable<ModelStreamChunk> {\n let stream: AsyncIterable<Anthropic.RawMessageStreamEvent>;\n\n try {\n stream = (await this.dispatch(\n request,\n options,\n \"create\",\n )) as AsyncIterable<Anthropic.RawMessageStreamEvent>;\n } catch (thrown) {\n throw this.logAndWrap(thrown);\n }\n\n let rawStopReason: string | null = null;\n let compaction = compactionIterationUsage(undefined);\n const usage: Usage = { input: 0, output: 0, total: 0, inputIncludesCache: false };\n const cacheTtl = requestCacheTtl(request.body);\n const want = resolveStreamChunks(options);\n const toolBlocks = new Map<number, { id: string; name: string; json: string }>();\n const thinkingBlocks = new Map<number, AnthropicThinkingBlock>();\n // Every content block of the turn, by index, so the full ordered turn\n // can be returned as `blocks` (thinking, compaction, server tools…).\n const streamedBlocks = new Map<number, StreamedBlock>();\n\n try {\n for await (const event of stream) {\n this.trackStreamedBlock(streamedBlocks, event);\n\n if (event.type === \"message_start\") {\n usage.input = event.message.usage.input_tokens ?? 0;\n\n const thinkingTokens = event.message.usage.output_tokens_details?.thinking_tokens;\n\n if (thinkingTokens !== null && thinkingTokens !== undefined) {\n usage.reasoningTokens = thinkingTokens;\n }\n\n applyAnthropicCacheUsage(usage, event.message.usage, cacheTtl);\n\n if (want.usage) {\n yield { type: \"usage\", usage: { ...usage, total: usage.input + usage.output } };\n }\n\n continue;\n }\n\n if (event.type === \"content_block_start\") {\n const block = event.content_block;\n\n if (block.type === \"tool_use\") {\n toolBlocks.set(event.index, { id: block.id, name: block.name, json: \"\" });\n } else if (block.type === \"thinking\") {\n thinkingBlocks.set(event.index, { ...block });\n } else if (block.type === \"redacted_thinking\") {\n thinkingBlocks.set(event.index, { ...block });\n }\n\n continue;\n }\n\n if (event.type === \"content_block_delta\") {\n if (event.delta.type === \"text_delta\") {\n yield { type: \"delta\", content: event.delta.text };\n } else if (event.delta.type === \"input_json_delta\") {\n const accumulator = toolBlocks.get(event.index);\n\n if (accumulator) {\n accumulator.json += event.delta.partial_json;\n\n // Only client `tool_use` blocks: a `server_tool_use` input\n // (e.g. a web search query) never becomes a `tool-call`.\n if (want.toolArgs && event.delta.partial_json !== \"\") {\n yield {\n type: \"tool-args\",\n callId: accumulator.id,\n name: accumulator.name,\n delta: event.delta.partial_json,\n };\n }\n }\n } else if (event.delta.type === \"thinking_delta\") {\n const thinking = thinkingBlocks.get(event.index);\n\n if (thinking?.type === \"thinking\") {\n thinking.thinking += event.delta.thinking;\n }\n\n // `display: \"omitted\"` streams one empty `thinking_delta`.\n if (want.reasoning && event.delta.thinking !== \"\") {\n yield { type: \"reasoning\", delta: event.delta.thinking };\n }\n } else if (event.delta.type === \"signature_delta\") {\n const thinking = thinkingBlocks.get(event.index);\n\n if (thinking?.type === \"thinking\") {\n thinking.signature += event.delta.signature;\n }\n }\n\n continue;\n }\n\n if (event.type === \"content_block_stop\") {\n const accumulator = toolBlocks.get(event.index);\n\n if (accumulator) {\n yield {\n type: \"tool-call\",\n id: accumulator.id,\n name: accumulator.name,\n input: safeJsonParse<Record<string, unknown>>(accumulator.json, {}),\n ...this.buildThinkingMetadata(\n Array.from(thinkingBlocks.entries())\n .sort(([left], [right]) => left - right)\n .map(([, block]) => block),\n ),\n };\n\n toolBlocks.delete(event.index);\n }\n\n continue;\n }\n\n if (event.type === \"message_delta\") {\n rawStopReason = event.delta.stop_reason ?? rawStopReason;\n // The final delta carries every iteration of the request.\n if (Array.isArray((event.usage as { iterations?: unknown }).iterations)) {\n compaction = compactionIterationUsage(event.usage);\n }\n usage.output = event.usage.output_tokens ?? usage.output;\n\n const thinkingTokens = event.usage.output_tokens_details?.thinking_tokens;\n\n if (thinkingTokens !== null && thinkingTokens !== undefined) {\n usage.reasoningTokens = thinkingTokens;\n }\n\n // `message_delta.usage` carries the cumulative cache counts —\n // prefer them over the `message_start` snapshot when present\n // and non-zero so the terminal `done` reflects the final tally.\n // It has no per-lifetime breakdown, so a 1-hour share already\n // read from `message_start` is kept.\n applyAnthropicCacheUsage(\n usage,\n {\n cache_read_input_tokens: event.usage.cache_read_input_tokens,\n cache_creation_input_tokens: event.usage.cache_creation_input_tokens,\n cache_creation:\n usage.cacheWrite1hTokens !== undefined\n ? { ephemeral_1h_input_tokens: usage.cacheWrite1hTokens }\n : undefined,\n },\n cacheTtl,\n );\n\n // `message_delta.usage` counts are cumulative (Anthropic streaming\n // docs), so this is the running total so far.\n if (want.usage) {\n yield { type: \"usage\", usage: { ...usage, total: usage.input + usage.output } };\n }\n }\n }\n } catch (thrown) {\n throw this.logAndWrap(thrown);\n }\n\n usage.input += compaction.input;\n usage.output += compaction.output;\n addCacheCounts(usage, compaction);\n usage.total = usage.input + usage.output;\n\n const cost = computeCost(usage, this.pricing);\n\n if (cost) {\n usage.cost = cost;\n }\n\n const finishReason = mapStopReason(rawStopReason);\n const blocks = toProviderBlocks(this.finishStreamedBlocks(streamedBlocks));\n\n this.logger.debug(LOG_MODULE, \"response\", \"Streaming call to messages.create succeeded\", {\n finishReason,\n usage,\n });\n\n yield { type: \"done\", finishReason, usage, ...(blocks ? { blocks } : {}) };\n }\n\n /**\n * Fold one stream event into the per-index block accumulator. Unknown\n * block and delta types (beta `compaction`, future additions) are kept\n * as their start payload plus whatever their delta carries, so they\n * round-trip without the adapter knowing their shape.\n */\n private trackStreamedBlock(\n blocks: Map<number, StreamedBlock>,\n event: Anthropic.RawMessageStreamEvent,\n ): void {\n if (event.type === \"content_block_start\") {\n const block = { ...(event.content_block as unknown as Record<string, unknown>) };\n\n blocks.set(event.index, {\n block,\n ...(STREAMED_INPUT_BLOCK_TYPES.has(String(block.type)) ? { json: \"\" } : {}),\n });\n\n return;\n }\n\n if (event.type !== \"content_block_delta\") {\n return;\n }\n\n const entry = blocks.get(event.index);\n\n if (!entry) {\n return;\n }\n\n const delta = event.delta as unknown as Record<string, unknown> & { type: string };\n const block = entry.block;\n\n if (delta.type === \"text_delta\") {\n block.text = String(block.text ?? \"\") + String(delta.text ?? \"\");\n } else if (delta.type === \"thinking_delta\") {\n block.thinking = String(block.thinking ?? \"\") + String(delta.thinking ?? \"\");\n } else if (delta.type === \"signature_delta\") {\n block.signature = String(block.signature ?? \"\") + String(delta.signature ?? \"\");\n } else if (delta.type === \"input_json_delta\") {\n entry.json = (entry.json ?? \"\") + String(delta.partial_json ?? \"\");\n } else if (delta.type === \"citations_delta\") {\n block.citations = [\n ...(Array.isArray(block.citations) ? block.citations : []),\n delta.citation,\n ];\n } else {\n // e.g. beta `compaction_delta` — carries the block's final fields.\n for (const [key, value] of Object.entries(delta)) {\n if (key !== \"type\") {\n block[key] = value;\n }\n }\n }\n }\n\n /** Close the accumulated stream blocks into an ordered content array. */\n private finishStreamedBlocks(blocks: Map<number, StreamedBlock>): Array<{ type: string }> {\n return Array.from(blocks.entries())\n .sort(([left], [right]) => left - right)\n .map(([, { block, json }]) => {\n if (json !== undefined) {\n block.input = safeJsonParse<Record<string, unknown>>(json, {});\n }\n\n return block as { type: string };\n });\n }\n\n /**\n * Send a request through the SDK. With `providerOptions.anthropic.betas`\n * the call goes to `client.beta.messages` (which takes the `betas` list\n * and the beta-only body fields); otherwise to `client.messages`. The\n * cancellation signal rides in the request options, as before.\n */\n private dispatch(\n request: {\n endpoint: AnthropicRequest[\"endpoint\"];\n body: Record<string, unknown>;\n betas: string[];\n },\n options: AnthropicRequestOptions | undefined,\n method: \"create\" | \"countTokens\",\n ): Promise<unknown> {\n const requestOptions = options?.signal ? { signal: options.signal } : undefined;\n const api =\n request.endpoint === \"beta.messages\" ? this.client.beta.messages : this.client.messages;\n const call = api[method] as unknown as LooseCreate;\n\n return call.call(\n api,\n request.endpoint === \"beta.messages\"\n ? { ...request.body, betas: request.betas }\n : request.body,\n requestOptions,\n );\n }\n\n /**\n * The full request body and the beta flags it needs: the adapter-built\n * params, then `thinking.display` when thinking is sent on an adaptive\n * model, the typed `thinkingBlockBinding`, `contextManagement` and\n * `serverCompaction` options, then `providerOptions.anthropic.body`\n * merged last (caller fields win). The body may add fields the adapter\n * does not build (`fallbacks`, …) but may not replace the conversation or\n * the model — see {@link RESERVED_BODY_FIELDS}.\n */\n private buildBody(\n messages: Message[],\n options: (ModelCallOptions & { stream?: boolean }) | undefined,\n ): { body: Record<string, unknown>; betas: string[] } {\n const anthropic = resolveAnthropicOptions(options);\n const betas: string[] = [];\n // Kept turns after a client-written summary carry thinking signed\n // against the replaced history. Leave it out on models that check the\n // conversation, unless the caller chose how the API handles it.\n const body: Record<string, unknown> = {\n ...this.buildParams(messages, options, {\n dropRetainedThinking:\n this.preservedThinking && anthropic.thinkingBlockBinding === undefined,\n }),\n };\n\n // `display` belongs to adaptive thinking only; `between_tools` takes\n // no other field and 400s with one.\n if (\n anthropic.thinkingDisplay &&\n this.thinkingMode === \"adaptive\" &&\n (body.thinking as { type?: string } | undefined)?.type === \"adaptive\"\n ) {\n body.thinking = {\n ...(body.thinking as Record<string, unknown>),\n display: anthropic.thinkingDisplay,\n };\n }\n\n if (anthropic.thinkingBlockBinding) {\n this.applyBlockBinding(body, anthropic.thinkingBlockBinding, betas);\n }\n\n const edits = buildContextEdits(anthropic);\n\n if (edits.length > 0) {\n if (anthropic.body?.context_management !== undefined) {\n throw new InvalidRequestError(\n \"providerOptions.anthropic.contextManagement / serverCompaction cannot be combined with \" +\n \"body.context_management: set the edits in one place.\",\n { context: { fields: [\"context_management\"] } },\n );\n }\n\n body.context_management = { edits };\n\n if (edits.some((edit) => edit.type !== \"compact_20260112\")) {\n betas.push(CONTEXT_MANAGEMENT_BETA);\n }\n\n if (edits.some((edit) => edit.type === \"compact_20260112\")) {\n betas.push(COMPACTION_BETA);\n }\n }\n\n const reserved = Object.keys(anthropic.body ?? {}).filter((key) =>\n RESERVED_BODY_FIELDS.has(key),\n );\n\n if (reserved.length > 0) {\n throw new InvalidRequestError(\n `providerOptions.anthropic.body cannot set ${reserved.map((key) => `\"${key}\"`).join(\", \")}: ` +\n \"the adapter builds these from the call's messages, tools and model. \" +\n \"Use the agent/model options instead.\",\n { context: { fields: reserved } },\n );\n }\n\n return { body: { ...body, ...anthropic.body }, betas };\n }\n\n /**\n * Set `thinking.block_binding.prefix_mismatch_behavior`. It rides on\n * adaptive or budget (`enabled`) thinking. A model that runs adaptive\n * thinking when `thinking` is omitted (every preserved-thinking model) gets\n * an explicit `{ type: \"adaptive\" }`, which is the same request. Any other\n * shape (`between_tools`, `disabled`) takes no extra field, so the option\n * is skipped with a debug log.\n */\n private applyBlockBinding(\n body: Record<string, unknown>,\n behavior: \"error\" | \"drop_block\",\n betas: string[],\n ): void {\n const thinking = body.thinking as { type?: string } | undefined;\n const type = thinking?.type ?? (this.preservedThinking ? \"adaptive\" : undefined);\n\n if (type !== \"adaptive\" && type !== \"enabled\") {\n this.logger.debug(\n LOG_MODULE,\n \"thinking-block-binding.ignored\",\n \"thinkingBlockBinding needs adaptive or budget thinking on this request; not sent\",\n { model: this.name, thinking: thinking?.type ?? \"none\" },\n );\n\n return;\n }\n\n body.thinking = {\n ...(thinking ?? { type }),\n block_binding: { prefix_mismatch_behavior: behavior },\n };\n betas.push(THINKING_BINDING_BETA);\n }\n\n /**\n * Assemble the Anthropic request body shared by `complete()` and\n * `stream()` (each adds its own `stream` literal so the SDK's create\n * overload resolves to the right return type). Hoists the system\n * prompt out of `messages`, resolves `max_tokens` (required by\n * Anthropic) with the documented default, and conditionally attaches\n * temperature, tools, native structured output, extended thinking\n * (`reasoning`), and automatic or explicit prompt-cache control.\n * Temperature is dropped when thinking is enabled, since Anthropic\n * rejects the two together, and always for adaptive-mode models, which\n * reject any explicit temperature (see `acceptsTemperature`).\n */\n private buildParams(\n messages: Message[],\n options: (ModelCallOptions & { stream?: boolean }) | undefined,\n conversion: { dropRetainedThinking: boolean },\n ): Omit<Anthropic.MessageCreateParamsNonStreaming, \"stream\"> {\n const { system, messages: anthropicMessages } = toAnthropicMessages(messages, conversion);\n const thinking = this.buildThinking(options?.reasoning);\n const temperature = options?.temperature ?? this.config.temperature;\n const configuredMaxTokens = options?.maxTokens ?? this.config.maxTokens;\n const thinkingBudget =\n thinking.thinking?.type === \"enabled\" ? thinking.thinking.budget_tokens : undefined;\n const maxTokens =\n configuredMaxTokens ??\n this.resolveDefaultMaxTokens(options?.stream === true, thinking.reservedTokens);\n // Extended thinking pins sampling to the default temperature —\n // Anthropic 400s when `thinking` is enabled alongside any explicit\n // `temperature`. Models released after Opus 4.6 (adaptive mode) reject\n // an explicit temperature outright (installed SDK\n // `MessageCreateParamsBase.temperature`, `messages.d.ts:2036-2040`).\n // Drop it in both cases rather than letting the request fail.\n const sendTemperature =\n temperature !== undefined && !thinking.thinking && acceptsTemperature(this.thinkingMode);\n\n if (\n thinkingBudget !== undefined &&\n configuredMaxTokens !== undefined &&\n configuredMaxTokens <= thinkingBudget\n ) {\n throw new Error(\n `Anthropic maxTokens (${configuredMaxTokens}) must be greater than thinking budget_tokens (${thinkingBudget})`,\n );\n }\n\n return {\n model: this.name,\n max_tokens: maxTokens,\n messages: anthropicMessages,\n ...this.buildAutomaticCacheControl(options?.cacheControl),\n ...this.buildSystem(system, options?.cacheControl),\n ...(sendTemperature ? { temperature } : {}),\n ...this.buildTools(options, options?.cacheControl),\n ...this.buildOutputConfig(options?.responseSchema, thinking.effort),\n ...(thinking.thinking ? { thinking: thinking.thinking } : {}),\n };\n }\n\n /**\n * The `max_tokens` sent when neither the call nor the model config sets\n * `maxTokens`:\n *\n * - streaming: the model's documented max output, or\n * `DEFAULT_MAX_TOKENS` (16384) for an unknown id;\n * - non-streaming: `DEFAULT_MAX_TOKENS`, capped by the model's max output\n * (the SDK requires streaming for larger non-streaming requests unless\n * the client sets a `timeout`; see `DEFAULT_MAX_TOKENS`).\n *\n * With thinking on, the value is raised to at least the thinking budget\n * plus `MIN_ANSWER_TOKENS`, and never exceeds the model's max output.\n */\n private resolveDefaultMaxTokens(stream: boolean, reservedTokens: number | undefined): number {\n const limit = this.maxOutputTokens;\n const fallback = limit === undefined ? DEFAULT_MAX_TOKENS : Math.min(limit, DEFAULT_MAX_TOKENS);\n const base = stream ? (limit ?? DEFAULT_MAX_TOKENS) : fallback;\n const withThinking =\n reservedTokens === undefined ? base : Math.max(base, reservedTokens + MIN_ANSWER_TOKENS);\n\n return limit === undefined ? withThinking : Math.min(withThinking, limit);\n }\n\n /**\n * Spread-friendly `system` fragment. Returns an empty object when no\n * system prompt was hoisted out of the messages.\n *\n * When a per-call `cacheControl.breakpoints` hint is present (≥ 1),\n * the system prompt is emitted as a single `TextBlockParam` carrying\n * `cache_control: ephemeral` — the system prompt is the longest stable\n * prefix on a turn, so one breakpoint there lets multi-turn agents\n * read it back at the ~0.1x cache-read rate. Without the hint the\n * system prompt stays a plain string (left uncached) so a one-shot\n * call never pays the ~1.25x cache-write surcharge.\n */\n private buildSystem(\n system: string | undefined,\n cacheControl: ModelCallOptions[\"cacheControl\"],\n ): { system?: string | Anthropic.TextBlockParam[] } {\n if (!system) {\n return {};\n }\n\n const breakpoints = cacheControl?.breakpoints ?? 0;\n\n if (this.capabilities.promptCaching && breakpoints > 0) {\n return {\n system: [\n { type: \"text\", text: system, cache_control: this.cacheControl(cacheControl?.ttl) },\n ],\n };\n }\n\n return { system };\n }\n\n /**\n * Let Anthropic select the last cacheable block when caching is enabled\n * without a caller-selected breakpoint. An explicit breakpoint remains\n * authoritative, so the request-level form is deliberately omitted then.\n */\n private buildAutomaticCacheControl(cacheControl: ModelCallOptions[\"cacheControl\"]): {\n cache_control?: Anthropic.CacheControlEphemeral;\n } {\n const breakpoints = cacheControl?.breakpoints ?? 0;\n\n return this.config.promptCaching && breakpoints <= 0\n ? { cache_control: this.cacheControl(cacheControl?.ttl) }\n : {};\n }\n\n /**\n * Build a typed cache-control marker. The per-call\n * `cacheControl.ttl` wins over the model's `promptCacheTtl`; with\n * neither, TTL is omitted for Anthropic's 5-minute default.\n */\n private cacheControl(callTtl?: \"5m\" | \"1h\"): Anthropic.CacheControlEphemeral {\n const ttl = callTtl ?? this.config.promptCacheTtl;\n\n return {\n type: \"ephemeral\",\n ...(ttl ? { ttl } : {}),\n };\n }\n\n /**\n * Translate the neutral `reasoning` option into Anthropic's thinking\n * settings, in the shape this model accepts (`thinkingMode`). Emitted\n * only when the model declares the `reasoning` capability AND a\n * reasoning option is supplied; otherwise returns an empty object.\n *\n * - Adaptive mode (Opus 4.7+, Sonnet 5+, Fable 5+, unknown ids):\n * `thinking: { type: \"adaptive\" }` (installed SDK\n * `ThinkingConfigAdaptive`, `messages.d.ts:1065`) plus\n * `output_config.effort` from the neutral effort, defaulting to\n * `\"medium\"`. `budget_tokens` is never sent — these models 400 on it\n * (claude-api ref). `reasoning.maxTokens` only sizes the default\n * `max_tokens` headroom.\n * - Budget mode (Haiku 4.5, Opus/Sonnet 4.6, older):\n * `thinking: { type: \"enabled\", budget_tokens }`. An explicit\n * `reasoning.maxTokens` wins; otherwise the effort maps to a tiered\n * budget. `budget_tokens` must be ≥ 1024 (`ThinkingConfigEnabled`,\n * `messages.d.ts:1084`), so the budget is floored at that minimum.\n *\n * The neutral `effort: \"none\"` (\"run without reasoning\") is mapped per\n * model by `noReasoningForm` (see `thinking-mode.ts` for the sources):\n * - Claude Sonnet 5.5: `thinking: { type: \"between_tools\" }`, its only\n * thinking-off form. It is sent alone — no `output_config.effort` (the\n * model default, `high`, is within the `high`-or-below range it\n * requires) and no `display`, both of which the API rejects alongside it.\n * - Claude Sonnet 5 and Claude Haiku 5.5: `thinking: { type: \"disabled\" }`\n * with no effort and no `display`. Haiku 5.5 accepts `disabled` only at\n * effort `high` or below; its default (`medium`) applies.\n * - Claude Opus 5: adaptive thinking at `output_config.effort: \"low\"`.\n * Opus 5 accepts `disabled`, but with it the model can write a tool call\n * as plain text (the call never runs) and leak thinking tags; the lowest\n * effort is the documented alternative.\n * - Opus 5.5 and Fable 5/5.1: no `thinking` field. These models have no\n * thinking-off form (`disabled` and `budget_tokens` are a 400 at every\n * effort), so thinking still runs at the model's default effort. Pass\n * `effort: \"low\"` to spend less.\n * - Every other model: no `thinking` field, as before.\n */\n private buildThinking(reasoning: ModelCallOptions[\"reasoning\"]): ThinkingRequest {\n if (!this.capabilities.reasoning || !reasoning) {\n return {};\n }\n\n // `effort: \"none\"` is an explicit \"run without reasoning\", in the form\n // this model accepts. (This also short-circuits the\n // `EFFORT_THINKING_BUDGET[\"none\"]` → `undefined` → `NaN` budget path.)\n if (reasoning.effort === \"none\") {\n return this.buildNoReasoning();\n }\n\n if (reasoning.maxTokens === undefined && reasoning.effort === undefined) {\n return {};\n }\n\n const effort = reasoning.effort ?? DEFAULT_THINKING_EFFORT;\n const budget = Math.max(\n MIN_THINKING_BUDGET,\n reasoning.maxTokens ?? EFFORT_THINKING_BUDGET[effort],\n );\n\n if (this.thinkingMode === \"adaptive\") {\n return {\n thinking: { type: \"adaptive\" },\n effort: EFFORT_TO_OUTPUT_EFFORT[effort],\n reservedTokens: budget,\n };\n }\n\n return {\n thinking: { type: \"enabled\", budget_tokens: budget },\n reservedTokens: budget,\n };\n }\n\n /**\n * The thinking settings for `reasoning: { effort: \"none\" }`, per\n * `noReasoningForm(this.name)` (documented on `buildThinking`).\n */\n private buildNoReasoning(): ThinkingRequest {\n switch (noReasoningForm(this.name)) {\n case \"between_tools\":\n return { thinking: { type: \"between_tools\" } };\n case \"disabled\":\n return { thinking: { type: \"disabled\" } };\n case \"lowest-effort\":\n return {\n thinking: { type: \"adaptive\" },\n effort: EFFORT_TO_OUTPUT_EFFORT.low,\n reservedTokens: EFFORT_THINKING_BUDGET.low,\n };\n case \"omit\":\n return {};\n }\n }\n\n /**\n * Spread-friendly tools fragment. Returns an empty object when no\n * tools were supplied so the caller can unconditionally spread it.\n *\n * When `config.promptCaching` is on, marks the LAST tool with\n * `cache_control: ephemeral` — Anthropic caches the whole prefix up\n * to a breakpoint, and tools sit before `system` in that prefix, so\n * one breakpoint on the final tool caches every tool definition.\n * Reads bill at ~0.1x after the first write. The system prompt is\n * deliberately left uncached: it carries per-turn placeholders, so a\n * breakpoint there would pay the ~1.25x write surcharge every turn\n * with no reads.\n */\n private buildTools(\n options: ModelCallOptions | undefined,\n cacheControl: ModelCallOptions[\"cacheControl\"],\n ): { tools?: Anthropic.ToolUnion[] } {\n const { tools, definitions } = selectProviderTools(options, {\n // The wire format, plus the provider label when a gateway sets one.\n accepts: [ANTHROPIC_WIRE_FORMAT, this.provider],\n module: LOG_MODULE,\n model: this.name,\n logger: this.logger,\n });\n const mapped = toAnthropicTools(tools);\n // Provider-defined tools (`web_search_20250305`, `bash_20250124`, …) go\n // first and verbatim; the cache breakpoint stays on the last function\n // tool so it still covers every definition before it.\n const providerDefined = definitions as unknown as Anthropic.ToolUnion[];\n\n if (!mapped) {\n return providerDefined.length > 0 ? { tools: providerDefined } : {};\n }\n\n if (this.config.promptCaching && mapped.length > 0) {\n const last = mapped.length - 1;\n const lastTool = mapped[last];\n\n if (lastTool) {\n mapped[last] = { ...lastTool, cache_control: this.cacheControl(cacheControl?.ttl) };\n }\n }\n\n return { tools: [...providerDefined, ...mapped] };\n }\n\n /**\n * Spread-friendly `output_config` fragment carrying both the native\n * structured-output `format` and the adaptive-thinking `effort`, merged\n * into one object (both live under `OutputConfig`, installed SDK\n * `messages.d.ts:796-806`). Returns an empty object when neither applies,\n * so budget-mode requests carry `output_config` only when a schema asks\n * for it.\n */\n private buildOutputConfig(\n responseSchema: Record<string, unknown> | undefined,\n effort: Anthropic.OutputConfig[\"effort\"],\n ): { output_config?: Anthropic.OutputConfig } {\n const format = this.buildStructuredOutputFormat(responseSchema);\n\n if (!format && !effort) {\n return {};\n }\n\n return {\n output_config: {\n ...(format ? { format } : {}),\n ...(effort ? { effort } : {}),\n },\n };\n }\n\n /**\n * Translate the neutral `responseSchema` option into Anthropic's\n * native `output_config.format` (JSON-schema structured outputs).\n *\n * Only returned when the model declares the `structuredOutput`\n * capability AND the schema is a proper root-object JSON Schema —\n * Anthropic rejects non-object roots. When the capability is off\n * (config override) or the schema is non-object, returns `undefined`:\n * the agent has already injected a soft schema hint into the system\n * prompt as the fallback, and client-side `validate()` still enforces\n * shape.\n */\n private buildStructuredOutputFormat(\n responseSchema: Record<string, unknown> | undefined,\n ): Anthropic.JSONOutputFormat | undefined {\n if (!responseSchema || !this.capabilities.structuredOutput) {\n return undefined;\n }\n\n if (responseSchema.type !== \"object\" || typeof responseSchema.properties !== \"object\") {\n return undefined;\n }\n\n return { type: \"json_schema\", schema: responseSchema };\n }\n\n /**\n * Concatenate every `text` content block into the single neutral\n * `content` string. `tool_use` and other block types are ignored\n * here — tool calls are surfaced separately via `extractToolCalls`.\n */\n private extractText(content: Anthropic.ContentBlock[]): string {\n return content\n .filter((block): block is Anthropic.TextBlock => block.type === \"text\")\n .map((block) => block.text)\n .join(\"\");\n }\n\n /**\n * Reshape Anthropic's `tool_use` content blocks into the neutral\n * `ModelToolCallRequest[]`. Returns `undefined` when the model\n * requested no tools so callers can branch on presence.\n */\n private extractToolCalls(content: Anthropic.ContentBlock[]): ModelToolCallRequest[] | undefined {\n const toolUses = content.filter(\n (block): block is Anthropic.ToolUseBlock => block.type === \"tool_use\",\n );\n\n if (toolUses.length === 0) {\n return undefined;\n }\n\n const thinkingMetadata = this.buildThinkingMetadata(content);\n\n return toolUses.map((block) => ({\n id: block.id,\n name: block.name,\n input: (block.input ?? {}) as Record<string, unknown>,\n ...thinkingMetadata,\n }));\n }\n\n /**\n * Preserve Anthropic's opaque extended-thinking blocks beside a tool\n * request so the next assistant turn can replay their signatures exactly.\n */\n private buildThinkingMetadata(blocks: Iterable<Anthropic.ContentBlock>): {\n providerMetadata?: Record<string, unknown>;\n } {\n const thinkingBlocks = Array.from(blocks).filter(\n (block): block is AnthropicThinkingBlock =>\n block.type === \"thinking\" || block.type === \"redacted_thinking\",\n );\n\n if (thinkingBlocks.length === 0) {\n return {};\n }\n\n return { providerMetadata: { anthropic: { thinkingBlocks } } };\n }\n\n /**\n * Normalize Anthropic's `usage` block into the neutral `Usage` shape.\n * Anthropic reports `input_tokens` / `output_tokens` separately with\n * no pre-summed total, so `total` is computed. `input_tokens` is the\n * uncached remainder only — cache reads (`cachedTokens`) and writes\n * (`cacheWriteTokens`, with the 1-hour share in `cacheWrite1hTokens`)\n * come on top of it — so the usage is marked\n * `inputIncludesCache: false`. Anthropic also reports\n * `output_tokens_details.thinking_tokens` as the reasoning subset of\n * its inclusive `output_tokens`; it is surfaced as `reasoningTokens`\n * when present, without changing the billing total. Server-side\n * compaction iterations are added in (see {@link compactionIterationUsage}).\n * `cost` is attached when the model is priced.\n */\n private extractUsage(raw: Anthropic.Usage, cacheTtl: ReturnType<typeof requestCacheTtl>): Usage {\n const compaction = compactionIterationUsage(raw);\n const input = (raw.input_tokens ?? 0) + compaction.input;\n const output = (raw.output_tokens ?? 0) + compaction.output;\n const thinkingTokens = raw.output_tokens_details?.thinking_tokens;\n const usage: Usage = {\n input,\n output,\n total: input + output,\n inputIncludesCache: false,\n ...(thinkingTokens !== null && thinkingTokens !== undefined\n ? { reasoningTokens: thinkingTokens }\n : {}),\n };\n\n applyAnthropicCacheUsage(usage, raw, cacheTtl);\n addCacheCounts(usage, compaction);\n\n const cost = computeCost(usage, this.pricing);\n\n if (cost) {\n usage.cost = cost;\n }\n\n return usage;\n }\n\n /**\n * Wrap a thrown provider error into the typed `AIError` hierarchy and\n * emit the standard error log line before it propagates. Shared by\n * every catch site so the log shape stays identical.\n */\n private logAndWrap(thrown: unknown) {\n const wrapped = wrapAnthropicError(thrown);\n\n this.logger.error(LOG_MODULE, \"error\", wrapped.message, {\n code: wrapped.code,\n context: wrapped.context,\n });\n\n return wrapped;\n }\n}\n\n/**\n * Request fields `providerOptions.anthropic.body` may not set: they carry\n * the conversation, the model and the tool surface the agent registered,\n * so an override would silently replace the agent's input (or let the\n * model call tools the agent never registered). `stream` is chosen per\n * call by `complete()` / `stream()`.\n */\nconst RESERVED_BODY_FIELDS: ReadonlySet<string> = new Set([\n \"model\",\n \"messages\",\n \"system\",\n \"tools\",\n \"mcp_servers\",\n \"stream\",\n]);\n\n/** Body fields `messages.countTokens` accepts, copied from the full request body. */\nconst COUNT_TOKENS_FIELDS = [\n \"model\",\n \"messages\",\n \"system\",\n \"tools\",\n \"tool_choice\",\n \"thinking\",\n \"output_config\",\n \"cache_control\",\n \"context_management\",\n \"mcp_servers\",\n] as const;\n\n/** Beta flag for typed context editing (Anthropic docs, \"Context editing\", read 2026-10-17). */\nconst CONTEXT_MANAGEMENT_BETA = \"context-management-2025-06-27\";\n\n/** Beta flag for threshold compaction (Anthropic docs, \"Compaction at a token threshold\"). */\nconst COMPACTION_BETA = \"compact-2026-01-12\";\n\n/** Beta flag for `thinking.block_binding` (Anthropic docs, \"Preserved thinking\"). */\nconst THINKING_BINDING_BETA = \"thinking-binding-controls-2026-08-01\";\n\n/** The API rejects a compaction trigger below 50,000 input tokens. */\nconst MIN_COMPACTION_TRIGGER = 50_000;\n\ntype ContextEdit = { type: string } & Record<string, unknown>;\n\n/**\n * Translate the typed `contextManagement` / `serverCompaction` options into\n * `context_management.edits`. `clear_thinking_20251015` must come first\n * when strategies are combined (Anthropic docs, \"Context editing\").\n */\nfunction buildContextEdits(anthropic: AnthropicCallOptions): ContextEdit[] {\n const edits: ContextEdit[] = [];\n const { clearThinking, clearToolUses } = anthropic.contextManagement ?? {};\n\n if (clearThinking) {\n edits.push(clearThinkingEdit(clearThinking === true ? {} : clearThinking));\n }\n\n if (clearToolUses) {\n edits.push(clearToolUsesEdit(clearToolUses === true ? {} : clearToolUses));\n }\n\n if (anthropic.serverCompaction) {\n const compaction = anthropic.serverCompaction === true ? {} : anthropic.serverCompaction;\n\n if (compaction.triggerTokens !== undefined) {\n assertCount(\n \"serverCompaction.triggerTokens\",\n compaction.triggerTokens,\n MIN_COMPACTION_TRIGGER,\n );\n }\n\n edits.push({\n type: \"compact_20260112\",\n ...(compaction.triggerTokens !== undefined\n ? { trigger: { type: \"input_tokens\", value: compaction.triggerTokens } }\n : {}),\n ...(compaction.instructions ? { instructions: compaction.instructions } : {}),\n });\n }\n\n return edits;\n}\n\nfunction clearThinkingEdit(options: AnthropicClearThinking): ContextEdit {\n if (options.keep === undefined || options.keep === \"all\") {\n return { type: \"clear_thinking_20251015\", ...(options.keep ? { keep: \"all\" } : {}) };\n }\n\n assertCount(\"contextManagement.clearThinking.keep\", options.keep, 1);\n\n return {\n type: \"clear_thinking_20251015\",\n keep: { type: \"thinking_turns\", value: options.keep },\n };\n}\n\nfunction clearToolUsesEdit(options: AnthropicClearToolUses): ContextEdit {\n const edit: ContextEdit = { type: \"clear_tool_uses_20250919\" };\n\n if (options.trigger) {\n const trigger =\n \"inputTokens\" in options.trigger\n ? { type: \"input_tokens\", value: options.trigger.inputTokens }\n : { type: \"tool_uses\", value: options.trigger.toolUses };\n\n assertCount(\"contextManagement.clearToolUses.trigger\", trigger.value, 1);\n edit.trigger = trigger;\n }\n\n if (options.keep !== undefined) {\n assertCount(\"contextManagement.clearToolUses.keep\", options.keep, 0);\n edit.keep = { type: \"tool_uses\", value: options.keep };\n }\n\n if (options.clearAtLeast !== undefined) {\n assertCount(\"contextManagement.clearToolUses.clearAtLeast\", options.clearAtLeast, 1);\n edit.clear_at_least = { type: \"input_tokens\", value: options.clearAtLeast };\n }\n\n if (options.excludeTools !== undefined) {\n edit.exclude_tools = [...options.excludeTools];\n }\n\n if (options.clearToolInputs !== undefined) {\n edit.clear_tool_inputs = Array.isArray(options.clearToolInputs)\n ? [...options.clearToolInputs]\n : options.clearToolInputs;\n }\n\n return edit;\n}\n\nfunction assertCount(field: string, value: number, minimum: number): void {\n if (!Number.isSafeInteger(value) || value < minimum) {\n throw new InvalidRequestError(\n `providerOptions.anthropic.${field} must be an integer of at least ${minimum}; got ${value}.`,\n { context: { field } },\n );\n }\n}\n\ntype IterationTotals = { input: number; output: number; cacheRead: number; cacheWrite: number };\n\n/**\n * Tokens of the `compaction` entries in a beta response's `usage.iterations`.\n * With server-side compaction the top-level `input_tokens` / `output_tokens`\n * cover only the non-compaction iterations; the billed total is the sum\n * over every iteration (Anthropic docs, \"Compaction at a token threshold\" →\n * \"Understanding usage\", read 2026-10-17). Zeros when there are none.\n */\nfunction compactionIterationUsage(raw: unknown): IterationTotals {\n const totals: IterationTotals = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };\n const iterations = (raw as { iterations?: unknown } | null | undefined)?.iterations;\n\n if (!Array.isArray(iterations)) {\n return totals;\n }\n\n for (const entry of iterations as unknown[]) {\n const iteration = entry as Record<string, unknown> | null;\n\n if (iteration?.type !== \"compaction\") {\n continue;\n }\n\n totals.input += numberOrZero(iteration.input_tokens);\n totals.output += numberOrZero(iteration.output_tokens);\n totals.cacheRead += numberOrZero(iteration.cache_read_input_tokens);\n totals.cacheWrite += numberOrZero(iteration.cache_creation_input_tokens);\n }\n\n return totals;\n}\n\nfunction numberOrZero(value: unknown): number {\n return typeof value === \"number\" && Number.isFinite(value) ? value : 0;\n}\n\nfunction addCacheCounts(usage: Usage, extra: IterationTotals): void {\n if (extra.cacheRead > 0) {\n usage.cachedTokens = (usage.cachedTokens ?? 0) + extra.cacheRead;\n }\n\n if (extra.cacheWrite > 0) {\n usage.cacheWriteTokens = (usage.cacheWriteTokens ?? 0) + extra.cacheWrite;\n }\n}\n\n/** Read `providerOptions.anthropic`, tolerating its absence or a wrong shape. */\nfunction resolveAnthropicOptions(options: ModelCallOptions | undefined): AnthropicCallOptions {\n const raw = options?.providerOptions?.anthropic;\n\n return typeof raw === \"object\" && raw !== null ? (raw as AnthropicCallOptions) : {};\n}\n","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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUA,MAAa,mCAAmC;AAChD,MAAa,sCAAsC;;;;;;;;;;;;;;;;;;;AAoBnD,MAAa,0BAAkE;CAC7E,oBAAoB;EAClB,OAAO;EACP,QAAQ;EACR,aAAa;EACb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ACF"}
1
+ {"version":3,"file":"index.cjs","names":["extractJsonSchema","AIError","ProviderTimeoutError","ProviderAuthError","QuotaExceededError","ProviderRateLimitError","ProviderOverloadedError","ContextLengthExceededError","InvalidRequestError","ProviderError","APIError","APIConnectionTimeoutError","log","AIError","InvalidRequestError","resolveStreamChunks","safeJsonParse","computeCost","selectProviderTools","Anthropic","approximateTokenCount"],"sources":["../../../../../../../packages/ai-anthropic/src/known-pricing.ts","../../../../../../../packages/ai-anthropic/src/thinking-mode.ts","../../../../../../../packages/ai-anthropic/src/known-output-limits.ts","../../../../../../../packages/ai-anthropic/src/known-vision-models.ts","../../../../../../../packages/ai-anthropic/src/utils/server-tool-usage.ts","../../../../../../../packages/ai-anthropic/src/utils/cache-usage.ts","../../../../../../../packages/ai-anthropic/src/utils/map-stop-reason.ts","../../../../../../../packages/ai-anthropic/src/utils/provider-blocks.ts","../../../../../../../packages/ai-anthropic/src/utils/to-anthropic-messages.ts","../../../../../../../packages/ai-anthropic/src/utils/to-anthropic-tools.ts","../../../../../../../packages/ai-anthropic/src/utils/wrap-anthropic-error.ts","../../../../../../../packages/ai-anthropic/src/model.ts","../../../../../../../packages/ai-anthropic/src/sdk.ts"],"sourcesContent":["import type { ModelPricing } from \"@warlock.js/ai\";\n\n/**\n * Anthropic's prompt-cache write multipliers, relative to the base input\n * rate: a 5-minute write costs 1.25x, a 1-hour write 2x. They hold for\n * every Claude model on Anthropic's price list.\n *\n * Source: https://platform.claude.com/docs/en/about-claude/pricing\n * (fetched 2026-10-17).\n */\nexport const ANTHROPIC_CACHE_WRITE_MULTIPLIER = 1.25;\nexport const ANTHROPIC_CACHE_WRITE_1H_MULTIPLIER = 2;\n\n/**\n * Built-in Claude API list prices, USD per 1,000,000 tokens, keyed by\n * model id. `cachedInput` is the cache-hit rate, `cacheWrite` the\n * 5-minute write rate and `cacheWrite1h` the 1-hour write rate.\n *\n * Source: https://platform.claude.com/docs/en/about-claude/pricing,\n * \"Model pricing\" table, fetched 2026-10-17. Standard (global) routing,\n * non-batch. Not covered, so pass `pricing` yourself when you need them:\n *\n * - Claude Haiku 5.5 — priced by prompt length (higher rates above\n * 100,000 prompt tokens), which a flat `ModelPricing` cannot express.\n * - US-only inference (`inference_geo: \"us\"`, 1.1x), fast mode, the Batch\n * API, and Claude on Bedrock / Vertex AI (partner-priced).\n * - Limited-availability models (Mythos) and retired models.\n *\n * Dated snapshot ids (`claude-haiku-4-5-20251001`) resolve to their alias\n * entry through {@link anthropicPricingFor}.\n */\nexport const ANTHROPIC_MODEL_PRICING: Readonly<Record<string, ModelPricing>> = {\n \"claude-fable-5-1\": {\n input: 10,\n output: 50,\n cachedInput: 0.25,\n cacheWrite: 12.5,\n cacheWrite1h: 20,\n },\n \"claude-fable-5\": { input: 10, output: 50, cachedInput: 1, cacheWrite: 12.5, cacheWrite1h: 20 },\n \"claude-opus-5-5\": { input: 4, output: 20, cachedInput: 0.2, cacheWrite: 5, cacheWrite1h: 8 },\n \"claude-opus-5\": { input: 5, output: 25, cachedInput: 0.5, cacheWrite: 6.25, cacheWrite1h: 10 },\n \"claude-opus-4-8\": { input: 5, output: 25, cachedInput: 0.5, cacheWrite: 6.25, cacheWrite1h: 10 },\n \"claude-opus-4-7\": { input: 5, output: 25, cachedInput: 0.5, cacheWrite: 6.25, cacheWrite1h: 10 },\n \"claude-opus-4-6\": { input: 5, output: 25, cachedInput: 0.5, cacheWrite: 6.25, cacheWrite1h: 10 },\n \"claude-opus-4-5\": { input: 5, output: 25, cachedInput: 0.5, cacheWrite: 6.25, cacheWrite1h: 10 },\n \"claude-sonnet-5-5\": { input: 2, output: 10, cachedInput: 0.1, cacheWrite: 2.5, cacheWrite1h: 4 },\n \"claude-sonnet-5\": { input: 2, output: 10, cachedInput: 0.2, cacheWrite: 2.5, cacheWrite1h: 4 },\n \"claude-sonnet-4-6\": {\n input: 3,\n output: 15,\n cachedInput: 0.3,\n cacheWrite: 3.75,\n cacheWrite1h: 6,\n },\n \"claude-sonnet-4-5\": {\n input: 3,\n output: 15,\n cachedInput: 0.3,\n cacheWrite: 3.75,\n cacheWrite1h: 6,\n },\n \"claude-haiku-4-5\": { input: 1, output: 5, cachedInput: 0.1, cacheWrite: 1.25, cacheWrite1h: 2 },\n};\n\n/** A trailing `-YYYYMMDD` snapshot date on a Claude model id. */\nconst SNAPSHOT_SUFFIX = /-\\d{8}$/;\n\n/**\n * Look up the built-in list price for a Claude model id. Accepts the\n * alias (`claude-sonnet-4-5`) or a dated snapshot\n * (`claude-sonnet-4-5-20250929`). Returns `undefined` for any id not in\n * {@link ANTHROPIC_MODEL_PRICING}, so cost stays unknown rather than wrong.\n *\n * @example\n * anthropicPricingFor(\"claude-haiku-4-5-20251001\"); // { input: 1, output: 5, … }\n * anthropicPricingFor(\"claude-haiku-5-5\"); // undefined (prompt-length tiers)\n */\nexport function anthropicPricingFor(modelName: string): ModelPricing | undefined {\n const exact = ANTHROPIC_MODEL_PRICING[modelName];\n\n if (exact) {\n return exact;\n }\n\n return ANTHROPIC_MODEL_PRICING[modelName.replace(SNAPSHOT_SUFFIX, \"\")];\n}\n\n/**\n * Fill the cache-write rates Anthropic derives from the input rate\n * (5-minute writes 1.25x, 1-hour writes 2x) into a pricing entry that\n * omits them, so a caller who supplies only `{ input, output }` is no\n * longer billed nothing for cache writes. Explicit rates always win; the\n * cache-read rate is left alone because it differs per model.\n *\n * @example\n * withAnthropicCacheWriteRates({ input: 3, output: 15 });\n * // { input: 3, output: 15, cacheWrite: 3.75, cacheWrite1h: 6 }\n */\nexport function withAnthropicCacheWriteRates(\n pricing: ModelPricing | undefined,\n): ModelPricing | undefined {\n if (!pricing) {\n return undefined;\n }\n\n const cacheWrite =\n pricing.cacheWrite ?? pricing.cachedOutput ?? pricing.input * ANTHROPIC_CACHE_WRITE_MULTIPLIER;\n const cacheWrite1h = pricing.cacheWrite1h ?? pricing.input * ANTHROPIC_CACHE_WRITE_1H_MULTIPLIER;\n\n if (pricing.cacheWrite === cacheWrite && pricing.cacheWrite1h === cacheWrite1h) {\n return pricing;\n }\n\n return { ...pricing, cacheWrite, cacheWrite1h };\n}\n\n/** USD per request, verified 2026-10-18. Tokens are additional.\n * https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool#usage-and-pricing\n * https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-fetch-tool#usage-and-pricing */\nexport const ANTHROPIC_SERVER_TOOL_PRICING = { webSearch: 0.01, webFetch: 0 };\n","/**\n * How a Claude model accepts extended thinking on the Messages API.\n *\n * - `\"adaptive\"` — `thinking: { type: \"adaptive\" }`, with depth steered by\n * `output_config.effort`. Sending `budget_tokens` to these models is a\n * 400. Installed SDK: `ThinkingConfigAdaptive`\n * (`@anthropic-ai/sdk/resources/messages/messages.d.ts:1065`) and\n * `OutputConfig.effort` (`messages.d.ts:796-800`).\n * - `\"budget\"` — the legacy `thinking: { type: \"enabled\", budget_tokens }`\n * (`ThinkingConfigEnabled`, `messages.d.ts:1078-1090`). Required on\n * Haiku 4.5 and older models.\n */\nexport type AnthropicThinkingMode = \"adaptive\" | \"budget\";\n\n/*\n * Model-family table (source: claude-api ref, \"Thinking & Effort\" per-model\n * table, cached 2026-09-25; summarised in `releases/5.26-ai-sdk-review.md` §A):\n *\n * | Model ids | Mode | `budget_tokens` | `temperature` |\n * |----------------------------------------------|------------|-------------------------|--------------------|\n * | claude-fable-5, claude-fable-5-1 (+ mythos) | adaptive | removed (400) | removed (400) |\n * | claude-opus-5-5, claude-opus-5 | adaptive | removed (400) | removed (400) |\n * | claude-opus-4-8, claude-opus-4-7 | adaptive | removed (400) | removed (400) |\n * | claude-sonnet-5-5, claude-sonnet-5 | adaptive | removed (400) | 400 (5.5: non-1.0) |\n * | claude-opus-4-6, claude-sonnet-4-6 | budget (*) | deprecated, still works | allowed |\n * | claude-haiku-4-5 and every older model | budget | required for thinking | allowed |\n * | anything not listed (future / unknown ids) | adaptive | — | — |\n *\n * (*) The 4.6 pair accepts both shapes; the claude-api ref recommends\n * adaptive there but keeps `budget_tokens` functional as a transitional\n * path. It stays on `budget` so 4.6 callers see no behaviour change (their\n * `reasoning.maxTokens` is still honoured as a hard budget) and so that\n * the `budget` set is exactly the set that still accepts `temperature`\n * (see `acceptsTemperature`). Opt 4.6 into adaptive with\n * `anthropic.model({ name, thinkingMode: \"adaptive\" })`.\n *\n * Unknown ids default to adaptive because that is the current API\n * direction: every model released after Opus 4.6 rejects `budget_tokens`.\n */\n\n/**\n * Family prefixes that are budget-mode in their entirety — plain\n * `startsWith` match (dated and `-latest` variants included).\n */\nconst BUDGET_FAMILY_PREFIXES = [\n // Claude 3 / 3.5 / 3.7 legacy naming (claude-3-haiku-…, claude-3-5-sonnet-…).\n \"claude-3\",\n // Pre-3 text models: no thinking support at all, never adaptive.\n \"claude-2\",\n \"claude-instant\",\n // Haiku 4.x: Haiku 4.5 still requires budget_tokens (claude-api ref).\n \"claude-haiku-4\",\n];\n\n/**\n * Individual pre-4.7 releases in the `claude-<tier>-4-*` naming. Matched\n * as a release root: the id must equal the root or continue with a\n * separator that is not a new minor version number, so `claude-opus-4`\n * matches `claude-opus-4-20250514` but NOT `claude-opus-4-7`. Ids from the\n * installed SDK `Model` union (`messages.d.ts:795`) plus the 4.6 pair.\n */\nconst BUDGET_RELEASE_ROOTS = [\n \"claude-opus-4\",\n \"claude-opus-4-0\",\n \"claude-opus-4-1\",\n \"claude-opus-4-5\",\n \"claude-opus-4-6\",\n \"claude-sonnet-4\",\n \"claude-sonnet-4-0\",\n \"claude-sonnet-4-5\",\n \"claude-sonnet-4-6\",\n];\n\n/**\n * A remainder that starts a new minor version (`-7`, `-10`) — used to\n * stop a release root from swallowing a later release of the same line.\n * Dates (`-20250514`) and tags (`-latest`, `-v1`) are not minor versions.\n */\nconst NEXT_MINOR_VERSION = /^-\\d{1,2}(?!\\d)/;\n\n/**\n * Whether a lower-cased model id is the release `root` itself, or a dated /\n * tagged / `@` snapshot of it — but not a later minor version of the same\n * line (`claude-opus-4` matches `claude-opus-4-20250514`, not `claude-opus-4-7`).\n */\nexport function matchesReleaseRoot(name: string, root: string): boolean {\n if (!name.startsWith(root)) {\n return false;\n }\n\n const rest = name.slice(root.length);\n\n if (rest === \"\") {\n return true;\n }\n\n return (rest.startsWith(\"-\") || rest.startsWith(\"@\")) && !NEXT_MINOR_VERSION.test(rest);\n}\n\n/**\n * Infer the thinking mode for a Claude model id. Budget for Haiku 4.5, the\n * 4.6 pair, and every older family; adaptive for everything else,\n * including unknown and future ids. Explicit per-model config\n * (`AnthropicModelConfig.thinkingMode`) always wins over this inference.\n *\n * @example\n * inferThinkingMode(\"claude-opus-5-5\"); // → \"adaptive\"\n * inferThinkingMode(\"claude-haiku-4-5\"); // → \"budget\"\n * inferThinkingMode(\"claude-opus-9\"); // → \"adaptive\" (unknown → current API direction)\n */\nexport function inferThinkingMode(modelName: string): AnthropicThinkingMode {\n const normalized = modelName.toLowerCase();\n\n if (BUDGET_FAMILY_PREFIXES.some((prefix) => normalized.startsWith(prefix))) {\n return \"budget\";\n }\n\n if (BUDGET_RELEASE_ROOTS.some((root) => matchesReleaseRoot(normalized, root))) {\n return \"budget\";\n }\n\n return \"adaptive\";\n}\n\n/**\n * Whether a model of this thinking mode accepts an explicit `temperature`.\n *\n * Installed SDK, `MessageCreateParamsBase.temperature`\n * (`messages.d.ts:2036-2040`): \"Models released after Claude Opus 4.6 do\n * not support setting temperature. A value of 1.0 will be accepted for\n * backwards compatibility, all other values will be rejected with a 400\n * error.\" The claude-api ref's per-model table agrees: sampling is\n * \"Removed - 400\" on Fable 5/5.1, Opus 5.5/5/4.8/4.7 and Sonnet 5, and\n * \"Non-default values - 400\" on Sonnet 5.5; \"Allowed\" on Opus 4.6,\n * Sonnet 4.6, Haiku 4.5 and older.\n *\n * That split is exactly the adaptive/budget split in the table above\n * (adaptive = released after Opus 4.6; budget = Opus 4.6 and earlier), so\n * the thinking mode doubles as the sampling-parameter classification.\n */\nexport function acceptsTemperature(mode: AnthropicThinkingMode): boolean {\n return mode === \"budget\";\n}\n\n/**\n * Model release roots that accept `thinking: { type: \"between_tools\" }`,\n * the only way to turn thinking off on them. Source: claude-api ref,\n * \"Thinking & Effort\" per-model table (cached 2026-10-06): Claude Sonnet\n * 5.5 returns a 400 on `{ type: \"disabled\" }` and takes `between_tools`\n * instead (no other field alongside it, effort `high` or below). No other\n * current model is documented to accept it. Opus 5.5 and Fable 5/5.1 have\n * no thinking-off form at all: `disabled` and `budget_tokens` are a 400 at\n * every effort, so the lowest they go is `effort: \"low\"`.\n */\nconst BETWEEN_TOOLS_RELEASE_ROOTS = [\"claude-sonnet-5-5\"];\n\n/**\n * Whether `effort: \"none\"` can turn thinking off on this model with\n * `thinking: { type: \"between_tools\" }`. Matches the release id with or\n * without a platform prefix (`anthropic.claude-sonnet-5-5` on Bedrock)\n * and with dated or tagged suffixes, but not a later minor release.\n *\n * @example\n * acceptsBetweenTools(\"claude-sonnet-5-5\"); // → true\n * acceptsBetweenTools(\"claude-opus-5-5\"); // → false\n */\nexport function acceptsBetweenTools(modelName: string): boolean {\n return matchesAnyRelease(modelName, BETWEEN_TOOLS_RELEASE_ROOTS);\n}\n\n/**\n * Whether the model id — lower-cased, with any platform prefix\n * (`anthropic.`, `us.anthropic.` on Bedrock) removed — is one of these\n * releases, dated or tagged, but not a later minor release.\n */\nfunction matchesAnyRelease(modelName: string, roots: readonly string[]): boolean {\n const normalized = modelName.toLowerCase();\n const id = normalized.slice(normalized.lastIndexOf(\".\") + 1);\n\n return roots.some((root) => matchesReleaseRoot(id, root));\n}\n\n/**\n * How a model is asked to run without reasoning when the caller passes the\n * neutral `reasoning: { effort: \"none\" }`.\n *\n * - `\"between_tools\"` — send `thinking: { type: \"between_tools\" }` alone.\n * - `\"disabled\"` — send `thinking: { type: \"disabled\" }` with no effort.\n * - `\"lowest-effort\"` — keep adaptive thinking on and send the lowest\n * `output_config.effort` (`\"low\"`).\n * - `\"omit\"` — send no `thinking` field at all.\n */\nexport type AnthropicNoReasoningForm = \"between_tools\" | \"disabled\" | \"lowest-effort\" | \"omit\";\n\n/**\n * Releases that accept `thinking: { type: \"disabled\" }` and run reliably\n * with it. Source: claude-api ref, \"Thinking & Effort\" per-model table\n * (cached 2026-10-06): Claude Sonnet 5 accepts `disabled`; Claude Haiku 5.5\n * accepts it at effort `low`, `medium` and `high` (a 400 at `xhigh` /\n * `max`). No effort is sent alongside it, so Haiku 5.5 runs at its default,\n * `medium`, which is inside the accepted range.\n */\nconst DISABLED_THINKING_RELEASE_ROOTS = [\"claude-sonnet-5\", \"claude-haiku-5-5\"];\n\n/**\n * Releases that accept `disabled` but are kept on adaptive thinking at the\n * lowest effort instead. Claude Opus 5 accepts `disabled` at effort `high`\n * or below, but the claude-api ref (\"Two failure modes when thinking is\n * disabled\", cached 2026-10-06) documents that with thinking disabled it\n * occasionally writes a tool call into its visible text instead of a\n * `tool_use` block — the call never runs and no error is raised — and can\n * leak `<thinking>` tags into the response. The ref's primary\n * recommendation is to keep thinking on and lower `effort`, so the adapter\n * does exactly that.\n */\nconst LOWEST_EFFORT_RELEASE_ROOTS = [\"claude-opus-5\"];\n\n/**\n * The wire form for `reasoning: { effort: \"none\" }` on this model:\n *\n * | Model | Form |\n * |----------------------------------------|-------------------|\n * | Claude Sonnet 5.5 | `between_tools` |\n * | Claude Sonnet 5, Claude Haiku 5.5 | `disabled` |\n * | Claude Opus 5 | `lowest-effort` |\n * | Opus 5.5, Fable 5/5.1, everything else | `omit` |\n *\n * Opus 5.5 and Fable 5/5.1 have no thinking-off form (`disabled` and\n * `budget_tokens` are a 400 at every effort), so nothing is sent and the\n * model runs at its default effort; older models run without thinking when\n * the field is absent.\n *\n * @example\n * noReasoningForm(\"claude-sonnet-5\"); // → \"disabled\"\n * noReasoningForm(\"claude-opus-5\"); // → \"lowest-effort\"\n * noReasoningForm(\"claude-opus-5-5\"); // → \"omit\"\n */\nexport function noReasoningForm(modelName: string): AnthropicNoReasoningForm {\n if (acceptsBetweenTools(modelName)) {\n return \"between_tools\";\n }\n\n if (matchesAnyRelease(modelName, DISABLED_THINKING_RELEASE_ROOTS)) {\n return \"disabled\";\n }\n\n if (matchesAnyRelease(modelName, LOWEST_EFFORT_RELEASE_ROOTS)) {\n return \"lowest-effort\";\n }\n\n return \"omit\";\n}\n\n/*\n * Preserved thinking (Anthropic docs, \"Thinking\" → \"Preserved thinking\" and\n * the \"Preserved thinking\" page, read 2026-10-17): the API checks that the\n * `system` prompt, `tools` and every message before a replayed thinking\n * block are unchanged since the block was produced, on Claude Fable 5.1,\n * Claude Opus 5.5, Claude Sonnet 5.5 and Claude Haiku 5.5. Claude Mythos 5.1\n * and every model released before Claude Fable 5.1 don't run that check, so\n * a thinking block kept after a client-written summary stays valid there.\n */\nconst PREFIX_CHECK_RELEASE_ROOTS = [\n \"claude-fable-5-1\",\n \"claude-opus-5-5\",\n \"claude-sonnet-5-5\",\n \"claude-haiku-5-5\",\n];\n\n/** Releases documented not to run the conversation check. */\nconst NO_PREFIX_CHECK_RELEASE_ROOTS = [\n \"claude-mythos-5-1\",\n \"claude-mythos-5\",\n \"claude-mythos-preview\",\n \"claude-fable-5\",\n \"claude-opus-5\",\n \"claude-sonnet-5\",\n];\n\n/** Families released before Claude Fable 5.1 in their entirety. */\nconst NO_PREFIX_CHECK_FAMILY_PREFIXES = [\n ...BUDGET_FAMILY_PREFIXES,\n \"claude-opus-4\",\n \"claude-sonnet-4\",\n];\n\n/**\n * Whether this model binds a replayed thinking block to the exact\n * conversation before it (preserved thinking). Unknown and future ids are\n * assumed to run the check — the safe direction: reasoning a kept turn\n * can't use is left out instead of risking a 400. Matches the id with or\n * without a platform prefix and with dated or tagged suffixes.\n *\n * @example\n * inferPreservedThinking(\"claude-opus-5-5\"); // → true\n * inferPreservedThinking(\"claude-opus-5\"); // → false\n * inferPreservedThinking(\"claude-opus-4-8\"); // → false\n */\nexport function inferPreservedThinking(modelName: string): boolean {\n const normalized = modelName.toLowerCase();\n const id = normalized.slice(normalized.lastIndexOf(\".\") + 1);\n\n if (PREFIX_CHECK_RELEASE_ROOTS.some((root) => matchesReleaseRoot(id, root))) {\n return true;\n }\n\n if (\n NO_PREFIX_CHECK_RELEASE_ROOTS.some((root) => matchesReleaseRoot(id, root)) ||\n NO_PREFIX_CHECK_FAMILY_PREFIXES.some((prefix) => id.startsWith(prefix))\n ) {\n return false;\n }\n\n return true;\n}\n","import { matchesReleaseRoot } from \"./thinking-mode\";\n\n/*\n * Documented maximum output tokens (`max_tokens`) on the synchronous\n * Messages API. Source: Anthropic's model pages and models overview,\n * platform.claude.com/docs/en/about-claude/models/overview and\n * …/models/{opus-4-5,sonnet-4-5,haiku-4-5}/overview, checked 2026-10-17.\n *\n * | Model ids | Max output |\n * |--------------------------------------------------------------|------------|\n * | Claude 5 family: fable-5 / 5.1, mythos-5 / 5.1, opus-5 / 5.5, | 128K |\n * | sonnet-5 / 5.5, haiku-5-5 | |\n * | claude-opus-4-8, claude-opus-4-7, claude-opus-4-6, | 128K |\n * | claude-sonnet-4-6 | |\n * | claude-opus-4-5, claude-sonnet-4-5, claude-haiku-4-5 | 64K |\n *\n * Older models (Claude 3.x, Opus 4 / 4.1, Sonnet 4) are retired and have no\n * entry; like any id not listed they fall back to the adapter default.\n */\n\n/** Family prefixes whose every release has a 128K output limit. */\nconst FAMILY_128K_PREFIXES = [\n \"claude-fable-5\",\n \"claude-mythos-5\",\n \"claude-opus-5\",\n \"claude-sonnet-5\",\n \"claude-haiku-5\",\n];\n\n/** Individual releases, matched as a release root (dated / `@` variants included). */\nconst RELEASE_OUTPUT_LIMITS: ReadonlyArray<readonly [root: string, limit: number]> = [\n [\"claude-opus-4-8\", 128_000],\n [\"claude-opus-4-7\", 128_000],\n [\"claude-opus-4-6\", 128_000],\n [\"claude-sonnet-4-6\", 128_000],\n [\"claude-opus-4-5\", 64_000],\n [\"claude-sonnet-4-5\", 64_000],\n [\"claude-haiku-4-5\", 64_000],\n];\n\n/**\n * The documented maximum output tokens of a Claude model, or `undefined`\n * when the id is not a known Claude model. Platform prefixes before\n * `claude-` (`anthropic.`, `us.anthropic.`) and dated or `@` snapshot\n * suffixes are accepted, so the Bedrock / Google Cloud ids of a known\n * model resolve too. Override per model with\n * `anthropic.model({ name, maxOutputTokens })`.\n *\n * @example\n * inferMaxOutputTokens(\"claude-opus-5-5\"); // → 128000\n * inferMaxOutputTokens(\"claude-haiku-4-5-20251001\"); // → 64000\n * inferMaxOutputTokens(\"my-gateway/model\"); // → undefined\n */\nexport function inferMaxOutputTokens(modelName: string): number | undefined {\n const lowered = modelName.toLowerCase();\n const start = lowered.indexOf(\"claude-\");\n\n if (start === -1) {\n return undefined;\n }\n\n const normalized = lowered.slice(start);\n\n if (FAMILY_128K_PREFIXES.some((prefix) => normalized.startsWith(prefix))) {\n return 128_000;\n }\n\n for (const [root, limit] of RELEASE_OUTPUT_LIMITS) {\n if (matchesReleaseRoot(normalized, root)) {\n return limit;\n }\n }\n\n return undefined;\n}\n","/**\n * Model-name prefixes for Claude families that accept image input\n * (vision) on the Messages API.\n *\n * Every Claude 3, Claude 3.5/3.7, Claude 4 and Claude 5 family model is\n * multimodal, so the list covers both the dotted legacy naming\n * (`claude-3-haiku-...`, `claude-3-5-sonnet-...`) and the current\n * `claude-<tier>-4-*` naming (`claude-opus-4-7`, `claude-sonnet-4-6`,\n * `claude-haiku-4-5`). Pre-3 families (`claude-2`, `claude-instant`)\n * are text-only and intentionally absent.\n *\n * The Claude 5 series is multimodal too (claude-api ref, cached\n * 2026-09-25): its vision examples use `claude-opus-5-5`; the models list\n * credits Claude Fable 5.1 with vision and Claude Sonnet 5 with\n * high-resolution vision; Claude Mythos 5.1 has \"same capabilities\" as\n * Fable 5.1. The tier-5 prefixes cover every 5.x release\n * (`claude-opus-5`, `claude-opus-5-5`, `claude-sonnet-5-5`,\n * `claude-fable-5-1`, …). Opus/Sonnet 4.6–4.8 are already covered by the\n * tier-4 prefixes.\n *\n * Matched as a prefix so dated variants (`claude-opus-4-20250514`) are\n * covered without listing every release tag. Devs can always override\n * per-model via `anthropic.model({ name, vision: true | false })` —\n * explicit config wins over inference in either direction.\n */\nconst VISION_CAPABLE_PREFIXES = [\n \"claude-3\",\n \"claude-4\",\n \"claude-opus-4\",\n \"claude-sonnet-4\",\n \"claude-haiku-4\",\n \"claude-opus-5\",\n \"claude-sonnet-5\",\n \"claude-fable-5\",\n \"claude-mythos-5\",\n];\n\n/**\n * Infer whether a given Claude model name supports vision based on the\n * known-prefix list. Unknown models default to `false` so that passing\n * an image attachment to an unsupported model surfaces a clear,\n * agent-side capability error instead of an opaque Anthropic 400.\n *\n * @example\n * inferVisionCapability(\"claude-sonnet-4-6\"); // → true\n * inferVisionCapability(\"claude-3-5-sonnet-latest\"); // → true\n * inferVisionCapability(\"claude-2.1\"); // → false\n * inferVisionCapability(\"custom-proxy-llm\"); // → false\n */\nexport function inferVisionCapability(modelName: string): boolean {\n const normalized = modelName.toLowerCase();\n\n return VISION_CAPABLE_PREFIXES.some((prefix) => normalized.startsWith(prefix));\n}\n","import type Anthropic from \"@anthropic-ai/sdk\";\nimport type { Usage } from \"@warlock.js/ai\";\n\n/** Installed @anthropic-ai/sdk 0.129.0 ServerToolUsage and MessageDeltaUsage use the same cumulative counters.\n * https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool\n * https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-fetch-tool\n * No code-execution request counter is reported: never count content blocks instead. */\nexport function applyServerToolUsage(\n usage: Usage,\n raw: Partial<Anthropic.ServerToolUsage> | null | undefined,\n): void {\n if (!raw) return;\n usage.serverToolUse = {\n ...usage.serverToolUse,\n ...(raw.web_search_requests !== undefined\n ? { webSearchRequests: raw.web_search_requests }\n : {}),\n ...(raw.web_fetch_requests !== undefined ? { webFetchRequests: raw.web_fetch_requests } : {}),\n };\n}\n","import type { Usage } from \"@warlock.js/ai\";\n\n/** The cache-related fields of an Anthropic usage block (final or streamed). */\nexport type AnthropicCacheUsage = {\n cache_read_input_tokens?: number | null;\n cache_creation_input_tokens?: number | null;\n cache_creation?: {\n ephemeral_1h_input_tokens?: number | null;\n ephemeral_5m_input_tokens?: number | null;\n } | null;\n};\n\n/**\n * Copy Anthropic's cache counters onto a neutral `Usage`.\n *\n * - `cache_read_input_tokens` → `cachedTokens`\n * - `cache_creation_input_tokens` → `cacheWriteTokens`\n * - `cache_creation.ephemeral_1h_input_tokens` → `cacheWrite1hTokens`\n * (the 1-hour writes, billed at 2x input instead of 1.25x)\n *\n * When Anthropic omits the per-lifetime breakdown, `requestTtl` decides:\n * a request whose every cache marker asked for `\"1h\"` wrote only 1-hour\n * entries. Counters are set only when positive, so an absent channel\n * stays undefined. Anthropic's `input_tokens` excludes all of these, so\n * the caller marks the usage `inputIncludesCache: false`.\n */\nexport function applyAnthropicCacheUsage(\n usage: Usage,\n raw: AnthropicCacheUsage,\n requestTtl: RequestCacheTtl,\n): void {\n const cacheRead = raw.cache_read_input_tokens;\n\n if (typeof cacheRead === \"number\" && cacheRead > 0) {\n usage.cachedTokens = cacheRead;\n }\n\n const cacheWrite = raw.cache_creation_input_tokens;\n\n if (typeof cacheWrite !== \"number\" || cacheWrite <= 0) {\n return;\n }\n\n usage.cacheWriteTokens = cacheWrite;\n\n const reported1h = raw.cache_creation?.ephemeral_1h_input_tokens;\n const writes1h =\n typeof reported1h === \"number\" ? reported1h : requestTtl === \"1h\" ? cacheWrite : 0;\n\n if (writes1h > 0) {\n usage.cacheWrite1hTokens = Math.min(writes1h, cacheWrite);\n }\n}\n\n/**\n * The cache lifetime a request body asked for: `\"1h\"` when every\n * `cache_control` marker in it says `ttl: \"1h\"`, `\"5m\"` when every marker\n * uses the default lifetime, `\"mixed\"` when both appear, and `undefined`\n * when the body carries no marker.\n */\nexport type RequestCacheTtl = \"1h\" | \"5m\" | \"mixed\" | undefined;\n\n/**\n * Scan a request body (top level, system, tools, messages) for\n * `cache_control` markers and report the lifetime they request. Used only\n * as a fallback when the response lacks Anthropic's per-lifetime\n * cache-write breakdown.\n *\n * @example\n * requestCacheTtl({ cache_control: { type: \"ephemeral\", ttl: \"1h\" } }); // \"1h\"\n */\nexport function requestCacheTtl(body: unknown): RequestCacheTtl {\n let found: RequestCacheTtl;\n\n const visit = (value: unknown, depth: number): void => {\n if (depth > 8 || typeof value !== \"object\" || value === null) {\n return;\n }\n\n if (Array.isArray(value)) {\n for (const item of value) {\n visit(item, depth + 1);\n }\n\n return;\n }\n\n const record = value as Record<string, unknown>;\n const marker = record.cache_control;\n\n if (typeof marker === \"object\" && marker !== null) {\n const ttl = (marker as { ttl?: unknown }).ttl === \"1h\" ? \"1h\" : \"5m\";\n found = found === undefined || found === ttl ? ttl : \"mixed\";\n }\n\n for (const key of [\"system\", \"tools\", \"messages\", \"content\"] as const) {\n if (key in record) {\n visit(record[key], depth + 1);\n }\n }\n };\n\n visit(body, 0);\n\n return found;\n}\n","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","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","import type { ContentPart, Message, ModelToolCallRequest } from \"@warlock.js/ai\";\nimport type Anthropic from \"@anthropic-ai/sdk\";\nimport { fromProviderBlocks } from \"./provider-blocks\";\n\n/**\n * Result of splitting a vendor-neutral `Message[]` for the Anthropic\n * Messages API: the system prompt is hoisted to a top-level `system`\n * string (Anthropic has no `\"system\"` role inside `messages`), and the\n * remaining turns are mapped to `MessageParam[]`.\n */\nexport type AnthropicMessages = {\n system: string | undefined;\n messages: Anthropic.MessageParam[];\n};\n\n/** Options for {@link toAnthropicMessages}. */\nexport type ToAnthropicMessagesOptions = {\n /**\n * Leave out the `thinking` / `redacted_thinking` blocks of assistant turns\n * marked `compaction: \"retained\"` — turns kept verbatim after a\n * client-written summary. On models that run the preserved-thinking\n * conversation check those blocks were produced against the replaced\n * history, so replaying them is a 400 (or a server-side drop). Text and\n * tool-use blocks stay. Removing them is the no-beta path Anthropic\n * documents for compaction that keeps recent turns.\n */\n dropRetainedThinking?: boolean;\n};\n\nconst ANTHROPIC_IMAGE_MEDIA_TYPES = [\"image/jpeg\", \"image/png\", \"image/gif\", \"image/webp\"] as const;\n\ntype AnthropicImageMediaType = (typeof ANTHROPIC_IMAGE_MEDIA_TYPES)[number];\n\n/**\n * Convert vendor-neutral `Message[]` into Anthropic's request shape.\n *\n * Anthropic differs from the OpenAI Chat protocol in three ways this\n * function absorbs:\n *\n * 1. **No `system` role.** System messages are concatenated (newline-\n * separated) and returned separately as the top-level `system`\n * parameter.\n * 2. **Tool results are `user` turns.** A neutral `tool` message becomes\n * a `tool_result` block keyed by `tool_use_id`. Consecutive tool\n * messages (the results of one parallel tool-use turn) are grouped\n * into a single `user` message, as Anthropic expects — splitting them\n * across messages teaches the model to stop calling tools in parallel.\n * 3. **Tool calls are `tool_use` content blocks.** An assistant message\n * carrying `toolCalls` becomes an `assistant` message whose content\n * is an optional leading `text` block followed by one `tool_use`\n * block per call.\n *\n * An assistant message that carries Anthropic `blocks` (thinking,\n * redacted thinking, compaction, server-tool blocks — see\n * `ProviderContentBlock`) is replayed verbatim from those blocks, which\n * keeps signed thinking and compaction state valid. Blocks from another\n * provider, or blocks whose `tool_use` ids no longer match `toolCalls`,\n * are ignored and the turn is rebuilt from `content` + `toolCalls`.\n *\n * With `dropRetainedThinking`, a turn marked `compaction: \"retained\"` is\n * replayed without its thinking blocks (see {@link ToAnthropicMessagesOptions}).\n *\n * Other consecutive same-role turns are left as-is — the Messages API\n * merges them server-side.\n *\n * @example\n * const { system, messages } = toAnthropicMessages([\n * { role: \"system\", content: \"Be concise.\" },\n * { role: \"user\", content: \"Hi\" },\n * ]);\n * // system === \"Be concise.\"\n * // messages === [{ role: \"user\", content: \"Hi\" }]\n */\nexport function toAnthropicMessages(\n messages: Message[],\n options: ToAnthropicMessagesOptions = {},\n): AnthropicMessages {\n const systemParts: string[] = [];\n const mapped: Anthropic.MessageParam[] = [];\n\n for (const message of messages) {\n if (message.role === \"system\") {\n systemParts.push(stringifyContent(message.content));\n\n continue;\n }\n\n if (message.role === \"tool\") {\n const toolResult: Anthropic.ToolResultBlockParam = {\n type: \"tool_result\",\n tool_use_id: message.toolCallId ?? \"\",\n content: stringifyContent(message.content),\n };\n const previous = mapped[mapped.length - 1];\n\n if (previous && previous.role === \"user\" && isToolResultTurn(previous)) {\n previous.content.push(toolResult);\n } else {\n mapped.push({ role: \"user\", content: [toolResult] });\n }\n\n continue;\n }\n\n const dropThinking = options.dropRetainedThinking === true && message.compaction === \"retained\";\n\n if (message.role === \"assistant\") {\n const replayed = fromProviderBlocks(message.blocks, message.toolCalls);\n const content = dropThinking\n ? replayed?.filter((block) => !isThinkingBlock(block))\n : replayed;\n\n if (content && content.length > 0) {\n mapped.push({ role: \"assistant\", content });\n\n continue;\n }\n }\n\n if (message.role === \"assistant\" && message.toolCalls && message.toolCalls.length > 0) {\n const blocks: Anthropic.ContentBlockParam[] = dropThinking\n ? []\n : extractThinkingBlocks(message.toolCalls);\n const text = stringifyContent(message.content);\n\n if (text) {\n blocks.push({ type: \"text\", text });\n }\n\n for (const toolCall of message.toolCalls) {\n blocks.push({\n type: \"tool_use\",\n id: toolCall.id,\n name: toolCall.name,\n input: toolCall.input ?? {},\n });\n }\n\n mapped.push({ role: \"assistant\", content: blocks });\n\n continue;\n }\n\n if (message.role === \"user\" && Array.isArray(message.content)) {\n mapped.push({\n role: \"user\",\n content: message.content.map(toAnthropicContentBlock),\n });\n\n continue;\n }\n\n mapped.push({\n role: message.role === \"assistant\" ? \"assistant\" : \"user\",\n content: stringifyContent(message.content),\n });\n }\n\n return {\n system: systemParts.length > 0 ? systemParts.join(\"\\n\\n\") : undefined,\n messages: mapped,\n };\n}\n\nfunction isThinkingBlock(block: Anthropic.ContentBlockParam): boolean {\n return block.type === \"thinking\" || block.type === \"redacted_thinking\";\n}\n\n/**\n * Recover signed extended-thinking blocks stored by this adapter on a tool\n * request. Anthropic requires these blocks to be replayed before the\n * assistant's text and tool uses on the following request.\n */\nfunction extractThinkingBlocks(toolCalls: ModelToolCallRequest[]): Anthropic.ContentBlockParam[] {\n for (const toolCall of toolCalls) {\n const anthropic = toolCall.providerMetadata?.anthropic;\n\n if (!isRecord(anthropic) || !Array.isArray(anthropic.thinkingBlocks)) {\n continue;\n }\n\n return anthropic.thinkingBlocks.flatMap(toAnthropicThinkingBlock);\n }\n\n return [];\n}\n\nfunction toAnthropicThinkingBlock(block: unknown): Anthropic.ContentBlockParam[] {\n if (!isRecord(block) || typeof block.type !== \"string\") {\n return [];\n }\n\n if (\n block.type === \"thinking\" &&\n typeof block.thinking === \"string\" &&\n typeof block.signature === \"string\"\n ) {\n return [{ type: \"thinking\", thinking: block.thinking, signature: block.signature }];\n }\n\n if (block.type === \"redacted_thinking\" && typeof block.data === \"string\") {\n return [{ type: \"redacted_thinking\", data: block.data }];\n }\n\n return [];\n}\n\n/**\n * A `user` turn this function built from tool results — its content is a\n * non-empty array made only of `tool_result` blocks. Later tool results\n * of the same tool-use turn are appended to it.\n */\nfunction isToolResultTurn(\n message: Anthropic.MessageParam,\n): message is Anthropic.MessageParam & { content: Anthropic.ContentBlockParam[] } {\n return (\n Array.isArray(message.content) &&\n message.content.length > 0 &&\n message.content.every((block) => block.type === \"tool_result\")\n );\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\n/**\n * Multipart content is only meaningful on user messages — for any other\n * role collapse a `ContentPart[]` to its concatenated text so the wire\n * format stays valid. Plain strings pass through unchanged.\n */\nfunction stringifyContent(content: string | ContentPart[]): string {\n if (typeof content === \"string\") {\n return content;\n }\n\n return content\n .filter((part): part is { type: \"text\"; text: string } => part.type === \"text\")\n .map((part) => part.text)\n .join(\"\");\n}\n\n/**\n * Map a single resolved `ContentPart` to an Anthropic content block.\n * Text passes straight through; images become an `image` block with a\n * `url` source (remote) or a `base64` source (inlined bytes). The\n * agent has already resolved every attachment before it reaches here,\n * so this never reads files or fetches URLs.\n */\nfunction toAnthropicContentBlock(part: ContentPart): Anthropic.ContentBlockParam {\n if (part.type === \"text\") {\n return { type: \"text\", text: part.text };\n }\n\n // PDF → Anthropic `document` block (A2). The Messages API accepts a\n // url or base64 `application/pdf` source on PDF-capable Claude models.\n if (part.type === \"pdf\") {\n const source =\n \"url\" in part.source\n ? { type: \"url\", url: part.source.url }\n : { type: \"base64\", media_type: \"application/pdf\", data: part.source.base64 };\n return { type: \"document\", source } as unknown as Anthropic.ContentBlockParam;\n }\n\n // Anthropic has no audio content block; the agent's capability gate\n // normally prevents this, but stay loud rather than mis-map it.\n if (part.type === \"audio\") {\n throw new Error(\"Anthropic adapter: audio attachments are not supported\");\n }\n\n if (\"url\" in part.source) {\n return { type: \"image\", source: { type: \"url\", url: part.source.url } };\n }\n\n return {\n type: \"image\",\n source: {\n type: \"base64\",\n media_type: part.source.mediaType as AnthropicImageMediaType,\n data: part.source.base64,\n },\n };\n}\n","import { extractJsonSchema, type ToolConfig } from \"@warlock.js/ai\";\nimport type Anthropic from \"@anthropic-ai/sdk\";\n\n/**\n * Convert vendor-neutral `ToolConfig[]` into Anthropic's `tools` array.\n * Uses the shared `extractJsonSchema` helper; Anthropic requires the\n * input schema to be a JSON-Schema object, so a non-object extraction\n * is coerced into an empty-object schema rather than rejected — the\n * tool still registers and the model simply sees no parameters.\n *\n * @example\n * const tools = toAnthropicTools([weatherTool, calculatorTool]);\n * await client.messages.create({ model, max_tokens, messages, tools });\n */\nexport function toAnthropicTools(\n tools: ToolConfig<unknown, unknown>[] | undefined,\n): Anthropic.Tool[] | undefined {\n if (!tools || tools.length === 0) {\n return undefined;\n }\n\n return tools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n input_schema: toInputSchema(tool.input),\n }));\n}\n\n/**\n * Coerce the extracted JSON Schema into Anthropic's `Tool.InputSchema`\n * shape (root must be `{ type: \"object\" }`). Anything that isn't an\n * object schema degrades to a parameterless object so registration\n * never fails on a malformed extractor result.\n */\nfunction toInputSchema(input: ToolConfig<unknown, unknown>[\"input\"]): Anthropic.Tool.InputSchema {\n const schema = extractJsonSchema(input);\n\n if (schema && schema.type === \"object\") {\n return schema as Anthropic.Tool.InputSchema;\n }\n\n return { type: \"object\" };\n}\n","import {\n AIError,\n ContextLengthExceededError,\n InvalidRequestError,\n ProviderAuthError,\n ProviderError,\n ProviderOverloadedError,\n ProviderRateLimitError,\n ProviderTimeoutError,\n QuotaExceededError,\n} from \"@warlock.js/ai\";\nimport { APIConnectionTimeoutError, APIError } from \"@anthropic-ai/sdk\";\n\n/**\n * Raw-error fields the wrapper reads off an Anthropic SDK error.\n *\n * `APIError` exposes `status`, `type` (the `error.type` from the\n * response body, e.g. `\"rate_limit_error\"`), `message`, `headers`, and\n * `requestID`. We duck-type because wrapped retries, proxied errors,\n * and custom subclasses sometimes lose the `instanceof` relationship.\n */\ntype AnthropicErrorShape = {\n status?: number;\n type?: string | null;\n message?: string;\n headers?: HeaderBag | undefined;\n name?: string;\n requestId?: string;\n};\n\n/** Either a fetch `Headers` instance or a plain record (duck-typed tests). */\ntype HeaderBag = Headers | Record<string, string>;\n\n/**\n * Wrap any thrown value caught inside the Anthropic adapter into the\n * appropriate `@warlock.js/ai` `AIError` subclass.\n *\n * **Dispatch strategy.** Anthropic has no per-error machine `code`; the\n * stable identifier is `error.type` on the response body (surfaced as\n * `APIError.type`). Dispatch prefers `type`, falls back to `status`\n * when the body was stripped (common with proxies). Name-based\n * detection catches transport-layer timeouts that never produced an\n * HTTP response. The `invalid_request_error` branch additionally\n * sniffs the message for Anthropic's \"prompt is too long\" phrasing,\n * which is the only signal that a 400 was a context-length overflow.\n *\n * `AIError` instances pass through unchanged so `catch/throw wrap(e)`\n * pipelines never double-wrap.\n *\n * @example\n * try {\n * return await this.client.messages.create(...);\n * } catch (thrown) {\n * throw wrapAnthropicError(thrown);\n * }\n */\nexport function wrapAnthropicError(thrown: unknown): AIError {\n if (thrown instanceof AIError) {\n return thrown;\n }\n\n const shape = toShape(thrown);\n const context = buildContext(shape);\n const message = shape.message ?? (thrown instanceof Error ? thrown.message : String(thrown));\n\n if (isTimeout(thrown, shape)) {\n return new ProviderTimeoutError(message, { cause: thrown, context });\n }\n\n if (shape.type === \"authentication_error\" || shape.type === \"permission_error\") {\n return new ProviderAuthError(message, { cause: thrown, context });\n }\n\n if (shape.status === 401 || shape.status === 403) {\n return new ProviderAuthError(message, { cause: thrown, context });\n }\n\n if (shape.type === \"billing_error\") {\n return new QuotaExceededError(message, { cause: thrown, context });\n }\n\n if (shape.type === \"rate_limit_error\" || shape.status === 429) {\n return new ProviderRateLimitError(message, {\n cause: thrown,\n context,\n retryAfter: parseRetryAfter(shape.headers),\n });\n }\n\n // HTTP 529 / `overloaded_error` — also delivered as a mid-stream SSE\n // `error` event, where no status exists.\n if (shape.type === \"overloaded_error\" || shape.status === 529) {\n return new ProviderOverloadedError(message, {\n cause: thrown,\n context,\n retryAfter: parseRetryAfter(shape.headers),\n });\n }\n\n if (shape.type === \"invalid_request_error\" || isClientStatus(shape.status)) {\n if (/prompt is too long/i.test(message)) {\n return new ContextLengthExceededError(message, { cause: thrown, context });\n }\n\n return new InvalidRequestError(message, { cause: thrown, context });\n }\n\n return new ProviderError(message, { cause: thrown, context });\n}\n\n/**\n * Read the raw error shape without depending on `instanceof APIError`\n * — proxies and re-wrappers strip the prototype chain. Duck-typing on\n * the visible fields is resilient to both.\n */\nfunction toShape(thrown: unknown): AnthropicErrorShape {\n if (thrown instanceof APIError) {\n return {\n status: typeof thrown.status === \"number\" ? thrown.status : undefined,\n type: thrown.type,\n message: thrown.message,\n headers: thrown.headers,\n name: thrown.name,\n requestId: thrown.requestID ?? undefined,\n };\n }\n\n if (typeof thrown === \"object\" && thrown !== null) {\n const raw = thrown as Record<string, unknown>;\n\n return {\n status: typeof raw.status === \"number\" ? raw.status : undefined,\n type: typeof raw.type === \"string\" ? raw.type : undefined,\n message: typeof raw.message === \"string\" ? raw.message : undefined,\n headers: isHeaderBag(raw.headers) ? raw.headers : undefined,\n name: typeof raw.name === \"string\" ? raw.name : undefined,\n requestId: readRequestId(raw),\n };\n }\n\n return {};\n}\n\n/**\n * Decide whether the thrown value represents a timeout. The Anthropic\n * SDK throws `APIConnectionTimeoutError` for transport-level timeouts;\n * Node surfaces `ETIMEDOUT` / `ECONNABORTED` on the socket layer.\n * Either signal counts.\n */\nfunction isTimeout(thrown: unknown, shape: AnthropicErrorShape): boolean {\n if (thrown instanceof APIConnectionTimeoutError) {\n return true;\n }\n\n if (shape.name === \"APIConnectionTimeoutError\") {\n return true;\n }\n\n if (typeof thrown === \"object\" && thrown !== null) {\n const code = (thrown as Record<string, unknown>).code;\n\n if (code === \"ETIMEDOUT\" || code === \"ECONNABORTED\") {\n return true;\n }\n }\n\n return false;\n}\n\n/** True for HTTP 4xx — a client-side request problem, not a server fault. */\nfunction isClientStatus(status: number | undefined): boolean {\n return typeof status === \"number\" && status >= 400 && status < 500;\n}\n\n/**\n * Attach the raw diagnostic fields to `error.context` so consumers\n * have everything the provider surfaced without each subclass having\n * to redeclare them. Never includes `cause` — that lives on\n * `error.cause`.\n */\nfunction buildContext(shape: AnthropicErrorShape): Record<string, unknown> {\n const context: Record<string, unknown> = {};\n\n if (shape.status !== undefined) {\n context.status = shape.status;\n }\n\n if (shape.type) {\n context.type = shape.type;\n }\n\n if (shape.requestId) {\n context.requestId = shape.requestId;\n }\n\n return context;\n}\n\n/** Anthropic exposes the request id as `requestID`; some proxies use `request_id`. */\nfunction readRequestId(raw: Record<string, unknown>): string | undefined {\n if (typeof raw.requestID === \"string\") {\n return raw.requestID;\n }\n\n if (typeof raw.request_id === \"string\") {\n return raw.request_id;\n }\n\n return undefined;\n}\n\nfunction isHeaderBag(value: unknown): value is HeaderBag {\n return typeof value === \"object\" && value !== null;\n}\n\n/** Read a header value from either a `Headers` instance or a plain record. */\nfunction readHeader(headers: HeaderBag, name: string): string | undefined {\n if (typeof (headers as Headers).get === \"function\") {\n return (headers as Headers).get(name) ?? undefined;\n }\n\n const record = headers as Record<string, string>;\n\n return record[name] ?? record[name.toLowerCase()];\n}\n\n/**\n * Parse the `Retry-After` response header (seconds per HTTP spec) into\n * milliseconds so consumers can feed it straight to `setTimeout`.\n * Returns `undefined` when missing or unparseable.\n */\nfunction parseRetryAfter(headers: HeaderBag | undefined): number | undefined {\n if (!headers) {\n return undefined;\n }\n\n const raw = readHeader(headers, \"retry-after\") ?? readHeader(headers, \"Retry-After\");\n\n if (!raw) {\n return undefined;\n }\n\n const seconds = Number(raw);\n\n if (!Number.isFinite(seconds) || seconds < 0) {\n return undefined;\n }\n\n return Math.round(seconds * 1000);\n}\n","import {\n AIError,\n computeCost,\n InvalidRequestError,\n resolveStreamChunks,\n safeJsonParse,\n selectProviderTools,\n type Message,\n type ModelCallOptions,\n type ModelCapabilities,\n type ModelContract,\n type ModelPricing,\n type ModelResponse,\n type ModelStreamChunk,\n type ModelToolCallRequest,\n type ReasoningEffort,\n type Usage,\n} from \"@warlock.js/ai\";\nimport { log, type Logger } from \"@warlock.js/logger\";\nimport type Anthropic from \"@anthropic-ai/sdk\";\nimport type {\n AnthropicCallOptions,\n AnthropicClearThinking,\n AnthropicClearToolUses,\n AnthropicModelConfig,\n} from \"./config.type\";\nimport type {\n AnthropicRequest,\n AnthropicRequestOptions,\n AnthropicStreamingRequest,\n AnthropicNonStreamingRequest,\n} from \"./request.type\";\nimport { anthropicPricingFor, withAnthropicCacheWriteRates } from \"./known-pricing\";\nimport { inferMaxOutputTokens } from \"./known-output-limits\";\nimport { inferVisionCapability } from \"./known-vision-models\";\nimport {\n acceptsTemperature,\n inferPreservedThinking,\n inferThinkingMode,\n type AnthropicThinkingMode,\n noReasoningForm,\n} from \"./thinking-mode\";\nimport { applyServerToolUsage } from \"./utils/server-tool-usage\";\nimport { applyAnthropicCacheUsage, requestCacheTtl } from \"./utils/cache-usage\";\nimport {\n mapStopReason,\n toAnthropicMessages,\n toAnthropicTools,\n toProviderBlocks,\n wrapAnthropicError,\n} from \"./utils\";\n\nconst LOG_MODULE = \"ai.anthropic\";\n\n/** `provider` value of `ai.providerTool()` entries this adapter sends verbatim. */\nconst ANTHROPIC_WIRE_FORMAT = \"anthropic\";\n\n/**\n * Anthropic requires `max_tokens` on every request (unlike OpenAI,\n * where it is optional). When neither the per-call option nor the model\n * config supplies one, the adapter picks a default large enough for agent\n * work (see `resolveDefaultMaxTokens`):\n *\n * - streaming: the model's documented max output (`known-output-limits.ts`,\n * or `config.maxOutputTokens`), else this value;\n * - non-streaming: this value, capped by the model's max output. The\n * installed `@anthropic-ai/sdk` (0.129.0, `calculateNonstreamingTimeout`)\n * refuses a non-streaming request whose `max_tokens` implies more than\n * ten minutes (above ~21,333 tokens) unless the client sets a `timeout`,\n * so the non-streaming default stays below that.\n */\nconst DEFAULT_MAX_TOKENS = 16_384;\n\n/**\n * Answer room kept on top of a thinking budget when the default\n * `max_tokens` is sized: thinking counts toward `max_tokens` (installed\n * SDK `ThinkingConfigParam` docs, `messages.d.ts:1105`), and in budget\n * mode `max_tokens` must exceed `budget_tokens`.\n */\nconst MIN_ANSWER_TOKENS = 4096;\n\n/**\n * Anthropic rejects an extended-thinking budget below 1024 tokens, so\n * any resolved budget is floored at this minimum before it reaches the\n * wire.\n */\nconst MIN_THINKING_BUDGET = 1024;\n\ntype ThinkingEffort = Exclude<ReasoningEffort, \"none\">;\n\n/**\n * Effort used when the caller asks for reasoning with only\n * `reasoning.maxTokens` and no `effort`. `\"medium\"` is what the adapter\n * has always assumed (the budget lookup fell back to\n * `EFFORT_THINKING_BUDGET.medium`), so adaptive models get the same tier.\n */\nconst DEFAULT_THINKING_EFFORT: ThinkingEffort = \"medium\";\n\n/**\n * Map the neutral `ReasoningEffort` level to a thinking token count.\n *\n * - Budget-mode models: sent as `thinking.budget_tokens` when the caller\n * doesn't pass an explicit `reasoning.maxTokens`.\n * - Both modes: when the caller sets no `maxTokens`, the default\n * `max_tokens` keeps at least this budget plus `MIN_ANSWER_TOKENS`,\n * because thinking counts toward `max_tokens` (installed SDK\n * `ThinkingConfigParam` docs, `messages.d.ts:1105`).\n */\nconst EFFORT_THINKING_BUDGET: Record<ThinkingEffort, number> = {\n // Anthropic's adaptive output config has no `minimal`; keep the minimum\n // budget for it in legacy budget mode too.\n minimal: 1024,\n low: 1024,\n medium: 4096,\n high: 12000,\n // Keep the tiers monotonic for older budget-mode models. Explicit\n // reasoning.maxTokens still wins and the existing max_tokens validation\n // remains authoritative.\n xhigh: 24000,\n max: 32000,\n};\n\n/**\n * Map the neutral `ReasoningEffort` level to Anthropic's\n * `output_config.effort` for adaptive-mode models. The installed SDK\n * accepts `low | medium | high | xhigh | max` (`OutputConfig.effort`,\n * `messages.ts:2767`); map every supported value 1:1 and clamp `minimal` to\n * the nearest accepted value, `low`.\n */\nconst EFFORT_TO_OUTPUT_EFFORT: Record<\n ThinkingEffort,\n NonNullable<Anthropic.OutputConfig[\"effort\"]>\n> = {\n minimal: \"low\",\n low: \"low\",\n medium: \"medium\",\n high: \"high\",\n xhigh: \"xhigh\",\n max: \"max\",\n};\n\ntype AnthropicThinkingBlock = Anthropic.ThinkingBlock | Anthropic.RedactedThinkingBlock;\n\n/**\n * The SDK's `messages.create` (or `beta.messages.create`) seen through a\n * loose signature: provider-option body fields and beta flags are merged\n * in untyped, and the response is narrowed by the caller.\n */\ntype LooseCreate = (\n body: Record<string, unknown>,\n options?: { signal?: AbortSignal },\n) => Promise<unknown>;\n\n/** Content-block types whose input arrives as `input_json_delta` while streaming. */\nconst STREAMED_INPUT_BLOCK_TYPES = new Set([\"tool_use\", \"server_tool_use\", \"mcp_tool_use\"]);\n\n/** One content block being assembled from stream events. */\ntype StreamedBlock = { block: Record<string, unknown>; json?: string };\n\n/**\n * Resolved thinking settings for one request.\n *\n * - `thinking`: the wire `thinking` field (absent = send nothing).\n * - `effort`: `output_config.effort`, set for adaptive-mode models only.\n * - `reservedTokens`: thinking tokens the default `max_tokens` must leave\n * room for (plus `MIN_ANSWER_TOKENS`) when the caller configured no\n * `maxTokens`.\n */\ntype ThinkingRequest = {\n thinking?: Anthropic.ThinkingConfigParam;\n effort?: Anthropic.OutputConfig[\"effort\"];\n reservedTokens?: number;\n};\n\n/**\n * Anthropic-backed implementation of `ModelContract`.\n *\n * **Role.** The provider-facing bridge between the vendor-neutral\n * `@warlock.js/ai` agent runtime and the official `@anthropic-ai/sdk`\n * Messages API. Agents, workflows, and supervisors never talk to\n * Anthropic directly — they hold a `ModelContract`, and this class is\n * what makes that contract concrete for Claude models.\n *\n * **Responsibility.**\n * - Owns: a long-lived `Anthropic` client + frozen `ModelConfig`\n * (name, temperature, maxTokens) used as defaults for every call.\n * - Owns: translating vendor-neutral `Message[]` / `ToolConfig[]` into\n * Anthropic wire shapes (system hoisting, `tool_use` / `tool_result`\n * blocks) on the way out, and translating Anthropic's content-block\n * response (text, tool calls, stop reason, usage) back into the\n * neutral shapes on the way in.\n * - Does NOT own: dispatching tools, deciding whether to loop, tracking\n * conversation history, or retrying on failure — those are agent\n * concerns. The model is a stateless (per-call) protocol adapter.\n *\n * Because it holds a live client and shared defaults, it is modeled as\n * a class (see §4.2 of code-style.md — \"long-lived state across\n * calls\").\n *\n * @example\n * import Anthropic from \"@anthropic-ai/sdk\";\n * const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });\n * const model = new AnthropicModel(client, { name: \"claude-sonnet-4-6\" });\n *\n * const myAgent = agent({\n * model,\n * systemPrompt: \"You are a helpful assistant.\",\n * tools: [searchTool],\n * });\n *\n * const result = await myAgent.execute(\"Summarize today's news.\");\n */\nexport class AnthropicModel implements ModelContract {\n public readonly name: string;\n public readonly provider: string;\n public readonly capabilities: ModelCapabilities;\n public readonly pricing?: ModelPricing;\n\n private readonly client: Anthropic;\n private readonly config: AnthropicModelConfig;\n private readonly thinkingMode: AnthropicThinkingMode;\n /** Documented max output tokens of this model, when known. Sizes the default `max_tokens`. */\n private readonly maxOutputTokens?: number;\n private readonly preservedThinking: boolean;\n private readonly logger: Logger = log;\n\n public constructor(\n client: Anthropic,\n config: AnthropicModelConfig,\n provider: string = \"anthropic\",\n ) {\n this.client = client;\n this.config = config;\n this.name = config.name;\n this.provider = provider;\n // Explicit pricing (per-model, or the SDK registry) wins over the\n // built-in Claude list prices; either way the Anthropic cache-write\n // multipliers fill any write rate the entry leaves out.\n this.pricing = withAnthropicCacheWriteRates(config.pricing ?? anthropicPricingFor(config.name));\n // Adaptive vs budget thinking — also decides whether `temperature` is\n // accepted. Explicit config wins over name inference, like `vision`.\n this.thinkingMode = config.thinkingMode ?? inferThinkingMode(config.name);\n this.maxOutputTokens = config.maxOutputTokens ?? inferMaxOutputTokens(config.name);\n // Budget-mode models predate preserved thinking; explicit config wins.\n this.preservedThinking =\n config.preservedThinking ??\n (this.thinkingMode === \"adaptive\" && inferPreservedThinking(config.name));\n this.capabilities = {\n structuredOutput: config.structuredOutput ?? true,\n vision: config.vision ?? inferVisionCapability(config.name),\n // Every modern Claude model accepts Anthropic extended thinking\n // (adaptive or `budget_tokens`, per `thinkingMode`). Advertise the\n // reasoning channel so the agent forwards `reasoning` options;\n // explicit config override wins for proxied/legacy targets.\n reasoning: config.reasoning ?? true,\n // Anthropic prompt caching is caller-driven via `cache_control`\n // breakpoints. The adapter both places those breakpoints (tools\n // when `config.promptCaching`, system when\n // `options.cacheControl.breakpoints`) and reports the read/write\n // accounting (`cachedTokens` / `cacheWriteTokens`), so advertise\n // the capability unconditionally.\n promptCaching: true,\n // The Messages API accepts PDF/document content blocks\n // (`DocumentBlockParam`) on vision-capable Claude models.\n pdf: true,\n // Anthropic has no audio input content block, so `audio` stays\n // absent (treated as false) and the agent rejects audio\n // attachments upfront rather than dropping them at the wire layer.\n };\n }\n\n /**\n * Single-shot completion. Sends the full message list to the Messages\n * endpoint, waits for the terminal response, and reshapes it into a\n * vendor-neutral `ModelResponse`. Per-call `options` override the\n * instance's `ModelConfig` defaults for this call only.\n */\n public async complete(messages: Message[], options?: ModelCallOptions): Promise<ModelResponse> {\n return this.send(this.buildLoggedRequest(messages, { ...options, stream: false }), {\n signal: options?.signal,\n });\n }\n\n /** Build a detached request snapshot without sending it to Anthropic. */\n public buildRequest(\n messages: Message[],\n options: ModelCallOptions & { stream: true },\n ): AnthropicStreamingRequest;\n public buildRequest(\n messages: Message[],\n options?: ModelCallOptions & { stream?: false },\n ): AnthropicNonStreamingRequest;\n public buildRequest(\n messages: Message[],\n options?: ModelCallOptions & { stream?: boolean },\n ): AnthropicRequest;\n public buildRequest(\n messages: Message[],\n options?: ModelCallOptions & { stream?: boolean },\n ): AnthropicRequest {\n const built = this.buildBody(messages, options);\n const betas = [...new Set([...(resolveAnthropicOptions(options).betas ?? []), ...built.betas])];\n const body = structuredClone({ ...built.body, stream: options?.stream ?? false });\n\n return { endpoint: betas.length > 0 ? \"beta.messages\" : \"messages\", body, betas };\n }\n\n /**\n * `buildRequest()` for the adapter's own calls: a build failure (a reserved\n * body key, a `providerOptions.anthropic.body` value `structuredClone`\n * cannot copy) is logged like a send failure and rejects as an `AIError`.\n * Errors that are not already an `AIError` become an `InvalidRequestError`,\n * since nothing reached Anthropic and retrying cannot help.\n */\n private buildLoggedRequest(\n messages: Message[],\n options: ModelCallOptions & { stream: true },\n ): AnthropicStreamingRequest;\n private buildLoggedRequest(\n messages: Message[],\n options: ModelCallOptions & { stream: false },\n ): AnthropicNonStreamingRequest;\n private buildLoggedRequest(\n messages: Message[],\n options: ModelCallOptions & { stream: boolean },\n ): AnthropicRequest;\n private buildLoggedRequest(\n messages: Message[],\n options: ModelCallOptions & { stream: boolean },\n ): AnthropicRequest {\n try {\n return this.buildRequest(messages, options);\n } catch (thrown) {\n throw this.logAndWrap(\n thrown instanceof AIError\n ? thrown\n : new InvalidRequestError(\n `Could not build the Anthropic request: ${thrown instanceof Error ? thrown.message : String(thrown)}`,\n { cause: thrown },\n ),\n );\n }\n }\n\n /** Send a built request without rebuilding its body or applying model defaults. */\n public send(\n request: AnthropicNonStreamingRequest,\n options?: AnthropicRequestOptions,\n ): Promise<ModelResponse>;\n public send(\n request: AnthropicStreamingRequest,\n options?: AnthropicRequestOptions,\n ): AsyncIterable<ModelStreamChunk>;\n public send(\n request: AnthropicRequest,\n options?: AnthropicRequestOptions,\n ): Promise<ModelResponse> | AsyncIterable<ModelStreamChunk>;\n public send(\n request: AnthropicRequest,\n options?: AnthropicRequestOptions,\n ): Promise<ModelResponse> | AsyncIterable<ModelStreamChunk> {\n const message = request.body.stream\n ? \"Starting streaming call to messages.create\"\n : \"Starting call to messages.create\";\n\n this.logger.debug(LOG_MODULE, \"request\", message, {\n model: request.body.model,\n messageCount: Array.isArray(request.body.messages) ? request.body.messages.length : 0,\n streaming: request.body.stream,\n toolCount: Array.isArray(request.body.tools) ? request.body.tools.length : 0,\n });\n\n return request.body.stream\n ? this.streamRequest(request, options)\n : this.completeRequest(request, options);\n }\n\n private async completeRequest(\n request: AnthropicRequest,\n options?: AnthropicRequestOptions,\n ): Promise<ModelResponse> {\n let response: Anthropic.Message;\n\n try {\n response = (await this.dispatch(request, options, \"create\")) as Anthropic.Message;\n } catch (thrown) {\n throw this.logAndWrap(thrown);\n }\n\n const finishReason = mapStopReason(response.stop_reason);\n const usage = this.extractUsage(response.usage, requestCacheTtl(request.body));\n const toolCalls = this.extractToolCalls(response.content);\n const blocks = toProviderBlocks(response.content);\n\n this.logger.debug(LOG_MODULE, \"response\", \"call to messages.create succeeded\", {\n finishReason,\n usage,\n });\n\n return {\n content: this.extractText(response.content),\n finishReason,\n usage,\n toolCalls,\n ...(blocks ? { blocks } : {}),\n };\n }\n\n /**\n * Count the input tokens a request would use, through Anthropic's\n * `messages.countTokens` endpoint (a network call; no tokens are\n * generated or billed as output). Takes the same messages and options\n * as `complete()` — system prompt, tools, thinking and\n * `providerOptions.anthropic.betas` are counted exactly as they would be\n * sent. For an offline estimate use `AnthropicSDK.count()`.\n *\n * @example\n * const tokens = await model.countTokens(messages, { tools });\n */\n public async countTokens(messages: Message[], options?: ModelCallOptions): Promise<number> {\n const request = this.buildLoggedRequest(messages, {\n ...options,\n stream: options?.stream === true,\n });\n const body = request.body;\n const countBody: Record<string, unknown> = {};\n\n for (const key of COUNT_TOKENS_FIELDS) {\n if (body[key] !== undefined) {\n countBody[key] = body[key];\n }\n }\n\n try {\n const result = (await this.dispatch(\n { ...request, body: countBody },\n options,\n \"countTokens\",\n )) as {\n input_tokens: number;\n };\n\n return result.input_tokens;\n } catch (thrown) {\n throw this.logAndWrap(thrown);\n }\n }\n\n /**\n * Incremental streaming completion. Yields neutral `ModelStreamChunk`s\n * — `delta` for text tokens, `tool-call` once a `tool_use` block's\n * arguments have fully accumulated, and a terminal `done` carrying the\n * final finish reason + usage totals. Callers consume it with\n * `for await`.\n *\n * With `options.streamChunks` it also yields `reasoning` for every\n * non-empty `thinking_delta`, `tool-args` for every `input_json_delta`\n * of a client `tool_use` block, and `usage` after `message_start` and\n * each `message_delta` (whose counts are cumulative).\n */\n public async *stream(\n messages: Message[],\n options?: ModelCallOptions,\n ): AsyncIterable<ModelStreamChunk> {\n yield* this.send(this.buildLoggedRequest(messages, { ...options, stream: true }), {\n signal: options?.signal,\n streamChunks: options?.streamChunks,\n });\n }\n\n private async *streamRequest(\n request: AnthropicRequest,\n options?: AnthropicRequestOptions,\n ): AsyncIterable<ModelStreamChunk> {\n let stream: AsyncIterable<Anthropic.RawMessageStreamEvent>;\n\n try {\n stream = (await this.dispatch(\n request,\n options,\n \"create\",\n )) as AsyncIterable<Anthropic.RawMessageStreamEvent>;\n } catch (thrown) {\n throw this.logAndWrap(thrown);\n }\n\n let rawStopReason: string | null = null;\n let compaction = compactionIterationUsage(undefined);\n const usage: Usage = { input: 0, output: 0, total: 0, inputIncludesCache: false };\n const cacheTtl = requestCacheTtl(request.body);\n const want = resolveStreamChunks(options);\n const toolBlocks = new Map<number, { id: string; name: string; json: string }>();\n const thinkingBlocks = new Map<number, AnthropicThinkingBlock>();\n // Every content block of the turn, by index, so the full ordered turn\n // can be returned as `blocks` (thinking, compaction, server tools…).\n const streamedBlocks = new Map<number, StreamedBlock>();\n\n try {\n for await (const event of stream) {\n this.trackStreamedBlock(streamedBlocks, event);\n\n if (event.type === \"message_start\") {\n usage.input = event.message.usage.input_tokens ?? 0;\n\n const thinkingTokens = event.message.usage.output_tokens_details?.thinking_tokens;\n\n if (thinkingTokens !== null && thinkingTokens !== undefined) {\n usage.reasoningTokens = thinkingTokens;\n }\n\n applyServerToolUsage(usage, event.message.usage.server_tool_use);\n applyAnthropicCacheUsage(usage, event.message.usage, cacheTtl);\n\n if (want.usage) {\n yield { type: \"usage\", usage: { ...usage, total: usage.input + usage.output } };\n }\n\n continue;\n }\n\n if (event.type === \"content_block_start\") {\n const block = event.content_block;\n\n if (block.type === \"tool_use\") {\n toolBlocks.set(event.index, { id: block.id, name: block.name, json: \"\" });\n } else if (block.type === \"thinking\") {\n thinkingBlocks.set(event.index, { ...block });\n } else if (block.type === \"redacted_thinking\") {\n thinkingBlocks.set(event.index, { ...block });\n }\n\n continue;\n }\n\n if (event.type === \"content_block_delta\") {\n if (event.delta.type === \"text_delta\") {\n yield { type: \"delta\", content: event.delta.text };\n } else if (event.delta.type === \"input_json_delta\") {\n const accumulator = toolBlocks.get(event.index);\n\n if (accumulator) {\n accumulator.json += event.delta.partial_json;\n\n // Only client `tool_use` blocks: a `server_tool_use` input\n // (e.g. a web search query) never becomes a `tool-call`.\n if (want.toolArgs && event.delta.partial_json !== \"\") {\n yield {\n type: \"tool-args\",\n callId: accumulator.id,\n name: accumulator.name,\n delta: event.delta.partial_json,\n };\n }\n }\n } else if (event.delta.type === \"thinking_delta\") {\n const thinking = thinkingBlocks.get(event.index);\n\n if (thinking?.type === \"thinking\") {\n thinking.thinking += event.delta.thinking;\n }\n\n // `display: \"omitted\"` streams one empty `thinking_delta`.\n if (want.reasoning && event.delta.thinking !== \"\") {\n yield { type: \"reasoning\", delta: event.delta.thinking };\n }\n } else if (event.delta.type === \"signature_delta\") {\n const thinking = thinkingBlocks.get(event.index);\n\n if (thinking?.type === \"thinking\") {\n thinking.signature += event.delta.signature;\n }\n }\n\n continue;\n }\n\n if (event.type === \"content_block_stop\") {\n const accumulator = toolBlocks.get(event.index);\n\n if (accumulator) {\n yield {\n type: \"tool-call\",\n id: accumulator.id,\n name: accumulator.name,\n input: safeJsonParse<Record<string, unknown>>(accumulator.json, {}),\n ...this.buildThinkingMetadata(\n Array.from(thinkingBlocks.entries())\n .sort(([left], [right]) => left - right)\n .map(([, block]) => block),\n ),\n };\n\n toolBlocks.delete(event.index);\n }\n\n continue;\n }\n\n if (event.type === \"message_delta\") {\n rawStopReason = event.delta.stop_reason ?? rawStopReason;\n // The final delta carries every iteration of the request.\n if (Array.isArray((event.usage as { iterations?: unknown }).iterations)) {\n compaction = compactionIterationUsage(event.usage);\n }\n applyServerToolUsage(usage, event.usage.server_tool_use);\n usage.output = event.usage.output_tokens ?? usage.output;\n\n const thinkingTokens = event.usage.output_tokens_details?.thinking_tokens;\n\n if (thinkingTokens !== null && thinkingTokens !== undefined) {\n usage.reasoningTokens = thinkingTokens;\n }\n\n // `message_delta.usage` carries the cumulative cache counts —\n // prefer them over the `message_start` snapshot when present\n // and non-zero so the terminal `done` reflects the final tally.\n // It has no per-lifetime breakdown, so a 1-hour share already\n // read from `message_start` is kept.\n applyAnthropicCacheUsage(\n usage,\n {\n cache_read_input_tokens: event.usage.cache_read_input_tokens,\n cache_creation_input_tokens: event.usage.cache_creation_input_tokens,\n cache_creation:\n usage.cacheWrite1hTokens !== undefined\n ? { ephemeral_1h_input_tokens: usage.cacheWrite1hTokens }\n : undefined,\n },\n cacheTtl,\n );\n\n // `message_delta.usage` counts are cumulative (Anthropic streaming\n // docs), so this is the running total so far.\n if (want.usage) {\n yield { type: \"usage\", usage: { ...usage, total: usage.input + usage.output } };\n }\n }\n }\n } catch (thrown) {\n throw this.logAndWrap(thrown);\n }\n\n usage.input += compaction.input;\n usage.output += compaction.output;\n addCacheCounts(usage, compaction);\n usage.total = usage.input + usage.output;\n\n const cost = computeCost(usage, this.pricing);\n\n if (cost) {\n usage.cost = cost;\n }\n\n const finishReason = mapStopReason(rawStopReason);\n const blocks = toProviderBlocks(this.finishStreamedBlocks(streamedBlocks));\n\n this.logger.debug(LOG_MODULE, \"response\", \"Streaming call to messages.create succeeded\", {\n finishReason,\n usage,\n });\n\n yield { type: \"done\", finishReason, usage, ...(blocks ? { blocks } : {}) };\n }\n\n /**\n * Fold one stream event into the per-index block accumulator. Unknown\n * block and delta types (beta `compaction`, future additions) are kept\n * as their start payload plus whatever their delta carries, so they\n * round-trip without the adapter knowing their shape.\n */\n private trackStreamedBlock(\n blocks: Map<number, StreamedBlock>,\n event: Anthropic.RawMessageStreamEvent,\n ): void {\n if (event.type === \"content_block_start\") {\n const block = { ...(event.content_block as unknown as Record<string, unknown>) };\n\n blocks.set(event.index, {\n block,\n ...(STREAMED_INPUT_BLOCK_TYPES.has(String(block.type)) ? { json: \"\" } : {}),\n });\n\n return;\n }\n\n if (event.type !== \"content_block_delta\") {\n return;\n }\n\n const entry = blocks.get(event.index);\n\n if (!entry) {\n return;\n }\n\n const delta = event.delta as unknown as Record<string, unknown> & { type: string };\n const block = entry.block;\n\n if (delta.type === \"text_delta\") {\n block.text = String(block.text ?? \"\") + String(delta.text ?? \"\");\n } else if (delta.type === \"thinking_delta\") {\n block.thinking = String(block.thinking ?? \"\") + String(delta.thinking ?? \"\");\n } else if (delta.type === \"signature_delta\") {\n block.signature = String(block.signature ?? \"\") + String(delta.signature ?? \"\");\n } else if (delta.type === \"input_json_delta\") {\n entry.json = (entry.json ?? \"\") + String(delta.partial_json ?? \"\");\n } else if (delta.type === \"citations_delta\") {\n block.citations = [\n ...(Array.isArray(block.citations) ? block.citations : []),\n delta.citation,\n ];\n } else {\n // e.g. beta `compaction_delta` — carries the block's final fields.\n for (const [key, value] of Object.entries(delta)) {\n if (key !== \"type\") {\n block[key] = value;\n }\n }\n }\n }\n\n /** Close the accumulated stream blocks into an ordered content array. */\n private finishStreamedBlocks(blocks: Map<number, StreamedBlock>): Array<{ type: string }> {\n return Array.from(blocks.entries())\n .sort(([left], [right]) => left - right)\n .map(([, { block, json }]) => {\n if (json !== undefined) {\n block.input = safeJsonParse<Record<string, unknown>>(json, {});\n }\n\n return block as { type: string };\n });\n }\n\n /**\n * Send a request through the SDK. With `providerOptions.anthropic.betas`\n * the call goes to `client.beta.messages` (which takes the `betas` list\n * and the beta-only body fields); otherwise to `client.messages`. The\n * cancellation signal rides in the request options, as before.\n */\n private dispatch(\n request: {\n endpoint: AnthropicRequest[\"endpoint\"];\n body: Record<string, unknown>;\n betas: string[];\n },\n options: AnthropicRequestOptions | undefined,\n method: \"create\" | \"countTokens\",\n ): Promise<unknown> {\n const requestOptions = options?.signal ? { signal: options.signal } : undefined;\n const api =\n request.endpoint === \"beta.messages\" ? this.client.beta.messages : this.client.messages;\n const call = api[method] as unknown as LooseCreate;\n\n return call.call(\n api,\n request.endpoint === \"beta.messages\"\n ? { ...request.body, betas: request.betas }\n : request.body,\n requestOptions,\n );\n }\n\n /**\n * The full request body and the beta flags it needs: the adapter-built\n * params, then `thinking.display` when thinking is sent on an adaptive\n * model, the typed `thinkingBlockBinding`, `contextManagement` and\n * `serverCompaction` options, then `providerOptions.anthropic.body`\n * merged last (caller fields win). The body may add fields the adapter\n * does not build (`fallbacks`, …) but may not replace the conversation or\n * the model — see {@link RESERVED_BODY_FIELDS}.\n */\n private buildBody(\n messages: Message[],\n options: (ModelCallOptions & { stream?: boolean }) | undefined,\n ): { body: Record<string, unknown>; betas: string[] } {\n const anthropic = resolveAnthropicOptions(options);\n const betas: string[] = [];\n // Kept turns after a client-written summary carry thinking signed\n // against the replaced history. Leave it out on models that check the\n // conversation, unless the caller chose how the API handles it.\n const body: Record<string, unknown> = {\n ...this.buildParams(messages, options, {\n dropRetainedThinking:\n this.preservedThinking && anthropic.thinkingBlockBinding === undefined,\n }),\n };\n\n // `display` belongs to adaptive thinking only; `between_tools` takes\n // no other field and 400s with one.\n if (\n anthropic.thinkingDisplay &&\n this.thinkingMode === \"adaptive\" &&\n (body.thinking as { type?: string } | undefined)?.type === \"adaptive\"\n ) {\n body.thinking = {\n ...(body.thinking as Record<string, unknown>),\n display: anthropic.thinkingDisplay,\n };\n }\n\n if (anthropic.thinkingBlockBinding) {\n this.applyBlockBinding(body, anthropic.thinkingBlockBinding, betas);\n }\n\n const edits = buildContextEdits(anthropic);\n\n if (edits.length > 0) {\n if (anthropic.body?.context_management !== undefined) {\n throw new InvalidRequestError(\n \"providerOptions.anthropic.contextManagement / serverCompaction cannot be combined with \" +\n \"body.context_management: set the edits in one place.\",\n { context: { fields: [\"context_management\"] } },\n );\n }\n\n body.context_management = { edits };\n\n if (edits.some((edit) => edit.type !== \"compact_20260112\")) {\n betas.push(CONTEXT_MANAGEMENT_BETA);\n }\n\n if (edits.some((edit) => edit.type === \"compact_20260112\")) {\n betas.push(COMPACTION_BETA);\n }\n }\n\n const reserved = Object.keys(anthropic.body ?? {}).filter((key) =>\n RESERVED_BODY_FIELDS.has(key),\n );\n\n if (reserved.length > 0) {\n throw new InvalidRequestError(\n `providerOptions.anthropic.body cannot set ${reserved.map((key) => `\"${key}\"`).join(\", \")}: ` +\n \"the adapter builds these from the call's messages, tools and model. \" +\n \"Use the agent/model options instead.\",\n { context: { fields: reserved } },\n );\n }\n\n return { body: { ...body, ...anthropic.body }, betas };\n }\n\n /**\n * Set `thinking.block_binding.prefix_mismatch_behavior`. It rides on\n * adaptive or budget (`enabled`) thinking. A model that runs adaptive\n * thinking when `thinking` is omitted (every preserved-thinking model) gets\n * an explicit `{ type: \"adaptive\" }`, which is the same request. Any other\n * shape (`between_tools`, `disabled`) takes no extra field, so the option\n * is skipped with a debug log.\n */\n private applyBlockBinding(\n body: Record<string, unknown>,\n behavior: \"error\" | \"drop_block\",\n betas: string[],\n ): void {\n const thinking = body.thinking as { type?: string } | undefined;\n const type = thinking?.type ?? (this.preservedThinking ? \"adaptive\" : undefined);\n\n if (type !== \"adaptive\" && type !== \"enabled\") {\n this.logger.debug(\n LOG_MODULE,\n \"thinking-block-binding.ignored\",\n \"thinkingBlockBinding needs adaptive or budget thinking on this request; not sent\",\n { model: this.name, thinking: thinking?.type ?? \"none\" },\n );\n\n return;\n }\n\n body.thinking = {\n ...(thinking ?? { type }),\n block_binding: { prefix_mismatch_behavior: behavior },\n };\n betas.push(THINKING_BINDING_BETA);\n }\n\n /**\n * Assemble the Anthropic request body shared by `complete()` and\n * `stream()` (each adds its own `stream` literal so the SDK's create\n * overload resolves to the right return type). Hoists the system\n * prompt out of `messages`, resolves `max_tokens` (required by\n * Anthropic) with the documented default, and conditionally attaches\n * temperature, tools, native structured output, extended thinking\n * (`reasoning`), and automatic or explicit prompt-cache control.\n * Temperature is dropped when thinking is enabled, since Anthropic\n * rejects the two together, and always for adaptive-mode models, which\n * reject any explicit temperature (see `acceptsTemperature`).\n */\n private buildParams(\n messages: Message[],\n options: (ModelCallOptions & { stream?: boolean }) | undefined,\n conversion: { dropRetainedThinking: boolean },\n ): Omit<Anthropic.MessageCreateParamsNonStreaming, \"stream\"> {\n const { system, messages: anthropicMessages } = toAnthropicMessages(messages, conversion);\n const thinking = this.buildThinking(options?.reasoning);\n const temperature = options?.temperature ?? this.config.temperature;\n const configuredMaxTokens = options?.maxTokens ?? this.config.maxTokens;\n const thinkingBudget =\n thinking.thinking?.type === \"enabled\" ? thinking.thinking.budget_tokens : undefined;\n const maxTokens =\n configuredMaxTokens ??\n this.resolveDefaultMaxTokens(options?.stream === true, thinking.reservedTokens);\n // Extended thinking pins sampling to the default temperature —\n // Anthropic 400s when `thinking` is enabled alongside any explicit\n // `temperature`. Models released after Opus 4.6 (adaptive mode) reject\n // an explicit temperature outright (installed SDK\n // `MessageCreateParamsBase.temperature`, `messages.d.ts:2036-2040`).\n // Drop it in both cases rather than letting the request fail.\n const sendTemperature =\n temperature !== undefined && !thinking.thinking && acceptsTemperature(this.thinkingMode);\n\n if (\n thinkingBudget !== undefined &&\n configuredMaxTokens !== undefined &&\n configuredMaxTokens <= thinkingBudget\n ) {\n throw new Error(\n `Anthropic maxTokens (${configuredMaxTokens}) must be greater than thinking budget_tokens (${thinkingBudget})`,\n );\n }\n\n return {\n model: this.name,\n max_tokens: maxTokens,\n messages: anthropicMessages,\n ...this.buildAutomaticCacheControl(options?.cacheControl),\n ...this.buildSystem(system, options?.cacheControl),\n ...(sendTemperature ? { temperature } : {}),\n ...this.buildTools(options, options?.cacheControl),\n ...this.buildOutputConfig(options?.responseSchema, thinking.effort),\n ...(thinking.thinking ? { thinking: thinking.thinking } : {}),\n };\n }\n\n /**\n * The `max_tokens` sent when neither the call nor the model config sets\n * `maxTokens`:\n *\n * - streaming: the model's documented max output, or\n * `DEFAULT_MAX_TOKENS` (16384) for an unknown id;\n * - non-streaming: `DEFAULT_MAX_TOKENS`, capped by the model's max output\n * (the SDK requires streaming for larger non-streaming requests unless\n * the client sets a `timeout`; see `DEFAULT_MAX_TOKENS`).\n *\n * With thinking on, the value is raised to at least the thinking budget\n * plus `MIN_ANSWER_TOKENS`, and never exceeds the model's max output.\n */\n private resolveDefaultMaxTokens(stream: boolean, reservedTokens: number | undefined): number {\n const limit = this.maxOutputTokens;\n const fallback = limit === undefined ? DEFAULT_MAX_TOKENS : Math.min(limit, DEFAULT_MAX_TOKENS);\n const base = stream ? (limit ?? DEFAULT_MAX_TOKENS) : fallback;\n const withThinking =\n reservedTokens === undefined ? base : Math.max(base, reservedTokens + MIN_ANSWER_TOKENS);\n\n return limit === undefined ? withThinking : Math.min(withThinking, limit);\n }\n\n /**\n * Spread-friendly `system` fragment. Returns an empty object when no\n * system prompt was hoisted out of the messages.\n *\n * When a per-call `cacheControl.breakpoints` hint is present (≥ 1),\n * the system prompt is emitted as a single `TextBlockParam` carrying\n * `cache_control: ephemeral` — the system prompt is the longest stable\n * prefix on a turn, so one breakpoint there lets multi-turn agents\n * read it back at the ~0.1x cache-read rate. Without the hint the\n * system prompt stays a plain string (left uncached) so a one-shot\n * call never pays the ~1.25x cache-write surcharge.\n */\n private buildSystem(\n system: string | undefined,\n cacheControl: ModelCallOptions[\"cacheControl\"],\n ): { system?: string | Anthropic.TextBlockParam[] } {\n if (!system) {\n return {};\n }\n\n const breakpoints = cacheControl?.breakpoints ?? 0;\n\n if (this.capabilities.promptCaching && breakpoints > 0) {\n return {\n system: [\n { type: \"text\", text: system, cache_control: this.cacheControl(cacheControl?.ttl) },\n ],\n };\n }\n\n return { system };\n }\n\n /**\n * Let Anthropic select the last cacheable block when caching is enabled\n * without a caller-selected breakpoint. An explicit breakpoint remains\n * authoritative, so the request-level form is deliberately omitted then.\n */\n private buildAutomaticCacheControl(cacheControl: ModelCallOptions[\"cacheControl\"]): {\n cache_control?: Anthropic.CacheControlEphemeral;\n } {\n const breakpoints = cacheControl?.breakpoints ?? 0;\n\n return this.config.promptCaching && breakpoints <= 0\n ? { cache_control: this.cacheControl(cacheControl?.ttl) }\n : {};\n }\n\n /**\n * Build a typed cache-control marker. The per-call\n * `cacheControl.ttl` wins over the model's `promptCacheTtl`; with\n * neither, TTL is omitted for Anthropic's 5-minute default.\n */\n private cacheControl(callTtl?: \"5m\" | \"1h\"): Anthropic.CacheControlEphemeral {\n const ttl = callTtl ?? this.config.promptCacheTtl;\n\n return {\n type: \"ephemeral\",\n ...(ttl ? { ttl } : {}),\n };\n }\n\n /**\n * Translate the neutral `reasoning` option into Anthropic's thinking\n * settings, in the shape this model accepts (`thinkingMode`). Emitted\n * only when the model declares the `reasoning` capability AND a\n * reasoning option is supplied; otherwise returns an empty object.\n *\n * - Adaptive mode (Opus 4.7+, Sonnet 5+, Fable 5+, unknown ids):\n * `thinking: { type: \"adaptive\" }` (installed SDK\n * `ThinkingConfigAdaptive`, `messages.d.ts:1065`) plus\n * `output_config.effort` from the neutral effort, defaulting to\n * `\"medium\"`. `budget_tokens` is never sent — these models 400 on it\n * (claude-api ref). `reasoning.maxTokens` only sizes the default\n * `max_tokens` headroom.\n * - Budget mode (Haiku 4.5, Opus/Sonnet 4.6, older):\n * `thinking: { type: \"enabled\", budget_tokens }`. An explicit\n * `reasoning.maxTokens` wins; otherwise the effort maps to a tiered\n * budget. `budget_tokens` must be ≥ 1024 (`ThinkingConfigEnabled`,\n * `messages.d.ts:1084`), so the budget is floored at that minimum.\n *\n * The neutral `effort: \"none\"` (\"run without reasoning\") is mapped per\n * model by `noReasoningForm` (see `thinking-mode.ts` for the sources):\n * - Claude Sonnet 5.5: `thinking: { type: \"between_tools\" }`, its only\n * thinking-off form. It is sent alone — no `output_config.effort` (the\n * model default, `high`, is within the `high`-or-below range it\n * requires) and no `display`, both of which the API rejects alongside it.\n * - Claude Sonnet 5 and Claude Haiku 5.5: `thinking: { type: \"disabled\" }`\n * with no effort and no `display`. Haiku 5.5 accepts `disabled` only at\n * effort `high` or below; its default (`medium`) applies.\n * - Claude Opus 5: adaptive thinking at `output_config.effort: \"low\"`.\n * Opus 5 accepts `disabled`, but with it the model can write a tool call\n * as plain text (the call never runs) and leak thinking tags; the lowest\n * effort is the documented alternative.\n * - Opus 5.5 and Fable 5/5.1: no `thinking` field. These models have no\n * thinking-off form (`disabled` and `budget_tokens` are a 400 at every\n * effort), so thinking still runs at the model's default effort. Pass\n * `effort: \"low\"` to spend less.\n * - Every other model: no `thinking` field, as before.\n */\n private buildThinking(reasoning: ModelCallOptions[\"reasoning\"]): ThinkingRequest {\n if (!this.capabilities.reasoning || !reasoning) {\n return {};\n }\n\n // `effort: \"none\"` is an explicit \"run without reasoning\", in the form\n // this model accepts. (This also short-circuits the\n // `EFFORT_THINKING_BUDGET[\"none\"]` → `undefined` → `NaN` budget path.)\n if (reasoning.effort === \"none\") {\n return this.buildNoReasoning();\n }\n\n if (reasoning.maxTokens === undefined && reasoning.effort === undefined) {\n return {};\n }\n\n const effort = reasoning.effort ?? DEFAULT_THINKING_EFFORT;\n const budget = Math.max(\n MIN_THINKING_BUDGET,\n reasoning.maxTokens ?? EFFORT_THINKING_BUDGET[effort],\n );\n\n if (this.thinkingMode === \"adaptive\") {\n return {\n thinking: { type: \"adaptive\" },\n effort: EFFORT_TO_OUTPUT_EFFORT[effort],\n reservedTokens: budget,\n };\n }\n\n return {\n thinking: { type: \"enabled\", budget_tokens: budget },\n reservedTokens: budget,\n };\n }\n\n /**\n * The thinking settings for `reasoning: { effort: \"none\" }`, per\n * `noReasoningForm(this.name)` (documented on `buildThinking`).\n */\n private buildNoReasoning(): ThinkingRequest {\n switch (noReasoningForm(this.name)) {\n case \"between_tools\":\n return { thinking: { type: \"between_tools\" } };\n case \"disabled\":\n return { thinking: { type: \"disabled\" } };\n case \"lowest-effort\":\n return {\n thinking: { type: \"adaptive\" },\n effort: EFFORT_TO_OUTPUT_EFFORT.low,\n reservedTokens: EFFORT_THINKING_BUDGET.low,\n };\n case \"omit\":\n return {};\n }\n }\n\n /**\n * Spread-friendly tools fragment. Returns an empty object when no\n * tools were supplied so the caller can unconditionally spread it.\n *\n * When `config.promptCaching` is on, marks the LAST tool with\n * `cache_control: ephemeral` — Anthropic caches the whole prefix up\n * to a breakpoint, and tools sit before `system` in that prefix, so\n * one breakpoint on the final tool caches every tool definition.\n * Reads bill at ~0.1x after the first write. The system prompt is\n * deliberately left uncached: it carries per-turn placeholders, so a\n * breakpoint there would pay the ~1.25x write surcharge every turn\n * with no reads.\n */\n private buildTools(\n options: ModelCallOptions | undefined,\n cacheControl: ModelCallOptions[\"cacheControl\"],\n ): { tools?: Anthropic.ToolUnion[] } {\n const { tools, definitions } = selectProviderTools(options, {\n // The wire format, plus the provider label when a gateway sets one.\n accepts: [ANTHROPIC_WIRE_FORMAT, this.provider],\n module: LOG_MODULE,\n model: this.name,\n logger: this.logger,\n });\n const mapped = toAnthropicTools(tools);\n // Provider-defined tools (`web_search_20250305`, `bash_20250124`, …) go\n // first and verbatim; the cache breakpoint stays on the last function\n // tool so it still covers every definition before it.\n const providerDefined = definitions as unknown as Anthropic.ToolUnion[];\n\n if (!mapped) {\n return providerDefined.length > 0 ? { tools: providerDefined } : {};\n }\n\n if (this.config.promptCaching && mapped.length > 0) {\n const last = mapped.length - 1;\n const lastTool = mapped[last];\n\n if (lastTool) {\n mapped[last] = { ...lastTool, cache_control: this.cacheControl(cacheControl?.ttl) };\n }\n }\n\n return { tools: [...providerDefined, ...mapped] };\n }\n\n /**\n * Spread-friendly `output_config` fragment carrying both the native\n * structured-output `format` and the adaptive-thinking `effort`, merged\n * into one object (both live under `OutputConfig`, installed SDK\n * `messages.d.ts:796-806`). Returns an empty object when neither applies,\n * so budget-mode requests carry `output_config` only when a schema asks\n * for it.\n */\n private buildOutputConfig(\n responseSchema: Record<string, unknown> | undefined,\n effort: Anthropic.OutputConfig[\"effort\"],\n ): { output_config?: Anthropic.OutputConfig } {\n const format = this.buildStructuredOutputFormat(responseSchema);\n\n if (!format && !effort) {\n return {};\n }\n\n return {\n output_config: {\n ...(format ? { format } : {}),\n ...(effort ? { effort } : {}),\n },\n };\n }\n\n /**\n * Translate the neutral `responseSchema` option into Anthropic's\n * native `output_config.format` (JSON-schema structured outputs).\n *\n * Only returned when the model declares the `structuredOutput`\n * capability AND the schema is a proper root-object JSON Schema —\n * Anthropic rejects non-object roots. When the capability is off\n * (config override) or the schema is non-object, returns `undefined`:\n * the agent has already injected a soft schema hint into the system\n * prompt as the fallback, and client-side `validate()` still enforces\n * shape.\n */\n private buildStructuredOutputFormat(\n responseSchema: Record<string, unknown> | undefined,\n ): Anthropic.JSONOutputFormat | undefined {\n if (!responseSchema || !this.capabilities.structuredOutput) {\n return undefined;\n }\n\n if (responseSchema.type !== \"object\" || typeof responseSchema.properties !== \"object\") {\n return undefined;\n }\n\n return { type: \"json_schema\", schema: responseSchema };\n }\n\n /**\n * Concatenate every `text` content block into the single neutral\n * `content` string. `tool_use` and other block types are ignored\n * here — tool calls are surfaced separately via `extractToolCalls`.\n */\n private extractText(content: Anthropic.ContentBlock[]): string {\n return content\n .filter((block): block is Anthropic.TextBlock => block.type === \"text\")\n .map((block) => block.text)\n .join(\"\");\n }\n\n /**\n * Reshape Anthropic's `tool_use` content blocks into the neutral\n * `ModelToolCallRequest[]`. Returns `undefined` when the model\n * requested no tools so callers can branch on presence.\n */\n private extractToolCalls(content: Anthropic.ContentBlock[]): ModelToolCallRequest[] | undefined {\n const toolUses = content.filter(\n (block): block is Anthropic.ToolUseBlock => block.type === \"tool_use\",\n );\n\n if (toolUses.length === 0) {\n return undefined;\n }\n\n const thinkingMetadata = this.buildThinkingMetadata(content);\n\n return toolUses.map((block) => ({\n id: block.id,\n name: block.name,\n input: (block.input ?? {}) as Record<string, unknown>,\n ...thinkingMetadata,\n }));\n }\n\n /**\n * Preserve Anthropic's opaque extended-thinking blocks beside a tool\n * request so the next assistant turn can replay their signatures exactly.\n */\n private buildThinkingMetadata(blocks: Iterable<Anthropic.ContentBlock>): {\n providerMetadata?: Record<string, unknown>;\n } {\n const thinkingBlocks = Array.from(blocks).filter(\n (block): block is AnthropicThinkingBlock =>\n block.type === \"thinking\" || block.type === \"redacted_thinking\",\n );\n\n if (thinkingBlocks.length === 0) {\n return {};\n }\n\n return { providerMetadata: { anthropic: { thinkingBlocks } } };\n }\n\n /**\n * Normalize Anthropic's `usage` block into the neutral `Usage` shape.\n * Anthropic reports `input_tokens` / `output_tokens` separately with\n * no pre-summed total, so `total` is computed. `input_tokens` is the\n * uncached remainder only — cache reads (`cachedTokens`) and writes\n * (`cacheWriteTokens`, with the 1-hour share in `cacheWrite1hTokens`)\n * come on top of it — so the usage is marked\n * `inputIncludesCache: false`. Anthropic also reports\n * `output_tokens_details.thinking_tokens` as the reasoning subset of\n * its inclusive `output_tokens`; it is surfaced as `reasoningTokens`\n * when present, without changing the billing total. Server-side\n * compaction iterations are added in (see {@link compactionIterationUsage}).\n * `cost` is attached when the model is priced.\n */\n private extractUsage(raw: Anthropic.Usage, cacheTtl: ReturnType<typeof requestCacheTtl>): Usage {\n const compaction = compactionIterationUsage(raw);\n const input = (raw.input_tokens ?? 0) + compaction.input;\n const output = (raw.output_tokens ?? 0) + compaction.output;\n const thinkingTokens = raw.output_tokens_details?.thinking_tokens;\n const usage: Usage = {\n input,\n output,\n total: input + output,\n inputIncludesCache: false,\n ...(thinkingTokens !== null && thinkingTokens !== undefined\n ? { reasoningTokens: thinkingTokens }\n : {}),\n };\n\n applyServerToolUsage(usage, raw.server_tool_use);\n applyAnthropicCacheUsage(usage, raw, cacheTtl);\n addCacheCounts(usage, compaction);\n\n const cost = computeCost(usage, this.pricing);\n\n if (cost) {\n usage.cost = cost;\n }\n\n return usage;\n }\n\n /**\n * Wrap a thrown provider error into the typed `AIError` hierarchy and\n * emit the standard error log line before it propagates. Shared by\n * every catch site so the log shape stays identical.\n */\n private logAndWrap(thrown: unknown) {\n const wrapped = wrapAnthropicError(thrown);\n\n this.logger.error(LOG_MODULE, \"error\", wrapped.message, {\n code: wrapped.code,\n context: wrapped.context,\n });\n\n return wrapped;\n }\n}\n\n/**\n * Request fields `providerOptions.anthropic.body` may not set: they carry\n * the conversation, the model and the tool surface the agent registered,\n * so an override would silently replace the agent's input (or let the\n * model call tools the agent never registered). `stream` is chosen per\n * call by `complete()` / `stream()`.\n */\nconst RESERVED_BODY_FIELDS: ReadonlySet<string> = new Set([\n \"model\",\n \"messages\",\n \"system\",\n \"tools\",\n \"mcp_servers\",\n \"stream\",\n]);\n\n/** Body fields `messages.countTokens` accepts, copied from the full request body. */\nconst COUNT_TOKENS_FIELDS = [\n \"model\",\n \"messages\",\n \"system\",\n \"tools\",\n \"tool_choice\",\n \"thinking\",\n \"output_config\",\n \"cache_control\",\n \"context_management\",\n \"mcp_servers\",\n] as const;\n\n/** Beta flag for typed context editing (Anthropic docs, \"Context editing\", read 2026-10-17). */\nconst CONTEXT_MANAGEMENT_BETA = \"context-management-2025-06-27\";\n\n/** Beta flag for threshold compaction (Anthropic docs, \"Compaction at a token threshold\"). */\nconst COMPACTION_BETA = \"compact-2026-01-12\";\n\n/** Beta flag for `thinking.block_binding` (Anthropic docs, \"Preserved thinking\"). */\nconst THINKING_BINDING_BETA = \"thinking-binding-controls-2026-08-01\";\n\n/** The API rejects a compaction trigger below 50,000 input tokens. */\nconst MIN_COMPACTION_TRIGGER = 50_000;\n\ntype ContextEdit = { type: string } & Record<string, unknown>;\n\n/**\n * Translate the typed `contextManagement` / `serverCompaction` options into\n * `context_management.edits`. `clear_thinking_20251015` must come first\n * when strategies are combined (Anthropic docs, \"Context editing\").\n */\nfunction buildContextEdits(anthropic: AnthropicCallOptions): ContextEdit[] {\n const edits: ContextEdit[] = [];\n const { clearThinking, clearToolUses } = anthropic.contextManagement ?? {};\n\n if (clearThinking) {\n edits.push(clearThinkingEdit(clearThinking === true ? {} : clearThinking));\n }\n\n if (clearToolUses) {\n edits.push(clearToolUsesEdit(clearToolUses === true ? {} : clearToolUses));\n }\n\n if (anthropic.serverCompaction) {\n const compaction = anthropic.serverCompaction === true ? {} : anthropic.serverCompaction;\n\n if (compaction.triggerTokens !== undefined) {\n assertCount(\n \"serverCompaction.triggerTokens\",\n compaction.triggerTokens,\n MIN_COMPACTION_TRIGGER,\n );\n }\n\n edits.push({\n type: \"compact_20260112\",\n ...(compaction.triggerTokens !== undefined\n ? { trigger: { type: \"input_tokens\", value: compaction.triggerTokens } }\n : {}),\n ...(compaction.instructions ? { instructions: compaction.instructions } : {}),\n });\n }\n\n return edits;\n}\n\nfunction clearThinkingEdit(options: AnthropicClearThinking): ContextEdit {\n if (options.keep === undefined || options.keep === \"all\") {\n return { type: \"clear_thinking_20251015\", ...(options.keep ? { keep: \"all\" } : {}) };\n }\n\n assertCount(\"contextManagement.clearThinking.keep\", options.keep, 1);\n\n return {\n type: \"clear_thinking_20251015\",\n keep: { type: \"thinking_turns\", value: options.keep },\n };\n}\n\nfunction clearToolUsesEdit(options: AnthropicClearToolUses): ContextEdit {\n const edit: ContextEdit = { type: \"clear_tool_uses_20250919\" };\n\n if (options.trigger) {\n const trigger =\n \"inputTokens\" in options.trigger\n ? { type: \"input_tokens\", value: options.trigger.inputTokens }\n : { type: \"tool_uses\", value: options.trigger.toolUses };\n\n assertCount(\"contextManagement.clearToolUses.trigger\", trigger.value, 1);\n edit.trigger = trigger;\n }\n\n if (options.keep !== undefined) {\n assertCount(\"contextManagement.clearToolUses.keep\", options.keep, 0);\n edit.keep = { type: \"tool_uses\", value: options.keep };\n }\n\n if (options.clearAtLeast !== undefined) {\n assertCount(\"contextManagement.clearToolUses.clearAtLeast\", options.clearAtLeast, 1);\n edit.clear_at_least = { type: \"input_tokens\", value: options.clearAtLeast };\n }\n\n if (options.excludeTools !== undefined) {\n edit.exclude_tools = [...options.excludeTools];\n }\n\n if (options.clearToolInputs !== undefined) {\n edit.clear_tool_inputs = Array.isArray(options.clearToolInputs)\n ? [...options.clearToolInputs]\n : options.clearToolInputs;\n }\n\n return edit;\n}\n\nfunction assertCount(field: string, value: number, minimum: number): void {\n if (!Number.isSafeInteger(value) || value < minimum) {\n throw new InvalidRequestError(\n `providerOptions.anthropic.${field} must be an integer of at least ${minimum}; got ${value}.`,\n { context: { field } },\n );\n }\n}\n\ntype IterationTotals = { input: number; output: number; cacheRead: number; cacheWrite: number };\n\n/**\n * Tokens of the `compaction` entries in a beta response's `usage.iterations`.\n * With server-side compaction the top-level `input_tokens` / `output_tokens`\n * cover only the non-compaction iterations; the billed total is the sum\n * over every iteration (Anthropic docs, \"Compaction at a token threshold\" →\n * \"Understanding usage\", read 2026-10-17). Zeros when there are none.\n */\nfunction compactionIterationUsage(raw: unknown): IterationTotals {\n const totals: IterationTotals = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };\n const iterations = (raw as { iterations?: unknown } | null | undefined)?.iterations;\n\n if (!Array.isArray(iterations)) {\n return totals;\n }\n\n for (const entry of iterations as unknown[]) {\n const iteration = entry as Record<string, unknown> | null;\n\n if (iteration?.type !== \"compaction\") {\n continue;\n }\n\n totals.input += numberOrZero(iteration.input_tokens);\n totals.output += numberOrZero(iteration.output_tokens);\n totals.cacheRead += numberOrZero(iteration.cache_read_input_tokens);\n totals.cacheWrite += numberOrZero(iteration.cache_creation_input_tokens);\n }\n\n return totals;\n}\n\nfunction numberOrZero(value: unknown): number {\n return typeof value === \"number\" && Number.isFinite(value) ? value : 0;\n}\n\nfunction addCacheCounts(usage: Usage, extra: IterationTotals): void {\n if (extra.cacheRead > 0) {\n usage.cachedTokens = (usage.cachedTokens ?? 0) + extra.cacheRead;\n }\n\n if (extra.cacheWrite > 0) {\n usage.cacheWriteTokens = (usage.cacheWriteTokens ?? 0) + extra.cacheWrite;\n }\n}\n\n/** Read `providerOptions.anthropic`, tolerating its absence or a wrong shape. */\nfunction resolveAnthropicOptions(options: ModelCallOptions | undefined): AnthropicCallOptions {\n const raw = options?.providerOptions?.anthropic;\n\n return typeof raw === \"object\" && raw !== null ? (raw as AnthropicCallOptions) : {};\n}\n","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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUA,MAAa,mCAAmC;AAChD,MAAa,sCAAsC;;;;;;;;;;;;;;;;;;;AAoBnD,MAAa,0BAAkE;CAC7E,oBAAoB;EAClB,OAAO;EACP,QAAQ;EACR,aAAa;EACb,YAAY;EACZ,cAAc;CAChB;CACA,kBAAkB;EAAE,OAAO;EAAI,QAAQ;EAAI,aAAa;EAAG,YAAY;EAAM,cAAc;CAAG;CAC9F,mBAAmB;EAAE,OAAO;EAAG,QAAQ;EAAI,aAAa;EAAK,YAAY;EAAG,cAAc;CAAE;CAC5F,iBAAiB;EAAE,OAAO;EAAG,QAAQ;EAAI,aAAa;EAAK,YAAY;EAAM,cAAc;CAAG;CAC9F,mBAAmB;EAAE,OAAO;EAAG,QAAQ;EAAI,aAAa;EAAK,YAAY;EAAM,cA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