zidane 6.5.5 → 6.5.7

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 (93) hide show
  1. package/dist/{acp-BPJbXS2J.js → acp-Dm95NwNM.js} +4 -4
  2. package/dist/{acp-BPJbXS2J.js.map → acp-Dm95NwNM.js.map} +1 -1
  3. package/dist/acp-cli.js +5 -5
  4. package/dist/acp.d.ts +1 -1
  5. package/dist/acp.js +1 -1
  6. package/dist/{agent-gZjHsUft.js → agent-CcTWL-Z6.js} +59 -5
  7. package/dist/agent-CcTWL-Z6.js.map +1 -0
  8. package/dist/agent.d.ts +1 -1
  9. package/dist/agent.js +1 -1
  10. package/dist/{anthropic-D3le2d-s.js → anthropic-BomWPIYw.js} +392 -30
  11. package/dist/anthropic-BomWPIYw.js.map +1 -0
  12. package/dist/{auth-DCiXCwGa.js → auth-C-Zx5zBo.js} +127 -35
  13. package/dist/auth-C-Zx5zBo.js.map +1 -0
  14. package/dist/chat/pure.d.ts +3 -3
  15. package/dist/chat.d.ts +91 -6
  16. package/dist/chat.d.ts.map +1 -1
  17. package/dist/chat.js +4 -4
  18. package/dist/contexts/daytona.d.ts +1 -1
  19. package/dist/contexts/e2b.d.ts +1 -1
  20. package/dist/eval.d.ts +1 -1
  21. package/dist/eval.js +1 -1
  22. package/dist/extensions.d.ts +1 -1
  23. package/dist/extensions.js +1 -1
  24. package/dist/headless.d.ts +1 -1
  25. package/dist/headless.js +3 -3
  26. package/dist/{index-BYKzzYzi.d.ts → index-ZWibV230.d.ts} +33 -7
  27. package/dist/index-ZWibV230.d.ts.map +1 -0
  28. package/dist/index.d.ts +1 -1
  29. package/dist/index.js +6 -6
  30. package/dist/mcp.d.ts +1 -1
  31. package/dist/{messages-CVVg5jUL.js → messages-CZMUuKzo.js} +2 -2
  32. package/dist/{messages-CVVg5jUL.js.map → messages-CZMUuKzo.js.map} +1 -1
  33. package/dist/{openai-compat-hmZzpDrB.js → openai-compat-BoTi-9fd.js} +8 -3
  34. package/dist/openai-compat-BoTi-9fd.js.map +1 -0
  35. package/dist/output/stream-json.d.ts +1 -1
  36. package/dist/output/terminal.d.ts +1 -1
  37. package/dist/plugins.d.ts +1 -1
  38. package/dist/presets.d.ts +1 -1
  39. package/dist/presets.js +1 -1
  40. package/dist/providers/anthropic.d.ts +1 -1
  41. package/dist/providers/anthropic.js +1 -1
  42. package/dist/providers/arcee.d.ts +1 -1
  43. package/dist/providers/arcee.js +1 -1
  44. package/dist/providers/baseten.d.ts +1 -1
  45. package/dist/providers/baseten.js +1 -1
  46. package/dist/providers/cerebras.d.ts +1 -1
  47. package/dist/providers/cerebras.js +2 -2
  48. package/dist/providers/cerebras.js.map +1 -1
  49. package/dist/providers/local.d.ts +1 -1
  50. package/dist/providers/local.js +1 -1
  51. package/dist/providers/openai-compat.d.ts +1 -1
  52. package/dist/providers/openai-compat.js +1 -1
  53. package/dist/providers/openai.d.ts +1 -1
  54. package/dist/providers/openai.js +2 -2
  55. package/dist/providers/openrouter.d.ts +1 -1
  56. package/dist/providers/openrouter.js +1 -1
  57. package/dist/providers/xai.d.ts +1 -1
  58. package/dist/providers/xai.js +1 -1
  59. package/dist/{providers-Cf0AXIIZ.js → providers-CmhdtD7w.js} +2 -2
  60. package/dist/{providers-Cf0AXIIZ.js.map → providers-CmhdtD7w.js.map} +1 -1
  61. package/dist/providers.d.ts +1 -1
  62. package/dist/providers.js +3 -3
  63. package/dist/restate.d.ts +1 -1
  64. package/dist/restate.js +2 -2
  65. package/dist/session/sqlite.d.ts +1 -1
  66. package/dist/{session-cqN5NbO-.js → session-CyRLSsVa.js} +2 -2
  67. package/dist/{session-cqN5NbO-.js.map → session-CyRLSsVa.js.map} +1 -1
  68. package/dist/session.d.ts +1 -1
  69. package/dist/session.js +2 -2
  70. package/dist/skills.d.ts +1 -1
  71. package/dist/{tool-formatters-B5WSHMCU.d.ts → tool-formatters-D3wSS2zz.d.ts} +2 -2
  72. package/dist/{tool-formatters-B5WSHMCU.d.ts.map → tool-formatters-D3wSS2zz.d.ts.map} +1 -1
  73. package/dist/tools/fetch-url.d.ts +1 -1
  74. package/dist/tools/web-search.d.ts +1 -1
  75. package/dist/tools.d.ts +1 -1
  76. package/dist/tools.js +1 -1
  77. package/dist/{transcript-anchors-BvC8t7dt.js → transcript-anchors-DGUqw92H.js} +3 -3
  78. package/dist/{transcript-anchors-BvC8t7dt.js.map → transcript-anchors-DGUqw92H.js.map} +1 -1
  79. package/dist/{transcript-anchors-BPnWHLyr.d.ts → transcript-anchors-llwMrLRG.d.ts} +2 -2
  80. package/dist/{transcript-anchors-BPnWHLyr.d.ts.map → transcript-anchors-llwMrLRG.d.ts.map} +1 -1
  81. package/dist/tui.d.ts +9 -3
  82. package/dist/tui.d.ts.map +1 -1
  83. package/dist/tui.js +232 -13
  84. package/dist/tui.js.map +1 -1
  85. package/dist/{turn-operations-BvP3_HsU.d.ts → turn-operations-C_XvfBU3.d.ts} +3 -3
  86. package/dist/{turn-operations-BvP3_HsU.d.ts.map → turn-operations-C_XvfBU3.d.ts.map} +1 -1
  87. package/dist/types.d.ts +1 -1
  88. package/package.json +2 -2
  89. package/dist/agent-gZjHsUft.js.map +0 -1
  90. package/dist/anthropic-D3le2d-s.js.map +0 -1
  91. package/dist/auth-DCiXCwGa.js.map +0 -1
  92. package/dist/index-BYKzzYzi.d.ts.map +0 -1
  93. package/dist/openai-compat-hmZzpDrB.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"anthropic-BomWPIYw.js","names":["osArch","osPlatform"],"sources":["../src/chat/anthropic-models.ts","../src/providers/anthropic-claude-code.ts","../src/providers/anthropic.ts"],"sourcesContent":["/**\n * Anthropic models not (yet) bundled in `@earendil-works/pi-ai`'s registry.\n *\n * pi-ai ships a static price/metadata registry that lags new Anthropic\n * releases by a dep bump. Until the bump lands, list freshly-shipped models\n * here so they show in the picker, expose the reasoning knob, and get an\n * accurate cost estimate. Entries are merged ahead of pi-ai's list in\n * {@link modelsForDescriptor} and de-duped by id, so once pi-ai catches up\n * the bundled entry simply wins.\n */\n\nimport type { ModelInfo, ModelOption } from './providers'\n\n/**\n * Anthropic \"fast mode\" — `speed: \"fast\"` on the Messages API. ~2.5× output\n * tokens/sec at a per-model price multiplier. Supported on Opus 4.6 / 4.7 /\n * 4.8 / 5 only; the API errors if sent on any other model, so it's attached\n * just to those entries (see {@link FAST_MODE_OPTIONS}).\n *\n * The multiplier scales ALL rate components (input, output, and both cache\n * rates) uniformly: per Anthropic, \"prompt caching multipliers apply on top of\n * fast mode pricing\" across the full context window. Opus 5 and 4.8 are 2×\n * ($5/$25 → $10/$50); Opus 4.6 / 4.7 are a steeper 6× ($5/$25 → $30/$150).\n * See https://platform.claude.com/docs/en/build-with-claude/fast-mode.\n */\nexport const FAST_MODE_OPTION: ModelOption = {\n id: 'fast',\n label: 'Fast mode',\n description: '~2.5× faster output at premium pricing',\n costMultiplier: { input: 2, output: 2, cacheRead: 2, cacheWrite: 2 },\n}\n\nconst FAST_MODE_OPTION_LEGACY: ModelOption = {\n ...FAST_MODE_OPTION,\n description: '~2.5× faster output at 6× pricing',\n costMultiplier: { input: 6, output: 6, cacheRead: 6, cacheWrite: 6 },\n}\n\n/** Model ids that accept `speed: \"fast\"`, mapped to their fast-mode option. */\nexport const FAST_MODE_OPTIONS: Readonly<Record<string, ModelOption>> = {\n 'claude-opus-5': FAST_MODE_OPTION,\n 'claude-opus-4-8': FAST_MODE_OPTION,\n 'claude-opus-4-7': FAST_MODE_OPTION_LEGACY,\n 'claude-opus-4-6': FAST_MODE_OPTION_LEGACY,\n}\n\n/**\n * The price multiplier to apply to a model's base rates when fast mode is\n * active, or `undefined` when the model has no fast-mode pricing (i.e. doesn't\n * support it). Mirrors {@link FAST_MODE_OPTIONS} — kept as a separate accessor\n * so the cost layer can stay decoupled from the picker-facing option objects.\n */\nexport function fastModeCostMultiplier(modelId: string): ModelOption['costMultiplier'] {\n return FAST_MODE_OPTIONS[modelId]?.costMultiplier\n}\n\n/**\n * Claude Fable 5.1 — GA 2026-09-01, `claude-fable-5-1`. Same input/output price\n * as Fable 5 ($10/$50 per MTok) with cache reads cut 75% ($1 → $0.25); 1M\n * context, 128k output, adaptive thinking always on, vision. Rates are the\n * published table, not inferred: input $10, 5m cache write $12.50, 1h cache\n * write $20, cache hit $0.25, output $50.\n * See https://platform.claude.com/docs/en/models/fable-5-1/overview.\n *\n * CAVEAT — this model REJECTS forced tool use: `tool_choice` of `any` or `tool`\n * returns 400. Zidane pins a forced tool for structured output (`loop.ts`,\n * `generate-data.ts`, the eval judge), so those paths fail on this model. Not\n * handled here; adding the entry only makes the model selectable.\n *\n * Claude Opus 5 — GA 2026-07-24. The announcement confirms $5/$25 per MTok\n * (same as Opus 4.8) and fast mode at 2×; the 1M context, 128k output, and\n * cache rates are ASSUMED from Opus 4.8 — verify against the model docs once\n * they're up. See https://www.anthropic.com/news/claude-opus-5.\n *\n * Claude Fable 5 — GA 2026-06-09. Anthropic's most capable widely released\n * model: $10/$50 per MTok, 1M context, 128k output, adaptive thinking\n * (always on), vision. No fast-mode support (Opus 4.6/4.7/4.8/5 only).\n *\n * Claude Opus 4.8 — shipped 2026-05-28. Same price/context/output as Opus 4.7\n * ($5/$25 per MTok, 1M context, 128k output), adaptive thinking, vision.\n * See https://www.anthropic.com/news/claude-opus-4-8.\n *\n * Claude Mythos 5 / 5.1 are deliberately absent: invitation-only (Project\n * Glasswing) despite sharing Fable's specs and pricing, so they would be dead\n * picker entries for virtually all users.\n *\n * See https://platform.claude.com/docs/en/about-claude/models/overview.\n */\nexport const ANTHROPIC_EXTRA_MODELS: readonly ModelInfo[] = [\n {\n id: 'claude-fable-5-1',\n name: 'Claude Fable 5.1',\n reasoning: true,\n input: ['text', 'image'],\n cost: { input: 10, output: 50, cacheRead: 0.25, cacheWrite: 12.5 },\n contextWindow: 1_000_000,\n maxTokens: 128_000,\n provider: 'anthropic',\n },\n {\n id: 'claude-opus-5',\n name: 'Claude Opus 5',\n reasoning: true,\n input: ['text', 'image'],\n cost: { input: 5, output: 25, cacheRead: 0.5, cacheWrite: 6.25 },\n contextWindow: 1_000_000,\n maxTokens: 128_000,\n provider: 'anthropic',\n options: [FAST_MODE_OPTION],\n },\n {\n id: 'claude-fable-5',\n name: 'Claude Fable 5',\n reasoning: true,\n input: ['text', 'image'],\n cost: { input: 10, output: 50, cacheRead: 1, cacheWrite: 12.5 },\n contextWindow: 1_000_000,\n maxTokens: 128_000,\n provider: 'anthropic',\n },\n {\n id: 'claude-opus-4-8',\n name: 'Claude Opus 4.8',\n reasoning: true,\n input: ['text', 'image'],\n cost: { input: 5, output: 25, cacheRead: 0.5, cacheWrite: 6.25 },\n contextWindow: 1_000_000,\n maxTokens: 128_000,\n provider: 'anthropic',\n options: [FAST_MODE_OPTION],\n },\n]\n","/**\n * Claude Code client alignment for Anthropic subscription OAuth.\n *\n * Anthropic's subscription endpoint serves the Claude Code CLI. Requests that\n * do not look like that client are, at best, treated as a different product; at\n * worst they miss features the CLI relies on. This module holds every surface\n * that has to match, in one file, so a client bump is one edit rather than a\n * scavenger hunt through the provider.\n *\n * Modelled on `@pi-plugins/claude-oauth`, which maintains the same alignment\n * for pi and verifies its pins against a live client trace. Everything here is\n * scoped to the OAuth path — API-key, gateway-bearer and Bedrock requests never\n * reach it.\n */\n\nimport { Buffer } from 'node:buffer'\nimport { createHash, randomUUID } from 'node:crypto'\nimport { homedir, hostname, arch as osArch, platform as osPlatform, userInfo } from 'node:os'\n\n/**\n * Pinned Claude Code client versions.\n *\n * These travel together: the billing fingerprint below hashes\n * {@link CLAUDE_CODE_VERSION}, so bumping one without the others produces a\n * value that does not correspond to any real client. Re-check all five against\n * the upstream plugin's `constants.ts` when bumping.\n */\nexport const CLAUDE_CODE_VERSION = '2.1.165'\nexport const CLAUDE_AGENT_SDK_VERSION = '0.3.165'\nexport const CLAUDE_CLIENT_VERSION = '1.11187.4'\nconst CLAUDE_CODE_STAINLESS_PACKAGE_VERSION = '0.94.0'\nconst CLAUDE_CODE_STAINLESS_RUNTIME_VERSION = 'v24.3.0'\n\n/**\n * Claude Code caps requested output at 64k even where the model ceiling is\n * higher (Opus allows 128k). Requests above the cap are clamped to match.\n */\nexport const CLAUDE_CODE_MAX_OUTPUT_TOKENS = 64_000\n\n/**\n * Tool names the Claude subscription backend reserves.\n *\n * A tool named exactly `todowrite` is classified as a paid Claude product\n * surface: the otherwise-valid OAuth request is refused with \"You're out of\n * extra usage\" when the account has no purchased usage credits. The same body\n * succeeds when only that wire name changes.\n */\nexport const CLAUDE_CODE_RESERVED_TOOL_NAMES: readonly string[] = ['todowrite']\n\nconst RESERVED_TOOL_ALIAS_PREFIX = 'zidane_'\n\n/**\n * Request-local wire aliases that move reserved names out of the way, for\n * Claude subscription OAuth only.\n *\n * Resolved against the request's FULL name set (history + current specs) rather\n * than hardcoded, because the obvious alias is itself a legal tool name: an\n * extension shipping `zidane_todowrite` alongside `todowrite` would otherwise\n * make the boundary throw on a collision it can trivially avoid. Suffixing is\n * deterministic, so the wire bytes — and the provider prompt cache — stay\n * stable across turns with the same tool set.\n *\n * Canonical names are restored at the provider boundary, so dispatch, hooks,\n * persistence, and other auth modes never see the alias.\n */\nexport function claudeCodeToolAliases(names: ReadonlySet<string>): Record<string, string> | undefined {\n let aliases: Record<string, string> | undefined\n const taken = new Set(names)\n for (const reserved of CLAUDE_CODE_RESERVED_TOOL_NAMES) {\n if (!names.has(reserved))\n continue\n let candidate = `${RESERVED_TOOL_ALIAS_PREFIX}${reserved}`\n for (let n = 2; taken.has(candidate); n++)\n candidate = `${RESERVED_TOOL_ALIAS_PREFIX}${reserved}_${n}`\n taken.add(candidate)\n aliases ??= {}\n aliases[reserved] = candidate\n }\n return aliases\n}\n\n/**\n * Beta set the Claude Code agent sends, in client order.\n *\n * Sent as one unit: the endpoint is configured for this combination, and\n * trimming it to \"the ones we think we use\" is how a client stops looking like\n * the client. Betas without matching request fields are inert.\n */\nexport const CLAUDE_CODE_BETAS = [\n 'claude-code-20250219',\n 'oauth-2025-04-20',\n 'interleaved-thinking-2025-05-14',\n 'fine-grained-tool-streaming-2025-05-14',\n 'context-management-2025-06-27',\n 'prompt-caching-scope-2026-01-05',\n 'mid-conversation-system-2026-04-07',\n 'advanced-tool-use-2025-11-20',\n 'effort-2025-11-24',\n 'extended-cache-ttl-2025-04-11',\n] as const\n\n/** Billing-header pins. See {@link claudeCodeBillingText}. */\nconst BILLING_FINGERPRINT_SALT = '59cf53e54c78'\nconst BILLING_FINGERPRINT_INDICES = [4, 7, 20] as const\nexport const BILLING_HEADER_PREFIX = 'x-anthropic-billing-header:'\nexport const CCH_PLACEHOLDER = 'cch=00000'\nconst CCH_SEED = 0x4D659218E32A3268n\n\n// ---------------------------------------------------------------------------\n// Headers\n// ---------------------------------------------------------------------------\n\n/** `os.arch()` values mapped to the labels Stainless emits. */\nfunction stainlessArch(value: string): string {\n switch (value.toLowerCase()) {\n case 'amd64': case 'x64': return 'x64'\n case 'arm64': case 'aarch64': return 'arm64'\n case '386': case 'x86': case 'ia32': return 'x86'\n default: return `other::${value.toLowerCase()}`\n }\n}\n\n/** `os.platform()` values mapped to the labels Stainless emits. */\nfunction stainlessOs(value: string): string {\n switch (value.toLowerCase()) {\n case 'darwin': return 'MacOS'\n case 'win32': case 'windows': return 'Windows'\n case 'linux': return 'Linux'\n case 'freebsd': return 'FreeBSD'\n default: return `Other::${value.toLowerCase()}`\n }\n}\n\n/**\n * Headers a Claude Code OAuth request carries.\n *\n * The `x-stainless-*` entries deliberately OVERRIDE the ones the Anthropic SDK\n * generates about itself: left alone they advertise `Anthropic/JS <sdk version>`\n * on a request claiming to be the CLI, which is a contradiction no real client\n * produces.\n */\nexport function buildClaudeCodeHeaders(): Record<string, string> {\n return {\n 'user-agent': `claude-cli/${CLAUDE_CODE_VERSION} (external, local-agent, agent-sdk/${CLAUDE_AGENT_SDK_VERSION})`,\n 'x-app': 'cli',\n 'anthropic-dangerous-direct-browser-access': 'true',\n 'x-stainless-retry-count': '0',\n 'x-stainless-runtime-version': CLAUDE_CODE_STAINLESS_RUNTIME_VERSION,\n 'x-stainless-package-version': CLAUDE_CODE_STAINLESS_PACKAGE_VERSION,\n 'x-stainless-runtime': 'node',\n 'x-stainless-lang': 'js',\n 'x-stainless-arch': stainlessArch(osArch()),\n 'x-stainless-os': stainlessOs(osPlatform()),\n 'x-stainless-timeout': '900',\n 'anthropic-client-platform': 'desktop_app',\n 'anthropic-client-version': CLAUDE_CLIENT_VERSION,\n }\n}\n\n// ---------------------------------------------------------------------------\n// Billing header block\n// ---------------------------------------------------------------------------\n\n/**\n * Text of the `system[0]` billing block.\n *\n * The version suffix is `sha256(salt + msg[4] + msg[7] + msg[20] + version)`\n * truncated to 3 hex chars, where the indices sample the first user message.\n * Missing characters (a first message shorter than 21 chars) contribute `'0'`,\n * matching the client rather than throwing.\n *\n * The `cch` field ships as {@link CCH_PLACEHOLDER} and is overwritten by\n * {@link patchCch} once the body is serialized — it hashes those very bytes, so\n * it cannot be computed here.\n */\nexport function claudeCodeBillingText(firstUserMessage: string): string {\n const seed = BILLING_FINGERPRINT_INDICES.map(i => firstUserMessage[i] ?? '0').join('')\n const suffix = createHash('sha256')\n .update(`${BILLING_FINGERPRINT_SALT}${seed}${CLAUDE_CODE_VERSION}`)\n .digest('hex')\n .slice(0, 3)\n return `${BILLING_HEADER_PREFIX} cc_version=${CLAUDE_CODE_VERSION}.${suffix}; cc_entrypoint=local-agent; ${CCH_PLACEHOLDER};`\n}\n\n/** Concatenated text of the first user message — the fingerprint's sample source. */\nexport function firstUserMessageText(\n messages: readonly { role?: string, content?: unknown }[],\n): string {\n const first = messages.find(m => m.role === 'user')\n const content = first?.content\n if (typeof content === 'string')\n return content\n if (!Array.isArray(content))\n return ''\n return content\n .filter((b): b is { type: 'text', text: string } =>\n !!b && typeof b === 'object' && (b as { type?: unknown }).type === 'text'\n && typeof (b as { text?: unknown }).text === 'string')\n .map(b => b.text)\n .join('')\n}\n\n/**\n * Machine-stable device id + per-process session id, sent as\n * `metadata.user_id`'s JSON envelope.\n *\n * `userInfo()` throws in locked-down sandboxes, so the seed degrades to the\n * hostname rather than taking the process down.\n */\nfunction machineSeed(): string {\n try {\n return `${hostname()}:${userInfo().username}:${homedir()}`\n }\n catch {\n return `${hostname()}:zidane-claude-code-fallback`\n }\n}\n\nconst DEVICE_ID = createHash('sha256').update(`zidane-claude-code-device-v1:${machineSeed()}`).digest('hex')\nconst SESSION_ID = randomUUID()\n\n/** The `metadata.user_id` envelope Claude Code sends. */\nexport function claudeCodeUserId(): string {\n return JSON.stringify({ device_id: DEVICE_ID, session_id: SESSION_ID })\n}\n\n// ---------------------------------------------------------------------------\n// cch attestation\n// ---------------------------------------------------------------------------\n\nconst MASK = (1n << 64n) - 1n\nconst PRIME64_1 = 11400714785074694791n\nconst PRIME64_2 = 14029467366897019727n\nconst PRIME64_3 = 1609587929392839161n\nconst PRIME64_4 = 9650029242287828579n\nconst PRIME64_5 = 2870177450012600261n\n\nconst rotl = (x: bigint, r: bigint): bigint => ((x << r) | (x >> (64n - r))) & MASK\n\nfunction round(acc: bigint, input: bigint): bigint {\n const next = (acc + input * PRIME64_2) & MASK\n return (rotl(next, 31n) * PRIME64_1) & MASK\n}\n\nfunction mergeRound(acc: bigint, val: bigint): bigint {\n const merged = acc ^ round(0n, val)\n return (((merged * PRIME64_1) & MASK) + PRIME64_4) & MASK\n}\n\n/**\n * XXH64, reproducing Claude Code's `cch` request-integrity value.\n *\n * Ported rather than delegated to `Bun.hash.xxHash64` so the result cannot\n * drift with a runtime's hash implementation or seed handling, and so the\n * provider still works off-Bun. Verified against published XXH64 vectors.\n */\nexport function xxHash64(input: Uint8Array, seed: bigint): bigint {\n const len = input.length\n const dv = new DataView(input.buffer, input.byteOffset, input.byteLength)\n let h64: bigint\n let p = 0\n\n if (len >= 32) {\n let v1 = (seed + PRIME64_1 + PRIME64_2) & MASK\n let v2 = (seed + PRIME64_2) & MASK\n let v3 = seed & MASK\n let v4 = (seed - PRIME64_1) & MASK\n const limit = len - 32\n while (p <= limit) {\n v1 = round(v1, dv.getBigUint64(p, true))\n p += 8\n v2 = round(v2, dv.getBigUint64(p, true))\n p += 8\n v3 = round(v3, dv.getBigUint64(p, true))\n p += 8\n v4 = round(v4, dv.getBigUint64(p, true))\n p += 8\n }\n h64 = (rotl(v1, 1n) + rotl(v2, 7n) + rotl(v3, 12n) + rotl(v4, 18n)) & MASK\n h64 = mergeRound(h64, v1)\n h64 = mergeRound(h64, v2)\n h64 = mergeRound(h64, v3)\n h64 = mergeRound(h64, v4)\n }\n else {\n h64 = (seed + PRIME64_5) & MASK\n }\n\n h64 = (h64 + BigInt(len)) & MASK\n\n while (p + 8 <= len) {\n h64 ^= round(0n, dv.getBigUint64(p, true))\n h64 = (rotl(h64, 27n) * PRIME64_1) & MASK\n h64 = (h64 + PRIME64_4) & MASK\n p += 8\n }\n if (p + 4 <= len) {\n h64 ^= (BigInt(dv.getUint32(p, true)) * PRIME64_1) & MASK\n h64 = (rotl(h64, 23n) * PRIME64_2) & MASK\n h64 = (h64 + PRIME64_3) & MASK\n p += 4\n }\n while (p < len) {\n h64 ^= (BigInt(input[p] ?? 0) * PRIME64_5) & MASK\n h64 = (rotl(h64, 11n) * PRIME64_1) & MASK\n p += 1\n }\n\n h64 ^= h64 >> 33n\n h64 = (h64 * PRIME64_2) & MASK\n h64 ^= h64 >> 29n\n h64 = (h64 * PRIME64_3) & MASK\n h64 ^= h64 >> 32n\n return h64 & MASK\n}\n\nconst encoder = new TextEncoder()\n/**\n * Anchor for the placeholder search. The SDK serializes `messages` before\n * `system`, so these bytes can only belong to the block we injected — user\n * content that happens to contain `cch=00000` can never match.\n */\nconst BILLING_SYSTEM_MARKER = encoder.encode(`\"system\":[{\"type\":\"text\",\"text\":\"${BILLING_HEADER_PREFIX}`)\nconst CCH_PLACEHOLDER_BYTES = encoder.encode(CCH_PLACEHOLDER)\n/** The placeholder must sit this close to the marker, else system[0] was reshaped. */\nconst CCH_SEARCH_WINDOW = 150\n\n/**\n * Overwrite the `cch` placeholder with `XXH64(body) & 0xfffff`, in place.\n *\n * Returns the original bytes untouched when the placeholder is absent or not\n * anchored to `system[0]` — a request that goes out with the placeholder intact\n * is far better than one whose user content was corrupted by a stray patch.\n */\nexport function patchCch(encoded: Uint8Array): Uint8Array {\n const view = Buffer.from(encoded.buffer, encoded.byteOffset, encoded.byteLength)\n const markerIdx = view.indexOf(BILLING_SYSTEM_MARKER)\n if (markerIdx === -1)\n return encoded\n const searchFrom = markerIdx + BILLING_SYSTEM_MARKER.length\n const placeholderIdx = view.indexOf(CCH_PLACEHOLDER_BYTES, searchFrom)\n if (placeholderIdx === -1 || placeholderIdx - searchFrom > CCH_SEARCH_WINDOW)\n return encoded\n\n const cch = (xxHash64(encoded, CCH_SEED) & 0xFFFFFn).toString(16).padStart(5, '0')\n // Skip `cch=` and overwrite the five placeholder digits.\n for (let i = 0; i < 5; i++)\n encoded[placeholderIdx + 4 + i] = cch.charCodeAt(i)\n return encoded\n}\n\n/**\n * Wrap a `fetch` so bodies carrying the placeholder get their attestation\n * patched after serialization.\n *\n * Handed to the Anthropic SDK per client rather than installed on\n * `globalThis` — every other request in the process stays untouched, and two\n * providers cannot fight over the global.\n */\nexport function wrapFetchForCch(base: typeof fetch): typeof fetch {\n const wrapped = (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {\n const body = init?.body\n let finalBody: BodyInit | null | undefined = body\n if (typeof body === 'string' && body.includes(CCH_PLACEHOLDER)) {\n // `BodyInit` accepts a BufferSource; the Uint8Array is narrowed for the DOM\n // lib's overloads, which do not model the ArrayBufferLike generic.\n finalBody = patchCch(encoder.encode(body)) as unknown as BodyInit\n }\n\n return base(input, finalBody === body ? init : { ...init, body: finalBody })\n }\n // `preconnect` is part of the runtime's `fetch` surface but never used here;\n // carry the original's so the wrapper stays a drop-in.\n wrapped.preconnect = base.preconnect?.bind(base) ?? (() => {})\n return wrapped as typeof fetch\n}\n","// Type-only imports — erased at build time. Safe when the peer dep is not installed\n// at consume time; the types only need to resolve during Zidane's own build\n// (where `@anthropic-ai/sdk` is present as a devDependency).\nimport type Anthropic from '@anthropic-ai/sdk'\nimport type { Model } from '@anthropic-ai/sdk/resources'\nimport type { Provider, ProviderCapabilities, StreamCallbacks, ToolResult, ToolSpec, TurnResult } from '.'\nimport type { ClassifiedError } from '../errors'\nimport type { CacheTtl, PromptPart, SessionContentBlock, SessionMessage, ThinkingLevel, TurnFinishReason, TurnUsage } from '../types'\nimport type { ModelCatalog } from './model-catalog'\nimport type { OAuthParams } from './oauth'\nimport type { PromptCacheKeyOption } from './prompt-cache-key'\nimport { fastModeCostMultiplier } from '../chat/anthropic-models'\nimport { classifyErrorPrelude, errorMessage, isRetryableHttpStatus, matchesContextExceeded, matchesToolPairingError } from '../errors'\nimport { lazyAsync } from '../lazy'\nimport { unsupportedMediaError } from '../prompt'\nimport { fromAnthropic, toAnthropic } from '../session/messages'\nimport { renderSystemForWire, splitSystemPrompt } from '../system-prompt'\nimport {\n buildClaudeCodeHeaders,\n CLAUDE_CODE_BETAS,\n CLAUDE_CODE_MAX_OUTPUT_TOKENS,\n claudeCodeBillingText,\n claudeCodeToolAliases,\n claudeCodeUserId,\n firstUserMessageText,\n wrapFetchForCch,\n} from './anthropic-claude-code'\nimport { fillEstimatedCost } from './cost'\nimport { lookupModel } from './model-catalog'\nimport { extractRuntimeCredentials, readOAuthCredentials, resolveOAuthApiKey } from './oauth'\nimport { resolvePromptCacheKey } from './prompt-cache-key'\nimport { sanitizeToolSpecs } from './schema-sanitize'\nimport { createToolNameBoundary } from './tool-name-boundary'\n\ntype AnthropicCtor = typeof Anthropic\ntype AnthropicInstance = InstanceType<AnthropicCtor>\n\n// Lazy-loaded SDK class. `@anthropic-ai/sdk` is an OPTIONAL peer dependency: the\n// module is imported only when the anthropic provider opens a connection.\nconst loadAnthropicSdk = lazyAsync(async (): Promise<AnthropicCtor> => {\n try {\n const mod = await import('@anthropic-ai/sdk')\n return mod.default as unknown as AnthropicCtor\n }\n catch (err) {\n throw new Error(\n 'The `anthropic` provider requires the `@anthropic-ai/sdk` package, which is an optional peer dependency. '\n + 'Install it with your package manager (e.g. `bun add @anthropic-ai/sdk`).',\n err instanceof Error ? { cause: err } : undefined,\n )\n }\n})\n\n// Same optional-peer treatment for the Bedrock flavor. `AnthropicBedrock`\n// subclasses the same client core (`BaseAnthropic`) and exposes the identical\n// `messages` surface (minus `countTokens` / `batches`), so downstream stream\n// handling is byte-identical — only construction and auth differ (SigV4).\nconst loadBedrockSdk = lazyAsync(async (): Promise<AnthropicCtor> => {\n try {\n const mod = await import('@anthropic-ai/bedrock-sdk')\n return mod.AnthropicBedrock as unknown as AnthropicCtor\n }\n catch (err) {\n throw new Error(\n 'The `anthropic` provider in Bedrock mode requires the `@anthropic-ai/bedrock-sdk` package, which is an optional peer dependency. '\n + 'Install it with your package manager (e.g. `bun add @anthropic-ai/bedrock-sdk`).',\n err instanceof Error ? { cause: err } : undefined,\n )\n }\n})\n\n/**\n * Build the Bedrock client for one call. Auth is SigV4 via the AWS credential\n * chain — the Anthropic key/OAuth machinery is intentionally bypassed. Betas\n * are NOT forwarded: Bedrock's translation layer rejects unknown beta flags,\n * and the persona/fast-mode features they gate don't exist there.\n */\nasync function createBedrockClient(\n config: AnthropicBedrockConfig,\n anthropicParams: AnthropicParams | undefined,\n extraHeaders: Record<string, string> | undefined,\n): Promise<AnthropicInstance> {\n const Ctor = (config.sdk ?? await loadBedrockSdk()) as AnthropicCtor\n const options: Record<string, unknown> = {\n awsRegion: config.region ?? process.env.AWS_REGION ?? 'us-west-2',\n ...(anthropicParams?.baseURL ? { baseURL: anthropicParams.baseURL } : {}),\n ...(extraHeaders && Object.keys(extraHeaders).length > 0 ? { defaultHeaders: extraHeaders } : {}),\n }\n return new (Ctor as unknown as new (o: Record<string, unknown>) => AnthropicInstance)(options)\n}\n\n/** Normalize the `bedrock` param: `true` → empty config, absent → undefined. */\nfunction normalizeBedrock(value: AnthropicParams['bedrock']): AnthropicBedrockConfig | undefined {\n if (!value)\n return undefined\n return value === true ? {} : value\n}\n\n/**\n * Server-side context-management config — the body of `context_management` on\n * the Messages API. Typed loosely (Record-of-unknown) so we don't pin a specific\n * SDK schema version: the v0.90 SDK does not yet type this field, but the wire\n * format is stable behind the `context-management-2025-06-27` beta.\n *\n * See: https://docs.anthropic.com/en/docs/build-with-claude/context-management\n */\nexport interface AnthropicContextManagement {\n edits?: Array<Record<string, unknown>>\n [key: string]: unknown\n}\n\n/**\n * Amazon Bedrock mode for the anthropic provider.\n *\n * Routes the identical Messages wire shape through `@anthropic-ai/bedrock-sdk`\n * (`AnthropicBedrock`), which signs requests with SigV4 instead of an\n * Anthropic API key. Credentials resolve through the standard AWS chain —\n * `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` (+ `AWS_SESSION_TOKEN`) env\n * vars, shared config, instance roles — so no `ANTHROPIC_API_KEY` is needed\n * or consulted.\n *\n * Model ids are Bedrock-shaped (e.g.\n * `global.anthropic.claude-haiku-4-5-20251001-v1:0`); pass one as\n * `defaultModel` or per run.\n */\nexport interface AnthropicBedrockConfig {\n /**\n * AWS region for the Bedrock runtime endpoint. Resolution order:\n * this field → `AWS_REGION` env → `us-west-2`.\n */\n region?: string\n /**\n * Bring-your-own client constructor. The default lazily imports\n * `@anthropic-ai/bedrock-sdk` (an optional peer dependency); override for\n * runtimes where that default cannot work — edge workers needing a custom\n * `providerChainResolver`, pre-configured credentials objects — or to\n * inject a fake in tests without module-level mocking (Bun's\n * `mock.module` leaks across test files).\n *\n * Receives the resolved client options (`awsRegion`, plus `baseURL` /\n * `defaultHeaders` passthrough) and must return an object exposing the\n * Anthropic `messages` surface.\n */\n sdk?: new (options: Record<string, unknown>) => unknown\n}\n\nexport interface AnthropicParams extends OAuthParams {\n defaultModel?: string\n /**\n * Run against Amazon Bedrock instead of the Anthropic API. `true` uses\n * env-resolved AWS credentials and region defaults; pass an\n * {@link AnthropicBedrockConfig} to set the region or inject a client\n * constructor. See the config type for credential resolution and model-id\n * shape.\n *\n * Bedrock has no `count_tokens` endpoint (the provider's `countTokens`\n * returns `null` and callers fall back to the heuristic) and no Claude\n * Code persona; beta headers are not sent. Thinking degrades to the\n * legacy explicit-budget shape — Bedrock rejects the 4.6 surface\n * (`output_config.effort`, adaptive) — with per-effort budgets from\n * `BEDROCK_THINKING_BUDGETS` clamped under the model's output ceiling;\n * an explicit `thinkingBudget` wins. Server-side web search\n * (`nativeWebSearch`) is not advertised: AWS doesn't host Anthropic's\n * search tool, so the canonical `web_search` ToolDef runs client-side\n * like on other non-Anthropic routes.\n *\n * Caveats: {@link AnthropicParams.contextManagement} is DROPPED in bedrock\n * mode — Bedrock's translation layer rejects the field, so sending it would\n * guarantee a 400. Any `extraBodyParams` from the 4.6+ API surface are\n * forwarded verbatim and will fail the same way; don't combine them with\n * bedrock mode. `baseURL` is\n * honored but must point at a genuine Bedrock endpoint (e.g. a VPC\n * endpoint): SigV4 signs the request for that host, so a rewriting proxy\n * breaks the signature.\n */\n bedrock?: boolean | AnthropicBedrockConfig\n /**\n * Optional override for the Anthropic SDK base URL. Honored end-to-end — headers and\n * routing pass through to the forwarded host. Useful for proxies (e.g. corporate\n * gateways, internal router).\n */\n baseURL?: string\n /**\n * Additional `anthropic-beta` flags to opt into. Merged with the OAuth-path\n * defaults (`claude-code-20250219`, `oauth-2025-04-20`); duplicates are\n * de-duped. Examples:\n *\n * - `'context-management-2025-06-27'` — server-side context compaction\n * (token-accurate; pair with {@link AnthropicParams.contextManagement}).\n * - `'token-efficient-tools-2026-03-28'` — terser tool_use wire format.\n * - `'interleaved-thinking-2025-05-14'` — think between tool calls within\n * one turn.\n * - `'redact-thinking-2026-02-12'` — replace large thinking blocks with\n * stubs server-side.\n * - `'prompt-caching-scope-2026-01-05'` — extended prompt-cache scope.\n *\n * Honored on both the OAuth and API-key paths.\n */\n extraBetas?: readonly string[]\n /**\n * Server-side context-management directive. Sent on the request body as\n * `context_management`. Requires the `context-management-2025-06-27` beta —\n * add it to {@link AnthropicParams.extraBetas}.\n *\n * Typed loosely so future Anthropic schema additions land without an SDK\n * bump. A typical compaction edit:\n *\n * ```ts\n * contextManagement: {\n * edits: [{\n * type: 'clear_tool_uses_20250919',\n * trigger: { type: 'input_tokens', value: 180_000 },\n * clear_at_least: { type: 'input_tokens', value: 140_000 },\n * clear_tool_inputs: ['Read', 'Bash', 'Grep'],\n * }],\n * }\n * ```\n */\n contextManagement?: AnthropicContextManagement\n /**\n * Generic pass-through for fields on the Messages API request body that the\n * SDK does not yet type. Spread into the request before the typed fields,\n * so explicit options ({@link AnthropicParams.contextManagement} and the\n * built-in fields like `model` / `tools` / `messages`) win on collision.\n *\n * Forward-compat escape hatch for new Anthropic betas — when a future flag\n * ships before zidane has a dedicated typed knob, set it here without\n * waiting on a release. Most fields will still need the matching beta in\n * {@link AnthropicParams.extraBetas}.\n */\n extraBodyParams?: Record<string, unknown>\n /**\n * Prompt-cache affinity key — an opt-in routing hint carried on the request as\n * `metadata.user_id`. See {@link PromptCacheKeyOption} for the shapes and\n * `./prompt-cache-key.ts` for which routes honor it.\n *\n * On 1P Anthropic this is effectively a no-op: cache entries are scoped per\n * organization/workspace and matched purely by prefix, with no client-side\n * routing knob, and `metadata.user_id`'s documented purpose is abuse\n * detection. It is plumbed here for the case {@link AnthropicParams.baseURL}\n * already serves — a proxy or AI gateway in front of the Messages API, which\n * CAN route on a stable session key — and so a host sets one flag regardless\n * of which provider is behind it.\n *\n * The derived default is a hash, which also satisfies Anthropic's guidance\n * that this field not carry PII.\n *\n * Default: unset — no `metadata` is added and requests stay byte-identical.\n */\n promptCacheKey?: PromptCacheKeyOption\n /**\n * Additionally send the affinity key as this HTTP header, for gateways that\n * route on a header rather than a body field. Defers to any same-named entry\n * in {@link AnthropicParams.extraHeaders}.\n *\n * Default: unset — no header is added.\n */\n promptCacheKeyHeader?: string\n /**\n * Extra HTTP headers sent on every request, merged into the SDK's\n * `defaultHeaders`. Honored on both the OAuth and API-key paths.\n *\n * Use for routing/attribution headers a proxy or gateway in front of the\n * `baseURL` consumes (e.g. a target-provider selector). Reserved zidane\n * headers (`anthropic-beta`, `user-agent`, `x-app`, and the OAuth browser\n * flag) take precedence on collision.\n *\n * May be a **function** resolved per request (awaited) instead of a static\n * map — the seam for gateways minting short-lived/signed auth tokens that a\n * long, suspended, or replayed durable run outlives. The resolver runs on\n * every `stream()` / `countTokens()` call, so it can return a freshly-minted\n * token each turn (e.g. `{ authorization: \\`Bearer ${await mintWorkToken()}\\` }`)\n * without rebuilding the provider.\n */\n extraHeaders?: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>)\n /**\n * How the resolved credential reaches the wire.\n *\n * - `'auto'` (default) — bearer iff the token is an Anthropic OAuth access\n * token (`sk-ant-oat…`), which also turns on the **Claude Code persona**\n * (`claude-code-*` betas, `x-app: cli`, the canonical Claude Code system\n * block). Otherwise `x-api-key`.\n * - `'bearer'` — always `Authorization: Bearer <token>`, WITHOUT the Claude\n * Code persona. This is the mode for an Anthropic-Messages-compatible\n * gateway behind {@link AnthropicParams.baseURL} that authenticates with\n * its own bearer token (Bolt's `bex_…`, an internal router, …).\n * - `'api-key'` — always `x-api-key`, no persona. Forces a proxy that\n * expects Anthropic's native header even when the token happens to look\n * like an OAuth one.\n *\n * Only `'auto'` can enable the persona: an explicit mode means \"this is not\n * Anthropic's own OAuth\", and sending Claude Code's betas / system block to\n * a third-party gateway is at best noise and at worst a 400.\n */\n authMode?: 'auto' | 'bearer' | 'api-key'\n /**\n * Override advertised capabilities (merged over the Anthropic defaults).\n * For gateways behind {@link AnthropicParams.baseURL} that don't implement\n * a native affordance — e.g. `{ nativeWebSearch: undefined }` to fall back\n * to the client-side `web_search` tool when the proxy rejects Anthropic's\n * `web_search_20250305` server tool.\n */\n capabilities?: Partial<ProviderCapabilities>\n /**\n * Override the credential identity used to resolve (and lazily refresh) the\n * token on every call. Defaults to Anthropic's own\n * (`providerId: 'anthropic'`, env `ANTHROPIC_API_KEY`).\n *\n * Set this when {@link AnthropicParams.baseURL} points at a gateway that\n * issues its own OAuth credentials under a different key in\n * `credentials.json`. The whole shared machinery — refresh-on-expiry,\n * cross-process lock, atomic persist, the `onOAuthRefresh` callback — then\n * applies to that provider instead, with no reimplementation. Pair with\n * `authMode: 'bearer'` for a bearer-token gateway.\n *\n * `providerId` must be registered in pi-ai's OAuth registry\n * (`registerOAuthProvider`) for refresh to resolve.\n */\n credentialSource?: {\n /** OAuth provider id — also the credentials-file key. */\n providerId: string\n /** Env var consulted before the credentials file. Omit for OAuth-only. */\n envKey?: string\n /** Message thrown when no credential is configured. */\n missingError?: string\n /** Message thrown when refresh fails, given the underlying reason. */\n refreshError?: (reason: string) => string\n }\n}\n\n/**\n * Beta flags sent unconditionally on the OAuth path (Claude Code parity).\n *\n * The full client set, sent as one unit — see `CLAUDE_CODE_BETAS`. Betas whose\n * request fields we never populate are inert, so the cost of matching the\n * client exactly is nil while the cost of guessing a subset is looking like a\n * different client.\n */\nconst OAUTH_DEFAULT_BETAS = CLAUDE_CODE_BETAS\n\n/**\n * Beta flag that enables the `speed: \"fast\"` request field (fast mode — up to\n * 2.5× output tokens/sec at premium pricing; supported models are enumerated\n * in `FAST_MODE_OPTIONS` in chat/anthropic-models.ts). Sent as an\n * `anthropic-beta` header only on requests that opt into fast mode; absent\n * otherwise so standard requests keep a byte-stable header for prompt caching.\n *\n * See: https://platform.claude.com/docs/en/build-with-claude/fast-mode\n */\nconst FAST_MODE_BETA = 'fast-mode-2026-02-01'\nconst API_KEY_RESERVED_EXTRA_HEADER_NAMES = new Set(['anthropic-beta'])\nconst OAUTH_RESERVED_EXTRA_HEADER_NAMES = new Set([\n 'accept',\n 'anthropic-beta',\n 'anthropic-client-platform',\n 'anthropic-client-version',\n 'x-stainless-arch',\n 'x-stainless-lang',\n 'x-stainless-os',\n 'x-stainless-package-version',\n 'x-stainless-retry-count',\n 'x-stainless-runtime',\n 'x-stainless-runtime-version',\n 'x-stainless-timeout',\n 'anthropic-dangerous-direct-browser-access',\n 'user-agent',\n 'x-app',\n])\n\nfunction filterReservedExtraHeaders(\n extraHeaders: Record<string, string> | undefined,\n reservedNames: ReadonlySet<string>,\n): Record<string, string> {\n const out: Record<string, string> = {}\n for (const [name, value] of Object.entries(extraHeaders ?? {})) {\n if (!reservedNames.has(name.toLowerCase()))\n out[name] = value\n }\n return out\n}\n\n/**\n * Build the `anthropic-beta` header value — OAuth defaults plus caller-supplied\n * extras, de-duped while preserving order. Returns `undefined` when no betas\n * apply (non-OAuth, no extras).\n */\nexport function resolveAnthropicBetas(\n isOAuth: boolean,\n extraBetas?: readonly string[],\n): string | undefined {\n const seen = new Set<string>()\n const out: string[] = []\n if (isOAuth) {\n for (const b of OAUTH_DEFAULT_BETAS) {\n if (!seen.has(b)) { seen.add(b); out.push(b) }\n }\n }\n if (extraBetas) {\n for (const b of extraBetas) {\n if (typeof b === 'string' && b.length > 0 && !seen.has(b)) {\n seen.add(b)\n out.push(b)\n }\n }\n }\n return out.length > 0 ? out.join(',') : undefined\n}\n\n/**\n * Credential-resolution identity for {@link resolveOAuthApiKey}. Anthropic's\n * own unless the caller pointed the provider at a gateway with its own\n * credentials via {@link AnthropicParams.credentialSource}.\n */\nexport function credentialIdentity(anthropicParams?: AnthropicParams): {\n providerId: string\n envKey?: string\n missingError: string\n refreshError: (reason: string) => string\n} {\n const source = anthropicParams?.credentialSource\n if (!source) {\n return {\n providerId: 'anthropic',\n envKey: 'ANTHROPIC_API_KEY',\n missingError: 'No API key found. Run `bun run auth` first.',\n refreshError: reason => `Anthropic OAuth token refresh failed. Run \\`bun run auth --anthropic\\` again. ${reason}`,\n }\n }\n return {\n providerId: source.providerId,\n envKey: source.envKey,\n missingError: source.missingError ?? `No credentials found for \"${source.providerId}\". Sign in first.`,\n refreshError: source.refreshError ?? (reason => `OAuth token refresh failed for \"${source.providerId}\". Sign in again. ${reason}`),\n }\n}\n\n/**\n * Whether the wire auth is a bearer token, and whether the Claude Code\n * persona (betas + `x-app` headers + system-prompt folding) applies. Only the\n * default `'auto'` mode infers both from the token shape — see\n * {@link AnthropicParams.authMode}.\n */\nexport function resolveAnthropicAuthShape(\n apiKey: string,\n authMode: AnthropicParams['authMode'],\n): { bearer: boolean, claudeCode: boolean } {\n if (authMode === 'bearer')\n return { bearer: true, claudeCode: false }\n if (authMode === 'api-key')\n return { bearer: false, claudeCode: false }\n const isOAuth = apiKey.includes('sk-ant-oat')\n return { bearer: isOAuth, claudeCode: isOAuth }\n}\n\nfunction getConfiguredApiKey(anthropicParams?: AnthropicParams): string {\n if (anthropicParams?.apiKey)\n return anthropicParams.apiKey\n\n if (anthropicParams?.access)\n return anthropicParams.access\n\n // Gateway credentials live under their own key — resolve the factory-time\n // snapshot from there and never fall back to Anthropic's own key/creds\n // (a `bex_` gateway must not silently stream on the user's Anthropic key).\n // An empty snapshot is fine: the real error surfaces per call from\n // `resolveOAuthApiKey` with this source's `missingError`.\n const source = anthropicParams?.credentialSource\n if (source) {\n const fromEnv = source.envKey ? process.env[source.envKey] : undefined\n if (fromEnv)\n return fromEnv\n return readOAuthCredentials()[source.providerId]?.access ?? ''\n }\n\n if (process.env.ANTHROPIC_API_KEY)\n return process.env.ANTHROPIC_API_KEY\n\n // `readOAuthCredentials` tolerates a missing or corrupted file and returns `{}`\n // in both cases, so stale/half-written creds never crash agent construction.\n const access = readOAuthCredentials().anthropic?.access\n if (typeof access === 'string' && access.length > 0)\n return access\n\n throw new Error('No API key found. Run `bun run auth` first.')\n}\n\n/**\n * Resolve {@link AnthropicParams.extraHeaders} to a concrete map. A function\n * form is invoked (and awaited) per call so gateway auth tokens can refresh\n * each turn; a static map passes through.\n */\nasync function resolveExtraHeaders(\n value: AnthropicParams['extraHeaders'],\n): Promise<Record<string, string> | undefined> {\n return typeof value === 'function' ? value() : value\n}\n\n/**\n * SDK constructor options for a resolved credential — the single place that\n * decides which auth header goes on the wire.\n *\n * Exported (and pure) so the header shape is test-pinned without a network\n * round-trip: `authToken` → `Authorization: Bearer …`, `apiKey` → `x-api-key`,\n * and `apiKey: null` alongside `authToken` is what suppresses `x-api-key` so a\n * gateway sees exactly one credential.\n */\nexport function buildAnthropicClientOptions(\n apiKey: string,\n auth: { bearer: boolean, claudeCode: boolean },\n baseURL?: string,\n extraBetas?: readonly string[],\n extraHeaders?: Record<string, string>,\n): Record<string, unknown> {\n const base = baseURL ? { baseURL } : {}\n const betaHeader = resolveAnthropicBetas(auth.claudeCode, extraBetas)\n if (auth.claudeCode) {\n const callerHeaders = filterReservedExtraHeaders(extraHeaders, OAUTH_RESERVED_EXTRA_HEADER_NAMES)\n const defaultHeaders: Record<string, string> = {\n ...callerHeaders,\n accept: 'application/json',\n ...buildClaudeCodeHeaders(),\n }\n if (betaHeader)\n defaultHeaders['anthropic-beta'] = betaHeader\n return {\n apiKey: null,\n authToken: apiKey,\n dangerouslyAllowBrowser: true,\n defaultHeaders,\n // Patches the `cch` attestation into the serialized body. Per-client\n // rather than on `globalThis` so nothing else in the process is touched.\n fetch: wrapFetchForCch(globalThis.fetch),\n ...base,\n }\n }\n // Non-persona paths — only emit the beta header when the caller opted in,\n // and let caller headers through except `anthropic-beta` (reserved so the\n // fast-mode / opt-in beta computation stays authoritative).\n const defaultHeaders = filterReservedExtraHeaders(extraHeaders, API_KEY_RESERVED_EXTRA_HEADER_NAMES)\n if (betaHeader)\n defaultHeaders['anthropic-beta'] = betaHeader\n const headers = Object.keys(defaultHeaders).length > 0 ? { defaultHeaders } : {}\n // Bearer without the persona: a gateway token (`bex_…`, an internal router\n // key) in front of `baseURL`.\n if (auth.bearer)\n return { apiKey: null, authToken: apiKey, ...headers, ...base }\n return { apiKey, ...headers, ...base }\n}\n\nfunction createClient(\n SDK: AnthropicCtor,\n apiKey: string,\n auth: { bearer: boolean, claudeCode: boolean },\n baseURL?: string,\n extraBetas?: readonly string[],\n extraHeaders?: Record<string, string>,\n): AnthropicInstance {\n return new SDK(\n buildAnthropicClientOptions(apiKey, auth, baseURL, extraBetas, extraHeaders) as ConstructorParameters<AnthropicCtor>[0],\n )\n}\n\ntype BudgetedThinkingLevel = Exclude<ThinkingLevel, 'off' | 'adaptive'>\n\n/**\n * Map `ThinkingLevel` budgeted tiers to Anthropic's `output_config.effort`\n * enum. `minimal` collapses to `low` (the closest equivalent — Anthropic does\n * not have a sub-`low` tier).\n */\n/**\n * Explicit thinking budgets for Bedrock, per effort tier. Bedrock's\n * anthropic-native path only accepts the legacy\n * `thinking: { type: 'enabled', budget_tokens }` shape (the 4.6 surface —\n * `output_config.effort`, adaptive, `display` — is rejected by its\n * translation layer), so effort tiers degrade to token budgets. Floor is\n * Anthropic's 1024 minimum; ceilings stay well under haiku/sonnet output\n * caps — the request builder clamps against the model ceiling regardless.\n */\n/**\n * Output tokens reserved for the visible response when an explicit thinking\n * budget must be shrunk to fit under the model's `max_tokens` ceiling — see\n * the budget clamp in `stream()`.\n */\nconst THINKING_RESPONSE_RESERVE_TOKENS = 1024\n\nconst BEDROCK_THINKING_BUDGETS: Record<'low' | 'medium' | 'high' | 'xhigh' | 'max', number> = {\n low: 4096,\n medium: 12288,\n high: 24576,\n xhigh: 32768,\n max: 32768,\n}\n\nconst EFFORT_FOR_LEVEL: Record<BudgetedThinkingLevel, 'low' | 'medium' | 'high' | 'xhigh' | 'max'> = {\n minimal: 'low',\n low: 'low',\n medium: 'medium',\n high: 'high',\n xhigh: 'xhigh',\n max: 'max',\n}\n\n/**\n * Description of the Anthropic-side thinking configuration derived from a\n * ThinkingLevel. `null` means no thinking-related field should be set on the\n * request.\n *\n * Two shapes:\n * - `adaptive` — `thinking.type='adaptive'`. The model self-budgets per turn.\n * When `effort` is set, also emits `output_config.effort` to hint at the\n * level of reasoning the caller wants. This is the post-Claude-4.6 default\n * for level-based control and avoids the `thinking.type='enabled'`\n * deprecation warning. When `maxTokensCap` is set, the request builder\n * reduces `max_tokens` to `min(max_tokens, maxTokensCap)` — adaptive thinks\n * and replies inside one envelope, so capping the envelope soft-bounds the\n * thinking too.\n * - `enabled` — explicit-budget path: `thinking.type='enabled'` with an\n * explicit `budget_tokens`. `maxTokensBump` is added to the request's\n * `max_tokens` so the budget sits on top of the response cap. When the\n * caller's level maps to an effort tier, `effort` is carried too and\n * emitted as `output_config.effort` alongside the explicit budget —\n * both fields are valid together on 4.6+ models. The only way to pin a\n * precise token budget; Anthropic emits a deprecation warning for this\n * shape on opus 4.6+, so we only route here when the caller explicitly\n * sets `behavior.thinkingBudget`.\n *\n * In both shapes Anthropic requires `temperature` to be `1`.\n */\nexport type AnthropicThinkingPlan\n = | { kind: 'enabled', budgetTokens: number, maxTokensBump: number, effort?: 'low' | 'medium' | 'high' | 'xhigh' | 'max' }\n | { kind: 'adaptive', effort?: 'low' | 'medium' | 'high' | 'xhigh' | 'max', maxTokensCap?: number, taskBudgetTokens?: number }\n\n/**\n * Decide how to translate a `ThinkingLevel` into Anthropic's request shape.\n * Pure / synchronous — exported so tests can assert routing without standing\n * up the SDK.\n *\n * Routing rules:\n * - `'off'` → `null` (no thinking field, no effort hint).\n * - `'adaptive'` → adaptive thinking with no effort hint (model decides\n * everything). When `taskBudget` is set, it is carried as\n * `taskBudgetTokens` and emitted as `output_config.task_budget` — the\n * native whole-task thinking cap. LEGACY: when `customBudget` is set, it\n * is carried as `maxTokensCap` so the request builder caps `max_tokens`\n * accordingly — this clamps the whole response envelope (text and\n * tool-call JSON included), which is the wrong knob for bounding thinking\n * now that `taskBudget` exists; kept only for callers who already depend\n * on it. Prefer `taskBudget`.\n * - Budgeted levels → adaptive thinking with an `effort` hint (plus\n * `taskBudgetTokens` when `taskBudget` is set), unless `customBudget` is\n * provided.\n * - Any level + `customBudget` → explicit-budget `enabled` path, carrying\n * the level's `effort` hint alongside the budget. The caller has opted\n * into precise budget control and accepts the Anthropic deprecation\n * warning that comes with it on opus 4.6+. `'adaptive'` is the sole\n * exception: it never falls back to enabled, since adaptive is the\n * current Anthropic API surface for self-budgeted thinking. `taskBudget`\n * is adaptive-only and ignored on this path.\n * - `effortHint: false` (default `true`) strips the `effort` hint from\n * every shape — budgeted levels plan plain adaptive and the\n * `customBudget` path plans `enabled` with no `output_config.effort` —\n * for Anthropic models that reject the effort field.\n */\nexport function planAnthropicThinking(\n level: ThinkingLevel,\n customBudget?: number,\n taskBudget?: number,\n effortHint = true,\n): AnthropicThinkingPlan | null {\n if (level === 'off')\n return null\n const taskBudgetTokens = typeof taskBudget === 'number' && taskBudget > 0 ? taskBudget : undefined\n if (level === 'adaptive') {\n return {\n kind: 'adaptive',\n ...(typeof customBudget === 'number' && customBudget > 0 ? { maxTokensCap: customBudget } : {}),\n ...(taskBudgetTokens !== undefined ? { taskBudgetTokens } : {}),\n }\n }\n if (customBudget !== undefined) {\n return {\n kind: 'enabled',\n budgetTokens: customBudget,\n maxTokensBump: customBudget,\n ...(effortHint ? { effort: EFFORT_FOR_LEVEL[level] } : {}),\n }\n }\n return {\n kind: 'adaptive',\n ...(effortHint ? { effort: EFFORT_FOR_LEVEL[level] } : {}),\n ...(taskBudgetTokens !== undefined ? { taskBudgetTokens } : {}),\n }\n}\n\n/**\n * Map Anthropic's native `stop_reason` to the zidane `TurnFinishReason` union.\n *\n * `pause_turn` and `model_context_window_exceeded` are 4.6+ stop reasons that\n * pre-Z21 collapsed to `'other'` and silently terminated the run. They now\n * map to `'pause'` and `'length'` respectively, and the surrounding caller\n * adjusts the `done` flag so the loop can recover.\n */\nfunction mapStopReason(stopReason: string | null | undefined): TurnFinishReason | undefined {\n if (!stopReason)\n return undefined\n switch (stopReason) {\n case 'end_turn':\n case 'stop_sequence':\n return 'stop'\n case 'tool_use':\n return 'tool-calls'\n case 'max_tokens':\n case 'model_context_window_exceeded':\n // 4.6+: response bumped against the model's context window mid-stream.\n // Treat as a length-class stop so consumers can prune + retry; the\n // partial assistant response is preserved.\n return 'length'\n case 'refusal':\n return 'content-filter'\n // 4.6+: server-side mid-turn pause for long thinking. The loop\n // continues with a synthetic continue message rather than terminating.\n case 'pause_turn':\n return 'pause'\n default:\n return 'other'\n }\n}\n\n/**\n * Conservative per-family output ceiling, used ONLY as a fallback when pi-ai's\n * model registry doesn't know the model (or pi-ai is externalized) — see\n * {@link resolveAnthropicMaxOutput}, which is the primary path. These are\n * non-beta floors we can always send without a 400; the registry reports the\n * real (often much higher, e.g. Opus 4.x = 128K native) max when available.\n */\nexport function defaultAnthropicMaxTokens(modelId: string): number {\n const id = modelId.toLowerCase()\n if (id.includes('haiku'))\n return 8192\n if (id.includes('sonnet'))\n return 64000\n // opus + anything unrecognized → 32000: a safe floor when the registry is\n // unavailable. The registry lifts this to the model's true max when present.\n return 32000\n}\n\n/**\n * Lazily-loaded pi-ai model-registry getter (cached; keeps the multi-MB\n * registry out of the static bundle, mirroring `cost.ts`). Returns `null` when\n * pi-ai is externalized, in which case callers fall back to the family map.\n */\nconst loadPiModelGetter = lazyAsync(\n async (): Promise<((provider: string, model: string) => { maxTokens?: number } | undefined) | null> => {\n try {\n const mod = await import('@earendil-works/pi-ai/providers/all')\n return mod.getBuiltinModel as unknown as (provider: string, model: string) => { maxTokens?: number } | undefined\n }\n catch {\n return null\n }\n },\n)\n\n/**\n * Resolve a model's max output tokens. Prefers pi-ai's bundled registry — the\n * authoritative source the SDK itself uses to build requests, so e.g. Opus 4.x\n * reports its full native 128K (no extended-output beta required) — and falls\n * back to {@link defaultAnthropicMaxTokens} only when the registry lacks the\n * model. Used as BOTH the default (when the caller leaves `maxTokens` unset)\n * and a hard clamp, since a `max_tokens` above the model's max would 400.\n *\n * The clamp is only as good as the ceiling's provenance, so an explicit caller\n * `maxTokens` can RAISE the fallback: models the registry doesn't know are\n * mostly ids that never appear in pi-ai's anthropic registry — Bedrock ids\n * (`global.anthropic.claude-*`) and non-Anthropic models served over the\n * Anthropic wire (`openai.gpt-*` on Bedrock, gateway aliases). For the\n * latter the fallback degrades to the 32000 catch-all; for the former the\n * family match yields a deliberately conservative non-beta floor. Clamping a\n * caller who knows the real ceiling down to either silently truncates long\n * generations mid-write (observed as turns pinned at exactly 32000 tokens).\n *\n * It can only raise, never lower: the caller's `maxTokens` is a cap on the\n * VISIBLE response, already enforced as `max_tokens` itself, whereas this\n * value is the model's physical ceiling. Letting it lower the ceiling would\n * break the `enabled` thinking path's invariant that the budget sits ON TOP\n * of the response cap — the budget would be shrunk to share the caller's cap,\n * or dropped entirely once no satisfiable budget fits.\n *\n * A registry-backed max always wins over the caller — above it the provider\n * 400s. A CATALOG entry (`behavior.modelCatalog` / `setModelCatalog`) outranks\n * even that: it's an explicit claim about a model whose registry entry may be\n * absent, stale, or an alias for something else entirely.\n */\nexport async function resolveAnthropicMaxOutput(\n modelId: string,\n explicitMaxTokens?: number,\n catalog?: ModelCatalog,\n): Promise<number> {\n const override = lookupModel('anthropic', modelId, catalog)?.maxTokens\n if (typeof override === 'number' && override > 0)\n return override\n const getModel = await loadPiModelGetter()\n const registryMax = getModel?.('anthropic', modelId)?.maxTokens\n if (typeof registryMax === 'number' && registryMax > 0)\n return registryMax\n const fallback = defaultAnthropicMaxTokens(modelId)\n return typeof explicitMaxTokens === 'number' && explicitMaxTokens > 0\n ? Math.max(fallback, explicitMaxTokens)\n : fallback\n}\n\nconst EPHEMERAL: Anthropic.CacheControlEphemeral = { type: 'ephemeral' }\n\n/**\n * `cache_control` for the requested TTL. `'5m'` stays the bare ephemeral shape\n * (no `ttl` field) so default-TTL requests are byte-identical to what every\n * zidane version has ever sent — adding `ttl: '5m'` would be semantically\n * equal but is gratuitous churn against proxies that pattern-match the body.\n * `'1h'` also requires the `extended-cache-ttl-2025-04-11` beta header, which\n * the request path adds — see {@link EXTENDED_CACHE_TTL_BETA}.\n */\nfunction cacheControlFor(ttl: CacheTtl | undefined): Anthropic.CacheControlEphemeral {\n return ttl === '1h' ? { type: 'ephemeral', ttl: '1h' } : EPHEMERAL\n}\n\n/** Beta flag Anthropic requires before it honors `ttl: '1h'` on `cache_control`. */\nexport const EXTENDED_CACHE_TTL_BETA = 'extended-cache-ttl-2025-04-11'\n\n/**\n * Mutate an Anthropic request in place to add cache breakpoints on the three\n * stable prefixes:\n * 1. System prompt — `cache_control` on the static prefix only (see below).\n * 2. Tool definitions — last tool.\n * 3. Conversation — last content block of the last message.\n *\n * Each breakpoint tells Anthropic to cache the prefix ending at that block;\n * subsequent turns reuse the cached prefix and pay only for the delta. Safe\n * no-op when any prefix is empty (no tools, empty system, etc.).\n *\n * System-prompt boundary handling (`SYSTEM_PROMPT_BOUNDARY`):\n *\n * - When `originalSystem` is provided AND carries the marker, the system\n * block is rewritten as a 2-block array: static (cached) then dynamic\n * (uncached). The caller is expected to have already stripped the marker\n * from `params.system` via {@link renderSystemForWire} — this helper\n * only re-splits to apply `cache_control` cleanly.\n * - When `originalSystem` is omitted or marker-free, the existing single-\n * block treatment applies: `cache_control` on the whole system string.\n * - Array system prompts: existing semantics — `cache_control` lands on the\n * last block. Callers building their own multi-block layout own the\n * breakpoint placement.\n */\nexport function applyAnthropicCacheBreakpoints(\n params: Anthropic.MessageCreateParamsStreaming,\n originalSystem?: string,\n ttl?: CacheTtl,\n): void {\n const cacheControl = cacheControlFor(ttl)\n if (typeof params.system === 'string') {\n if (params.system.length > 0) {\n // `originalSystem` is the authoritative source for the boundary split\n // — `params.system` may have been pre-rendered by `renderSystemForWire`.\n // Fall back to `params.system` itself when no original was supplied\n // (or an empty original) so an external caller that embedded a marker\n // directly doesn't leak it into the cached block on the wire.\n const splitSource = originalSystem && originalSystem.length > 0\n ? originalSystem\n : params.system\n const parts = splitSystemPrompt(splitSource)\n if (parts.dynamic.length > 0) {\n const blocks: Anthropic.TextBlockParam[] = []\n if (parts.static.length > 0)\n blocks.push({ type: 'text', text: parts.static, cache_control: cacheControl })\n blocks.push({ type: 'text', text: parts.dynamic })\n params.system = blocks\n }\n else {\n // No marker — wrap the (already marker-free) string in a single\n // cached block. `parts.static` equals `splitSource` in this branch.\n params.system = [{ type: 'text', text: parts.static, cache_control: cacheControl }]\n }\n }\n }\n else if (Array.isArray(params.system) && params.system.length > 0) {\n const lastIdx = params.system.length - 1\n params.system = params.system.map((block, i) =>\n i === lastIdx ? { ...block, cache_control: cacheControl } : block,\n )\n }\n\n if (params.tools && params.tools.length > 0) {\n const lastIdx = params.tools.length - 1\n params.tools = params.tools.map((tool, i) =>\n i === lastIdx ? { ...tool, cache_control: cacheControl } : tool,\n ) as Anthropic.ToolUnion[]\n }\n\n if (params.messages.length === 0)\n return\n const lastMsgIdx = params.messages.length - 1\n const lastMsg = params.messages[lastMsgIdx]\n if (typeof lastMsg.content === 'string') {\n if (lastMsg.content.length === 0)\n return\n params.messages[lastMsgIdx] = {\n ...lastMsg,\n content: [{ type: 'text', text: lastMsg.content, cache_control: cacheControl }],\n }\n return\n }\n if (!Array.isArray(lastMsg.content) || lastMsg.content.length === 0)\n return\n const blocks = lastMsg.content\n // `ThinkingBlockParam` and `RedactedThinkingBlockParam` do not accept `cache_control`\n // in the SDK types — walk backward past any trailing thinking blocks to find the\n // nearest cache-eligible block. Returns -1 when every block is a thinking variant,\n // which skips this breakpoint; system + tools still carry the cache prefix.\n let targetIdx = blocks.length - 1\n while (targetIdx >= 0 && isThinkingBlock(blocks[targetIdx]))\n targetIdx -= 1\n if (targetIdx < 0)\n return\n const nextBlocks = blocks.slice()\n nextBlocks[targetIdx] = { ...nextBlocks[targetIdx], cache_control: cacheControl } as typeof nextBlocks[number]\n params.messages[lastMsgIdx] = { ...lastMsg, content: nextBlocks }\n}\n\nfunction isThinkingBlock(block: { type: string }): boolean {\n return block.type === 'thinking' || block.type === 'redacted_thinking'\n}\n\n/**\n * Duck-type check for an Anthropic SDK `APIError` — avoids a runtime dependency\n * on `@anthropic-ai/sdk` so `classifyError` stays usable even when the optional\n * peer dep isn't loaded (e.g. host code calling it on an unrelated provider's\n * error).\n *\n * Anthropic's APIError shape: `.status: number` + `.error` (parsed body, object\n * or null). Plain `Error`s don't have `.status` + `.error`.\n */\nfunction looksLikeAnthropicApiError(err: unknown): boolean {\n if (!err || typeof err !== 'object')\n return false\n const e = err as { status?: unknown, error?: unknown }\n return typeof e.status === 'number' && 'error' in e\n}\n\n/**\n * Anthropic SSE `error` event types that warrant a retry. `overloaded_error`\n * is the headline case (capacity event mid-stream); `api_error` and\n * `timeout_error` are both server-side transient failures. `invalid_request_error`,\n * `authentication_error`, `permission_error`, `not_found_error`, `billing_error`\n * are terminal — retrying them would just hammer a bad request.\n *\n * `rate_limit_error` here would be redundant: the SDK's pre-stream retry\n * handles 429, and a mid-stream `rate_limit_error` is exceedingly rare. We\n * include it anyway for symmetry with the HTTP-level retry policy.\n */\nconst SSE_RETRYABLE_ERROR_TYPES = new Set<string>([\n 'overloaded_error',\n 'api_error',\n 'timeout_error',\n 'rate_limit_error',\n])\n\n/**\n * Try to parse an Anthropic SSE `error` event payload out of a thrown error's\n * message. The SDK's `MessageStream` surfaces mid-stream error events by\n * throwing an `AnthropicError` whose `.message` contains the raw JSON shape:\n *\n * {\"type\":\"error\",\"error\":{\"type\":\"overloaded_error\",\"message\":\"Overloaded\"},\"request_id\":\"req_...\"}\n *\n * Returns the inner `{ type, message }` or `null` when the message isn't\n * the canonical SSE error shape. Tolerant: silently returns `null` for\n * non-string input, non-JSON content, or any shape mismatch.\n */\nfunction matchSseErrorEvent(message: unknown): { type: string, message: string } | null {\n if (typeof message !== 'string' || message.length === 0)\n return null\n // Cheap pre-check to avoid JSON.parse on every error message.\n if (!message.includes('\"type\":\"error\"') && !message.includes('\"type\": \"error\"'))\n return null\n // The message may be the JSON itself or have it embedded (some SDK paths\n // prefix a human prelude). Scan for the first `{` and try from there.\n const start = message.indexOf('{')\n if (start < 0)\n return null\n try {\n const parsed = JSON.parse(message.slice(start)) as unknown\n if (!parsed || typeof parsed !== 'object')\n return null\n const outer = parsed as { type?: unknown, error?: unknown }\n if (outer.type !== 'error' || !outer.error || typeof outer.error !== 'object')\n return null\n const inner = outer.error as { type?: unknown, message?: unknown }\n if (typeof inner.type !== 'string')\n return null\n return {\n type: inner.type,\n message: typeof inner.message === 'string' ? inner.message : inner.type,\n }\n }\n catch {\n return null\n }\n}\n\n/**\n * Classify an Anthropic SDK / HTTP error for typed-error wrapping.\n *\n * - `prompt is too long` (400 invalid_request_error) → `context_exceeded`.\n * - `'tool_use' ids were found without 'tool_result' blocks` /\n * `'tool_result must be preceded by a tool_call'` (400) →\n * `tool_pairing_corruption`. The local repair pass should have caught\n * this — the typed error tells consumers their pre-send pipeline is\n * shipping orphaned blocks somehow (custom `context:transform` hook,\n * bypassed loop, mid-stream session edit) so they can patch the root\n * cause instead of chasing 400s.\n * - Any other Anthropic `APIError`-shaped value → `provider_error` with the\n * native status/type code.\n * - Unknown errors → `null` (loop wraps in `AgentProviderError` generically).\n *\n * Anthropic's wire error shape is `{ type: 'error', error: { type, message } }` — the\n * SDK stores the parsed body on `err.error`. We walk both levels so callers see the\n * most specific `providerCode` we can find.\n */\nexport function classifyAnthropicError(err: unknown): ClassifiedError | null {\n const prelude = classifyErrorPrelude(err)\n if (prelude === 'not-object')\n return null\n if (prelude === 'aborted')\n return { kind: 'aborted' }\n\n interface InnerError { type?: string, message?: string }\n interface AnthError {\n name?: string\n message?: string\n status?: number\n error?: InnerError & { error?: InnerError }\n }\n const anyErr = err as AnthError\n\n // Mid-stream SSE error event — the SDK's `MessageStream` surfaces these by\n // throwing an `AnthropicError` (plain Error subclass, no `.status`) whose\n // `.message` carries the raw SSE error JSON, e.g.\n // `{\"type\":\"error\",\"error\":{\"type\":\"overloaded_error\",\"message\":\"Overloaded\"},\"request_id\":\"...\"}`.\n // The pre-stream HTTP retry inside the SDK can't help here — the response\n // already opened with a 200, then the server emitted `event: error`\n // mid-stream. Classify these so the loop-level retry kicks in.\n //\n // Guarded on `!looksLikeAnthropicApiError(err)` so we don't shadow the\n // structured `APIError` branch below (which also stringifies its body into\n // `.message` and would otherwise match this same pattern).\n if (!looksLikeAnthropicApiError(err)) {\n const sseError = matchSseErrorEvent(anyErr.message)\n if (sseError) {\n return {\n kind: 'provider_error',\n providerCode: sseError.type,\n message: sseError.message,\n retryable: SSE_RETRYABLE_ERROR_TYPES.has(sseError.type),\n }\n }\n return null\n }\n\n // Prefer the inner error when present (Anthropic's nested shape).\n const innerType = anyErr.error?.error?.type\n const outerType = anyErr.error?.type\n const nativeType = innerType && innerType !== 'error' ? innerType : outerType\n const message = anyErr.error?.error?.message\n ?? anyErr.error?.message\n ?? anyErr.message\n ?? ''\n\n if (matchesContextExceeded(message)) {\n return {\n kind: 'context_exceeded',\n providerCode: nativeType ?? 'invalid_request_error',\n message,\n }\n }\n\n if (matchesToolPairingError(message)) {\n return {\n kind: 'tool_pairing_corruption',\n providerCode: nativeType ?? 'invalid_request_error',\n message,\n }\n }\n\n const status = anyErr.status\n const retryable = typeof status === 'number'\n ? isRetryableHttpStatus(status)\n : undefined\n\n return {\n kind: 'provider_error',\n providerCode: nativeType ?? (status ? String(status) : undefined),\n message,\n ...(retryable !== undefined ? { retryable } : {}),\n }\n}\n\n/** True only for a provider authentication rejection eligible for one OAuth refresh retry. */\nfunction isAnthropicAuthenticationError(err: unknown): boolean {\n if (!err || typeof err !== 'object')\n return false\n const candidate = err as { status?: number, error?: { type?: string, error?: { type?: string } } }\n return candidate.status === 401\n || candidate.error?.type === 'authentication_error'\n || candidate.error?.error?.type === 'authentication_error'\n}\n\nfunction shouldFallbackFromFastMode(err: unknown): boolean {\n const classified = classifyAnthropicError(err)\n if (classified?.kind === 'provider_error' && classified.retryable === true)\n return true\n\n const message = err instanceof Error ? err.message : String(err)\n return /\\b(?:fast|speed)\\b/i.test(message)\n && /capacity|overload|rate|unavailable|unsupported|not supported|not permitted|extra inputs|invalid/i.test(message)\n}\n\n/**\n * Anthropic signs thinking blocks so they can be echoed through tool-use\n * chains without exposing raw reasoning. A signature can become\n * unverifiable after a model/route/account switch, a legacy session edit,\n * or a provider-side signing-key rotation. We cannot validate the opaque\n * signature locally; Anthropic reports this as a request-validation 400\n * (`invalid_request_error`) with no machine-readable subcode — the message\n * string is the only signal.\n *\n * Detection is layered, most-stable signal first:\n *\n * 1. Structural: the validation 400 pinpoints a wire location\n * (`messages.N.content.M: …`) and OUR OWN request payload has a\n * thinking/redacted_thinking block at that exact position. The locator\n * format is API-stable; the prose around it is not (Anthropic has\n * already reworded it once, from \"Invalid signature in thinking block\"\n * to \"Invalid `signature` in `thinking` block\", which silently\n * disabled a wording-only matcher). This deliberately classifies ANY\n * validation complaint targeting one of our opaque thinking blocks as\n * recoverable — dropping the block is the correct remedy for the whole\n * class (bad signature, corrupt data, ordering), and if the scrubbed\n * retry still 400s the error propagates unchanged.\n * 2. Wording fallback: some error shapes omit the locator; match the\n * known prose variants, tolerating backticks and minor rewording.\n *\n * Match narrowly: retrying any broader 400 could hide a real bad request.\n */\nfunction isRecoverableThinkingBlockError(err: unknown, messages?: Anthropic.MessageParam[]): boolean {\n if (!isRequestValidationError(err))\n return false\n\n if (messages !== undefined) {\n const path = parseFailingBlockPath(err)\n if (path !== undefined) {\n const content = messages[path.message]?.content\n const block = Array.isArray(content) ? content[path.content] : undefined\n if (block !== undefined && (block.type === 'thinking' || block.type === 'redacted_thinking'))\n return true\n }\n }\n\n return /invalid\\s+`?signature`?\\s+in\\s+(?:the\\s+)?`?thinking`?\\s+block/i.test(errorText(err))\n}\n\n/**\n * True when the error looks like an Anthropic request-validation failure:\n * status 400 and, when the nested API body carries a type, that type is\n * `invalid_request_error`. Both fields are optional on SDK-wrapped or\n * gateway shapes, so each is enforced only when present — but a present,\n * different value (e.g. 429, `authentication_error`) disqualifies: the\n * recovery permanently scrubs session history, so it must never fire on a\n * non-validation failure that coincidentally mentions a locator.\n */\nfunction isRequestValidationError(err: unknown): boolean {\n // Field probes only — a non-object error (string throw from a custom\n // stream factory) has neither status nor type and falls through to the\n // caller's prose match, same as the pre-structural matcher.\n const status = typeof err === 'object' && err !== null && 'status' in err\n ? (err as { status?: unknown }).status\n : undefined\n if (status !== undefined && status !== 400)\n return false\n const nestedType = typeof err === 'object' && err !== null ? nestedErrorType(err) : undefined\n return nestedType === undefined || nestedType === 'invalid_request_error'\n}\n\n/** The `error.error.type` of a nested Anthropic API error body, when present. */\nfunction nestedErrorType(err: object): string | undefined {\n const outer = 'error' in err ? (err as { error?: unknown }).error : undefined\n if (typeof outer !== 'object' || outer === null)\n return undefined\n const inner = 'error' in outer ? (outer as { error?: unknown }).error : outer\n if (typeof inner !== 'object' || inner === null)\n return undefined\n const type = 'type' in inner ? (inner as { type?: unknown }).type : undefined\n return typeof type === 'string' ? type : undefined\n}\n\n/** Error message + nested API error body, flattened for pattern matching. */\nfunction errorText(err: unknown): string {\n const nested = typeof err === 'object' && err !== null && 'error' in err\n ? JSON.stringify((err as { error?: unknown }).error)\n : ''\n return `${err instanceof Error ? err.message : String(err)} ${nested}`\n}\n\n/**\n * Full wire locator of the block the 400 pinpointed (`messages.5.content.0:\n * …`), or `undefined` when the shape doesn't carry one. Unlike the prose,\n * this locator prefix is a stable part of Anthropic's validation-error\n * format — it lets {@link isRecoverableThinkingBlockError} verify against\n * the actual request payload instead of trusting wording.\n */\nfunction parseFailingBlockPath(err: unknown): { message: number, content: number } | undefined {\n const match = /\\bmessages\\.(\\d+)\\.content\\.(\\d+)\\b/.exec(errorText(err))\n if (!match)\n return undefined\n const message = Number(match[1])\n const content = Number(match[2])\n return Number.isSafeInteger(message) && Number.isSafeInteger(content)\n ? { message, content }\n : undefined\n}\n\n/**\n * Wire index of the message the 400 pinpointed (`messages.5.content.0:\n * Invalid signature…`), or `undefined` when the shape doesn't carry one.\n * Lets the retry scrub only blocks at/before the failing message — later\n * messages can hold STILL-VALID thinking (e.g. minted this run after a\n * mid-session account switch) that the active tool-use chain requires.\n */\nfunction parseFailingMessageIndex(err: unknown): number | undefined {\n const match = /\\bmessages\\.(\\d+)\\./.exec(errorText(err))\n if (!match)\n return undefined\n const index = Number(match[1])\n return Number.isSafeInteger(index) ? index : undefined\n}\n\n/**\n * Hard cap on signature-400 scrub retries within one `stream()` call. Two\n * passes resolve every real-world shape (bounded pass, then the\n * everything-but-active-chain pass); the third is margin. Beyond that the\n * error is not signature poisoning and must surface.\n */\nconst MAX_THINKING_SCRUB_PASSES = 3\n\n/**\n * Wire index where the ACTIVE chain begins: the last user message that\n * carries real user content (string content, or any non-tool_result\n * block). Everything from there onward is the current prompt plus the\n * in-flight assistant/tool exchange — its thinking blocks were minted by\n * this very call chain and Anthropic requires them to be echoed back, so\n * escalated scrubs must never cross this boundary. `undefined` when no\n * such message exists (degenerate resume shapes) — callers treat that as\n * \"no protected region\".\n */\nfunction activeChainScrubBoundary(messages: Anthropic.MessageParam[]): number | undefined {\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i]\n if (message?.role !== 'user')\n continue\n if (typeof message.content === 'string')\n return i\n if (message.content.some(block => block.type !== 'tool_result'))\n return i\n }\n return undefined\n}\n\n/**\n * Decide what a scrub pass may touch. The bound NEVER crosses into the\n * active chain wholesale — not even on pass 0 with no parseable locator\n * (an unbounded first pass would strip the in-flight chain's thinking and\n * trade a recoverable 400 for an \"expected thinking block\" one). When the\n * API-reported failing index lies INSIDE the chain, only that single\n * message is scrubbed on top of the pre-chain region: the block the API\n * itself rejected fails whether or not it is echoed, but sibling chain\n * messages below it may hold still-valid thinking the exchange requires.\n *\n * - pass 0 with a pre-chain locator → bounded at the locator (preserves\n * later, still-valid historical thinking).\n * - pass 0 without a locator, and every escalated pass → the full\n * pre-chain history.\n * - no active chain at all (degenerate resume shapes) → locator bound on\n * pass 0, full history afterwards.\n */\nfunction planThinkingScrub(\n scrubPass: number,\n failingIndex: number | undefined,\n messages: Anthropic.MessageParam[],\n): { upToIndex?: number, alsoMessageIndex?: number } {\n const chainStart = activeChainScrubBoundary(messages)\n if (chainStart === undefined) {\n return scrubPass === 0 && failingIndex !== undefined\n ? { upToIndex: failingIndex }\n : {} // no protected region — scrub the full history\n }\n const beforeChain = chainStart - 1\n const inChain = failingIndex !== undefined && failingIndex >= chainStart\n const upToIndex = scrubPass === 0 && failingIndex !== undefined && !inChain\n ? failingIndex\n : beforeChain\n return inChain ? { upToIndex, alsoMessageIndex: failingIndex } : { upToIndex }\n}\n\n/**\n * Remove opaque historical Anthropic reasoning from a retry payload. Text,\n * tool calls/results, images, and every other block are preserved exactly.\n * If a message consisted only of reasoning, leave a neutral text marker so\n * the wire never receives an empty content array and conversation role\n * boundaries stay intact.\n *\n * `upToIndex` bounds the scrub to messages at/before the API-reported\n * failing index (see {@link parseFailingMessageIndex}); `undefined` strips\n * everywhere. `alsoMessageIndex` additionally scrubs that single message\n * beyond the bound (see {@link planThinkingScrub}). A later stale block\n * simply triggers the same recovery again — each pass removes at least\n * one block, so the recursion is bounded.\n */\nfunction withoutHistoricalThinking(\n messages: Anthropic.MessageParam[],\n upToIndex?: number,\n alsoMessageIndex?: number,\n): {\n messages: Anthropic.MessageParam[]\n removed: number\n} {\n let removed = 0\n const scrubbed = messages.map((message, index) => {\n if (upToIndex !== undefined && index > upToIndex && index !== alsoMessageIndex)\n return message\n if (!Array.isArray(message.content))\n return message\n const content = message.content.filter((block) => {\n if (block.type === 'thinking' || block.type === 'redacted_thinking') {\n removed += 1\n return false\n }\n return true\n })\n return {\n ...message,\n content: content.length > 0\n ? content\n : [{ type: 'text' as const, text: '[historical reasoning omitted]' }],\n }\n })\n return { messages: scrubbed, removed }\n}\n\n/**\n * Build a user `SessionMessage` from multimodal prompt parts.\n *\n * - Text parts → text blocks.\n * - Image parts → base64 image blocks.\n * - Document parts → canonical document blocks. `toAnthropic` emits native\n * document blocks only for base64 PDFs; text/non-PDF documents fall back to\n * attachment-tagged text to avoid invalid Anthropic source media types.\n *\n * The format mirrors `defaultPromptMessage`'s output on shape — Anthropic-specific\n * handling differs only in that `promptMessage` being present tells the agent loop\n * to route PromptPart[] through this function rather than throwing on base64 docs.\n */\nfunction anthropicPromptMessage(parts: PromptPart[]): SessionMessage {\n const content: SessionContentBlock[] = []\n\n for (const part of parts) {\n if (part.type === 'text') {\n if (part.text.length > 0)\n content.push({ type: 'text', text: part.text })\n continue\n }\n\n if (part.type === 'image') {\n content.push({ type: 'image', mediaType: part.mediaType, data: part.data })\n continue\n }\n\n if (part.type === 'audio')\n throw unsupportedMediaError('audio', 'anthropic')\n if (part.type === 'video')\n throw unsupportedMediaError('video', 'anthropic')\n\n // document\n content.push({\n type: 'document',\n mediaType: part.mediaType,\n data: part.data,\n encoding: part.encoding,\n ...(part.name ? { name: part.name } : {}),\n })\n }\n\n return { role: 'user', content }\n}\n\nexport function anthropic(\n anthropicParams?: AnthropicParams,\n): Provider {\n const bedrockConfig = normalizeBedrock(anthropicParams?.bedrock)\n // Bedrock mode authenticates through the AWS credential chain — resolving\n // an Anthropic key here would throw for users who (correctly) have none.\n const configuredApiKey = bedrockConfig ? '' : getConfiguredApiKey(anthropicParams)\n // Factory-time snapshot — used only for the static `meta.isOAuth` flag.\n // Keys resolve per call (env / file creds can change between construction\n // and a turn), so `countTokens` / `stream` re-derive the auth shape from the\n // freshly resolved key instead of trusting this.\n const isOAuth = resolveAnthropicAuthShape(configuredApiKey, anthropicParams?.authMode).bearer\n const defaultModel = anthropicParams?.defaultModel || 'claude-opus-4-8'\n let runtimeCredentials = extractRuntimeCredentials(anthropicParams)\n\n return {\n name: 'anthropic',\n meta: {\n defaultModel,\n isOAuth,\n // True when server-side context management is configured: the API may\n // clear old tool results mid-conversation without the client knowing.\n // The loop reads this to disable the read_file dedup, whose client-side\n // hash can't tell that a server-cleared body left the wire — otherwise\n // the \"unchanged\" replay stub would strand the model on missing content.\n clearsContextServerSide: Boolean(anthropicParams?.contextManagement),\n capabilities: {\n vision: true,\n imageInToolResult: true,\n documents: true,\n // Anthropic Messages API has no audio/video input content block.\n audio: false,\n video: false,\n // Anthropic Messages API supports `web_search_20250305` as a\n // server-side tool — the model issues searches and consumes\n // results without a client-visible tool_use round-trip. The\n // canonical `web_search` `ToolDef` ships as a cross-provider\n // fallback; when this capability is set, `formatTools` rewrites\n // it to the server-tool wire shape and drops the function-tool\n // version so the model uses the native path.\n //\n // NOT on Bedrock: AWS doesn't host Anthropic's server-side search\n // (live-verified 400, \"The provided request is not valid\"), and\n // because `formatTools` rewrites the TOOLS ARRAY, advertising it\n // would fail every request from any agent whose toolset merely\n // CONTAINS a `web_search` tool — zidane's default set does. With\n // the capability absent, that ToolDef passes through as a regular\n // function tool and executes client-side like on every other\n // non-Anthropic route. Callers can re-enable via `capabilities`\n // below if AWS ever ships it.\n ...(bedrockConfig ? {} : { nativeWebSearch: { maxUses: 5 } }),\n // Anthropic adaptive has no native per-turn thinking budget knob, so\n // `thinkingBudget` caps the whole response envelope (`max_tokens`).\n // The loop skips `thinkingDecay` for adaptive here — see the flag docs.\n adaptiveBudgetIsEnvelope: true,\n // Caller overrides last — a gateway in front of `baseURL` may not\n // implement every native affordance (server-side web search is the\n // usual casualty), and advertising one it lacks 400s every turn.\n ...anthropicParams?.capabilities,\n },\n },\n\n formatTools(tools: ToolSpec[]): Anthropic.ToolUnion[] {\n // Sanitize before forwarding — Anthropic 400s on the strict shapes\n // (root `$ref`, root `oneOf|anyOf|allOf`, `type: ['object', 'null']`,\n // missing `properties`, `nullable: true`) that show up in MCP-server\n // schemas. The strict `anthropic` profile coerces those without\n // changing semantics for valid schemas. Warnings are de-duped to\n // `console.warn` so the same bad schema doesn't spam the log every\n // turn.\n //\n // `web_search` is special-cased: when present, it's emitted as the\n // server-tool `web_search_20250305` block and removed from the\n // function-tools list. The model invokes it without a client-side\n // round-trip; Anthropic injects the search results into the\n // assistant message directly. See the `nativeWebSearch` capability\n // declared above.\n const nativeWebSearch = this.meta.capabilities?.nativeWebSearch\n // `hasWebSearch` is the existence check; `fnTools` is the filtered\n // list. Computing existence via `tools.some` (rather than comparing\n // pre/post-filter lengths) makes the rewrite intent obvious at a\n // glance.\n const hasWebSearch = !!nativeWebSearch && tools.some(t => t.name === 'web_search')\n const fnTools = hasWebSearch ? tools.filter(t => t.name !== 'web_search') : tools\n const sanitized = sanitizeToolSpecs(fnTools, { profile: 'anthropic' })\n // `?? ''`: MCP servers routinely omit descriptions, and while the\n // Anthropic API tolerates the field's absence, anthropic-format\n // GATEWAYS in front of it often validate `description` as a required\n // string — one description-less tool then 400s the whole request\n // before any model sees it. An empty string is valid everywhere.\n const out: Anthropic.ToolUnion[] = sanitized.map(t => ({\n name: t.name,\n description: t.description ?? '',\n input_schema: t.inputSchema as Anthropic.Tool['input_schema'],\n }))\n if (hasWebSearch && nativeWebSearch) {\n // `max_uses` is optional — omit when the capability doesn't pin a value\n // so Anthropic's server-side default applies.\n const block: Anthropic.WebSearchTool20250305 = {\n type: 'web_search_20250305',\n name: 'web_search',\n }\n if (typeof nativeWebSearch.maxUses === 'number')\n block.max_uses = nativeWebSearch.maxUses\n out.push(block)\n }\n return out\n },\n\n userMessage(content: string): SessionMessage {\n return { role: 'user', content: [{ type: 'text', text: content }] }\n },\n\n assistantMessage(content: string): SessionMessage {\n return { role: 'assistant', content: [{ type: 'text', text: content }] }\n },\n\n toolResultsMessage(results: ToolResult[]): SessionMessage {\n return {\n role: 'user',\n content: results.map(r => ({\n type: 'tool_result' as const,\n callId: r.id,\n output: r.content,\n ...(r.isError ? { isError: true as const } : {}),\n ...(r.metadata ? { metadata: r.metadata } : {}),\n })),\n }\n },\n\n promptMessage: anthropicPromptMessage,\n\n classifyError: classifyAnthropicError,\n\n async countTokens(payload, signal): Promise<number | null> {\n // Bedrock has no `count_tokens` endpoint (the SDK omits the method) —\n // return null immediately so the caller's heuristic takes over without\n // paying a doomed request or logging an error every turn.\n if (bedrockConfig)\n return null\n try {\n const SDK = await loadAnthropicSdk()\n const identity = credentialIdentity(anthropicParams)\n const apiKey = await resolveOAuthApiKey(\n {\n provider: identity.providerId,\n providerId: identity.providerId,\n params: runtimeCredentials ? { ...anthropicParams, ...runtimeCredentials } : anthropicParams,\n envKey: identity.envKey,\n missingError: identity.missingError,\n refreshError: identity.refreshError,\n },\n )\n // Derive OAuth-ness from the freshly resolved key — auth mode can\n // change between factory construction and this call (env var set,\n // creds file rotated), and a stale flag would skew the count's\n // system-prompt folding relative to what `stream()` actually sends.\n const callAuth = resolveAnthropicAuthShape(apiKey, anthropicParams?.authMode)\n const callIsOAuth = callAuth.claudeCode\n const client = createClient(\n SDK,\n apiKey,\n callAuth,\n anthropicParams?.baseURL,\n anthropicParams?.extraBetas,\n await resolveExtraHeaders(anthropicParams?.extraHeaders),\n )\n\n // Mirror `stream()`'s wire-payload build so the count matches what is\n // actually sent: OAuth folds the real system prompt into a synthetic\n // user/assistant pair and sends the canonical Claude Code prompt as\n // the system block.\n const wireSystem = renderSystemForWire(payload.system)\n const system = callIsOAuth\n ? `You are Claude Code, Anthropic's official CLI for Claude.`\n : wireSystem\n const messages: SessionMessage[] = callIsOAuth && payload.system\n ? [\n { role: 'user', content: [{ type: 'text' as const, text: wireSystem }] },\n { role: 'assistant', content: [{ type: 'text' as const, text: 'Understood. I will proceed with these instructions above the rest of my system prompt.' }] },\n ...payload.messages,\n ]\n : [...payload.messages]\n\n // Same request-local name boundary as `stream()` — a foreign/legacy\n // tool name in replayed history would 400 the count exactly like the\n // real request.\n const countTools = payload.tools as Anthropic.Tool[]\n const countBoundary = createToolNameBoundary(\n messages,\n countTools.map(t => t.name),\n callIsOAuth ? claudeCodeToolAliases : undefined,\n )\n const res = await client.messages.countTokens(\n {\n model: payload.model as Model,\n system,\n tools: countBoundary.changed\n ? countTools.map(t => ({ ...t, name: countBoundary.toWire(t.name) }))\n : countTools,\n messages: countBoundary.messages.map(m => toAnthropic(m)) as Anthropic.MessageParam[],\n },\n signal ? { signal } : undefined,\n )\n return res.input_tokens\n }\n catch (err) {\n // Unreachable under the active auth / network — caller falls back to\n // the heuristic. Surface the cause when debugging so a silent auth /\n // scope rejection (e.g. OAuth lacking the count endpoint) is visible.\n if (process.env.ZIDANE_DEBUG_COUNT)\n console.error('[anthropic.countTokens] failed:', err)\n return null\n }\n },\n\n async stream(options, callbacks: StreamCallbacks): Promise<TurnResult> {\n // Bedrock mode: SigV4 auth via the AWS credential chain — the Anthropic\n // key/OAuth resolution below must not run (it throws for users who,\n // correctly, have no Anthropic key). No persona, no betas: the wire\n // shape past client construction is identical, so everything from the\n // system block on flows through the same code.\n let apiKey = ''\n const resolveCallApiKey = async (forceRefresh = false, rejectedAccess?: string): Promise<string> => {\n const identity = credentialIdentity(anthropicParams)\n return await resolveOAuthApiKey(\n {\n provider: identity.providerId,\n providerId: identity.providerId,\n params: runtimeCredentials ? { ...anthropicParams, ...runtimeCredentials } : anthropicParams,\n envKey: identity.envKey,\n missingError: identity.missingError,\n refreshError: identity.refreshError,\n forceRefresh,\n rejectedAccess,\n },\n {\n ...callbacks,\n async onOAuthRefresh(ctx) {\n if (ctx.source === 'params') {\n runtimeCredentials = {\n access: ctx.credentials.access,\n refresh: ctx.credentials.refresh,\n expires: ctx.credentials.expires,\n }\n }\n await callbacks.onOAuthRefresh?.(ctx)\n },\n },\n )\n }\n if (!bedrockConfig)\n apiKey = await resolveCallApiKey()\n // Per-call OAuth detection — see the matching note in `countTokens`.\n // Resolved before the conditional betas: the extended-TTL gate below\n // branches on it. Bedrock is never OAuth (empty key → bearer: false).\n const callAuth = resolveAnthropicAuthShape(apiKey, bedrockConfig ? 'api-key' : anthropicParams?.authMode)\n const callIsOAuth = callAuth.claudeCode\n /**\n * Whether a provider auth rejection on this call is worth ATTEMPTING one\n * forced credential rotation. A bearer-authenticated call MAY resolve its\n * token through the refreshable OAuth store — subscription OAuth and\n * `authMode: 'bearer'` gateways (`extensions/bolt`) both do — so a 401\n * arriving before the local expiry is recoverable for them. Deliberately\n * WIDER than {@link callIsOAuth}, which additionally means \"wear the\n * Claude Code persona\"; a gateway is not Claude Code but its token still\n * rotates.\n *\n * The ones that cannot rotate stop at the identical-credential guard in\n * the recovery below rather than being excluded here: a static bearer\n * token supplied as `apiKey` short-circuits `resolveOAuthApiKey` and never\n * reaches the store, so the re-resolve returns the same value and costs\n * nothing but a function call. API-key and Bedrock calls never get that\n * far — `callAuth.bearer` is false for both.\n */\n const callCanRotateAuth = callAuth.bearer\n // Fast mode (`speed: \"fast\"`) is gated behind the `fast-mode-2026-02-01`\n // beta — without the header Anthropic rejects the body field with\n // `speed: Extra inputs are not permitted`. Inject it here (not in the\n // static default betas) so the header is present exactly when the request\n // will carry `speed: \"fast\"`, keeping non-fast requests byte-stable for\n // the prompt cache.\n //\n // Same conditional-injection contract for the extended cache TTL: the\n // `ttl: '1h'` field on `cache_control` is rejected without its beta, so\n // the header rides exactly the requests whose breakpoints carry the ttl\n // (cache on + cacheTtl '1h') and every other request stays byte-stable.\n //\n // OAuth DEFAULTS TO 1h, matching the Claude Code client: the CLI runs\n // extended retention on subscription auth, and the whole point of this\n // path is to behave like it. A 5-minute TTL re-writes the entire prefix\n // at cache-write pricing after any pause longer than five minutes, and\n // on a subscription those writes come out of a fixed allowance rather\n // than a bill — so the default that is merely expensive on API-key auth\n // is the one that exhausts a plan here.\n //\n // An explicit `cacheTtl` from the caller still wins in both directions,\n // which is the opt-out (`cacheTtl: '5m'`) equivalent to the reference\n // plugin's `PI_CACHE_RETENTION=short`.\n //\n // API-key auth keeps the 5m default: there the tradeoff is real money\n // per token (1h writes bill ~2x base input against 1.25x for 5m), so it\n // stays opt-in.\n //\n // Bedrock stays excluded: beta headers are not sent there (the SigV4\n // client drops them), so a `ttl` field would arrive without its gating\n // beta and 400. `cacheTtl` degrades to the default TTL on Bedrock.\n const effectiveCacheTtl = options.cacheTtl ?? (callIsOAuth ? '1h' : undefined)\n const extendedTtl = options.cache !== false && effectiveCacheTtl === '1h' && !bedrockConfig\n const conditionalBetas = [\n // Gated with the field below — the beta rides exactly the requests that\n // carry `speed`, so an OAuth request stays byte-stable for the cache.\n ...(options.modelOptions?.fast && !callIsOAuth ? [FAST_MODE_BETA] : []),\n ...(extendedTtl ? [EXTENDED_CACHE_TTL_BETA] : []),\n ]\n const requestBetas = conditionalBetas.length > 0\n ? [...(anthropicParams?.extraBetas ?? []), ...conditionalBetas]\n : anthropicParams?.extraBetas\n // Bound rather than inlined into `createClient`: the affinity-header\n // no-clobber check below needs the resolved map, and a function resolver\n // must not be called twice per request (it may mint a token).\n const resolvedExtraHeaders = await resolveExtraHeaders(anthropicParams?.extraHeaders)\n let client = bedrockConfig\n ? await createBedrockClient(bedrockConfig, anthropicParams, resolvedExtraHeaders)\n : createClient(\n await loadAnthropicSdk(),\n apiKey,\n callAuth,\n anthropicParams?.baseURL,\n requestBetas,\n resolvedExtraHeaders,\n )\n\n // System prompt injection is handled by agent.ts — we just pass it through.\n // For OAuth, the Claude Code API requires the system block to start with\n // the canonical Claude Code prompt — we prepend it to the real system prompt.\n // For OAuth, the CC API requires the system block to start with the canonical\n // Claude Code prompt. The real system prompt is injected as user+assistant messages.\n //\n // The boundary marker (`SYSTEM_PROMPT_BOUNDARY`) is structural metadata\n // for `applyAnthropicCacheBreakpoints`; strip it before the bytes hit\n // the wire so it never reaches the model. The original (un-rendered)\n // string is preserved as `options.system` and forwarded to the cache\n // helper below for an accurate static/dynamic split.\n const wireSystem = renderSystemForWire(options.system)\n const system = callIsOAuth\n ? `You are Claude Code, Anthropic's official CLI for Claude.`\n : wireSystem\n const messages: SessionMessage[] = callIsOAuth && options.system\n ? [\n { role: 'user', content: [{ type: 'text' as const, text: wireSystem }] },\n { role: 'assistant', content: [{ type: 'text' as const, text: 'Understood. I will proceed with these instructions above the rest of my system prompt.' }] },\n ...options.messages,\n ]\n : [...options.messages]\n const thinking = options.thinking ?? 'off'\n\n // Request-local tool-name boundary. The tools array is normally clean\n // (agent aliasing + `sanitizeToolSpecs` ran upstream), but REPLAYED\n // HISTORY can carry names the current alias maps never saw — sessions\n // imported from other clients, renamed MCP servers, removed tools. The\n // Anthropic-family endpoints (direct API, Bedrock Converse, compatible\n // gateways) validate historical `toolUse.name` against\n // `[a-zA-Z0-9_-]{1,64}` as strictly as the tools array, so one stale\n // name 400s the whole request. Offender-only: clean requests are\n // byte-identical and the prompt cache is unaffected.\n const inputTools = (options.tools ?? []) as Anthropic.ToolUnion[]\n const nameBoundary = createToolNameBoundary(\n messages,\n inputTools.map(t => t.name),\n callIsOAuth ? claudeCodeToolAliases : undefined,\n )\n // Renaming only touches genuine offenders — always plain custom tools\n // (server-tool names like `web_search` are wire-legal by construction),\n // so widening the spread back to the union member is safe.\n const wireTools = nameBoundary.changed\n ? inputTools.map(t => (t.name === nameBoundary.toWire(t.name) ? t : { ...t, name: nameBoundary.toWire(t.name) } as Anthropic.ToolUnion))\n : inputTools\n\n const modelId = options.model as Model\n // The model's max output, sourced from pi-ai's registry (Opus 4.x = 128K\n // native; conservative family fallback when the registry misses). Used as\n // BOTH the default (when `maxTokens` is unset — the field is required) AND\n // a hard clamp, since a value above the model's max would 400. An explicit\n // caller maxTokens RAISES the fallback for registry-unknown models (never\n // lowers it — see the resolver's docblock: the thinking budget sits on top\n // of the caller's cap, so the cap can't double as the ceiling).\n const modelMaxOutput = await resolveAnthropicMaxOutput(modelId, options.maxTokens, options.modelCatalog)\n\n // `context_management` is an untyped beta in SDK v0.90; widen `params` with\n // an optional field so we don't have to double-cast through `unknown` to\n // attach it below.\n const params: Anthropic.MessageCreateParamsStreaming & {\n context_management?: AnthropicContextManagement\n speed?: 'fast' | 'standard'\n // `task_budget` shipped after the pinned SDK's `OutputConfig` type;\n // widen until the SDK catches up.\n output_config?: { task_budget?: { type: 'tokens', total: number } }\n } = {\n // Forward-compat escape hatch for un-typed beta fields. Spread first so\n // the typed core (model / max_tokens / system / tools / messages /\n // stream) and the explicit `context_management` below override on\n // collision — explicit always wins.\n ...((anthropicParams?.extraBodyParams ?? {}) as Record<string, unknown>),\n model: modelId,\n // Required field — default to the model's full max output when unset.\n // The ceiling (incl. a caller cap above the model max) is enforced once,\n // after the thinking plan, since the `enabled` path adds budget on top.\n max_tokens: options.maxTokens ?? modelMaxOutput,\n system,\n tools: wireTools,\n messages: nameBoundary.messages.map(m => toAnthropic(m)) as Anthropic.MessageParam[],\n stream: true,\n }\n\n // Server-side context management (beta `context-management-2025-06-27`).\n // Skipped when the caller didn't pass a config — leaving the field off\n // the wire keeps requests valid on accounts that don't have the beta enabled.\n //\n // Also skipped on Bedrock: its translation layer rejects the field (same\n // API generation as `output_config`, which it 400s with \"Extra inputs are\n // not permitted\"). Dropping a request-shaping option we know will fail is\n // what this file does elsewhere for locally-predictable 400s (the thinking\n // budget clamp, the effort-surface swap); shipping it instead would\n // guarantee the failure.\n if (anthropicParams?.contextManagement && !bedrockConfig)\n params.context_management = anthropicParams.contextManagement\n\n // Prompt caching — inject `cache_control: { type: 'ephemeral' }` breakpoints\n // on the three largest stable prefixes: system prompt, tool definitions, and\n // the last message's final content block. Three of Anthropic's four allowed\n // breakpoints; leaves headroom for a future thinking-block breakpoint.\n //\n // On the API-key path, `params.system` was derived from\n // `renderSystemForWire(options.system)` so the cache helper can split\n // the original on the `SYSTEM_PROMPT_BOUNDARY` marker and apply\n // `cache_control` to the static prefix only — per-turn churn in the\n // dynamic suffix no longer invalidates the cached doctrine above.\n //\n // On the OAuth path, `params.system` is the canonical Claude Code\n // prompt (`\"You are Claude Code...\"`) — `options.system` lives in the\n // injected user message instead, so we do NOT forward it here. Passing\n // it would replace the CC prompt with the user's doctrine. The user\n // message is still naturally cached via the last-message breakpoint\n // applied below; per-turn churn there bypasses the boundary feature on\n // OAuth, but parity with the pre-feature behavior is preserved.\n //\n // Skipped when `options.cache === false` (opt-out) or on any shape that would\n // produce an invalid request (empty system string, zero tools, empty message list).\n if (options.cache !== false)\n applyAnthropicCacheBreakpoints(params, callIsOAuth ? undefined : options.system, extendedTtl ? effectiveCacheTtl : undefined)\n\n // Enable thinking / extended thinking when requested. The default path\n // for level-based control is `thinking.type='adaptive'` plus an\n // `output_config.effort` hint — Anthropic deprecated the explicit\n // `thinking.type='enabled' + budget_tokens` shape on opus 4.6+ and\n // recommends adaptive instead. Callers who need a precise token budget\n // can opt into the explicit-budget path by setting\n // `behavior.thinkingBudget`, accepting Anthropic's deprecation\n // warning in exchange. Either shape requires `temperature=1`.\n //\n // `display: 'summarized'` is set explicitly on both shapes — Opus 4.7\n // and Claude Mythos Preview silently flipped the default to\n // `'omitted'` (signature-only, no text), which makes the SDK fire\n // `thinking` deltas with empty `thinking` content and breaks every\n // host that surfaces traces live. Older models still default to\n // `'summarized'` so this is a no-op there.\n const plan = planAnthropicThinking(thinking, options.thinkingBudget, options.taskBudget, options.effortHint !== false)\n if (plan && bedrockConfig) {\n // Bedrock's translation layer predates the 4.6 thinking surface:\n // `output_config.effort` is rejected with \"Extra inputs are not\n // permitted\" (live-verified), and `thinking.type='adaptive'` /\n // `display` are the same API generation — so every level routes\n // through the legacy explicit-budget shape Bedrock documents. The\n // effort tier picks the budget; an explicit `thinkingBudget` wins.\n const budget = plan.kind === 'enabled'\n ? plan.budgetTokens\n : BEDROCK_THINKING_BUDGETS[plan.effort ?? 'medium']\n params.thinking = { type: 'enabled', budget_tokens: budget }\n // Budget rides on top of the response cap, clamped to the model\n // ceiling below like the standard `enabled` path.\n params.max_tokens = budget + params.max_tokens\n params.temperature = 1\n }\n else if (plan) {\n if (plan.kind === 'enabled') {\n params.thinking = { type: 'enabled', budget_tokens: plan.budgetTokens, display: 'summarized' }\n params.max_tokens = plan.maxTokensBump + params.max_tokens\n // The explicit budget pins tokens; the effort hint still shapes HOW\n // the model spends them. Both fields are valid together on 4.6+.\n // Merge onto any `output_config` the caller passed via\n // `extraBodyParams` (spread first above) rather than clobbering it.\n if (plan.effort)\n params.output_config = { ...params.output_config, effort: plan.effort }\n }\n else {\n params.thinking = { type: 'adaptive', display: 'summarized' }\n const outputConfig: NonNullable<typeof params.output_config> = {}\n if (plan.effort)\n outputConfig.effort = plan.effort\n // Native whole-task thinking cap — adaptive-only. Coexists with the\n // effort hint.\n if (typeof plan.taskBudgetTokens === 'number' && plan.taskBudgetTokens > 0)\n outputConfig.task_budget = { type: 'tokens', total: plan.taskBudgetTokens }\n // Merge onto any caller-supplied `output_config` from\n // `extraBodyParams`; don't drop their fields.\n if (Object.keys(outputConfig).length > 0)\n params.output_config = { ...params.output_config, ...outputConfig }\n // LEGACY (`thinkingBudget` on adaptive): soft-cap the response\n // envelope (`max_tokens`). This clamps text and tool-call JSON too —\n // prefer `taskBudget` above. Reduce only; never raise above the\n // caller's request.\n if (typeof plan.maxTokensCap === 'number' && plan.maxTokensCap > 0)\n params.max_tokens = Math.min(params.max_tokens, plan.maxTokensCap)\n }\n params.temperature = 1\n }\n\n // The `enabled` thinking path adds the budget ON TOP of `max_tokens`,\n // which — now that the base defaults to the model's full max — can push\n // the envelope past the model's hard ceiling → 400. Clamp the final value\n // so the budget shares the envelope rather than overflowing it.\n params.max_tokens = Math.min(params.max_tokens, modelMaxOutput)\n\n // Claude Code payload alignment. Applied after every other mutation so\n // nothing downstream reshapes what the attestation will be hashed over.\n if (callIsOAuth) {\n // The client caps requested output at 64k even where the model allows\n // more (Opus permits 128k), so a larger ceiling is a shape no real\n // client sends.\n params.max_tokens = Math.min(params.max_tokens, CLAUDE_CODE_MAX_OUTPUT_TOKENS)\n // Billing block goes at system[0], ahead of the persona marker. Its\n // `cch` placeholder is filled in by the wrapped fetch once the body is\n // serialized — the hash covers those bytes, so it cannot be computed\n // here.\n if (Array.isArray(params.system)) {\n params.system = [\n { type: 'text', text: claudeCodeBillingText(firstUserMessageText(params.messages)) },\n ...params.system,\n ]\n }\n // Never clobber a caller-set `user_id`: `promptCacheKey` writes the same\n // field and its routing intent outranks fingerprint parity.\n const metadata = params.metadata as { user_id?: unknown } | undefined\n if (typeof metadata?.user_id !== 'string')\n params.metadata = { ...params.metadata, user_id: claudeCodeUserId() }\n }\n\n // Anthropic requires `thinking.budget_tokens` STRICTLY below\n // `max_tokens` (400 otherwise — live-verified on Bedrock, where every\n // level routes through the explicit-budget shape and a mid-tier budget\n // already exceeds a haiku-class 8K ceiling; the direct API has the\n // same failure with a caller `thinkingBudget` above the ceiling).\n // After the envelope clamp above, shrink the budget to fit, reserving\n // room for the visible response. When even Anthropic's documented\n // 1024-token budget minimum can't fit under the envelope, no\n // satisfiable budget exists — degrade to a non-thinking request\n // (dropping the temperature pin the thinking branch set; nothing else\n // sets it) rather than shipping a 400 we can predict locally.\n if (params.thinking?.type === 'enabled' && params.thinking.budget_tokens >= params.max_tokens) {\n const fitted = params.max_tokens - THINKING_RESPONSE_RESERVE_TOKENS\n if (fitted >= 1024) {\n params.thinking.budget_tokens = fitted\n }\n else {\n delete params.thinking\n delete params.temperature\n }\n }\n\n // Fast mode (`speed: \"fast\"`) — ~2.5× output throughput at premium\n // pricing. Supported only on the models in `FAST_MODE_OPTIONS`\n // (chat/anthropic-models.ts); the model-options surface only offers it\n // on those, and Anthropic 400s a request with\n // `speed` on an unsupported model. `speed` is an untyped beta field in\n // SDK v0.90 (widened on `params` above).\n //\n // NOT sent on subscription OAuth: fast mode bills against PURCHASED usage\n // credits, not the plan's included allowance, so Anthropic refuses it with\n // `Usage credits are required for fast mode` (429) — surfaced in the TUI as\n // \"You're out of extra usage\" — for every subscription user who has not\n // topped up, no matter how much included allowance remains. Live-verified:\n // the identical request returns 200 without `speed` and is refused with\n // it. Dropping the field degrades to standard throughput, which is the\n // only thing that can actually run on that credential.\n if (options.modelOptions?.fast && !callIsOAuth)\n params.speed = 'fast'\n\n // Tool choice forcing. The forced name must match the (possibly\n // boundary-renamed) name in the tools array, mirroring openai-compat.\n if (options.toolChoice) {\n if (options.toolChoice.type === 'tool' && options.toolChoice.name)\n params.tool_choice = { type: 'tool', name: nameBoundary.toWire(options.toolChoice.name) }\n else if (options.toolChoice.type === 'required')\n params.tool_choice = { type: 'any' }\n else\n params.tool_choice = { type: 'auto' }\n }\n\n // Prompt-cache affinity key, carried as `metadata.user_id`. Derived from\n // the session's stable prefix, so it is byte-identical across a session's\n // turns and cannot itself break a cache. Merged onto any `metadata` the\n // caller passed via `extraBodyParams` (spread first above) rather than\n // clobbering it, and a caller- or gateway-supplied `user_id` always wins:\n // an intermediary that sets this itself must not be second-guessed.\n //\n // `options.system` is used for the derivation on BOTH auth paths, not\n // `params.system` — on OAuth the latter is the canonical Claude Code\n // prompt, identical across every session, which would collapse all\n // sessions onto one key.\n const promptCacheKey = resolvePromptCacheKey(anthropicParams?.promptCacheKey, {\n model: modelId,\n system: options.system,\n messages: options.messages,\n })\n if (promptCacheKey !== undefined && params.metadata?.user_id === undefined)\n params.metadata = { ...params.metadata, user_id: promptCacheKey }\n\n // HTTP header names are case-insensitive (and the SDK merges per-request\n // headers over `defaultHeaders` case-insensitively), so the no-clobber\n // probe must be too — an exact-key check would let the affinity header\n // silently beat a differently-cased caller header from `extraHeaders`.\n const affinityHeaderName = anthropicParams?.promptCacheKeyHeader?.toLowerCase()\n const affinityHeader = anthropicParams?.promptCacheKeyHeader !== undefined && promptCacheKey !== undefined\n && !Object.keys(resolvedExtraHeaders ?? {}).some(k => k.toLowerCase() === affinityHeaderName)\n ? { [anthropicParams.promptCacheKeyHeader]: promptCacheKey }\n : undefined\n\n const runStream = async (\n requestParams: typeof params,\n fastRequested: boolean,\n scrubPass = 0,\n authPass = 0,\n ): Promise<TurnResult> => {\n const s = client.messages.stream(requestParams, {\n signal: options.signal,\n ...(affinityHeader ? { headers: affinityHeader } : {}),\n })\n\n let text = ''\n let observedOutput = false\n\n s.on('text', (delta) => {\n observedOutput = true\n text += delta\n callbacks.onText(delta)\n })\n\n if (callbacks.onThinking) {\n s.on('thinking', (delta) => {\n observedOutput = true\n callbacks.onThinking!(delta)\n })\n }\n\n // Liveness signal for tool-only turns: `inputJson` fires as a\n // `tool_use` block's arguments stream in. Without it, a turn that\n // emits only tool calls (no text/thinking) never trips the loop's\n // \"first response observed\" gate and the first-response watchdog can\n // abort an actively-progressing stream. (B2)\n if (callbacks.onToolCallDelta) {\n s.on('inputJson', () => {\n observedOutput = true\n callbacks.onToolCallDelta!()\n })\n }\n\n // Server-tool blocks (e.g. `web_search_20250305`) execute on Anthropic's\n // side and arrive in the assistant content stream — not via our tool\n // loop. The SDK fires `contentBlock` once per block as it closes, so\n // listen for the two we care about and dispatch generic callbacks.\n // Other block types (text, thinking, tool_use, …) have their own paths\n // above / in `finalMessage()` — ignored here to avoid double-emission.\n if (callbacks.onServerToolUse || callbacks.onServerToolResult) {\n s.on('contentBlock', (block) => {\n observedOutput = true\n if (block.type === 'server_tool_use') {\n callbacks.onServerToolUse?.({\n id: block.id,\n name: block.name,\n input: (block.input as Record<string, unknown> | undefined) ?? {},\n })\n }\n else if (block.type === 'web_search_tool_result') {\n callbacks.onServerToolResult?.({\n toolUseId: block.tool_use_id,\n toolName: 'web_search',\n content: block.content,\n })\n }\n })\n }\n\n let response: Anthropic.Message\n try {\n response = await s.finalMessage()\n }\n catch (err) {\n if (!observedOutput && scrubPass < MAX_THINKING_SCRUB_PASSES && isRecoverableThinkingBlockError(err, requestParams.messages)) {\n const failingIndex = parseFailingMessageIndex(err)\n // Escalation ladder: the first pass scrubs only at/before the\n // API-reported failing index (preserving still-valid thinking\n // later in the wire). If the retry hits ANOTHER signature 400 —\n // the API reports one bad locator at a time, so scattered stale\n // blocks surface index-by-index — stop chasing locators and\n // scrub the full history EXCEPT the active chain. See\n // {@link planThinkingScrub} for the chain-protection rules\n // (never strip the in-flight exchange's thinking wholesale;\n // Anthropic requires it echoed back).\n const plan = planThinkingScrub(scrubPass, failingIndex, requestParams.messages)\n const scrubbed = withoutHistoricalThinking(requestParams.messages, plan.upToIndex, plan.alsoMessageIndex)\n // Guard against an infinite retry if Anthropic reports the same\n // error despite there being nothing left to strip (or if this is\n // already the scrubbed retry).\n if (scrubbed.removed > 0) {\n // Ask the loop to repair + persist its canonical history before\n // retrying. Direct provider consumers may omit the callback;\n // the scrubbed wire retry still succeeds for this turn.\n try {\n await callbacks.onHistoryRepair?.({\n type: 'invalid-anthropic-thinking-signature',\n ...(failingIndex !== undefined ? { wireMessageIndex: failingIndex } : {}),\n })\n }\n catch (repairErr) {\n // Canonical persistence is best-effort; never let a host\n // callback block the safe wire-level recovery for this turn.\n if (process.env.ZIDANE_DEBUG)\n process.stderr.write(`[zidane/anthropic] history repair callback failed: ${errorMessage(repairErr)}\\n`)\n }\n return await runStream(\n { ...requestParams, messages: scrubbed.messages },\n fastRequested,\n scrubPass + 1,\n authPass,\n )\n }\n }\n // OAuth access can be revoked server-side before its local expiry.\n // Re-read/refresh once, rebuild the client with the rotated access\n // token, and retry only when no output was observed (avoids replaying\n // a partially delivered assistant turn). API-key and Bedrock runs\n // never enter this path — `callAuth.bearer` is false for both. Bearer\n // gateways DO enter it, and stop at the identical-credential guard\n // below when their token turns out not to rotate. Zidane still\n // persists only through the existing onOAuthRefresh callback for\n // parameter-owned credentials.\n if (callCanRotateAuth && authPass === 0 && !observedOutput && isAnthropicAuthenticationError(err)) {\n const rejectedAccess = apiKey\n let refreshedApiKey: string\n try {\n refreshedApiKey = await resolveCallApiKey(true, rejectedAccess)\n }\n catch (refreshErr) {\n // The forced refresh is additive recovery, so its failure must not\n // replace the provider's own rejection: a revoked grant fails BOTH\n // (and the 401 is what carries the status / `authentication_error`\n // that `classifyAnthropicError` keys on), while a transient\n // network failure here would otherwise surface as \"re-login\" to a\n // user whose credential was fine.\n //\n // The reason still has to survive, though — a revoked grant is the\n // likeliest way into this branch, and \"why\" should not be reachable\n // only through an env var nobody has set. `cause` keeps it in the\n // chain and in printed stack traces while leaving the message and\n // the classification untouched. Never clobber a cause the SDK set.\n //\n // Best-effort by construction: `err` belongs to the provider SDK,\n // and assigning to a frozen or sealed object throws a TypeError\n // under ESM's strict mode. Letting that escape would replace the\n // 401 with a TypeError — precisely the masking this whole branch\n // exists to prevent — so a failure to annotate is swallowed and\n // the rejection propagates unchanged.\n if (err !== null && typeof err === 'object' && (err as { cause?: unknown }).cause === undefined) {\n try {\n (err as { cause?: unknown }).cause = refreshErr\n }\n catch {}\n }\n if (process.env.ZIDANE_DEBUG)\n process.stderr.write(`[zidane/anthropic] forced OAuth refresh after 401 failed: ${errorMessage(refreshErr)}\\n`)\n throw err\n }\n // Access-only OAuth inputs cannot rotate. Retrying the identical\n // rejected credential would only duplicate the request and can be\n // dangerous if the provider emitted an empty/ambiguous stream.\n if (refreshedApiKey === rejectedAccess)\n throw err\n apiKey = refreshedApiKey\n client = createClient(\n await loadAnthropicSdk(),\n apiKey,\n // `callAuth`, not a re-sniff of the rotated token: the persona\n // decision is already baked into this call's system block and\n // message shape (see the `callIsOAuth` branches above). A rotated\n // token that happens not to look like `sk-ant-oat` — every\n // `authMode: 'bearer'` gateway token, plus anything from a\n // `credentialSource` custom flow — would otherwise flip the wire\n // auth to `x-api-key` and drop the Claude Code betas mid-call.\n callAuth,\n anthropicParams?.baseURL,\n requestBetas,\n resolvedExtraHeaders,\n )\n return await runStream(requestParams, fastRequested, scrubPass, authPass + 1)\n }\n if (fastRequested && !observedOutput && shouldFallbackFromFastMode(err)) {\n const standardParams = { ...requestParams }\n delete standardParams.speed\n return await runStream(standardParams, false, scrubPass, authPass)\n }\n throw err\n }\n\n const toolCalls = response.content\n .filter((b): b is Anthropic.ToolUseBlock => b.type === 'tool_use')\n .map(b => ({ id: b.id, name: nameBoundary.fromWire(b.name), input: b.input as Record<string, unknown> }))\n\n const finishReason = mapStopReason(response.stop_reason)\n\n // `pause_turn` is *not* terminal — the loop has to inject a continue\n // message and run another turn. Without this branch, the previous\n // `toolCalls.length === 0` shortcut would mark the run done at the\n // pause and silently drop the work in flight.\n const isPause = response.stop_reason === 'pause_turn'\n\n const rawUsage: TurnUsage = {\n input: response.usage.input_tokens,\n output: response.usage.output_tokens,\n cacheCreation: response.usage.cache_creation_input_tokens ?? undefined,\n cacheRead: response.usage.cache_read_input_tokens ?? undefined,\n ...(finishReason ? { finishReason } : {}),\n modelId: response.model ?? (options.model as string),\n }\n // OAuth = subscription traffic (Claude Pro/Max via a Claude Code\n // account): usage is included in the flat plan, not billed per\n // token. Estimating API-list prices for it produces large dollar\n // figures the user never pays — so `cost` stays absent and cost\n // surfaces (footer counter, usage-by-model rows) show tokens\n // without a price, matching Claude Code's own /cost behavior.\n // API-key turns estimate as before; a mixed session (OAuth primary\n // with an API-key fallback, or vice versa) prices each turn by how\n // it was actually served.\n const usage = callIsOAuth\n ? rawUsage\n : await fillEstimatedCost(rawUsage, 'anthropic', fastRequested\n ? fastModeCostMultiplier(response.model ?? (options.model as string))\n : undefined, options.modelCatalog)\n const assistantMessage = fromAnthropic({ role: 'assistant', content: response.content })\n // Restore caller-side names on persisted content so the outer loop's\n // own wire→canonical aliasing applies normally (mirrors openai.ts).\n if (nameBoundary.changed) {\n assistantMessage.content = assistantMessage.content.map(block =>\n block.type === 'tool_call' ? { ...block, name: nameBoundary.fromWire(block.name) } : block,\n )\n }\n return {\n assistantMessage,\n text,\n toolCalls,\n done: !isPause && (response.stop_reason === 'end_turn' || toolCalls.length === 0),\n usage,\n }\n }\n\n // `fastRequested` drives the fast→standard downgrade retry, so it must\n // track whether `speed` actually reached the payload — on OAuth it never\n // does, and claiming otherwise would arm a fallback for a field we did\n // not send.\n return await runStream(params, options.modelOptions?.fast === true && !callIsOAuth)\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAyBA,MAAa,mBAAgC;CAC3C,IAAI;CACJ,OAAO;CACP,aAAa;CACb,gBAAgB;EAAE,OAAO;EAAG,QAAQ;EAAG,WAAW;EAAG,YAAY;CAAE;AACrE;AAEA,MAAM,0BAAuC;CAC3C,GAAG;CACH,aAAa;CACb,gBAAgB;EAAE,OAAO;EAAG,QAAQ;EAAG,WAAW;EAAG,YAAY;CAAE;AACrE;;AAGA,MAAa,oBAA2D;CACtE,iBAAiB;CACjB,mBAAmB;CACnB,mBAAmB;CACnB,mBAAmB;AACrB;;;;;;;AAQA,SAAgB,uBAAuB,SAAgD;CACrF,OAAO,kBAAkB,QAAQ,EAAE;AACrC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,MAAa,yBAA+C;CAC1D;EACE,IAAI;EACJ,MAAM;EACN,WAAW;EACX,OAAO,CAAC,QAAQ,OAAO;EACvB,MAAM;GAAE,OAAO;GAAI,QAAQ;GAAI,WAAW;GAAM,YAAY;EAAK;EACjE,eAAe;EACf,WAAW;EACX,UAAU;CACZ;CACA;EACE,IAAI;EACJ,MAAM;EACN,WAAW;EACX,OAAO,CAAC,QAAQ,OAAO;EACvB,MAAM;GAAE,OAAO;GAAG,QAAQ;GAAI,WAAW;GAA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