@bastani/pi-ai 0.9.74-alpha.1 → 0.9.75-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/README.md +3 -1
- package/dist/api/anthropic-messages.d.ts.map +1 -1
- package/dist/api/anthropic-messages.js +21 -7
- package/dist/api/anthropic-messages.js.map +1 -1
- package/dist/api/bedrock-converse-stream.d.ts.map +1 -1
- package/dist/api/bedrock-converse-stream.js +4 -2
- package/dist/api/bedrock-converse-stream.js.map +1 -1
- package/dist/api/constrained-sampling.d.ts +0 -2
- package/dist/api/constrained-sampling.d.ts.map +1 -1
- package/dist/api/constrained-sampling.js +0 -13
- package/dist/api/constrained-sampling.js.map +1 -1
- package/dist/api/openai-completions.d.ts.map +1 -1
- package/dist/api/openai-completions.js +9 -5
- package/dist/api/openai-completions.js.map +1 -1
- package/dist/api/openai-images-options.d.ts +18 -5
- package/dist/api/openai-images-options.d.ts.map +1 -1
- package/dist/api/openai-images-options.js +9 -3
- package/dist/api/openai-images-options.js.map +1 -1
- package/dist/api/openai-images.d.ts.map +1 -1
- package/dist/api/openai-images.js +121 -19
- package/dist/api/openai-images.js.map +1 -1
- package/dist/api/openai-responses.d.ts.map +1 -1
- package/dist/api/openai-responses.js +10 -3
- package/dist/api/openai-responses.js.map +1 -1
- package/dist/api/strict-tool-limits.d.ts +13 -0
- package/dist/api/strict-tool-limits.d.ts.map +1 -0
- package/dist/api/strict-tool-limits.js +50 -0
- package/dist/api/strict-tool-limits.js.map +1 -0
- package/dist/auth/types.d.ts +7 -0
- package/dist/auth/types.d.ts.map +1 -1
- package/dist/auth/types.js.map +1 -1
- package/dist/cache-warming.d.ts +53 -0
- package/dist/cache-warming.d.ts.map +1 -0
- package/dist/cache-warming.js +82 -0
- package/dist/cache-warming.js.map +1 -0
- package/dist/image-generation-error.d.ts +10 -3
- package/dist/image-generation-error.d.ts.map +1 -1
- package/dist/image-generation-error.js +3 -2
- package/dist/image-generation-error.js.map +1 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/models.d.ts +15 -6
- package/dist/models.d.ts.map +1 -1
- package/dist/models.js +22 -7
- package/dist/models.js.map +1 -1
- package/dist/providers/data/.manifest.json +1 -1
- package/dist/providers/data/amazon-bedrock.json +1 -1
- package/dist/providers/data/anthropic.json +1 -1
- package/dist/providers/data/azure.json +1 -1
- package/dist/providers/data/google.json +1 -1
- package/dist/providers/data/meta.json +1 -1
- package/dist/providers/data/opencode-go.json +1 -1
- package/dist/providers/data/opencode.json +1 -1
- package/dist/providers/data/openrouter.json +1 -1
- package/dist/providers/data/vercel-ai-gateway.json +1 -1
- package/dist/providers/github-copilot-errors.d.ts +17 -5
- package/dist/providers/github-copilot-errors.d.ts.map +1 -1
- package/dist/providers/github-copilot-errors.js +55 -11
- package/dist/providers/github-copilot-errors.js.map +1 -1
- package/dist/providers/github-copilot-stream-attempt.d.ts +27 -0
- package/dist/providers/github-copilot-stream-attempt.d.ts.map +1 -0
- package/dist/providers/github-copilot-stream-attempt.js +45 -0
- package/dist/providers/github-copilot-stream-attempt.js.map +1 -0
- package/dist/providers/github-copilot.d.ts +10 -2
- package/dist/providers/github-copilot.d.ts.map +1 -1
- package/dist/providers/github-copilot.js +62 -36
- package/dist/providers/github-copilot.js.map +1 -1
- package/dist/types.d.ts +2 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/utils/stream-deadline.d.ts +6 -2
- package/dist/utils/stream-deadline.d.ts.map +1 -1
- package/dist/utils/stream-deadline.js +12 -3
- package/dist/utils/stream-deadline.js.map +1 -1
- package/dist/utils/version.d.ts +1 -1
- package/dist/utils/version.js +1 -1
- package/dist/utils/version.js.map +1 -1
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"anthropic-messages.js","sourceRoot":"","sources":["../../src/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AO,EAAE,UAAU,EAAE,MAAM,EAAE,CAAC;QAC/B,KAAK,YAAY;YAChB,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,CAAC;QACjC,KAAK,UAAU;YACd,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,CAAC;QAClC,KAAK,SAAS;YACb,OAAO;gBACN,UAAU,EAAE,OAAO;gBACnB,YAAY,EAAE,WAAW,EAAE,WAAW,IAAI,2CAA2C;aACrF,CAAC;QACH,KAAK,YAAY,EAAE,kCAAkC;YACpD,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,CAAC;QAC/B,KAAK,eAAe;YACnB,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,CAAC,CAAC,8DAA8D;QAC9F,KAAK,WAAW,EAAE,2DAA2D;YAC5E,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,YAAY,EAAE,kCAAkC,EAAE,CAAC;QAClF;YACC,kEAAkE;YAClE,MAAM,IAAI,KAAK,CAAC,0BAA0B,MAAM,EAAE,CAAC,CAAC;IACtD,CAAC;AACF,CAAC","sourcesContent":["import Anthropic, { type ClientOptions, type Middleware } from \"@anthropic-ai/sdk\";\nimport type {\n\tBetaTool,\n\tBetaCacheControlEphemeral as CacheControlEphemeral,\n\tBetaContentBlockParam as ContentBlockParam,\n\tMessageCreateParamsStreaming,\n\tBetaMessageParam as MessageParam,\n} from \"@anthropic-ai/sdk/resources/beta/messages/messages.js\";\nimport type { RawMessageStreamEvent, RefusalStopDetails } from \"@anthropic-ai/sdk/resources/messages.js\";\nimport type { ErrorType } from \"@anthropic-ai/sdk/resources/shared.js\";\nimport {\n\tANTHROPIC_FEDERATION_RULE_ID_ENV,\n\tANTHROPIC_IDENTITY_TOKEN_FILE_ENV,\n\tANTHROPIC_ORGANIZATION_ID_ENV,\n\tANTHROPIC_SERVICE_ACCOUNT_ID_ENV,\n\tANTHROPIC_WORKSPACE_ID_ENV,\n} from \"../env-api-keys.ts\";\nimport { calculateCost } from \"../models.ts\";\nimport { recordGitHubCopilotFailure } from \"../providers/github-copilot-errors.ts\";\nimport { registerSessionResourceCleanup } from \"../session-resources.ts\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tCacheRetention,\n\tImageContent,\n\tMessage,\n\tModel,\n\tProviderEnv,\n\tProviderHeaders,\n\tSimpleStreamOptions,\n\tStopReason,\n\tStreamFunction,\n\tStreamOptions,\n\tTextContent,\n\tThinkingLevel,\n\tTool,\n\tToolResultMessage,\n\tUsage,\n} from \"../types.ts\";\nimport { raceWithAbortSignal } from \"../utils/abort.js\";\nimport { appendAssistantMessageDiagnostic } from \"../utils/diagnostics.ts\";\nimport { assertSupportedDocumentMimeType } from \"../utils/document-input.ts\";\nimport { withCauseDetail } from \"../utils/error-body.ts\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.ts\";\nimport { shortHash } from \"../utils/hash.ts\";\nimport { headersToRecord } from \"../utils/headers.ts\";\nimport { type ClientIdentity, getIdentityHeaders } from \"../utils/identity.ts\";\nimport { parseJsonWithRepair } from \"../utils/json-parse.ts\";\nimport {\n\tapplyOpenRouterReportedCost,\n\tisOpenRouterModel,\n\ttype OpenRouterUsageAccounting,\n} from \"../utils/openrouter-cost.ts\";\nimport { getProviderEnvValue } from \"../utils/provider-env.ts\";\nimport { retryProviderRequest } from \"../utils/provider-retry.ts\";\nimport { getFetchAdmission } from \"../utils/request-admission.js\";\nimport { getProviderRetryAfterMs } from \"../utils/retry-hints.ts\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.ts\";\nimport { createStreamDeadline, withStreamDeadline } from \"../utils/stream-deadline.ts\";\nimport { ToolCallArgumentsStream } from \"../utils/streaming-json.ts\";\nimport { getSystemMessageText, renderSystemMessageUpdate } from \"../utils/text.ts\";\nimport { appendThinkingOffFallbackDiagnostic, getThinkingOffFallbackLevel } from \"../utils/thinking-off.ts\";\nimport {\n\tgetCurrentTools,\n\tgetInitialSystemMessage,\n\tresolveTranscript,\n\ttype TranscriptContext,\n} from \"../utils/transcript.ts\";\nimport { convertAnthropicAssistantContent } from \"./anthropic-assistant-content.ts\";\nimport {\n\tANTHROPIC_STRICT_JSON_SCHEMA_PROFILE,\n\tgetJsonSchemaToolParameters,\n\tisStrictToolLimitErrorMessage,\n\tprefersJsonSchemaStrictSampling,\n\tresolveJsonSchemaStrictSampling,\n} from \"./constrained-sampling.ts\";\nimport {\n\tbuildCopilotDynamicHeaders,\n\thasCopilotVisionInput,\n\tpreserveCopilotIntegrationHeader,\n} from \"./github-copilot-headers.ts\";\nimport { adjustMaxTokensForThinking, buildBaseOptions, clampMaxTokensToContext } from \"./simple-options.ts\";\nimport { splitErrorToolResultImages, transformMessages } from \"./transform-messages.ts\";\n\n/**\n * Resolve cache retention preference.\n * Defaults to \"short\" and uses PI_CACHE_RETENTION for backward compatibility.\n */\nfunction resolveCacheRetention(cacheRetention?: CacheRetention, env?: ProviderEnv): CacheRetention {\n\tif (cacheRetention) {\n\t\treturn cacheRetention;\n\t}\n\tif (getProviderEnvValue(\"PI_CACHE_RETENTION\", env) === \"long\") {\n\t\treturn \"long\";\n\t}\n\treturn \"short\";\n}\n\nfunction getCacheControl(\n\tmodel: Model<\"anthropic-messages\">,\n\tcacheRetention?: CacheRetention,\n\tenv?: ProviderEnv,\n): { retention: CacheRetention; cacheControl?: CacheControlEphemeral } {\n\tconst retention = resolveCacheRetention(cacheRetention, env);\n\tif (retention === \"none\") {\n\t\treturn { retention };\n\t}\n\tconst ttl = retention === \"long\" && getAnthropicCompat(model).supportsLongCacheRetention ? \"1h\" : undefined;\n\treturn {\n\t\tretention,\n\t\tcacheControl: { type: \"ephemeral\", ...(ttl && { ttl }) },\n\t};\n}\n\n// Stealth mode: Mimic Claude Code's tool naming exactly\n//\n// Anthropic gates newer models on the `claude-cli/<version>` user agent alone and rejects an\n// older one with `claude_code_version_too_old`. `claude-fable-5-1` requires >= 2.1.251 (bisected\n// against the live API: 2.1.250 -> 400, 2.1.251 -> 200) and Claude Opus 5.5 requires >= 2.1.280,\n// the floor the API names in its rejection. This is pinned to the highest published minimum\n// among shipped models rather than the newest release; every model this provider ships answers\n// 200 at 2.1.280. Raise it only when a model rejects this value; a caller can override it for\n// one client through the `headers` option, whose lowercase `user-agent` key is merged last.\nconst claudeCodeVersion = \"2.1.280\";\n\n// Claude Code 2.x tool names (canonical casing)\n// Source: https://cchistory.mariozechner.at/data/prompts-2.1.11.md\n// To update: https://github.com/badlogic/cchistory\nconst claudeCodeTools = [\n\t\"Read\",\n\t\"Write\",\n\t\"Edit\",\n\t\"Bash\",\n\t\"Grep\",\n\t\"Glob\",\n\t\"AskUserQuestion\",\n\t\"EnterPlanMode\",\n\t\"ExitPlanMode\",\n\t\"KillShell\",\n\t\"NotebookEdit\",\n\t\"Skill\",\n\t\"Task\",\n\t\"TaskOutput\",\n\t\"TodoWrite\",\n\t\"WebFetch\",\n\t\"WebSearch\",\n];\n\nconst ccToolLookup = new Map(claudeCodeTools.map((t) => [t.toLowerCase(), t]));\n\n// Convert tool name to CC canonical casing if it matches (case-insensitive)\nconst toClaudeCodeName = (name: string) => ccToolLookup.get(name.toLowerCase()) ?? name;\nconst fromClaudeCodeName = (name: string, tools?: Tool[]) => {\n\tif (tools && tools.length > 0) {\n\t\tconst lowerName = name.toLowerCase();\n\t\tconst matchedTool = tools.find((tool) => tool.name.toLowerCase() === lowerName);\n\t\tif (matchedTool) return matchedTool.name;\n\t}\n\treturn name;\n};\n\nfunction convertImageBlock(image: ImageContent) {\n\treturn {\n\t\ttype: \"image\" as const,\n\t\tsource: {\n\t\t\ttype: \"base64\" as const,\n\t\t\tmedia_type: image.mimeType as \"image/jpeg\" | \"image/png\" | \"image/gif\" | \"image/webp\",\n\t\t\tdata: image.data,\n\t\t},\n\t};\n}\n\n/**\n * Convert tool-result content blocks to Anthropic API format.\n *\n * Tool results carry text and images only. `DocumentContent` appears exclusively in user\n * messages, which `convertMessages` serializes on its own path.\n */\nfunction convertContentBlocks(content: (TextContent | ImageContent)[]):\n\t| string\n\t| Array<\n\t\t\t| { type: \"text\"; text: string }\n\t\t\t| {\n\t\t\t\t\ttype: \"image\";\n\t\t\t\t\tsource: {\n\t\t\t\t\t\ttype: \"base64\";\n\t\t\t\t\t\tmedia_type: \"image/jpeg\" | \"image/png\" | \"image/gif\" | \"image/webp\";\n\t\t\t\t\t\tdata: string;\n\t\t\t\t\t};\n\t\t\t }\n\t > {\n\t// If only text blocks, return as concatenated string for simplicity\n\tconst hasImages = content.some((c) => c.type === \"image\");\n\tif (!hasImages) {\n\t\treturn sanitizeSurrogates(content.map((c) => (c as TextContent).text).join(\"\\n\"));\n\t}\n\n\t// If we have images, convert to content block array\n\tconst blocks = content.map((block) => {\n\t\tif (block.type === \"text\") {\n\t\t\treturn {\n\t\t\t\ttype: \"text\" as const,\n\t\t\t\ttext: sanitizeSurrogates(block.text),\n\t\t\t};\n\t\t}\n\t\treturn convertImageBlock(block);\n\t});\n\n\t// If only images (no text), add placeholder text block\n\tconst hasText = blocks.some((b) => b.type === \"text\");\n\tif (!hasText) {\n\t\tblocks.unshift({\n\t\t\ttype: \"text\" as const,\n\t\t\ttext: \"(see attached image)\",\n\t\t});\n\t}\n\n\treturn blocks;\n}\n\nexport type AnthropicEffort = \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n\nexport type AnthropicThinkingDisplay = \"summarized\" | \"omitted\";\n\nconst FINE_GRAINED_TOOL_STREAMING_BETA = \"fine-grained-tool-streaming-2025-05-14\";\nconst INTERLEAVED_THINKING_BETA = \"interleaved-thinking-2025-05-14\";\nconst SERVER_SIDE_FALLBACK_BETA = \"server-side-fallback-2026-07-01\";\nconst THINKING_BINDING_CONTROLS_BETA = \"thinking-binding-controls-2026-08-01\";\nconst MID_CONVERSATION_OUTPUT_CONFIG_BETA = \"mid-conversation-output-config-2026-07-01\";\nconst INLINE_TOOLS_BETA = \"inline-tools-2026-09-15\";\nconst MESSAGE_THREADS_BETA = \"message-threads-2026-08-12\";\nconst FAST_MODE_BETA = \"fast-mode-2026-02-01\";\n\n/**\n * Fast mode bills every token category at twice the standard rate for each supported model, across\n * the full context window, and prompt-caching multipliers stack on top.\n * https://platform.claude.com/docs/en/build-with-claude/fast-mode#pricing\n */\nconst FAST_MODE_PRICE_MULTIPLIER = 2;\n\ntype AnthropicSpeed = \"standard\" | \"fast\";\n\nfunction requestedSpeed(model: Pick<Model<\"anthropic-messages\">, \"fastRoute\">): AnthropicSpeed | undefined {\n\treturn model.fastRoute?.speed;\n}\n\nfunction upstreamModelId(model: Pick<Model<\"anthropic-messages\">, \"fastRoute\" | \"id\">): string {\n\treturn model.fastRoute?.upstreamModelId ?? model.id;\n}\n\nfunction reportedSpeed(usage: unknown): AnthropicSpeed | undefined {\n\tconst speed = (usage as { speed?: unknown } | null | undefined)?.speed;\n\treturn speed === \"fast\" || speed === \"standard\" ? speed : undefined;\n}\n\nfunction applyFastModePricing(usage: Usage): void {\n\tusage.cost.input *= FAST_MODE_PRICE_MULTIPLIER;\n\tusage.cost.output *= FAST_MODE_PRICE_MULTIPLIER;\n\tusage.cost.cacheRead *= FAST_MODE_PRICE_MULTIPLIER;\n\tusage.cost.cacheWrite *= FAST_MODE_PRICE_MULTIPLIER;\n\tusage.cost.total = usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite;\n\tusage.cost.totalFromProvider = false;\n}\n\n/**\n * Reject a payload hook that rewrote a field the model's fast route owns.\n *\n * A fast variant is recorded, persisted, and billed under its own `-fast` identity, so a hook that\n * changes the upstream model or drops `speed: \"fast\"` would send a different request under that\n * identity. Refusing loudly surfaces the misconfigured hook instead of silently restoring the route.\n */\nfunction assertPayloadPreservesFastRoute(model: Model<\"anthropic-messages\">, payload: unknown): void {\n\tconst fastRoute = model.fastRoute;\n\tif (fastRoute?.speed === undefined) return;\n\tconst remedy =\n\t\t`A fast model variant must send its route's upstream model and speed, because it is recorded, persisted, ` +\n\t\t`and billed under its own identity. Select the normal model \"${model.provider}/${fastRoute.baseModelId}\" ` +\n\t\t`if the request needs different routing`;\n\tif (typeof payload !== \"object\" || payload === null || Array.isArray(payload)) {\n\t\tthrow new Error(\n\t\t\t`A request hook changed payload for fast model \"${model.provider}/${model.id}\" to a value that cannot carry ` +\n\t\t\t\t`the route's upstream model and speed. ${remedy}, or return an object that preserves those fields.`,\n\t\t);\n\t}\n\tconst record = payload as Record<string, unknown>;\n\tconst conflicts: string[] = [];\n\tif (record.model !== fastRoute.upstreamModelId) {\n\t\tconflicts.push(`model (expected \"${fastRoute.upstreamModelId}\", got ${JSON.stringify(record.model)})`);\n\t}\n\tif (record.speed !== fastRoute.speed) {\n\t\tconflicts.push(`speed (expected ${JSON.stringify(fastRoute.speed)}, got ${JSON.stringify(record.speed)})`);\n\t}\n\tif (conflicts.length === 0) return;\n\tthrow new Error(\n\t\t`A request hook changed ${conflicts.join(\" and \")} for fast model \"${model.provider}/${model.id}\". ` +\n\t\t\t`${remedy}, or stop rewriting those fields.`,\n\t);\n}\n\n/**\n * Stable deferred tool declared whenever native tool changes are in use. Anthropic adds\n * hidden prompt scaffolding for mid-conversation tool changes; declaring this placeholder\n * from the first request keeps that scaffolding in the cached prefix. It is never activated\n * and the model cannot see it.\n */\nconst DEFERRED_TOOL_PLACEHOLDER: BetaTool = {\n\tname: \"__pi_deferred_placeholder__\",\n\tdescription: \"Reserved placeholder. Never available. Never call this.\",\n\tinput_schema: { type: \"object\", properties: {}, required: [] },\n\tdefer_loading: true,\n};\n\nfunction shouldUseServerSideFallbackBeta(model: Model<\"anthropic-messages\">): boolean {\n\treturn (model.compat?.allowedFallbackModels?.length ?? 0) > 0;\n}\n\n/**\n * Claude Fable 5.1 binds each thinking block to the conversation prefix that produced it and,\n * for Anthropic accounts created on or after 2026-08-31, rejects a replay behind a changed\n * `system` prompt, `tools` array, or earlier message with a 400 `invalid_request_error`.\n * Atomic rebuilds those inputs between turns (dynamic system prompt, tool availability changes,\n * model switches), so it opts into `prefix_mismatch_behavior: \"drop_block\"`: the API discards\n * the affected thinking blocks and answers the turn instead of failing the session.\n *\n * This covers live prefix mismatches *between* compaction boundaries. It is not what handles\n * compaction itself: Atomic's client-side `preserve_recent` tail compaction serializes the\n * protected tail into a single boundary message, so no signed thinking block survives a\n * boundary to be replayed behind it. That is Anthropic's documented keep-tail remedy applied\n * structurally rather than a case `drop_block` has to catch.\n * https://platform.claude.com/docs/en/build-with-claude/preserved-thinking\n */\nfunction shouldUseThinkingBindingControlsBeta(model: Model<\"anthropic-messages\">): boolean {\n\treturn model.compat?.enforcesPreservedThinkingBinding === true;\n}\n\n/**\n * Per-turn effort and preserved-thinking binding are independent capabilities.\n * `supportsMidConvoEffort` adds provider effort markers and requires binding controls;\n * Atomic's older `enforcesPreservedThinkingBinding` remains the broader opt-in for\n * transports that need drop recovery without supporting effort-only system messages.\n */\nfunction supportsMidConvoEffort(model: Model<\"anthropic-messages\">): boolean {\n\treturn model.compat?.supportsMidConvoEffort === true;\n}\n\n/** One entry of the `input_transformations` array the block-binding controls beta adds. */\ninterface AnthropicInputTransformation {\n\ttype?: string;\n\tpath?: string;\n\treason?: string;\n}\n\nfunction getInputTransformations(message: unknown): AnthropicInputTransformation[] | undefined {\n\tconst transformations = (message as { input_transformations?: AnthropicInputTransformation[] })\n\t\t?.input_transformations;\n\treturn Array.isArray(transformations) ? transformations : undefined;\n}\n\n/** Record thinking blocks the API dropped from this request without exposing block contents. */\nfunction recordInputTransformations(output: AssistantMessage, transformations: AnthropicInputTransformation[]): void {\n\tif (transformations.length === 0) return;\n\tappendAssistantMessageDiagnostic(output, {\n\t\ttype: \"anthropic_input_transformations\",\n\t\ttimestamp: Date.now(),\n\t\tdetails: {\n\t\t\tdroppedBlockCount: transformations.length,\n\t\t\treasons: [...new Set(transformations.map((entry) => entry.reason).filter((r): r is string => !!r))],\n\t\t\tpaths: transformations.map((entry) => entry.path).filter((p): p is string => !!p),\n\t\t},\n\t});\n}\n\n/** One entry of the per-attempt `usage.iterations` array a server-side fallback response carries. */\ninterface AnthropicUsageIteration {\n\ttype?: string;\n\tmodel?: string;\n\tinput_tokens?: number;\n\toutput_tokens?: number;\n\tcache_read_input_tokens?: number;\n\t/** The aggregate cache-write count. `cache_creation` splits the same tokens by TTL. */\n\tcache_creation_input_tokens?: number;\n\t/** \"Breakdown of cached tokens by TTL\", per `BetaMessageIterationUsage`. */\n\tcache_creation?: { ephemeral_1h_input_tokens?: number; ephemeral_5m_input_tokens?: number } | null;\n}\n\n/**\n * Bill the attempts that ran *before* the one which produced the returned message.\n *\n * \"Every attempt that produced output, including one that declined partway through its response,\n * is billed separately at the rates of the model that ran it. The `usage.iterations` array is the\n * per-attempt record of what you're billed. The top-level `usage` counts describe only the attempt\n * that produced the returned message. Tokens from different models are never summed into one\n * field.\" https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback\n *\n * Two rules follow, and both matter for not double-counting:\n *\n * - Only `type: \"message\"` entries are added. The `fallback_message` entry *is* the serving\n * attempt, and its tokens are already in the top-level usage that `calculateCost` just priced.\n * - Only entries with output are added: \"An attempt that declined before producing any output is\n * not billed: its tokens are reported on its `usage.iterations` entry but not charged.\"\n *\n * Token counts are deliberately left alone — the docs forbid summing across models and `Usage` has\n * no per-attempt shape — so this contributes to `usage.cost` only.\n */\nfunction addEarlierAttemptCosts(\n\toutput: AssistantMessage,\n\tmodel: Model<\"anthropic-messages\">,\n\tservingModel: Model<\"anthropic-messages\">,\n\tevent: unknown,\n): void {\n\tconst iterations = (event as { usage?: { iterations?: AnthropicUsageIteration[] } })?.usage?.iterations;\n\tif (!Array.isArray(iterations) || iterations.length === 0) return;\n\n\tfor (const iteration of iterations) {\n\t\tif (iteration.type !== \"message\") continue;\n\t\tif (!iteration.output_tokens) continue;\n\n\t\t// Price at the rates of the model that ran the attempt, which is not the serving model.\n\t\tconst attemptCost =\n\t\t\titeration.model === upstreamModelId(model)\n\t\t\t\t? model.cost\n\t\t\t\t: iteration.model === servingModel.id\n\t\t\t\t\t? servingModel.cost\n\t\t\t\t\t: model.compat?.allowedFallbackModels?.find(\n\t\t\t\t\t\t\t(fallback) => fallback.provider === model.provider && fallback.model === iteration.model,\n\t\t\t\t\t\t)?.cost;\n\t\tif (!attemptCost) continue;\n\n\t\tconst attemptUsage: Usage = {\n\t\t\tinput: iteration.input_tokens ?? 0,\n\t\t\toutput: iteration.output_tokens,\n\t\t\tcacheRead: iteration.cache_read_input_tokens ?? 0,\n\t\t\t// `cacheWrite` stays the aggregate: `calculateCost` derives the 5-minute share by\n\t\t\t// subtracting `cacheWrite1h` from it, so setting this to the 5-minute count instead\n\t\t\t// would under-charge and adding the two together would double-charge. Without the 1h\n\t\t\t// split, an hour-long write bills at the 5-minute rate rather than 2x base input.\n\t\t\tcacheWrite: iteration.cache_creation_input_tokens ?? 0,\n\t\t\tcacheWrite1h: iteration.cache_creation?.ephemeral_1h_input_tokens ?? 0,\n\t\t\ttotalTokens: 0,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t};\n\t\tcalculateCost({ ...model, id: iteration.model ?? model.id, cost: attemptCost }, attemptUsage);\n\n\t\toutput.usage.cost.input += attemptUsage.cost.input;\n\t\toutput.usage.cost.output += attemptUsage.cost.output;\n\t\toutput.usage.cost.cacheRead += attemptUsage.cost.cacheRead;\n\t\toutput.usage.cost.cacheWrite += attemptUsage.cost.cacheWrite;\n\t\toutput.usage.cost.total += attemptUsage.cost.total;\n\t\toutput.usage.cost.totalFromProvider = false;\n\t}\n}\n\nfunction getAnthropicCompat(model: Model<\"anthropic-messages\">) {\n\tconst isOpenRouter = model.provider === \"openrouter\" || model.baseUrl.includes(\"openrouter.ai\");\n\treturn {\n\t\tsupportsEagerToolInputStreaming: model.compat?.supportsEagerToolInputStreaming ?? true,\n\t\tsupportsLongCacheRetention: model.compat?.supportsLongCacheRetention ?? true,\n\t\tsendSessionAffinityHeaders: model.compat?.sendSessionAffinityHeaders ?? isOpenRouter,\n\t\tsessionAffinityFormat: model.compat?.sessionAffinityFormat ?? (isOpenRouter ? \"openrouter\" : undefined),\n\t\tsupportsCacheControlOnTools: model.compat?.supportsCacheControlOnTools ?? true,\n\t\tsupportsTemperature: model.compat?.supportsTemperature ?? true,\n\t\tallowEmptySignature: model.compat?.allowEmptySignature ?? false,\n\t\tsupportsStrictTools: model.compat?.supportsStrictTools ?? false,\n\t\tsupportsMidConvoSystemMessages: model.compat?.supportsMidConvoSystemMessages ?? false,\n\t\tsupportsMidConvoToolChanges: model.compat?.supportsMidConvoToolChanges ?? false,\n\t\t// Gateways that drop unknown request fields would silently turn a `continue` into a request\n\t\t// without the earlier conversation, so the default is limited to the `anthropic` provider on\n\t\t// Anthropic's own host. Copilot's endpoint does not accept the threads beta.\n\t\tsupportsMessageThreads:\n\t\t\tmodel.compat?.supportsMessageThreads ??\n\t\t\t(model.provider === \"anthropic\" && isAnthropicApiHost(model.baseUrl)),\n\t};\n}\n\n/** Whether `baseUrl` is Anthropic's own API host, compared by parsed hostname (not a substring). */\nfunction isAnthropicApiHost(baseUrl: string): boolean {\n\ttry {\n\t\treturn new URL(baseUrl).hostname === \"api.anthropic.com\";\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * Message threads (`message-threads-2026-08-12` beta): the server keeps the conversation of a\n * thread, so a request can continue from the previous reply and send only the new messages.\n * Atomic still builds the full request; `prepareThreadRequest()` compares it with the previous\n * request of the session and sends only the new part when nothing earlier changed.\n */\ntype ThreadParam = { type: \"create\" } | { type: \"continue\"; previous_message_id: string };\n\n/** The pinned SDK types do not include the `thread` request field yet. */\ntype ThreadedParams = MessageCreateParamsStreaming & { thread?: ThreadParam };\n\ninterface ThreadEntry {\n\t/** Number of messages in the last full request as sent plus the converted reply. */\n\tprefixCount: number;\n\t/** `hashThreadPrefix()` of the request's settings and those messages. */\n\tprefixHash: string;\n\t/** Id of the reply to continue from. */\n\treplyId: string;\n}\n\n/** Per session: where the next request can continue, or \"off\" after the endpoint rejected threads. */\nconst threadState = new Map<string, ThreadEntry | \"off\">();\nconst MAX_THREAD_STATE_ENTRIES = 10_000;\n\n/** Rejections of a `continue` that a new thread fixes: expired, raced, or a fixed setting changed. */\nconst NEW_THREAD_ERRORS: ReadonlySet<string> = new Set([\n\t\"thread_not_found\",\n\t\"thread_already_continued\",\n\t\"thread_continue_in_flight\",\n\t\"thread_fingerprint_mismatch\",\n]);\n\n/**\n * Sets a session's thread state, keeping at most `MAX_THREAD_STATE_ENTRIES` sessions.\n *\n * State is normally freed by `cleanupSessionResources(sessionId)` when a session ends. The cap\n * bounds memory for library users that never call it, for example a server passing a new\n * `sessionId` per conversation. Dropping the least recently updated session is cheap: its thread\n * has most likely expired on the server already, and otherwise its next request starts a new thread.\n */\nfunction setThreadState(sessionId: string, value: ThreadEntry | \"off\"): void {\n\t// Re-insert so Map order stays oldest-first for the cap.\n\tthreadState.delete(sessionId);\n\tthreadState.set(sessionId, value);\n\tif (threadState.size > MAX_THREAD_STATE_ENTRIES) {\n\t\tconst oldest = threadState.keys().next().value;\n\t\tif (oldest !== undefined) threadState.delete(oldest);\n\t}\n}\n\nregisterSessionResourceCleanup((sessionId) => {\n\tif (sessionId) threadState.delete(sessionId);\n\telse threadState.clear();\n});\n\n/**\n * Hash of everything a `continue` builds on: the settings that must stay the same within a thread\n * and the messages the server already holds.\n *\n * - Settings, as sent: the endpoint (a thread exists on one endpoint only) and the fixed request\n * fields. A `continue` omits `system` and `tools` and the server keeps the thread's own, so only\n * this check can notice a change to them, including their cache markers. The server rejects\n * changes to the other fields with `thread_fingerprint_mismatch`; checking them here saves that\n * rejected request. Atomic also checks the fast-mode `speed`.\n * - Messages, normalized so messages that mean the same to the API hash the same.\n */\nfunction hashThreadPrefix(\n\tmodel: Model<\"anthropic-messages\">,\n\tparams: MessageCreateParamsStreaming,\n\tmessages: readonly unknown[],\n): string {\n\tconst { system, tools, thinking, output_config, tool_choice, betas, fallbacks } = params;\n\tconst settings = JSON.stringify([\n\t\tmodel.provider,\n\t\tmodel.baseUrl,\n\t\tparams.model,\n\t\tsystem,\n\t\ttools,\n\t\tthinking,\n\t\toutput_config,\n\t\ttool_choice,\n\t\tbetas,\n\t\tfallbacks,\n\t\tparams.speed,\n\t]);\n\tconst conversation = JSON.stringify(messages.map(normalizeThreadMessage));\n\treturn shortHash(settings + conversation);\n}\n\n/**\n * Normalizes one message so messages that mean the same to the API compare equal. Only message and\n * content-block fields are touched; tool inputs and every other value compare exactly as sent.\n *\n * - Cache markers don't change what a message means, but they move: Atomic puts one on the newest\n * message, so the message that had it in the last request has none in this one.\n * - To attach that marker, the newest user message's string content is sent as one text block; the\n * next request sends the same message as a string: \"hi\" vs [{ type: \"text\", text: \"hi\" }]. The\n * same holds for a tool result's content.\n */\nfunction normalizeThreadMessage(message: unknown): unknown {\n\tif (message === null || typeof message !== \"object\") return message;\n\tconst { content, ...rest } = message as { content?: unknown };\n\treturn { ...rest, content: normalizeThreadContent(content) };\n}\n\nfunction normalizeThreadContent(content: unknown): unknown {\n\tif (typeof content === \"string\") return [{ type: \"text\", text: content }];\n\tif (!Array.isArray(content)) return content;\n\treturn content.map((block: unknown) => {\n\t\tif (block === null || typeof block !== \"object\") return block;\n\t\tconst { cache_control: _cacheControl, ...rest } = block as { cache_control?: unknown; type?: unknown };\n\t\tif (rest.type !== \"tool_result\") return rest;\n\t\tconst toolResult = rest as { content?: unknown };\n\t\treturn { ...toolResult, content: normalizeThreadContent(toolResult.content) };\n\t});\n}\n\ninterface PreparedThreadRequest {\n\tsessionId: string;\n\tbody: ThreadedParams;\n}\n\nfunction createThreadRequest(sessionId: string, params: MessageCreateParamsStreaming): PreparedThreadRequest {\n\treturn { sessionId, body: { ...params, thread: { type: \"create\" } } };\n}\n\nfunction prepareThreadRequest(\n\tmodel: Model<\"anthropic-messages\">,\n\tsessionId: string,\n\tparams: MessageCreateParamsStreaming,\n): PreparedThreadRequest | undefined {\n\tconst state = threadState.get(sessionId);\n\tif (state === \"off\") return undefined;\n\tif (\n\t\tstate !== undefined &&\n\t\tparams.messages.length > state.prefixCount &&\n\t\thashThreadPrefix(model, params, params.messages.slice(0, state.prefixCount)) === state.prefixHash\n\t) {\n\t\t// Each reply can be continued once; deleting also keeps a concurrent request from trying.\n\t\tthreadState.delete(sessionId);\n\t\tconst { system: _system, tools: _tools, ...rest } = params;\n\t\treturn {\n\t\t\tbody: {\n\t\t\t\t...rest,\n\t\t\t\tmessages: params.messages.slice(state.prefixCount),\n\t\t\t\tthread: { type: \"continue\", previous_message_id: state.replyId },\n\t\t\t},\n\t\t\tsessionId,\n\t\t};\n\t}\n\treturn createThreadRequest(sessionId, params);\n}\n\n/** The `error_code` Anthropic puts in `error.details` of thread rejections. */\nfunction getThreadErrorCode(error: InstanceType<typeof Anthropic.APIError>): string | undefined {\n\tconst body = error.error as { error?: { details?: { error_code?: unknown } } } | undefined;\n\tconst code = body?.error?.details?.error_code;\n\treturn typeof code === \"string\" ? code : undefined;\n}\n\n/**\n * Sends a thread request. A rejection about the thread (never a started stream) is resent once in\n * full: as a new thread when the old one can't be continued, or without `thread` when the endpoint\n * can't use threads, which also turns threads off for the session. Other errors are passed on.\n * Returns the response and the thread request that produced it, if any.\n */\nasync function sendThreadRequest(\n\tthread: PreparedThreadRequest,\n\tparams: MessageCreateParamsStreaming,\n\tsend: (body: ThreadedParams) => Promise<Response>,\n\toutput: AssistantMessage,\n\tsignal: AbortSignal | undefined,\n): Promise<{ response: Response; thread: PreparedThreadRequest | undefined }> {\n\ttry {\n\t\treturn { response: await send(thread.body), thread };\n\t} catch (error) {\n\t\tif (signal?.aborted || !(error instanceof Anthropic.APIError)) throw error;\n\t\tconst errorCode = getThreadErrorCode(error);\n\t\tconst startNewThread = errorCode !== undefined && NEW_THREAD_ERRORS.has(errorCode);\n\t\t// The endpoint can't use threads: it can't thread this request, or it doesn't know the\n\t\t// `thread` field and rejects it without a code (\"thread: Extra inputs are not permitted\"),\n\t\t// e.g. with an `anthropic-beta` header that lacks the threads beta.\n\t\tconst threadsUnsupported =\n\t\t\terrorCode === \"thread_unsupported_request\" ||\n\t\t\t(errorCode === undefined && error.status === 400 && error.message.includes(\"thread\"));\n\t\t// Any other error (prompt too long, unknown model, strict tool limits, ...) is not about the\n\t\t// thread, and resending would only fail again.\n\t\tif (!startNewThread && !threadsUnsupported) throw error;\n\t\t// Recorded before the resend, so a failed resend keeps it.\n\t\tappendAssistantMessageDiagnostic(output, {\n\t\t\ttype: \"anthropic_thread_fallback\",\n\t\t\ttimestamp: Date.now(),\n\t\t\terror: { message: error.message },\n\t\t\tdetails: { reason: errorCode ?? String(error.status) },\n\t\t});\n\t\tif (startNewThread) {\n\t\t\tconst created = createThreadRequest(thread.sessionId, params);\n\t\t\treturn { response: await send(created.body), thread: created };\n\t\t}\n\t\t// With the threads beta, a request without `thread` is a normal request.\n\t\tconst response = await send(params);\n\t\tsetThreadState(thread.sessionId, \"off\");\n\t\treturn { response, thread: undefined };\n\t}\n}\n\n/**\n * Records where the session's next request can continue: after `output`, the clean reply to the\n * thread request `thread`, whose full request was `params`.\n */\nfunction recordThreadReply(\n\tmodel: Model<\"anthropic-messages\">,\n\tthread: PreparedThreadRequest,\n\tparams: MessageCreateParamsStreaming,\n\toutput: AssistantMessage,\n\tisOAuth: boolean,\n\tallowEmptySignature: boolean,\n): void {\n\t// `responseModel` is set only when another model answered (server-side fallback); the server\n\t// does not store those replies, so they cannot be continued.\n\tif (output.responseId === undefined || output.responseModel !== undefined) return;\n\t// Convert the reply like the next request will, keeping only the assistant message\n\t// (transformMessages adds placeholder results for trailing tool calls).\n\tconst reply = convertMessages(\n\t\ttransformMessages([output], model, normalizeToolCallId),\n\t\tisOAuth,\n\t\tundefined,\n\t\tallowEmptySignature,\n\t).messages.filter((message) => message.role === \"assistant\");\n\tconst prefix = [...params.messages, ...reply];\n\tsetThreadState(thread.sessionId, {\n\t\tprefixCount: prefix.length,\n\t\tprefixHash: hashThreadPrefix(model, params, prefix),\n\t\treplyId: output.responseId,\n\t});\n}\n\nexport interface AnthropicOptions extends StreamOptions {\n\t/**\n\t * Enable extended thinking.\n\t * For adaptive thinking models: the model decides when/how much to think.\n\t * For older models: uses budget-based thinking with thinkingBudgetTokens.\n\t * Default: undefined (thinking is omitted unless `streamSimple()` maps\n\t * a simple reasoning level to this option, or callers set it explicitly).\n\t */\n\tthinkingEnabled?: boolean;\n\t/**\n\t * Token budget for extended thinking (older models only).\n\t * Ignored for adaptive thinking models.\n\t * Default: 1024 when `thinkingEnabled` is true and no budget is provided.\n\t */\n\tthinkingBudgetTokens?: number;\n\t/**\n\t * Effort level for adaptive thinking models.\n\t * Controls how much thinking Claude allocates:\n\t * - \"max\": Always thinks with no constraints (Opus 4.6 only)\n\t * - \"xhigh\": Highest reasoning level (Opus 4.7+, Fable 5)\n\t * - \"high\": Always thinks, deep reasoning\n\t * - \"medium\": Moderate thinking, may skip for simple queries\n\t * - \"low\": Minimal thinking, skips for simple tasks\n\t * Ignored for older models.\n\t * Default: omitted unless `streamSimple()` maps a simple reasoning\n\t * level to this option.\n\t */\n\teffort?: AnthropicEffort;\n\t/**\n\t * Controls how thinking content is returned in API responses.\n\t * - \"summarized\": Thinking blocks contain summarized thinking text.\n\t * - \"omitted\": Thinking blocks return an empty thinking field; the encrypted\n\t * signature still travels back for multi-turn continuity. Use for faster\n\t * time-to-first-text-token when your UI does not surface thinking.\n\t *\n\t * Note: Anthropic's API default for Claude Opus 4.7 and Claude Mythos Preview\n\t * is \"omitted\". We default to \"summarized\" here to keep behavior consistent\n\t * with older Claude 4 models. Set this explicitly to \"omitted\" to opt in.\n\t * Default: \"summarized\" when thinking is enabled.\n\t */\n\tthinkingDisplay?: AnthropicThinkingDisplay;\n\t/**\n\t * Whether to request the interleaved thinking beta header for non-adaptive\n\t * thinking models. Adaptive thinking models have interleaved thinking built in,\n\t * so the header is skipped for them regardless of this setting.\n\t * Default: true.\n\t */\n\tinterleavedThinking?: boolean;\n\t/**\n\t * Anthropic tool choice behavior. String values map to Anthropic's built-in\n\t * choices; `{ type: \"tool\", name }` forces a specific tool.\n\t * Default: omitted (Anthropic default behavior, currently equivalent to auto).\n\t */\n\ttoolChoice?: \"auto\" | \"any\" | \"none\" | { type: \"tool\"; name: string };\n\t/**\n\t * Pre-built Anthropic client instance. When provided, skips internal client\n\t * construction entirely. Use this to inject alternative SDK clients such as\n\t * `AnthropicVertex` that shares the same messaging API.\n\t */\n\tclient?: Anthropic;\n}\n\nfunction mergeHeaders(...headerSources: (ProviderHeaders | undefined)[]): ProviderHeaders {\n\tconst merged: ProviderHeaders = {};\n\tfor (const headers of headerSources) {\n\t\tif (headers) {\n\t\t\tObject.assign(merged, headers);\n\t\t}\n\t}\n\treturn merged;\n}\n\nfunction hasHeader(headers: ProviderHeaders | undefined, name: string): boolean {\n\tif (!headers) return false;\n\tconst expected = name.toLowerCase();\n\tfor (const [key, value] of Object.entries(headers)) {\n\t\tif (key.toLowerCase() === expected && value !== null && value.trim().length > 0) return true;\n\t}\n\treturn false;\n}\n\nfunction hasRequestAuth(apiKey: string | undefined, headers: ProviderHeaders | undefined): boolean {\n\treturn (\n\t\t!!apiKey ||\n\t\thasHeader(headers, \"authorization\") ||\n\t\thasHeader(headers, \"x-api-key\") ||\n\t\thasHeader(headers, \"cf-aig-authorization\")\n\t);\n}\n\nfunction assertRequestAuth(provider: string, apiKey: string | undefined, headers: ProviderHeaders | undefined): void {\n\tif (!hasRequestAuth(apiKey, headers)) throw new Error(`No API key for provider: ${provider}`);\n}\n\n/**\n * Anthropic SDK client that never runs the SDK's own credential chain\n * (ANTHROPIC_PROFILE config files, federation env vars). Without this, every\n * client built with `apiKey: null, authToken: null` for header-owned auth would\n * also resolve and exchange SDK credentials behind Atomic's auth resolver.\n */\nclass AtomicAnthropic extends Anthropic {\n\tprivate readonly admission: ReturnType<typeof getFetchAdmission>;\n\n\tconstructor(options: ClientOptions) {\n\t\tconst admission = getFetchAdmission(options.fetch);\n\t\tconst tokenAdmission: Middleware = async (request, next, context) => {\n\t\t\tif (!context.options) await admission?.beforeRequest(request.signal ?? undefined);\n\t\t\treturn next(request);\n\t\t};\n\t\tsuper({\n\t\t\t...options,\n\t\t\tfetch: admission?.fetch ?? options.fetch,\n\t\t\tmiddleware: admission ? [tokenAdmission, ...(options.middleware ?? [])] : options.middleware,\n\t\t});\n\t\tthis.admission = admission;\n\t}\n\n\tprotected override authHeaders(...args: Parameters<Anthropic[\"authHeaders\"]>): ReturnType<Anthropic[\"authHeaders\"]> {\n\t\tconst result = super.authHeaders(...args);\n\t\tconst signal = args[0].signal;\n\t\treturn signal ? raceWithAbortSignal(result, signal) : result;\n\t}\n\n\tprotected override async prepareRequest(...args: Parameters<Anthropic[\"prepareRequest\"]>): Promise<void> {\n\t\tawait super.prepareRequest(...args);\n\t\tawait this.admission?.beforeRequest(args[0].signal ?? undefined);\n\t}\n\tprotected override _shouldResolveDefaultCredentials(): boolean {\n\t\treturn false;\n\t}\n}\n\ntype AnthropicFederationConfig = NonNullable<ClientOptions[\"config\"]>;\n\n/**\n * Workload identity federation config from the ANTHROPIC_* variables the\n * Anthropic SDK documents; the SDK performs the token exchange and refresh.\n * Only for the anthropic provider, since the exchange is an Anthropic API\n * endpoint, and only when no key or auth header was resolved.\n */\nfunction getAnthropicFederation(\n\tmodel: Model<\"anthropic-messages\">,\n\tapiKey: string | undefined,\n\theaders: ProviderHeaders | undefined,\n\tenv: ProviderEnv | undefined,\n): AnthropicFederationConfig | undefined {\n\tif (model.provider !== \"anthropic\" || hasRequestAuth(apiKey, headers)) return undefined;\n\tconst federationRuleId = getProviderEnvValue(ANTHROPIC_FEDERATION_RULE_ID_ENV, env);\n\tconst organizationId = getProviderEnvValue(ANTHROPIC_ORGANIZATION_ID_ENV, env);\n\tconst identityTokenFile = getProviderEnvValue(ANTHROPIC_IDENTITY_TOKEN_FILE_ENV, env);\n\tif (!federationRuleId || !organizationId || !identityTokenFile) return undefined;\n\treturn {\n\t\torganization_id: organizationId,\n\t\tworkspace_id: getProviderEnvValue(ANTHROPIC_WORKSPACE_ID_ENV, env),\n\t\tauthentication: {\n\t\t\ttype: \"oidc_federation\",\n\t\t\tfederation_rule_id: federationRuleId,\n\t\t\tservice_account_id: getProviderEnvValue(ANTHROPIC_SERVICE_ACCOUNT_ID_ENV, env),\n\t\t\tidentity_token: { source: \"file\", path: identityTokenFile },\n\t\t},\n\t};\n}\n\n/**\n * The SDK caches the federated access token per client, but a client is created\n * per request. Keep one client for the current federation config and fetch, and\n * clone it per request with `withOptions()`, which shares the token cache.\n */\nlet federationClient: { key: string; fetch: typeof globalThis.fetch | undefined; client: Anthropic } | undefined;\n\ninterface ServerSentEvent {\n\tevent: string | null;\n\tdata: string;\n\traw: string[];\n}\n\ninterface SseDecoderState {\n\tevent: string | null;\n\tdata: string[];\n\traw: string[];\n}\n\nconst ANTHROPIC_MESSAGE_EVENTS: ReadonlySet<string> = new Set([\n\t\"message_start\",\n\t\"message_delta\",\n\t\"message_stop\",\n\t\"content_block_start\",\n\t\"content_block_delta\",\n\t\"content_block_stop\",\n]);\n\nfunction flushSseEvent(state: SseDecoderState): ServerSentEvent | null {\n\tif (!state.event && state.data.length === 0) {\n\t\treturn null;\n\t}\n\n\tconst event: ServerSentEvent = {\n\t\tevent: state.event,\n\t\tdata: state.data.join(\"\\n\"),\n\t\traw: [...state.raw],\n\t};\n\tstate.event = null;\n\tstate.data = [];\n\tstate.raw = [];\n\treturn event;\n}\n\nfunction decodeSseLine(line: string, state: SseDecoderState): ServerSentEvent | null {\n\tif (line === \"\") {\n\t\treturn flushSseEvent(state);\n\t}\n\n\tstate.raw.push(line);\n\tif (line.startsWith(\":\")) {\n\t\treturn null;\n\t}\n\n\tconst delimiterIndex = line.indexOf(\":\");\n\tconst fieldName = delimiterIndex === -1 ? line : line.slice(0, delimiterIndex);\n\tlet value = delimiterIndex === -1 ? \"\" : line.slice(delimiterIndex + 1);\n\tif (value.startsWith(\" \")) {\n\t\tvalue = value.slice(1);\n\t}\n\n\tif (fieldName === \"event\") {\n\t\tstate.event = value;\n\t} else if (fieldName === \"data\") {\n\t\tstate.data.push(value);\n\t}\n\n\treturn null;\n}\n\nfunction nextLineBreakIndex(text: string): number {\n\tconst carriageReturnIndex = text.indexOf(\"\\r\");\n\tconst newlineIndex = text.indexOf(\"\\n\");\n\tif (carriageReturnIndex === -1) {\n\t\treturn newlineIndex;\n\t}\n\tif (newlineIndex === -1) {\n\t\treturn carriageReturnIndex;\n\t}\n\treturn Math.min(carriageReturnIndex, newlineIndex);\n}\n\nfunction consumeLine(text: string): { line: string; rest: string } | null {\n\tconst lineBreakIndex = nextLineBreakIndex(text);\n\tif (lineBreakIndex === -1) {\n\t\treturn null;\n\t}\n\n\tlet nextIndex = lineBreakIndex + 1;\n\tif (text[lineBreakIndex] === \"\\r\" && text[nextIndex] === \"\\n\") {\n\t\tnextIndex += 1;\n\t}\n\n\treturn {\n\t\tline: text.slice(0, lineBreakIndex),\n\t\trest: text.slice(nextIndex),\n\t};\n}\n\nasync function* iterateSseMessages(\n\tbody: ReadableStream<Uint8Array>,\n\tsignal?: AbortSignal,\n): AsyncGenerator<ServerSentEvent> {\n\tconst reader = body.getReader();\n\tconst decoder = new TextDecoder();\n\tconst state: SseDecoderState = { event: null, data: [], raw: [] };\n\tlet buffer = \"\";\n\tconst onAbort = () => {\n\t\tvoid reader.cancel().catch(() => {});\n\t};\n\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\n\ttry {\n\t\twhile (true) {\n\t\t\tif (signal?.aborted) {\n\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t}\n\n\t\t\tconst { value, done } = await reader.read();\n\t\t\tif (done) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tbuffer += decoder.decode(value, { stream: true });\n\t\t\tlet consumed = consumeLine(buffer);\n\t\t\twhile (consumed) {\n\t\t\t\tbuffer = consumed.rest;\n\t\t\t\tconst event = decodeSseLine(consumed.line, state);\n\t\t\t\tif (event) {\n\t\t\t\t\tyield event;\n\t\t\t\t}\n\t\t\t\tconsumed = consumeLine(buffer);\n\t\t\t}\n\t\t}\n\n\t\tbuffer += decoder.decode();\n\t\tlet consumed = consumeLine(buffer);\n\t\twhile (consumed) {\n\t\t\tbuffer = consumed.rest;\n\t\t\tconst event = decodeSseLine(consumed.line, state);\n\t\t\tif (event) {\n\t\t\t\tyield event;\n\t\t\t}\n\t\t\tconsumed = consumeLine(buffer);\n\t\t}\n\n\t\tif (buffer.length > 0) {\n\t\t\tconst event = decodeSseLine(buffer, state);\n\t\t\tif (event) {\n\t\t\t\tyield event;\n\t\t\t}\n\t\t}\n\n\t\tconst trailingEvent = flushSseEvent(state);\n\t\tif (trailingEvent) {\n\t\t\tyield trailingEvent;\n\t\t}\n\t} finally {\n\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\ttry {\n\t\t\tawait reader.cancel();\n\t\t} catch {}\n\t\treader.releaseLock();\n\t}\n}\n\nfunction parseStreamedErrorBody(data: string): NonNullable<unknown> {\n\ttry {\n\t\treturn JSON.parse(data) ?? data;\n\t} catch {\n\t\treturn data;\n\t}\n}\n\nfunction streamedErrorType(body: NonNullable<unknown>): ErrorType | undefined {\n\tconst error = (body as { error?: unknown }).error;\n\tconst type = typeof error === \"object\" && error !== null ? (error as { type?: unknown }).type : undefined;\n\treturn typeof type === \"string\" ? (type as ErrorType) : undefined;\n}\n\nasync function* iterateAnthropicEvents(\n\tresponse: Response,\n\tsignal?: AbortSignal,\n): AsyncGenerator<RawMessageStreamEvent> {\n\tif (!response.body) {\n\t\tthrow new Error(\"Attempted to iterate over an Anthropic response with no body\");\n\t}\n\n\tlet sawMessageStart = false;\n\tlet sawMessageEnd = false;\n\n\tfor await (const sse of iterateSseMessages(response.body, signal)) {\n\t\tif (sse.event === \"error\") {\n\t\t\tconst body = parseStreamedErrorBody(sse.data);\n\t\t\tthrow new Anthropic.APIError(undefined, body, sse.data, response.headers, streamedErrorType(body));\n\t\t}\n\n\t\tif (!ANTHROPIC_MESSAGE_EVENTS.has(sse.event ?? \"\")) {\n\t\t\tcontinue;\n\t\t}\n\n\t\ttry {\n\t\t\tconst event = parseJsonWithRepair<RawMessageStreamEvent>(sse.data);\n\t\t\tif (event.type === \"message_start\") {\n\t\t\t\tsawMessageStart = true;\n\t\t\t} else if (event.type === \"message_stop\") {\n\t\t\t\tsawMessageEnd = true;\n\t\t\t}\n\t\t\tyield event;\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tthrow new Error(\n\t\t\t\t`Could not parse Anthropic SSE event ${sse.event}: ${message}; data=${sse.data}; raw=${sse.raw.join(\"\\\\n\")}`,\n\t\t\t);\n\t\t}\n\t}\n\n\tif (sawMessageStart && !sawMessageEnd) {\n\t\tthrow new Error(\"Anthropic stream ended before message_stop\");\n\t}\n}\n\nexport const stream: StreamFunction<\"anthropic-messages\", AnthropicOptions> = (\n\tmodel: Model<\"anthropic-messages\">,\n\tcontext: TranscriptContext,\n\toptions?: AnthropicOptions,\n): AssistantMessageEventStream => {\n\tconst stream = new AssistantMessageEventStream();\n\tconst compat = getAnthropicCompat(model);\n\tconst normalizedContext = resolveTranscript(context, compat.supportsMidConvoSystemMessages);\n\tconst currentTools = getCurrentTools(normalizedContext.messages);\n\n\t(async () => {\n\t\tconst output: AssistantMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [],\n\t\t\tapi: model.api as Api,\n\t\t\tprovider: model.provider,\n\t\t\tmodel: model.id,\n\t\t\tusage: {\n\t\t\t\tinput: 0,\n\t\t\t\toutput: 0,\n\t\t\t\tcacheRead: 0,\n\t\t\t\tcacheWrite: 0,\n\t\t\t\ttotalTokens: 0,\n\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t},\n\t\t\tstopReason: \"pending\",\n\t\t\ttimestamp: Date.now(),\n\t\t};\n\n\t\tconst streamDeadline = createStreamDeadline(options?.streamDeadlineMs, options?.signal);\n\t\tlet streamStarted = false;\n\n\t\tlet inputTransformations: AnthropicInputTransformation[] | undefined;\n\n\t\ttry {\n\t\t\tconst thinkingOffFallback = getAnthropicThinkingOffFallback(model, options);\n\t\t\tif (thinkingOffFallback) {\n\t\t\t\tappendThinkingOffFallbackDiagnostic(output, thinkingOffFallback.level, thinkingOffFallback.effort);\n\t\t\t}\n\t\t\tlet client: Anthropic;\n\t\t\tlet isOAuth: boolean;\n\t\t\tlet usageModel = model;\n\t\t\tlet servedSpeed = requestedSpeed(model);\n\t\t\tconst cacheRetention = resolveCacheRetention(options?.cacheRetention, options?.env);\n\t\t\tconst cacheSessionId = cacheRetention === \"none\" ? undefined : options?.sessionId;\n\t\t\t// Session whose requests may use message threads; undefined when threads don't apply. A\n\t\t\t// caller-supplied client carries its own `anthropic-beta` header, which Atomic cannot extend\n\t\t\t// with the threads beta, so it never uses threads. Sessions where the endpoint rejected threads\n\t\t\t// (\"off\") still send the threads beta, which the resend that turned them off was accepted\n\t\t\t// with; `prepareThreadRequest()` just sends no `thread`.\n\t\t\tconst threadSessionId = compat.supportsMessageThreads && !options?.client ? cacheSessionId : undefined;\n\n\t\t\tif (options?.client) {\n\t\t\t\tclient = options.client;\n\t\t\t\tisOAuth = false;\n\t\t\t} else {\n\t\t\t\tconst apiKey = options?.apiKey;\n\t\t\t\tconst federation = getAnthropicFederation(model, apiKey, options?.headers, options?.env);\n\t\t\t\tif (!federation) assertRequestAuth(model.provider, apiKey, options?.headers);\n\n\t\t\t\tlet copilotDynamicHeaders: Record<string, string> | undefined;\n\t\t\t\tif (model.provider === \"github-copilot\") {\n\t\t\t\t\tconst hasImages = hasCopilotVisionInput(normalizedContext.messages);\n\t\t\t\t\tcopilotDynamicHeaders = preserveCopilotIntegrationHeader(\n\t\t\t\t\t\tmodel.headers,\n\t\t\t\t\t\tbuildCopilotDynamicHeaders({\n\t\t\t\t\t\t\tmessages: normalizedContext.messages,\n\t\t\t\t\t\t\thasImages,\n\t\t\t\t\t\t\tapiKey,\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t}\n\n\n\t\t\t\tconst created = createClient(\n\t\t\t\t\tmodel,\n\t\t\t\t\tapiKey,\n\t\t\t\t\tmodel.reasoning && options?.thinkingEnabled === true && (options.interleavedThinking ?? true),\n\t\t\t\t\tshouldUseFineGrainedToolStreamingBeta(model, context),\n\t\t\t\t\tshouldUseServerSideFallbackBeta(model),\n\t\t\t\t\toptions?.headers,\n\t\t\t\t\toptions?.fetch,\n\t\t\t\t\tcopilotDynamicHeaders,\n\t\t\t\t\tcacheSessionId,\n\t\t\t\t\tcompat.supportsMidConvoToolChanges &&\n\t\t\t\t\t\tcompat.supportsMidConvoSystemMessages &&\n\t\t\t\t\t\t(getInitialSystemMessage(normalizedContext.messages)?.toolsAdded?.length ?? 0) > 0,\n\t\t\t\t\tfederation,\n\t\t\t\t\toptions?.identity,\n\t\t\t\t\tthreadSessionId !== undefined,\n\t\t\t\t);\n\t\t\t\tclient = created.client;\n\t\t\t\tisOAuth = created.isOAuthToken;\n\t\t\t}\n\t\t\tconst requestOptions = {\n\t\t\t\t...(streamDeadline.signal ? { signal: streamDeadline.signal } : {}),\n\t\t\t\t...(options?.timeoutMs !== undefined ? { timeout: options.timeoutMs } : {}),\n\t\t\t\tmaxRetries: 0,\n\t\t\t};\n\t\t\tconst send = (body: ThreadedParams) =>\n\t\t\t\tretryProviderRequest(\n\t\t\t\t\t() => client.beta.messages.create({ ...body, stream: true }, requestOptions).asResponse(),\n\t\t\t\t\t{\n\t\t\t\t\t\tmaxRetries: options?.maxRetries,\n\t\t\t\t\t\tmaxRetryDelayMs: options?.maxRetryDelayMs,\n\t\t\t\t\t\tsignal: streamDeadline.signal,\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\tlet disablePreferredStrictTools = false;\n\t\t\tlet response: Response;\n\t\t\tlet params: MessageCreateParamsStreaming;\n\t\t\t// The thread request that produced the response; undefined when no `thread` was sent.\n\t\t\tlet thread: PreparedThreadRequest | undefined;\n\t\t\tfor (;;) {\n\t\t\t\tstreamDeadline.signal?.throwIfAborted();\n\t\t\t\tconst built = buildParams(model, normalizedContext, isOAuth, options, {\n\t\t\t\t\tdisablePreferredStrictTools,\n\t\t\t\t\tmessageThreads: threadSessionId !== undefined,\n\t\t\t\t});\n\t\t\t\tif (built.providerThinkingLevel) output.providerThinkingLevel = built.providerThinkingLevel;\n\t\t\t\tparams = built.params;\n\t\t\t\tconst nextParams = await options?.onPayload?.(params, model);\n\t\t\t\tif (nextParams !== undefined) params = nextParams as MessageCreateParamsStreaming;\n\t\t\t\tassertPayloadPreservesFastRoute(model, params);\n\t\t\t\tconst prepared =\n\t\t\t\t\tthreadSessionId !== undefined && options?.disableContinuation !== true\n\t\t\t\t\t\t? prepareThreadRequest(model, threadSessionId, params)\n\t\t\t\t\t\t: undefined;\n\t\t\t\ttry {\n\t\t\t\t\tconst sent = prepared\n\t\t\t\t\t\t? await sendThreadRequest(prepared, params, send, output, streamDeadline.signal)\n\t\t\t\t\t\t: { response: await send(params), thread: undefined };\n\t\t\t\t\tresponse = sent.response;\n\t\t\t\t\tthread = sent.thread;\n\t\t\t\t\tbreak;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (\n\t\t\t\t\t\tstreamDeadline.signal?.aborted ||\n\t\t\t\t\t\tdisablePreferredStrictTools ||\n\t\t\t\t\t\t!built.hasPreferredStrictTools ||\n\t\t\t\t\t\t!(error instanceof Anthropic.APIError) ||\n\t\t\t\t\t\terror.status !== 400 ||\n\t\t\t\t\t\terror.type !== \"invalid_request_error\" ||\n\t\t\t\t\t\t!isStrictToolLimitErrorMessage(error.message)\n\t\t\t\t\t)\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\tdisablePreferredStrictTools = true;\n\t\t\t\t\tappendAssistantMessageDiagnostic(output, {\n\t\t\t\t\t\ttype: \"anthropic_strict_tools_fallback\",\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\terror: { message: error.message },\n\t\t\t\t\t\tdetails: { reason: \"strict_tool_limits_exceeded\" },\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\tawait options?.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model);\n\t\t\tstream.push({ type: \"start\", partial: output });\n\t\t\tstreamStarted = true;\n\n\t\t\t// Stream state per Anthropic block index, kept off the content blocks so it never reaches partials.\n\t\t\tconst openBlocks = new Map<number, { contentIndex: number; arguments?: ToolCallArgumentsStream }>();\n\t\t\tconst openBlock = (anthropicIndex: number) => {\n\t\t\t\tconst open = openBlocks.get(anthropicIndex);\n\t\t\t\treturn open === undefined ? undefined : { ...open, block: output.content[open.contentIndex]! };\n\t\t\t};\n\n\t\t\tfor await (const event of withStreamDeadline(\n\t\t\t\titerateAnthropicEvents(response, streamDeadline.signal),\n\t\t\t\tstreamDeadline.deadlineMs,\n\t\t\t\tstreamDeadline.abort,\n\t\t\t)) {\n\t\t\t\tawait options?.onProviderStreamEvent?.(event, model);\n\t\t\t\tif (event.type === \"message_start\") {\n\t\t\t\t\toutput.responseId = event.message.id;\n\t\t\t\t\tconst responseModel = event.message.model;\n\t\t\t\t\tif (responseModel !== upstreamModelId(model)) output.responseModel = responseModel;\n\t\t\t\t\tconst fallbackCost =\n\t\t\t\t\t\tresponseModel === upstreamModelId(model)\n\t\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t\t: model.compat?.allowedFallbackModels?.find(\n\t\t\t\t\t\t\t\t\t(fallback) => fallback.provider === model.provider && fallback.model === responseModel,\n\t\t\t\t\t\t\t\t)?.cost;\n\t\t\t\t\tusageModel = fallbackCost ? { ...model, id: responseModel, cost: fallbackCost } : model;\n\t\t\t\t\t// Capture initial token usage from message_start event\n\t\t\t\t\t// This ensures we have input token counts even if the stream is aborted early\n\t\t\t\t\toutput.usage.input = event.message.usage.input_tokens || 0;\n\t\t\t\t\toutput.usage.output = event.message.usage.output_tokens || 0;\n\t\t\t\t\toutput.usage.cacheRead = event.message.usage.cache_read_input_tokens || 0;\n\t\t\t\t\toutput.usage.cacheWrite = event.message.usage.cache_creation_input_tokens || 0;\n\t\t\t\t\toutput.usage.cacheWrite1h = event.message.usage.cache_creation?.ephemeral_1h_input_tokens || 0;\n\t\t\t\t\t// Anthropic doesn't provide total_tokens, compute from components\n\t\t\t\t\toutput.usage.totalTokens =\n\t\t\t\t\t\toutput.usage.input + output.usage.output + output.usage.cacheRead + output.usage.cacheWrite;\n\t\t\t\t\tcalculateCost(usageModel, output.usage);\n\t\t\t\t\tservedSpeed = reportedSpeed(event.message.usage) ?? servedSpeed;\n\t\t\t\t\tif (servedSpeed === \"fast\") applyFastModePricing(output.usage);\n\t\t\t\t\tinputTransformations = getInputTransformations(event.message) ?? inputTransformations;\n\t\t\t\t} else if (event.type === \"content_block_start\") {\n\t\t\t\t\tif (event.content_block.type === \"text\") {\n\t\t\t\t\t\toutput.content.push({ type: \"text\", text: event.content_block.text ?? \"\" });\n\t\t\t\t\t\topenBlocks.set(event.index, { contentIndex: output.content.length - 1 });\n\t\t\t\t\t\tstream.push({ type: \"text_start\", contentIndex: output.content.length - 1, partial: output });\n\t\t\t\t\t} else if (event.content_block.type === \"thinking\") {\n\t\t\t\t\t\toutput.content.push({\n\t\t\t\t\t\t\ttype: \"thinking\",\n\t\t\t\t\t\t\tthinking: event.content_block.thinking ?? \"\",\n\t\t\t\t\t\t\tthinkingSignature: event.content_block.signature ?? \"\",\n\t\t\t\t\t\t});\n\t\t\t\t\t\topenBlocks.set(event.index, { contentIndex: output.content.length - 1 });\n\t\t\t\t\t\tstream.push({ type: \"thinking_start\", contentIndex: output.content.length - 1, partial: output });\n\t\t\t\t\t} else if (event.content_block.type === \"redacted_thinking\") {\n\t\t\t\t\t\toutput.content.push({\n\t\t\t\t\t\t\ttype: \"thinking\",\n\t\t\t\t\t\t\tthinking: \"[Reasoning redacted]\",\n\t\t\t\t\t\t\tthinkingSignature: event.content_block.data,\n\t\t\t\t\t\t\tredacted: true,\n\t\t\t\t\t\t});\n\t\t\t\t\t\topenBlocks.set(event.index, { contentIndex: output.content.length - 1 });\n\t\t\t\t\t\tstream.push({ type: \"thinking_start\", contentIndex: output.content.length - 1, partial: output });\n\t\t\t\t\t} else if (event.content_block.type === \"tool_use\") {\n\t\t\t\t\t\toutput.content.push({\n\t\t\t\t\t\t\ttype: \"toolCall\",\n\t\t\t\t\t\t\tid: event.content_block.id,\n\t\t\t\t\t\t\tname: isOAuth\n\t\t\t\t\t\t\t\t? fromClaudeCodeName(event.content_block.name, currentTools)\n\t\t\t\t\t\t\t\t: event.content_block.name,\n\t\t\t\t\t\t\targuments: (event.content_block.input as Record<string, any>) ?? {},\n\t\t\t\t\t\t});\n\t\t\t\t\t\topenBlocks.set(event.index, {\n\t\t\t\t\t\t\tcontentIndex: output.content.length - 1,\n\t\t\t\t\t\t\targuments: new ToolCallArgumentsStream(),\n\t\t\t\t\t\t});\n\t\t\t\t\t\tstream.push({ type: \"toolcall_start\", contentIndex: output.content.length - 1, partial: output });\n\t\t\t\t\t} else if ((event.content_block as { type?: string }).type === \"fallback\") {\n\t\t\t\t\t\t// Server-side fallback boundary: \"the `fallback` block (an ordinary\n\t\t\t\t\t\t// `content_block_start` and `content_block_stop` pair with no deltas) marks the\n\t\t\t\t\t\t// boundary\", and clients must \"Keep it exactly where it appeared. The API uses\n\t\t\t\t\t\t// its position to validate the thinking blocks around it\".\n\t\t\t\t\t\t// https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback\n\t\t\t\t\t\t//\n\t\t\t\t\t\t// The SDK types lag this block, so read it through a narrow cast.\n\t\t\t\t\t\tconst fallbackBlock = event.content_block as unknown as {\n\t\t\t\t\t\t\tfrom?: { model?: string };\n\t\t\t\t\t\t\tto?: { model?: string };\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst toModel = fallbackBlock.to?.model;\n\t\t\t\t\t\toutput.content.push({\n\t\t\t\t\t\t\ttype: \"fallback\",\n\t\t\t\t\t\t\tfromModel: fallbackBlock.from?.model ?? output.model,\n\t\t\t\t\t\t\ttoModel: toModel ?? output.model,\n\t\t\t\t\t\t});\n\t\t\t\t\t\t// `message_start` named the requested model, so on a mid-output fallback the\n\t\t\t\t\t\t// serving model is only knowable here. Re-derive pricing the same way the\n\t\t\t\t\t\t// `message_start` branch does, so the returned message is costed at the rates\n\t\t\t\t\t\t// of the model that actually produced it.\n\t\t\t\t\t\tif (toModel && toModel !== output.model) {\n\t\t\t\t\t\t\toutput.model = toModel;\n\t\t\t\t\t\t\tconst fallbackCost = model.compat?.allowedFallbackModels?.find(\n\t\t\t\t\t\t\t\t(fallback) => fallback.provider === model.provider && fallback.model === toModel,\n\t\t\t\t\t\t\t)?.cost;\n\t\t\t\t\t\t\tusageModel = fallbackCost ? { ...model, id: toModel, cost: fallbackCost } : model;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else if (event.type === \"content_block_delta\") {\n\t\t\t\t\tconst open = openBlock(event.index);\n\t\t\t\t\tif (event.delta.type === \"text_delta\") {\n\t\t\t\t\t\tif (open?.block.type === \"text\") {\n\t\t\t\t\t\t\topen.block.text += event.delta.text;\n\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\ttype: \"text_delta\",\n\t\t\t\t\t\t\t\tcontentIndex: open.contentIndex,\n\t\t\t\t\t\t\t\tdelta: event.delta.text,\n\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (event.delta.type === \"thinking_delta\") {\n\t\t\t\t\t\tif (open?.block.type === \"thinking\") {\n\t\t\t\t\t\t\topen.block.thinking += event.delta.thinking;\n\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\t\t\t\t\tcontentIndex: open.contentIndex,\n\t\t\t\t\t\t\t\tdelta: event.delta.thinking,\n\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (event.delta.type === \"input_json_delta\") {\n\t\t\t\t\t\tif (open?.block.type === \"toolCall\" && open.arguments !== undefined) {\n\t\t\t\t\t\t\topen.block.arguments = open.arguments.append(event.delta.partial_json);\n\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\ttype: \"toolcall_delta\",\n\t\t\t\t\t\t\t\tcontentIndex: open.contentIndex,\n\t\t\t\t\t\t\t\tdelta: event.delta.partial_json,\n\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (event.delta.type === \"signature_delta\") {\n\t\t\t\t\t\tif (open?.block.type === \"thinking\") {\n\t\t\t\t\t\t\topen.block.thinkingSignature = open.block.thinkingSignature || \"\";\n\t\t\t\t\t\t\topen.block.thinkingSignature += event.delta.signature;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else if (event.type === \"content_block_stop\") {\n\t\t\t\t\tconst open = openBlock(event.index);\n\t\t\t\t\topenBlocks.delete(event.index);\n\t\t\t\t\tif (open) {\n\t\t\t\t\t\tconst { block, contentIndex: index } = open;\n\t\t\t\t\t\tif (block.type === \"text\") {\n\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\ttype: \"text_end\",\n\t\t\t\t\t\t\t\tcontentIndex: index,\n\t\t\t\t\t\t\t\tcontent: block.text,\n\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} else if (block.type === \"thinking\") {\n\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\ttype: \"thinking_end\",\n\t\t\t\t\t\t\t\tcontentIndex: index,\n\t\t\t\t\t\t\t\tcontent: block.thinking,\n\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} else if (block.type === \"toolCall\" && open.arguments !== undefined) {\n\t\t\t\t\t\t\tObject.assign(block, open.arguments.finish());\n\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\ttype: \"toolcall_end\",\n\t\t\t\t\t\t\t\tcontentIndex: index,\n\t\t\t\t\t\t\t\ttoolCall: block,\n\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else if (event.type === \"message_delta\") {\n\t\t\t\t\tif (event.delta.stop_reason) {\n\t\t\t\t\t\toutput.rawStopReason = event.delta.stop_reason;\n\t\t\t\t\t\tconst stopReasonResult = mapStopReason(event.delta.stop_reason, event.delta.stop_details);\n\t\t\t\t\t\toutput.stopReason = stopReasonResult.stopReason;\n\t\t\t\t\t\tif (stopReasonResult.errorMessage) {\n\t\t\t\t\t\t\toutput.errorMessage = stopReasonResult.errorMessage;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t// Only update usage fields if present (not null).\n\t\t\t\t\t// Preserves input_tokens from message_start when proxies omit it in message_delta.\n\t\t\t\t\tif (event.usage) {\n\t\t\t\t\t\tif (event.usage.input_tokens != null) {\n\t\t\t\t\t\t\toutput.usage.input = event.usage.input_tokens;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (event.usage.output_tokens != null) {\n\t\t\t\t\t\t\toutput.usage.output = event.usage.output_tokens;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (event.usage.cache_read_input_tokens != null) {\n\t\t\t\t\t\t\toutput.usage.cacheRead = event.usage.cache_read_input_tokens;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (event.usage.cache_creation_input_tokens != null) {\n\t\t\t\t\t\t\toutput.usage.cacheWrite = event.usage.cache_creation_input_tokens;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Anthropic reports reasoning tokens in `output_tokens_details.thinking_tokens` on the\n\t\t\t\t\t\t// final message_delta usage (a subset of output_tokens). SDK 0.91.1 omits the field from\n\t\t\t\t\t\t// its Usage type, so read it through a narrow cast. Verified against the live API.\n\t\t\t\t\t\tconst thinkingTokens = (event.usage as { output_tokens_details?: { thinking_tokens?: number } })\n\t\t\t\t\t\t\t.output_tokens_details?.thinking_tokens;\n\t\t\t\t\t\t// Vercel AI Gateway includes the TTL breakdown in deltas, though the SDK only types it on message_start.\n\t\t\t\t\t\tconst cacheCreation = (\n\t\t\t\t\t\t\tevent.usage as typeof event.usage & { cache_creation?: { ephemeral_1h_input_tokens?: number } }\n\t\t\t\t\t\t).cache_creation;\n\t\t\t\t\t\tif (cacheCreation?.ephemeral_1h_input_tokens != null) {\n\t\t\t\t\t\t\toutput.usage.cacheWrite1h = cacheCreation.ephemeral_1h_input_tokens;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (thinkingTokens != null) {\n\t\t\t\t\t\t\toutput.usage.reasoning = thinkingTokens;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t// Anthropic doesn't provide total_tokens, compute from components\n\t\t\t\t\toutput.usage.totalTokens =\n\t\t\t\t\t\toutput.usage.input + output.usage.output + output.usage.cacheRead + output.usage.cacheWrite;\n\t\t\t\t\tcalculateCost(usageModel, output.usage);\n\t\t\t\t\tservedSpeed = reportedSpeed(event.usage) ?? servedSpeed;\n\t\t\t\t\tif (servedSpeed === \"fast\") applyFastModePricing(output.usage);\n\t\t\t\t\t// A non-empty final fallback report supersedes the request-start report with\n\t\t\t\t\t// the serving model's transformations. An empty report must not erase drops\n\t\t\t\t\t// already reported at message_start.\n\t\t\t\t\tconst servingTransformations = getInputTransformations(event);\n\t\t\t\t\tif (servingTransformations && servingTransformations.length > 0) {\n\t\t\t\t\t\tinputTransformations = servingTransformations;\n\t\t\t\t\t}\n\t\t\t\t\taddEarlierAttemptCosts(output, model, usageModel, event);\n\t\t\t\t\tif (isOpenRouterModel(model) && event.usage) {\n\t\t\t\t\t\t// OpenRouter adds billing fields to streamed message_delta usage at runtime,\n\t\t\t\t\t\t// although its OpenAPI schema and the Anthropic SDK do not type those fields.\n\t\t\t\t\t\tapplyOpenRouterReportedCost(\n\t\t\t\t\t\t\toutput.usage,\n\t\t\t\t\t\t\tevent.usage as typeof event.usage & OpenRouterUsageAccounting,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (inputTransformations) recordInputTransformations(output, inputTransformations);\n\t\t\tif (options?.signal?.aborted) {\n\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t}\n\n\t\t\tif (output.stopReason === \"pending\") {\n\t\t\t\tthrow new Error(\"Anthropic stream ended without a stop reason\");\n\t\t\t}\n\t\t\tif (output.stopReason === \"aborted\" || output.stopReason === \"error\") {\n\t\t\t\tthrow new Error(output.errorMessage || \"An unknown error occurred\");\n\t\t\t}\n\t\t\tif (thread) recordThreadReply(model, thread, params, output, isOAuth, compat.allowEmptySignature);\n\n\t\t\tstream.push({ type: \"done\", reason: output.stopReason, message: output });\n\t\t\tstream.end();\n\t\t} catch (error) {\n\t\t\tif (\n\t\t\t\tinputTransformations &&\n\t\t\t\t!output.diagnostics?.some((diagnostic) => diagnostic.type === \"anthropic_input_transformations\")\n\t\t\t) {\n\t\t\t\trecordInputTransformations(output, inputTransformations);\n\t\t\t}\n\t\t\toutput.stopReason = options?.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\toutput.errorMessage = error instanceof Error ? withCauseDetail(error) : JSON.stringify(error);\n\t\t\toutput.retryAfterMs = error instanceof Error ? getProviderRetryAfterMs(error) : undefined;\n\t\t\tif (model.provider === \"github-copilot\") recordGitHubCopilotFailure(output, error, streamStarted);\n\t\t\tstream.push({ type: \"error\", reason: output.stopReason, error: output });\n\t\t\tstream.end();\n\t\t} finally {\n\t\t\tstreamDeadline.cleanup();\n\t\t}\n\t})();\n\n\treturn stream;\n};\n\n/**\n * Map ThinkingLevel to Anthropic effort levels for adaptive thinking.\n * Note: effort \"max\" is available on all adaptive-thinking Claude models, while native\n * \"xhigh\" is available on Opus 4.7, Opus 4.8, Opus 5, Sonnet 5, Fable 5, and Fable 5.1 —\n * the models the generator merges an `xhigh` mapping onto.\n */\nfunction mapThinkingLevelToEffort(\n\tmodel: Model<\"anthropic-messages\">,\n\tlevel: SimpleStreamOptions[\"reasoning\"],\n): AnthropicEffort {\n\tconst mapped = level ? model.thinkingLevelMap?.[level] : undefined;\n\tif (typeof mapped === \"string\") return mapped as AnthropicEffort;\n\n\tswitch (level) {\n\t\tcase \"minimal\":\n\t\tcase \"low\":\n\t\t\treturn \"low\";\n\t\tcase \"medium\":\n\t\t\treturn \"medium\";\n\t\tcase \"high\":\n\t\t\treturn \"high\";\n\t\tdefault:\n\t\t\treturn \"high\";\n\t}\n}\n\ninterface AnthropicThinkingOffFallback {\n\tlevel: ThinkingLevel;\n\teffort: AnthropicEffort;\n}\n\n/**\n * Thinking `off` on an adaptive model that cannot disable thinking runs at the model's lowest effort.\n * Sending no effort would leave the API's default, which is `high`.\n */\nfunction getAnthropicThinkingOffFallback(\n\tmodel: Model<\"anthropic-messages\">,\n\toptions: AnthropicOptions | undefined,\n): AnthropicThinkingOffFallback | undefined {\n\tif (options?.thinkingEnabled !== false) return undefined;\n\tif (model.compat?.forceAdaptiveThinking !== true && !supportsMidConvoEffort(model)) return undefined;\n\tconst level = getThinkingOffFallbackLevel(model);\n\treturn level === undefined ? undefined : { level, effort: mapThinkingLevelToEffort(model, level) };\n}\n\nexport const streamSimple: StreamFunction<\"anthropic-messages\", SimpleStreamOptions> = (\n\tmodel: Model<\"anthropic-messages\">,\n\tcontext: TranscriptContext,\n\toptions?: SimpleStreamOptions,\n): AssistantMessageEventStream => {\n\tif (!getAnthropicFederation(model, options?.apiKey, options?.headers, options?.env)) {\n\t\tassertRequestAuth(model.provider, options?.apiKey, options?.headers);\n\t}\n\n\tconst base = {\n\t\t...buildBaseOptions(model, context, options, options?.apiKey),\n\t\ttoolChoice: options?.toolChoice,\n\t} satisfies AnthropicOptions;\n\tif (!options?.reasoning) {\n\t\treturn stream(model, context, {\n\t\t\t...base,\n\t\t\tthinkingEnabled: false,\n\t\t} satisfies AnthropicOptions);\n\t}\n\n\t// For models with adaptive thinking: use an effort level.\n\t// For older models: use budget-based thinking.\n\tif (model.compat?.forceAdaptiveThinking === true) {\n\t\tconst effort = mapThinkingLevelToEffort(model, options.reasoning);\n\t\treturn stream(model, context, {\n\t\t\t...base,\n\t\t\tthinkingEnabled: true,\n\t\t\teffort,\n\t\t} satisfies AnthropicOptions);\n\t}\n\n\t// Undefined means the caller did not request an output cap; let the helper use the model cap.\n\t// Do not coerce to 0 here, or the thinking budget would become the entire max_tokens value.\n\tconst adjusted = adjustMaxTokensForThinking(\n\t\tbase.maxTokens,\n\t\tmodel.maxTokens,\n\t\toptions.reasoning,\n\t\toptions.thinkingBudgets,\n\t);\n\n\tconst maxTokens = clampMaxTokensToContext(model, context, adjusted.maxTokens);\n\n\treturn stream(model, context, {\n\t\t...base,\n\t\tmaxTokens,\n\t\tthinkingEnabled: true,\n\t\tthinkingBudgetTokens: Math.min(adjusted.thinkingBudget, Math.max(0, maxTokens - 1024)),\n\t} satisfies AnthropicOptions);\n};\n\nfunction isOAuthToken(apiKey: string): boolean {\n\treturn apiKey.includes(\"sk-ant-oat\");\n}\n\nfunction createClient(\n\tmodel: Model<\"anthropic-messages\">,\n\tapiKey: string | undefined,\n\tinterleavedThinking: boolean,\n\tuseFineGrainedToolStreamingBeta: boolean,\n\tuseServerSideFallbackBeta: boolean,\n\toptionsHeaders?: ProviderHeaders,\n\tfetch?: typeof globalThis.fetch,\n\tdynamicHeaders?: Record<string, string>,\n\tsessionId?: string,\n\tuseNativeToolChanges = false,\n\tfederation?: AnthropicFederationConfig,\n\tidentity?: ClientIdentity,\n\tuseMessageThreads = false,\n): { client: Anthropic; isOAuthToken: boolean } {\n\t// Adaptive thinking models have interleaved thinking built in, so skip the beta header.\n\tconst needsInterleavedBeta = interleavedThinking && model.compat?.forceAdaptiveThinking !== true;\n\tconst betaFeatures: string[] = [];\n\tif (useFineGrainedToolStreamingBeta) {\n\t\tbetaFeatures.push(FINE_GRAINED_TOOL_STREAMING_BETA);\n\t}\n\tif (needsInterleavedBeta) {\n\t\tbetaFeatures.push(INTERLEAVED_THINKING_BETA);\n\t}\n\tif (useServerSideFallbackBeta) {\n\t\tbetaFeatures.push(SERVER_SIDE_FALLBACK_BETA);\n\t}\n\tif (shouldUseThinkingBindingControlsBeta(model)) {\n\t\tbetaFeatures.push(THINKING_BINDING_CONTROLS_BETA);\n\t}\n\tif (supportsMidConvoEffort(model)) {\n\t\tbetaFeatures.push(MID_CONVERSATION_OUTPUT_CONFIG_BETA, THINKING_BINDING_CONTROLS_BETA);\n\t}\n\tif (useNativeToolChanges) betaFeatures.push(INLINE_TOOLS_BETA);\n\tif (requestedSpeed(model) === \"fast\") betaFeatures.push(FAST_MODE_BETA);\n\tif (useMessageThreads) betaFeatures.push(MESSAGE_THREADS_BETA);\n\tconst uniqueBetaFeatures = [...new Set(betaFeatures)];\n\n\t// Copilot: Bearer auth, selective betas.\n\tif (model.provider === \"github-copilot\") {\n\t\tconst client = new AtomicAnthropic({\n\t\t\tapiKey: null,\n\t\t\tauthToken: apiKey ?? null,\n\t\t\tbaseURL: model.baseUrl,\n\t\t\tdangerouslyAllowBrowser: true,\n\t\t\tfetch,\n\t\t\tdefaultHeaders: mergeHeaders(\n\t\t\t\tgetIdentityHeaders(model, identity),\n\t\t\t\t{\n\t\t\t\t\taccept: \"application/json\",\n\t\t\t\t\t\"anthropic-dangerous-direct-browser-access\": \"true\",\n\t\t\t\t\t...(uniqueBetaFeatures.length > 0 ? { \"anthropic-beta\": uniqueBetaFeatures.join(\",\") } : {}),\n\t\t\t\t},\n\t\t\t\tmodel.headers,\n\t\t\t\tdynamicHeaders,\n\t\t\t\toptionsHeaders,\n\t\t\t),\n\t\t});\n\n\t\treturn { client, isOAuthToken: false };\n\t}\n\n\t// OAuth: Bearer auth, Claude Code identity headers instead of the client identity.\n\tif (apiKey && isOAuthToken(apiKey)) {\n\t\tconst client = new AtomicAnthropic({\n\t\t\tapiKey: null,\n\t\t\tauthToken: apiKey,\n\t\t\tbaseURL: model.baseUrl,\n\t\t\tdangerouslyAllowBrowser: true,\n\t\t\tfetch,\n\t\t\tdefaultHeaders: mergeHeaders(\n\t\t\t\t{\n\t\t\t\t\taccept: \"application/json\",\n\t\t\t\t\t\"anthropic-dangerous-direct-browser-access\": \"true\",\n\t\t\t\t\t\"anthropic-beta\": [\"claude-code-20250219\", \"oauth-2025-04-20\", ...uniqueBetaFeatures].join(\",\"),\n\t\t\t\t\t\"user-agent\": `claude-cli/${claudeCodeVersion}`,\n\t\t\t\t\t\"x-app\": \"cli\",\n\t\t\t\t},\n\t\t\t\tmodel.headers,\n\t\t\t\toptionsHeaders,\n\t\t\t),\n\t\t});\n\n\t\treturn { client, isOAuthToken: true };\n\t}\n\n\t// API key, header-owned auth, or workload identity federation.\n\tconst compat = getAnthropicCompat(model);\n\tconst sessionAffinityHeaders: ProviderHeaders = {};\n\tif (sessionId && compat.sendSessionAffinityHeaders) {\n\t\tconst header = compat.sessionAffinityFormat === \"openrouter\" ? \"x-session-id\" : \"x-session-affinity\";\n\t\tsessionAffinityHeaders[header] = sessionId;\n\t}\n\tconst defaultHeaders = mergeHeaders(\n\t\tgetIdentityHeaders(model, identity),\n\t\t{\n\t\t\taccept: \"application/json\",\n\t\t\t\"anthropic-dangerous-direct-browser-access\": \"true\",\n\t\t\t...(uniqueBetaFeatures.length > 0 ? { \"anthropic-beta\": uniqueBetaFeatures.join(\",\") } : {}),\n\t\t},\n\t\tsessionAffinityHeaders,\n\t\tmodel.headers,\n\t\toptionsHeaders,\n\t);\n\tif (federation) {\n\t\tconst key = JSON.stringify([model.baseUrl, federation]);\n\t\tif (federationClient?.key !== key || federationClient.fetch !== fetch) {\n\t\t\tconst client = new AtomicAnthropic({\n\t\t\t\tapiKey: null,\n\t\t\t\tauthToken: null,\n\t\t\t\tconfig: federation,\n\t\t\t\tbaseURL: model.baseUrl,\n\t\t\t\tdangerouslyAllowBrowser: true,\n\t\t\t\tfetch,\n\t\t\t});\n\t\t\tfederationClient = { key, fetch, client };\n\t\t}\n\t\treturn { client: federationClient.client.withOptions({ defaultHeaders, fetch }), isOAuthToken: false };\n\t}\n\n\tconst client = new AtomicAnthropic({\n\t\tapiKey: apiKey ?? null,\n\t\tauthToken: null,\n\t\tbaseURL: model.baseUrl,\n\t\tdangerouslyAllowBrowser: true,\n\t\tfetch,\n\t\tdefaultHeaders,\n\t});\n\n\treturn { client, isOAuthToken: false };\n}\n\nfunction getNativeToolChangeBetas(\n\tmodel: Model<\"anthropic-messages\">,\n\tcontext: TranscriptContext,\n\tisOAuth: boolean,\n\toptions: AnthropicOptions | undefined,\n\tmessageThreads: boolean,\n): NonNullable<MessageCreateParamsStreaming[\"betas\"]> {\n\tlet configured: string | null | undefined;\n\tfor (const headers of [model.headers, options?.headers]) {\n\t\tfor (const [name, value] of Object.entries(headers ?? {})) {\n\t\t\tif (name.toLowerCase() === \"anthropic-beta\") configured = value;\n\t\t}\n\t}\n\tif (configured === null) return [];\n\tif (configured !== undefined)\n\t\treturn [\n\t\t\t...new Set(\n\t\t\t\tconfigured\n\t\t\t\t\t.split(\",\")\n\t\t\t\t\t.map((feature) => feature.trim())\n\t\t\t\t\t.filter(Boolean),\n\t\t\t),\n\t\t];\n\tconst features = [INLINE_TOOLS_BETA];\n\tif (isOAuth) features.push(\"claude-code-20250219\", \"oauth-2025-04-20\");\n\tif (shouldUseFineGrainedToolStreamingBeta(model, context)) features.push(FINE_GRAINED_TOOL_STREAMING_BETA);\n\tif (\n\t\tmodel.reasoning &&\n\t\toptions?.thinkingEnabled &&\n\t\t(options.interleavedThinking ?? true) &&\n\t\tmodel.compat?.forceAdaptiveThinking !== true\n\t) {\n\t\tfeatures.push(INTERLEAVED_THINKING_BETA);\n\t}\n\tif (shouldUseServerSideFallbackBeta(model)) features.push(SERVER_SIDE_FALLBACK_BETA);\n\tif (shouldUseThinkingBindingControlsBeta(model)) features.push(THINKING_BINDING_CONTROLS_BETA);\n\tif (supportsMidConvoEffort(model))\n\t\tfeatures.push(MID_CONVERSATION_OUTPUT_CONFIG_BETA, THINKING_BINDING_CONTROLS_BETA);\n\tif (requestedSpeed(model) === \"fast\") features.push(FAST_MODE_BETA);\n\tif (messageThreads) features.push(MESSAGE_THREADS_BETA);\n\treturn [...new Set(features)];\n}\n\ninterface BuildParamsFlags {\n\t/** Send `strict: \"prefer\"` tools without strict schemas, after Anthropic rejected them. */\n\tdisablePreferredStrictTools: boolean;\n\t/** The session uses message threads, so the threads beta is sent. */\n\tmessageThreads: boolean;\n}\n\nfunction buildParams(\n\tmodel: Model<\"anthropic-messages\">,\n\tcontext: TranscriptContext,\n\tisOAuthToken: boolean,\n\toptions: AnthropicOptions | undefined,\n\t{ disablePreferredStrictTools, messageThreads }: BuildParamsFlags,\n): {\n\tparams: MessageCreateParamsStreaming;\n\thasPreferredStrictTools: boolean;\n\t/** Effort of the final effort marker, recorded on the reply so later requests can replay it. */\n\tproviderThinkingLevel: AnthropicEffort | undefined;\n} {\n\tconst { cacheControl } = getCacheControl(model, options?.cacheRetention, options?.env);\n\tconst compat = getAnthropicCompat(model);\n\tconst initialSystemMessage = getInitialSystemMessage(context.messages);\n\tconst initialSystemText = initialSystemMessage ? getSystemMessageText(initialSystemMessage) : \"\";\n\tconst transformedMessages = transformMessages(context.messages, model, normalizeToolCallId);\n\tconst conversationMessages = initialSystemMessage ? transformedMessages.slice(1) : transformedMessages;\n\tlet hasPreferredStrictTools = false;\n\tconst convertToolDefinitions = (tools: Tool[], toolCacheControl?: CacheControlEphemeral): BetaTool[] => {\n\t\tif (isOAuthToken) tools = [...new Map(tools.map((tool) => [toClaudeCodeName(tool.name), tool])).values()];\n\t\tconst definitions = convertTools(\n\t\t\ttools,\n\t\t\tisOAuthToken,\n\t\t\tcompat.supportsEagerToolInputStreaming,\n\t\t\tcompat.supportsStrictTools,\n\t\t\ttoolCacheControl,\n\t\t\tdisablePreferredStrictTools,\n\t\t);\n\t\tif (\n\t\t\tdefinitions.some(\n\t\t\t\t(definition, index) => definition.strict === true && prefersJsonSchemaStrictSampling(tools[index]),\n\t\t\t)\n\t\t)\n\t\t\thasPreferredStrictTools = true;\n\t\treturn definitions;\n\t};\n\tconst initialTools = initialSystemMessage?.toolsAdded ?? [];\n\tconst nativeToolChanges =\n\t\tcompat.supportsMidConvoSystemMessages && compat.supportsMidConvoToolChanges && initialTools.length > 0;\n\tconst thinkingOffFallback = getAnthropicThinkingOffFallback(model, options);\n\tconst thinkingDisabled =\n\t\tmodel.reasoning && options?.thinkingEnabled === false && model.thinkingLevelMap?.off !== null;\n\t// Effort cannot change between messages while thinking is disabled, so \"off\" sends no effort markers.\n\tconst effortMessages = supportsMidConvoEffort(model) && !thinkingDisabled;\n\tconst converted = convertMessages(\n\t\tconversationMessages,\n\t\tisOAuthToken,\n\t\tcacheControl,\n\t\tcompat.allowEmptySignature,\n\t\teffortMessages ? model.provider : undefined,\n\t\tnativeToolChanges ? convertToolDefinitions : undefined,\n\t);\n\tconst activeEffort = options?.effort ?? thinkingOffFallback?.effort ?? \"high\";\n\tconst params: MessageCreateParamsStreaming = {\n\t\tmodel: upstreamModelId(model),\n\t\tmessages: (effortMessages\n\t\t\t? insertThinkingLevelMessages(converted, activeEffort)\n\t\t\t: converted.messages) as MessageParam[],\n\t\tmax_tokens: options?.maxTokens ?? model.maxTokens,\n\t\tstream: true,\n\t};\n\tif (nativeToolChanges)\n\t\tparams.betas = getNativeToolChangeBetas(model, context, isOAuthToken, options, messageThreads);\n\tconst speed = requestedSpeed(model);\n\tif (speed !== undefined) params.speed = speed;\n\n\t// For OAuth tokens, we MUST include Claude Code identity\n\tif (isOAuthToken) {\n\t\tparams.system = [\n\t\t\t{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: \"You are Claude Code, Anthropic's official CLI for Claude.\",\n\t\t\t\t...(cacheControl ? { cache_control: cacheControl } : {}),\n\t\t\t},\n\t\t];\n\t\tif (initialSystemText) {\n\t\t\tparams.system.push({\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: sanitizeSurrogates(initialSystemText),\n\t\t\t\t...(cacheControl ? { cache_control: cacheControl } : {}),\n\t\t\t});\n\t\t}\n\t} else if (initialSystemText) {\n\t\t// Add cache control to system prompt for non-OAuth tokens\n\t\tparams.system = [\n\t\t\t{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: sanitizeSurrogates(initialSystemText),\n\t\t\t\t...(cacheControl ? { cache_control: cacheControl } : {}),\n\t\t\t},\n\t\t];\n\t}\n\n\t// Temperature is incompatible with extended thinking and unsupported on Claude Opus 4.7+.\n\tif (\n\t\toptions?.temperature !== undefined &&\n\t\t!options?.thinkingEnabled &&\n\t\t!thinkingOffFallback &&\n\t\t!supportsMidConvoEffort(model) &&\n\t\tcompat.supportsTemperature\n\t) {\n\t\tparams.temperature = options.temperature;\n\t}\n\n\tconst toolCacheControl = compat.supportsCacheControlOnTools ? cacheControl : undefined;\n\tif (nativeToolChanges) {\n\t\tparams.tools = [...convertToolDefinitions(initialTools, toolCacheControl), DEFERRED_TOOL_PLACEHOLDER];\n\t} else {\n\t\tconst tools = getCurrentTools(context.messages);\n\t\tif (tools.length > 0) {\n\t\t\tparams.tools = convertToolDefinitions(tools, toolCacheControl);\n\t\t}\n\t}\n\n\t// Managed effort models always use adaptive thinking. Their per-turn markers\n\t// carry the actual effort for every reply.\n\tif (effortMessages) {\n\t\tparams.thinking = {\n\t\t\ttype: \"adaptive\",\n\t\t\tdisplay: options?.thinkingDisplay ?? \"summarized\",\n\t\t\tblock_binding: { prefix_mismatch_behavior: \"drop_block\" },\n\t\t} as unknown as NonNullable<MessageCreateParamsStreaming[\"thinking\"]>;\n\t\t// The top-level effort is part of the cached prompt, so it stays fixed. It is \"low\" because\n\t\t// organizations can cap effort and reject requests containing any level above the cap.\n\t\tparams.output_config = { effort: \"low\" };\n\t} else if (model.reasoning) {\n\t\tif (options?.thinkingEnabled || thinkingOffFallback) {\n\t\t\t// Default to \"summarized\" so Opus 4.7 and Mythos Preview behave like\n\t\t\t// older Claude 4 models (whose API default is also \"summarized\").\n\t\t\tconst display: AnthropicThinkingDisplay = options?.thinkingDisplay ?? \"summarized\";\n\t\t\tconst effort = options?.effort ?? thinkingOffFallback?.effort;\n\t\t\tif (model.compat?.forceAdaptiveThinking === true) {\n\t\t\t\t// Adaptive thinking: Claude decides when and how much to think.\n\t\t\t\tparams.thinking = { type: \"adaptive\", display };\n\t\t\t\tif (effort) {\n\t\t\t\t\t// The Anthropic SDK types can lag newly supported effort values such as \"xhigh\".\n\t\t\t\t\tparams.output_config =\n\t\t\t\t\t\teffort === \"xhigh\"\n\t\t\t\t\t\t\t? ({ effort } as unknown as NonNullable<MessageCreateParamsStreaming[\"output_config\"]>)\n\t\t\t\t\t\t\t: { effort };\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Budget-based thinking for older models\n\t\t\t\tparams.thinking = {\n\t\t\t\t\ttype: \"enabled\",\n\t\t\t\t\tbudget_tokens: options?.thinkingBudgetTokens || 1024,\n\t\t\t\t\tdisplay,\n\t\t\t\t};\n\t\t\t}\n\t\t} else if (options?.thinkingEnabled === false && model.thinkingLevelMap?.off !== null) {\n\t\t\tparams.thinking = { type: \"disabled\" };\n\t\t}\n\n\t\t// `block_binding` must accompany the beta header on *every* request for a model that\n\t\t// enforces the conversation check, not only on reasoning turns. The header alone leaves\n\t\t// `prefix_mismatch_behavior` at its `\"error\"` default, which is the 400 this opts out of.\n\t\t// `streamSimple` sets `thinkingEnabled: false` whenever no reasoning level is requested,\n\t\t// and Claude Fable 5.1 denies thinking-off (`thinkingLevelMap.off === null`), so without\n\t\t// this the no-reasoning path would send the header with no field at all.\n\t\tif (shouldUseThinkingBindingControlsBeta(model)) {\n\t\t\tconst blockBinding = { block_binding: { prefix_mismatch_behavior: \"drop_block\" } };\n\t\t\t// The Anthropic SDK types lag the `thinking-binding-controls-2026-08-01` beta.\n\t\t\tif (params.thinking?.type === \"adaptive\" || params.thinking?.type === \"enabled\") {\n\t\t\t\t// Accepted alongside both thinking types. It only changes what happens to a block\n\t\t\t\t// replayed behind a changed prefix; the model check always drops regardless.\n\t\t\t\tparams.thinking = { ...params.thinking, ...blockBinding } as unknown as NonNullable<\n\t\t\t\t\tMessageCreateParamsStreaming[\"thinking\"]\n\t\t\t\t>;\n\t\t\t} else if (!params.thinking && model.compat?.forceAdaptiveThinking === true) {\n\t\t\t\t// Adaptive thinking is always on for these models, so omitting `thinking` and\n\t\t\t\t// sending `{type: \"adaptive\"}` are equivalent. `display` stays absent to keep the\n\t\t\t\t// API's `\"omitted\"` default, which is exactly what omitting `thinking` produced.\n\t\t\t\tparams.thinking = { type: \"adaptive\", ...blockBinding } as unknown as NonNullable<\n\t\t\t\t\tMessageCreateParamsStreaming[\"thinking\"]\n\t\t\t\t>;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (options?.metadata) {\n\t\tconst userId = options.metadata.user_id;\n\t\tif (typeof userId === \"string\") {\n\t\t\tparams.metadata = { user_id: userId };\n\t\t}\n\t}\n\n\tif (options?.toolChoice) {\n\t\tconst requested = options.toolChoice;\n\t\tconst isForced = requested === \"any\" || (typeof requested !== \"string\" && requested.type === \"tool\");\n\t\tif (isForced && model.compat?.supportsForcedToolChoice === false) {\n\t\t\t// \"The exceptions are Claude Fable 5.1 and Claude Mythos 5.1, which reject forced tool\n\t\t\t// use on every request with a 400 error. On those models, use\n\t\t\t// `tool_choice: {\"type\": \"auto\"}` with strict tool use or structured outputs instead.\"\n\t\t\t// https://platform.claude.com/docs/en/build-with-claude/thinking\n\t\t\t//\n\t\t\t// Reject the request rather than rewriting it. Silently substituting `auto` would\n\t\t\t// discard an explicit caller instruction and make `AnthropicOptions.toolChoice`'s\n\t\t\t// declared shape a lie; the caller asked the model to call a tool, and quietly asking\n\t\t\t// it to decide instead is a different request. Failing here matches how this package\n\t\t\t// handles other explicitly requested capabilities a model cannot honor, and surfaces\n\t\t\t// the remedy before a round trip that would 400 anyway. Callers that want the\n\t\t\t// substitution can make it themselves, and can branch on\n\t\t\t// `model.compat.supportsForcedToolChoice` to decide.\n\t\t\tconst requestedLabel = typeof requested === \"string\" ? requested : `tool \"${requested.name}\"`;\n\t\t\tthrow new Error(\n\t\t\t\t`Model ${model.id} does not support forced tool choice (requested: ${requestedLabel}). ` +\n\t\t\t\t\t`Use toolChoice \"auto\" with strict tool use or structured outputs instead.`,\n\t\t\t);\n\t\t}\n\t\tif (typeof requested === \"string\") {\n\t\t\tparams.tool_choice = { type: requested };\n\t\t} else {\n\t\t\tparams.tool_choice = requested;\n\t\t}\n\t}\n\n\tconst allowedFallbackModels = model.compat?.allowedFallbackModels;\n\tif (allowedFallbackModels && allowedFallbackModels.length > 0) {\n\t\tparams.fallbacks = allowedFallbackModels.map((fallback) => ({ model: fallback.model }));\n\t}\n\n\treturn { params, hasPreferredStrictTools, providerThinkingLevel: effortMessages ? activeEffort : undefined };\n}\n\n// Normalize tool call IDs to match Anthropic's required pattern and length\nfunction normalizeToolCallId(id: string): string {\n\treturn id.replace(/[^a-zA-Z0-9_-]/g, \"_\").slice(0, 64);\n}\n\nfunction convertToolResult(msg: ToolResultMessage, content = msg.content): ContentBlockParam {\n\treturn {\n\t\ttype: \"tool_result\",\n\t\ttool_use_id: msg.toolCallId,\n\t\tcontent: convertContentBlocks(content),\n\t\tis_error: msg.isError,\n\t};\n}\n\nfunction convertMessages(\n\ttransformedMessages: Message[],\n\tisOAuthToken: boolean,\n\tcacheControl?: CacheControlEphemeral,\n\tallowEmptySignature = false,\n\tmanagedProvider?: string,\n\tconvertToolDefinitions?: (tools: Tool[]) => BetaTool[],\n): ConvertedAnthropicMessages {\n\tconst params: MessageParam[] = [];\n\tconst assistantLevels = new Map<number, AnthropicEffort>();\n\t// Later system messages are held back and emitted directly before the next assistant\n\t// message that is sent (or at the end of the transcript). Assistant messages that convert to\n\t// no blocks are dropped, so holding past them keeps an update from landing before a user\n\t// message (pi #11091). Anthropic requires `tool_result` blocks to\n\t// immediately follow their `tool_use`, so a system message between them is rejected; this\n\t// also mirrors where the managed-effort system messages are inserted. As a result an\n\t// update placed before a user message in the transcript lands after it on the wire.\n\tconst pendingSystemMessages: MessageParam[] = [];\n\tconst flushPendingSystemMessages = (): void => {\n\t\tparams.push(...pendingSystemMessages);\n\t\tpendingSystemMessages.length = 0;\n\t};\n\n\tfor (let i = 0; i < transformedMessages.length; i++) {\n\t\tconst msg = transformedMessages[i];\n\n\t\tif (msg.role === \"system\") {\n\t\t\t// Later system messages only reach this point when the model accepts them natively;\n\t\t\t// otherwise the transcript was collapsed into the leading message before conversion.\n\t\t\tconst text = renderSystemMessageUpdate(msg);\n\t\t\tconst blocks: ContentBlockParam[] = [];\n\t\t\tif (text.length > 0) blocks.push({ type: \"text\", text: sanitizeSurrogates(text) });\n\t\t\tif (convertToolDefinitions) {\n\t\t\t\tconst added = msg.toolsAdded ?? [];\n\t\t\t\tconst redefined = new Set(added.map((tool) => tool.name));\n\t\t\t\tfor (const tool of msg.toolsRemoved ?? []) {\n\t\t\t\t\tif (redefined.has(tool.name)) continue;\n\t\t\t\t\tblocks.push({\n\t\t\t\t\t\ttype: \"tool_removal\",\n\t\t\t\t\t\ttool: { type: \"tool_reference\", name: isOAuthToken ? toClaudeCodeName(tool.name) : tool.name },\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tfor (const definition of convertToolDefinitions(added)) {\n\t\t\t\t\tblocks.push({ type: \"tool_addition\", tool: { type: \"tool_definition\", definition } });\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (blocks.length > 0) pendingSystemMessages.push({ role: \"system\", content: blocks });\n\t\t} else if (msg.role === \"user\") {\n\t\t\tif (typeof msg.content === \"string\") {\n\t\t\t\tif (msg.content.trim().length > 0) {\n\t\t\t\t\tparams.push({\n\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\tcontent: sanitizeSurrogates(msg.content),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tconst blocks: ContentBlockParam[] = msg.content.map((item) => {\n\t\t\t\t\tif (item.type === \"text\") {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: sanitizeSurrogates(item.text),\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tif (item.type === \"document\") {\n\t\t\t\t\t\t// `BetaBase64PDFSource`. PDFs ride Claude's vision path, so no beta header.\n\t\t\t\t\t\t// The media type is a fixed literal in that SDK type, so it is hardcoded here\n\t\t\t\t\t\t// and the block's own field is verified rather than read.\n\t\t\t\t\t\t// https://platform.claude.com/docs/en/build-with-claude/pdf-support\n\t\t\t\t\t\tassertSupportedDocumentMimeType(item);\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\ttype: \"document\",\n\t\t\t\t\t\t\tsource: {\n\t\t\t\t\t\t\t\ttype: \"base64\",\n\t\t\t\t\t\t\t\tmedia_type: \"application/pdf\",\n\t\t\t\t\t\t\t\tdata: item.data,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t...(item.name ? { title: item.name } : {}),\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"image\",\n\t\t\t\t\t\tsource: {\n\t\t\t\t\t\t\ttype: \"base64\",\n\t\t\t\t\t\t\tmedia_type: item.mimeType as \"image/jpeg\" | \"image/png\" | \"image/gif\" | \"image/webp\",\n\t\t\t\t\t\t\tdata: item.data,\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t});\n\t\t\t\tconst filteredBlocks = blocks.filter((b) => {\n\t\t\t\t\tif (b.type === \"text\") {\n\t\t\t\t\t\treturn b.text.trim().length > 0;\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t});\n\t\t\t\tif (filteredBlocks.length === 0) continue;\n\t\t\t\tparams.push({\n\t\t\t\t\trole: \"user\",\n\t\t\t\t\tcontent: filteredBlocks,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (msg.role === \"assistant\") {\n\t\t\tconst blocks = convertAnthropicAssistantContent(msg, {\n\t\t\t\tallowEmptySignature,\n\t\t\t\ttoolName: isOAuthToken ? toClaudeCodeName : undefined,\n\t\t\t});\n\t\t\tif (blocks.length === 0) continue;\n\t\t\tflushPendingSystemMessages();\n\t\t\tconst messageIndex = params.length;\n\t\t\tparams.push({\n\t\t\t\trole: \"assistant\",\n\t\t\t\tcontent: blocks,\n\t\t\t});\n\t\t\tif (\n\t\t\t\tmanagedProvider !== undefined &&\n\t\t\t\tmsg.api === \"anthropic-messages\" &&\n\t\t\t\tmsg.provider === managedProvider &&\n\t\t\t\tisAnthropicEffort(msg.providerThinkingLevel)\n\t\t\t) {\n\t\t\t\tassistantLevels.set(messageIndex, msg.providerThinkingLevel);\n\t\t\t}\n\t\t} else if (msg.role === \"toolResult\") {\n\t\t\t// Collect all consecutive toolResult messages, needed for z.ai Anthropic endpoint.\n\t\t\tconst toolResults: ContentBlockParam[] = [];\n\t\t\t// Anthropic rejects error tool results that contain anything but text, so their images follow\n\t\t\t// all tool results of the turn, which must come first in the user message (#10794).\n\t\t\tconst errorImages: ContentBlockParam[] = [];\n\t\t\tlet j = i;\n\t\t\twhile (j < transformedMessages.length && transformedMessages[j].role === \"toolResult\") {\n\t\t\t\tconst toolMsg = transformedMessages[j] as ToolResultMessage;\n\t\t\t\tconst split = splitErrorToolResultImages(toolMsg);\n\t\t\t\ttoolResults.push(convertToolResult(toolMsg, split?.content));\n\t\t\t\tif (split) {\n\t\t\t\t\terrorImages.push({ type: \"text\", text: split.caption }, ...split.images.map(convertImageBlock));\n\t\t\t\t}\n\t\t\t\tj++;\n\t\t\t}\n\n\t\t\t// Skip the messages we've already processed.\n\t\t\ti = j - 1;\n\n\t\t\tparams.push({\n\t\t\t\trole: \"user\",\n\t\t\t\tcontent: [...toolResults, ...errorImages],\n\t\t\t});\n\t\t}\n\t}\n\n\tflushPendingSystemMessages();\n\n\t// Add cache_control to the last user or system message to cache conversation history\n\tif (cacheControl && params.length > 0) {\n\t\tconst lastMessage = params[params.length - 1];\n\t\tif (lastMessage.role === \"user\" || lastMessage.role === \"system\") {\n\t\t\tif (Array.isArray(lastMessage.content)) {\n\t\t\t\tconst lastBlock = lastMessage.content[lastMessage.content.length - 1];\n\t\t\t\tif (\n\t\t\t\t\tlastBlock &&\n\t\t\t\t\t(lastBlock.type === \"text\" ||\n\t\t\t\t\t\tlastBlock.type === \"image\" ||\n\t\t\t\t\t\tlastBlock.type === \"tool_result\" ||\n\t\t\t\t\t\tlastBlock.type === \"tool_addition\" ||\n\t\t\t\t\t\tlastBlock.type === \"tool_removal\")\n\t\t\t\t) {\n\t\t\t\t\t(lastBlock as any).cache_control = cacheControl;\n\t\t\t\t}\n\t\t\t} else if (typeof lastMessage.content === \"string\") {\n\t\t\t\tlastMessage.content = [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: lastMessage.content,\n\t\t\t\t\t\tcache_control: cacheControl,\n\t\t\t\t\t},\n\t\t\t\t] as any;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { messages: params, assistantLevels };\n}\n\ninterface ConvertedAnthropicMessages {\n\tmessages: MessageParam[];\n\tassistantLevels: Map<number, AnthropicEffort>;\n}\n\nfunction isAnthropicEffort(value: string | undefined): value is AnthropicEffort {\n\treturn value === \"low\" || value === \"medium\" || value === \"high\" || value === \"xhigh\" || value === \"max\";\n}\n\ninterface EffortMessage {\n\trole: \"system\";\n\tcontent: [];\n\toutput_config: { effort: AnthropicEffort };\n}\n\nfunction insertThinkingLevelMessages(\n\tconverted: ConvertedAnthropicMessages,\n\tactiveEffort: AnthropicEffort,\n): Array<MessageParam | EffortMessage> {\n\tconst messages: Array<MessageParam | EffortMessage> = [];\n\tfor (let index = 0; index < converted.messages.length; index++) {\n\t\tconst historicalEffort = converted.assistantLevels.get(index);\n\t\tif (historicalEffort !== undefined) {\n\t\t\tmessages.push({ role: \"system\", content: [], output_config: { effort: historicalEffort } });\n\t\t}\n\t\tmessages.push(converted.messages[index]);\n\t}\n\tmessages.push({ role: \"system\", content: [], output_config: { effort: activeEffort } });\n\treturn messages;\n}\n\nfunction shouldUseFineGrainedToolStreamingBeta(\n\tmodel: Model<\"anthropic-messages\">,\n\tcontext: TranscriptContext,\n): boolean {\n\treturn getCurrentTools(context.messages).length > 0 && !getAnthropicCompat(model).supportsEagerToolInputStreaming;\n}\n\ntype ToolSchemaObject = {\n\ttype?: string | string[];\n\tproperties?: Record<string, unknown>;\n\trequired?: string[];\n\tanyOf?: ToolSchemaObject[];\n\t$defs?: unknown;\n\tdefinitions?: unknown;\n};\n\nfunction projectObjectUnionForAnthropic(\n\tschema: ToolSchemaObject,\n): { properties: Record<string, unknown>; required: string[] } | undefined {\n\tif (schema.properties !== undefined || !Array.isArray(schema.anyOf) || schema.anyOf.length === 0) return undefined;\n\tconst branches = schema.anyOf;\n\tif (\n\t\t!branches.every(\n\t\t\t(branch) =>\n\t\t\t\t(branch.type === undefined ||\n\t\t\t\t\tbranch.type === \"object\" ||\n\t\t\t\t\t(Array.isArray(branch.type) &&\n\t\t\t\t\t\tbranch.type.length > 0 &&\n\t\t\t\t\t\tbranch.type.every((type) => type === \"object\"))) &&\n\t\t\t\tbranch.properties !== undefined,\n\t\t)\n\t)\n\t\treturn undefined;\n\n\tconst variantsByKey = new Map<string, unknown[]>();\n\tfor (const branch of branches) {\n\t\tfor (const [key, propertySchema] of Object.entries(branch.properties ?? {})) {\n\t\t\tconst variants = variantsByKey.get(key);\n\t\t\tif (variants === undefined) {\n\t\t\t\tvariantsByKey.set(key, [propertySchema]);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst serialized = JSON.stringify(propertySchema);\n\t\t\tif (!variants.some((variant) => variant === propertySchema || JSON.stringify(variant) === serialized)) {\n\t\t\t\tvariants.push(propertySchema);\n\t\t\t}\n\t\t}\n\t}\n\n\tconst properties: Record<string, unknown> = Object.fromEntries(\n\t\t[...variantsByKey].flatMap(([key, variants]) => {\n\t\t\tconst first = variants[0];\n\t\t\treturn first === undefined ? [] : [[key, variants.length === 1 ? first : { anyOf: variants }]];\n\t\t}),\n\t);\n\n\treturn {\n\t\tproperties,\n\t\trequired: (branches[0]?.required ?? []).filter((key) =>\n\t\t\tbranches.every((branch) => (branch.required ?? []).includes(key)),\n\t\t),\n\t};\n}\n\nfunction convertTools(\n\ttools: Tool[],\n\tisOAuthToken: boolean,\n\tsupportsEagerToolInputStreaming: boolean,\n\tsupportsStrictTools: boolean,\n\tcacheControl?: CacheControlEphemeral,\n\tdisablePreferredStrictTools = false,\n): BetaTool[] {\n\tif (!tools) return [];\n\n\treturn tools.map((tool, index) => {\n\t\tconst strict =\n\t\t\tdisablePreferredStrictTools && prefersJsonSchemaStrictSampling(tool)\n\t\t\t\t? undefined\n\t\t\t\t: resolveJsonSchemaStrictSampling(tool, supportsStrictTools, ANTHROPIC_STRICT_JSON_SCHEMA_PROFILE);\n\t\tconst parameters = getJsonSchemaToolParameters(tool, strict, ANTHROPIC_STRICT_JSON_SCHEMA_PROFILE);\n\t\tconst schema = parameters as ToolSchemaObject;\n\t\t// Anthropic rejects top-level combinators, so project object-union fields for advertising only.\n\t\t// Local runtime validation still enforces the complete authored union without mutating it.\n\t\tconst projectedUnion = projectObjectUnionForAnthropic(schema);\n\t\tconst legacyInputSchema = {\n\t\t\ttype: \"object\" as const,\n\t\t\tproperties: projectedUnion?.properties ?? schema.properties ?? {},\n\t\t\trequired: projectedUnion?.required ?? schema.required ?? [],\n\t\t\t// Keep shared definitions so property $refs still resolve. Other root keywords stay out:\n\t\t\t// Anthropic rejects root anyOf/oneOf/allOf with a 400.\n\t\t\t...(schema.$defs === undefined ? {} : { $defs: schema.$defs }),\n\t\t\t...(schema.definitions === undefined ? {} : { definitions: schema.definitions }),\n\t\t};\n\t\tconst inputSchema =\n\t\t\tstrict === true && projectedUnion === undefined\n\t\t\t\t? {\n\t\t\t\t\t\t...(parameters as Record<string, unknown>),\n\t\t\t\t\t\t...legacyInputSchema,\n\t\t\t\t\t}\n\t\t\t\t: legacyInputSchema;\n\n\t\treturn {\n\t\t\tname: isOAuthToken ? toClaudeCodeName(tool.name) : tool.name,\n\t\t\tdescription: tool.description,\n\t\t\t...(supportsEagerToolInputStreaming ? { eager_input_streaming: true } : {}),\n\t\t\t...(strict === true ? { strict: true } : {}),\n\t\t\tinput_schema: inputSchema,\n\t\t\t...(cacheControl && index === tools.length - 1 ? { cache_control: cacheControl } : {}),\n\t\t};\n\t});\n}\n\nfunction mapStopReason(\n\treason: Anthropic.Messages.StopReason | string,\n\tstopDetails?: RefusalStopDetails | null,\n): { stopReason: StopReason; errorMessage?: string } {\n\tswitch (reason) {\n\t\tcase \"end_turn\":\n\t\t\treturn { stopReason: \"stop\" };\n\t\tcase \"max_tokens\":\n\t\t\treturn { stopReason: \"length\" };\n\t\tcase \"tool_use\":\n\t\t\treturn { stopReason: \"toolUse\" };\n\t\tcase \"refusal\":\n\t\t\treturn {\n\t\t\t\tstopReason: \"error\",\n\t\t\t\terrorMessage: stopDetails?.explanation || `The model refused to complete the request`,\n\t\t\t};\n\t\tcase \"pause_turn\": // Stop is good enough -> resubmit\n\t\t\treturn { stopReason: \"stop\" };\n\t\tcase \"stop_sequence\":\n\t\t\treturn { stopReason: \"stop\" }; // We don't supply stop sequences, so this should never happen\n\t\tcase \"sensitive\": // Content flagged by safety filters (not yet in SDK types)\n\t\t\treturn { stopReason: \"error\", errorMessage: \"Provider stopped with: sensitive\" };\n\t\tdefault:\n\t\t\t// Handle unknown stop reasons gracefully (API may add new values)\n\t\t\tthrow new Error(`Unhandled stop reason: ${reason}`);\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"anthropic-messages.js","sourceRoot":"","sources":["../../src/api/anthropic-messages.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,EAAE,EAAuC,MAAM,mBAAmB,CAAC;AAUnF,OAAO,EACN,gCAAgC,EAChC,iCAAiC,EACjC,6BAA6B,EAC7B,gCAAgC,EAChC,0BAA0B,GAC1B,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC7C,OAAO,EAAE,0BAA0B,EAAE,MAAM,uCAAuC,CAAC;AACnF,OAAO,EAAE,0BAA0B,EAAE,MAAM,+CAA+C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AAC,YAAY,IAAI,KAAK,KAAK,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,aAAa,EAAE,YAAY,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SACtF,CAAC;IACH,CAAC,CAAC,CAAC;AACJ,CAAC;AAED,SAAS,aAAa,CACrB,MAA8C,EAC9C,WAAuC;IAEvC,QAAQ,MAAM,EAAE,CAAC;QAChB,KAAK,UAAU;YACd,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,CAAC;QAC/B,KAAK,YAAY;YAChB,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,CAAC;QACjC,KAAK,UAAU;YACd,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,CAAC;QAClC,KAAK,SAAS;YACb,OAAO;gBACN,UAAU,EAAE,OAAO;gBACnB,YAAY,EAAE,WAAW,EAAE,WAAW,IAAI,2CAA2C;aACrF,CAAC;QACH,KAAK,YAAY,EAAE,kCAAkC;YACpD,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,CAAC;QAC/B,KAAK,eAAe;YACnB,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,CAAC,CAAC,8DAA8D;QAC9F,KAAK,WAAW,EAAE,2DAA2D;YAC5E,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,YAAY,EAAE,kCAAkC,EAAE,CAAC;QAClF;YACC,kEAAkE;YAClE,MAAM,IAAI,KAAK,CAAC,0BAA0B,MAAM,EAAE,CAAC,CAAC;IACtD,CAAC;AACF,CAAC","sourcesContent":["import Anthropic, { type ClientOptions, type Middleware } from \"@anthropic-ai/sdk\";\nimport type {\n\tBetaTool,\n\tBetaCacheControlEphemeral as CacheControlEphemeral,\n\tBetaContentBlockParam as ContentBlockParam,\n\tMessageCreateParamsStreaming,\n\tBetaMessageParam as MessageParam,\n} from \"@anthropic-ai/sdk/resources/beta/messages/messages.js\";\nimport type { RawMessageStreamEvent, RefusalStopDetails } from \"@anthropic-ai/sdk/resources/messages.js\";\nimport type { ErrorType } from \"@anthropic-ai/sdk/resources/shared.js\";\nimport {\n\tANTHROPIC_FEDERATION_RULE_ID_ENV,\n\tANTHROPIC_IDENTITY_TOKEN_FILE_ENV,\n\tANTHROPIC_ORGANIZATION_ID_ENV,\n\tANTHROPIC_SERVICE_ACCOUNT_ID_ENV,\n\tANTHROPIC_WORKSPACE_ID_ENV,\n} from \"../env-api-keys.ts\";\nimport { calculateCost } from \"../models.ts\";\nimport { recordGitHubCopilotFailure } from \"../providers/github-copilot-errors.ts\";\nimport { GitHubCopilotStreamAttempt } from \"../providers/github-copilot-stream-attempt.ts\";\nimport { registerSessionResourceCleanup } from \"../session-resources.ts\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tCacheRetention,\n\tImageContent,\n\tMessage,\n\tModel,\n\tProviderEnv,\n\tProviderHeaders,\n\tSimpleStreamOptions,\n\tStopReason,\n\tStreamFunction,\n\tStreamOptions,\n\tTextContent,\n\tThinkingLevel,\n\tTool,\n\tToolResultMessage,\n\tUsage,\n} from \"../types.ts\";\nimport { raceWithAbortSignal } from \"../utils/abort.js\";\nimport { appendAssistantMessageDiagnostic } from \"../utils/diagnostics.ts\";\nimport { assertSupportedDocumentMimeType } from \"../utils/document-input.ts\";\nimport { withCauseDetail } from \"../utils/error-body.ts\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.ts\";\nimport { shortHash } from \"../utils/hash.ts\";\nimport { headersToRecord } from \"../utils/headers.ts\";\nimport { type ClientIdentity, getIdentityHeaders } from \"../utils/identity.ts\";\nimport { parseJsonWithRepair } from \"../utils/json-parse.ts\";\nimport {\n\tapplyOpenRouterReportedCost,\n\tisOpenRouterModel,\n\ttype OpenRouterUsageAccounting,\n} from \"../utils/openrouter-cost.ts\";\nimport { getProviderEnvValue } from \"../utils/provider-env.ts\";\nimport { retryProviderRequest } from \"../utils/provider-retry.ts\";\nimport { getFetchAdmission } from \"../utils/request-admission.js\";\nimport { getProviderRetryAfterMs } from \"../utils/retry-hints.ts\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.ts\";\nimport { createStreamDeadline, withStreamDeadline } from \"../utils/stream-deadline.ts\";\nimport { ToolCallArgumentsStream } from \"../utils/streaming-json.ts\";\nimport { getSystemMessageText, renderSystemMessageUpdate } from \"../utils/text.ts\";\nimport { appendThinkingOffFallbackDiagnostic, getThinkingOffFallbackLevel } from \"../utils/thinking-off.ts\";\nimport {\n\tgetCurrentTools,\n\tgetInitialSystemMessage,\n\tresolveTranscript,\n\ttype TranscriptContext,\n} from \"../utils/transcript.ts\";\nimport { convertAnthropicAssistantContent } from \"./anthropic-assistant-content.ts\";\nimport {\n\tANTHROPIC_STRICT_JSON_SCHEMA_PROFILE,\n\tgetJsonSchemaToolParameters,\n\tprefersJsonSchemaStrictSampling,\n\tresolveJsonSchemaStrictSampling,\n} from \"./constrained-sampling.ts\";\nimport {\n\tbuildCopilotDynamicHeaders,\n\thasCopilotVisionInput,\n\tpreserveCopilotIntegrationHeader,\n} from \"./github-copilot-headers.ts\";\nimport { adjustMaxTokensForThinking, buildBaseOptions, clampMaxTokensToContext } from \"./simple-options.ts\";\nimport {\n\thasExceededStrictToolLimits,\n\tisStrictToolLimitErrorMessage,\n\tmarkStrictToolLimitsExceeded,\n} from \"./strict-tool-limits.ts\";\nimport { splitErrorToolResultImages, transformMessages } from \"./transform-messages.ts\";\n\n/**\n * Resolve cache retention preference.\n * Defaults to \"short\" and uses PI_CACHE_RETENTION for backward compatibility.\n */\nfunction resolveCacheRetention(cacheRetention?: CacheRetention, env?: ProviderEnv): CacheRetention {\n\tif (cacheRetention) {\n\t\treturn cacheRetention;\n\t}\n\tif (getProviderEnvValue(\"PI_CACHE_RETENTION\", env) === \"long\") {\n\t\treturn \"long\";\n\t}\n\treturn \"short\";\n}\n\nfunction getCacheControl(\n\tmodel: Model<\"anthropic-messages\">,\n\tcacheRetention?: CacheRetention,\n\tenv?: ProviderEnv,\n): { retention: CacheRetention; cacheControl?: CacheControlEphemeral } {\n\tconst retention = resolveCacheRetention(cacheRetention, env);\n\tif (retention === \"none\") {\n\t\treturn { retention };\n\t}\n\tconst ttl = retention === \"long\" && getAnthropicCompat(model).supportsLongCacheRetention ? \"1h\" : undefined;\n\treturn {\n\t\tretention,\n\t\tcacheControl: { type: \"ephemeral\", ...(ttl && { ttl }) },\n\t};\n}\n\n// Stealth mode: Mimic Claude Code's tool naming exactly\n//\n// Anthropic gates newer models on the `claude-cli/<version>` user agent alone and rejects an\n// older one with `claude_code_version_too_old`. `claude-fable-5-1` requires >= 2.1.251 (bisected\n// against the live API: 2.1.250 -> 400, 2.1.251 -> 200) and Claude Opus 5.5 requires >= 2.1.280,\n// the floor the API names in its rejection. This is pinned to the highest published minimum\n// among shipped models rather than the newest release; every model this provider ships answers\n// 200 at 2.1.280. Raise it only when a model rejects this value; a caller can override it for\n// one client through the `headers` option, whose lowercase `user-agent` key is merged last.\nconst claudeCodeVersion = \"2.1.280\";\n\n// Claude Code 2.x tool names (canonical casing)\n// Source: https://cchistory.mariozechner.at/data/prompts-2.1.11.md\n// To update: https://github.com/badlogic/cchistory\nconst claudeCodeTools = [\n\t\"Read\",\n\t\"Write\",\n\t\"Edit\",\n\t\"Bash\",\n\t\"Grep\",\n\t\"Glob\",\n\t\"AskUserQuestion\",\n\t\"EnterPlanMode\",\n\t\"ExitPlanMode\",\n\t\"KillShell\",\n\t\"NotebookEdit\",\n\t\"Skill\",\n\t\"Task\",\n\t\"TaskOutput\",\n\t\"TodoWrite\",\n\t\"WebFetch\",\n\t\"WebSearch\",\n];\n\nconst ccToolLookup = new Map(claudeCodeTools.map((t) => [t.toLowerCase(), t]));\n\n// Convert tool name to CC canonical casing if it matches (case-insensitive)\nconst toClaudeCodeName = (name: string) => ccToolLookup.get(name.toLowerCase()) ?? name;\nconst fromClaudeCodeName = (name: string, tools?: Tool[]) => {\n\tif (tools && tools.length > 0) {\n\t\tconst lowerName = name.toLowerCase();\n\t\tconst matchedTool = tools.find((tool) => tool.name.toLowerCase() === lowerName);\n\t\tif (matchedTool) return matchedTool.name;\n\t}\n\treturn name;\n};\n\nfunction convertImageBlock(image: ImageContent) {\n\treturn {\n\t\ttype: \"image\" as const,\n\t\tsource: {\n\t\t\ttype: \"base64\" as const,\n\t\t\tmedia_type: image.mimeType as \"image/jpeg\" | \"image/png\" | \"image/gif\" | \"image/webp\",\n\t\t\tdata: image.data,\n\t\t},\n\t};\n}\n\n/**\n * Convert tool-result content blocks to Anthropic API format.\n *\n * Tool results carry text and images only. `DocumentContent` appears exclusively in user\n * messages, which `convertMessages` serializes on its own path.\n */\nfunction convertContentBlocks(content: (TextContent | ImageContent)[]):\n\t| string\n\t| Array<\n\t\t\t| { type: \"text\"; text: string }\n\t\t\t| {\n\t\t\t\t\ttype: \"image\";\n\t\t\t\t\tsource: {\n\t\t\t\t\t\ttype: \"base64\";\n\t\t\t\t\t\tmedia_type: \"image/jpeg\" | \"image/png\" | \"image/gif\" | \"image/webp\";\n\t\t\t\t\t\tdata: string;\n\t\t\t\t\t};\n\t\t\t }\n\t > {\n\t// If only text blocks, return as concatenated string for simplicity\n\tconst hasImages = content.some((c) => c.type === \"image\");\n\tif (!hasImages) {\n\t\treturn sanitizeSurrogates(content.map((c) => (c as TextContent).text).join(\"\\n\"));\n\t}\n\n\t// If we have images, convert to content block array\n\tconst blocks = content.map((block) => {\n\t\tif (block.type === \"text\") {\n\t\t\treturn {\n\t\t\t\ttype: \"text\" as const,\n\t\t\t\ttext: sanitizeSurrogates(block.text),\n\t\t\t};\n\t\t}\n\t\treturn convertImageBlock(block);\n\t});\n\n\t// If only images (no text), add placeholder text block\n\tconst hasText = blocks.some((b) => b.type === \"text\");\n\tif (!hasText) {\n\t\tblocks.unshift({\n\t\t\ttype: \"text\" as const,\n\t\t\ttext: \"(see attached image)\",\n\t\t});\n\t}\n\n\treturn blocks;\n}\n\nexport type AnthropicEffort = \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n\nexport type AnthropicThinkingDisplay = \"summarized\" | \"omitted\";\n\nconst FINE_GRAINED_TOOL_STREAMING_BETA = \"fine-grained-tool-streaming-2025-05-14\";\nconst INTERLEAVED_THINKING_BETA = \"interleaved-thinking-2025-05-14\";\nconst SERVER_SIDE_FALLBACK_BETA = \"server-side-fallback-2026-07-01\";\nconst THINKING_BINDING_CONTROLS_BETA = \"thinking-binding-controls-2026-08-01\";\nconst MID_CONVERSATION_OUTPUT_CONFIG_BETA = \"mid-conversation-output-config-2026-07-01\";\nconst INLINE_TOOLS_BETA = \"inline-tools-2026-09-15\";\nconst MESSAGE_THREADS_BETA = \"message-threads-2026-08-12\";\nconst FAST_MODE_BETA = \"fast-mode-2026-02-01\";\n\n/**\n * Fast mode bills every token category at twice the standard rate for each supported model, across\n * the full context window, and prompt-caching multipliers stack on top.\n * https://platform.claude.com/docs/en/build-with-claude/fast-mode#pricing\n */\nconst FAST_MODE_PRICE_MULTIPLIER = 2;\n\ntype AnthropicSpeed = \"standard\" | \"fast\";\n\nfunction requestedSpeed(model: Pick<Model<\"anthropic-messages\">, \"fastRoute\">): AnthropicSpeed | undefined {\n\treturn model.fastRoute?.speed;\n}\n\nfunction upstreamModelId(model: Pick<Model<\"anthropic-messages\">, \"fastRoute\" | \"id\">): string {\n\treturn model.fastRoute?.upstreamModelId ?? model.id;\n}\n\nfunction reportedSpeed(usage: unknown): AnthropicSpeed | undefined {\n\tconst speed = (usage as { speed?: unknown } | null | undefined)?.speed;\n\treturn speed === \"fast\" || speed === \"standard\" ? speed : undefined;\n}\n\nfunction applyFastModePricing(usage: Usage): void {\n\tusage.cost.input *= FAST_MODE_PRICE_MULTIPLIER;\n\tusage.cost.output *= FAST_MODE_PRICE_MULTIPLIER;\n\tusage.cost.cacheRead *= FAST_MODE_PRICE_MULTIPLIER;\n\tusage.cost.cacheWrite *= FAST_MODE_PRICE_MULTIPLIER;\n\tusage.cost.total = usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite;\n\tusage.cost.totalFromProvider = false;\n}\n\n/**\n * Reject a payload hook that rewrote a field the model's fast route owns.\n *\n * A fast variant is recorded, persisted, and billed under its own `-fast` identity, so a hook that\n * changes the upstream model or drops `speed: \"fast\"` would send a different request under that\n * identity. Refusing loudly surfaces the misconfigured hook instead of silently restoring the route.\n */\nfunction assertPayloadPreservesFastRoute(model: Model<\"anthropic-messages\">, payload: unknown): void {\n\tconst fastRoute = model.fastRoute;\n\tif (fastRoute?.speed === undefined) return;\n\tconst remedy =\n\t\t`A fast model variant must send its route's upstream model and speed, because it is recorded, persisted, ` +\n\t\t`and billed under its own identity. Select the normal model \"${model.provider}/${fastRoute.baseModelId}\" ` +\n\t\t`if the request needs different routing`;\n\tif (typeof payload !== \"object\" || payload === null || Array.isArray(payload)) {\n\t\tthrow new Error(\n\t\t\t`A request hook changed payload for fast model \"${model.provider}/${model.id}\" to a value that cannot carry ` +\n\t\t\t\t`the route's upstream model and speed. ${remedy}, or return an object that preserves those fields.`,\n\t\t);\n\t}\n\tconst record = payload as Record<string, unknown>;\n\tconst conflicts: string[] = [];\n\tif (record.model !== fastRoute.upstreamModelId) {\n\t\tconflicts.push(`model (expected \"${fastRoute.upstreamModelId}\", got ${JSON.stringify(record.model)})`);\n\t}\n\tif (record.speed !== fastRoute.speed) {\n\t\tconflicts.push(`speed (expected ${JSON.stringify(fastRoute.speed)}, got ${JSON.stringify(record.speed)})`);\n\t}\n\tif (conflicts.length === 0) return;\n\tthrow new Error(\n\t\t`A request hook changed ${conflicts.join(\" and \")} for fast model \"${model.provider}/${model.id}\". ` +\n\t\t\t`${remedy}, or stop rewriting those fields.`,\n\t);\n}\n\n/**\n * Stable deferred tool declared whenever native tool changes are in use. Anthropic adds\n * hidden prompt scaffolding for mid-conversation tool changes; declaring this placeholder\n * from the first request keeps that scaffolding in the cached prefix. It is never activated\n * and the model cannot see it.\n */\nconst DEFERRED_TOOL_PLACEHOLDER: BetaTool = {\n\tname: \"__pi_deferred_placeholder__\",\n\tdescription: \"Reserved placeholder. Never available. Never call this.\",\n\tinput_schema: { type: \"object\", properties: {}, required: [] },\n\tdefer_loading: true,\n};\n\nfunction shouldUseServerSideFallbackBeta(model: Model<\"anthropic-messages\">): boolean {\n\treturn (model.compat?.allowedFallbackModels?.length ?? 0) > 0;\n}\n\n/**\n * Claude Fable 5.1 binds each thinking block to the conversation prefix that produced it and,\n * for Anthropic accounts created on or after 2026-08-31, rejects a replay behind a changed\n * `system` prompt, `tools` array, or earlier message with a 400 `invalid_request_error`.\n * Atomic rebuilds those inputs between turns (dynamic system prompt, tool availability changes,\n * model switches), so it opts into `prefix_mismatch_behavior: \"drop_block\"`: the API discards\n * the affected thinking blocks and answers the turn instead of failing the session.\n *\n * This covers live prefix mismatches *between* compaction boundaries. It is not what handles\n * compaction itself: Atomic's client-side `preserve_recent` tail compaction serializes the\n * protected tail into a single boundary message, so no signed thinking block survives a\n * boundary to be replayed behind it. That is Anthropic's documented keep-tail remedy applied\n * structurally rather than a case `drop_block` has to catch.\n * https://platform.claude.com/docs/en/build-with-claude/preserved-thinking\n */\nfunction shouldUseThinkingBindingControlsBeta(model: Model<\"anthropic-messages\">): boolean {\n\treturn model.compat?.enforcesPreservedThinkingBinding === true;\n}\n\n/**\n * Per-turn effort and preserved-thinking binding are independent capabilities.\n * `supportsMidConvoEffort` adds provider effort markers and requires binding controls;\n * Atomic's older `enforcesPreservedThinkingBinding` remains the broader opt-in for\n * transports that need drop recovery without supporting effort-only system messages.\n */\nfunction supportsMidConvoEffort(model: Model<\"anthropic-messages\">): boolean {\n\treturn model.compat?.supportsMidConvoEffort === true;\n}\n\n/** One entry of the `input_transformations` array the block-binding controls beta adds. */\ninterface AnthropicInputTransformation {\n\ttype?: string;\n\tpath?: string;\n\treason?: string;\n}\n\nfunction getInputTransformations(message: unknown): AnthropicInputTransformation[] | undefined {\n\tconst transformations = (message as { input_transformations?: AnthropicInputTransformation[] })\n\t\t?.input_transformations;\n\treturn Array.isArray(transformations) ? transformations : undefined;\n}\n\n/** Record thinking blocks the API dropped from this request without exposing block contents. */\nfunction recordInputTransformations(output: AssistantMessage, transformations: AnthropicInputTransformation[]): void {\n\tif (transformations.length === 0) return;\n\tappendAssistantMessageDiagnostic(output, {\n\t\ttype: \"anthropic_input_transformations\",\n\t\ttimestamp: Date.now(),\n\t\tdetails: {\n\t\t\tdroppedBlockCount: transformations.length,\n\t\t\treasons: [...new Set(transformations.map((entry) => entry.reason).filter((r): r is string => !!r))],\n\t\t\tpaths: transformations.map((entry) => entry.path).filter((p): p is string => !!p),\n\t\t},\n\t});\n}\n\n/** One entry of the per-attempt `usage.iterations` array a server-side fallback response carries. */\ninterface AnthropicUsageIteration {\n\ttype?: string;\n\tmodel?: string;\n\tinput_tokens?: number;\n\toutput_tokens?: number;\n\tcache_read_input_tokens?: number;\n\t/** The aggregate cache-write count. `cache_creation` splits the same tokens by TTL. */\n\tcache_creation_input_tokens?: number;\n\t/** \"Breakdown of cached tokens by TTL\", per `BetaMessageIterationUsage`. */\n\tcache_creation?: { ephemeral_1h_input_tokens?: number; ephemeral_5m_input_tokens?: number } | null;\n}\n\n/**\n * Bill the attempts that ran *before* the one which produced the returned message.\n *\n * \"Every attempt that produced output, including one that declined partway through its response,\n * is billed separately at the rates of the model that ran it. The `usage.iterations` array is the\n * per-attempt record of what you're billed. The top-level `usage` counts describe only the attempt\n * that produced the returned message. Tokens from different models are never summed into one\n * field.\" https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback\n *\n * Two rules follow, and both matter for not double-counting:\n *\n * - Only `type: \"message\"` entries are added. The `fallback_message` entry *is* the serving\n * attempt, and its tokens are already in the top-level usage that `calculateCost` just priced.\n * - Only entries with output are added: \"An attempt that declined before producing any output is\n * not billed: its tokens are reported on its `usage.iterations` entry but not charged.\"\n *\n * Token counts are deliberately left alone — the docs forbid summing across models and `Usage` has\n * no per-attempt shape — so this contributes to `usage.cost` only.\n */\nfunction addEarlierAttemptCosts(\n\toutput: AssistantMessage,\n\tmodel: Model<\"anthropic-messages\">,\n\tservingModel: Model<\"anthropic-messages\">,\n\tevent: unknown,\n): void {\n\tconst iterations = (event as { usage?: { iterations?: AnthropicUsageIteration[] } })?.usage?.iterations;\n\tif (!Array.isArray(iterations) || iterations.length === 0) return;\n\n\tfor (const iteration of iterations) {\n\t\tif (iteration.type !== \"message\") continue;\n\t\tif (!iteration.output_tokens) continue;\n\n\t\t// Price at the rates of the model that ran the attempt, which is not the serving model.\n\t\tconst attemptCost =\n\t\t\titeration.model === upstreamModelId(model)\n\t\t\t\t? model.cost\n\t\t\t\t: iteration.model === servingModel.id\n\t\t\t\t\t? servingModel.cost\n\t\t\t\t\t: model.compat?.allowedFallbackModels?.find(\n\t\t\t\t\t\t\t(fallback) => fallback.provider === model.provider && fallback.model === iteration.model,\n\t\t\t\t\t\t)?.cost;\n\t\tif (!attemptCost) continue;\n\n\t\tconst attemptUsage: Usage = {\n\t\t\tinput: iteration.input_tokens ?? 0,\n\t\t\toutput: iteration.output_tokens,\n\t\t\tcacheRead: iteration.cache_read_input_tokens ?? 0,\n\t\t\t// `cacheWrite` stays the aggregate: `calculateCost` derives the 5-minute share by\n\t\t\t// subtracting `cacheWrite1h` from it, so setting this to the 5-minute count instead\n\t\t\t// would under-charge and adding the two together would double-charge. Without the 1h\n\t\t\t// split, an hour-long write bills at the 5-minute rate rather than 2x base input.\n\t\t\tcacheWrite: iteration.cache_creation_input_tokens ?? 0,\n\t\t\tcacheWrite1h: iteration.cache_creation?.ephemeral_1h_input_tokens ?? 0,\n\t\t\ttotalTokens: 0,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t};\n\t\tcalculateCost({ ...model, id: iteration.model ?? model.id, cost: attemptCost }, attemptUsage);\n\n\t\toutput.usage.cost.input += attemptUsage.cost.input;\n\t\toutput.usage.cost.output += attemptUsage.cost.output;\n\t\toutput.usage.cost.cacheRead += attemptUsage.cost.cacheRead;\n\t\toutput.usage.cost.cacheWrite += attemptUsage.cost.cacheWrite;\n\t\toutput.usage.cost.total += attemptUsage.cost.total;\n\t\toutput.usage.cost.totalFromProvider = false;\n\t}\n}\n\nfunction getAnthropicCompat(model: Model<\"anthropic-messages\">) {\n\tconst isOpenRouter = model.provider === \"openrouter\" || model.baseUrl.includes(\"openrouter.ai\");\n\treturn {\n\t\tsupportsEagerToolInputStreaming: model.compat?.supportsEagerToolInputStreaming ?? true,\n\t\tsupportsLongCacheRetention: model.compat?.supportsLongCacheRetention ?? true,\n\t\tsendSessionAffinityHeaders: model.compat?.sendSessionAffinityHeaders ?? isOpenRouter,\n\t\tsessionAffinityFormat: model.compat?.sessionAffinityFormat ?? (isOpenRouter ? \"openrouter\" : undefined),\n\t\tsupportsCacheControlOnTools: model.compat?.supportsCacheControlOnTools ?? true,\n\t\tsupportsTemperature: model.compat?.supportsTemperature ?? true,\n\t\tallowEmptySignature: model.compat?.allowEmptySignature ?? false,\n\t\tsupportsStrictTools: model.compat?.supportsStrictTools ?? false,\n\t\tsupportsMidConvoSystemMessages: model.compat?.supportsMidConvoSystemMessages ?? false,\n\t\tsupportsMidConvoToolChanges: model.compat?.supportsMidConvoToolChanges ?? false,\n\t\t// Gateways that drop unknown request fields would silently turn a `continue` into a request\n\t\t// without the earlier conversation, so the default is limited to the `anthropic` provider on\n\t\t// Anthropic's own host. Copilot's endpoint does not accept the threads beta.\n\t\tsupportsMessageThreads:\n\t\t\tmodel.compat?.supportsMessageThreads ??\n\t\t\t(model.provider === \"anthropic\" && isAnthropicApiHost(model.baseUrl)),\n\t};\n}\n\n/** Whether `baseUrl` is Anthropic's own API host, compared by parsed hostname (not a substring). */\nfunction isAnthropicApiHost(baseUrl: string): boolean {\n\ttry {\n\t\treturn new URL(baseUrl).hostname === \"api.anthropic.com\";\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * Message threads (`message-threads-2026-08-12` beta): the server keeps the conversation of a\n * thread, so a request can continue from the previous reply and send only the new messages.\n * Atomic still builds the full request; `prepareThreadRequest()` compares it with the previous\n * request of the session and sends only the new part when nothing earlier changed.\n */\ntype ThreadParam = { type: \"create\" } | { type: \"continue\"; previous_message_id: string };\n\n/** The pinned SDK types do not include the `thread` request field yet. */\ntype ThreadedParams = MessageCreateParamsStreaming & { thread?: ThreadParam };\n\ninterface ThreadEntry {\n\t/** Number of messages in the last full request as sent plus the converted reply. */\n\tprefixCount: number;\n\t/** `hashThreadPrefix()` of the request's settings and those messages. */\n\tprefixHash: string;\n\t/** Id of the reply to continue from. */\n\treplyId: string;\n}\n\n/** Per session: where the next request can continue, or \"off\" after the endpoint rejected threads. */\nconst threadState = new Map<string, ThreadEntry | \"off\">();\nconst MAX_THREAD_STATE_ENTRIES = 10_000;\n\n/** Rejections of a `continue` that a new thread fixes: expired, raced, or a fixed setting changed. */\nconst NEW_THREAD_ERRORS: ReadonlySet<string> = new Set([\n\t\"thread_not_found\",\n\t\"thread_already_continued\",\n\t\"thread_continue_in_flight\",\n\t\"thread_fingerprint_mismatch\",\n]);\n\n/**\n * Sets a session's thread state, keeping at most `MAX_THREAD_STATE_ENTRIES` sessions.\n *\n * State is normally freed by `cleanupSessionResources(sessionId)` when a session ends. The cap\n * bounds memory for library users that never call it, for example a server passing a new\n * `sessionId` per conversation. Dropping the least recently updated session is cheap: its thread\n * has most likely expired on the server already, and otherwise its next request starts a new thread.\n */\nfunction setThreadState(sessionId: string, value: ThreadEntry | \"off\"): void {\n\t// Re-insert so Map order stays oldest-first for the cap.\n\tthreadState.delete(sessionId);\n\tthreadState.set(sessionId, value);\n\tif (threadState.size > MAX_THREAD_STATE_ENTRIES) {\n\t\tconst oldest = threadState.keys().next().value;\n\t\tif (oldest !== undefined) threadState.delete(oldest);\n\t}\n}\n\nregisterSessionResourceCleanup((sessionId) => {\n\tif (sessionId) threadState.delete(sessionId);\n\telse threadState.clear();\n});\n\n/**\n * Hash of everything a `continue` builds on: the settings that must stay the same within a thread\n * and the messages the server already holds.\n *\n * - Settings, as sent: the endpoint (a thread exists on one endpoint only) and the fixed request\n * fields. A `continue` omits `system` and `tools` and the server keeps the thread's own, so only\n * this check can notice a change to them, including their cache markers. The server rejects\n * changes to the other fields with `thread_fingerprint_mismatch`; checking them here saves that\n * rejected request. Atomic also checks the fast-mode `speed`.\n * - Messages, normalized so messages that mean the same to the API hash the same.\n */\nfunction hashThreadPrefix(\n\tmodel: Model<\"anthropic-messages\">,\n\tparams: MessageCreateParamsStreaming,\n\tmessages: readonly unknown[],\n): string {\n\tconst { system, tools, thinking, output_config, tool_choice, betas, fallbacks } = params;\n\tconst settings = JSON.stringify([\n\t\tmodel.provider,\n\t\tmodel.baseUrl,\n\t\tparams.model,\n\t\tsystem,\n\t\ttools,\n\t\tthinking,\n\t\toutput_config,\n\t\ttool_choice,\n\t\tbetas,\n\t\tfallbacks,\n\t\tparams.speed,\n\t]);\n\tconst conversation = JSON.stringify(messages.map(normalizeThreadMessage));\n\treturn shortHash(settings + conversation);\n}\n\n/**\n * Normalizes one message so messages that mean the same to the API compare equal. Only message and\n * content-block fields are touched; tool inputs and every other value compare exactly as sent.\n *\n * - Cache markers don't change what a message means, but they move: Atomic puts one on the newest\n * message, so the message that had it in the last request has none in this one.\n * - To attach that marker, the newest user message's string content is sent as one text block; the\n * next request sends the same message as a string: \"hi\" vs [{ type: \"text\", text: \"hi\" }]. The\n * same holds for a tool result's content.\n */\nfunction normalizeThreadMessage(message: unknown): unknown {\n\tif (message === null || typeof message !== \"object\") return message;\n\tconst { content, ...rest } = message as { content?: unknown };\n\treturn { ...rest, content: normalizeThreadContent(content) };\n}\n\nfunction normalizeThreadContent(content: unknown): unknown {\n\tif (typeof content === \"string\") return [{ type: \"text\", text: content }];\n\tif (!Array.isArray(content)) return content;\n\treturn content.map((block: unknown) => {\n\t\tif (block === null || typeof block !== \"object\") return block;\n\t\tconst { cache_control: _cacheControl, ...rest } = block as { cache_control?: unknown; type?: unknown };\n\t\tif (rest.type !== \"tool_result\") return rest;\n\t\tconst toolResult = rest as { content?: unknown };\n\t\treturn { ...toolResult, content: normalizeThreadContent(toolResult.content) };\n\t});\n}\n\ninterface PreparedThreadRequest {\n\tsessionId: string;\n\tbody: ThreadedParams;\n}\n\nfunction createThreadRequest(sessionId: string, params: MessageCreateParamsStreaming): PreparedThreadRequest {\n\treturn { sessionId, body: { ...params, thread: { type: \"create\" } } };\n}\n\nfunction prepareThreadRequest(\n\tmodel: Model<\"anthropic-messages\">,\n\tsessionId: string,\n\tparams: MessageCreateParamsStreaming,\n): PreparedThreadRequest | undefined {\n\tconst state = threadState.get(sessionId);\n\tif (state === \"off\") return undefined;\n\tif (\n\t\tstate !== undefined &&\n\t\tparams.messages.length > state.prefixCount &&\n\t\thashThreadPrefix(model, params, params.messages.slice(0, state.prefixCount)) === state.prefixHash\n\t) {\n\t\t// Each reply can be continued once; deleting also keeps a concurrent request from trying.\n\t\tthreadState.delete(sessionId);\n\t\tconst { system: _system, tools: _tools, ...rest } = params;\n\t\treturn {\n\t\t\tbody: {\n\t\t\t\t...rest,\n\t\t\t\tmessages: params.messages.slice(state.prefixCount),\n\t\t\t\tthread: { type: \"continue\", previous_message_id: state.replyId },\n\t\t\t},\n\t\t\tsessionId,\n\t\t};\n\t}\n\treturn createThreadRequest(sessionId, params);\n}\n\n/** The `error_code` Anthropic puts in `error.details` of thread rejections. */\nfunction getThreadErrorCode(error: InstanceType<typeof Anthropic.APIError>): string | undefined {\n\tconst body = error.error as { error?: { details?: { error_code?: unknown } } } | undefined;\n\tconst code = body?.error?.details?.error_code;\n\treturn typeof code === \"string\" ? code : undefined;\n}\n\n/**\n * Sends a thread request. A rejection about the thread (never a started stream) is resent once in\n * full: as a new thread when the old one can't be continued, or without `thread` when the endpoint\n * can't use threads, which also turns threads off for the session. Other errors are passed on.\n * Returns the response and the thread request that produced it, if any.\n */\nasync function sendThreadRequest(\n\tthread: PreparedThreadRequest,\n\tparams: MessageCreateParamsStreaming,\n\tsend: (body: ThreadedParams) => Promise<Response>,\n\toutput: AssistantMessage,\n\tsignal: AbortSignal | undefined,\n): Promise<{ response: Response; thread: PreparedThreadRequest | undefined }> {\n\ttry {\n\t\treturn { response: await send(thread.body), thread };\n\t} catch (error) {\n\t\tif (signal?.aborted || !(error instanceof Anthropic.APIError)) throw error;\n\t\tconst errorCode = getThreadErrorCode(error);\n\t\tconst startNewThread = errorCode !== undefined && NEW_THREAD_ERRORS.has(errorCode);\n\t\t// The endpoint can't use threads: it can't thread this request, or it doesn't know the\n\t\t// `thread` field and rejects it without a code (\"thread: Extra inputs are not permitted\"),\n\t\t// e.g. with an `anthropic-beta` header that lacks the threads beta.\n\t\tconst threadsUnsupported =\n\t\t\terrorCode === \"thread_unsupported_request\" ||\n\t\t\t(errorCode === undefined && error.status === 400 && error.message.includes(\"thread\"));\n\t\t// Any other error (prompt too long, unknown model, strict tool limits, ...) is not about the\n\t\t// thread, and resending would only fail again.\n\t\tif (!startNewThread && !threadsUnsupported) throw error;\n\t\t// Recorded before the resend, so a failed resend keeps it.\n\t\tappendAssistantMessageDiagnostic(output, {\n\t\t\ttype: \"anthropic_thread_fallback\",\n\t\t\ttimestamp: Date.now(),\n\t\t\terror: { message: error.message },\n\t\t\tdetails: { reason: errorCode ?? String(error.status) },\n\t\t});\n\t\tif (startNewThread) {\n\t\t\tconst created = createThreadRequest(thread.sessionId, params);\n\t\t\treturn { response: await send(created.body), thread: created };\n\t\t}\n\t\t// With the threads beta, a request without `thread` is a normal request.\n\t\tconst response = await send(params);\n\t\tsetThreadState(thread.sessionId, \"off\");\n\t\treturn { response, thread: undefined };\n\t}\n}\n\n/**\n * Records where the session's next request can continue: after `output`, the clean reply to the\n * thread request `thread`, whose full request was `params`.\n */\nfunction recordThreadReply(\n\tmodel: Model<\"anthropic-messages\">,\n\tthread: PreparedThreadRequest,\n\tparams: MessageCreateParamsStreaming,\n\toutput: AssistantMessage,\n\tisOAuth: boolean,\n\tallowEmptySignature: boolean,\n): void {\n\t// `responseModel` is set only when another model answered (server-side fallback); the server\n\t// does not store those replies, so they cannot be continued.\n\tif (output.responseId === undefined || output.responseModel !== undefined) return;\n\t// Convert the reply like the next request will, keeping only the assistant message\n\t// (transformMessages adds placeholder results for trailing tool calls).\n\tconst reply = convertMessages(\n\t\ttransformMessages([output], model, normalizeToolCallId),\n\t\tisOAuth,\n\t\tundefined,\n\t\tallowEmptySignature,\n\t).messages.filter((message) => message.role === \"assistant\");\n\tconst prefix = [...params.messages, ...reply];\n\tsetThreadState(thread.sessionId, {\n\t\tprefixCount: prefix.length,\n\t\tprefixHash: hashThreadPrefix(model, params, prefix),\n\t\treplyId: output.responseId,\n\t});\n}\n\nexport interface AnthropicOptions extends StreamOptions {\n\t/**\n\t * Enable extended thinking.\n\t * For adaptive thinking models: the model decides when/how much to think.\n\t * For older models: uses budget-based thinking with thinkingBudgetTokens.\n\t * Default: undefined (thinking is omitted unless `streamSimple()` maps\n\t * a simple reasoning level to this option, or callers set it explicitly).\n\t */\n\tthinkingEnabled?: boolean;\n\t/**\n\t * Token budget for extended thinking (older models only).\n\t * Ignored for adaptive thinking models.\n\t * Default: 1024 when `thinkingEnabled` is true and no budget is provided.\n\t */\n\tthinkingBudgetTokens?: number;\n\t/**\n\t * Effort level for adaptive thinking models.\n\t * Controls how much thinking Claude allocates:\n\t * - \"max\": Always thinks with no constraints (Opus 4.6 only)\n\t * - \"xhigh\": Highest reasoning level (Opus 4.7+, Fable 5)\n\t * - \"high\": Always thinks, deep reasoning\n\t * - \"medium\": Moderate thinking, may skip for simple queries\n\t * - \"low\": Minimal thinking, skips for simple tasks\n\t * Ignored for older models.\n\t * Default: omitted unless `streamSimple()` maps a simple reasoning\n\t * level to this option.\n\t */\n\teffort?: AnthropicEffort;\n\t/**\n\t * Controls how thinking content is returned in API responses.\n\t * - \"summarized\": Thinking blocks contain summarized thinking text.\n\t * - \"omitted\": Thinking blocks return an empty thinking field; the encrypted\n\t * signature still travels back for multi-turn continuity. Use for faster\n\t * time-to-first-text-token when your UI does not surface thinking.\n\t *\n\t * Note: Anthropic's API default for Claude Opus 4.7 and Claude Mythos Preview\n\t * is \"omitted\". We default to \"summarized\" here to keep behavior consistent\n\t * with older Claude 4 models. Set this explicitly to \"omitted\" to opt in.\n\t * Default: \"summarized\" when thinking is enabled.\n\t */\n\tthinkingDisplay?: AnthropicThinkingDisplay;\n\t/**\n\t * Whether to request the interleaved thinking beta header for non-adaptive\n\t * thinking models. Adaptive thinking models have interleaved thinking built in,\n\t * so the header is skipped for them regardless of this setting.\n\t * Default: true.\n\t */\n\tinterleavedThinking?: boolean;\n\t/**\n\t * Anthropic tool choice behavior. String values map to Anthropic's built-in\n\t * choices; `{ type: \"tool\", name }` forces a specific tool.\n\t * Default: omitted (Anthropic default behavior, currently equivalent to auto).\n\t */\n\ttoolChoice?: \"auto\" | \"any\" | \"none\" | { type: \"tool\"; name: string };\n\t/**\n\t * Pre-built Anthropic client instance. When provided, skips internal client\n\t * construction entirely. Use this to inject alternative SDK clients such as\n\t * `AnthropicVertex` that shares the same messaging API.\n\t */\n\tclient?: Anthropic;\n}\n\nfunction mergeHeaders(...headerSources: (ProviderHeaders | undefined)[]): ProviderHeaders {\n\tconst merged: ProviderHeaders = {};\n\tfor (const headers of headerSources) {\n\t\tif (headers) {\n\t\t\tObject.assign(merged, headers);\n\t\t}\n\t}\n\treturn merged;\n}\n\nfunction hasHeader(headers: ProviderHeaders | undefined, name: string): boolean {\n\tif (!headers) return false;\n\tconst expected = name.toLowerCase();\n\tfor (const [key, value] of Object.entries(headers)) {\n\t\tif (key.toLowerCase() === expected && value !== null && value.trim().length > 0) return true;\n\t}\n\treturn false;\n}\n\nfunction hasRequestAuth(apiKey: string | undefined, headers: ProviderHeaders | undefined): boolean {\n\treturn (\n\t\t!!apiKey ||\n\t\thasHeader(headers, \"authorization\") ||\n\t\thasHeader(headers, \"x-api-key\") ||\n\t\thasHeader(headers, \"cf-aig-authorization\")\n\t);\n}\n\nfunction assertRequestAuth(provider: string, apiKey: string | undefined, headers: ProviderHeaders | undefined): void {\n\tif (!hasRequestAuth(apiKey, headers)) throw new Error(`No API key for provider: ${provider}`);\n}\n\n/**\n * Anthropic SDK client that never runs the SDK's own credential chain\n * (ANTHROPIC_PROFILE config files, federation env vars). Without this, every\n * client built with `apiKey: null, authToken: null` for header-owned auth would\n * also resolve and exchange SDK credentials behind Atomic's auth resolver.\n */\nclass AtomicAnthropic extends Anthropic {\n\tprivate readonly admission: ReturnType<typeof getFetchAdmission>;\n\n\tconstructor(options: ClientOptions) {\n\t\tconst admission = getFetchAdmission(options.fetch);\n\t\tconst tokenAdmission: Middleware = async (request, next, context) => {\n\t\t\tif (!context.options) await admission?.beforeRequest(request.signal ?? undefined);\n\t\t\treturn next(request);\n\t\t};\n\t\tsuper({\n\t\t\t...options,\n\t\t\tfetch: admission?.fetch ?? options.fetch,\n\t\t\tmiddleware: admission ? [tokenAdmission, ...(options.middleware ?? [])] : options.middleware,\n\t\t});\n\t\tthis.admission = admission;\n\t}\n\n\tprotected override authHeaders(...args: Parameters<Anthropic[\"authHeaders\"]>): ReturnType<Anthropic[\"authHeaders\"]> {\n\t\tconst result = super.authHeaders(...args);\n\t\tconst signal = args[0].signal;\n\t\treturn signal ? raceWithAbortSignal(result, signal) : result;\n\t}\n\n\tprotected override async prepareRequest(...args: Parameters<Anthropic[\"prepareRequest\"]>): Promise<void> {\n\t\tawait super.prepareRequest(...args);\n\t\tawait this.admission?.beforeRequest(args[0].signal ?? undefined);\n\t}\n\tprotected override _shouldResolveDefaultCredentials(): boolean {\n\t\treturn false;\n\t}\n}\n\ntype AnthropicFederationConfig = NonNullable<ClientOptions[\"config\"]>;\n\n/**\n * Workload identity federation config from the ANTHROPIC_* variables the\n * Anthropic SDK documents; the SDK performs the token exchange and refresh.\n * Only for the anthropic provider, since the exchange is an Anthropic API\n * endpoint, and only when no key or auth header was resolved.\n */\nfunction getAnthropicFederation(\n\tmodel: Model<\"anthropic-messages\">,\n\tapiKey: string | undefined,\n\theaders: ProviderHeaders | undefined,\n\tenv: ProviderEnv | undefined,\n): AnthropicFederationConfig | undefined {\n\tif (model.provider !== \"anthropic\" || hasRequestAuth(apiKey, headers)) return undefined;\n\tconst federationRuleId = getProviderEnvValue(ANTHROPIC_FEDERATION_RULE_ID_ENV, env);\n\tconst organizationId = getProviderEnvValue(ANTHROPIC_ORGANIZATION_ID_ENV, env);\n\tconst identityTokenFile = getProviderEnvValue(ANTHROPIC_IDENTITY_TOKEN_FILE_ENV, env);\n\tif (!federationRuleId || !organizationId || !identityTokenFile) return undefined;\n\treturn {\n\t\torganization_id: organizationId,\n\t\tworkspace_id: getProviderEnvValue(ANTHROPIC_WORKSPACE_ID_ENV, env),\n\t\tauthentication: {\n\t\t\ttype: \"oidc_federation\",\n\t\t\tfederation_rule_id: federationRuleId,\n\t\t\tservice_account_id: getProviderEnvValue(ANTHROPIC_SERVICE_ACCOUNT_ID_ENV, env),\n\t\t\tidentity_token: { source: \"file\", path: identityTokenFile },\n\t\t},\n\t};\n}\n\n/**\n * The SDK caches the federated access token per client, but a client is created\n * per request. Keep one client for the current federation config and fetch, and\n * clone it per request with `withOptions()`, which shares the token cache.\n */\nlet federationClient: { key: string; fetch: typeof globalThis.fetch | undefined; client: Anthropic } | undefined;\n\ninterface ServerSentEvent {\n\tevent: string | null;\n\tdata: string;\n\traw: string[];\n}\n\ninterface SseDecoderState {\n\tevent: string | null;\n\tdata: string[];\n\traw: string[];\n}\n\nconst ANTHROPIC_MESSAGE_EVENTS: ReadonlySet<string> = new Set([\n\t\"message_start\",\n\t\"message_delta\",\n\t\"message_stop\",\n\t\"content_block_start\",\n\t\"content_block_delta\",\n\t\"content_block_stop\",\n]);\n\n/** The `ping` events Anthropic's streaming API sends to keep a quiet connection alive: activity, not message events. */\ninterface AnthropicPing {\n\treadonly type: \"ping\";\n}\n\nconst ANTHROPIC_PING: AnthropicPing = { type: \"ping\" };\n\nfunction isAnthropicPing(event: RawMessageStreamEvent | AnthropicPing): event is AnthropicPing {\n\treturn event.type === \"ping\";\n}\n\nfunction flushSseEvent(state: SseDecoderState): ServerSentEvent | null {\n\tif (!state.event && state.data.length === 0) {\n\t\treturn null;\n\t}\n\n\tconst event: ServerSentEvent = {\n\t\tevent: state.event,\n\t\tdata: state.data.join(\"\\n\"),\n\t\traw: [...state.raw],\n\t};\n\tstate.event = null;\n\tstate.data = [];\n\tstate.raw = [];\n\treturn event;\n}\n\nfunction decodeSseLine(line: string, state: SseDecoderState): ServerSentEvent | null {\n\tif (line === \"\") {\n\t\treturn flushSseEvent(state);\n\t}\n\n\tstate.raw.push(line);\n\tif (line.startsWith(\":\")) {\n\t\treturn null;\n\t}\n\n\tconst delimiterIndex = line.indexOf(\":\");\n\tconst fieldName = delimiterIndex === -1 ? line : line.slice(0, delimiterIndex);\n\tlet value = delimiterIndex === -1 ? \"\" : line.slice(delimiterIndex + 1);\n\tif (value.startsWith(\" \")) {\n\t\tvalue = value.slice(1);\n\t}\n\n\tif (fieldName === \"event\") {\n\t\tstate.event = value;\n\t} else if (fieldName === \"data\") {\n\t\tstate.data.push(value);\n\t}\n\n\treturn null;\n}\n\nfunction nextLineBreakIndex(text: string): number {\n\tconst carriageReturnIndex = text.indexOf(\"\\r\");\n\tconst newlineIndex = text.indexOf(\"\\n\");\n\tif (carriageReturnIndex === -1) {\n\t\treturn newlineIndex;\n\t}\n\tif (newlineIndex === -1) {\n\t\treturn carriageReturnIndex;\n\t}\n\treturn Math.min(carriageReturnIndex, newlineIndex);\n}\n\nfunction consumeLine(text: string): { line: string; rest: string } | null {\n\tconst lineBreakIndex = nextLineBreakIndex(text);\n\tif (lineBreakIndex === -1) {\n\t\treturn null;\n\t}\n\n\tlet nextIndex = lineBreakIndex + 1;\n\tif (text[lineBreakIndex] === \"\\r\" && text[nextIndex] === \"\\n\") {\n\t\tnextIndex += 1;\n\t}\n\n\treturn {\n\t\tline: text.slice(0, lineBreakIndex),\n\t\trest: text.slice(nextIndex),\n\t};\n}\n\nasync function* iterateSseMessages(\n\tbody: ReadableStream<Uint8Array>,\n\tsignal?: AbortSignal,\n): AsyncGenerator<ServerSentEvent> {\n\tconst reader = body.getReader();\n\tconst decoder = new TextDecoder();\n\tconst state: SseDecoderState = { event: null, data: [], raw: [] };\n\tlet buffer = \"\";\n\tconst onAbort = () => {\n\t\tvoid reader.cancel().catch(() => {});\n\t};\n\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\n\ttry {\n\t\twhile (true) {\n\t\t\tif (signal?.aborted) {\n\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t}\n\n\t\t\tconst { value, done } = await reader.read();\n\t\t\tif (done) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tbuffer += decoder.decode(value, { stream: true });\n\t\t\tlet consumed = consumeLine(buffer);\n\t\t\twhile (consumed) {\n\t\t\t\tbuffer = consumed.rest;\n\t\t\t\tconst event = decodeSseLine(consumed.line, state);\n\t\t\t\tif (event) {\n\t\t\t\t\tyield event;\n\t\t\t\t}\n\t\t\t\tconsumed = consumeLine(buffer);\n\t\t\t}\n\t\t}\n\n\t\tbuffer += decoder.decode();\n\t\tlet consumed = consumeLine(buffer);\n\t\twhile (consumed) {\n\t\t\tbuffer = consumed.rest;\n\t\t\tconst event = decodeSseLine(consumed.line, state);\n\t\t\tif (event) {\n\t\t\t\tyield event;\n\t\t\t}\n\t\t\tconsumed = consumeLine(buffer);\n\t\t}\n\n\t\tif (buffer.length > 0) {\n\t\t\tconst event = decodeSseLine(buffer, state);\n\t\t\tif (event) {\n\t\t\t\tyield event;\n\t\t\t}\n\t\t}\n\n\t\tconst trailingEvent = flushSseEvent(state);\n\t\tif (trailingEvent) {\n\t\t\tyield trailingEvent;\n\t\t}\n\t} finally {\n\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\ttry {\n\t\t\tawait reader.cancel();\n\t\t} catch {}\n\t\treader.releaseLock();\n\t}\n}\n\nfunction parseStreamedErrorBody(data: string): NonNullable<unknown> {\n\ttry {\n\t\treturn JSON.parse(data) ?? data;\n\t} catch {\n\t\treturn data;\n\t}\n}\n\nfunction streamedErrorType(body: NonNullable<unknown>): ErrorType | undefined {\n\tconst error = (body as { error?: unknown }).error;\n\tconst type = typeof error === \"object\" && error !== null ? (error as { type?: unknown }).type : undefined;\n\treturn typeof type === \"string\" ? (type as ErrorType) : undefined;\n}\n\nasync function* iterateAnthropicEvents(\n\tresponse: Response,\n\tsignal?: AbortSignal,\n): AsyncGenerator<RawMessageStreamEvent | AnthropicPing> {\n\tif (!response.body) {\n\t\tthrow new Error(\"Attempted to iterate over an Anthropic response with no body\");\n\t}\n\n\tlet sawMessageStart = false;\n\tlet sawMessageEnd = false;\n\n\tfor await (const sse of iterateSseMessages(response.body, signal)) {\n\t\tif (sse.event === \"error\") {\n\t\t\tconst body = parseStreamedErrorBody(sse.data);\n\t\t\tthrow new Anthropic.APIError(undefined, body, sse.data, response.headers, streamedErrorType(body));\n\t\t}\n\n\t\tif (sse.event === \"ping\") {\n\t\t\tyield ANTHROPIC_PING;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (!ANTHROPIC_MESSAGE_EVENTS.has(sse.event ?? \"\")) {\n\t\t\tcontinue;\n\t\t}\n\n\t\ttry {\n\t\t\tconst event = parseJsonWithRepair<RawMessageStreamEvent>(sse.data);\n\t\t\tif (event.type === \"message_start\") {\n\t\t\t\tsawMessageStart = true;\n\t\t\t} else if (event.type === \"message_stop\") {\n\t\t\t\tsawMessageEnd = true;\n\t\t\t}\n\t\t\tyield event;\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tthrow new Error(\n\t\t\t\t`Could not parse Anthropic SSE event ${sse.event}: ${message}; data=${sse.data}; raw=${sse.raw.join(\"\\\\n\")}`,\n\t\t\t);\n\t\t}\n\t}\n\n\tif (sawMessageStart && !sawMessageEnd) {\n\t\tthrow new Error(\"Anthropic stream ended before message_stop\");\n\t}\n}\n\nexport const stream: StreamFunction<\"anthropic-messages\", AnthropicOptions> = (\n\tmodel: Model<\"anthropic-messages\">,\n\tcontext: TranscriptContext,\n\toptions?: AnthropicOptions,\n): AssistantMessageEventStream => {\n\tconst stream = new AssistantMessageEventStream();\n\tconst compat = getAnthropicCompat(model);\n\tconst normalizedContext = resolveTranscript(context, compat.supportsMidConvoSystemMessages);\n\tconst currentTools = getCurrentTools(normalizedContext.messages);\n\n\t(async () => {\n\t\tconst output: AssistantMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [],\n\t\t\tapi: model.api as Api,\n\t\t\tprovider: model.provider,\n\t\t\tmodel: model.id,\n\t\t\tusage: {\n\t\t\t\tinput: 0,\n\t\t\t\toutput: 0,\n\t\t\t\tcacheRead: 0,\n\t\t\t\tcacheWrite: 0,\n\t\t\t\ttotalTokens: 0,\n\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t},\n\t\t\tstopReason: \"pending\",\n\t\t\ttimestamp: Date.now(),\n\t\t};\n\n\t\tconst streamDeadline = createStreamDeadline(options?.streamDeadlineMs, options?.signal);\n\t\tconst streamAttempt = new GitHubCopilotStreamAttempt();\n\n\t\tlet inputTransformations: AnthropicInputTransformation[] | undefined;\n\n\t\ttry {\n\t\t\tconst thinkingOffFallback = getAnthropicThinkingOffFallback(model, options);\n\t\t\tif (thinkingOffFallback) {\n\t\t\t\tappendThinkingOffFallbackDiagnostic(output, thinkingOffFallback.level, thinkingOffFallback.effort);\n\t\t\t}\n\t\t\tlet client: Anthropic;\n\t\t\tlet isOAuth: boolean;\n\t\t\tlet usageModel = model;\n\t\t\tlet servedSpeed = requestedSpeed(model);\n\t\t\tconst cacheRetention = resolveCacheRetention(options?.cacheRetention, options?.env);\n\t\t\tconst cacheSessionId = cacheRetention === \"none\" ? undefined : options?.sessionId;\n\t\t\t// Session whose requests may use message threads; undefined when threads don't apply. A\n\t\t\t// caller-supplied client carries its own `anthropic-beta` header, which Atomic cannot extend\n\t\t\t// with the threads beta, so it never uses threads. Sessions where the endpoint rejected threads\n\t\t\t// (\"off\") still send the threads beta, which the resend that turned them off was accepted\n\t\t\t// with; `prepareThreadRequest()` just sends no `thread`.\n\t\t\tconst threadSessionId = compat.supportsMessageThreads && !options?.client ? cacheSessionId : undefined;\n\n\t\t\tif (options?.client) {\n\t\t\t\tclient = options.client;\n\t\t\t\tisOAuth = false;\n\t\t\t} else {\n\t\t\t\tconst apiKey = options?.apiKey;\n\t\t\t\tconst federation = getAnthropicFederation(model, apiKey, options?.headers, options?.env);\n\t\t\t\tif (!federation) assertRequestAuth(model.provider, apiKey, options?.headers);\n\n\t\t\t\tlet copilotDynamicHeaders: Record<string, string> | undefined;\n\t\t\t\tif (model.provider === \"github-copilot\") {\n\t\t\t\t\tconst hasImages = hasCopilotVisionInput(normalizedContext.messages);\n\t\t\t\t\tcopilotDynamicHeaders = preserveCopilotIntegrationHeader(\n\t\t\t\t\t\tmodel.headers,\n\t\t\t\t\t\tbuildCopilotDynamicHeaders({\n\t\t\t\t\t\t\tmessages: normalizedContext.messages,\n\t\t\t\t\t\t\thasImages,\n\t\t\t\t\t\t\tapiKey,\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t}\n\n\n\t\t\t\tconst created = createClient(\n\t\t\t\t\tmodel,\n\t\t\t\t\tapiKey,\n\t\t\t\t\tmodel.reasoning && options?.thinkingEnabled === true && (options.interleavedThinking ?? true),\n\t\t\t\t\tshouldUseFineGrainedToolStreamingBeta(model, context),\n\t\t\t\t\tshouldUseServerSideFallbackBeta(model),\n\t\t\t\t\toptions?.headers,\n\t\t\t\t\toptions?.fetch,\n\t\t\t\t\tcopilotDynamicHeaders,\n\t\t\t\t\tcacheSessionId,\n\t\t\t\t\tcompat.supportsMidConvoToolChanges &&\n\t\t\t\t\t\tcompat.supportsMidConvoSystemMessages &&\n\t\t\t\t\t\t(getInitialSystemMessage(normalizedContext.messages)?.toolsAdded?.length ?? 0) > 0,\n\t\t\t\t\tfederation,\n\t\t\t\t\toptions?.identity,\n\t\t\t\t\tthreadSessionId !== undefined,\n\t\t\t\t);\n\t\t\t\tclient = created.client;\n\t\t\t\tisOAuth = created.isOAuthToken;\n\t\t\t}\n\t\t\tconst requestOptions = {\n\t\t\t\t...(streamDeadline.signal ? { signal: streamDeadline.signal } : {}),\n\t\t\t\t...(options?.timeoutMs !== undefined ? { timeout: options.timeoutMs } : {}),\n\t\t\t\tmaxRetries: 0,\n\t\t\t};\n\t\t\tconst send = (body: ThreadedParams) =>\n\t\t\t\tretryProviderRequest(\n\t\t\t\t\t() => {\n\t\t\t\t\t\tstreamAttempt.begin();\n\t\t\t\t\t\treturn client.beta.messages.create({ ...body, stream: true }, requestOptions).asResponse();\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tmaxRetries: options?.maxRetries,\n\t\t\t\t\t\tmaxRetryDelayMs: options?.maxRetryDelayMs,\n\t\t\t\t\t\tsignal: streamDeadline.signal,\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\tlet disablePreferredStrictTools = hasExceededStrictToolLimits(options?.sessionId);\n\t\t\tlet response: Response;\n\t\t\tlet params: MessageCreateParamsStreaming;\n\t\t\t// The thread request that produced the response; undefined when no `thread` was sent.\n\t\t\tlet thread: PreparedThreadRequest | undefined;\n\t\t\tfor (;;) {\n\t\t\t\tstreamDeadline.signal?.throwIfAborted();\n\t\t\t\tconst built = buildParams(model, normalizedContext, isOAuth, options, {\n\t\t\t\t\tdisablePreferredStrictTools,\n\t\t\t\t\tmessageThreads: threadSessionId !== undefined,\n\t\t\t\t});\n\t\t\t\tif (built.providerThinkingLevel) output.providerThinkingLevel = built.providerThinkingLevel;\n\t\t\t\tparams = built.params;\n\t\t\t\tconst nextParams = await options?.onPayload?.(params, model);\n\t\t\t\tif (nextParams !== undefined) params = nextParams as MessageCreateParamsStreaming;\n\t\t\t\tassertPayloadPreservesFastRoute(model, params);\n\t\t\t\tconst prepared =\n\t\t\t\t\tthreadSessionId !== undefined && options?.disableContinuation !== true\n\t\t\t\t\t\t? prepareThreadRequest(model, threadSessionId, params)\n\t\t\t\t\t\t: undefined;\n\t\t\t\ttry {\n\t\t\t\t\tconst sent = prepared\n\t\t\t\t\t\t? await sendThreadRequest(prepared, params, send, output, streamDeadline.signal)\n\t\t\t\t\t\t: { response: await send(params), thread: undefined };\n\t\t\t\t\tresponse = sent.response;\n\t\t\t\t\tthread = sent.thread;\n\t\t\t\t\tbreak;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (\n\t\t\t\t\t\tstreamDeadline.signal?.aborted ||\n\t\t\t\t\t\tdisablePreferredStrictTools ||\n\t\t\t\t\t\t!built.hasPreferredStrictTools ||\n\t\t\t\t\t\t!(error instanceof Anthropic.APIError) ||\n\t\t\t\t\t\terror.status !== 400 ||\n\t\t\t\t\t\terror.type !== \"invalid_request_error\" ||\n\t\t\t\t\t\t!isStrictToolLimitErrorMessage(error.message)\n\t\t\t\t\t)\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\tdisablePreferredStrictTools = true;\n\t\t\t\t\tmarkStrictToolLimitsExceeded(options?.sessionId);\n\t\t\t\t\tappendAssistantMessageDiagnostic(output, {\n\t\t\t\t\t\ttype: \"anthropic_strict_tools_fallback\",\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\terror: { message: error.message },\n\t\t\t\t\t\tdetails: { reason: \"strict_tool_limits_exceeded\" },\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\tawait options?.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model);\n\t\t\tstream.push({ type: \"start\", partial: output });\n\t\t\tstreamAttempt.respond(response.headers);\n\n\t\t\t// Stream state per Anthropic block index, kept off the content blocks so it never reaches partials.\n\t\t\tconst openBlocks = new Map<number, { contentIndex: number; arguments?: ToolCallArgumentsStream }>();\n\t\t\tconst openBlock = (anthropicIndex: number) => {\n\t\t\t\tconst open = openBlocks.get(anthropicIndex);\n\t\t\t\treturn open === undefined ? undefined : { ...open, block: output.content[open.contentIndex]! };\n\t\t\t};\n\n\t\t\tfor await (const event of streamAttempt.observe(\n\t\t\t\twithStreamDeadline(\n\t\t\t\t\titerateAnthropicEvents(response, streamDeadline.signal),\n\t\t\t\t\tstreamDeadline.deadlineMs,\n\t\t\t\t\tstreamDeadline.abort,\n\t\t\t\t\tisAnthropicPing,\n\t\t\t\t),\n\t\t\t)) {\n\t\t\t\tawait options?.onProviderStreamEvent?.(event, model);\n\t\t\t\tif (event.type === \"message_start\") {\n\t\t\t\t\toutput.responseId = event.message.id;\n\t\t\t\t\tconst responseModel = event.message.model;\n\t\t\t\t\tif (responseModel !== upstreamModelId(model)) output.responseModel = responseModel;\n\t\t\t\t\tconst fallbackCost =\n\t\t\t\t\t\tresponseModel === upstreamModelId(model)\n\t\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t\t: model.compat?.allowedFallbackModels?.find(\n\t\t\t\t\t\t\t\t\t(fallback) => fallback.provider === model.provider && fallback.model === responseModel,\n\t\t\t\t\t\t\t\t)?.cost;\n\t\t\t\t\tusageModel = fallbackCost ? { ...model, id: responseModel, cost: fallbackCost } : model;\n\t\t\t\t\t// Capture initial token usage from message_start event\n\t\t\t\t\t// This ensures we have input token counts even if the stream is aborted early\n\t\t\t\t\toutput.usage.input = event.message.usage.input_tokens || 0;\n\t\t\t\t\toutput.usage.output = event.message.usage.output_tokens || 0;\n\t\t\t\t\toutput.usage.cacheRead = event.message.usage.cache_read_input_tokens || 0;\n\t\t\t\t\toutput.usage.cacheWrite = event.message.usage.cache_creation_input_tokens || 0;\n\t\t\t\t\toutput.usage.cacheWrite1h = event.message.usage.cache_creation?.ephemeral_1h_input_tokens || 0;\n\t\t\t\t\t// Anthropic doesn't provide total_tokens, compute from components\n\t\t\t\t\toutput.usage.totalTokens =\n\t\t\t\t\t\toutput.usage.input + output.usage.output + output.usage.cacheRead + output.usage.cacheWrite;\n\t\t\t\t\tcalculateCost(usageModel, output.usage);\n\t\t\t\t\tservedSpeed = reportedSpeed(event.message.usage) ?? servedSpeed;\n\t\t\t\t\tif (servedSpeed === \"fast\") applyFastModePricing(output.usage);\n\t\t\t\t\tinputTransformations = getInputTransformations(event.message) ?? inputTransformations;\n\t\t\t\t} else if (event.type === \"content_block_start\") {\n\t\t\t\t\tif (event.content_block.type === \"text\") {\n\t\t\t\t\t\toutput.content.push({ type: \"text\", text: event.content_block.text ?? \"\" });\n\t\t\t\t\t\topenBlocks.set(event.index, { contentIndex: output.content.length - 1 });\n\t\t\t\t\t\tstream.push({ type: \"text_start\", contentIndex: output.content.length - 1, partial: output });\n\t\t\t\t\t} else if (event.content_block.type === \"thinking\") {\n\t\t\t\t\t\toutput.content.push({\n\t\t\t\t\t\t\ttype: \"thinking\",\n\t\t\t\t\t\t\tthinking: event.content_block.thinking ?? \"\",\n\t\t\t\t\t\t\tthinkingSignature: event.content_block.signature ?? \"\",\n\t\t\t\t\t\t});\n\t\t\t\t\t\topenBlocks.set(event.index, { contentIndex: output.content.length - 1 });\n\t\t\t\t\t\tstream.push({ type: \"thinking_start\", contentIndex: output.content.length - 1, partial: output });\n\t\t\t\t\t} else if (event.content_block.type === \"redacted_thinking\") {\n\t\t\t\t\t\toutput.content.push({\n\t\t\t\t\t\t\ttype: \"thinking\",\n\t\t\t\t\t\t\tthinking: \"[Reasoning redacted]\",\n\t\t\t\t\t\t\tthinkingSignature: event.content_block.data,\n\t\t\t\t\t\t\tredacted: true,\n\t\t\t\t\t\t});\n\t\t\t\t\t\topenBlocks.set(event.index, { contentIndex: output.content.length - 1 });\n\t\t\t\t\t\tstream.push({ type: \"thinking_start\", contentIndex: output.content.length - 1, partial: output });\n\t\t\t\t\t} else if (event.content_block.type === \"tool_use\") {\n\t\t\t\t\t\toutput.content.push({\n\t\t\t\t\t\t\ttype: \"toolCall\",\n\t\t\t\t\t\t\tid: event.content_block.id,\n\t\t\t\t\t\t\tname: isOAuth\n\t\t\t\t\t\t\t\t? fromClaudeCodeName(event.content_block.name, currentTools)\n\t\t\t\t\t\t\t\t: event.content_block.name,\n\t\t\t\t\t\t\targuments: (event.content_block.input as Record<string, any>) ?? {},\n\t\t\t\t\t\t});\n\t\t\t\t\t\topenBlocks.set(event.index, {\n\t\t\t\t\t\t\tcontentIndex: output.content.length - 1,\n\t\t\t\t\t\t\targuments: new ToolCallArgumentsStream(),\n\t\t\t\t\t\t});\n\t\t\t\t\t\tstream.push({ type: \"toolcall_start\", contentIndex: output.content.length - 1, partial: output });\n\t\t\t\t\t} else if ((event.content_block as { type?: string }).type === \"fallback\") {\n\t\t\t\t\t\t// Server-side fallback boundary: \"the `fallback` block (an ordinary\n\t\t\t\t\t\t// `content_block_start` and `content_block_stop` pair with no deltas) marks the\n\t\t\t\t\t\t// boundary\", and clients must \"Keep it exactly where it appeared. The API uses\n\t\t\t\t\t\t// its position to validate the thinking blocks around it\".\n\t\t\t\t\t\t// https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback\n\t\t\t\t\t\t//\n\t\t\t\t\t\t// The SDK types lag this block, so read it through a narrow cast.\n\t\t\t\t\t\tconst fallbackBlock = event.content_block as unknown as {\n\t\t\t\t\t\t\tfrom?: { model?: string };\n\t\t\t\t\t\t\tto?: { model?: string };\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst toModel = fallbackBlock.to?.model;\n\t\t\t\t\t\toutput.content.push({\n\t\t\t\t\t\t\ttype: \"fallback\",\n\t\t\t\t\t\t\tfromModel: fallbackBlock.from?.model ?? output.model,\n\t\t\t\t\t\t\ttoModel: toModel ?? output.model,\n\t\t\t\t\t\t});\n\t\t\t\t\t\t// `message_start` named the requested model, so on a mid-output fallback the\n\t\t\t\t\t\t// serving model is only knowable here. Re-derive pricing the same way the\n\t\t\t\t\t\t// `message_start` branch does, so the returned message is costed at the rates\n\t\t\t\t\t\t// of the model that actually produced it.\n\t\t\t\t\t\tif (toModel && toModel !== output.model) {\n\t\t\t\t\t\t\toutput.model = toModel;\n\t\t\t\t\t\t\tconst fallbackCost = model.compat?.allowedFallbackModels?.find(\n\t\t\t\t\t\t\t\t(fallback) => fallback.provider === model.provider && fallback.model === toModel,\n\t\t\t\t\t\t\t)?.cost;\n\t\t\t\t\t\t\tusageModel = fallbackCost ? { ...model, id: toModel, cost: fallbackCost } : model;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else if (event.type === \"content_block_delta\") {\n\t\t\t\t\tconst open = openBlock(event.index);\n\t\t\t\t\tif (event.delta.type === \"text_delta\") {\n\t\t\t\t\t\tif (open?.block.type === \"text\") {\n\t\t\t\t\t\t\topen.block.text += event.delta.text;\n\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\ttype: \"text_delta\",\n\t\t\t\t\t\t\t\tcontentIndex: open.contentIndex,\n\t\t\t\t\t\t\t\tdelta: event.delta.text,\n\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (event.delta.type === \"thinking_delta\") {\n\t\t\t\t\t\tif (open?.block.type === \"thinking\") {\n\t\t\t\t\t\t\topen.block.thinking += event.delta.thinking;\n\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\t\t\t\t\tcontentIndex: open.contentIndex,\n\t\t\t\t\t\t\t\tdelta: event.delta.thinking,\n\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (event.delta.type === \"input_json_delta\") {\n\t\t\t\t\t\tif (open?.block.type === \"toolCall\" && open.arguments !== undefined) {\n\t\t\t\t\t\t\topen.block.arguments = open.arguments.append(event.delta.partial_json);\n\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\ttype: \"toolcall_delta\",\n\t\t\t\t\t\t\t\tcontentIndex: open.contentIndex,\n\t\t\t\t\t\t\t\tdelta: event.delta.partial_json,\n\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (event.delta.type === \"signature_delta\") {\n\t\t\t\t\t\tif (open?.block.type === \"thinking\") {\n\t\t\t\t\t\t\topen.block.thinkingSignature = open.block.thinkingSignature || \"\";\n\t\t\t\t\t\t\topen.block.thinkingSignature += event.delta.signature;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else if (event.type === \"content_block_stop\") {\n\t\t\t\t\tconst open = openBlock(event.index);\n\t\t\t\t\topenBlocks.delete(event.index);\n\t\t\t\t\tif (open) {\n\t\t\t\t\t\tconst { block, contentIndex: index } = open;\n\t\t\t\t\t\tif (block.type === \"text\") {\n\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\ttype: \"text_end\",\n\t\t\t\t\t\t\t\tcontentIndex: index,\n\t\t\t\t\t\t\t\tcontent: block.text,\n\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} else if (block.type === \"thinking\") {\n\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\ttype: \"thinking_end\",\n\t\t\t\t\t\t\t\tcontentIndex: index,\n\t\t\t\t\t\t\t\tcontent: block.thinking,\n\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} else if (block.type === \"toolCall\" && open.arguments !== undefined) {\n\t\t\t\t\t\t\tObject.assign(block, open.arguments.finish());\n\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\ttype: \"toolcall_end\",\n\t\t\t\t\t\t\t\tcontentIndex: index,\n\t\t\t\t\t\t\t\ttoolCall: block,\n\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else if (event.type === \"message_delta\") {\n\t\t\t\t\tif (event.delta.stop_reason) {\n\t\t\t\t\t\toutput.rawStopReason = event.delta.stop_reason;\n\t\t\t\t\t\tconst stopReasonResult = mapStopReason(event.delta.stop_reason, event.delta.stop_details);\n\t\t\t\t\t\toutput.stopReason = stopReasonResult.stopReason;\n\t\t\t\t\t\tif (stopReasonResult.errorMessage) {\n\t\t\t\t\t\t\toutput.errorMessage = stopReasonResult.errorMessage;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t// Only update usage fields if present (not null).\n\t\t\t\t\t// Preserves input_tokens from message_start when proxies omit it in message_delta.\n\t\t\t\t\tif (event.usage) {\n\t\t\t\t\t\tif (event.usage.input_tokens != null) {\n\t\t\t\t\t\t\toutput.usage.input = event.usage.input_tokens;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (event.usage.output_tokens != null) {\n\t\t\t\t\t\t\toutput.usage.output = event.usage.output_tokens;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (event.usage.cache_read_input_tokens != null) {\n\t\t\t\t\t\t\toutput.usage.cacheRead = event.usage.cache_read_input_tokens;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (event.usage.cache_creation_input_tokens != null) {\n\t\t\t\t\t\t\toutput.usage.cacheWrite = event.usage.cache_creation_input_tokens;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Anthropic reports reasoning tokens in `output_tokens_details.thinking_tokens` on the\n\t\t\t\t\t\t// final message_delta usage (a subset of output_tokens). SDK 0.91.1 omits the field from\n\t\t\t\t\t\t// its Usage type, so read it through a narrow cast. Verified against the live API.\n\t\t\t\t\t\tconst thinkingTokens = (event.usage as { output_tokens_details?: { thinking_tokens?: number } })\n\t\t\t\t\t\t\t.output_tokens_details?.thinking_tokens;\n\t\t\t\t\t\t// Vercel AI Gateway includes the TTL breakdown in deltas, though the SDK only types it on message_start.\n\t\t\t\t\t\tconst cacheCreation = (\n\t\t\t\t\t\t\tevent.usage as typeof event.usage & { cache_creation?: { ephemeral_1h_input_tokens?: number } }\n\t\t\t\t\t\t).cache_creation;\n\t\t\t\t\t\tif (cacheCreation?.ephemeral_1h_input_tokens != null) {\n\t\t\t\t\t\t\toutput.usage.cacheWrite1h = cacheCreation.ephemeral_1h_input_tokens;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (thinkingTokens != null) {\n\t\t\t\t\t\t\toutput.usage.reasoning = thinkingTokens;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t// Anthropic doesn't provide total_tokens, compute from components\n\t\t\t\t\toutput.usage.totalTokens =\n\t\t\t\t\t\toutput.usage.input + output.usage.output + output.usage.cacheRead + output.usage.cacheWrite;\n\t\t\t\t\tcalculateCost(usageModel, output.usage);\n\t\t\t\t\tservedSpeed = reportedSpeed(event.usage) ?? servedSpeed;\n\t\t\t\t\tif (servedSpeed === \"fast\") applyFastModePricing(output.usage);\n\t\t\t\t\t// A non-empty final fallback report supersedes the request-start report with\n\t\t\t\t\t// the serving model's transformations. An empty report must not erase drops\n\t\t\t\t\t// already reported at message_start.\n\t\t\t\t\tconst servingTransformations = getInputTransformations(event);\n\t\t\t\t\tif (servingTransformations && servingTransformations.length > 0) {\n\t\t\t\t\t\tinputTransformations = servingTransformations;\n\t\t\t\t\t}\n\t\t\t\t\taddEarlierAttemptCosts(output, model, usageModel, event);\n\t\t\t\t\tif (isOpenRouterModel(model) && event.usage) {\n\t\t\t\t\t\t// OpenRouter adds billing fields to streamed message_delta usage at runtime,\n\t\t\t\t\t\t// although its OpenAPI schema and the Anthropic SDK do not type those fields.\n\t\t\t\t\t\tapplyOpenRouterReportedCost(\n\t\t\t\t\t\t\toutput.usage,\n\t\t\t\t\t\t\tevent.usage as typeof event.usage & OpenRouterUsageAccounting,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (inputTransformations) recordInputTransformations(output, inputTransformations);\n\t\t\tif (options?.signal?.aborted) {\n\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t}\n\n\t\t\tif (output.stopReason === \"pending\") {\n\t\t\t\tthrow new Error(\"Anthropic stream ended without a stop reason\");\n\t\t\t}\n\t\t\tif (output.stopReason === \"aborted\" || output.stopReason === \"error\") {\n\t\t\t\tthrow new Error(output.errorMessage || \"An unknown error occurred\");\n\t\t\t}\n\t\t\tif (thread) recordThreadReply(model, thread, params, output, isOAuth, compat.allowEmptySignature);\n\n\t\t\tstream.push({ type: \"done\", reason: output.stopReason, message: output });\n\t\t\tstream.end();\n\t\t} catch (error) {\n\t\t\tif (\n\t\t\t\tinputTransformations &&\n\t\t\t\t!output.diagnostics?.some((diagnostic) => diagnostic.type === \"anthropic_input_transformations\")\n\t\t\t) {\n\t\t\t\trecordInputTransformations(output, inputTransformations);\n\t\t\t}\n\t\t\toutput.stopReason = options?.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\toutput.errorMessage = error instanceof Error ? withCauseDetail(error) : JSON.stringify(error);\n\t\t\toutput.retryAfterMs = error instanceof Error ? getProviderRetryAfterMs(error) : undefined;\n\t\t\tif (model.provider === \"github-copilot\") recordGitHubCopilotFailure(output, error, streamAttempt.snapshot());\n\t\t\tstream.push({ type: \"error\", reason: output.stopReason, error: output });\n\t\t\tstream.end();\n\t\t} finally {\n\t\t\tstreamDeadline.cleanup();\n\t\t}\n\t})();\n\n\treturn stream;\n};\n\n/**\n * Map ThinkingLevel to Anthropic effort levels for adaptive thinking.\n * Note: effort \"max\" is available on all adaptive-thinking Claude models, while native\n * \"xhigh\" is available on Opus 4.7, Opus 4.8, Opus 5, Sonnet 5, Fable 5, and Fable 5.1 —\n * the models the generator merges an `xhigh` mapping onto.\n */\nfunction mapThinkingLevelToEffort(\n\tmodel: Model<\"anthropic-messages\">,\n\tlevel: SimpleStreamOptions[\"reasoning\"],\n): AnthropicEffort {\n\tconst mapped = level ? model.thinkingLevelMap?.[level] : undefined;\n\tif (typeof mapped === \"string\") return mapped as AnthropicEffort;\n\n\tswitch (level) {\n\t\tcase \"minimal\":\n\t\tcase \"low\":\n\t\t\treturn \"low\";\n\t\tcase \"medium\":\n\t\t\treturn \"medium\";\n\t\tcase \"high\":\n\t\t\treturn \"high\";\n\t\tdefault:\n\t\t\treturn \"high\";\n\t}\n}\n\ninterface AnthropicThinkingOffFallback {\n\tlevel: ThinkingLevel;\n\teffort: AnthropicEffort;\n}\n\n/**\n * Thinking `off` on an adaptive model that cannot disable thinking runs at the model's lowest effort.\n * Sending no effort would leave the API's default, which is `high`.\n */\nfunction getAnthropicThinkingOffFallback(\n\tmodel: Model<\"anthropic-messages\">,\n\toptions: AnthropicOptions | undefined,\n): AnthropicThinkingOffFallback | undefined {\n\tif (options?.thinkingEnabled !== false) return undefined;\n\tif (model.compat?.forceAdaptiveThinking !== true && !supportsMidConvoEffort(model)) return undefined;\n\tconst level = getThinkingOffFallbackLevel(model);\n\treturn level === undefined ? undefined : { level, effort: mapThinkingLevelToEffort(model, level) };\n}\n\nexport const streamSimple: StreamFunction<\"anthropic-messages\", SimpleStreamOptions> = (\n\tmodel: Model<\"anthropic-messages\">,\n\tcontext: TranscriptContext,\n\toptions?: SimpleStreamOptions,\n): AssistantMessageEventStream => {\n\tif (!getAnthropicFederation(model, options?.apiKey, options?.headers, options?.env)) {\n\t\tassertRequestAuth(model.provider, options?.apiKey, options?.headers);\n\t}\n\n\tconst base = {\n\t\t...buildBaseOptions(model, context, options, options?.apiKey),\n\t\ttoolChoice: options?.toolChoice,\n\t} satisfies AnthropicOptions;\n\tif (!options?.reasoning) {\n\t\treturn stream(model, context, {\n\t\t\t...base,\n\t\t\tthinkingEnabled: false,\n\t\t} satisfies AnthropicOptions);\n\t}\n\n\t// For models with adaptive thinking: use an effort level.\n\t// For older models: use budget-based thinking.\n\tif (model.compat?.forceAdaptiveThinking === true) {\n\t\tconst effort = mapThinkingLevelToEffort(model, options.reasoning);\n\t\treturn stream(model, context, {\n\t\t\t...base,\n\t\t\tthinkingEnabled: true,\n\t\t\teffort,\n\t\t} satisfies AnthropicOptions);\n\t}\n\n\t// Undefined means the caller did not request an output cap; let the helper use the model cap.\n\t// Do not coerce to 0 here, or the thinking budget would become the entire max_tokens value.\n\tconst adjusted = adjustMaxTokensForThinking(\n\t\tbase.maxTokens,\n\t\tmodel.maxTokens,\n\t\toptions.reasoning,\n\t\toptions.thinkingBudgets,\n\t);\n\n\tconst maxTokens = clampMaxTokensToContext(model, context, adjusted.maxTokens);\n\n\treturn stream(model, context, {\n\t\t...base,\n\t\tmaxTokens,\n\t\tthinkingEnabled: true,\n\t\tthinkingBudgetTokens: Math.min(adjusted.thinkingBudget, Math.max(0, maxTokens - 1024)),\n\t} satisfies AnthropicOptions);\n};\n\nfunction isOAuthToken(apiKey: string): boolean {\n\treturn apiKey.includes(\"sk-ant-oat\");\n}\n\nfunction createClient(\n\tmodel: Model<\"anthropic-messages\">,\n\tapiKey: string | undefined,\n\tinterleavedThinking: boolean,\n\tuseFineGrainedToolStreamingBeta: boolean,\n\tuseServerSideFallbackBeta: boolean,\n\toptionsHeaders?: ProviderHeaders,\n\tfetch?: typeof globalThis.fetch,\n\tdynamicHeaders?: Record<string, string>,\n\tsessionId?: string,\n\tuseNativeToolChanges = false,\n\tfederation?: AnthropicFederationConfig,\n\tidentity?: ClientIdentity,\n\tuseMessageThreads = false,\n): { client: Anthropic; isOAuthToken: boolean } {\n\t// Adaptive thinking models have interleaved thinking built in, so skip the beta header.\n\tconst needsInterleavedBeta = interleavedThinking && model.compat?.forceAdaptiveThinking !== true;\n\tconst betaFeatures: string[] = [];\n\tif (useFineGrainedToolStreamingBeta) {\n\t\tbetaFeatures.push(FINE_GRAINED_TOOL_STREAMING_BETA);\n\t}\n\tif (needsInterleavedBeta) {\n\t\tbetaFeatures.push(INTERLEAVED_THINKING_BETA);\n\t}\n\tif (useServerSideFallbackBeta) {\n\t\tbetaFeatures.push(SERVER_SIDE_FALLBACK_BETA);\n\t}\n\tif (shouldUseThinkingBindingControlsBeta(model)) {\n\t\tbetaFeatures.push(THINKING_BINDING_CONTROLS_BETA);\n\t}\n\tif (supportsMidConvoEffort(model)) {\n\t\tbetaFeatures.push(MID_CONVERSATION_OUTPUT_CONFIG_BETA, THINKING_BINDING_CONTROLS_BETA);\n\t}\n\tif (useNativeToolChanges) betaFeatures.push(INLINE_TOOLS_BETA);\n\tif (requestedSpeed(model) === \"fast\") betaFeatures.push(FAST_MODE_BETA);\n\tif (useMessageThreads) betaFeatures.push(MESSAGE_THREADS_BETA);\n\tconst uniqueBetaFeatures = [...new Set(betaFeatures)];\n\n\t// Copilot: Bearer auth, selective betas.\n\tif (model.provider === \"github-copilot\") {\n\t\tconst client = new AtomicAnthropic({\n\t\t\tapiKey: null,\n\t\t\tauthToken: apiKey ?? null,\n\t\t\tbaseURL: model.baseUrl,\n\t\t\tdangerouslyAllowBrowser: true,\n\t\t\tfetch,\n\t\t\tdefaultHeaders: mergeHeaders(\n\t\t\t\tgetIdentityHeaders(model, identity),\n\t\t\t\t{\n\t\t\t\t\taccept: \"application/json\",\n\t\t\t\t\t\"anthropic-dangerous-direct-browser-access\": \"true\",\n\t\t\t\t\t...(uniqueBetaFeatures.length > 0 ? { \"anthropic-beta\": uniqueBetaFeatures.join(\",\") } : {}),\n\t\t\t\t},\n\t\t\t\tmodel.headers,\n\t\t\t\tdynamicHeaders,\n\t\t\t\toptionsHeaders,\n\t\t\t),\n\t\t});\n\n\t\treturn { client, isOAuthToken: false };\n\t}\n\n\t// OAuth: Bearer auth, Claude Code identity headers instead of the client identity.\n\tif (apiKey && isOAuthToken(apiKey)) {\n\t\tconst client = new AtomicAnthropic({\n\t\t\tapiKey: null,\n\t\t\tauthToken: apiKey,\n\t\t\tbaseURL: model.baseUrl,\n\t\t\tdangerouslyAllowBrowser: true,\n\t\t\tfetch,\n\t\t\tdefaultHeaders: mergeHeaders(\n\t\t\t\t{\n\t\t\t\t\taccept: \"application/json\",\n\t\t\t\t\t\"anthropic-dangerous-direct-browser-access\": \"true\",\n\t\t\t\t\t\"anthropic-beta\": [\"claude-code-20250219\", \"oauth-2025-04-20\", ...uniqueBetaFeatures].join(\",\"),\n\t\t\t\t\t\"user-agent\": `claude-cli/${claudeCodeVersion}`,\n\t\t\t\t\t\"x-app\": \"cli\",\n\t\t\t\t},\n\t\t\t\tmodel.headers,\n\t\t\t\toptionsHeaders,\n\t\t\t),\n\t\t});\n\n\t\treturn { client, isOAuthToken: true };\n\t}\n\n\t// API key, header-owned auth, or workload identity federation.\n\tconst compat = getAnthropicCompat(model);\n\tconst sessionAffinityHeaders: ProviderHeaders = {};\n\tif (sessionId && compat.sendSessionAffinityHeaders) {\n\t\tconst header = compat.sessionAffinityFormat === \"openrouter\" ? \"x-session-id\" : \"x-session-affinity\";\n\t\tsessionAffinityHeaders[header] = sessionId;\n\t}\n\tconst defaultHeaders = mergeHeaders(\n\t\tgetIdentityHeaders(model, identity),\n\t\t{\n\t\t\taccept: \"application/json\",\n\t\t\t\"anthropic-dangerous-direct-browser-access\": \"true\",\n\t\t\t...(uniqueBetaFeatures.length > 0 ? { \"anthropic-beta\": uniqueBetaFeatures.join(\",\") } : {}),\n\t\t},\n\t\tsessionAffinityHeaders,\n\t\tmodel.headers,\n\t\toptionsHeaders,\n\t);\n\tif (federation) {\n\t\tconst key = JSON.stringify([model.baseUrl, federation]);\n\t\tif (federationClient?.key !== key || federationClient.fetch !== fetch) {\n\t\t\tconst client = new AtomicAnthropic({\n\t\t\t\tapiKey: null,\n\t\t\t\tauthToken: null,\n\t\t\t\tconfig: federation,\n\t\t\t\tbaseURL: model.baseUrl,\n\t\t\t\tdangerouslyAllowBrowser: true,\n\t\t\t\tfetch,\n\t\t\t});\n\t\t\tfederationClient = { key, fetch, client };\n\t\t}\n\t\treturn { client: federationClient.client.withOptions({ defaultHeaders, fetch }), isOAuthToken: false };\n\t}\n\n\tconst client = new AtomicAnthropic({\n\t\tapiKey: apiKey ?? null,\n\t\tauthToken: null,\n\t\tbaseURL: model.baseUrl,\n\t\tdangerouslyAllowBrowser: true,\n\t\tfetch,\n\t\tdefaultHeaders,\n\t});\n\n\treturn { client, isOAuthToken: false };\n}\n\nfunction getNativeToolChangeBetas(\n\tmodel: Model<\"anthropic-messages\">,\n\tcontext: TranscriptContext,\n\tisOAuth: boolean,\n\toptions: AnthropicOptions | undefined,\n\tmessageThreads: boolean,\n): NonNullable<MessageCreateParamsStreaming[\"betas\"]> {\n\tlet configured: string | null | undefined;\n\tfor (const headers of [model.headers, options?.headers]) {\n\t\tfor (const [name, value] of Object.entries(headers ?? {})) {\n\t\t\tif (name.toLowerCase() === \"anthropic-beta\") configured = value;\n\t\t}\n\t}\n\tif (configured === null) return [];\n\tif (configured !== undefined)\n\t\treturn [\n\t\t\t...new Set(\n\t\t\t\tconfigured\n\t\t\t\t\t.split(\",\")\n\t\t\t\t\t.map((feature) => feature.trim())\n\t\t\t\t\t.filter(Boolean),\n\t\t\t),\n\t\t];\n\tconst features = [INLINE_TOOLS_BETA];\n\tif (isOAuth) features.push(\"claude-code-20250219\", \"oauth-2025-04-20\");\n\tif (shouldUseFineGrainedToolStreamingBeta(model, context)) features.push(FINE_GRAINED_TOOL_STREAMING_BETA);\n\tif (\n\t\tmodel.reasoning &&\n\t\toptions?.thinkingEnabled &&\n\t\t(options.interleavedThinking ?? true) &&\n\t\tmodel.compat?.forceAdaptiveThinking !== true\n\t) {\n\t\tfeatures.push(INTERLEAVED_THINKING_BETA);\n\t}\n\tif (shouldUseServerSideFallbackBeta(model)) features.push(SERVER_SIDE_FALLBACK_BETA);\n\tif (shouldUseThinkingBindingControlsBeta(model)) features.push(THINKING_BINDING_CONTROLS_BETA);\n\tif (supportsMidConvoEffort(model))\n\t\tfeatures.push(MID_CONVERSATION_OUTPUT_CONFIG_BETA, THINKING_BINDING_CONTROLS_BETA);\n\tif (requestedSpeed(model) === \"fast\") features.push(FAST_MODE_BETA);\n\tif (messageThreads) features.push(MESSAGE_THREADS_BETA);\n\treturn [...new Set(features)];\n}\n\ninterface BuildParamsFlags {\n\t/** Send `strict: \"prefer\"` tools without strict schemas, after Anthropic rejected them in this request or session. */\n\tdisablePreferredStrictTools: boolean;\n\t/** The session uses message threads, so the threads beta is sent. */\n\tmessageThreads: boolean;\n}\n\nfunction buildParams(\n\tmodel: Model<\"anthropic-messages\">,\n\tcontext: TranscriptContext,\n\tisOAuthToken: boolean,\n\toptions: AnthropicOptions | undefined,\n\t{ disablePreferredStrictTools, messageThreads }: BuildParamsFlags,\n): {\n\tparams: MessageCreateParamsStreaming;\n\thasPreferredStrictTools: boolean;\n\t/** Effort of the final effort marker, recorded on the reply so later requests can replay it. */\n\tproviderThinkingLevel: AnthropicEffort | undefined;\n} {\n\tconst { cacheControl } = getCacheControl(model, options?.cacheRetention, options?.env);\n\tconst compat = getAnthropicCompat(model);\n\tconst initialSystemMessage = getInitialSystemMessage(context.messages);\n\tconst initialSystemText = initialSystemMessage ? getSystemMessageText(initialSystemMessage) : \"\";\n\tconst transformedMessages = transformMessages(context.messages, model, normalizeToolCallId);\n\tconst conversationMessages = initialSystemMessage ? transformedMessages.slice(1) : transformedMessages;\n\tlet hasPreferredStrictTools = false;\n\tconst convertToolDefinitions = (tools: Tool[], toolCacheControl?: CacheControlEphemeral): BetaTool[] => {\n\t\tif (isOAuthToken) tools = [...new Map(tools.map((tool) => [toClaudeCodeName(tool.name), tool])).values()];\n\t\tconst definitions = convertTools(\n\t\t\ttools,\n\t\t\tisOAuthToken,\n\t\t\tcompat.supportsEagerToolInputStreaming,\n\t\t\tcompat.supportsStrictTools,\n\t\t\ttoolCacheControl,\n\t\t\tdisablePreferredStrictTools,\n\t\t);\n\t\tif (\n\t\t\tdefinitions.some(\n\t\t\t\t(definition, index) => definition.strict === true && prefersJsonSchemaStrictSampling(tools[index]),\n\t\t\t)\n\t\t)\n\t\t\thasPreferredStrictTools = true;\n\t\treturn definitions;\n\t};\n\tconst initialTools = initialSystemMessage?.toolsAdded ?? [];\n\tconst nativeToolChanges =\n\t\tcompat.supportsMidConvoSystemMessages && compat.supportsMidConvoToolChanges && initialTools.length > 0;\n\tconst thinkingOffFallback = getAnthropicThinkingOffFallback(model, options);\n\tconst thinkingDisabled =\n\t\tmodel.reasoning && options?.thinkingEnabled === false && model.thinkingLevelMap?.off !== null;\n\t// Effort cannot change between messages while thinking is disabled, so \"off\" sends no effort markers.\n\tconst effortMessages = supportsMidConvoEffort(model) && !thinkingDisabled;\n\tconst converted = convertMessages(\n\t\tconversationMessages,\n\t\tisOAuthToken,\n\t\tcacheControl,\n\t\tcompat.allowEmptySignature,\n\t\teffortMessages ? model.provider : undefined,\n\t\tnativeToolChanges ? convertToolDefinitions : undefined,\n\t);\n\tconst activeEffort = options?.effort ?? thinkingOffFallback?.effort ?? \"high\";\n\tconst params: MessageCreateParamsStreaming = {\n\t\tmodel: upstreamModelId(model),\n\t\tmessages: (effortMessages\n\t\t\t? insertThinkingLevelMessages(converted, activeEffort)\n\t\t\t: converted.messages) as MessageParam[],\n\t\tmax_tokens: options?.maxTokens ?? model.maxTokens,\n\t\tstream: true,\n\t};\n\tif (nativeToolChanges)\n\t\tparams.betas = getNativeToolChangeBetas(model, context, isOAuthToken, options, messageThreads);\n\tconst speed = requestedSpeed(model);\n\tif (speed !== undefined) params.speed = speed;\n\n\t// For OAuth tokens, we MUST include Claude Code identity\n\tif (isOAuthToken) {\n\t\tparams.system = [\n\t\t\t{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: \"You are Claude Code, Anthropic's official CLI for Claude.\",\n\t\t\t\t...(cacheControl ? { cache_control: cacheControl } : {}),\n\t\t\t},\n\t\t];\n\t\tif (initialSystemText) {\n\t\t\tparams.system.push({\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: sanitizeSurrogates(initialSystemText),\n\t\t\t\t...(cacheControl ? { cache_control: cacheControl } : {}),\n\t\t\t});\n\t\t}\n\t} else if (initialSystemText) {\n\t\t// Add cache control to system prompt for non-OAuth tokens\n\t\tparams.system = [\n\t\t\t{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: sanitizeSurrogates(initialSystemText),\n\t\t\t\t...(cacheControl ? { cache_control: cacheControl } : {}),\n\t\t\t},\n\t\t];\n\t}\n\n\t// Temperature is incompatible with extended thinking and unsupported on Claude Opus 4.7+.\n\tif (\n\t\toptions?.temperature !== undefined &&\n\t\t!options?.thinkingEnabled &&\n\t\t!thinkingOffFallback &&\n\t\t!supportsMidConvoEffort(model) &&\n\t\tcompat.supportsTemperature\n\t) {\n\t\tparams.temperature = options.temperature;\n\t}\n\n\tconst toolCacheControl = compat.supportsCacheControlOnTools ? cacheControl : undefined;\n\tif (nativeToolChanges) {\n\t\tparams.tools = [...convertToolDefinitions(initialTools, toolCacheControl), DEFERRED_TOOL_PLACEHOLDER];\n\t} else {\n\t\tconst tools = getCurrentTools(context.messages);\n\t\tif (tools.length > 0) {\n\t\t\tparams.tools = convertToolDefinitions(tools, toolCacheControl);\n\t\t}\n\t}\n\n\t// Managed effort models always use adaptive thinking. Their per-turn markers\n\t// carry the actual effort for every reply.\n\tif (effortMessages) {\n\t\tparams.thinking = {\n\t\t\ttype: \"adaptive\",\n\t\t\tdisplay: options?.thinkingDisplay ?? \"summarized\",\n\t\t\tblock_binding: { prefix_mismatch_behavior: \"drop_block\" },\n\t\t} as unknown as NonNullable<MessageCreateParamsStreaming[\"thinking\"]>;\n\t\t// The top-level effort is part of the cached prompt, so it stays fixed. It is \"low\" because\n\t\t// organizations can cap effort and reject requests containing any level above the cap.\n\t\tparams.output_config = { effort: \"low\" };\n\t} else if (model.reasoning) {\n\t\tif (options?.thinkingEnabled || thinkingOffFallback) {\n\t\t\t// Default to \"summarized\" so Opus 4.7 and Mythos Preview behave like\n\t\t\t// older Claude 4 models (whose API default is also \"summarized\").\n\t\t\tconst display: AnthropicThinkingDisplay = options?.thinkingDisplay ?? \"summarized\";\n\t\t\tconst effort = options?.effort ?? thinkingOffFallback?.effort;\n\t\t\tif (model.compat?.forceAdaptiveThinking === true) {\n\t\t\t\t// Adaptive thinking: Claude decides when and how much to think.\n\t\t\t\tparams.thinking = { type: \"adaptive\", display };\n\t\t\t\tif (effort) {\n\t\t\t\t\t// The Anthropic SDK types can lag newly supported effort values such as \"xhigh\".\n\t\t\t\t\tparams.output_config =\n\t\t\t\t\t\teffort === \"xhigh\"\n\t\t\t\t\t\t\t? ({ effort } as unknown as NonNullable<MessageCreateParamsStreaming[\"output_config\"]>)\n\t\t\t\t\t\t\t: { effort };\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Budget-based thinking for older models\n\t\t\t\tparams.thinking = {\n\t\t\t\t\ttype: \"enabled\",\n\t\t\t\t\tbudget_tokens: options?.thinkingBudgetTokens || 1024,\n\t\t\t\t\tdisplay,\n\t\t\t\t};\n\t\t\t}\n\t\t} else if (options?.thinkingEnabled === false && model.thinkingLevelMap?.off !== null) {\n\t\t\tparams.thinking = { type: \"disabled\" };\n\t\t}\n\n\t\t// `block_binding` must accompany the beta header on *every* request for a model that\n\t\t// enforces the conversation check, not only on reasoning turns. The header alone leaves\n\t\t// `prefix_mismatch_behavior` at its `\"error\"` default, which is the 400 this opts out of.\n\t\t// `streamSimple` sets `thinkingEnabled: false` whenever no reasoning level is requested,\n\t\t// and Claude Fable 5.1 denies thinking-off (`thinkingLevelMap.off === null`), so without\n\t\t// this the no-reasoning path would send the header with no field at all.\n\t\tif (shouldUseThinkingBindingControlsBeta(model)) {\n\t\t\tconst blockBinding = { block_binding: { prefix_mismatch_behavior: \"drop_block\" } };\n\t\t\t// The Anthropic SDK types lag the `thinking-binding-controls-2026-08-01` beta.\n\t\t\tif (params.thinking?.type === \"adaptive\" || params.thinking?.type === \"enabled\") {\n\t\t\t\t// Accepted alongside both thinking types. It only changes what happens to a block\n\t\t\t\t// replayed behind a changed prefix; the model check always drops regardless.\n\t\t\t\tparams.thinking = { ...params.thinking, ...blockBinding } as unknown as NonNullable<\n\t\t\t\t\tMessageCreateParamsStreaming[\"thinking\"]\n\t\t\t\t>;\n\t\t\t} else if (!params.thinking && model.compat?.forceAdaptiveThinking === true) {\n\t\t\t\t// Adaptive thinking is always on for these models, so omitting `thinking` and\n\t\t\t\t// sending `{type: \"adaptive\"}` are equivalent. `display` stays absent to keep the\n\t\t\t\t// API's `\"omitted\"` default, which is exactly what omitting `thinking` produced.\n\t\t\t\tparams.thinking = { type: \"adaptive\", ...blockBinding } as unknown as NonNullable<\n\t\t\t\t\tMessageCreateParamsStreaming[\"thinking\"]\n\t\t\t\t>;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (options?.metadata) {\n\t\tconst userId = options.metadata.user_id;\n\t\tif (typeof userId === \"string\") {\n\t\t\tparams.metadata = { user_id: userId };\n\t\t}\n\t}\n\n\tif (options?.toolChoice) {\n\t\tconst requested = options.toolChoice;\n\t\tconst isForced = requested === \"any\" || (typeof requested !== \"string\" && requested.type === \"tool\");\n\t\tif (isForced && model.compat?.supportsForcedToolChoice === false) {\n\t\t\t// \"The exceptions are Claude Fable 5.1 and Claude Mythos 5.1, which reject forced tool\n\t\t\t// use on every request with a 400 error. On those models, use\n\t\t\t// `tool_choice: {\"type\": \"auto\"}` with strict tool use or structured outputs instead.\"\n\t\t\t// https://platform.claude.com/docs/en/build-with-claude/thinking\n\t\t\t//\n\t\t\t// Reject the request rather than rewriting it. Silently substituting `auto` would\n\t\t\t// discard an explicit caller instruction and make `AnthropicOptions.toolChoice`'s\n\t\t\t// declared shape a lie; the caller asked the model to call a tool, and quietly asking\n\t\t\t// it to decide instead is a different request. Failing here matches how this package\n\t\t\t// handles other explicitly requested capabilities a model cannot honor, and surfaces\n\t\t\t// the remedy before a round trip that would 400 anyway. Callers that want the\n\t\t\t// substitution can make it themselves, and can branch on\n\t\t\t// `model.compat.supportsForcedToolChoice` to decide.\n\t\t\tconst requestedLabel = typeof requested === \"string\" ? requested : `tool \"${requested.name}\"`;\n\t\t\tthrow new Error(\n\t\t\t\t`Model ${model.id} does not support forced tool choice (requested: ${requestedLabel}). ` +\n\t\t\t\t\t`Use toolChoice \"auto\" with strict tool use or structured outputs instead.`,\n\t\t\t);\n\t\t}\n\t\tif (typeof requested === \"string\") {\n\t\t\tparams.tool_choice = { type: requested };\n\t\t} else {\n\t\t\tparams.tool_choice = requested;\n\t\t}\n\t}\n\n\tconst allowedFallbackModels = model.compat?.allowedFallbackModels;\n\tif (allowedFallbackModels && allowedFallbackModels.length > 0) {\n\t\tparams.fallbacks = allowedFallbackModels.map((fallback) => ({ model: fallback.model }));\n\t}\n\n\treturn { params, hasPreferredStrictTools, providerThinkingLevel: effortMessages ? activeEffort : undefined };\n}\n\n// Normalize tool call IDs to match Anthropic's required pattern and length\nfunction normalizeToolCallId(id: string): string {\n\treturn id.replace(/[^a-zA-Z0-9_-]/g, \"_\").slice(0, 64);\n}\n\nfunction convertToolResult(msg: ToolResultMessage, content = msg.content): ContentBlockParam {\n\treturn {\n\t\ttype: \"tool_result\",\n\t\ttool_use_id: msg.toolCallId,\n\t\tcontent: convertContentBlocks(content),\n\t\tis_error: msg.isError,\n\t};\n}\n\nfunction convertMessages(\n\ttransformedMessages: Message[],\n\tisOAuthToken: boolean,\n\tcacheControl?: CacheControlEphemeral,\n\tallowEmptySignature = false,\n\tmanagedProvider?: string,\n\tconvertToolDefinitions?: (tools: Tool[]) => BetaTool[],\n): ConvertedAnthropicMessages {\n\tconst params: MessageParam[] = [];\n\tconst assistantLevels = new Map<number, AnthropicEffort>();\n\t// Later system messages are held back and emitted directly before the next assistant\n\t// message that is sent (or at the end of the transcript). Assistant messages that convert to\n\t// no blocks are dropped, so holding past them keeps an update from landing before a user\n\t// message (pi #11091). Anthropic requires `tool_result` blocks to\n\t// immediately follow their `tool_use`, so a system message between them is rejected; this\n\t// also mirrors where the managed-effort system messages are inserted. As a result an\n\t// update placed before a user message in the transcript lands after it on the wire.\n\tconst pendingSystemMessages: MessageParam[] = [];\n\tconst flushPendingSystemMessages = (): void => {\n\t\tparams.push(...pendingSystemMessages);\n\t\tpendingSystemMessages.length = 0;\n\t};\n\n\tfor (let i = 0; i < transformedMessages.length; i++) {\n\t\tconst msg = transformedMessages[i];\n\n\t\tif (msg.role === \"system\") {\n\t\t\t// Later system messages only reach this point when the model accepts them natively;\n\t\t\t// otherwise the transcript was collapsed into the leading message before conversion.\n\t\t\tconst text = renderSystemMessageUpdate(msg);\n\t\t\tconst blocks: ContentBlockParam[] = [];\n\t\t\tif (text.length > 0) blocks.push({ type: \"text\", text: sanitizeSurrogates(text) });\n\t\t\tif (convertToolDefinitions) {\n\t\t\t\tconst added = msg.toolsAdded ?? [];\n\t\t\t\tconst redefined = new Set(added.map((tool) => tool.name));\n\t\t\t\tfor (const tool of msg.toolsRemoved ?? []) {\n\t\t\t\t\tif (redefined.has(tool.name)) continue;\n\t\t\t\t\tblocks.push({\n\t\t\t\t\t\ttype: \"tool_removal\",\n\t\t\t\t\t\ttool: { type: \"tool_reference\", name: isOAuthToken ? toClaudeCodeName(tool.name) : tool.name },\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tfor (const definition of convertToolDefinitions(added)) {\n\t\t\t\t\tblocks.push({ type: \"tool_addition\", tool: { type: \"tool_definition\", definition } });\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (blocks.length > 0) pendingSystemMessages.push({ role: \"system\", content: blocks });\n\t\t} else if (msg.role === \"user\") {\n\t\t\tif (typeof msg.content === \"string\") {\n\t\t\t\tif (msg.content.trim().length > 0) {\n\t\t\t\t\tparams.push({\n\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\tcontent: sanitizeSurrogates(msg.content),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tconst blocks: ContentBlockParam[] = msg.content.map((item) => {\n\t\t\t\t\tif (item.type === \"text\") {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: sanitizeSurrogates(item.text),\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tif (item.type === \"document\") {\n\t\t\t\t\t\t// `BetaBase64PDFSource`. PDFs ride Claude's vision path, so no beta header.\n\t\t\t\t\t\t// The media type is a fixed literal in that SDK type, so it is hardcoded here\n\t\t\t\t\t\t// and the block's own field is verified rather than read.\n\t\t\t\t\t\t// https://platform.claude.com/docs/en/build-with-claude/pdf-support\n\t\t\t\t\t\tassertSupportedDocumentMimeType(item);\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\ttype: \"document\",\n\t\t\t\t\t\t\tsource: {\n\t\t\t\t\t\t\t\ttype: \"base64\",\n\t\t\t\t\t\t\t\tmedia_type: \"application/pdf\",\n\t\t\t\t\t\t\t\tdata: item.data,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t...(item.name ? { title: item.name } : {}),\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"image\",\n\t\t\t\t\t\tsource: {\n\t\t\t\t\t\t\ttype: \"base64\",\n\t\t\t\t\t\t\tmedia_type: item.mimeType as \"image/jpeg\" | \"image/png\" | \"image/gif\" | \"image/webp\",\n\t\t\t\t\t\t\tdata: item.data,\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t});\n\t\t\t\tconst filteredBlocks = blocks.filter((b) => {\n\t\t\t\t\tif (b.type === \"text\") {\n\t\t\t\t\t\treturn b.text.trim().length > 0;\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t});\n\t\t\t\tif (filteredBlocks.length === 0) continue;\n\t\t\t\tparams.push({\n\t\t\t\t\trole: \"user\",\n\t\t\t\t\tcontent: filteredBlocks,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (msg.role === \"assistant\") {\n\t\t\tconst blocks = convertAnthropicAssistantContent(msg, {\n\t\t\t\tallowEmptySignature,\n\t\t\t\ttoolName: isOAuthToken ? toClaudeCodeName : undefined,\n\t\t\t});\n\t\t\tif (blocks.length === 0) continue;\n\t\t\tflushPendingSystemMessages();\n\t\t\tconst messageIndex = params.length;\n\t\t\tparams.push({\n\t\t\t\trole: \"assistant\",\n\t\t\t\tcontent: blocks,\n\t\t\t});\n\t\t\tif (\n\t\t\t\tmanagedProvider !== undefined &&\n\t\t\t\tmsg.api === \"anthropic-messages\" &&\n\t\t\t\tmsg.provider === managedProvider &&\n\t\t\t\tisAnthropicEffort(msg.providerThinkingLevel)\n\t\t\t) {\n\t\t\t\tassistantLevels.set(messageIndex, msg.providerThinkingLevel);\n\t\t\t}\n\t\t} else if (msg.role === \"toolResult\") {\n\t\t\t// Collect all consecutive toolResult messages, needed for z.ai Anthropic endpoint.\n\t\t\tconst toolResults: ContentBlockParam[] = [];\n\t\t\t// Anthropic rejects error tool results that contain anything but text, so their images follow\n\t\t\t// all tool results of the turn, which must come first in the user message (#10794).\n\t\t\tconst errorImages: ContentBlockParam[] = [];\n\t\t\tlet j = i;\n\t\t\twhile (j < transformedMessages.length && transformedMessages[j].role === \"toolResult\") {\n\t\t\t\tconst toolMsg = transformedMessages[j] as ToolResultMessage;\n\t\t\t\tconst split = splitErrorToolResultImages(toolMsg);\n\t\t\t\ttoolResults.push(convertToolResult(toolMsg, split?.content));\n\t\t\t\tif (split) {\n\t\t\t\t\terrorImages.push({ type: \"text\", text: split.caption }, ...split.images.map(convertImageBlock));\n\t\t\t\t}\n\t\t\t\tj++;\n\t\t\t}\n\n\t\t\t// Skip the messages we've already processed.\n\t\t\ti = j - 1;\n\n\t\t\tparams.push({\n\t\t\t\trole: \"user\",\n\t\t\t\tcontent: [...toolResults, ...errorImages],\n\t\t\t});\n\t\t}\n\t}\n\n\tflushPendingSystemMessages();\n\n\t// Add cache_control to the last user or system message to cache conversation history\n\tif (cacheControl && params.length > 0) {\n\t\tconst lastMessage = params[params.length - 1];\n\t\tif (lastMessage.role === \"user\" || lastMessage.role === \"system\") {\n\t\t\tif (Array.isArray(lastMessage.content)) {\n\t\t\t\tconst lastBlock = lastMessage.content[lastMessage.content.length - 1];\n\t\t\t\tif (\n\t\t\t\t\tlastBlock &&\n\t\t\t\t\t(lastBlock.type === \"text\" ||\n\t\t\t\t\t\tlastBlock.type === \"image\" ||\n\t\t\t\t\t\tlastBlock.type === \"tool_result\" ||\n\t\t\t\t\t\tlastBlock.type === \"tool_addition\" ||\n\t\t\t\t\t\tlastBlock.type === \"tool_removal\")\n\t\t\t\t) {\n\t\t\t\t\t(lastBlock as any).cache_control = cacheControl;\n\t\t\t\t}\n\t\t\t} else if (typeof lastMessage.content === \"string\") {\n\t\t\t\tlastMessage.content = [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: lastMessage.content,\n\t\t\t\t\t\tcache_control: cacheControl,\n\t\t\t\t\t},\n\t\t\t\t] as any;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { messages: params, assistantLevels };\n}\n\ninterface ConvertedAnthropicMessages {\n\tmessages: MessageParam[];\n\tassistantLevels: Map<number, AnthropicEffort>;\n}\n\nfunction isAnthropicEffort(value: string | undefined): value is AnthropicEffort {\n\treturn value === \"low\" || value === \"medium\" || value === \"high\" || value === \"xhigh\" || value === \"max\";\n}\n\ninterface EffortMessage {\n\trole: \"system\";\n\tcontent: [];\n\toutput_config: { effort: AnthropicEffort };\n}\n\nfunction insertThinkingLevelMessages(\n\tconverted: ConvertedAnthropicMessages,\n\tactiveEffort: AnthropicEffort,\n): Array<MessageParam | EffortMessage> {\n\tconst messages: Array<MessageParam | EffortMessage> = [];\n\tfor (let index = 0; index < converted.messages.length; index++) {\n\t\tconst historicalEffort = converted.assistantLevels.get(index);\n\t\tif (historicalEffort !== undefined) {\n\t\t\tmessages.push({ role: \"system\", content: [], output_config: { effort: historicalEffort } });\n\t\t}\n\t\tmessages.push(converted.messages[index]);\n\t}\n\tmessages.push({ role: \"system\", content: [], output_config: { effort: activeEffort } });\n\treturn messages;\n}\n\nfunction shouldUseFineGrainedToolStreamingBeta(\n\tmodel: Model<\"anthropic-messages\">,\n\tcontext: TranscriptContext,\n): boolean {\n\treturn getCurrentTools(context.messages).length > 0 && !getAnthropicCompat(model).supportsEagerToolInputStreaming;\n}\n\ntype ToolSchemaObject = {\n\ttype?: string | string[];\n\tproperties?: Record<string, unknown>;\n\trequired?: string[];\n\tanyOf?: ToolSchemaObject[];\n\t$defs?: unknown;\n\tdefinitions?: unknown;\n};\n\nfunction projectObjectUnionForAnthropic(\n\tschema: ToolSchemaObject,\n): { properties: Record<string, unknown>; required: string[] } | undefined {\n\tif (schema.properties !== undefined || !Array.isArray(schema.anyOf) || schema.anyOf.length === 0) return undefined;\n\tconst branches = schema.anyOf;\n\tif (\n\t\t!branches.every(\n\t\t\t(branch) =>\n\t\t\t\t(branch.type === undefined ||\n\t\t\t\t\tbranch.type === \"object\" ||\n\t\t\t\t\t(Array.isArray(branch.type) &&\n\t\t\t\t\t\tbranch.type.length > 0 &&\n\t\t\t\t\t\tbranch.type.every((type) => type === \"object\"))) &&\n\t\t\t\tbranch.properties !== undefined,\n\t\t)\n\t)\n\t\treturn undefined;\n\n\tconst variantsByKey = new Map<string, unknown[]>();\n\tfor (const branch of branches) {\n\t\tfor (const [key, propertySchema] of Object.entries(branch.properties ?? {})) {\n\t\t\tconst variants = variantsByKey.get(key);\n\t\t\tif (variants === undefined) {\n\t\t\t\tvariantsByKey.set(key, [propertySchema]);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst serialized = JSON.stringify(propertySchema);\n\t\t\tif (!variants.some((variant) => variant === propertySchema || JSON.stringify(variant) === serialized)) {\n\t\t\t\tvariants.push(propertySchema);\n\t\t\t}\n\t\t}\n\t}\n\n\tconst properties: Record<string, unknown> = Object.fromEntries(\n\t\t[...variantsByKey].flatMap(([key, variants]) => {\n\t\t\tconst first = variants[0];\n\t\t\treturn first === undefined ? [] : [[key, variants.length === 1 ? first : { anyOf: variants }]];\n\t\t}),\n\t);\n\n\treturn {\n\t\tproperties,\n\t\trequired: (branches[0]?.required ?? []).filter((key) =>\n\t\t\tbranches.every((branch) => (branch.required ?? []).includes(key)),\n\t\t),\n\t};\n}\n\nfunction convertTools(\n\ttools: Tool[],\n\tisOAuthToken: boolean,\n\tsupportsEagerToolInputStreaming: boolean,\n\tsupportsStrictTools: boolean,\n\tcacheControl?: CacheControlEphemeral,\n\tdisablePreferredStrictTools = false,\n): BetaTool[] {\n\tif (!tools) return [];\n\n\treturn tools.map((tool, index) => {\n\t\tconst strict =\n\t\t\tdisablePreferredStrictTools && prefersJsonSchemaStrictSampling(tool)\n\t\t\t\t? undefined\n\t\t\t\t: resolveJsonSchemaStrictSampling(tool, supportsStrictTools, ANTHROPIC_STRICT_JSON_SCHEMA_PROFILE);\n\t\tconst parameters = getJsonSchemaToolParameters(tool, strict, ANTHROPIC_STRICT_JSON_SCHEMA_PROFILE);\n\t\tconst schema = parameters as ToolSchemaObject;\n\t\t// Anthropic rejects top-level combinators, so project object-union fields for advertising only.\n\t\t// Local runtime validation still enforces the complete authored union without mutating it.\n\t\tconst projectedUnion = projectObjectUnionForAnthropic(schema);\n\t\tconst legacyInputSchema = {\n\t\t\ttype: \"object\" as const,\n\t\t\tproperties: projectedUnion?.properties ?? schema.properties ?? {},\n\t\t\trequired: projectedUnion?.required ?? schema.required ?? [],\n\t\t\t// Keep shared definitions so property $refs still resolve. Other root keywords stay out:\n\t\t\t// Anthropic rejects root anyOf/oneOf/allOf with a 400.\n\t\t\t...(schema.$defs === undefined ? {} : { $defs: schema.$defs }),\n\t\t\t...(schema.definitions === undefined ? {} : { definitions: schema.definitions }),\n\t\t};\n\t\tconst inputSchema =\n\t\t\tstrict === true && projectedUnion === undefined\n\t\t\t\t? {\n\t\t\t\t\t\t...(parameters as Record<string, unknown>),\n\t\t\t\t\t\t...legacyInputSchema,\n\t\t\t\t\t}\n\t\t\t\t: legacyInputSchema;\n\n\t\treturn {\n\t\t\tname: isOAuthToken ? toClaudeCodeName(tool.name) : tool.name,\n\t\t\tdescription: tool.description,\n\t\t\t...(supportsEagerToolInputStreaming ? { eager_input_streaming: true } : {}),\n\t\t\t...(strict === true ? { strict: true } : {}),\n\t\t\tinput_schema: inputSchema,\n\t\t\t...(cacheControl && index === tools.length - 1 ? { cache_control: cacheControl } : {}),\n\t\t};\n\t});\n}\n\nfunction mapStopReason(\n\treason: Anthropic.Messages.StopReason | string,\n\tstopDetails?: RefusalStopDetails | null,\n): { stopReason: StopReason; errorMessage?: string } {\n\tswitch (reason) {\n\t\tcase \"end_turn\":\n\t\t\treturn { stopReason: \"stop\" };\n\t\tcase \"max_tokens\":\n\t\t\treturn { stopReason: \"length\" };\n\t\tcase \"tool_use\":\n\t\t\treturn { stopReason: \"toolUse\" };\n\t\tcase \"refusal\":\n\t\t\treturn {\n\t\t\t\tstopReason: \"error\",\n\t\t\t\terrorMessage: stopDetails?.explanation || `The model refused to complete the request`,\n\t\t\t};\n\t\tcase \"pause_turn\": // Stop is good enough -> resubmit\n\t\t\treturn { stopReason: \"stop\" };\n\t\tcase \"stop_sequence\":\n\t\t\treturn { stopReason: \"stop\" }; // We don't supply stop sequences, so this should never happen\n\t\tcase \"sensitive\": // Content flagged by safety filters (not yet in SDK types)\n\t\t\treturn { stopReason: \"error\", errorMessage: \"Provider stopped with: sensitive\" };\n\t\tdefault:\n\t\t\t// Handle unknown stop reasons gracefully (API may add new values)\n\t\t\tthrow new Error(`Unhandled stop reason: ${reason}`);\n\t}\n}\n"]}
|