@draht/ai 2026.3.2-2
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/README.md +1185 -0
- package/dist/api-registry.d.ts +20 -0
- package/dist/api-registry.d.ts.map +1 -0
- package/dist/api-registry.js +44 -0
- package/dist/api-registry.js.map +1 -0
- package/dist/cli.d.ts +3 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +116 -0
- package/dist/cli.js.map +1 -0
- package/dist/env-api-keys.d.ts +9 -0
- package/dist/env-api-keys.d.ts.map +1 -0
- package/dist/env-api-keys.js +99 -0
- package/dist/env-api-keys.js.map +1 -0
- package/dist/index.d.ts +22 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +21 -0
- package/dist/index.js.map +1 -0
- package/dist/models.d.ts +24 -0
- package/dist/models.d.ts.map +1 -0
- package/dist/models.generated.d.ts +13133 -0
- package/dist/models.generated.d.ts.map +1 -0
- package/dist/models.generated.js +12939 -0
- package/dist/models.generated.js.map +1 -0
- package/dist/models.js +55 -0
- package/dist/models.js.map +1 -0
- package/dist/providers/amazon-bedrock.d.ts +15 -0
- package/dist/providers/amazon-bedrock.d.ts.map +1 -0
- package/dist/providers/amazon-bedrock.js +585 -0
- package/dist/providers/amazon-bedrock.js.map +1 -0
- package/dist/providers/anthropic.d.ts +33 -0
- package/dist/providers/anthropic.d.ts.map +1 -0
- package/dist/providers/anthropic.js +729 -0
- package/dist/providers/anthropic.js.map +1 -0
- package/dist/providers/azure-openai-responses.d.ts +15 -0
- package/dist/providers/azure-openai-responses.d.ts.map +1 -0
- package/dist/providers/azure-openai-responses.js +184 -0
- package/dist/providers/azure-openai-responses.js.map +1 -0
- package/dist/providers/github-copilot-headers.d.ts +8 -0
- package/dist/providers/github-copilot-headers.d.ts.map +1 -0
- package/dist/providers/github-copilot-headers.js +29 -0
- package/dist/providers/github-copilot-headers.js.map +1 -0
- package/dist/providers/google-gemini-cli.d.ts +74 -0
- package/dist/providers/google-gemini-cli.d.ts.map +1 -0
- package/dist/providers/google-gemini-cli.js +735 -0
- package/dist/providers/google-gemini-cli.js.map +1 -0
- package/dist/providers/google-shared.d.ts +65 -0
- package/dist/providers/google-shared.d.ts.map +1 -0
- package/dist/providers/google-shared.js +306 -0
- package/dist/providers/google-shared.js.map +1 -0
- package/dist/providers/google-vertex.d.ts +15 -0
- package/dist/providers/google-vertex.d.ts.map +1 -0
- package/dist/providers/google-vertex.js +371 -0
- package/dist/providers/google-vertex.js.map +1 -0
- package/dist/providers/google.d.ts +13 -0
- package/dist/providers/google.d.ts.map +1 -0
- package/dist/providers/google.js +352 -0
- package/dist/providers/google.js.map +1 -0
- package/dist/providers/openai-codex-responses.d.ts +9 -0
- package/dist/providers/openai-codex-responses.d.ts.map +1 -0
- package/dist/providers/openai-codex-responses.js +699 -0
- package/dist/providers/openai-codex-responses.js.map +1 -0
- package/dist/providers/openai-completions.d.ts +15 -0
- package/dist/providers/openai-completions.d.ts.map +1 -0
- package/dist/providers/openai-completions.js +712 -0
- package/dist/providers/openai-completions.js.map +1 -0
- package/dist/providers/openai-responses-shared.d.ts +17 -0
- package/dist/providers/openai-responses-shared.d.ts.map +1 -0
- package/dist/providers/openai-responses-shared.js +427 -0
- package/dist/providers/openai-responses-shared.js.map +1 -0
- package/dist/providers/openai-responses.d.ts +13 -0
- package/dist/providers/openai-responses.d.ts.map +1 -0
- package/dist/providers/openai-responses.js +198 -0
- package/dist/providers/openai-responses.js.map +1 -0
- package/dist/providers/register-builtins.d.ts +3 -0
- package/dist/providers/register-builtins.d.ts.map +1 -0
- package/dist/providers/register-builtins.js +63 -0
- package/dist/providers/register-builtins.js.map +1 -0
- package/dist/providers/simple-options.d.ts +8 -0
- package/dist/providers/simple-options.d.ts.map +1 -0
- package/dist/providers/simple-options.js +35 -0
- package/dist/providers/simple-options.js.map +1 -0
- package/dist/providers/transform-messages.d.ts +8 -0
- package/dist/providers/transform-messages.d.ts.map +1 -0
- package/dist/providers/transform-messages.js +155 -0
- package/dist/providers/transform-messages.js.map +1 -0
- package/dist/stream.d.ts +9 -0
- package/dist/stream.d.ts.map +1 -0
- package/dist/stream.js +28 -0
- package/dist/stream.js.map +1 -0
- package/dist/types.d.ts +279 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/dist/utils/event-stream.d.ts +21 -0
- package/dist/utils/event-stream.d.ts.map +1 -0
- package/dist/utils/event-stream.js +81 -0
- package/dist/utils/event-stream.js.map +1 -0
- package/dist/utils/http-proxy.d.ts +2 -0
- package/dist/utils/http-proxy.d.ts.map +1 -0
- package/dist/utils/http-proxy.js +15 -0
- package/dist/utils/http-proxy.js.map +1 -0
- package/dist/utils/json-parse.d.ts +9 -0
- package/dist/utils/json-parse.d.ts.map +1 -0
- package/dist/utils/json-parse.js +29 -0
- package/dist/utils/json-parse.js.map +1 -0
- package/dist/utils/oauth/anthropic.d.ts +17 -0
- package/dist/utils/oauth/anthropic.d.ts.map +1 -0
- package/dist/utils/oauth/anthropic.js +104 -0
- package/dist/utils/oauth/anthropic.js.map +1 -0
- package/dist/utils/oauth/github-copilot.d.ts +30 -0
- package/dist/utils/oauth/github-copilot.d.ts.map +1 -0
- package/dist/utils/oauth/github-copilot.js +281 -0
- package/dist/utils/oauth/github-copilot.js.map +1 -0
- package/dist/utils/oauth/google-antigravity.d.ts +26 -0
- package/dist/utils/oauth/google-antigravity.d.ts.map +1 -0
- package/dist/utils/oauth/google-antigravity.js +373 -0
- package/dist/utils/oauth/google-antigravity.js.map +1 -0
- package/dist/utils/oauth/google-gemini-cli.d.ts +26 -0
- package/dist/utils/oauth/google-gemini-cli.d.ts.map +1 -0
- package/dist/utils/oauth/google-gemini-cli.js +478 -0
- package/dist/utils/oauth/google-gemini-cli.js.map +1 -0
- package/dist/utils/oauth/index.d.ts +62 -0
- package/dist/utils/oauth/index.d.ts.map +1 -0
- package/dist/utils/oauth/index.js +133 -0
- package/dist/utils/oauth/index.js.map +1 -0
- package/dist/utils/oauth/openai-codex.d.ts +34 -0
- package/dist/utils/oauth/openai-codex.d.ts.map +1 -0
- package/dist/utils/oauth/openai-codex.js +380 -0
- package/dist/utils/oauth/openai-codex.js.map +1 -0
- package/dist/utils/oauth/pkce.d.ts +13 -0
- package/dist/utils/oauth/pkce.d.ts.map +1 -0
- package/dist/utils/oauth/pkce.js +31 -0
- package/dist/utils/oauth/pkce.js.map +1 -0
- package/dist/utils/oauth/types.d.ts +47 -0
- package/dist/utils/oauth/types.d.ts.map +1 -0
- package/dist/utils/oauth/types.js +2 -0
- package/dist/utils/oauth/types.js.map +1 -0
- package/dist/utils/overflow.d.ts +52 -0
- package/dist/utils/overflow.d.ts.map +1 -0
- package/dist/utils/overflow.js +115 -0
- package/dist/utils/overflow.js.map +1 -0
- package/dist/utils/sanitize-unicode.d.ts +22 -0
- package/dist/utils/sanitize-unicode.d.ts.map +1 -0
- package/dist/utils/sanitize-unicode.js +26 -0
- package/dist/utils/sanitize-unicode.js.map +1 -0
- package/dist/utils/typebox-helpers.d.ts +17 -0
- package/dist/utils/typebox-helpers.d.ts.map +1 -0
- package/dist/utils/typebox-helpers.js +21 -0
- package/dist/utils/typebox-helpers.js.map +1 -0
- package/dist/utils/validation.d.ts +18 -0
- package/dist/utils/validation.d.ts.map +1 -0
- package/dist/utils/validation.js +72 -0
- package/dist/utils/validation.js.map +1 -0
- package/package.json +67 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"amazon-bedrock.js","sourceRoot":"","sources":["../../src/providers/amazon-bedrock.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,oBAAoB,EAEpB,UAAU,IAAI,iBAAiB,EAE/B,cAAc,EACd,QAAQ,EAKR,gBAAgB,EAChB,qBAAqB,EAErB,WAAW,EAKX,gBAAgB,GAChB,MAAM,iCAAiC,CAAC;AAEzC,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAmB7C,OAAO,EAAE,2BAA2B,EAAE,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ool as BedrockTool,\n\tCachePointType,\n\tCacheTTL,\n\ttype ContentBlock,\n\ttype ContentBlockDeltaEvent,\n\ttype ContentBlockStartEvent,\n\ttype ContentBlockStopEvent,\n\tConversationRole,\n\tConverseStreamCommand,\n\ttype ConverseStreamMetadataEvent,\n\tImageFormat,\n\ttype Message,\n\ttype SystemContentBlock,\n\ttype ToolChoice,\n\ttype ToolConfiguration,\n\tToolResultStatus,\n} from \"@aws-sdk/client-bedrock-runtime\";\n\nimport { calculateCost } from \"../models.js\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tCacheRetention,\n\tContext,\n\tModel,\n\tSimpleStreamOptions,\n\tStopReason,\n\tStreamFunction,\n\tStreamOptions,\n\tTextContent,\n\tThinkingBudgets,\n\tThinkingContent,\n\tThinkingLevel,\n\tTool,\n\tToolCall,\n\tToolResultMessage,\n} from \"../types.js\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.js\";\nimport { parseStreamingJson } from \"../utils/json-parse.js\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.js\";\nimport { adjustMaxTokensForThinking, buildBaseOptions, clampReasoning } from \"./simple-options.js\";\nimport { transformMessages } from \"./transform-messages.js\";\n\nexport interface BedrockOptions extends StreamOptions {\n\tregion?: string;\n\tprofile?: string;\n\ttoolChoice?: \"auto\" | \"any\" | \"none\" | { type: \"tool\"; name: string };\n\t/* See https://docs.aws.amazon.com/bedrock/latest/userguide/inference-reasoning.html for supported models. */\n\treasoning?: ThinkingLevel;\n\t/* Custom token budgets per thinking level. Overrides default budgets. */\n\tthinkingBudgets?: ThinkingBudgets;\n\t/* Only supported by Claude 4.x models, see https://docs.aws.amazon.com/bedrock/latest/userguide/claude-messages-extended-thinking.html#claude-messages-extended-thinking-tool-use-interleaved */\n\tinterleavedThinking?: boolean;\n}\n\ntype Block = (TextContent | ThinkingContent | ToolCall) & { index?: number; partialJson?: string };\n\nexport const streamBedrock: StreamFunction<\"bedrock-converse-stream\", BedrockOptions> = (\n\tmodel: Model<\"bedrock-converse-stream\">,\n\tcontext: Context,\n\toptions: BedrockOptions = {},\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: \"bedrock-converse-stream\" 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 blocks = output.content as Block[];\n\n\t\tconst config: BedrockRuntimeClientConfig = {\n\t\t\tregion: options.region,\n\t\t\tprofile: options.profile,\n\t\t};\n\n\t\t// in Node.js/Bun environment only\n\t\tif (typeof process !== \"undefined\" && (process.versions?.node || process.versions?.bun)) {\n\t\t\tconfig.region = config.region || process.env.AWS_REGION || process.env.AWS_DEFAULT_REGION;\n\n\t\t\t// Support proxies that don't need authentication\n\t\t\tif (process.env.AWS_BEDROCK_SKIP_AUTH === \"1\") {\n\t\t\t\tconfig.credentials = {\n\t\t\t\t\taccessKeyId: \"dummy-access-key\",\n\t\t\t\t\tsecretAccessKey: \"dummy-secret-key\",\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (\n\t\t\t\tprocess.env.HTTP_PROXY ||\n\t\t\t\tprocess.env.HTTPS_PROXY ||\n\t\t\t\tprocess.env.NO_PROXY ||\n\t\t\t\tprocess.env.http_proxy ||\n\t\t\t\tprocess.env.https_proxy ||\n\t\t\t\tprocess.env.no_proxy\n\t\t\t) {\n\t\t\t\tconst nodeHttpHandler = await import(\"@smithy/node-http-handler\");\n\t\t\t\tconst proxyAgent = await import(\"proxy-agent\");\n\n\t\t\t\tconst agent = new proxyAgent.ProxyAgent();\n\n\t\t\t\t// Bedrock runtime uses NodeHttp2Handler by default since v3.798.0, which is based\n\t\t\t\t// on `http2` module and has no support for http agent.\n\t\t\t\t// Use NodeHttpHandler to support http agent.\n\t\t\t\tconfig.requestHandler = new nodeHttpHandler.NodeHttpHandler({\n\t\t\t\t\thttpAgent: agent,\n\t\t\t\t\thttpsAgent: agent,\n\t\t\t\t});\n\t\t\t} else if (process.env.AWS_BEDROCK_FORCE_HTTP1 === \"1\") {\n\t\t\t\t// Some custom endpoints require HTTP/1.1 instead of HTTP/2\n\t\t\t\tconst nodeHttpHandler = await import(\"@smithy/node-http-handler\");\n\t\t\t\tconfig.requestHandler = new nodeHttpHandler.NodeHttpHandler();\n\t\t\t}\n\t\t}\n\n\t\tconfig.region = config.region || \"us-east-1\";\n\n\t\ttry {\n\t\t\tconst client = new BedrockRuntimeClient(config);\n\n\t\t\tconst cacheRetention = resolveCacheRetention(options.cacheRetention);\n\t\t\tconst commandInput = {\n\t\t\t\tmodelId: model.id,\n\t\t\t\tmessages: convertMessages(context, model, cacheRetention),\n\t\t\t\tsystem: buildSystemPrompt(context.systemPrompt, model, cacheRetention),\n\t\t\t\tinferenceConfig: { maxTokens: options.maxTokens, temperature: options.temperature },\n\t\t\t\ttoolConfig: convertToolConfig(context.tools, options.toolChoice),\n\t\t\t\tadditionalModelRequestFields: buildAdditionalModelRequestFields(model, options),\n\t\t\t};\n\t\t\toptions?.onPayload?.(commandInput);\n\t\t\tconst command = new ConverseStreamCommand(commandInput);\n\n\t\t\tconst response = await client.send(command, { abortSignal: options.signal });\n\n\t\t\tfor await (const item of response.stream!) {\n\t\t\t\tif (item.messageStart) {\n\t\t\t\t\tif (item.messageStart.role !== ConversationRole.ASSISTANT) {\n\t\t\t\t\t\tthrow new Error(\"Unexpected assistant message start but got user message start instead\");\n\t\t\t\t\t}\n\t\t\t\t\tstream.push({ type: \"start\", partial: output });\n\t\t\t\t} else if (item.contentBlockStart) {\n\t\t\t\t\thandleContentBlockStart(item.contentBlockStart, blocks, output, stream);\n\t\t\t\t} else if (item.contentBlockDelta) {\n\t\t\t\t\thandleContentBlockDelta(item.contentBlockDelta, blocks, output, stream);\n\t\t\t\t} else if (item.contentBlockStop) {\n\t\t\t\t\thandleContentBlockStop(item.contentBlockStop, blocks, output, stream);\n\t\t\t\t} else if (item.messageStop) {\n\t\t\t\t\toutput.stopReason = mapStopReason(item.messageStop.stopReason);\n\t\t\t\t} else if (item.metadata) {\n\t\t\t\t\thandleMetadata(item.metadata, model, output);\n\t\t\t\t} else if (item.internalServerException) {\n\t\t\t\t\tthrow new Error(`Internal server error: ${item.internalServerException.message}`);\n\t\t\t\t} else if (item.modelStreamErrorException) {\n\t\t\t\t\tthrow new Error(`Model stream error: ${item.modelStreamErrorException.message}`);\n\t\t\t\t} else if (item.validationException) {\n\t\t\t\t\tthrow new Error(`Validation error: ${item.validationException.message}`);\n\t\t\t\t} else if (item.throttlingException) {\n\t\t\t\t\tthrow new Error(`Throttling error: ${item.throttlingException.message}`);\n\t\t\t\t} else if (item.serviceUnavailableException) {\n\t\t\t\t\tthrow new Error(`Service unavailable: ${item.serviceUnavailableException.message}`);\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 (output.stopReason === \"error\" || output.stopReason === \"aborted\") {\n\t\t\t\tthrow new Error(\"An unknown error occurred\");\n\t\t\t}\n\n\t\t\tstream.push({ type: \"done\", reason: output.stopReason, message: output });\n\t\t\tstream.end();\n\t\t} catch (error) {\n\t\t\tfor (const block of output.content) {\n\t\t\t\tdelete (block as Block).index;\n\t\t\t\tdelete (block as Block).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\nexport const streamSimpleBedrock: StreamFunction<\"bedrock-converse-stream\", SimpleStreamOptions> = (\n\tmodel: Model<\"bedrock-converse-stream\">,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): AssistantMessageEventStream => {\n\tconst base = buildBaseOptions(model, options, undefined);\n\tif (!options?.reasoning) {\n\t\treturn streamBedrock(model, context, { ...base, reasoning: undefined } satisfies BedrockOptions);\n\t}\n\n\tif (model.id.includes(\"anthropic.claude\") || model.id.includes(\"anthropic/claude\")) {\n\t\tif (supportsAdaptiveThinking(model.id)) {\n\t\t\treturn streamBedrock(model, context, {\n\t\t\t\t...base,\n\t\t\t\treasoning: options.reasoning,\n\t\t\t\tthinkingBudgets: options.thinkingBudgets,\n\t\t\t} satisfies BedrockOptions);\n\t\t}\n\n\t\tconst adjusted = adjustMaxTokensForThinking(\n\t\t\tbase.maxTokens || 0,\n\t\t\tmodel.maxTokens,\n\t\t\toptions.reasoning,\n\t\t\toptions.thinkingBudgets,\n\t\t);\n\n\t\treturn streamBedrock(model, context, {\n\t\t\t...base,\n\t\t\tmaxTokens: adjusted.maxTokens,\n\t\t\treasoning: options.reasoning,\n\t\t\tthinkingBudgets: {\n\t\t\t\t...(options.thinkingBudgets || {}),\n\t\t\t\t[clampReasoning(options.reasoning)!]: adjusted.thinkingBudget,\n\t\t\t},\n\t\t} satisfies BedrockOptions);\n\t}\n\n\treturn streamBedrock(model, context, {\n\t\t...base,\n\t\treasoning: options.reasoning,\n\t\tthinkingBudgets: options.thinkingBudgets,\n\t} satisfies BedrockOptions);\n};\n\nfunction handleContentBlockStart(\n\tevent: ContentBlockStartEvent,\n\tblocks: Block[],\n\toutput: AssistantMessage,\n\tstream: AssistantMessageEventStream,\n): void {\n\tconst index = event.contentBlockIndex!;\n\tconst start = event.start;\n\n\tif (start?.toolUse) {\n\t\tconst block: Block = {\n\t\t\ttype: \"toolCall\",\n\t\t\tid: start.toolUse.toolUseId || \"\",\n\t\t\tname: start.toolUse.name || \"\",\n\t\t\targuments: {},\n\t\t\tpartialJson: \"\",\n\t\t\tindex,\n\t\t};\n\t\toutput.content.push(block);\n\t\tstream.push({ type: \"toolcall_start\", contentIndex: blocks.length - 1, partial: output });\n\t}\n}\n\nfunction handleContentBlockDelta(\n\tevent: ContentBlockDeltaEvent,\n\tblocks: Block[],\n\toutput: AssistantMessage,\n\tstream: AssistantMessageEventStream,\n): void {\n\tconst contentBlockIndex = event.contentBlockIndex!;\n\tconst delta = event.delta;\n\tlet index = blocks.findIndex((b) => b.index === contentBlockIndex);\n\tlet block = blocks[index];\n\n\tif (delta?.text !== undefined) {\n\t\t// If no text block exists yet, create one, as `handleContentBlockStart` is not sent for text blocks\n\t\tif (!block) {\n\t\t\tconst newBlock: Block = { type: \"text\", text: \"\", index: contentBlockIndex };\n\t\t\toutput.content.push(newBlock);\n\t\t\tindex = blocks.length - 1;\n\t\t\tblock = blocks[index];\n\t\t\tstream.push({ type: \"text_start\", contentIndex: index, partial: output });\n\t\t}\n\t\tif (block.type === \"text\") {\n\t\t\tblock.text += delta.text;\n\t\t\tstream.push({ type: \"text_delta\", contentIndex: index, delta: delta.text, partial: output });\n\t\t}\n\t} else if (delta?.toolUse && block?.type === \"toolCall\") {\n\t\tblock.partialJson = (block.partialJson || \"\") + (delta.toolUse.input || \"\");\n\t\tblock.arguments = parseStreamingJson(block.partialJson);\n\t\tstream.push({ type: \"toolcall_delta\", contentIndex: index, delta: delta.toolUse.input || \"\", partial: output });\n\t} else if (delta?.reasoningContent) {\n\t\tlet thinkingBlock = block;\n\t\tlet thinkingIndex = index;\n\n\t\tif (!thinkingBlock) {\n\t\t\tconst newBlock: Block = { type: \"thinking\", thinking: \"\", thinkingSignature: \"\", index: contentBlockIndex };\n\t\t\toutput.content.push(newBlock);\n\t\t\tthinkingIndex = blocks.length - 1;\n\t\t\tthinkingBlock = blocks[thinkingIndex];\n\t\t\tstream.push({ type: \"thinking_start\", contentIndex: thinkingIndex, partial: output });\n\t\t}\n\n\t\tif (thinkingBlock?.type === \"thinking\") {\n\t\t\tif (delta.reasoningContent.text) {\n\t\t\t\tthinkingBlock.thinking += delta.reasoningContent.text;\n\t\t\t\tstream.push({\n\t\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\t\tcontentIndex: thinkingIndex,\n\t\t\t\t\tdelta: delta.reasoningContent.text,\n\t\t\t\t\tpartial: output,\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (delta.reasoningContent.signature) {\n\t\t\t\tthinkingBlock.thinkingSignature =\n\t\t\t\t\t(thinkingBlock.thinkingSignature || \"\") + delta.reasoningContent.signature;\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction handleMetadata(\n\tevent: ConverseStreamMetadataEvent,\n\tmodel: Model<\"bedrock-converse-stream\">,\n\toutput: AssistantMessage,\n): void {\n\tif (event.usage) {\n\t\toutput.usage.input = event.usage.inputTokens || 0;\n\t\toutput.usage.output = event.usage.outputTokens || 0;\n\t\toutput.usage.cacheRead = event.usage.cacheReadInputTokens || 0;\n\t\toutput.usage.cacheWrite = event.usage.cacheWriteInputTokens || 0;\n\t\toutput.usage.totalTokens = event.usage.totalTokens || output.usage.input + output.usage.output;\n\t\tcalculateCost(model, output.usage);\n\t}\n}\n\nfunction handleContentBlockStop(\n\tevent: ContentBlockStopEvent,\n\tblocks: Block[],\n\toutput: AssistantMessage,\n\tstream: AssistantMessageEventStream,\n): void {\n\tconst index = blocks.findIndex((b) => b.index === event.contentBlockIndex);\n\tconst block = blocks[index];\n\tif (!block) return;\n\tdelete (block as Block).index;\n\n\tswitch (block.type) {\n\t\tcase \"text\":\n\t\t\tstream.push({ type: \"text_end\", contentIndex: index, content: block.text, partial: output });\n\t\t\tbreak;\n\t\tcase \"thinking\":\n\t\t\tstream.push({ type: \"thinking_end\", contentIndex: index, content: block.thinking, partial: output });\n\t\t\tbreak;\n\t\tcase \"toolCall\":\n\t\t\tblock.arguments = parseStreamingJson(block.partialJson);\n\t\t\tdelete (block as Block).partialJson;\n\t\t\tstream.push({ type: \"toolcall_end\", contentIndex: index, toolCall: block, partial: output });\n\t\t\tbreak;\n\t}\n}\n\n/**\n * Check if the model supports adaptive thinking (Opus 4.6 and Sonnet 4.6).\n */\nfunction supportsAdaptiveThinking(modelId: string): boolean {\n\treturn (\n\t\tmodelId.includes(\"opus-4-6\") ||\n\t\tmodelId.includes(\"opus-4.6\") ||\n\t\tmodelId.includes(\"sonnet-4-6\") ||\n\t\tmodelId.includes(\"sonnet-4.6\")\n\t);\n}\n\nfunction mapThinkingLevelToEffort(\n\tlevel: SimpleStreamOptions[\"reasoning\"],\n\tmodelId: string,\n): \"low\" | \"medium\" | \"high\" | \"max\" {\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\treturn modelId.includes(\"opus-4-6\") || modelId.includes(\"opus-4.6\") ? \"max\" : \"high\";\n\t\tdefault:\n\t\t\treturn \"high\";\n\t}\n}\n\n/**\n * Resolve cache retention preference.\n * Defaults to \"short\" and uses DRAHT_CACHE_RETENTION for backward compatibility.\n */\nfunction resolveCacheRetention(cacheRetention?: CacheRetention): CacheRetention {\n\tif (cacheRetention) {\n\t\treturn cacheRetention;\n\t}\n\tif (typeof process !== \"undefined\" && process.env.DRAHT_CACHE_RETENTION === \"long\") {\n\t\treturn \"long\";\n\t}\n\treturn \"short\";\n}\n\n/**\n * Check if the model supports prompt caching.\n * Supported: Claude 3.5 Haiku, Claude 3.7 Sonnet, Claude 4.x models\n */\nfunction supportsPromptCaching(model: Model<\"bedrock-converse-stream\">): boolean {\n\tif (model.cost.cacheRead || model.cost.cacheWrite) {\n\t\treturn true;\n\t}\n\n\tconst id = model.id.toLowerCase();\n\t// Claude 4.x models (opus-4, sonnet-4, haiku-4)\n\tif (id.includes(\"claude\") && (id.includes(\"-4-\") || id.includes(\"-4.\"))) return true;\n\t// Claude 3.7 Sonnet\n\tif (id.includes(\"claude-3-7-sonnet\")) return true;\n\t// Claude 3.5 Haiku\n\tif (id.includes(\"claude-3-5-haiku\")) return true;\n\treturn false;\n}\n\n/**\n * Check if the model supports thinking signatures in reasoningContent.\n * Only Anthropic Claude models support the signature field.\n * Other models (OpenAI, Qwen, Minimax, Moonshot, etc.) reject it with:\n * \"This model doesn't support the reasoningContent.reasoningText.signature field\"\n */\nfunction supportsThinkingSignature(model: Model<\"bedrock-converse-stream\">): boolean {\n\tconst id = model.id.toLowerCase();\n\treturn id.includes(\"anthropic.claude\") || id.includes(\"anthropic/claude\");\n}\n\nfunction buildSystemPrompt(\n\tsystemPrompt: string | undefined,\n\tmodel: Model<\"bedrock-converse-stream\">,\n\tcacheRetention: CacheRetention,\n): SystemContentBlock[] | undefined {\n\tif (!systemPrompt) return undefined;\n\n\tconst blocks: SystemContentBlock[] = [{ text: sanitizeSurrogates(systemPrompt) }];\n\n\t// Add cache point for supported Claude models when caching is enabled\n\tif (cacheRetention !== \"none\" && supportsPromptCaching(model)) {\n\t\tblocks.push({\n\t\t\tcachePoint: { type: CachePointType.DEFAULT, ...(cacheRetention === \"long\" ? { ttl: CacheTTL.ONE_HOUR } : {}) },\n\t\t});\n\t}\n\n\treturn blocks;\n}\n\nfunction normalizeToolCallId(id: string): string {\n\tconst sanitized = id.replace(/[^a-zA-Z0-9_-]/g, \"_\");\n\treturn sanitized.length > 64 ? sanitized.slice(0, 64) : sanitized;\n}\n\nfunction convertMessages(\n\tcontext: Context,\n\tmodel: Model<\"bedrock-converse-stream\">,\n\tcacheRetention: CacheRetention,\n): Message[] {\n\tconst result: Message[] = [];\n\tconst transformedMessages = transformMessages(context.messages, model, normalizeToolCallId);\n\n\tfor (let i = 0; i < transformedMessages.length; i++) {\n\t\tconst m = transformedMessages[i];\n\n\t\tswitch (m.role) {\n\t\t\tcase \"user\":\n\t\t\t\tresult.push({\n\t\t\t\t\trole: ConversationRole.USER,\n\t\t\t\t\tcontent:\n\t\t\t\t\t\ttypeof m.content === \"string\"\n\t\t\t\t\t\t\t? [{ text: sanitizeSurrogates(m.content) }]\n\t\t\t\t\t\t\t: m.content.map((c) => {\n\t\t\t\t\t\t\t\t\tswitch (c.type) {\n\t\t\t\t\t\t\t\t\t\tcase \"text\":\n\t\t\t\t\t\t\t\t\t\t\treturn { text: sanitizeSurrogates(c.text) };\n\t\t\t\t\t\t\t\t\t\tcase \"image\":\n\t\t\t\t\t\t\t\t\t\t\treturn { image: createImageBlock(c.mimeType, c.data) };\n\t\t\t\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\t\t\t\tthrow new Error(\"Unknown user content type\");\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tcase \"assistant\": {\n\t\t\t\t// Skip assistant messages with empty content (e.g., from aborted requests)\n\t\t\t\t// Bedrock rejects messages with empty content arrays\n\t\t\t\tif (m.content.length === 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst contentBlocks: ContentBlock[] = [];\n\t\t\t\tfor (const c of m.content) {\n\t\t\t\t\tswitch (c.type) {\n\t\t\t\t\t\tcase \"text\":\n\t\t\t\t\t\t\t// Skip empty text blocks\n\t\t\t\t\t\t\tif (c.text.trim().length === 0) continue;\n\t\t\t\t\t\t\tcontentBlocks.push({ text: sanitizeSurrogates(c.text) });\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"toolCall\":\n\t\t\t\t\t\t\tcontentBlocks.push({\n\t\t\t\t\t\t\t\ttoolUse: { toolUseId: c.id, name: c.name, input: c.arguments },\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"thinking\":\n\t\t\t\t\t\t\t// Skip empty thinking blocks\n\t\t\t\t\t\t\tif (c.thinking.trim().length === 0) continue;\n\t\t\t\t\t\t\t// Only Anthropic models support the signature field in reasoningText.\n\t\t\t\t\t\t\t// For other models, we omit the signature to avoid errors like:\n\t\t\t\t\t\t\t// \"This model doesn't support the reasoningContent.reasoningText.signature field\"\n\t\t\t\t\t\t\tif (supportsThinkingSignature(model)) {\n\t\t\t\t\t\t\t\tcontentBlocks.push({\n\t\t\t\t\t\t\t\t\treasoningContent: {\n\t\t\t\t\t\t\t\t\t\treasoningText: { text: sanitizeSurrogates(c.thinking), signature: c.thinkingSignature },\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} else {\n\t\t\t\t\t\t\t\tcontentBlocks.push({\n\t\t\t\t\t\t\t\t\treasoningContent: {\n\t\t\t\t\t\t\t\t\t\treasoningText: { text: sanitizeSurrogates(c.thinking) },\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}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tthrow new Error(\"Unknown assistant content type\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Skip if all content blocks were filtered out\n\t\t\t\tif (contentBlocks.length === 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tresult.push({\n\t\t\t\t\trole: ConversationRole.ASSISTANT,\n\t\t\t\t\tcontent: contentBlocks,\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"toolResult\": {\n\t\t\t\t// Collect all consecutive toolResult messages into a single user message\n\t\t\t\t// Bedrock requires all tool results to be in one message\n\t\t\t\tconst toolResults: ContentBlock.ToolResultMember[] = [];\n\n\t\t\t\t// Add current tool result with all content blocks combined\n\t\t\t\ttoolResults.push({\n\t\t\t\t\ttoolResult: {\n\t\t\t\t\t\ttoolUseId: m.toolCallId,\n\t\t\t\t\t\tcontent: m.content.map((c) =>\n\t\t\t\t\t\t\tc.type === \"image\"\n\t\t\t\t\t\t\t\t? { image: createImageBlock(c.mimeType, c.data) }\n\t\t\t\t\t\t\t\t: { text: sanitizeSurrogates(c.text) },\n\t\t\t\t\t\t),\n\t\t\t\t\t\tstatus: m.isError ? ToolResultStatus.ERROR : ToolResultStatus.SUCCESS,\n\t\t\t\t\t},\n\t\t\t\t});\n\n\t\t\t\t// Look ahead for consecutive toolResult messages\n\t\t\t\tlet j = i + 1;\n\t\t\t\twhile (j < transformedMessages.length && transformedMessages[j].role === \"toolResult\") {\n\t\t\t\t\tconst nextMsg = transformedMessages[j] as ToolResultMessage;\n\t\t\t\t\ttoolResults.push({\n\t\t\t\t\t\ttoolResult: {\n\t\t\t\t\t\t\ttoolUseId: nextMsg.toolCallId,\n\t\t\t\t\t\t\tcontent: nextMsg.content.map((c) =>\n\t\t\t\t\t\t\t\tc.type === \"image\"\n\t\t\t\t\t\t\t\t\t? { image: createImageBlock(c.mimeType, c.data) }\n\t\t\t\t\t\t\t\t\t: { text: sanitizeSurrogates(c.text) },\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\tstatus: nextMsg.isError ? ToolResultStatus.ERROR : ToolResultStatus.SUCCESS,\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t\tj++;\n\t\t\t\t}\n\n\t\t\t\t// Skip the messages we've already processed\n\t\t\t\ti = j - 1;\n\n\t\t\t\tresult.push({\n\t\t\t\t\trole: ConversationRole.USER,\n\t\t\t\t\tcontent: toolResults,\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\tthrow new Error(\"Unknown message role\");\n\t\t}\n\t}\n\n\t// Add cache point to the last user message for supported Claude models when caching is enabled\n\tif (cacheRetention !== \"none\" && supportsPromptCaching(model) && result.length > 0) {\n\t\tconst lastMessage = result[result.length - 1];\n\t\tif (lastMessage.role === ConversationRole.USER && lastMessage.content) {\n\t\t\t(lastMessage.content as ContentBlock[]).push({\n\t\t\t\tcachePoint: {\n\t\t\t\t\ttype: CachePointType.DEFAULT,\n\t\t\t\t\t...(cacheRetention === \"long\" ? { ttl: CacheTTL.ONE_HOUR } : {}),\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t}\n\n\treturn result;\n}\n\nfunction convertToolConfig(\n\ttools: Tool[] | undefined,\n\ttoolChoice: BedrockOptions[\"toolChoice\"],\n): ToolConfiguration | undefined {\n\tif (!tools?.length || toolChoice === \"none\") return undefined;\n\n\tconst bedrockTools: BedrockTool[] = tools.map((tool) => ({\n\t\ttoolSpec: {\n\t\t\tname: tool.name,\n\t\t\tdescription: tool.description,\n\t\t\tinputSchema: { json: tool.parameters },\n\t\t},\n\t}));\n\n\tlet bedrockToolChoice: ToolChoice | undefined;\n\tswitch (toolChoice) {\n\t\tcase \"auto\":\n\t\t\tbedrockToolChoice = { auto: {} };\n\t\t\tbreak;\n\t\tcase \"any\":\n\t\t\tbedrockToolChoice = { any: {} };\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (toolChoice?.type === \"tool\") {\n\t\t\t\tbedrockToolChoice = { tool: { name: toolChoice.name } };\n\t\t\t}\n\t}\n\n\treturn { tools: bedrockTools, toolChoice: bedrockToolChoice };\n}\n\nfunction mapStopReason(reason: string | undefined): StopReason {\n\tswitch (reason) {\n\t\tcase BedrockStopReason.END_TURN:\n\t\tcase BedrockStopReason.STOP_SEQUENCE:\n\t\t\treturn \"stop\";\n\t\tcase BedrockStopReason.MAX_TOKENS:\n\t\tcase BedrockStopReason.MODEL_CONTEXT_WINDOW_EXCEEDED:\n\t\t\treturn \"length\";\n\t\tcase BedrockStopReason.TOOL_USE:\n\t\t\treturn \"toolUse\";\n\t\tdefault:\n\t\t\treturn \"error\";\n\t}\n}\n\nfunction buildAdditionalModelRequestFields(\n\tmodel: Model<\"bedrock-converse-stream\">,\n\toptions: BedrockOptions,\n): Record<string, any> | undefined {\n\tif (!options.reasoning || !model.reasoning) {\n\t\treturn undefined;\n\t}\n\n\tif (model.id.includes(\"anthropic.claude\") || model.id.includes(\"anthropic/claude\")) {\n\t\tconst result: Record<string, any> = supportsAdaptiveThinking(model.id)\n\t\t\t? {\n\t\t\t\t\tthinking: { type: \"adaptive\" },\n\t\t\t\t\toutput_config: { effort: mapThinkingLevelToEffort(options.reasoning, model.id) },\n\t\t\t\t}\n\t\t\t: (() => {\n\t\t\t\t\tconst defaultBudgets: Record<ThinkingLevel, number> = {\n\t\t\t\t\t\tminimal: 1024,\n\t\t\t\t\t\tlow: 2048,\n\t\t\t\t\t\tmedium: 8192,\n\t\t\t\t\t\thigh: 16384,\n\t\t\t\t\t\txhigh: 16384, // Claude doesn't support xhigh, clamp to high\n\t\t\t\t\t};\n\n\t\t\t\t\t// Custom budgets override defaults (xhigh not in ThinkingBudgets, use high)\n\t\t\t\t\tconst level = options.reasoning === \"xhigh\" ? \"high\" : options.reasoning;\n\t\t\t\t\tconst budget = options.thinkingBudgets?.[level] ?? defaultBudgets[options.reasoning];\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tthinking: {\n\t\t\t\t\t\t\ttype: \"enabled\",\n\t\t\t\t\t\t\tbudget_tokens: budget,\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t})();\n\n\t\tif (!supportsAdaptiveThinking(model.id) && (options.interleavedThinking ?? true)) {\n\t\t\tresult.anthropic_beta = [\"interleaved-thinking-2025-05-14\"];\n\t\t}\n\n\t\treturn result;\n\t}\n\n\treturn undefined;\n}\n\nfunction createImageBlock(mimeType: string, data: string) {\n\tlet format: ImageFormat;\n\tswitch (mimeType) {\n\t\tcase \"image/jpeg\":\n\t\tcase \"image/jpg\":\n\t\t\tformat = ImageFormat.JPEG;\n\t\t\tbreak;\n\t\tcase \"image/png\":\n\t\t\tformat = ImageFormat.PNG;\n\t\t\tbreak;\n\t\tcase \"image/gif\":\n\t\t\tformat = ImageFormat.GIF;\n\t\t\tbreak;\n\t\tcase \"image/webp\":\n\t\t\tformat = ImageFormat.WEBP;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow new Error(`Unknown image type: ${mimeType}`);\n\t}\n\n\tconst binaryString = atob(data);\n\tconst bytes = new Uint8Array(binaryString.length);\n\tfor (let i = 0; i < binaryString.length; i++) {\n\t\tbytes[i] = binaryString.charCodeAt(i);\n\t}\n\n\treturn { source: { bytes }, format };\n}\n"]}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { SimpleStreamOptions, StreamFunction, StreamOptions } from "../types.js";
|
|
2
|
+
export type AnthropicEffort = "low" | "medium" | "high" | "max";
|
|
3
|
+
export interface AnthropicOptions extends StreamOptions {
|
|
4
|
+
/**
|
|
5
|
+
* Enable extended thinking.
|
|
6
|
+
* For Opus 4.6 and Sonnet 4.6: uses adaptive thinking (model decides when/how much to think).
|
|
7
|
+
* For older models: uses budget-based thinking with thinkingBudgetTokens.
|
|
8
|
+
*/
|
|
9
|
+
thinkingEnabled?: boolean;
|
|
10
|
+
/**
|
|
11
|
+
* Token budget for extended thinking (older models only).
|
|
12
|
+
* Ignored for Opus 4.6 and Sonnet 4.6, which use adaptive thinking.
|
|
13
|
+
*/
|
|
14
|
+
thinkingBudgetTokens?: number;
|
|
15
|
+
/**
|
|
16
|
+
* Effort level for adaptive thinking (Opus 4.6 and Sonnet 4.6).
|
|
17
|
+
* Controls how much thinking Claude allocates:
|
|
18
|
+
* - "max": Always thinks with no constraints (Opus 4.6 only)
|
|
19
|
+
* - "high": Always thinks, deep reasoning (default)
|
|
20
|
+
* - "medium": Moderate thinking, may skip for simple queries
|
|
21
|
+
* - "low": Minimal thinking, skips for simple tasks
|
|
22
|
+
* Ignored for older models.
|
|
23
|
+
*/
|
|
24
|
+
effort?: AnthropicEffort;
|
|
25
|
+
interleavedThinking?: boolean;
|
|
26
|
+
toolChoice?: "auto" | "any" | "none" | {
|
|
27
|
+
type: "tool";
|
|
28
|
+
name: string;
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
export declare const streamAnthropic: StreamFunction<"anthropic-messages", AnthropicOptions>;
|
|
32
|
+
export declare const streamSimpleAnthropic: StreamFunction<"anthropic-messages", SimpleStreamOptions>;
|
|
33
|
+
//# sourceMappingURL=anthropic.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"anthropic.d.ts","sourceRoot":"","sources":["../../src/providers/anthropic.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAQX,mBAAmB,EAEnB,cAAc,EACd,aAAa,EAMb,MAAM,aAAa,CAAC;AAiIrB,MAAM,MAAM,eAAe,GAAG,KAAK,GAAG,QAAQ,GAAG,MAAM,GAAG,KAAK,CAAC;AAEhE,MAAM,WAAW,gBAAiB,SAAQ,aAAa;IACtD;;;;OAIG;IACH,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B;;;OAGG;IACH,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B;;;;;;;;OAQG;IACH,MAAM,CAAC,EAAE,eAAe,CAAC;IACzB,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B,UAAU,CAAC,EAAE,MAAM,GAAG,KAAK,GAAG,MAAM,GAAG;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC;CACtE;AAYD,eAAO,MAAM,eAAe,EAAE,cAAc,CAAC,oBAAoB,EAAE,gBAAgB,CAoOlF,CAAC;AAoCF,eAAO,MAAM,qBAAqB,EAAE,cAAc,CAAC,oBAAoB,EAAE,mBAAmB,CAuC3F,CAAC","sourcesContent":["import Anthropic from \"@anthropic-ai/sdk\";\nimport type {\n\tContentBlockParam,\n\tMessageCreateParamsStreaming,\n\tMessageParam,\n} from \"@anthropic-ai/sdk/resources/messages.js\";\nimport { getEnvApiKey } from \"../env-api-keys.js\";\nimport { calculateCost } from \"../models.js\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tCacheRetention,\n\tContext,\n\tImageContent,\n\tMessage,\n\tModel,\n\tSimpleStreamOptions,\n\tStopReason,\n\tStreamFunction,\n\tStreamOptions,\n\tTextContent,\n\tThinkingContent,\n\tTool,\n\tToolCall,\n\tToolResultMessage,\n} from \"../types.js\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.js\";\nimport { parseStreamingJson } from \"../utils/json-parse.js\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.js\";\n\nimport { buildCopilotDynamicHeaders, hasCopilotVisionInput } from \"./github-copilot-headers.js\";\nimport { adjustMaxTokensForThinking, buildBaseOptions } from \"./simple-options.js\";\nimport { transformMessages } from \"./transform-messages.js\";\n\n/**\n * Resolve cache retention preference.\n * Defaults to \"short\" and uses DRAHT_CACHE_RETENTION for backward compatibility.\n */\nfunction resolveCacheRetention(cacheRetention?: CacheRetention): CacheRetention {\n\tif (cacheRetention) {\n\t\treturn cacheRetention;\n\t}\n\tif (typeof process !== \"undefined\" && process.env.DRAHT_CACHE_RETENTION === \"long\") {\n\t\treturn \"long\";\n\t}\n\treturn \"short\";\n}\n\nfunction getCacheControl(\n\tbaseUrl: string,\n\tcacheRetention?: CacheRetention,\n): { retention: CacheRetention; cacheControl?: { type: \"ephemeral\"; ttl?: \"1h\" } } {\n\tconst retention = resolveCacheRetention(cacheRetention);\n\tif (retention === \"none\") {\n\t\treturn { retention };\n\t}\n\tconst ttl = retention === \"long\" && baseUrl.includes(\"api.anthropic.com\") ? \"1h\" : undefined;\n\treturn {\n\t\tretention,\n\t\tcacheControl: { type: \"ephemeral\", ...(ttl && { ttl }) },\n\t};\n}\n\n// Stealth mode: Mimic Claude Code's tool naming exactly\nconst claudeCodeVersion = \"2.1.62\";\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 */\nfunction convertContentBlocks(content: (TextContent | ImageContent)[]):\n\t| string\n\t| Array<\n\t\t\t| { type: \"text\"; text: string }\n\t\t\t| {\n\t\t\t\t\ttype: \"image\";\n\t\t\t\t\tsource: {\n\t\t\t\t\t\ttype: \"base64\";\n\t\t\t\t\t\tmedia_type: \"image/jpeg\" | \"image/png\" | \"image/gif\" | \"image/webp\";\n\t\t\t\t\t\tdata: string;\n\t\t\t\t\t};\n\t\t\t }\n\t > {\n\t// If only text blocks, return as concatenated string for simplicity\n\tconst hasImages = content.some((c) => c.type === \"image\");\n\tif (!hasImages) {\n\t\treturn sanitizeSurrogates(content.map((c) => (c as TextContent).text).join(\"\\n\"));\n\t}\n\n\t// If we have images, convert to content block array\n\tconst blocks = content.map((block) => {\n\t\tif (block.type === \"text\") {\n\t\t\treturn {\n\t\t\t\ttype: \"text\" as const,\n\t\t\t\ttext: sanitizeSurrogates(block.text),\n\t\t\t};\n\t\t}\n\t\treturn {\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 images (no text), add placeholder text block\n\tconst hasText = blocks.some((b) => b.type === \"text\");\n\tif (!hasText) {\n\t\tblocks.unshift({\n\t\t\ttype: \"text\" as const,\n\t\t\ttext: \"(see attached image)\",\n\t\t});\n\t}\n\n\treturn blocks;\n}\n\nexport type AnthropicEffort = \"low\" | \"medium\" | \"high\" | \"max\";\n\nexport interface AnthropicOptions extends StreamOptions {\n\t/**\n\t * Enable extended thinking.\n\t * For Opus 4.6 and Sonnet 4.6: uses adaptive thinking (model decides when/how much to think).\n\t * For older models: uses budget-based thinking with thinkingBudgetTokens.\n\t */\n\tthinkingEnabled?: boolean;\n\t/**\n\t * Token budget for extended thinking (older models only).\n\t * Ignored for Opus 4.6 and Sonnet 4.6, which use adaptive thinking.\n\t */\n\tthinkingBudgetTokens?: number;\n\t/**\n\t * Effort level for adaptive thinking (Opus 4.6 and Sonnet 4.6).\n\t * Controls how much thinking Claude allocates:\n\t * - \"max\": Always thinks with no constraints (Opus 4.6 only)\n\t * - \"high\": Always thinks, deep reasoning (default)\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 */\n\teffort?: AnthropicEffort;\n\tinterleavedThinking?: boolean;\n\ttoolChoice?: \"auto\" | \"any\" | \"none\" | { type: \"tool\"; name: string };\n}\n\nfunction mergeHeaders(...headerSources: (Record<string, string> | undefined)[]): Record<string, string> {\n\tconst merged: Record<string, string> = {};\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\nexport const streamAnthropic: 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\ttry {\n\t\t\tconst apiKey = options?.apiKey ?? getEnvApiKey(model.provider) ?? \"\";\n\n\t\t\tlet copilotDynamicHeaders: Record<string, string> | undefined;\n\t\t\tif (model.provider === \"github-copilot\") {\n\t\t\t\tconst hasImages = hasCopilotVisionInput(context.messages);\n\t\t\t\tcopilotDynamicHeaders = buildCopilotDynamicHeaders({\n\t\t\t\t\tmessages: context.messages,\n\t\t\t\t\thasImages,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tconst { client, isOAuthToken } = createClient(\n\t\t\t\tmodel,\n\t\t\t\tapiKey,\n\t\t\t\toptions?.interleavedThinking ?? true,\n\t\t\t\toptions?.headers,\n\t\t\t\tcopilotDynamicHeaders,\n\t\t\t);\n\t\t\tconst params = buildParams(model, context, isOAuthToken, options);\n\t\t\toptions?.onPayload?.(params);\n\t\t\tconst anthropicStream = client.messages.stream({ ...params, stream: true }, { signal: options?.signal });\n\t\t\tstream.push({ type: \"start\", partial: output });\n\n\t\t\ttype Block = (ThinkingContent | TextContent | (ToolCall & { partialJson: string })) & { index: number };\n\t\t\tconst blocks = output.content as Block[];\n\n\t\t\tfor await (const event of anthropicStream) {\n\t\t\t\tif (event.type === \"message_start\") {\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\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} else if (event.type === \"content_block_start\") {\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: isOAuthToken\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: (event.content_block.input as Record<string, any>) ?? {},\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}\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}\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 as any).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\tdelete (block as any).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}\n\t\t\t\t\t}\n\t\t\t\t} else if (event.type === \"message_delta\") {\n\t\t\t\t\tif (event.delta.stop_reason) {\n\t\t\t\t\t\toutput.stopReason = mapStopReason(event.delta.stop_reason);\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.input_tokens != null) {\n\t\t\t\t\t\toutput.usage.input = event.usage.input_tokens;\n\t\t\t\t\t}\n\t\t\t\t\tif (event.usage.output_tokens != null) {\n\t\t\t\t\t\toutput.usage.output = event.usage.output_tokens;\n\t\t\t\t\t}\n\t\t\t\t\tif (event.usage.cache_read_input_tokens != null) {\n\t\t\t\t\t\toutput.usage.cacheRead = event.usage.cache_read_input_tokens;\n\t\t\t\t\t}\n\t\t\t\t\tif (event.usage.cache_creation_input_tokens != null) {\n\t\t\t\t\t\toutput.usage.cacheWrite = event.usage.cache_creation_input_tokens;\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 (output.stopReason === \"aborted\" || output.stopReason === \"error\") {\n\t\t\t\tthrow new Error(\"An unknown error occurred\");\n\t\t\t}\n\n\t\t\tstream.push({ type: \"done\", reason: output.stopReason, message: output });\n\t\t\tstream.end();\n\t\t} catch (error) {\n\t\t\tfor (const block of output.content) delete (block as any).index;\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 * Check if a model supports adaptive thinking (Opus 4.6 and Sonnet 4.6)\n */\nfunction supportsAdaptiveThinking(modelId: string): boolean {\n\t// Opus 4.6 and Sonnet 4.6 model IDs (with or without date suffix)\n\treturn (\n\t\tmodelId.includes(\"opus-4-6\") ||\n\t\tmodelId.includes(\"opus-4.6\") ||\n\t\tmodelId.includes(\"sonnet-4-6\") ||\n\t\tmodelId.includes(\"sonnet-4.6\")\n\t);\n}\n\n/**\n * Map ThinkingLevel to Anthropic effort levels for adaptive thinking.\n * Note: effort \"max\" is only valid on Opus 4.6.\n */\nfunction mapThinkingLevelToEffort(level: SimpleStreamOptions[\"reasoning\"], modelId: string): AnthropicEffort {\n\tswitch (level) {\n\t\tcase \"minimal\":\n\t\t\treturn \"low\";\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\treturn modelId.includes(\"opus-4-6\") || modelId.includes(\"opus-4.6\") ? \"max\" : \"high\";\n\t\tdefault:\n\t\t\treturn \"high\";\n\t}\n}\n\nexport const streamSimpleAnthropic: StreamFunction<\"anthropic-messages\", SimpleStreamOptions> = (\n\tmodel: Model<\"anthropic-messages\">,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): AssistantMessageEventStream => {\n\tconst apiKey = options?.apiKey || getEnvApiKey(model.provider);\n\tif (!apiKey) {\n\t\tthrow new Error(`No API key for provider: ${model.provider}`);\n\t}\n\n\tconst base = buildBaseOptions(model, options, apiKey);\n\tif (!options?.reasoning) {\n\t\treturn streamAnthropic(model, context, { ...base, thinkingEnabled: false } satisfies AnthropicOptions);\n\t}\n\n\t// For Opus 4.6 and Sonnet 4.6: use adaptive thinking with effort level\n\t// For older models: use budget-based thinking\n\tif (supportsAdaptiveThinking(model.id)) {\n\t\tconst effort = mapThinkingLevelToEffort(options.reasoning, model.id);\n\t\treturn streamAnthropic(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\tconst adjusted = adjustMaxTokensForThinking(\n\t\tbase.maxTokens || 0,\n\t\tmodel.maxTokens,\n\t\toptions.reasoning,\n\t\toptions.thinkingBudgets,\n\t);\n\n\treturn streamAnthropic(model, context, {\n\t\t...base,\n\t\tmaxTokens: adjusted.maxTokens,\n\t\tthinkingEnabled: true,\n\t\tthinkingBudgetTokens: adjusted.thinkingBudget,\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,\n\tinterleavedThinking: boolean,\n\toptionsHeaders?: Record<string, string>,\n\tdynamicHeaders?: Record<string, string>,\n): { client: Anthropic; isOAuthToken: boolean } {\n\t// Adaptive thinking models (Opus 4.6, Sonnet 4.6) have interleaved thinking built-in.\n\t// The beta header is deprecated on Opus 4.6 and redundant on Sonnet 4.6, so skip it.\n\tconst needsInterleavedBeta = interleavedThinking && !supportsAdaptiveThinking(model.id);\n\n\t// Copilot: Bearer auth, selective betas (no fine-grained-tool-streaming)\n\tif (model.provider === \"github-copilot\") {\n\t\tconst betaFeatures: string[] = [];\n\t\tif (needsInterleavedBeta) {\n\t\t\tbetaFeatures.push(\"interleaved-thinking-2025-05-14\");\n\t\t}\n\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: mergeHeaders(\n\t\t\t\t{\n\t\t\t\t\taccept: \"application/json\",\n\t\t\t\t\t\"anthropic-dangerous-direct-browser-access\": \"true\",\n\t\t\t\t\t...(betaFeatures.length > 0 ? { \"anthropic-beta\": betaFeatures.join(\",\") } : {}),\n\t\t\t\t},\n\t\t\t\tmodel.headers,\n\t\t\t\tdynamicHeaders,\n\t\t\t\toptionsHeaders,\n\t\t\t),\n\t\t});\n\n\t\treturn { client, isOAuthToken: false };\n\t}\n\n\tconst betaFeatures = [\"fine-grained-tool-streaming-2025-05-14\"];\n\tif (needsInterleavedBeta) {\n\t\tbetaFeatures.push(\"interleaved-thinking-2025-05-14\");\n\t}\n\n\t// OAuth: Bearer auth, Claude Code identity headers\n\tif (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: mergeHeaders(\n\t\t\t\t{\n\t\t\t\t\taccept: \"application/json\",\n\t\t\t\t\t\"anthropic-dangerous-direct-browser-access\": \"true\",\n\t\t\t\t\t\"anthropic-beta\": `claude-code-20250219,oauth-2025-04-20,${betaFeatures.join(\",\")}`,\n\t\t\t\t\t\"user-agent\": `claude-cli/${claudeCodeVersion}`,\n\t\t\t\t\t\"x-app\": \"cli\",\n\t\t\t\t},\n\t\t\t\tmodel.headers,\n\t\t\t\toptionsHeaders,\n\t\t\t),\n\t\t});\n\n\t\treturn { client, isOAuthToken: true };\n\t}\n\n\t// API key auth\n\tconst client = new Anthropic({\n\t\tapiKey,\n\t\tbaseURL: model.baseUrl,\n\t\tdangerouslyAllowBrowser: true,\n\t\tdefaultHeaders: mergeHeaders(\n\t\t\t{\n\t\t\t\taccept: \"application/json\",\n\t\t\t\t\"anthropic-dangerous-direct-browser-access\": \"true\",\n\t\t\t\t\"anthropic-beta\": betaFeatures.join(\",\"),\n\t\t\t},\n\t\t\tmodel.headers,\n\t\t\toptionsHeaders,\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): MessageCreateParamsStreaming {\n\tconst { cacheControl } = getCacheControl(model.baseUrl, options?.cacheRetention);\n\tconst params: MessageCreateParamsStreaming = {\n\t\tmodel: model.id,\n\t\tmessages: convertMessages(context.messages, model, isOAuthToken, cacheControl),\n\t\tmax_tokens: options?.maxTokens || (model.maxTokens / 3) | 0,\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 (adaptive or budget-based).\n\tif (options?.temperature !== undefined && !options?.thinkingEnabled) {\n\t\tparams.temperature = options.temperature;\n\t}\n\n\tif (context.tools) {\n\t\tparams.tools = convertTools(context.tools, isOAuthToken);\n\t}\n\n\t// Configure thinking mode: adaptive (Opus 4.6 and Sonnet 4.6) or budget-based (older models)\n\tif (options?.thinkingEnabled && model.reasoning) {\n\t\tif (supportsAdaptiveThinking(model.id)) {\n\t\t\t// Adaptive thinking: Claude decides when and how much to think\n\t\t\tparams.thinking = { type: \"adaptive\" };\n\t\t\tif (options.effort) {\n\t\t\t\tparams.output_config = { effort: options.effort };\n\t\t\t}\n\t\t} else {\n\t\t\t// Budget-based thinking for older models\n\t\t\tparams.thinking = {\n\t\t\t\ttype: \"enabled\",\n\t\t\t\tbudget_tokens: options.thinkingBudgetTokens || 1024,\n\t\t\t};\n\t\t}\n\t}\n\n\tif (options?.metadata) {\n\t\tconst userId = options.metadata.user_id;\n\t\tif (typeof userId === \"string\") {\n\t\t\tparams.metadata = { user_id: userId };\n\t\t}\n\t}\n\n\tif (options?.toolChoice) {\n\t\tif (typeof options.toolChoice === \"string\") {\n\t\t\tparams.tool_choice = { type: options.toolChoice };\n\t\t} else {\n\t\t\tparams.tool_choice = options.toolChoice;\n\t\t}\n\t}\n\n\treturn params;\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 convertMessages(\n\tmessages: Message[],\n\tmodel: Model<\"anthropic-messages\">,\n\tisOAuthToken: boolean,\n\tcacheControl?: { type: \"ephemeral\"; ttl?: \"1h\" },\n): MessageParam[] {\n\tconst params: MessageParam[] = [];\n\n\t// Transform messages for cross-provider compatibility\n\tconst transformedMessages = transformMessages(messages, model, normalizeToolCallId);\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 {\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\tlet filteredBlocks = !model?.input.includes(\"image\") ? blocks.filter((b) => b.type !== \"image\") : blocks;\n\t\t\t\tfilteredBlocks = filteredBlocks.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\n\t\t\tfor (const block of msg.content) {\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\tif (block.thinking.trim().length === 0) 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 block without <thinking> tags to avoid API rejection\n\t\t\t\t\t// and prevent Claude from mimicking the tags in responses\n\t\t\t\t\tif (!block.thinkingSignature || block.thinkingSignature.trim().length === 0) {\n\t\t\t\t\t\tblocks.push({\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: sanitizeSurrogates(block.thinking),\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: sanitizeSurrogates(block.thinking),\n\t\t\t\t\t\t\tsignature: block.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}\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\n\t\t\t// Add the current tool result\n\t\t\ttoolResults.push({\n\t\t\t\ttype: \"tool_result\",\n\t\t\t\ttool_use_id: msg.toolCallId,\n\t\t\t\tcontent: convertContentBlocks(msg.content),\n\t\t\t\tis_error: msg.isError,\n\t\t\t});\n\n\t\t\t// Look ahead for consecutive toolResult messages\n\t\t\tlet j = i + 1;\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\ttoolResults.push({\n\t\t\t\t\ttype: \"tool_result\",\n\t\t\t\t\ttool_use_id: nextMsg.toolCallId,\n\t\t\t\t\tcontent: convertContentBlocks(nextMsg.content),\n\t\t\t\t\tis_error: nextMsg.isError,\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// Add a single user message with all tool results\n\t\t\tparams.push({\n\t\t\t\trole: \"user\",\n\t\t\t\tcontent: toolResults,\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 (\n\t\t\t\t\tlastBlock &&\n\t\t\t\t\t(lastBlock.type === \"text\" || lastBlock.type === \"image\" || lastBlock.type === \"tool_result\")\n\t\t\t\t) {\n\t\t\t\t\t(lastBlock as any).cache_control = cacheControl;\n\t\t\t\t}\n\t\t\t} else if (typeof lastMessage.content === \"string\") {\n\t\t\t\tlastMessage.content = [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: lastMessage.content,\n\t\t\t\t\t\tcache_control: cacheControl,\n\t\t\t\t\t},\n\t\t\t\t] as any;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn params;\n}\n\nfunction convertTools(tools: Tool[], isOAuthToken: boolean): Anthropic.Messages.Tool[] {\n\tif (!tools) return [];\n\n\treturn tools.map((tool) => {\n\t\tconst jsonSchema = tool.parameters as any; // TypeBox already generates JSON Schema\n\n\t\treturn {\n\t\t\tname: isOAuthToken ? toClaudeCodeName(tool.name) : tool.name,\n\t\t\tdescription: tool.description,\n\t\t\tinput_schema: {\n\t\t\t\ttype: \"object\" as const,\n\t\t\t\tproperties: jsonSchema.properties || {},\n\t\t\t\trequired: jsonSchema.required || [],\n\t\t\t},\n\t\t};\n\t});\n}\n\nfunction mapStopReason(reason: Anthropic.Messages.StopReason | string): StopReason {\n\tswitch (reason) {\n\t\tcase \"end_turn\":\n\t\t\treturn \"stop\";\n\t\tcase \"max_tokens\":\n\t\t\treturn \"length\";\n\t\tcase \"tool_use\":\n\t\t\treturn \"toolUse\";\n\t\tcase \"refusal\":\n\t\t\treturn \"error\";\n\t\tcase \"pause_turn\": // Stop is good enough -> resubmit\n\t\t\treturn \"stop\";\n\t\tcase \"stop_sequence\":\n\t\t\treturn \"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 \"error\";\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"]}
|