@code-yeongyu/senpi-ai 2026.7.25-2 → 2026.7.26
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/dist/api/anthropic-messages.d.ts.map +1 -1
- package/dist/api/anthropic-messages.js +135 -16
- package/dist/api/anthropic-messages.js.map +1 -1
- package/dist/api/azure-openai-responses.js +1 -1
- package/dist/api/azure-openai-responses.js.map +1 -1
- package/dist/api/bedrock-converse-stream.d.ts.map +1 -1
- package/dist/api/bedrock-converse-stream.js +1 -4
- package/dist/api/bedrock-converse-stream.js.map +1 -1
- package/dist/api/google-shared.d.ts.map +1 -1
- package/dist/api/google-shared.js +4 -3
- package/dist/api/google-shared.js.map +1 -1
- package/dist/api/openai-codex-responses.js +2 -2
- package/dist/api/openai-codex-responses.js.map +1 -1
- package/dist/api/openai-responses-shared.d.ts +1 -0
- package/dist/api/openai-responses-shared.d.ts.map +1 -1
- package/dist/api/openai-responses-shared.js +67 -31
- package/dist/api/openai-responses-shared.js.map +1 -1
- package/dist/api/openai-responses.js +1 -1
- package/dist/api/openai-responses.js.map +1 -1
- package/dist/providers/data/.manifest.json +1 -1
- package/dist/providers/data/openrouter.json +1 -1
- package/dist/utils/retry.d.ts.map +1 -1
- package/dist/utils/retry.js +10 -0
- package/dist/utils/retry.js.map +1 -1
- package/dist/utils/stop-details.d.ts +1 -1
- package/dist/utils/stop-details.d.ts.map +1 -1
- package/dist/utils/stop-details.js +7 -3
- package/dist/utils/stop-details.js.map +1 -1
- package/dist/utils/tool-call-id.d.ts +9 -0
- package/dist/utils/tool-call-id.d.ts.map +1 -0
- package/dist/utils/tool-call-id.js +16 -0
- package/dist/utils/tool-call-id.js.map +1 -0
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"anthropic-messages.js","sourceRoot":"","sources":["../../src/api/anthropic-messages.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,MAAM,mBAAmB,CAAC;AAS1C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;QACpE;YACC,kEAAkE;YAClE,MAAM,IAAI,KAAK,CAAC,0BAA0B,MAAM,EAAE,CAAC,CAAC;IACtD,CAAC;AACF,CAAC","sourcesContent":["import Anthropic from \"@anthropic-ai/sdk\";\nimport type {\n\tCacheControlEphemeral,\n\tContentBlockParam,\n\tMessageCreateParamsStreaming,\n\tMessageParam,\n\tRawMessageStreamEvent,\n\tRefusalStopDetails,\n} from \"@anthropic-ai/sdk/resources/messages.js\";\nimport { calculateCost } from \"../models.ts\";\nimport type {\n\tAnthropicMessagesCompat,\n\tApi,\n\tAssistantMessage,\n\tAssistantStopDetails,\n\tCacheRetention,\n\tContext,\n\tImageContent,\n\tMessage,\n\tModel,\n\tProviderEnv,\n\tProviderNativeContent,\n\tSimpleStreamOptions,\n\tStopReason,\n\tStreamFunction,\n\tStreamOptions,\n\tTextContent,\n\tThinkingContent,\n\tTool,\n\tToolCall,\n\tToolResultMessage,\n} from \"../types.ts\";\nimport { isVideoMimeType } from \"../types.ts\";\nimport { combineAbortSignals } from \"../utils/abort-signals.ts\";\nimport { splitDeferredTools } from \"../utils/deferred-tools.ts\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.ts\";\nimport { headersToRecord, providerHeadersToRecord } from \"../utils/headers.ts\";\nimport { parseJsonWithRepair, parseStreamingJson } from \"../utils/json-parse.ts\";\nimport { getProviderEnvValue } from \"../utils/provider-env.ts\";\nimport { retryProviderRequest } from \"../utils/provider-retry.ts\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.ts\";\nimport {\n\tapplyServerFallbackAbort,\n\tparseServerFallbackReceipt,\n\tparseStickyFallbackReceipt,\n\ttype ServerFallbackReceipt,\n} from \"../utils/server-fallback-receipt.ts\";\nimport { isForcedToolChoiceUnsupportedError, omitToolChoiceParam } from \"../utils/tool-choice-fallback.ts\";\n\nimport { resolveCloudflareBaseUrl } from \"./cloudflare.ts\";\nimport { resolveJsonSchemaStrictSampling } from \"./constrained-sampling.ts\";\nimport { buildCopilotDynamicHeaders, hasCopilotVisionInput } from \"./github-copilot-headers.ts\";\nimport {\n\tANTHROPIC_RESERVED_BODY_KEYS,\n\tadjustMaxTokensForThinking,\n\tbuildBaseOptions,\n\tclampMaxTokensToContext,\n} from \"./simple-options.ts\";\nimport { transformMessages } from \"./transform-messages.ts\";\n\n/**\n * Resolve cache retention preference.\n * Defaults to the provided fallback and uses PI_CACHE_RETENTION for backward compatibility.\n */\nfunction resolveCacheRetention(\n\tcacheRetention?: CacheRetention,\n\tenv?: ProviderEnv,\n\tfallback: CacheRetention = \"short\",\n): 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\tif (typeof process !== \"undefined\" && process.env.PI_CACHE_RETENTION !== undefined) {\n\t\treturn \"short\";\n\t}\n\treturn fallback;\n}\n\nfunction isAnthropicApiBaseUrl(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\nfunction getCacheControl(\n\tmodel: Model<\"anthropic-messages\">,\n\tcacheRetention?: CacheRetention,\n\tenv?: ProviderEnv,\n): { retention: CacheRetention; cacheControl?: CacheControlEphemeral } {\n\tconst retention = resolveCacheRetention(cacheRetention, env, \"long\");\n\tif (retention === \"none\") {\n\t\treturn { retention };\n\t}\n\tconst ttl =\n\t\tretention === \"long\" &&\n\t\tisAnthropicApiBaseUrl(model.baseUrl) &&\n\t\tgetAnthropicCompat(model).supportsLongCacheRetention\n\t\t\t? \"1h\"\n\t\t\t: 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\nconst claudeCodeVersion = \"2.1.75\";\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\n/**\n * Convert content blocks to Anthropic API format\n */\n/**\n * Anthropic-compatible video input block (not in the official SDK types).\n * Kimi's Anthropic-compatible endpoint accepts `{type:\"video\"}` content blocks\n * with the same source shape as images (verified against MoonshotAI/kimi-code\n * kosong anthropic provider).\n */\ninterface AnthropicVideoBlock {\n\ttype: \"video\";\n\tsource: { type: \"base64\"; media_type: string; data: string };\n}\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\t\t| AnthropicVideoBlock\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\tif (isVideoMimeType(block.mimeType)) {\n\t\t\treturn {\n\t\t\t\ttype: \"video\" as const,\n\t\t\t\tsource: {\n\t\t\t\t\ttype: \"base64\" as const,\n\t\t\t\t\tmedia_type: block.mimeType,\n\t\t\t\t\tdata: block.data,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\ttype: \"image\" as const,\n\t\t\tsource: {\n\t\t\t\ttype: \"base64\" as const,\n\t\t\t\tmedia_type: block.mimeType as \"image/jpeg\" | \"image/png\" | \"image/gif\" | \"image/webp\",\n\t\t\t\tdata: block.data,\n\t\t\t},\n\t\t};\n\t});\n\n\t// If only media (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 COMPUTER_USE_BETA_PREFIX = \"computer-use-\";\nconst NATIVE_COMPUTER_TOOL_TYPE = \"computer_20250124\";\nconst ADAPTIVE_THINKING_MODEL_MARKERS = [\n\t\"opus-4-6\",\n\t\"opus-4-7\",\n\t\"opus-4-8\",\n\t\"opus-5\",\n\t\"sonnet-4-6\",\n\t\"sonnet-5\",\n\t\"fable-5\",\n\t\"mythos-5\",\n] as const;\n/**\n * Adaptive families that expose the real `xhigh` effort tier. Everything else on the\n * adaptive ladder tops out at `max` (Opus/Sonnet 4.6 are four-tier: low/medium/high/max).\n */\nconst NATIVE_XHIGH_EFFORT_MODEL_MARKERS = [\n\t\"opus-4-7\",\n\t\"opus-4-8\",\n\t\"opus-5\",\n\t\"sonnet-5\",\n\t\"fable-5\",\n\t\"mythos-5\",\n] as const;\n/**\n * Adaptive families that reject `thinking: {type: \"disabled\"}` outright (verified 400:\n * `\"thinking.type.disabled\" is not supported for this model`). The generated catalog also encodes\n * this as `compat.supportsDisabledThinking: false`, but `models.json` entries and third-party\n * gateway rows carry no generated compat, so the family fact has to live here as well.\n */\nconst DISABLED_THINKING_REJECTING_MODEL_MARKERS = [\"fable-5\", \"mythos-5\"] as const;\nconst CLAUDE_FABLE_OR_MYTHOS_MODEL_ID = /^claude-(?:fable|mythos)(?:-|$)/i;\nconst UNSUPPORTED_NATIVE_COMPUTER_TOOL_MODEL_MARKERS = [\n\t\"opus-4-6\",\n\t\"opus-4.6\",\n\t\"opus-4-7\",\n\t\"opus-4.7\",\n\t\"opus-4-8\",\n\t\"opus-4.8\",\n] as const;\n\ntype UnsignedThinkingReplay = \"text\" | \"empty-signature\";\n\n// A provider can reject its own empty signatures. Learn that capability for one\n// conversation without changing the shared model definition used by other sessions.\nconst unsignedThinkingTextReplayFallbacks = new Set<string>();\n\nfunction unsignedThinkingFallbackKey(\n\tmodel: Model<\"anthropic-messages\">,\n\tsessionId: string | undefined,\n): string | undefined {\n\treturn sessionId === undefined ? undefined : `${sessionId}\\u0000${model.baseUrl}\\u0000${model.id}`;\n}\n\nfunction isInvalidUnsignedThinkingSignatureError(error: unknown): boolean {\n\treturn (\n\t\ttypeof error === \"object\" &&\n\t\terror !== null &&\n\t\t\"status\" in error &&\n\t\t(error as { status?: unknown }).status === 400 &&\n\t\terror instanceof Error &&\n\t\t/Invalid signature in thinking block/i.test(error.message)\n\t);\n}\n\nfunction getAnthropicCompat(\n\tmodel: Model<\"anthropic-messages\">,\n): Required<Omit<AnthropicMessagesCompat, \"forceAdaptiveThinking\">> {\n\t// Auto-detect session affinity and cache control support from provider\n\tconst isFireworks = model.provider === \"fireworks\";\n\tconst isCloudflareAiGatewayAnthropic =\n\t\tmodel.provider === \"cloudflare-ai-gateway\" && model.baseUrl.includes(\"anthropic\");\n\tconst isXiaomi = model.provider === \"xiaomi\" || model.provider.startsWith(\"xiaomi-token-plan-\");\n\treturn {\n\t\tsupportsEagerToolInputStreaming: model.compat?.supportsEagerToolInputStreaming ?? !isFireworks,\n\t\tsupportsLongCacheRetention: model.compat?.supportsLongCacheRetention ?? !isFireworks,\n\t\tsendSessionAffinityHeaders:\n\t\t\tmodel.compat?.sendSessionAffinityHeaders ?? !!(isFireworks || isCloudflareAiGatewayAnthropic),\n\t\tsupportsCacheControlOnTools: model.compat?.supportsCacheControlOnTools ?? !isFireworks,\n\t\tsupportsDisabledThinking: model.compat?.supportsDisabledThinking ?? !isXiaomi,\n\t\tsupportsTemperature: model.compat?.supportsTemperature ?? true,\n\t\tsupportsToolChoice: model.compat?.supportsToolChoice ?? true,\n\t\tsupportsForcedToolChoice:\n\t\t\tmodel.compat?.supportsForcedToolChoice ?? !CLAUDE_FABLE_OR_MYTHOS_MODEL_ID.test(model.id),\n\t\tallowEmptySignature: model.compat?.allowEmptySignature ?? false,\n\t\tunsignedThinkingReplay:\n\t\t\tmodel.compat?.unsignedThinkingReplay ?? (model.compat?.allowEmptySignature ? \"empty-signature\" : \"text\"),\n\t\tsupportsStrictTools: model.compat?.supportsStrictTools ?? false,\n\t\tsupportsToolReferences: model.compat?.supportsToolReferences ?? defaultSupportsToolReferences(model),\n\t\t// Default: first-party Anthropic only. Anthropic-compatible providers\n\t\t// (kimi-coding, fireworks, copilot, gateways) may execute the server-side\n\t\t// search but reject the replayed server_tool_use / web_search_tool_result\n\t\t// blocks on the next request (kimi-coding 400s with `tool_call_id is not\n\t\t// found`).\n\t\tsupportsWebSearch: model.compat?.supportsWebSearch ?? isAnthropicApiBaseUrl(model.baseUrl),\n\t};\n}\n\n/**\n * Default for `supportsToolReferences`: first-party Anthropic models except\n * Haiku (rejects client-side tool_reference blocks) and models that predate\n * tool search (Claude 3.x, Opus/Sonnet 4.0, Opus 4.1).\n */\nfunction defaultSupportsToolReferences(model: Model<\"anthropic-messages\">): boolean {\n\tif (model.provider !== \"anthropic\" || model.id.includes(\"haiku\")) return false;\n\tconst version = model.id.match(/^claude-(?:opus|sonnet|fable)-(\\d+)(?:-(\\d+))?(?:-|$)/);\n\tif (!version) return false;\n\tconst major = Number(version[1]);\n\tconst minor = version[2] && version[2].length < 8 ? Number(version[2]) : 0;\n\treturn major > 4 || (major === 4 && minor >= 5);\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 `streamSimpleAnthropic()` 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 `streamSimpleAnthropic()` 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: (Record<string, string | null> | undefined)[]): Record<string, string | null> {\n\tconst merged: Record<string, string | null> = {};\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 hasAuthorizationHeader(headers?: Record<string, string>): boolean {\n\treturn Object.keys(headers ?? {}).some((name) => name.toLowerCase() === \"authorization\");\n}\n\ninterface ServerSentEvent {\n\tevent: string | null;\n\tdata: string;\n\traw: string[];\n}\n\ntype AnthropicPayloadWithRequestMetadata = MessageCreateParamsStreaming & {\n\theaders?: unknown;\n\textra_body?: unknown;\n};\n\ninterface SseDecoderState {\n\tevent: string | null;\n\tdata: string[];\n\traw: string[];\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null;\n}\n\nconst REPLAYABLE_ANTHROPIC_PROVIDER_NATIVE_TYPES: ReadonlySet<string> = new Set([\n\t\"server_tool_use\",\n\t\"web_search_tool_result\",\n\t\"web_fetch_tool_result\",\n\t\"code_execution_tool_result\",\n\t\"bash_code_execution_tool_result\",\n\t\"text_editor_code_execution_tool_result\",\n\t\"tool_search_tool_result\",\n\t\"container_upload\",\n\t// Server-side fallback beta (server-side-fallback-2026-06-01) emits a\n\t// `fallback` marker mid-response. The marker itself is replayed as a kept\n\t// audit block. Blocks emitted *before* the final marker are the declined\n\t// attempt and are pruned in convertMessages (see lastAnthropicFallbackBoundary\n\t// and collectDiscardedFallbackToolCallIds); the marker onward replays verbatim.\n\t\"fallback\",\n]);\n\nfunction isReplayableAnthropicProviderNativeBlock(raw: unknown): raw is ContentBlockParam {\n\treturn isRecord(raw) && typeof raw.type === \"string\" && REPLAYABLE_ANTHROPIC_PROVIDER_NATIVE_TYPES.has(raw.type);\n}\n\nfunction isSameAnthropicModel(message: AssistantMessage, model: Model<\"anthropic-messages\">): boolean {\n\treturn message.provider === model.provider && message.api === model.api && message.model === model.id;\n}\n\nfunction isAnthropicFallbackMarkerBlock(block: AssistantMessage[\"content\"][number]): boolean {\n\treturn (\n\t\tblock.type === \"providerNative\" &&\n\t\tblock.subtype === \"fallback\" &&\n\t\tisRecord(block.raw) &&\n\t\tblock.raw.type === \"fallback\"\n\t);\n}\n\n// The server-side fallback beta (server-side-fallback-2026-06-01) can emit a\n// `fallback` marker mid-message after a declined attempt is replaced. Blocks\n// before the final marker belong to the discarded attempt: replaying its\n// thinking/tool_use makes the API reject the turn (a discarded tool_use has no\n// matching tool_result after normalization). Returns the index of the last\n// fallback marker, or -1 when the message has none.\nfunction lastAnthropicFallbackBoundary(content: AssistantMessage[\"content\"]): number {\n\tlet boundary = -1;\n\tfor (let index = 0; index < content.length; index++) {\n\t\tif (isAnthropicFallbackMarkerBlock(content[index])) {\n\t\t\tboundary = index;\n\t\t}\n\t}\n\treturn boundary;\n}\n\nfunction isAnthropicServerToolUseBlock(raw: unknown): raw is { readonly type: \"server_tool_use\"; readonly id: string } {\n\treturn isRecord(raw) && raw.type === \"server_tool_use\" && typeof raw.id === \"string\";\n}\n\n// Only tool_use-shaped provider-native blocks (server_tool_use, mcp_tool_use)\n// stream their input via input_json_delta. Result-shaped blocks must replay\n// byte-for-byte (encrypted_content), so never merge an `input` into them.\nfunction isProviderNativeToolUseBlock(raw: unknown): boolean {\n\treturn isRecord(raw) && (raw.type === \"server_tool_use\" || raw.type === \"mcp_tool_use\");\n}\n\n// Endpoints without `supportsWebSearch` reject replayed web-search server-tool\n// blocks (kimi-coding 400s with `tool_call_id is not found`), wedging every\n// subsequent request of the session. Dropping the pair loses the searched\n// context but keeps the conversation usable.\nfunction isAnthropicWebSearchReplayBlock(raw: unknown): boolean {\n\tif (!isRecord(raw)) return false;\n\tif (raw.type === \"web_search_tool_result\") return true;\n\treturn raw.type === \"server_tool_use\" && raw.name === \"web_search\";\n}\n\n// tool_use ids referenced by server-tool result blocks in content[0, boundary).\n// A pre-boundary `server_tool_use` whose id is absent here is unpaired — the\n// fallback interrupted the declined attempt before its result arrived — so\n// replaying it would leave a server tool_use with no adjacent result and 400 the\n// turn. Paired server-tool blocks replay verbatim per the fallback contract.\nfunction pairedServerToolUseIdsBeforeBoundary(content: AssistantMessage[\"content\"], boundary: number): Set<string> {\n\tconst paired = new Set<string>();\n\tfor (let index = 0; index < boundary; index++) {\n\t\tconst block = content[index];\n\t\tif (block.type !== \"providerNative\" || !isRecord(block.raw)) continue;\n\t\tconst toolUseId = block.raw.tool_use_id;\n\t\tif (typeof toolUseId === \"string\") paired.add(toolUseId);\n\t}\n\treturn paired;\n}\n\n// Tool-call ids emitted by a discarded pre-fallback attempt on a same-model\n// assistant turn. These tool_use blocks are dropped from the assistant turn, so\n// their tool_result blocks must be dropped from the following user turn too — an\n// orphaned tool_result triggers its own 400.\nfunction collectDiscardedFallbackToolCallIds(messages: Message[], model: Model<\"anthropic-messages\">): Set<string> {\n\tconst discarded = new Set<string>();\n\tfor (const message of messages) {\n\t\tif (message.role !== \"assistant\" || !isSameAnthropicModel(message, model)) continue;\n\t\tconst boundary = lastAnthropicFallbackBoundary(message.content);\n\t\tif (boundary < 0) continue;\n\t\tfor (let index = 0; index < boundary; index++) {\n\t\t\tconst block = message.content[index];\n\t\t\tif (block.type === \"toolCall\") {\n\t\t\t\tdiscarded.add(block.id);\n\t\t\t}\n\t\t}\n\t}\n\treturn discarded;\n}\n\nfunction stringRecord(value: unknown): Record<string, string> | undefined {\n\tif (!isRecord(value)) {\n\t\treturn undefined;\n\t}\n\n\tconst entries = Object.entries(value);\n\tif (entries.some(([, item]) => typeof item !== \"string\")) {\n\t\treturn undefined;\n\t}\n\n\treturn Object.fromEntries(entries) as Record<string, string>;\n}\n\nfunction isForcedAnthropicToolChoice(toolChoice: MessageCreateParamsStreaming[\"tool_choice\"] | undefined): boolean {\n\treturn isRecord(toolChoice) && (toolChoice.type === \"any\" || toolChoice.type === \"tool\");\n}\n\nfunction extractPayloadRequestMetadata(params: MessageCreateParamsStreaming): {\n\tparams: MessageCreateParamsStreaming;\n\theaders?: Record<string, string>;\n} {\n\tconst payload = params as AnthropicPayloadWithRequestMetadata;\n\tconst headers = stringRecord(payload.headers);\n\n\tif (!(\"headers\" in payload) && !(\"extra_body\" in payload)) {\n\t\treturn headers ? { params, headers } : { params };\n\t}\n\n\tconst stripped: AnthropicPayloadWithRequestMetadata = { ...payload };\n\tdelete stripped.headers;\n\tdelete stripped.extra_body;\n\n\treturn headers ? { params: stripped, headers } : { params: stripped };\n}\n\nfunction removeAnthropicBetaHeaders(\n\theaders: Record<string, string | null> | undefined,\n\tshouldRemoveBeta: (beta: string) => boolean,\n): {\n\tchanged: boolean;\n\theaders?: Record<string, string | null>;\n} {\n\tif (!headers) {\n\t\treturn { changed: false };\n\t}\n\n\tconst nextHeaders: Record<string, string | null> = {};\n\tlet changed = false;\n\n\tfor (const [key, value] of Object.entries(headers)) {\n\t\tif (key.toLowerCase() !== \"anthropic-beta\" || value === null) {\n\t\t\tnextHeaders[key] = value;\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst betas = value\n\t\t\t.split(\",\")\n\t\t\t.map((beta) => beta.trim())\n\t\t\t.filter((beta) => beta.length > 0);\n\t\tconst supportedBetas = betas.filter((beta) => !shouldRemoveBeta(beta));\n\t\tchanged = changed || supportedBetas.length !== betas.length;\n\n\t\tif (supportedBetas.length > 0) {\n\t\t\tnextHeaders[key] = supportedBetas.join(\", \");\n\t\t}\n\t}\n\n\tif (!changed) {\n\t\treturn { changed: false, headers };\n\t}\n\n\treturn {\n\t\tchanged: true,\n\t\theaders: Object.keys(nextHeaders).length > 0 ? nextHeaders : undefined,\n\t};\n}\n\nfunction removeComputerUseBetaHeader(headers: Record<string, string> | undefined): {\n\tchanged: boolean;\n\theaders?: Record<string, string | null>;\n} {\n\treturn removeAnthropicBetaHeaders(headers, (beta) => beta.startsWith(COMPUTER_USE_BETA_PREFIX));\n}\n\nfunction sanitizeAdaptiveThinkingHeaders(\n\tmodel: Model<\"anthropic-messages\">,\n\theaders: Record<string, string | null>,\n): Record<string, string | null> {\n\tif (!supportsAdaptiveThinking(model)) {\n\t\treturn headers;\n\t}\n\n\tconst headerSanitization = removeAnthropicBetaHeaders(headers, (beta) => beta === INTERLEAVED_THINKING_BETA);\n\treturn headerSanitization.changed ? (headerSanitization.headers ?? {}) : headers;\n}\n\nfunction rejectsNativeComputerTool(model: Model<\"anthropic-messages\">, toolType: string): boolean {\n\tif (model.provider === \"cloudflare-ai-gateway\" && model.baseUrl.includes(\"anthropic\")) {\n\t\treturn toolType.startsWith(\"computer_\");\n\t}\n\treturn (\n\t\tmatchesModelMarker(model, UNSUPPORTED_NATIVE_COMPUTER_TOOL_MODEL_MARKERS) &&\n\t\ttoolType === NATIVE_COMPUTER_TOOL_TYPE\n\t);\n}\n\nfunction rejectsComputerUseBeta(model: Model<\"anthropic-messages\">): boolean {\n\treturn (\n\t\t(model.provider === \"cloudflare-ai-gateway\" && model.baseUrl.includes(\"anthropic\")) ||\n\t\tmatchesModelMarker(model, UNSUPPORTED_NATIVE_COMPUTER_TOOL_MODEL_MARKERS)\n\t);\n}\n\nfunction isAnthropicWebSearchToolType(toolType: string): boolean {\n\treturn toolType.startsWith(\"web_search_\");\n}\n\nfunction sanitizeUnsupportedNativeTools(\n\tmodel: Model<\"anthropic-messages\">,\n\tparams: MessageCreateParamsStreaming,\n): MessageCreateParamsStreaming {\n\tconst payload = params as AnthropicPayloadWithRequestMetadata;\n\tconst headers = stringRecord(payload.headers);\n\tconst headerSanitization = rejectsComputerUseBeta(model)\n\t\t? removeComputerUseBetaHeader(headers)\n\t\t: ({ changed: false } as const);\n\tconst rejectsNativeWebSearch = !getAnthropicCompat(model).supportsWebSearch;\n\tconst tools = payload.tools;\n\tconst sanitized: AnthropicPayloadWithRequestMetadata = { ...payload };\n\tlet changed = false;\n\n\tif (Array.isArray(tools)) {\n\t\tconst supportedTools: typeof tools = [];\n\n\t\tfor (const tool of tools) {\n\t\t\tconst hookTool: unknown = tool;\n\t\t\tif (\n\t\t\t\tisRecord(hookTool) &&\n\t\t\t\ttypeof hookTool.type === \"string\" &&\n\t\t\t\t(rejectsNativeComputerTool(model, hookTool.type) ||\n\t\t\t\t\t(rejectsNativeWebSearch && isAnthropicWebSearchToolType(hookTool.type)))\n\t\t\t) {\n\t\t\t\tchanged = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tsupportedTools.push(tool);\n\t\t}\n\n\t\tif (changed) {\n\t\t\tif (supportedTools.length > 0) {\n\t\t\t\tsanitized.tools = supportedTools;\n\t\t\t} else {\n\t\t\t\tdelete sanitized.tools;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (headerSanitization.changed) {\n\t\tchanged = true;\n\t\tif (headerSanitization.headers) {\n\t\t\tsanitized.headers = headerSanitization.headers;\n\t\t} else {\n\t\t\tdelete sanitized.headers;\n\t\t}\n\t}\n\n\tif (changed && isRecord(sanitized.tool_choice)) {\n\t\tconst toolChoiceName = sanitized.tool_choice.name;\n\t\tconst hasSelectedTool =\n\t\t\ttypeof toolChoiceName === \"string\" &&\n\t\t\tArray.isArray(sanitized.tools) &&\n\t\t\tsanitized.tools.some((tool) => isRecord(tool) && tool.name === toolChoiceName);\n\t\tconst shouldRemoveToolChoice =\n\t\t\tsanitized.tools === undefined || (typeof toolChoiceName === \"string\" && !hasSelectedTool);\n\t\tif (shouldRemoveToolChoice) {\n\t\t\tdelete sanitized.tool_choice;\n\t\t}\n\t}\n\n\treturn changed ? (sanitized as MessageCreateParamsStreaming) : params;\n}\n\nfunction sanitizeAdaptiveThinkingPayload(\n\tmodel: Model<\"anthropic-messages\">,\n\tparams: MessageCreateParamsStreaming,\n\toptions?: AnthropicOptions,\n): MessageCreateParamsStreaming {\n\tif (!supportsAdaptiveThinking(model)) {\n\t\treturn params;\n\t}\n\n\tconst payload = params as AnthropicPayloadWithRequestMetadata;\n\tconst headers = stringRecord(payload.headers);\n\tconst headerSanitization = removeAnthropicBetaHeaders(headers, (beta) => beta === INTERLEAVED_THINKING_BETA);\n\tconst sanitized: AnthropicPayloadWithRequestMetadata = { ...payload };\n\tlet changed = false;\n\n\tconst thinking = isRecord(payload.thinking) ? payload.thinking : undefined;\n\tif (thinking?.type === \"enabled\") {\n\t\tconst display =\n\t\t\tthinking.display === \"omitted\" || thinking.display === \"summarized\"\n\t\t\t\t? thinking.display\n\t\t\t\t: (options?.thinkingDisplay ?? \"summarized\");\n\t\tsanitized.thinking = { type: \"adaptive\", display } as MessageCreateParamsStreaming[\"thinking\"];\n\t\tif (options?.effort !== undefined && !isRecord(payload.output_config)) {\n\t\t\tsanitized.output_config = { effort: options.effort } as NonNullable<\n\t\t\t\tMessageCreateParamsStreaming[\"output_config\"]\n\t\t\t>;\n\t\t}\n\t\tchanged = true;\n\t}\n\n\tif (headerSanitization.changed) {\n\t\tchanged = true;\n\t\tif (headerSanitization.headers) {\n\t\t\tsanitized.headers = headerSanitization.headers;\n\t\t} else {\n\t\t\tdelete sanitized.headers;\n\t\t}\n\t}\n\n\treturn changed ? (sanitized as MessageCreateParamsStreaming) : params;\n}\n\nfunction isCacheableUserContentBlock(\n\tblock: ContentBlockParam | undefined,\n): block is Extract<ContentBlockParam, { type: \"text\" | \"image\" | \"tool_result\" }> {\n\treturn block?.type === \"text\" || block?.type === \"image\" || block?.type === \"tool_result\";\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\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\treader.releaseLock();\n\t}\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\tthrow new Error(sse.data);\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: Context,\n\toptions?: AnthropicOptions,\n): AssistantMessageEventStream => {\n\tconst stream = new AssistantMessageEventStream();\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: \"stop\",\n\t\t\ttimestamp: Date.now(),\n\t\t};\n\n\t\tconst serverFallbackAbort = new AbortController();\n\t\tlet serverFallbackReceipt: ServerFallbackReceipt | undefined;\n\t\tconst combinedAbort = combineAbortSignals([options?.signal, serverFallbackAbort.signal]);\n\t\tconst requestSignal = combinedAbort.signal;\n\t\ttry {\n\t\t\tlet client: Anthropic;\n\t\t\tlet isOAuth: boolean;\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 optionsHeaders = providerHeadersToRecord(options?.headers);\n\t\t\t\tif (!apiKey && !hasAuthorizationHeader(optionsHeaders)) {\n\t\t\t\t\tthrow new Error(`No API key for provider: ${model.provider}`);\n\t\t\t\t}\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(context.messages);\n\t\t\t\t\tcopilotDynamicHeaders = buildCopilotDynamicHeaders({\n\t\t\t\t\t\tmessages: context.messages,\n\t\t\t\t\t\thasImages,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tconst cacheRetention = resolveCacheRetention(\n\t\t\t\t\toptions?.cacheRetention ?? model.cacheRetention,\n\t\t\t\t\toptions?.env,\n\t\t\t\t\t\"long\",\n\t\t\t\t);\n\t\t\t\tconst cacheSessionId = cacheRetention === \"none\" ? undefined : options?.sessionId;\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\toptions?.interleavedThinking ?? true,\n\t\t\t\t\tshouldUseFineGrainedToolStreamingBeta(model, context),\n\t\t\t\t\toptionsHeaders,\n\t\t\t\t\tcopilotDynamicHeaders,\n\t\t\t\t\tcacheSessionId,\n\t\t\t\t\toptions?.env,\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 fallbackKey = unsignedThinkingFallbackKey(model, options?.sessionId);\n\t\t\tlet unsignedThinkingReplay: UnsignedThinkingReplay =\n\t\t\t\tfallbackKey && unsignedThinkingTextReplayFallbacks.has(fallbackKey)\n\t\t\t\t\t? \"text\"\n\t\t\t\t\t: getAnthropicCompat(model).unsignedThinkingReplay;\n\t\t\tconst createRequest = async (): Promise<{ params: MessageCreateParamsStreaming; response: Response }> => {\n\t\t\t\tlet params = buildParams(model, context, isOAuth, options, unsignedThinkingReplay);\n\t\t\t\tconst nextParams = await options?.onPayload?.(params, model);\n\t\t\t\tif (nextParams !== undefined) {\n\t\t\t\t\tparams = nextParams as MessageCreateParamsStreaming;\n\t\t\t\t}\n\t\t\t\tparams = sanitizeAdaptiveThinkingPayload(model, params, options);\n\t\t\t\tparams = sanitizeUnsupportedNativeTools(model, params);\n\t\t\t\tconst payloadRequestMetadata = extractPayloadRequestMetadata(params);\n\t\t\t\tparams = payloadRequestMetadata.params;\n\t\t\t\tconst requestOptions = {\n\t\t\t\t\t...(requestSignal ? { signal: requestSignal } : {}),\n\t\t\t\t\t...(options?.timeoutMs !== undefined ? { timeout: options.timeoutMs } : {}),\n\t\t\t\t\tmaxRetries: 0,\n\t\t\t\t\t...(payloadRequestMetadata.headers ? { headers: payloadRequestMetadata.headers } : {}),\n\t\t\t\t};\n\t\t\t\ttry {\n\t\t\t\t\tconst response = await client.messages.create({ ...params, stream: true }, requestOptions).asResponse();\n\t\t\t\t\treturn { params, response };\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (isForcedToolChoiceUnsupportedError(error, isForcedAnthropicToolChoice(params.tool_choice))) {\n\t\t\t\t\t\tparams = omitToolChoiceParam(params);\n\t\t\t\t\t\tconst response = await client.messages\n\t\t\t\t\t\t\t.create({ ...params, stream: true }, requestOptions)\n\t\t\t\t\t\t\t.asResponse();\n\t\t\t\t\t\treturn { params, response };\n\t\t\t\t\t}\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t};\n\t\t\tconst { params: sentParams, response } = await retryProviderRequest(\n\t\t\t\tasync () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\treturn await createRequest();\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (unsignedThinkingReplay !== \"text\" && isInvalidUnsignedThinkingSignatureError(error)) {\n\t\t\t\t\t\t\tunsignedThinkingReplay = \"text\";\n\t\t\t\t\t\t\tif (fallbackKey) unsignedThinkingTextReplayFallbacks.add(fallbackKey);\n\t\t\t\t\t\t\treturn createRequest();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tmaxRetries: options?.maxRetries,\n\t\t\t\t\tmaxRetryDelayMs: options?.maxRetryDelayMs,\n\t\t\t\t\tsignal: requestSignal,\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\n\t\t\ttype Block =\n\t\t\t\t| (ThinkingContent & { index?: number })\n\t\t\t\t| (TextContent & { index?: number })\n\t\t\t\t| ((ToolCall & { partialJson: string }) & { index?: number })\n\t\t\t\t| (ProviderNativeContent & { partialJson?: string; index?: number });\n\t\t\tconst blocks = output.content as Block[];\n\n\t\t\tfor await (const event of iterateAnthropicEvents(response, requestSignal)) {\n\t\t\t\tif (event.type === \"message_start\") {\n\t\t\t\t\toutput.responseId = event.message.id;\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(model, output.usage);\n\t\t\t\t\tconst stickyReceipt =\n\t\t\t\t\t\toptions?.abortServerSideFallback === true\n\t\t\t\t\t\t\t? parseStickyFallbackReceipt(event.message.usage, sentParams.model, event.message.model)\n\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\tif (stickyReceipt !== undefined) {\n\t\t\t\t\t\tserverFallbackReceipt = stickyReceipt;\n\t\t\t\t\t\tserverFallbackAbort.abort();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t} else if (event.type === \"content_block_start\") {\n\t\t\t\t\tconst receipt =\n\t\t\t\t\t\toptions?.abortServerSideFallback === true\n\t\t\t\t\t\t\t? parseServerFallbackReceipt(event.content_block)\n\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\tif (receipt !== undefined) {\n\t\t\t\t\t\tserverFallbackReceipt = receipt;\n\t\t\t\t\t\tserverFallbackAbort.abort();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tif (event.content_block.type === \"text\") {\n\t\t\t\t\t\tconst block: Block = {\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: \"\",\n\t\t\t\t\t\t\tindex: event.index,\n\t\t\t\t\t\t};\n\t\t\t\t\t\toutput.content.push(block);\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\tconst block: Block = {\n\t\t\t\t\t\t\ttype: \"thinking\",\n\t\t\t\t\t\t\tthinking: \"\",\n\t\t\t\t\t\t\tthinkingSignature: \"\",\n\t\t\t\t\t\t\tindex: event.index,\n\t\t\t\t\t\t};\n\t\t\t\t\t\toutput.content.push(block);\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\tconst block: Block = {\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\tindex: event.index,\n\t\t\t\t\t\t};\n\t\t\t\t\t\toutput.content.push(block);\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\tconst block: Block = {\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, context.tools)\n\t\t\t\t\t\t\t\t: event.content_block.name,\n\t\t\t\t\t\t\targuments: isRecord(event.content_block.input) ? event.content_block.input : {},\n\t\t\t\t\t\t\tpartialJson: \"\",\n\t\t\t\t\t\t\tindex: event.index,\n\t\t\t\t\t\t};\n\t\t\t\t\t\toutput.content.push(block);\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 {\n\t\t\t\t\t\tconst block: Block = {\n\t\t\t\t\t\t\ttype: \"providerNative\",\n\t\t\t\t\t\t\tsubtype: event.content_block.type,\n\t\t\t\t\t\t\traw: event.content_block,\n\t\t\t\t\t\t\tindex: event.index,\n\t\t\t\t\t\t};\n\t\t\t\t\t\toutput.content.push(block);\n\t\t\t\t\t\t// Native blocks are represented in output.content but have no dedicated stream event variant.\n\t\t\t\t\t}\n\t\t\t\t} else if (event.type === \"content_block_delta\") {\n\t\t\t\t\tif (event.delta.type === \"text_delta\") {\n\t\t\t\t\t\tconst index = blocks.findIndex((b) => b.index === event.index);\n\t\t\t\t\t\tconst block = blocks[index];\n\t\t\t\t\t\tif (block && block.type === \"text\") {\n\t\t\t\t\t\t\tblock.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: index,\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\tconst index = blocks.findIndex((b) => b.index === event.index);\n\t\t\t\t\t\tconst block = blocks[index];\n\t\t\t\t\t\tif (block && block.type === \"thinking\") {\n\t\t\t\t\t\t\tblock.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: index,\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\tconst index = blocks.findIndex((b) => b.index === event.index);\n\t\t\t\t\t\tconst block = blocks[index];\n\t\t\t\t\t\tif (block && block.type === \"toolCall\") {\n\t\t\t\t\t\t\tblock.partialJson += event.delta.partial_json;\n\t\t\t\t\t\t\tblock.arguments = parseStreamingJson(block.partialJson);\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: index,\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} else if (block && block.type === \"providerNative\" && isProviderNativeToolUseBlock(block.raw)) {\n\t\t\t\t\t\t\t// Server-side tool blocks (server_tool_use) stream their input\n\t\t\t\t\t\t\t// the same way tool_use does; the block captured at\n\t\t\t\t\t\t\t// content_block_start still has `input: {}`.\n\t\t\t\t\t\t\tblock.partialJson = (block.partialJson ?? \"\") + event.delta.partial_json;\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\tconst index = blocks.findIndex((b) => b.index === event.index);\n\t\t\t\t\t\tconst block = blocks[index];\n\t\t\t\t\t\tif (block && block.type === \"thinking\") {\n\t\t\t\t\t\t\tblock.thinkingSignature = block.thinkingSignature || \"\";\n\t\t\t\t\t\t\tblock.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 index = blocks.findIndex((b) => b.index === event.index);\n\t\t\t\t\tconst block = blocks[index];\n\t\t\t\t\tif (block) {\n\t\t\t\t\t\tdelete block.index;\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\") {\n\t\t\t\t\t\t\tblock.arguments = parseStreamingJson(block.partialJson);\n\t\t\t\t\t\t\t// Finalize in-place and strip the scratch buffer so replay only\n\t\t\t\t\t\t\t// carries parsed arguments.\n\t\t\t\t\t\t\tdelete (block as { partialJson?: string }).partialJson;\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} else if (block.type === \"providerNative\") {\n\t\t\t\t\t\t\tconst partialJson = block.partialJson;\n\t\t\t\t\t\t\tdelete block.partialJson;\n\t\t\t\t\t\t\tif (partialJson !== undefined && isRecord(block.raw)) {\n\t\t\t\t\t\t\t\tblock.raw = { ...block.raw, input: parseStreamingJson(partialJson) };\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\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\tif (stopReasonResult.stopDetails) {\n\t\t\t\t\t\t\toutput.stopDetails = stopReasonResult.stopDetails;\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\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(model, output.usage);\n\t\t\t\t}\n\t\t\t}\n\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 (serverFallbackReceipt !== undefined) {\n\t\t\t\tapplyServerFallbackAbort(output, serverFallbackReceipt);\n\t\t\t}\n\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\n\t\t\tcombinedAbort.cleanup();\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\tcombinedAbort.cleanup();\n\t\t\tfor (const block of output.content) {\n\t\t\t\tdelete (block as { index?: number }).index;\n\t\t\t\t// An aborted stream never reaches content_block_stop; keep whatever\n\t\t\t\t// provider-native input accumulated, mirroring toolCall's partial\n\t\t\t\t// arguments.\n\t\t\t\tconst scratch = (block as { partialJson?: string }).partialJson;\n\t\t\t\tif (block.type === \"providerNative\" && scratch !== undefined && isRecord(block.raw)) {\n\t\t\t\t\tblock.raw = { ...block.raw, input: parseStreamingJson(scratch) };\n\t\t\t\t}\n\t\t\t\t// partialJson is only a streaming scratch buffer; never persist it.\n\t\t\t\tdelete (block as { partialJson?: string }).partialJson;\n\t\t\t}\n\t\t\toutput.stopReason = options?.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\toutput.errorMessage = error instanceof Error ? error.message : JSON.stringify(error);\n\t\t\tstream.push({ type: \"error\", reason: output.stopReason, error: output });\n\t\t\tstream.end();\n\t\t}\n\t})();\n\n\treturn stream;\n};\n\n/**\n * Opus-specific feature checks use provider model ids because those behaviors\n * are model-tier details, not custom-provider compatibility toggles.\n */\nfunction getModelMatchCandidates(model: Pick<Model<\"anthropic-messages\">, \"id\" | \"name\">): string[] {\n\treturn [model.id, model.name].flatMap((value) => {\n\t\tconst lower = value.toLowerCase();\n\t\treturn [lower, lower.replace(/[\\s_.:]+/g, \"-\")];\n\t});\n}\n\nfunction matchesModelMarker(\n\tmodel: Pick<Model<\"anthropic-messages\">, \"id\" | \"name\">,\n\tmarkers: readonly string[],\n): boolean {\n\tconst candidates = getModelMatchCandidates(model);\n\treturn candidates.some((candidate) => markers.some((marker) => candidate.includes(marker)));\n}\n\nfunction supportsNativeXhighEffort(model: Pick<Model<\"anthropic-messages\">, \"id\" | \"name\">): boolean {\n\treturn matchesModelMarker(model, NATIVE_XHIGH_EFFORT_MODEL_MARKERS);\n}\n\n/** True when the model cannot accept `thinking: {type: \"disabled\"}` on the wire. */\nfunction cannotDisableThinking(\n\tmodel: Model<\"anthropic-messages\">,\n\tcompat: { supportsDisabledThinking: boolean },\n): boolean {\n\tif (!compat.supportsDisabledThinking) return true;\n\tif (model.thinkingLevelMap?.off === null) return true;\n\treturn matchesModelMarker(model, DISABLED_THINKING_REJECTING_MODEL_MARKERS);\n}\n\nfunction supportsAdaptiveThinking(model: Model<\"anthropic-messages\">): boolean {\n\tif (model.compat?.forceAdaptiveThinking !== undefined) {\n\t\treturn model.compat.forceAdaptiveThinking;\n\t}\n\treturn matchesModelMarker(model, ADAPTIVE_THINKING_MODEL_MARKERS);\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 only available on Opus 4.7/4.8, Opus 5, Sonnet 5, and Fable 5.\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\tcase \"xhigh\":\n\t\t\t// Only called for adaptive models, so the floor is the adaptive ladder's top\n\t\t\t// tier (`max`), never `high` — degrading xhigh to high silently under-thinks.\n\t\t\treturn supportsNativeXhighEffort(model) ? \"xhigh\" : \"max\";\n\t\tcase \"max\":\n\t\t\treturn \"max\";\n\t\tdefault:\n\t\t\treturn \"high\";\n\t}\n}\n\nexport const streamSimple: StreamFunction<\"anthropic-messages\", SimpleStreamOptions> = (\n\tmodel: Model<\"anthropic-messages\">,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): AssistantMessageEventStream => {\n\tconst apiKey = options?.apiKey;\n\tif (!apiKey && !hasAuthorizationHeader(providerHeadersToRecord(options?.headers))) {\n\t\tthrow new Error(`No API key for provider: ${model.provider}`);\n\t}\n\n\tconst base = buildBaseOptions(model, context, options, options?.apiKey);\n\tif (!options?.reasoning) {\n\t\treturn stream(model, context, { ...base, thinkingEnabled: false } 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 (supportsAdaptiveThinking(model)) {\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\toptionsHeaders?: Record<string, string>,\n\tdynamicHeaders?: Record<string, string>,\n\tsessionId?: string,\n\tenv?: ProviderEnv,\n): { client: Anthropic; isOAuthToken: boolean } {\n\t// Adaptive thinking models have interleaved thinking built in, so skip the beta header.\n\tconst needsInterleavedBeta = interleavedThinking && !supportsAdaptiveThinking(model);\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\n\tif (model.provider === \"cloudflare-ai-gateway\") {\n\t\tconst client = new Anthropic({\n\t\t\tapiKey: null,\n\t\t\tauthToken: null,\n\t\t\tbaseURL: resolveCloudflareBaseUrl(model, env),\n\t\t\tdangerouslyAllowBrowser: true,\n\t\t\tdefaultHeaders: sanitizeAdaptiveThinkingHeaders(\n\t\t\t\tmodel,\n\t\t\t\tmergeHeaders(\n\t\t\t\t\t{\n\t\t\t\t\t\taccept: \"application/json\",\n\t\t\t\t\t\t\"anthropic-dangerous-direct-browser-access\": \"true\",\n\t\t\t\t\t\t\"cf-aig-authorization\": `Bearer ${apiKey}`,\n\t\t\t\t\t\t\"x-api-key\": null,\n\t\t\t\t\t\tAuthorization: null,\n\t\t\t\t\t\t...(betaFeatures.length > 0 ? { \"anthropic-beta\": betaFeatures.join(\",\") } : {}),\n\t\t\t\t\t},\n\t\t\t\t\tmodel.headers,\n\t\t\t\t\toptionsHeaders,\n\t\t\t\t),\n\t\t\t),\n\t\t});\n\n\t\treturn { client, isOAuthToken: false };\n\t}\n\n\t// Copilot: Bearer auth, selective betas.\n\tif (model.provider === \"github-copilot\") {\n\t\tconst client = new Anthropic({\n\t\t\tapiKey: null,\n\t\t\tauthToken: apiKey,\n\t\t\tbaseURL: model.baseUrl,\n\t\t\tdangerouslyAllowBrowser: true,\n\t\t\tdefaultHeaders: sanitizeAdaptiveThinkingHeaders(\n\t\t\t\tmodel,\n\t\t\t\tmergeHeaders(\n\t\t\t\t\t{\n\t\t\t\t\t\taccept: \"application/json\",\n\t\t\t\t\t\t\"anthropic-dangerous-direct-browser-access\": \"true\",\n\t\t\t\t\t\t...(betaFeatures.length > 0 ? { \"anthropic-beta\": betaFeatures.join(\",\") } : {}),\n\t\t\t\t\t},\n\t\t\t\t\tmodel.headers,\n\t\t\t\t\tdynamicHeaders,\n\t\t\t\t\toptionsHeaders,\n\t\t\t\t),\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\n\tif (apiKey && isOAuthToken(apiKey)) {\n\t\tconst client = new Anthropic({\n\t\t\tapiKey: null,\n\t\t\tauthToken: apiKey,\n\t\t\tbaseURL: model.baseUrl,\n\t\t\tdangerouslyAllowBrowser: true,\n\t\t\tdefaultHeaders: sanitizeAdaptiveThinkingHeaders(\n\t\t\t\tmodel,\n\t\t\t\tmergeHeaders(\n\t\t\t\t\t{\n\t\t\t\t\t\taccept: \"application/json\",\n\t\t\t\t\t\t\"anthropic-dangerous-direct-browser-access\": \"true\",\n\t\t\t\t\t\t\"anthropic-beta\": [\"claude-code-20250219\", \"oauth-2025-04-20\", ...betaFeatures].join(\",\"),\n\t\t\t\t\t\t\"user-agent\": `claude-cli/${claudeCodeVersion}`,\n\t\t\t\t\t\t\"x-app\": \"cli\",\n\t\t\t\t\t},\n\t\t\t\t\tmodel.headers,\n\t\t\t\t\toptionsHeaders,\n\t\t\t\t),\n\t\t\t),\n\t\t});\n\n\t\treturn { client, isOAuthToken: true };\n\t}\n\n\t// API key auth\n\tconst sessionAffinityHeaders: Record<string, string | null> =\n\t\tsessionId && getAnthropicCompat(model).sendSessionAffinityHeaders ? { \"x-session-affinity\": sessionId } : {};\n\tconst client = new Anthropic({\n\t\tapiKey: apiKey ?? null,\n\t\tauthToken: null,\n\t\tbaseURL: model.baseUrl,\n\t\tdangerouslyAllowBrowser: true,\n\t\tdefaultHeaders: sanitizeAdaptiveThinkingHeaders(\n\t\t\tmodel,\n\t\t\tmergeHeaders(\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...(betaFeatures.length > 0 ? { \"anthropic-beta\": betaFeatures.join(\",\") } : {}),\n\t\t\t\t},\n\t\t\t\tsessionAffinityHeaders,\n\t\t\t\tmodel.headers,\n\t\t\t\toptionsHeaders,\n\t\t\t),\n\t\t),\n\t});\n\n\treturn { client, isOAuthToken: false };\n}\n\nfunction buildParams(\n\tmodel: Model<\"anthropic-messages\">,\n\tcontext: Context,\n\tisOAuthToken: boolean,\n\toptions?: AnthropicOptions,\n\tunsignedThinkingReplay = getAnthropicCompat(model).unsignedThinkingReplay,\n): MessageCreateParamsStreaming {\n\tconst compat = getAnthropicCompat(model);\n\tconst { cacheControl } = getCacheControl(model, options?.cacheRetention ?? model.cacheRetention, options?.env);\n\tconst transformedMessages = transformMessages(context.messages, model, normalizeToolCallId, {\n\t\tpreserveThinking: options?.thinkingEnabled === true,\n\t\tpreserveUnsignedThinking: true,\n\t});\n\tconst normalizeToolName = isOAuthToken ? toClaudeCodeName : (name: string) => name;\n\t// A marker on a discarded pre-fallback result must not defer its tool:\n\t// convertMessages drops that result, so no tool_reference would replay to\n\t// load the deferred definition.\n\tconst discardedFallbackToolCallIds = collectDiscardedFallbackToolCallIds(transformedMessages, model);\n\tconst partitionMessages = transformedMessages.filter(\n\t\t(message) => !(message.role === \"toolResult\" && discardedFallbackToolCallIds.has(message.toolCallId)),\n\t);\n\tconst toolPlacement = splitDeferredTools(\n\t\t{ ...context, messages: partitionMessages },\n\t\tcompat.supportsToolReferences,\n\t\tnormalizeToolName,\n\t);\n\tlet immediateTools = toolPlacement.immediate;\n\tlet deferredTools = [...toolPlacement.deferred.values()];\n\tif (immediateTools.length === 0 && deferredTools.length > 0) {\n\t\timmediateTools = deferredTools;\n\t\tdeferredTools = [];\n\t}\n\tconst deferredToolNames = new Set(deferredTools.map((tool) => normalizeToolName(tool.name)));\n\tconst params: MessageCreateParamsStreaming = {\n\t\tmodel: model.id,\n\t\tmessages: convertMessages(\n\t\t\ttransformedMessages,\n\t\t\tmodel,\n\t\t\tisOAuthToken,\n\t\t\tcacheControl,\n\t\t\tunsignedThinkingReplay,\n\t\t\tdeferredToolNames,\n\t\t\tnormalizeToolName,\n\t\t),\n\t\tmax_tokens: options?.maxTokens ?? model.maxTokens,\n\t\tstream: true,\n\t};\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 (context.systemPrompt) {\n\t\t\tparams.system.push({\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: sanitizeSurrogates(context.systemPrompt),\n\t\t\t\t...(cacheControl ? { cache_control: cacheControl } : {}),\n\t\t\t});\n\t\t}\n\t} else if (context.systemPrompt) {\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(context.systemPrompt),\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 (options?.temperature !== undefined && !options?.thinkingEnabled && compat.supportsTemperature) {\n\t\tObject.defineProperty(params, \"temperature\", {\n\t\t\tvalue: options.temperature,\n\t\t\twritable: true,\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t});\n\t}\n\n\tif (immediateTools.length > 0 || deferredTools.length > 0) {\n\t\tparams.tools = [\n\t\t\t...convertTools(\n\t\t\t\timmediateTools,\n\t\t\t\tisOAuthToken,\n\t\t\t\tcompat.supportsEagerToolInputStreaming,\n\t\t\t\tcompat.supportsStrictTools,\n\t\t\t\tcompat.supportsCacheControlOnTools ? cacheControl : undefined,\n\t\t\t),\n\t\t\t...convertTools(\n\t\t\t\tdeferredTools,\n\t\t\t\tisOAuthToken,\n\t\t\t\tcompat.supportsEagerToolInputStreaming,\n\t\t\t\tcompat.supportsStrictTools,\n\t\t\t\tundefined,\n\t\t\t\ttrue,\n\t\t\t),\n\t\t];\n\t}\n\n\t// Configure thinking mode: adaptive, budget-based, or explicitly disabled.\n\tif (model.reasoning) {\n\t\tif (options?.thinkingEnabled) {\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\tif (supportsAdaptiveThinking(model)) {\n\t\t\t\t// Adaptive thinking: Claude decides when and how much to think.\n\t\t\t\tparams.thinking = { type: \"adaptive\", display } as MessageCreateParamsStreaming[\"thinking\"];\n\t\t\t\tif (options.effort) {\n\t\t\t\t\t// The Anthropic SDK types can lag newly supported effort values such as \"xhigh\" and \"max\".\n\t\t\t\t\tparams.output_config = { effort: options.effort } as NonNullable<\n\t\t\t\t\t\tMessageCreateParamsStreaming[\"output_config\"]\n\t\t\t\t\t>;\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} as MessageCreateParamsStreaming[\"thinking\"];\n\t\t\t}\n\t\t} else if (options?.thinkingEnabled === false) {\n\t\t\tif (cannotDisableThinking(model, compat)) {\n\t\t\t\t// These families reject `thinking.type: \"disabled\"` with a 400 AND default to adaptive\n\t\t\t\t// thinking when the field is absent, so omitting it silently bills full reasoning for a\n\t\t\t\t// \"thinking off\" turn. The API exposes no true off switch here, so pin the cheapest\n\t\t\t\t// effort: the request stays valid and reasoning stays at the documented minimum.\n\t\t\t\tif (supportsAdaptiveThinking(model)) {\n\t\t\t\t\tparams.output_config = { effort: \"low\" } as NonNullable<MessageCreateParamsStreaming[\"output_config\"]>;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tparams.thinking = { type: \"disabled\" };\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 && compat.supportsToolChoice) {\n\t\tconst isForcedToolChoice = options.toolChoice === \"any\" || typeof options.toolChoice === \"object\";\n\t\tif (!isForcedToolChoice || compat.supportsForcedToolChoice) {\n\t\t\tif (typeof options.toolChoice === \"string\") {\n\t\t\t\tparams.tool_choice = { type: options.toolChoice };\n\t\t\t} else {\n\t\t\t\tparams.tool_choice = options.toolChoice;\n\t\t\t}\n\t\t}\n\t}\n\n\tapplyExtraBodyToAnthropicParams(params, options?.extraBody);\n\n\treturn params;\n}\n\nfunction applyExtraBodyToAnthropicParams(\n\tparams: MessageCreateParamsStreaming,\n\textraBody: Record<string, unknown> | undefined,\n): void {\n\tif (!extraBody) return;\n\tfor (const [key, value] of Object.entries(extraBody)) {\n\t\tif (ANTHROPIC_RESERVED_BODY_KEYS.has(key)) continue;\n\t\tObject.defineProperty(params, key, { value, writable: true, enumerable: true, configurable: true });\n\t}\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(\n\tmsg: ToolResultMessage,\n\tisOAuthToken: boolean,\n\tdeferredToolNames: ReadonlySet<string>,\n\tloadedToolNames: Set<string>,\n\tnormalizeToolName: (name: string) => string,\n): { toolResult: ContentBlockParam; siblingContent: ContentBlockParam[] } {\n\tconst references: Array<{ type: \"tool_reference\"; tool_name: string }> = [];\n\tfor (const name of msg.addedToolNames ?? []) {\n\t\tconst normalizedName = normalizeToolName(name);\n\t\tif (!deferredToolNames.has(normalizedName) || loadedToolNames.has(normalizedName)) continue;\n\t\tloadedToolNames.add(normalizedName);\n\t\treferences.push({\n\t\t\ttype: \"tool_reference\",\n\t\t\ttool_name: isOAuthToken ? toClaudeCodeName(name) : name,\n\t\t});\n\t}\n\t// The video block variant is not in the SDK's ContentBlockParam union, so the\n\t// converted array is cast through the same escape hatch as tool_reference blocks.\n\tconst convertedContent = convertContentBlocks(msg.content) as string | ContentBlockParam[];\n\t// Anthropic rejects tool references mixed with ordinary tool-result content.\n\treturn {\n\t\ttoolResult: {\n\t\t\ttype: \"tool_result\",\n\t\t\ttool_use_id: msg.toolCallId,\n\t\t\tcontent: references.length > 0 ? references : convertedContent,\n\t\t\tis_error: msg.isError,\n\t\t} as unknown as ContentBlockParam,\n\t\tsiblingContent:\n\t\t\treferences.length === 0\n\t\t\t\t? []\n\t\t\t\t: typeof convertedContent === \"string\"\n\t\t\t\t\t? [{ type: \"text\", text: convertedContent }]\n\t\t\t\t\t: convertedContent,\n\t};\n}\n\nfunction convertMessages(\n\ttransformedMessages: Message[],\n\tmodel: Model<\"anthropic-messages\">,\n\tisOAuthToken: boolean,\n\tcacheControl?: CacheControlEphemeral,\n\tunsignedThinkingReplay: UnsignedThinkingReplay = \"text\",\n\tdeferredToolNames: ReadonlySet<string> = new Set(),\n\tnormalizeToolName: (name: string) => string = (name) => name,\n): MessageParam[] {\n\tconst params: MessageParam[] = [];\n\tconst loadedToolNames = new Set<string>();\n\t// Tool calls from a declined pre-fallback attempt are dropped from their\n\t// assistant turn below; drop their tool_results in lockstep so none dangle.\n\tconst discardedFallbackToolCallIds = collectDiscardedFallbackToolCallIds(transformedMessages, model);\n\tconst rejectsNativeWebSearchReplay = !getAnthropicCompat(model).supportsWebSearch;\n\n\tfor (let i = 0; i < transformedMessages.length; i++) {\n\t\tconst msg = transformedMessages[i];\n\n\t\tif (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} else if (isVideoMimeType(item.mimeType)) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\ttype: \"video\",\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: item.mimeType,\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} satisfies AnthropicVideoBlock as unknown as ContentBlockParam;\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\ttype: \"image\",\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: item.mimeType as \"image/jpeg\" | \"image/png\" | \"image/gif\" | \"image/webp\",\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};\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: ContentBlockParam[] = [];\n\t\t\tconst isSameModel = isSameAnthropicModel(msg, model);\n\t\t\t// Blocks before the final fallback marker are the declined attempt; the\n\t\t\t// marker onward is the serving model's output and replays verbatim.\n\t\t\tconst fallbackBoundary = isSameModel ? lastAnthropicFallbackBoundary(msg.content) : -1;\n\t\t\tconst preBoundaryPairedServerToolUseIds =\n\t\t\t\tfallbackBoundary >= 0\n\t\t\t\t\t? pairedServerToolUseIdsBeforeBoundary(msg.content, fallbackBoundary)\n\t\t\t\t\t: new Set<string>();\n\n\t\t\tfor (let blockIndex = 0; blockIndex < msg.content.length; blockIndex++) {\n\t\t\t\tconst block = msg.content[blockIndex];\n\t\t\t\tif (fallbackBoundary >= 0 && blockIndex < fallbackBoundary) {\n\t\t\t\t\t// Drop the declined attempt's model-internal blocks: thinking,\n\t\t\t\t\t// tool_use, and any unpaired server_tool_use. Paired server-tool\n\t\t\t\t\t// blocks and text survive per the fallback replay contract.\n\t\t\t\t\tif (block.type === \"thinking\" || block.type === \"toolCall\") {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif (\n\t\t\t\t\t\tblock.type === \"providerNative\" &&\n\t\t\t\t\t\tisAnthropicServerToolUseBlock(block.raw) &&\n\t\t\t\t\t\t!preBoundaryPairedServerToolUseIds.has(block.raw.id)\n\t\t\t\t\t) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (block.type === \"text\") {\n\t\t\t\t\tif (block.text.trim().length === 0) continue;\n\t\t\t\t\tblocks.push({\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: sanitizeSurrogates(block.text),\n\t\t\t\t\t});\n\t\t\t\t} else if (block.type === \"thinking\") {\n\t\t\t\t\t// Redacted thinking: pass the opaque payload back as redacted_thinking\n\t\t\t\t\tif (block.redacted) {\n\t\t\t\t\t\tblocks.push({\n\t\t\t\t\t\t\ttype: \"redacted_thinking\",\n\t\t\t\t\t\t\tdata: block.thinkingSignature!,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tconst thinkingSignature = block.thinkingSignature;\n\t\t\t\t\tconst hasThinkingSignature = !!thinkingSignature && thinkingSignature.trim().length > 0;\n\t\t\t\t\tif (block.thinking.trim().length === 0 && !hasThinkingSignature) continue;\n\t\t\t\t\t// If thinking signature is missing/empty (e.g., from aborted stream),\n\t\t\t\t\t// convert to plain text for Anthropic. Some compatible providers emit\n\t\t\t\t\t// and accept empty signatures, so let marked models preserve the block.\n\t\t\t\t\tif (!hasThinkingSignature) {\n\t\t\t\t\t\tblocks.push(\n\t\t\t\t\t\t\tunsignedThinkingReplay === \"empty-signature\"\n\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\ttype: \"thinking\",\n\t\t\t\t\t\t\t\t\t\tthinking: sanitizeSurrogates(block.thinking),\n\t\t\t\t\t\t\t\t\t\tsignature: \"\",\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\t\t\ttext: sanitizeSurrogates(block.thinking),\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tblocks.push({\n\t\t\t\t\t\t\ttype: \"thinking\",\n\t\t\t\t\t\t\tthinking: block.thinking,\n\t\t\t\t\t\t\tsignature: thinkingSignature,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t} else if (block.type === \"toolCall\") {\n\t\t\t\t\tblocks.push({\n\t\t\t\t\t\ttype: \"tool_use\",\n\t\t\t\t\t\tid: block.id,\n\t\t\t\t\t\tname: isOAuthToken ? toClaudeCodeName(block.name) : block.name,\n\t\t\t\t\t\tinput: block.arguments ?? {},\n\t\t\t\t\t});\n\t\t\t\t} else if (block.type === \"providerNative\") {\n\t\t\t\t\tif (\n\t\t\t\t\t\tisSameModel &&\n\t\t\t\t\t\tisReplayableAnthropicProviderNativeBlock(block.raw) &&\n\t\t\t\t\t\t!(rejectsNativeWebSearchReplay && isAnthropicWebSearchReplayBlock(block.raw))\n\t\t\t\t\t) {\n\t\t\t\t\t\tblocks.push(block.raw);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (blocks.length === 0) continue;\n\t\t\tparams.push({\n\t\t\t\trole: \"assistant\",\n\t\t\t\tcontent: blocks,\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\tconst siblingContent: ContentBlockParam[] = [];\n\t\t\tlet j = i;\n\t\t\twhile (j < transformedMessages.length && transformedMessages[j].role === \"toolResult\") {\n\t\t\t\tconst nextMsg = transformedMessages[j] as ToolResultMessage; // We know it's a toolResult\n\t\t\t\tif (!discardedFallbackToolCallIds.has(nextMsg.toolCallId)) {\n\t\t\t\t\tconst converted = convertToolResult(\n\t\t\t\t\t\tnextMsg,\n\t\t\t\t\t\tisOAuthToken,\n\t\t\t\t\t\tdeferredToolNames,\n\t\t\t\t\t\tloadedToolNames,\n\t\t\t\t\t\tnormalizeToolName,\n\t\t\t\t\t);\n\t\t\t\t\ttoolResults.push(converted.toolResult);\n\t\t\t\t\tsiblingContent.push(...converted.siblingContent);\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\t// Every result in this run may have been dropped; don't emit an empty turn.\n\t\t\tif (toolResults.length === 0) continue;\n\n\t\t\t// Displaced reference-bearing results must follow every tool_result block.\n\t\t\tparams.push({\n\t\t\t\trole: \"user\",\n\t\t\t\tcontent: [...toolResults, ...siblingContent],\n\t\t\t});\n\t\t}\n\t}\n\n\t// Add cache_control to the last user 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\") {\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 (isCacheableUserContentBlock(lastBlock)) {\n\t\t\t\t\tlastBlock.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];\n\t\t\t}\n\t\t}\n\t}\n\n\treturn params;\n}\n\nfunction shouldUseFineGrainedToolStreamingBeta(model: Model<\"anthropic-messages\">, context: Context): boolean {\n\treturn !!context.tools?.length && !getAnthropicCompat(model).supportsEagerToolInputStreaming;\n}\n\nfunction convertTools(\n\ttools: Tool[],\n\tisOAuthToken: boolean,\n\tsupportsEagerToolInputStreaming: boolean,\n\tsupportsStrictTools: boolean,\n\tcacheControl?: CacheControlEphemeral,\n\tdeferLoading = false,\n): Anthropic.Messages.Tool[] {\n\tif (!tools) return [];\n\n\treturn tools.map((tool, index) => {\n\t\tconst strict = resolveJsonSchemaStrictSampling(tool, supportsStrictTools);\n\t\tconst schema = tool.parameters as { properties?: unknown; required?: string[] };\n\t\tconst legacyInputSchema = {\n\t\t\ttype: \"object\" as const,\n\t\t\tproperties: schema.properties ?? {},\n\t\t\trequired: schema.required ?? [],\n\t\t};\n\t\tconst inputSchema =\n\t\t\tstrict === true\n\t\t\t\t? {\n\t\t\t\t\t\t...(tool.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...(deferLoading ? { defer_loading: true } : {}),\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; stopDetails?: AssistantStopDetails } {\n\tconst explanation = stopDetails?.explanation;\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: explanation || `The model refused to complete the request`,\n\t\t\t\tstopDetails: explanation == null ? { type: \"refusal\" } : { type: \"refusal\", explanation },\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\", stopDetails: { type: \"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,MAAM,mBAAmB,CAAC;AAS1C,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAwB7C,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,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AE,WAAW,EAAE,EAAE,IAAI,EAAE,WAAW,EAAE,EAAE,CAAC;QACpE;YACC,kEAAkE;YAClE,MAAM,IAAI,KAAK,CAAC,0BAA0B,MAAM,EAAE,CAAC,CAAC;IACtD,CAAC;AACF,CAAC","sourcesContent":["import Anthropic from \"@anthropic-ai/sdk\";\nimport type {\n\tCacheControlEphemeral,\n\tContentBlockParam,\n\tMessageCreateParamsStreaming,\n\tMessageParam,\n\tRawMessageStreamEvent,\n\tRefusalStopDetails,\n} from \"@anthropic-ai/sdk/resources/messages.js\";\nimport { calculateCost } from \"../models.ts\";\nimport type {\n\tAnthropicMessagesCompat,\n\tApi,\n\tAssistantMessage,\n\tAssistantStopDetails,\n\tCacheRetention,\n\tContext,\n\tImageContent,\n\tMessage,\n\tModel,\n\tProviderEnv,\n\tProviderNativeContent,\n\tSimpleStreamOptions,\n\tStopReason,\n\tStreamFunction,\n\tStreamOptions,\n\tTextContent,\n\tThinkingContent,\n\tTool,\n\tToolCall,\n\tToolResultMessage,\n\tUserMessage,\n} from \"../types.ts\";\nimport { isVideoMimeType } from \"../types.ts\";\nimport { combineAbortSignals } from \"../utils/abort-signals.ts\";\nimport { splitDeferredTools } from \"../utils/deferred-tools.ts\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.ts\";\nimport { headersToRecord, providerHeadersToRecord } from \"../utils/headers.ts\";\nimport { parseJsonWithRepair, parseStreamingJson } from \"../utils/json-parse.ts\";\nimport { getProviderEnvValue } from \"../utils/provider-env.ts\";\nimport { retryProviderRequest } from \"../utils/provider-retry.ts\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.ts\";\nimport {\n\tapplyServerFallbackAbort,\n\tparseServerFallbackReceipt,\n\tparseStickyFallbackReceipt,\n\ttype ServerFallbackReceipt,\n} from \"../utils/server-fallback-receipt.ts\";\nimport { normalizeToolCallId } from \"../utils/tool-call-id.ts\";\nimport { isForcedToolChoiceUnsupportedError, omitToolChoiceParam } from \"../utils/tool-choice-fallback.ts\";\n\nimport { resolveCloudflareBaseUrl } from \"./cloudflare.ts\";\nimport { resolveJsonSchemaStrictSampling } from \"./constrained-sampling.ts\";\nimport { buildCopilotDynamicHeaders, hasCopilotVisionInput } from \"./github-copilot-headers.ts\";\nimport {\n\tANTHROPIC_RESERVED_BODY_KEYS,\n\tadjustMaxTokensForThinking,\n\tbuildBaseOptions,\n\tclampMaxTokensToContext,\n} from \"./simple-options.ts\";\nimport { transformMessages } from \"./transform-messages.ts\";\n\n/**\n * Resolve cache retention preference.\n * Defaults to the provided fallback and uses PI_CACHE_RETENTION for backward compatibility.\n */\nfunction resolveCacheRetention(\n\tcacheRetention?: CacheRetention,\n\tenv?: ProviderEnv,\n\tfallback: CacheRetention = \"short\",\n): 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\tif (typeof process !== \"undefined\" && process.env.PI_CACHE_RETENTION !== undefined) {\n\t\treturn \"short\";\n\t}\n\treturn fallback;\n}\n\nfunction isAnthropicApiBaseUrl(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\nfunction getCacheControl(\n\tmodel: Model<\"anthropic-messages\">,\n\tcacheRetention?: CacheRetention,\n\tenv?: ProviderEnv,\n): { retention: CacheRetention; cacheControl?: CacheControlEphemeral } {\n\tconst retention = resolveCacheRetention(cacheRetention, env, \"long\");\n\tif (retention === \"none\") {\n\t\treturn { retention };\n\t}\n\tconst ttl =\n\t\tretention === \"long\" &&\n\t\tisAnthropicApiBaseUrl(model.baseUrl) &&\n\t\tgetAnthropicCompat(model).supportsLongCacheRetention\n\t\t\t? \"1h\"\n\t\t\t: 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\nconst claudeCodeVersion = \"2.1.75\";\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\n/**\n * Convert content blocks to Anthropic API format\n */\n/**\n * Anthropic-compatible video input block (not in the official SDK types).\n * Kimi's Anthropic-compatible endpoint accepts `{type:\"video\"}` content blocks\n * with the same source shape as images (verified against MoonshotAI/kimi-code\n * kosong anthropic provider).\n */\ninterface AnthropicVideoBlock {\n\ttype: \"video\";\n\tsource: { type: \"base64\"; media_type: string; data: string };\n}\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\t\t| AnthropicVideoBlock\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\tif (isVideoMimeType(block.mimeType)) {\n\t\t\treturn {\n\t\t\t\ttype: \"video\" as const,\n\t\t\t\tsource: {\n\t\t\t\t\ttype: \"base64\" as const,\n\t\t\t\t\tmedia_type: block.mimeType,\n\t\t\t\t\tdata: block.data,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\ttype: \"image\" as const,\n\t\t\tsource: {\n\t\t\t\ttype: \"base64\" as const,\n\t\t\t\tmedia_type: block.mimeType as \"image/jpeg\" | \"image/png\" | \"image/gif\" | \"image/webp\",\n\t\t\t\tdata: block.data,\n\t\t\t},\n\t\t};\n\t});\n\n\t// If only media (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 COMPUTER_USE_BETA_PREFIX = \"computer-use-\";\nconst NATIVE_COMPUTER_TOOL_TYPE = \"computer_20250124\";\nconst ADAPTIVE_THINKING_MODEL_MARKERS = [\n\t\"opus-4-6\",\n\t\"opus-4-7\",\n\t\"opus-4-8\",\n\t\"opus-5\",\n\t\"sonnet-4-6\",\n\t\"sonnet-5\",\n\t\"fable-5\",\n\t\"mythos-5\",\n] as const;\n/**\n * Adaptive families that expose the real `xhigh` effort tier. Everything else on the\n * adaptive ladder tops out at `max` (Opus/Sonnet 4.6 are four-tier: low/medium/high/max).\n */\nconst NATIVE_XHIGH_EFFORT_MODEL_MARKERS = [\n\t\"opus-4-7\",\n\t\"opus-4-8\",\n\t\"opus-5\",\n\t\"sonnet-5\",\n\t\"fable-5\",\n\t\"mythos-5\",\n] as const;\n/**\n * Adaptive families that reject `thinking: {type: \"disabled\"}` outright (verified 400:\n * `\"thinking.type.disabled\" is not supported for this model`). The generated catalog also encodes\n * this as `compat.supportsDisabledThinking: false`, but `models.json` entries and third-party\n * gateway rows carry no generated compat, so the family fact has to live here as well.\n */\nconst DISABLED_THINKING_REJECTING_MODEL_MARKERS = [\"fable-5\", \"mythos-5\"] as const;\nconst CLAUDE_FABLE_OR_MYTHOS_MODEL_ID = /^claude-(?:fable|mythos)(?:-|$)/i;\nconst UNSUPPORTED_NATIVE_COMPUTER_TOOL_MODEL_MARKERS = [\n\t\"opus-4-6\",\n\t\"opus-4.6\",\n\t\"opus-4-7\",\n\t\"opus-4.7\",\n\t\"opus-4-8\",\n\t\"opus-4.8\",\n] as const;\n\ntype UnsignedThinkingReplay = \"text\" | \"empty-signature\";\n\n// A provider can reject its own empty signatures. Learn that capability for one\n// conversation without changing the shared model definition used by other sessions.\nconst unsignedThinkingTextReplayFallbacks = new Set<string>();\n\nfunction unsignedThinkingFallbackKey(\n\tmodel: Model<\"anthropic-messages\">,\n\tsessionId: string | undefined,\n): string | undefined {\n\treturn sessionId === undefined ? undefined : `${sessionId}\\u0000${model.baseUrl}\\u0000${model.id}`;\n}\n\nfunction isInvalidUnsignedThinkingSignatureError(error: unknown): boolean {\n\treturn (\n\t\ttypeof error === \"object\" &&\n\t\terror !== null &&\n\t\t\"status\" in error &&\n\t\t(error as { status?: unknown }).status === 400 &&\n\t\terror instanceof Error &&\n\t\t/Invalid signature in thinking block/i.test(error.message)\n\t);\n}\n\nfunction getAnthropicCompat(\n\tmodel: Model<\"anthropic-messages\">,\n): Required<Omit<AnthropicMessagesCompat, \"forceAdaptiveThinking\">> {\n\t// Auto-detect session affinity and cache control support from provider\n\tconst isFireworks = model.provider === \"fireworks\";\n\tconst isCloudflareAiGatewayAnthropic =\n\t\tmodel.provider === \"cloudflare-ai-gateway\" && model.baseUrl.includes(\"anthropic\");\n\tconst isXiaomi = model.provider === \"xiaomi\" || model.provider.startsWith(\"xiaomi-token-plan-\");\n\treturn {\n\t\tsupportsEagerToolInputStreaming: model.compat?.supportsEagerToolInputStreaming ?? !isFireworks,\n\t\tsupportsLongCacheRetention: model.compat?.supportsLongCacheRetention ?? !isFireworks,\n\t\tsendSessionAffinityHeaders:\n\t\t\tmodel.compat?.sendSessionAffinityHeaders ?? !!(isFireworks || isCloudflareAiGatewayAnthropic),\n\t\tsupportsCacheControlOnTools: model.compat?.supportsCacheControlOnTools ?? !isFireworks,\n\t\tsupportsDisabledThinking: model.compat?.supportsDisabledThinking ?? !isXiaomi,\n\t\tsupportsTemperature: model.compat?.supportsTemperature ?? true,\n\t\tsupportsToolChoice: model.compat?.supportsToolChoice ?? true,\n\t\tsupportsForcedToolChoice:\n\t\t\tmodel.compat?.supportsForcedToolChoice ?? !CLAUDE_FABLE_OR_MYTHOS_MODEL_ID.test(model.id),\n\t\tallowEmptySignature: model.compat?.allowEmptySignature ?? false,\n\t\tunsignedThinkingReplay:\n\t\t\tmodel.compat?.unsignedThinkingReplay ?? (model.compat?.allowEmptySignature ? \"empty-signature\" : \"text\"),\n\t\tsupportsStrictTools: model.compat?.supportsStrictTools ?? false,\n\t\tsupportsToolReferences: model.compat?.supportsToolReferences ?? defaultSupportsToolReferences(model),\n\t\t// Default: first-party Anthropic only. Anthropic-compatible providers\n\t\t// (kimi-coding, fireworks, copilot, gateways) may execute the server-side\n\t\t// search but reject the replayed server_tool_use / web_search_tool_result\n\t\t// blocks on the next request (kimi-coding 400s with `tool_call_id is not\n\t\t// found`).\n\t\tsupportsWebSearch: model.compat?.supportsWebSearch ?? isAnthropicApiBaseUrl(model.baseUrl),\n\t};\n}\n\n/**\n * Default for `supportsToolReferences`: first-party Anthropic models except\n * Haiku (rejects client-side tool_reference blocks) and models that predate\n * tool search (Claude 3.x, Opus/Sonnet 4.0, Opus 4.1).\n */\nfunction defaultSupportsToolReferences(model: Model<\"anthropic-messages\">): boolean {\n\tif (model.provider !== \"anthropic\" || model.id.includes(\"haiku\")) return false;\n\tconst version = model.id.match(/^claude-(?:opus|sonnet|fable)-(\\d+)(?:-(\\d+))?(?:-|$)/);\n\tif (!version) return false;\n\tconst major = Number(version[1]);\n\tconst minor = version[2] && version[2].length < 8 ? Number(version[2]) : 0;\n\treturn major > 4 || (major === 4 && minor >= 5);\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 `streamSimpleAnthropic()` 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 `streamSimpleAnthropic()` 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: (Record<string, string | null> | undefined)[]): Record<string, string | null> {\n\tconst merged: Record<string, string | null> = {};\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 hasAuthorizationHeader(headers?: Record<string, string>): boolean {\n\treturn Object.keys(headers ?? {}).some((name) => name.toLowerCase() === \"authorization\");\n}\n\ninterface ServerSentEvent {\n\tevent: string | null;\n\tdata: string;\n\traw: string[];\n}\n\ntype AnthropicPayloadWithRequestMetadata = MessageCreateParamsStreaming & {\n\theaders?: unknown;\n\textra_body?: unknown;\n};\n\ninterface SseDecoderState {\n\tevent: string | null;\n\tdata: string[];\n\traw: string[];\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null;\n}\n\nconst REPLAYABLE_ANTHROPIC_PROVIDER_NATIVE_TYPES: ReadonlySet<string> = new Set([\n\t\"server_tool_use\",\n\t\"web_search_tool_result\",\n\t\"web_fetch_tool_result\",\n\t\"code_execution_tool_result\",\n\t\"bash_code_execution_tool_result\",\n\t\"text_editor_code_execution_tool_result\",\n\t\"tool_search_tool_result\",\n\t\"container_upload\",\n\t// Server-side fallback beta (server-side-fallback-2026-06-01) emits a\n\t// `fallback` marker mid-response. The marker itself is replayed as a kept\n\t// audit block. Blocks emitted *before* the final marker are the declined\n\t// attempt and are pruned in convertMessages (see lastAnthropicFallbackBoundary\n\t// and collectDiscardedFallbackToolCallIds); the marker onward replays verbatim.\n\t\"fallback\",\n]);\n\nfunction isReplayableAnthropicProviderNativeBlock(raw: unknown): raw is ContentBlockParam {\n\treturn isRecord(raw) && typeof raw.type === \"string\" && REPLAYABLE_ANTHROPIC_PROVIDER_NATIVE_TYPES.has(raw.type);\n}\n\nfunction isSameAnthropicModel(message: AssistantMessage, model: Model<\"anthropic-messages\">): boolean {\n\treturn message.provider === model.provider && message.api === model.api && message.model === model.id;\n}\n\nfunction isAnthropicFallbackMarkerBlock(block: AssistantMessage[\"content\"][number]): boolean {\n\treturn (\n\t\tblock.type === \"providerNative\" &&\n\t\tblock.subtype === \"fallback\" &&\n\t\tisRecord(block.raw) &&\n\t\tblock.raw.type === \"fallback\"\n\t);\n}\n\n// The server-side fallback beta (server-side-fallback-2026-06-01) can emit a\n// `fallback` marker mid-message after a declined attempt is replaced. Blocks\n// before the final marker belong to the discarded attempt: replaying its\n// thinking/tool_use makes the API reject the turn (a discarded tool_use has no\n// matching tool_result after normalization). Returns the index of the last\n// fallback marker, or -1 when the message has none.\nfunction lastAnthropicFallbackBoundary(content: AssistantMessage[\"content\"]): number {\n\tlet boundary = -1;\n\tfor (let index = 0; index < content.length; index++) {\n\t\tif (isAnthropicFallbackMarkerBlock(content[index])) {\n\t\t\tboundary = index;\n\t\t}\n\t}\n\treturn boundary;\n}\n\nfunction isAnthropicServerToolUseBlock(raw: unknown): raw is { readonly type: \"server_tool_use\"; readonly id: string } {\n\treturn isRecord(raw) && raw.type === \"server_tool_use\" && typeof raw.id === \"string\";\n}\n\n// Only tool_use-shaped provider-native blocks (server_tool_use, mcp_tool_use)\n// stream their input via input_json_delta. Result-shaped blocks must replay\n// byte-for-byte (encrypted_content), so never merge an `input` into them.\nfunction isProviderNativeToolUseBlock(raw: unknown): boolean {\n\treturn isRecord(raw) && (raw.type === \"server_tool_use\" || raw.type === \"mcp_tool_use\");\n}\n\n// Endpoints without `supportsWebSearch` reject replayed web-search server-tool\n// blocks (kimi-coding 400s with `tool_call_id is not found`), wedging every\n// subsequent request of the session. Dropping the pair loses the searched\n// context but keeps the conversation usable.\nfunction isAnthropicWebSearchReplayBlock(raw: unknown): boolean {\n\tif (!isRecord(raw)) return false;\n\tif (raw.type === \"web_search_tool_result\") return true;\n\treturn raw.type === \"server_tool_use\" && raw.name === \"web_search\";\n}\n\n// Anthropic validates server-tool pairing per request: a `server_tool_use` /\n// `mcp_tool_use` must be answered by its `*_tool_result`, and a result must\n// have its use — otherwise the API answers `400 ... \\`web_search\\` tool use\n// with id ... was found without a corresponding \\`web_search_tool_result\\`\n// block` and the session wedges, because history only grows.\n//\n// The pair may span two assistant messages. A mixed turn (a client `tool_use`\n// next to a `server_tool_use`, stop `tool_use`) returns with the server tool\n// deferred: the client answers with tool results, and the continuation\n// assistant message starts with the deferred result. Such a turn is LIVE while\n// only tool results follow it — dropping the pending use would stop the API\n// from running the deferred tool. A `pause_turn` turn replays the same way.\n//\n// The turn CLOSES — and a pending use becomes unpairable — when anything but\n// tool results follows it (a user text message tells the API the assistant\n// turn is over) or when a later assistant message exists without ever\n// answering it. Symmetrically, a result is valid when its use sits in the same\n// or an earlier assistant message (the deferred-continuation shape), and is\n// unpairable when its use is nowhere. Only the unpairable halves are dropped;\n// live turns and resolved pairs replay byte-for-byte.\ninterface ProviderNativeToolPairing {\n\treadonly resolvedUseIds: ReadonlySet<string>;\n\treadonly liveUseIds: ReadonlySet<string>;\n\treadonly validResultIds: ReadonlySet<string>;\n}\n\n// The user turn a pending server tool can survive is one that carries only\n// tool results. Anything else the wire would emit — real text, an image —\n// closes the assistant turn (the API then 400s the still-open use). A blank\n// message serializes to nothing, so it closes nothing.\nfunction userMessageClosesServerTurn(message: UserMessage): boolean {\n\tif (typeof message.content === \"string\") return message.content.trim().length > 0;\n\treturn message.content.some(\n\t\t(block) => (block.type === \"text\" && block.text.trim().length > 0) || block.type === \"image\",\n\t);\n}\n\nfunction collectProviderNativeToolPairing(\n\tmessages: Message[],\n\tmodel: Model<\"anthropic-messages\">,\n\tdeferredToolNames: ReadonlySet<string>,\n\tnormalizeToolName: (name: string) => string,\n\tdiscardedFallbackToolCallIds: ReadonlySet<string>,\n): ProviderNativeToolPairing {\n\tconst resolvedUseIds = new Set<string>();\n\tconst validResultIds = new Set<string>();\n\t// Uses whose turn can still be resumed. A same-model assistant resets the\n\t// set: its own result blocks may answer the prior pending uses, and any use\n\t// it leaves pending becomes the open set. Anything that closes the turn —\n\t// user text, a tool result whose deferred-tool references serialize sibling\n\t// text after the results, or another model's assistant — empties it.\n\tlet pendingUseIds = new Set<string>();\n\tconst loadedReferenceNames = new Set<string>();\n\tfor (const message of messages) {\n\t\tif (message.role === \"assistant\") {\n\t\t\tconst priorUseIds = pendingUseIds;\n\t\t\tpendingUseIds = new Set<string>();\n\t\t\tif (!isSameAnthropicModel(message, model)) continue;\n\t\t\tfor (const block of message.content) {\n\t\t\t\tif (block.type !== \"providerNative\" || !isRecord(block.raw)) continue;\n\t\t\t\tconst raw = block.raw;\n\t\t\t\tif (typeof raw.type !== \"string\" || !REPLAYABLE_ANTHROPIC_PROVIDER_NATIVE_TYPES.has(raw.type)) continue;\n\t\t\t\tif (isProviderNativeToolUseBlock(raw) && typeof raw.id === \"string\") pendingUseIds.add(raw.id);\n\t\t\t}\n\t\t\tfor (const block of message.content) {\n\t\t\t\tif (block.type !== \"providerNative\" || !isRecord(block.raw)) continue;\n\t\t\t\tconst raw = block.raw;\n\t\t\t\tif (typeof raw.type !== \"string\" || !REPLAYABLE_ANTHROPIC_PROVIDER_NATIVE_TYPES.has(raw.type)) continue;\n\t\t\t\tconst toolUseId = raw.tool_use_id;\n\t\t\t\tif (typeof toolUseId !== \"string\") continue;\n\t\t\t\tif (priorUseIds.has(toolUseId) || pendingUseIds.has(toolUseId)) {\n\t\t\t\t\tresolvedUseIds.add(toolUseId);\n\t\t\t\t\tvalidResultIds.add(toolUseId);\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (message.role === \"toolResult\") {\n\t\t\t// Conversion drops a discarded pre-fallback result without touching\n\t\t\t// loadedToolNames, so it must not load the name here either.\n\t\t\tif (discardedFallbackToolCallIds.has(message.toolCallId)) continue;\n\t\t\t// convertToolResult emits sibling text after the tool_result blocks only\n\t\t\t// for names that survive the deferred/loaded filter, so only those names\n\t\t\t// close the turn; a stale or already-loaded name leaves the result plain\n\t\t\t// and the pending use resumable.\n\t\t\tlet emitsReferences = false;\n\t\t\tfor (const name of message.addedToolNames ?? []) {\n\t\t\t\tconst normalizedName = normalizeToolName(name);\n\t\t\t\tif (!deferredToolNames.has(normalizedName) || loadedReferenceNames.has(normalizedName)) continue;\n\t\t\t\tloadedReferenceNames.add(normalizedName);\n\t\t\t\temitsReferences = true;\n\t\t\t}\n\t\t\tif (emitsReferences) pendingUseIds = new Set<string>();\n\t\t\tcontinue;\n\t\t}\n\t\tif (message.role === \"user\" && userMessageClosesServerTurn(message)) {\n\t\t\tpendingUseIds = new Set<string>();\n\t\t}\n\t}\n\t// Whatever is still pending at the end of history belongs to the last\n\t// assistant message and can still resume, so it is live rather than unpaired.\n\treturn { resolvedUseIds, liveUseIds: pendingUseIds, validResultIds };\n}\n\n// True for a server-tool block whose counterpart can never arrive: a use that\n// is neither answered nor resumable, or a result whose use is nowhere.\n// Blocks that pair nothing (`fallback`, `container_upload`) are never unpaired.\nfunction isUnpairedProviderNativeToolBlock(raw: unknown, pairing: ProviderNativeToolPairing): boolean {\n\tif (!isRecord(raw)) return false;\n\tif (isProviderNativeToolUseBlock(raw)) {\n\t\treturn typeof raw.id !== \"string\" || !(pairing.resolvedUseIds.has(raw.id) || pairing.liveUseIds.has(raw.id));\n\t}\n\tconst toolUseId = raw.tool_use_id;\n\treturn typeof toolUseId === \"string\" && !pairing.validResultIds.has(toolUseId);\n}\n\n// tool_use ids referenced by server-tool result blocks in content[0, boundary).\n// A pre-boundary `server_tool_use` whose id is absent here is unpaired — the\n// fallback interrupted the declined attempt before its result arrived — so\n// replaying it would leave a server tool_use with no adjacent result and 400 the\n// turn. Paired server-tool blocks replay verbatim per the fallback contract.\nfunction pairedServerToolUseIdsBeforeBoundary(content: AssistantMessage[\"content\"], boundary: number): Set<string> {\n\tconst paired = new Set<string>();\n\tfor (let index = 0; index < boundary; index++) {\n\t\tconst block = content[index];\n\t\tif (block.type !== \"providerNative\" || !isRecord(block.raw)) continue;\n\t\tconst toolUseId = block.raw.tool_use_id;\n\t\tif (typeof toolUseId === \"string\") paired.add(toolUseId);\n\t}\n\treturn paired;\n}\n\n// Tool-call ids emitted by a discarded pre-fallback attempt on a same-model\n// assistant turn. These tool_use blocks are dropped from the assistant turn, so\n// their tool_result blocks must be dropped from the following user turn too — an\n// orphaned tool_result triggers its own 400.\nfunction collectDiscardedFallbackToolCallIds(messages: Message[], model: Model<\"anthropic-messages\">): Set<string> {\n\tconst discarded = new Set<string>();\n\tfor (const message of messages) {\n\t\tif (message.role !== \"assistant\" || !isSameAnthropicModel(message, model)) continue;\n\t\tconst boundary = lastAnthropicFallbackBoundary(message.content);\n\t\tif (boundary < 0) continue;\n\t\tfor (let index = 0; index < boundary; index++) {\n\t\t\tconst block = message.content[index];\n\t\t\tif (block.type === \"toolCall\") {\n\t\t\t\tdiscarded.add(block.id);\n\t\t\t}\n\t\t}\n\t}\n\treturn discarded;\n}\n\nfunction stringRecord(value: unknown): Record<string, string> | undefined {\n\tif (!isRecord(value)) {\n\t\treturn undefined;\n\t}\n\n\tconst entries = Object.entries(value);\n\tif (entries.some(([, item]) => typeof item !== \"string\")) {\n\t\treturn undefined;\n\t}\n\n\treturn Object.fromEntries(entries) as Record<string, string>;\n}\n\nfunction isForcedAnthropicToolChoice(toolChoice: MessageCreateParamsStreaming[\"tool_choice\"] | undefined): boolean {\n\treturn isRecord(toolChoice) && (toolChoice.type === \"any\" || toolChoice.type === \"tool\");\n}\n\nfunction extractPayloadRequestMetadata(params: MessageCreateParamsStreaming): {\n\tparams: MessageCreateParamsStreaming;\n\theaders?: Record<string, string>;\n} {\n\tconst payload = params as AnthropicPayloadWithRequestMetadata;\n\tconst headers = stringRecord(payload.headers);\n\n\tif (!(\"headers\" in payload) && !(\"extra_body\" in payload)) {\n\t\treturn headers ? { params, headers } : { params };\n\t}\n\n\tconst stripped: AnthropicPayloadWithRequestMetadata = { ...payload };\n\tdelete stripped.headers;\n\tdelete stripped.extra_body;\n\n\treturn headers ? { params: stripped, headers } : { params: stripped };\n}\n\nfunction removeAnthropicBetaHeaders(\n\theaders: Record<string, string | null> | undefined,\n\tshouldRemoveBeta: (beta: string) => boolean,\n): {\n\tchanged: boolean;\n\theaders?: Record<string, string | null>;\n} {\n\tif (!headers) {\n\t\treturn { changed: false };\n\t}\n\n\tconst nextHeaders: Record<string, string | null> = {};\n\tlet changed = false;\n\n\tfor (const [key, value] of Object.entries(headers)) {\n\t\tif (key.toLowerCase() !== \"anthropic-beta\" || value === null) {\n\t\t\tnextHeaders[key] = value;\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst betas = value\n\t\t\t.split(\",\")\n\t\t\t.map((beta) => beta.trim())\n\t\t\t.filter((beta) => beta.length > 0);\n\t\tconst supportedBetas = betas.filter((beta) => !shouldRemoveBeta(beta));\n\t\tchanged = changed || supportedBetas.length !== betas.length;\n\n\t\tif (supportedBetas.length > 0) {\n\t\t\tnextHeaders[key] = supportedBetas.join(\", \");\n\t\t}\n\t}\n\n\tif (!changed) {\n\t\treturn { changed: false, headers };\n\t}\n\n\treturn {\n\t\tchanged: true,\n\t\theaders: Object.keys(nextHeaders).length > 0 ? nextHeaders : undefined,\n\t};\n}\n\nfunction removeComputerUseBetaHeader(headers: Record<string, string> | undefined): {\n\tchanged: boolean;\n\theaders?: Record<string, string | null>;\n} {\n\treturn removeAnthropicBetaHeaders(headers, (beta) => beta.startsWith(COMPUTER_USE_BETA_PREFIX));\n}\n\nfunction sanitizeAdaptiveThinkingHeaders(\n\tmodel: Model<\"anthropic-messages\">,\n\theaders: Record<string, string | null>,\n): Record<string, string | null> {\n\tif (!supportsAdaptiveThinking(model)) {\n\t\treturn headers;\n\t}\n\n\tconst headerSanitization = removeAnthropicBetaHeaders(headers, (beta) => beta === INTERLEAVED_THINKING_BETA);\n\treturn headerSanitization.changed ? (headerSanitization.headers ?? {}) : headers;\n}\n\nfunction rejectsNativeComputerTool(model: Model<\"anthropic-messages\">, toolType: string): boolean {\n\tif (model.provider === \"cloudflare-ai-gateway\" && model.baseUrl.includes(\"anthropic\")) {\n\t\treturn toolType.startsWith(\"computer_\");\n\t}\n\treturn (\n\t\tmatchesModelMarker(model, UNSUPPORTED_NATIVE_COMPUTER_TOOL_MODEL_MARKERS) &&\n\t\ttoolType === NATIVE_COMPUTER_TOOL_TYPE\n\t);\n}\n\nfunction rejectsComputerUseBeta(model: Model<\"anthropic-messages\">): boolean {\n\treturn (\n\t\t(model.provider === \"cloudflare-ai-gateway\" && model.baseUrl.includes(\"anthropic\")) ||\n\t\tmatchesModelMarker(model, UNSUPPORTED_NATIVE_COMPUTER_TOOL_MODEL_MARKERS)\n\t);\n}\n\nfunction isAnthropicWebSearchToolType(toolType: string): boolean {\n\treturn toolType.startsWith(\"web_search_\");\n}\n\nfunction sanitizeUnsupportedNativeTools(\n\tmodel: Model<\"anthropic-messages\">,\n\tparams: MessageCreateParamsStreaming,\n): MessageCreateParamsStreaming {\n\tconst payload = params as AnthropicPayloadWithRequestMetadata;\n\tconst headers = stringRecord(payload.headers);\n\tconst headerSanitization = rejectsComputerUseBeta(model)\n\t\t? removeComputerUseBetaHeader(headers)\n\t\t: ({ changed: false } as const);\n\tconst rejectsNativeWebSearch = !getAnthropicCompat(model).supportsWebSearch;\n\tconst tools = payload.tools;\n\tconst sanitized: AnthropicPayloadWithRequestMetadata = { ...payload };\n\tlet changed = false;\n\n\tif (Array.isArray(tools)) {\n\t\tconst supportedTools: typeof tools = [];\n\n\t\tfor (const tool of tools) {\n\t\t\tconst hookTool: unknown = tool;\n\t\t\tif (\n\t\t\t\tisRecord(hookTool) &&\n\t\t\t\ttypeof hookTool.type === \"string\" &&\n\t\t\t\t(rejectsNativeComputerTool(model, hookTool.type) ||\n\t\t\t\t\t(rejectsNativeWebSearch && isAnthropicWebSearchToolType(hookTool.type)))\n\t\t\t) {\n\t\t\t\tchanged = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tsupportedTools.push(tool);\n\t\t}\n\n\t\tif (changed) {\n\t\t\tif (supportedTools.length > 0) {\n\t\t\t\tsanitized.tools = supportedTools;\n\t\t\t} else {\n\t\t\t\tdelete sanitized.tools;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (headerSanitization.changed) {\n\t\tchanged = true;\n\t\tif (headerSanitization.headers) {\n\t\t\tsanitized.headers = headerSanitization.headers;\n\t\t} else {\n\t\t\tdelete sanitized.headers;\n\t\t}\n\t}\n\n\tif (changed && isRecord(sanitized.tool_choice)) {\n\t\tconst toolChoiceName = sanitized.tool_choice.name;\n\t\tconst hasSelectedTool =\n\t\t\ttypeof toolChoiceName === \"string\" &&\n\t\t\tArray.isArray(sanitized.tools) &&\n\t\t\tsanitized.tools.some((tool) => isRecord(tool) && tool.name === toolChoiceName);\n\t\tconst shouldRemoveToolChoice =\n\t\t\tsanitized.tools === undefined || (typeof toolChoiceName === \"string\" && !hasSelectedTool);\n\t\tif (shouldRemoveToolChoice) {\n\t\t\tdelete sanitized.tool_choice;\n\t\t}\n\t}\n\n\treturn changed ? (sanitized as MessageCreateParamsStreaming) : params;\n}\n\nfunction sanitizeAdaptiveThinkingPayload(\n\tmodel: Model<\"anthropic-messages\">,\n\tparams: MessageCreateParamsStreaming,\n\toptions?: AnthropicOptions,\n): MessageCreateParamsStreaming {\n\tif (!supportsAdaptiveThinking(model)) {\n\t\treturn params;\n\t}\n\n\tconst payload = params as AnthropicPayloadWithRequestMetadata;\n\tconst headers = stringRecord(payload.headers);\n\tconst headerSanitization = removeAnthropicBetaHeaders(headers, (beta) => beta === INTERLEAVED_THINKING_BETA);\n\tconst sanitized: AnthropicPayloadWithRequestMetadata = { ...payload };\n\tlet changed = false;\n\n\tconst thinking = isRecord(payload.thinking) ? payload.thinking : undefined;\n\tif (thinking?.type === \"enabled\") {\n\t\tconst display =\n\t\t\tthinking.display === \"omitted\" || thinking.display === \"summarized\"\n\t\t\t\t? thinking.display\n\t\t\t\t: (options?.thinkingDisplay ?? \"summarized\");\n\t\tsanitized.thinking = { type: \"adaptive\", display } as MessageCreateParamsStreaming[\"thinking\"];\n\t\tif (options?.effort !== undefined && !isRecord(payload.output_config)) {\n\t\t\tsanitized.output_config = { effort: options.effort } as NonNullable<\n\t\t\t\tMessageCreateParamsStreaming[\"output_config\"]\n\t\t\t>;\n\t\t}\n\t\tchanged = true;\n\t}\n\n\tif (headerSanitization.changed) {\n\t\tchanged = true;\n\t\tif (headerSanitization.headers) {\n\t\t\tsanitized.headers = headerSanitization.headers;\n\t\t} else {\n\t\t\tdelete sanitized.headers;\n\t\t}\n\t}\n\n\treturn changed ? (sanitized as MessageCreateParamsStreaming) : params;\n}\n\nfunction isCacheableUserContentBlock(\n\tblock: ContentBlockParam | undefined,\n): block is Extract<ContentBlockParam, { type: \"text\" | \"image\" | \"tool_result\" }> {\n\treturn block?.type === \"text\" || block?.type === \"image\" || block?.type === \"tool_result\";\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\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\treader.releaseLock();\n\t}\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\tthrow new Error(sse.data);\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: Context,\n\toptions?: AnthropicOptions,\n): AssistantMessageEventStream => {\n\tconst stream = new AssistantMessageEventStream();\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: \"stop\",\n\t\t\ttimestamp: Date.now(),\n\t\t};\n\n\t\tconst serverFallbackAbort = new AbortController();\n\t\tlet serverFallbackReceipt: ServerFallbackReceipt | undefined;\n\t\tconst combinedAbort = combineAbortSignals([options?.signal, serverFallbackAbort.signal]);\n\t\tconst requestSignal = combinedAbort.signal;\n\t\ttry {\n\t\t\tlet client: Anthropic;\n\t\t\tlet isOAuth: boolean;\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 optionsHeaders = providerHeadersToRecord(options?.headers);\n\t\t\t\tif (!apiKey && !hasAuthorizationHeader(optionsHeaders)) {\n\t\t\t\t\tthrow new Error(`No API key for provider: ${model.provider}`);\n\t\t\t\t}\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(context.messages);\n\t\t\t\t\tcopilotDynamicHeaders = buildCopilotDynamicHeaders({\n\t\t\t\t\t\tmessages: context.messages,\n\t\t\t\t\t\thasImages,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tconst cacheRetention = resolveCacheRetention(\n\t\t\t\t\toptions?.cacheRetention ?? model.cacheRetention,\n\t\t\t\t\toptions?.env,\n\t\t\t\t\t\"long\",\n\t\t\t\t);\n\t\t\t\tconst cacheSessionId = cacheRetention === \"none\" ? undefined : options?.sessionId;\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\toptions?.interleavedThinking ?? true,\n\t\t\t\t\tshouldUseFineGrainedToolStreamingBeta(model, context),\n\t\t\t\t\toptionsHeaders,\n\t\t\t\t\tcopilotDynamicHeaders,\n\t\t\t\t\tcacheSessionId,\n\t\t\t\t\toptions?.env,\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 fallbackKey = unsignedThinkingFallbackKey(model, options?.sessionId);\n\t\t\tlet unsignedThinkingReplay: UnsignedThinkingReplay =\n\t\t\t\tfallbackKey && unsignedThinkingTextReplayFallbacks.has(fallbackKey)\n\t\t\t\t\t? \"text\"\n\t\t\t\t\t: getAnthropicCompat(model).unsignedThinkingReplay;\n\t\t\tconst createRequest = async (): Promise<{ params: MessageCreateParamsStreaming; response: Response }> => {\n\t\t\t\tlet params = buildParams(model, context, isOAuth, options, unsignedThinkingReplay);\n\t\t\t\tconst nextParams = await options?.onPayload?.(params, model);\n\t\t\t\tif (nextParams !== undefined) {\n\t\t\t\t\tparams = nextParams as MessageCreateParamsStreaming;\n\t\t\t\t}\n\t\t\t\tparams = sanitizeAdaptiveThinkingPayload(model, params, options);\n\t\t\t\tparams = sanitizeUnsupportedNativeTools(model, params);\n\t\t\t\tconst payloadRequestMetadata = extractPayloadRequestMetadata(params);\n\t\t\t\tparams = payloadRequestMetadata.params;\n\t\t\t\tconst requestOptions = {\n\t\t\t\t\t...(requestSignal ? { signal: requestSignal } : {}),\n\t\t\t\t\t...(options?.timeoutMs !== undefined ? { timeout: options.timeoutMs } : {}),\n\t\t\t\t\tmaxRetries: 0,\n\t\t\t\t\t...(payloadRequestMetadata.headers ? { headers: payloadRequestMetadata.headers } : {}),\n\t\t\t\t};\n\t\t\t\ttry {\n\t\t\t\t\tconst response = await client.messages.create({ ...params, stream: true }, requestOptions).asResponse();\n\t\t\t\t\treturn { params, response };\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (isForcedToolChoiceUnsupportedError(error, isForcedAnthropicToolChoice(params.tool_choice))) {\n\t\t\t\t\t\tparams = omitToolChoiceParam(params);\n\t\t\t\t\t\tconst response = await client.messages\n\t\t\t\t\t\t\t.create({ ...params, stream: true }, requestOptions)\n\t\t\t\t\t\t\t.asResponse();\n\t\t\t\t\t\treturn { params, response };\n\t\t\t\t\t}\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t};\n\t\t\tconst { params: sentParams, response } = await retryProviderRequest(\n\t\t\t\tasync () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\treturn await createRequest();\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (unsignedThinkingReplay !== \"text\" && isInvalidUnsignedThinkingSignatureError(error)) {\n\t\t\t\t\t\t\tunsignedThinkingReplay = \"text\";\n\t\t\t\t\t\t\tif (fallbackKey) unsignedThinkingTextReplayFallbacks.add(fallbackKey);\n\t\t\t\t\t\t\treturn createRequest();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tmaxRetries: options?.maxRetries,\n\t\t\t\t\tmaxRetryDelayMs: options?.maxRetryDelayMs,\n\t\t\t\t\tsignal: requestSignal,\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\n\t\t\ttype Block =\n\t\t\t\t| (ThinkingContent & { index?: number })\n\t\t\t\t| (TextContent & { index?: number })\n\t\t\t\t| ((ToolCall & { partialJson: string }) & { index?: number })\n\t\t\t\t| (ProviderNativeContent & { partialJson?: string; index?: number });\n\t\t\tconst blocks = output.content as Block[];\n\n\t\t\tfor await (const event of iterateAnthropicEvents(response, requestSignal)) {\n\t\t\t\tif (event.type === \"message_start\") {\n\t\t\t\t\toutput.responseId = event.message.id;\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(model, output.usage);\n\t\t\t\t\tconst stickyReceipt =\n\t\t\t\t\t\toptions?.abortServerSideFallback === true\n\t\t\t\t\t\t\t? parseStickyFallbackReceipt(event.message.usage, sentParams.model, event.message.model)\n\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\tif (stickyReceipt !== undefined) {\n\t\t\t\t\t\tserverFallbackReceipt = stickyReceipt;\n\t\t\t\t\t\tserverFallbackAbort.abort();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t} else if (event.type === \"content_block_start\") {\n\t\t\t\t\tconst receipt =\n\t\t\t\t\t\toptions?.abortServerSideFallback === true\n\t\t\t\t\t\t\t? parseServerFallbackReceipt(event.content_block)\n\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\tif (receipt !== undefined) {\n\t\t\t\t\t\tserverFallbackReceipt = receipt;\n\t\t\t\t\t\tserverFallbackAbort.abort();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tif (event.content_block.type === \"text\") {\n\t\t\t\t\t\tconst block: Block = {\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: \"\",\n\t\t\t\t\t\t\tindex: event.index,\n\t\t\t\t\t\t};\n\t\t\t\t\t\toutput.content.push(block);\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\tconst block: Block = {\n\t\t\t\t\t\t\ttype: \"thinking\",\n\t\t\t\t\t\t\tthinking: \"\",\n\t\t\t\t\t\t\tthinkingSignature: \"\",\n\t\t\t\t\t\t\tindex: event.index,\n\t\t\t\t\t\t};\n\t\t\t\t\t\toutput.content.push(block);\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\tconst block: Block = {\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\tindex: event.index,\n\t\t\t\t\t\t};\n\t\t\t\t\t\toutput.content.push(block);\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\tconst block: Block = {\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, context.tools)\n\t\t\t\t\t\t\t\t: event.content_block.name,\n\t\t\t\t\t\t\targuments: isRecord(event.content_block.input) ? event.content_block.input : {},\n\t\t\t\t\t\t\tpartialJson: \"\",\n\t\t\t\t\t\t\tindex: event.index,\n\t\t\t\t\t\t};\n\t\t\t\t\t\toutput.content.push(block);\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 {\n\t\t\t\t\t\tconst block: Block = {\n\t\t\t\t\t\t\ttype: \"providerNative\",\n\t\t\t\t\t\t\tsubtype: event.content_block.type,\n\t\t\t\t\t\t\traw: event.content_block,\n\t\t\t\t\t\t\tindex: event.index,\n\t\t\t\t\t\t};\n\t\t\t\t\t\toutput.content.push(block);\n\t\t\t\t\t\t// Native blocks are represented in output.content but have no dedicated stream event variant.\n\t\t\t\t\t}\n\t\t\t\t} else if (event.type === \"content_block_delta\") {\n\t\t\t\t\tif (event.delta.type === \"text_delta\") {\n\t\t\t\t\t\tconst index = blocks.findIndex((b) => b.index === event.index);\n\t\t\t\t\t\tconst block = blocks[index];\n\t\t\t\t\t\tif (block && block.type === \"text\") {\n\t\t\t\t\t\t\tblock.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: index,\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\tconst index = blocks.findIndex((b) => b.index === event.index);\n\t\t\t\t\t\tconst block = blocks[index];\n\t\t\t\t\t\tif (block && block.type === \"thinking\") {\n\t\t\t\t\t\t\tblock.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: index,\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\tconst index = blocks.findIndex((b) => b.index === event.index);\n\t\t\t\t\t\tconst block = blocks[index];\n\t\t\t\t\t\tif (block && block.type === \"toolCall\") {\n\t\t\t\t\t\t\tblock.partialJson += event.delta.partial_json;\n\t\t\t\t\t\t\tblock.arguments = parseStreamingJson(block.partialJson);\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: index,\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} else if (block && block.type === \"providerNative\" && isProviderNativeToolUseBlock(block.raw)) {\n\t\t\t\t\t\t\t// Server-side tool blocks (server_tool_use) stream their input\n\t\t\t\t\t\t\t// the same way tool_use does; the block captured at\n\t\t\t\t\t\t\t// content_block_start still has `input: {}`.\n\t\t\t\t\t\t\tblock.partialJson = (block.partialJson ?? \"\") + event.delta.partial_json;\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\tconst index = blocks.findIndex((b) => b.index === event.index);\n\t\t\t\t\t\tconst block = blocks[index];\n\t\t\t\t\t\tif (block && block.type === \"thinking\") {\n\t\t\t\t\t\t\tblock.thinkingSignature = block.thinkingSignature || \"\";\n\t\t\t\t\t\t\tblock.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 index = blocks.findIndex((b) => b.index === event.index);\n\t\t\t\t\tconst block = blocks[index];\n\t\t\t\t\tif (block) {\n\t\t\t\t\t\tdelete block.index;\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\") {\n\t\t\t\t\t\t\tblock.arguments = parseStreamingJson(block.partialJson);\n\t\t\t\t\t\t\t// Finalize in-place and strip the scratch buffer so replay only\n\t\t\t\t\t\t\t// carries parsed arguments.\n\t\t\t\t\t\t\tdelete (block as { partialJson?: string }).partialJson;\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} else if (block.type === \"providerNative\") {\n\t\t\t\t\t\t\tconst partialJson = block.partialJson;\n\t\t\t\t\t\t\tdelete block.partialJson;\n\t\t\t\t\t\t\tif (partialJson !== undefined && isRecord(block.raw)) {\n\t\t\t\t\t\t\t\tblock.raw = { ...block.raw, input: parseStreamingJson(partialJson) };\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\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\tif (stopReasonResult.stopDetails) {\n\t\t\t\t\t\t\toutput.stopDetails = stopReasonResult.stopDetails;\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\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(model, output.usage);\n\t\t\t\t}\n\t\t\t}\n\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 (serverFallbackReceipt !== undefined) {\n\t\t\t\tapplyServerFallbackAbort(output, serverFallbackReceipt);\n\t\t\t}\n\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\n\t\t\tcombinedAbort.cleanup();\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\tcombinedAbort.cleanup();\n\t\t\tfor (const block of output.content) {\n\t\t\t\tdelete (block as { index?: number }).index;\n\t\t\t\t// An aborted stream never reaches content_block_stop; keep whatever\n\t\t\t\t// provider-native input accumulated, mirroring toolCall's partial\n\t\t\t\t// arguments.\n\t\t\t\tconst scratch = (block as { partialJson?: string }).partialJson;\n\t\t\t\tif (block.type === \"providerNative\" && scratch !== undefined && isRecord(block.raw)) {\n\t\t\t\t\tblock.raw = { ...block.raw, input: parseStreamingJson(scratch) };\n\t\t\t\t}\n\t\t\t\t// partialJson is only a streaming scratch buffer; never persist it.\n\t\t\t\tdelete (block as { partialJson?: string }).partialJson;\n\t\t\t}\n\t\t\toutput.stopReason = options?.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\toutput.errorMessage = error instanceof Error ? error.message : JSON.stringify(error);\n\t\t\tstream.push({ type: \"error\", reason: output.stopReason, error: output });\n\t\t\tstream.end();\n\t\t}\n\t})();\n\n\treturn stream;\n};\n\n/**\n * Opus-specific feature checks use provider model ids because those behaviors\n * are model-tier details, not custom-provider compatibility toggles.\n */\nfunction getModelMatchCandidates(model: Pick<Model<\"anthropic-messages\">, \"id\" | \"name\">): string[] {\n\treturn [model.id, model.name].flatMap((value) => {\n\t\tconst lower = value.toLowerCase();\n\t\treturn [lower, lower.replace(/[\\s_.:]+/g, \"-\")];\n\t});\n}\n\nfunction matchesModelMarker(\n\tmodel: Pick<Model<\"anthropic-messages\">, \"id\" | \"name\">,\n\tmarkers: readonly string[],\n): boolean {\n\tconst candidates = getModelMatchCandidates(model);\n\treturn candidates.some((candidate) => markers.some((marker) => candidate.includes(marker)));\n}\n\nfunction supportsNativeXhighEffort(model: Pick<Model<\"anthropic-messages\">, \"id\" | \"name\">): boolean {\n\treturn matchesModelMarker(model, NATIVE_XHIGH_EFFORT_MODEL_MARKERS);\n}\n\n/** True when the model cannot accept `thinking: {type: \"disabled\"}` on the wire. */\nfunction cannotDisableThinking(\n\tmodel: Model<\"anthropic-messages\">,\n\tcompat: { supportsDisabledThinking: boolean },\n): boolean {\n\tif (!compat.supportsDisabledThinking) return true;\n\tif (model.thinkingLevelMap?.off === null) return true;\n\treturn matchesModelMarker(model, DISABLED_THINKING_REJECTING_MODEL_MARKERS);\n}\n\nfunction disableThinkingForRequest(\n\tparams: MessageCreateParamsStreaming,\n\tmodel: Model<\"anthropic-messages\">,\n\tcompat: { supportsDisabledThinking: boolean },\n): void {\n\t// A degraded/disabled turn must not retain the caller's higher effort.\n\tdelete (params as { output_config?: unknown }).output_config;\n\tif (cannotDisableThinking(model, compat)) {\n\t\tdelete params.thinking;\n\t\tif (supportsAdaptiveThinking(model)) {\n\t\t\tparams.output_config = { effort: \"low\" } as NonNullable<MessageCreateParamsStreaming[\"output_config\"]>;\n\t\t}\n\t\treturn;\n\t}\n\tparams.thinking = { type: \"disabled\" };\n}\n\nfunction supportsAdaptiveThinking(model: Model<\"anthropic-messages\">): boolean {\n\tif (model.compat?.forceAdaptiveThinking !== undefined) {\n\t\treturn model.compat.forceAdaptiveThinking;\n\t}\n\treturn matchesModelMarker(model, ADAPTIVE_THINKING_MODEL_MARKERS);\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 only available on Opus 4.7/4.8, Opus 5, Sonnet 5, and Fable 5.\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\tcase \"xhigh\":\n\t\t\t// Only called for adaptive models, so the floor is the adaptive ladder's top\n\t\t\t// tier (`max`), never `high` — degrading xhigh to high silently under-thinks.\n\t\t\treturn supportsNativeXhighEffort(model) ? \"xhigh\" : \"max\";\n\t\tcase \"max\":\n\t\t\treturn \"max\";\n\t\tdefault:\n\t\t\treturn \"high\";\n\t}\n}\n\nexport const streamSimple: StreamFunction<\"anthropic-messages\", SimpleStreamOptions> = (\n\tmodel: Model<\"anthropic-messages\">,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): AssistantMessageEventStream => {\n\tconst apiKey = options?.apiKey;\n\tif (!apiKey && !hasAuthorizationHeader(providerHeadersToRecord(options?.headers))) {\n\t\tthrow new Error(`No API key for provider: ${model.provider}`);\n\t}\n\n\tconst base = buildBaseOptions(model, context, options, options?.apiKey);\n\tif (!options?.reasoning) {\n\t\treturn stream(model, context, { ...base, thinkingEnabled: false } 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 (supportsAdaptiveThinking(model)) {\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\toptionsHeaders?: Record<string, string>,\n\tdynamicHeaders?: Record<string, string>,\n\tsessionId?: string,\n\tenv?: ProviderEnv,\n): { client: Anthropic; isOAuthToken: boolean } {\n\t// Adaptive thinking models have interleaved thinking built in, so skip the beta header.\n\tconst needsInterleavedBeta = interleavedThinking && !supportsAdaptiveThinking(model);\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\n\tif (model.provider === \"cloudflare-ai-gateway\") {\n\t\tconst client = new Anthropic({\n\t\t\tapiKey: null,\n\t\t\tauthToken: null,\n\t\t\tbaseURL: resolveCloudflareBaseUrl(model, env),\n\t\t\tdangerouslyAllowBrowser: true,\n\t\t\tdefaultHeaders: sanitizeAdaptiveThinkingHeaders(\n\t\t\t\tmodel,\n\t\t\t\tmergeHeaders(\n\t\t\t\t\t{\n\t\t\t\t\t\taccept: \"application/json\",\n\t\t\t\t\t\t\"anthropic-dangerous-direct-browser-access\": \"true\",\n\t\t\t\t\t\t\"cf-aig-authorization\": `Bearer ${apiKey}`,\n\t\t\t\t\t\t\"x-api-key\": null,\n\t\t\t\t\t\tAuthorization: null,\n\t\t\t\t\t\t...(betaFeatures.length > 0 ? { \"anthropic-beta\": betaFeatures.join(\",\") } : {}),\n\t\t\t\t\t},\n\t\t\t\t\tmodel.headers,\n\t\t\t\t\toptionsHeaders,\n\t\t\t\t),\n\t\t\t),\n\t\t});\n\n\t\treturn { client, isOAuthToken: false };\n\t}\n\n\t// Copilot: Bearer auth, selective betas.\n\tif (model.provider === \"github-copilot\") {\n\t\tconst client = new Anthropic({\n\t\t\tapiKey: null,\n\t\t\tauthToken: apiKey,\n\t\t\tbaseURL: model.baseUrl,\n\t\t\tdangerouslyAllowBrowser: true,\n\t\t\tdefaultHeaders: sanitizeAdaptiveThinkingHeaders(\n\t\t\t\tmodel,\n\t\t\t\tmergeHeaders(\n\t\t\t\t\t{\n\t\t\t\t\t\taccept: \"application/json\",\n\t\t\t\t\t\t\"anthropic-dangerous-direct-browser-access\": \"true\",\n\t\t\t\t\t\t...(betaFeatures.length > 0 ? { \"anthropic-beta\": betaFeatures.join(\",\") } : {}),\n\t\t\t\t\t},\n\t\t\t\t\tmodel.headers,\n\t\t\t\t\tdynamicHeaders,\n\t\t\t\t\toptionsHeaders,\n\t\t\t\t),\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\n\tif (apiKey && isOAuthToken(apiKey)) {\n\t\tconst client = new Anthropic({\n\t\t\tapiKey: null,\n\t\t\tauthToken: apiKey,\n\t\t\tbaseURL: model.baseUrl,\n\t\t\tdangerouslyAllowBrowser: true,\n\t\t\tdefaultHeaders: sanitizeAdaptiveThinkingHeaders(\n\t\t\t\tmodel,\n\t\t\t\tmergeHeaders(\n\t\t\t\t\t{\n\t\t\t\t\t\taccept: \"application/json\",\n\t\t\t\t\t\t\"anthropic-dangerous-direct-browser-access\": \"true\",\n\t\t\t\t\t\t\"anthropic-beta\": [\"claude-code-20250219\", \"oauth-2025-04-20\", ...betaFeatures].join(\",\"),\n\t\t\t\t\t\t\"user-agent\": `claude-cli/${claudeCodeVersion}`,\n\t\t\t\t\t\t\"x-app\": \"cli\",\n\t\t\t\t\t},\n\t\t\t\t\tmodel.headers,\n\t\t\t\t\toptionsHeaders,\n\t\t\t\t),\n\t\t\t),\n\t\t});\n\n\t\treturn { client, isOAuthToken: true };\n\t}\n\n\t// API key auth\n\tconst sessionAffinityHeaders: Record<string, string | null> =\n\t\tsessionId && getAnthropicCompat(model).sendSessionAffinityHeaders ? { \"x-session-affinity\": sessionId } : {};\n\tconst client = new Anthropic({\n\t\tapiKey: apiKey ?? null,\n\t\tauthToken: null,\n\t\tbaseURL: model.baseUrl,\n\t\tdangerouslyAllowBrowser: true,\n\t\tdefaultHeaders: sanitizeAdaptiveThinkingHeaders(\n\t\t\tmodel,\n\t\t\tmergeHeaders(\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...(betaFeatures.length > 0 ? { \"anthropic-beta\": betaFeatures.join(\",\") } : {}),\n\t\t\t\t},\n\t\t\t\tsessionAffinityHeaders,\n\t\t\t\tmodel.headers,\n\t\t\t\toptionsHeaders,\n\t\t\t),\n\t\t),\n\t});\n\n\treturn { client, isOAuthToken: false };\n}\n\nfunction buildParams(\n\tmodel: Model<\"anthropic-messages\">,\n\tcontext: Context,\n\tisOAuthToken: boolean,\n\toptions?: AnthropicOptions,\n\tunsignedThinkingReplay = getAnthropicCompat(model).unsignedThinkingReplay,\n): MessageCreateParamsStreaming {\n\tconst compat = getAnthropicCompat(model);\n\tconst { cacheControl } = getCacheControl(model, options?.cacheRetention ?? model.cacheRetention, options?.env);\n\tconst transformedMessages = transformMessages(context.messages, model, normalizeToolCallId, {\n\t\tpreserveThinking: options?.thinkingEnabled === true,\n\t\tpreserveUnsignedThinking: true,\n\t});\n\tconst normalizeToolName = isOAuthToken ? toClaudeCodeName : (name: string) => name;\n\t// A marker on a discarded pre-fallback result must not defer its tool:\n\t// convertMessages drops that result, so no tool_reference would replay to\n\t// load the deferred definition.\n\tconst discardedFallbackToolCallIds = collectDiscardedFallbackToolCallIds(transformedMessages, model);\n\tconst partitionMessages = transformedMessages.filter(\n\t\t(message) => !(message.role === \"toolResult\" && discardedFallbackToolCallIds.has(message.toolCallId)),\n\t);\n\tconst toolPlacement = splitDeferredTools(\n\t\t{ ...context, messages: partitionMessages },\n\t\tcompat.supportsToolReferences,\n\t\tnormalizeToolName,\n\t);\n\tlet immediateTools = toolPlacement.immediate;\n\tlet deferredTools = [...toolPlacement.deferred.values()];\n\tif (immediateTools.length === 0 && deferredTools.length > 0) {\n\t\timmediateTools = deferredTools;\n\t\tdeferredTools = [];\n\t}\n\tconst deferredToolNames = new Set(deferredTools.map((tool) => normalizeToolName(tool.name)));\n\tconst params: MessageCreateParamsStreaming = {\n\t\tmodel: model.id,\n\t\tmessages: convertMessages(\n\t\t\ttransformedMessages,\n\t\t\tmodel,\n\t\t\tisOAuthToken,\n\t\t\tcacheControl,\n\t\t\tunsignedThinkingReplay,\n\t\t\tdeferredToolNames,\n\t\t\tnormalizeToolName,\n\t\t),\n\t\tmax_tokens: options?.maxTokens ?? model.maxTokens,\n\t\tstream: true,\n\t};\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 (context.systemPrompt) {\n\t\t\tparams.system.push({\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: sanitizeSurrogates(context.systemPrompt),\n\t\t\t\t...(cacheControl ? { cache_control: cacheControl } : {}),\n\t\t\t});\n\t\t}\n\t} else if (context.systemPrompt) {\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(context.systemPrompt),\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 (options?.temperature !== undefined && !options?.thinkingEnabled && compat.supportsTemperature) {\n\t\tObject.defineProperty(params, \"temperature\", {\n\t\t\tvalue: options.temperature,\n\t\t\twritable: true,\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t});\n\t}\n\n\tif (immediateTools.length > 0 || deferredTools.length > 0) {\n\t\tparams.tools = [\n\t\t\t...convertTools(\n\t\t\t\timmediateTools,\n\t\t\t\tisOAuthToken,\n\t\t\t\tcompat.supportsEagerToolInputStreaming,\n\t\t\t\tcompat.supportsStrictTools,\n\t\t\t\tcompat.supportsCacheControlOnTools ? cacheControl : undefined,\n\t\t\t),\n\t\t\t...convertTools(\n\t\t\t\tdeferredTools,\n\t\t\t\tisOAuthToken,\n\t\t\t\tcompat.supportsEagerToolInputStreaming,\n\t\t\t\tcompat.supportsStrictTools,\n\t\t\t\tundefined,\n\t\t\t\ttrue,\n\t\t\t),\n\t\t];\n\t}\n\n\t// Configure thinking mode: adaptive, budget-based, or explicitly disabled.\n\tif (model.reasoning) {\n\t\tif (options?.thinkingEnabled) {\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\tif (supportsAdaptiveThinking(model)) {\n\t\t\t\t// Adaptive thinking: Claude decides when and how much to think.\n\t\t\t\tparams.thinking = { type: \"adaptive\", display } as MessageCreateParamsStreaming[\"thinking\"];\n\t\t\t\tif (options.effort) {\n\t\t\t\t\t// The Anthropic SDK types can lag newly supported effort values such as \"xhigh\" and \"max\".\n\t\t\t\t\tparams.output_config = { effort: options.effort } as NonNullable<\n\t\t\t\t\t\tMessageCreateParamsStreaming[\"output_config\"]\n\t\t\t\t\t>;\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} as MessageCreateParamsStreaming[\"thinking\"];\n\t\t\t}\n\t\t} else if (options?.thinkingEnabled === false) {\n\t\t\t// Some adaptive families reject `thinking.type: \"disabled\"` and default\n\t\t\t// to reasoning when omitted. Keep their request valid at the cheapest\n\t\t\t// legal effort; use an explicit disabled block everywhere else.\n\t\t\tdisableThinkingForRequest(params, model, compat);\n\t\t}\n\t}\n\n\t// Anthropic rejects a thinking-enabled request whose final assistant turn\n\t// contains tool_use but does not begin with a thinking block. Cross-model\n\t// histories lose their signed thinking blocks (demoted to text or dropped),\n\t// so degrade thinking for this request instead of failing every turn.\n\tif (params.thinking && params.thinking.type !== \"disabled\" && finalAssistantTurnStartsWithToolUse(params.messages))\n\t\tdisableThinkingForRequest(params, model, compat);\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 && compat.supportsToolChoice) {\n\t\tconst isForcedToolChoice = options.toolChoice === \"any\" || typeof options.toolChoice === \"object\";\n\t\tif (!isForcedToolChoice || compat.supportsForcedToolChoice) {\n\t\t\tif (typeof options.toolChoice === \"string\") {\n\t\t\t\tparams.tool_choice = { type: options.toolChoice };\n\t\t\t} else {\n\t\t\t\tparams.tool_choice = options.toolChoice;\n\t\t\t}\n\t\t}\n\t}\n\n\tapplyExtraBodyToAnthropicParams(params, options?.extraBody);\n\n\treturn params;\n}\n\nfunction applyExtraBodyToAnthropicParams(\n\tparams: MessageCreateParamsStreaming,\n\textraBody: Record<string, unknown> | undefined,\n): void {\n\tif (!extraBody) return;\n\tfor (const [key, value] of Object.entries(extraBody)) {\n\t\tif (ANTHROPIC_RESERVED_BODY_KEYS.has(key)) continue;\n\t\tObject.defineProperty(params, key, { value, writable: true, enumerable: true, configurable: true });\n\t}\n}\n\ntype AnthropicMessageParam = MessageCreateParamsStreaming[\"messages\"][number];\n\n/**\n * Whether the final assistant turn contains tool_use without a leading\n * thinking/redacted_thinking block. Anthropic requires thinking-enabled\n * requests to start that turn with a thinking block.\n */\nfunction finalAssistantTurnStartsWithToolUse(messages: AnthropicMessageParam[]): boolean {\n\tfor (let index = messages.length - 1; index >= 0; index--) {\n\t\tconst message = messages[index];\n\t\tif (message.role !== \"assistant\") continue;\n\t\tif (!Array.isArray(message.content) || message.content.length === 0) return false;\n\t\tconst first = message.content[0];\n\t\tif (first.type === \"thinking\" || first.type === \"redacted_thinking\") return false;\n\t\treturn message.content.some((block) => block.type === \"tool_use\");\n\t}\n\treturn false;\n}\n\nfunction convertToolResult(\n\tmsg: ToolResultMessage,\n\tisOAuthToken: boolean,\n\tdeferredToolNames: ReadonlySet<string>,\n\tloadedToolNames: Set<string>,\n\tnormalizeToolName: (name: string) => string,\n): { toolResult: ContentBlockParam; siblingContent: ContentBlockParam[] } {\n\tconst references: Array<{ type: \"tool_reference\"; tool_name: string }> = [];\n\tfor (const name of msg.addedToolNames ?? []) {\n\t\tconst normalizedName = normalizeToolName(name);\n\t\tif (!deferredToolNames.has(normalizedName) || loadedToolNames.has(normalizedName)) continue;\n\t\tloadedToolNames.add(normalizedName);\n\t\treferences.push({\n\t\t\ttype: \"tool_reference\",\n\t\t\ttool_name: isOAuthToken ? toClaudeCodeName(name) : name,\n\t\t});\n\t}\n\t// The video block variant is not in the SDK's ContentBlockParam union, so the\n\t// converted array is cast through the same escape hatch as tool_reference blocks.\n\tconst convertedContent = convertContentBlocks(msg.content) as string | ContentBlockParam[];\n\t// Anthropic rejects tool references mixed with ordinary tool-result content.\n\treturn {\n\t\ttoolResult: {\n\t\t\ttype: \"tool_result\",\n\t\t\ttool_use_id: msg.toolCallId,\n\t\t\tcontent: references.length > 0 ? references : convertedContent,\n\t\t\tis_error: msg.isError,\n\t\t} as unknown as ContentBlockParam,\n\t\tsiblingContent:\n\t\t\treferences.length === 0\n\t\t\t\t? []\n\t\t\t\t: typeof convertedContent === \"string\"\n\t\t\t\t\t? [{ type: \"text\", text: convertedContent }]\n\t\t\t\t\t: convertedContent,\n\t};\n}\n\nfunction convertMessages(\n\ttransformedMessages: Message[],\n\tmodel: Model<\"anthropic-messages\">,\n\tisOAuthToken: boolean,\n\tcacheControl?: CacheControlEphemeral,\n\tunsignedThinkingReplay: UnsignedThinkingReplay = \"text\",\n\tdeferredToolNames: ReadonlySet<string> = new Set(),\n\tnormalizeToolName: (name: string) => string = (name) => name,\n): MessageParam[] {\n\tconst params: MessageParam[] = [];\n\tconst loadedToolNames = new Set<string>();\n\t// Tool calls from a declined pre-fallback attempt are dropped from their\n\t// assistant turn below; drop their tool_results in lockstep so none dangle.\n\tconst discardedFallbackToolCallIds = collectDiscardedFallbackToolCallIds(transformedMessages, model);\n\tconst rejectsNativeWebSearchReplay = !getAnthropicCompat(model).supportsWebSearch;\n\tconst providerNativeToolPairing = collectProviderNativeToolPairing(\n\t\ttransformedMessages,\n\t\tmodel,\n\t\tdeferredToolNames,\n\t\tnormalizeToolName,\n\t\tdiscardedFallbackToolCallIds,\n\t);\n\n\tfor (let i = 0; i < transformedMessages.length; i++) {\n\t\tconst msg = transformedMessages[i];\n\n\t\tif (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} else if (isVideoMimeType(item.mimeType)) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\ttype: \"video\",\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: item.mimeType,\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} satisfies AnthropicVideoBlock as unknown as ContentBlockParam;\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\ttype: \"image\",\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: item.mimeType as \"image/jpeg\" | \"image/png\" | \"image/gif\" | \"image/webp\",\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};\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: ContentBlockParam[] = [];\n\t\t\tconst isSameModel = isSameAnthropicModel(msg, model);\n\t\t\t// Blocks before the final fallback marker are the declined attempt; the\n\t\t\t// marker onward is the serving model's output and replays verbatim.\n\t\t\tconst fallbackBoundary = isSameModel ? lastAnthropicFallbackBoundary(msg.content) : -1;\n\t\t\tconst preBoundaryPairedServerToolUseIds =\n\t\t\t\tfallbackBoundary >= 0\n\t\t\t\t\t? pairedServerToolUseIdsBeforeBoundary(msg.content, fallbackBoundary)\n\t\t\t\t\t: new Set<string>();\n\n\t\t\tfor (let blockIndex = 0; blockIndex < msg.content.length; blockIndex++) {\n\t\t\t\tconst block = msg.content[blockIndex];\n\t\t\t\tif (fallbackBoundary >= 0 && blockIndex < fallbackBoundary) {\n\t\t\t\t\t// Drop the declined attempt's model-internal blocks: thinking,\n\t\t\t\t\t// tool_use, and any unpaired server_tool_use. Paired server-tool\n\t\t\t\t\t// blocks and text survive per the fallback replay contract.\n\t\t\t\t\tif (block.type === \"thinking\" || block.type === \"toolCall\") {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif (\n\t\t\t\t\t\tblock.type === \"providerNative\" &&\n\t\t\t\t\t\tisAnthropicServerToolUseBlock(block.raw) &&\n\t\t\t\t\t\t!preBoundaryPairedServerToolUseIds.has(block.raw.id)\n\t\t\t\t\t) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (block.type === \"text\") {\n\t\t\t\t\tif (block.text.trim().length === 0) continue;\n\t\t\t\t\tblocks.push({\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: sanitizeSurrogates(block.text),\n\t\t\t\t\t});\n\t\t\t\t} else if (block.type === \"thinking\") {\n\t\t\t\t\t// Redacted thinking: pass the opaque payload back as redacted_thinking\n\t\t\t\t\tif (block.redacted) {\n\t\t\t\t\t\tblocks.push({\n\t\t\t\t\t\t\ttype: \"redacted_thinking\",\n\t\t\t\t\t\t\tdata: block.thinkingSignature!,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tconst thinkingSignature = block.thinkingSignature;\n\t\t\t\t\tconst hasThinkingSignature = !!thinkingSignature && thinkingSignature.trim().length > 0;\n\t\t\t\t\tif (block.thinking.trim().length === 0 && !hasThinkingSignature) continue;\n\t\t\t\t\t// If thinking signature is missing/empty (e.g., from aborted stream),\n\t\t\t\t\t// convert to plain text for Anthropic. Some compatible providers emit\n\t\t\t\t\t// and accept empty signatures, so let marked models preserve the block.\n\t\t\t\t\tif (!hasThinkingSignature) {\n\t\t\t\t\t\tblocks.push(\n\t\t\t\t\t\t\tunsignedThinkingReplay === \"empty-signature\"\n\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\ttype: \"thinking\",\n\t\t\t\t\t\t\t\t\t\tthinking: sanitizeSurrogates(block.thinking),\n\t\t\t\t\t\t\t\t\t\tsignature: \"\",\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\t\t\ttext: sanitizeSurrogates(block.thinking),\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tblocks.push({\n\t\t\t\t\t\t\ttype: \"thinking\",\n\t\t\t\t\t\t\tthinking: block.thinking,\n\t\t\t\t\t\t\tsignature: thinkingSignature,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t} else if (block.type === \"toolCall\") {\n\t\t\t\t\tblocks.push({\n\t\t\t\t\t\ttype: \"tool_use\",\n\t\t\t\t\t\tid: block.id,\n\t\t\t\t\t\tname: isOAuthToken ? toClaudeCodeName(block.name) : block.name,\n\t\t\t\t\t\tinput: block.arguments ?? {},\n\t\t\t\t\t});\n\t\t\t\t} else if (block.type === \"providerNative\") {\n\t\t\t\t\tif (\n\t\t\t\t\t\tisSameModel &&\n\t\t\t\t\t\tisReplayableAnthropicProviderNativeBlock(block.raw) &&\n\t\t\t\t\t\t!(rejectsNativeWebSearchReplay && isAnthropicWebSearchReplayBlock(block.raw)) &&\n\t\t\t\t\t\t!isUnpairedProviderNativeToolBlock(block.raw, providerNativeToolPairing)\n\t\t\t\t\t) {\n\t\t\t\t\t\tblocks.push(block.raw);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (blocks.length === 0) continue;\n\t\t\tparams.push({\n\t\t\t\trole: \"assistant\",\n\t\t\t\tcontent: blocks,\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\tconst siblingContent: ContentBlockParam[] = [];\n\t\t\tlet j = i;\n\t\t\twhile (j < transformedMessages.length && transformedMessages[j].role === \"toolResult\") {\n\t\t\t\tconst nextMsg = transformedMessages[j] as ToolResultMessage; // We know it's a toolResult\n\t\t\t\tif (!discardedFallbackToolCallIds.has(nextMsg.toolCallId)) {\n\t\t\t\t\tconst converted = convertToolResult(\n\t\t\t\t\t\tnextMsg,\n\t\t\t\t\t\tisOAuthToken,\n\t\t\t\t\t\tdeferredToolNames,\n\t\t\t\t\t\tloadedToolNames,\n\t\t\t\t\t\tnormalizeToolName,\n\t\t\t\t\t);\n\t\t\t\t\ttoolResults.push(converted.toolResult);\n\t\t\t\t\tsiblingContent.push(...converted.siblingContent);\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\t// Every result in this run may have been dropped; don't emit an empty turn.\n\t\t\tif (toolResults.length === 0) continue;\n\n\t\t\t// Displaced reference-bearing results must follow every tool_result block.\n\t\t\tparams.push({\n\t\t\t\trole: \"user\",\n\t\t\t\tcontent: [...toolResults, ...siblingContent],\n\t\t\t});\n\t\t}\n\t}\n\n\t// Add cache_control to the last user 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\") {\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 (isCacheableUserContentBlock(lastBlock)) {\n\t\t\t\t\tlastBlock.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];\n\t\t\t}\n\t\t}\n\t}\n\n\treturn params;\n}\n\nfunction shouldUseFineGrainedToolStreamingBeta(model: Model<\"anthropic-messages\">, context: Context): boolean {\n\treturn !!context.tools?.length && !getAnthropicCompat(model).supportsEagerToolInputStreaming;\n}\n\nfunction convertTools(\n\ttools: Tool[],\n\tisOAuthToken: boolean,\n\tsupportsEagerToolInputStreaming: boolean,\n\tsupportsStrictTools: boolean,\n\tcacheControl?: CacheControlEphemeral,\n\tdeferLoading = false,\n): Anthropic.Messages.Tool[] {\n\tif (!tools) return [];\n\n\treturn tools.map((tool, index) => {\n\t\tconst strict = resolveJsonSchemaStrictSampling(tool, supportsStrictTools);\n\t\tconst schema = tool.parameters as { properties?: unknown; required?: string[] };\n\t\tconst legacyInputSchema = {\n\t\t\ttype: \"object\" as const,\n\t\t\tproperties: schema.properties ?? {},\n\t\t\trequired: schema.required ?? [],\n\t\t};\n\t\tconst inputSchema =\n\t\t\tstrict === true\n\t\t\t\t? {\n\t\t\t\t\t\t...(tool.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...(deferLoading ? { defer_loading: true } : {}),\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; stopDetails?: AssistantStopDetails } {\n\tconst explanation = stopDetails?.explanation;\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: explanation || `The model refused to complete the request`,\n\t\t\t\tstopDetails: explanation == null ? { type: \"refusal\" } : { type: \"refusal\", explanation },\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\", stopDetails: { type: \"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"]}
|