@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":"anthropic.js","sourceRoot":"","sources":["../../src/providers/anthropic.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,MAAM,mBAAmB,CAAC;AAM1C,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAmB7C,OAAO,EAAE,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;AACvE,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAC5D,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O;YACN,IAAI,EAAE,YAAY,CAAC,CAAC,CAAC,gBAAgB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI;YAC5D,WAAW,EAAE,IAAI,CAAC,WAAW;YAC7B,YAAY,EAAE;gBACb,IAAI,EAAE,QAAiB;gBACvB,UAAU,EAAE,UAAU,CAAC,UAAU,IAAI,EAAE;gBACvC,QAAQ,EAAE,UAAU,CAAC,QAAQ,IAAI,EAAE;aACnC;SACD,CAAC;IAAA,CACF,CAAC,CAAC;AAAA,CACH;AAED,SAAS,aAAa,CAAC,MAA8C,EAAc;IAClF,QAAQ,MAAM,EAAE,CAAC;QAChB,KAAK,UAAU;YACd,OAAO,MAAM,CAAC;QACf,KAAK,YAAY;YAChB,OAAO,QAAQ,CAAC;QACjB,KAAK,UAAU;YACd,OAAO,SAAS,CAAC;QAClB,KAAK,SAAS;YACb,OAAO,OAAO,CAAC;QAChB,KAAK,YAAY,EAAE,kCAAkC;YACpD,OAAO,MAAM,CAAC;QACf,KAAK,eAAe;YACnB,OAAO,MAAM,CAAC,CAAC,8DAA8D;QAC9E,KAAK,WAAW,EAAE,2DAA2D;YAC5E,OAAO,OAAO,CAAC;QAChB;YACC,kEAAkE;YAClE,MAAM,IAAI,KAAK,CAAC,0BAA0B,MAAM,EAAE,CAAC,CAAC;IACtD,CAAC;AAAA,CACD","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"]}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { SimpleStreamOptions, StreamFunction, StreamOptions } from "../types.js";
|
|
2
|
+
export interface AzureOpenAIResponsesOptions extends StreamOptions {
|
|
3
|
+
reasoningEffort?: "minimal" | "low" | "medium" | "high" | "xhigh";
|
|
4
|
+
reasoningSummary?: "auto" | "detailed" | "concise" | null;
|
|
5
|
+
azureApiVersion?: string;
|
|
6
|
+
azureResourceName?: string;
|
|
7
|
+
azureBaseUrl?: string;
|
|
8
|
+
azureDeploymentName?: string;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Generate function for Azure OpenAI Responses API
|
|
12
|
+
*/
|
|
13
|
+
export declare const streamAzureOpenAIResponses: StreamFunction<"azure-openai-responses", AzureOpenAIResponsesOptions>;
|
|
14
|
+
export declare const streamSimpleAzureOpenAIResponses: StreamFunction<"azure-openai-responses", SimpleStreamOptions>;
|
|
15
|
+
//# sourceMappingURL=azure-openai-responses.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"azure-openai-responses.d.ts","sourceRoot":"","sources":["../../src/providers/azure-openai-responses.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAKX,mBAAmB,EACnB,cAAc,EACd,aAAa,EACb,MAAM,aAAa,CAAC;AA8BrB,MAAM,WAAW,2BAA4B,SAAQ,aAAa;IACjE,eAAe,CAAC,EAAE,SAAS,GAAG,KAAK,GAAG,QAAQ,GAAG,MAAM,GAAG,OAAO,CAAC;IAClE,gBAAgB,CAAC,EAAE,MAAM,GAAG,UAAU,GAAG,SAAS,GAAG,IAAI,CAAC;IAC1D,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,mBAAmB,CAAC,EAAE,MAAM,CAAC;CAC7B;AAED;;GAEG;AACH,eAAO,MAAM,0BAA0B,EAAE,cAAc,CAAC,wBAAwB,EAAE,2BAA2B,CA+D5G,CAAC;AAEF,eAAO,MAAM,gCAAgC,EAAE,cAAc,CAAC,wBAAwB,EAAE,mBAAmB,CAiB1G,CAAC","sourcesContent":["import { AzureOpenAI } from \"openai\";\nimport type { ResponseCreateParamsStreaming } from \"openai/resources/responses/responses.js\";\nimport { getEnvApiKey } from \"../env-api-keys.js\";\nimport { supportsXhigh } from \"../models.js\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tContext,\n\tModel,\n\tSimpleStreamOptions,\n\tStreamFunction,\n\tStreamOptions,\n} from \"../types.js\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.js\";\nimport { convertResponsesMessages, convertResponsesTools, processResponsesStream } from \"./openai-responses-shared.js\";\nimport { buildBaseOptions, clampReasoning } from \"./simple-options.js\";\n\nconst DEFAULT_AZURE_API_VERSION = \"v1\";\nconst AZURE_TOOL_CALL_PROVIDERS = new Set([\"openai\", \"openai-codex\", \"opencode\", \"azure-openai-responses\"]);\n\nfunction parseDeploymentNameMap(value: string | undefined): Map<string, string> {\n\tconst map = new Map<string, string>();\n\tif (!value) return map;\n\tfor (const entry of value.split(\",\")) {\n\t\tconst trimmed = entry.trim();\n\t\tif (!trimmed) continue;\n\t\tconst [modelId, deploymentName] = trimmed.split(\"=\", 2);\n\t\tif (!modelId || !deploymentName) continue;\n\t\tmap.set(modelId.trim(), deploymentName.trim());\n\t}\n\treturn map;\n}\n\nfunction resolveDeploymentName(model: Model<\"azure-openai-responses\">, options?: AzureOpenAIResponsesOptions): string {\n\tif (options?.azureDeploymentName) {\n\t\treturn options.azureDeploymentName;\n\t}\n\tconst mappedDeployment = parseDeploymentNameMap(process.env.AZURE_OPENAI_DEPLOYMENT_NAME_MAP).get(model.id);\n\treturn mappedDeployment || model.id;\n}\n\n// Azure OpenAI Responses-specific options\nexport interface AzureOpenAIResponsesOptions extends StreamOptions {\n\treasoningEffort?: \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\";\n\treasoningSummary?: \"auto\" | \"detailed\" | \"concise\" | null;\n\tazureApiVersion?: string;\n\tazureResourceName?: string;\n\tazureBaseUrl?: string;\n\tazureDeploymentName?: string;\n}\n\n/**\n * Generate function for Azure OpenAI Responses API\n */\nexport const streamAzureOpenAIResponses: StreamFunction<\"azure-openai-responses\", AzureOpenAIResponsesOptions> = (\n\tmodel: Model<\"azure-openai-responses\">,\n\tcontext: Context,\n\toptions?: AzureOpenAIResponsesOptions,\n): AssistantMessageEventStream => {\n\tconst stream = new AssistantMessageEventStream();\n\n\t// Start async processing\n\t(async () => {\n\t\tconst deploymentName = resolveDeploymentName(model, options);\n\n\t\tconst output: AssistantMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [],\n\t\t\tapi: \"azure-openai-responses\" 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\t// Create Azure OpenAI client\n\t\t\tconst apiKey = options?.apiKey || getEnvApiKey(model.provider) || \"\";\n\t\t\tconst client = createClient(model, apiKey, options);\n\t\t\tconst params = buildParams(model, context, options, deploymentName);\n\t\t\toptions?.onPayload?.(params);\n\t\t\tconst openaiStream = await client.responses.create(\n\t\t\t\tparams,\n\t\t\t\toptions?.signal ? { signal: options.signal } : undefined,\n\t\t\t);\n\t\t\tstream.push({ type: \"start\", partial: output });\n\n\t\t\tawait processResponsesStream(openaiStream, output, stream, model);\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 { index?: number }).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\nexport const streamSimpleAzureOpenAIResponses: StreamFunction<\"azure-openai-responses\", SimpleStreamOptions> = (\n\tmodel: Model<\"azure-openai-responses\">,\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\tconst reasoningEffort = supportsXhigh(model) ? options?.reasoning : clampReasoning(options?.reasoning);\n\n\treturn streamAzureOpenAIResponses(model, context, {\n\t\t...base,\n\t\treasoningEffort,\n\t} satisfies AzureOpenAIResponsesOptions);\n};\n\nfunction normalizeAzureBaseUrl(baseUrl: string): string {\n\treturn baseUrl.replace(/\\/+$/, \"\");\n}\n\nfunction buildDefaultBaseUrl(resourceName: string): string {\n\treturn `https://${resourceName}.openai.azure.com/openai/v1`;\n}\n\nfunction resolveAzureConfig(\n\tmodel: Model<\"azure-openai-responses\">,\n\toptions?: AzureOpenAIResponsesOptions,\n): { baseUrl: string; apiVersion: string } {\n\tconst apiVersion = options?.azureApiVersion || process.env.AZURE_OPENAI_API_VERSION || DEFAULT_AZURE_API_VERSION;\n\n\tconst baseUrl = options?.azureBaseUrl?.trim() || process.env.AZURE_OPENAI_BASE_URL?.trim() || undefined;\n\tconst resourceName = options?.azureResourceName || process.env.AZURE_OPENAI_RESOURCE_NAME;\n\n\tlet resolvedBaseUrl = baseUrl;\n\n\tif (!resolvedBaseUrl && resourceName) {\n\t\tresolvedBaseUrl = buildDefaultBaseUrl(resourceName);\n\t}\n\n\tif (!resolvedBaseUrl && model.baseUrl) {\n\t\tresolvedBaseUrl = model.baseUrl;\n\t}\n\n\tif (!resolvedBaseUrl) {\n\t\tthrow new Error(\n\t\t\t\"Azure OpenAI base URL is required. Set AZURE_OPENAI_BASE_URL or AZURE_OPENAI_RESOURCE_NAME, or pass azureBaseUrl, azureResourceName, or model.baseUrl.\",\n\t\t);\n\t}\n\n\treturn {\n\t\tbaseUrl: normalizeAzureBaseUrl(resolvedBaseUrl),\n\t\tapiVersion,\n\t};\n}\n\nfunction createClient(model: Model<\"azure-openai-responses\">, apiKey: string, options?: AzureOpenAIResponsesOptions) {\n\tif (!apiKey) {\n\t\tif (!process.env.AZURE_OPENAI_API_KEY) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Azure OpenAI API key is required. Set AZURE_OPENAI_API_KEY environment variable or pass it as an argument.\",\n\t\t\t);\n\t\t}\n\t\tapiKey = process.env.AZURE_OPENAI_API_KEY;\n\t}\n\n\tconst headers = { ...model.headers };\n\n\tif (options?.headers) {\n\t\tObject.assign(headers, options.headers);\n\t}\n\n\tconst { baseUrl, apiVersion } = resolveAzureConfig(model, options);\n\n\treturn new AzureOpenAI({\n\t\tapiKey,\n\t\tapiVersion,\n\t\tdangerouslyAllowBrowser: true,\n\t\tdefaultHeaders: headers,\n\t\tbaseURL: baseUrl,\n\t});\n}\n\nfunction buildParams(\n\tmodel: Model<\"azure-openai-responses\">,\n\tcontext: Context,\n\toptions: AzureOpenAIResponsesOptions | undefined,\n\tdeploymentName: string,\n) {\n\tconst messages = convertResponsesMessages(model, context, AZURE_TOOL_CALL_PROVIDERS);\n\n\tconst params: ResponseCreateParamsStreaming = {\n\t\tmodel: deploymentName,\n\t\tinput: messages,\n\t\tstream: true,\n\t\tprompt_cache_key: options?.sessionId,\n\t};\n\n\tif (options?.maxTokens) {\n\t\tparams.max_output_tokens = options?.maxTokens;\n\t}\n\n\tif (options?.temperature !== undefined) {\n\t\tparams.temperature = options?.temperature;\n\t}\n\n\tif (context.tools) {\n\t\tparams.tools = convertResponsesTools(context.tools);\n\t}\n\n\tif (model.reasoning) {\n\t\tif (options?.reasoningEffort || options?.reasoningSummary) {\n\t\t\tparams.reasoning = {\n\t\t\t\teffort: options?.reasoningEffort || \"medium\",\n\t\t\t\tsummary: options?.reasoningSummary || \"auto\",\n\t\t\t};\n\t\t\tparams.include = [\"reasoning.encrypted_content\"];\n\t\t} else {\n\t\t\tif (model.name.toLowerCase().startsWith(\"gpt-5\")) {\n\t\t\t\t// Jesus Christ, see https://community.openai.com/t/need-reasoning-false-option-for-gpt-5/1351588/7\n\t\t\t\tmessages.push({\n\t\t\t\t\trole: \"developer\",\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"input_text\",\n\t\t\t\t\t\t\ttext: \"# Juice: 0 !important\",\n\t\t\t\t\t\t},\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"]}
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import { AzureOpenAI } from "openai";
|
|
2
|
+
import { getEnvApiKey } from "../env-api-keys.js";
|
|
3
|
+
import { supportsXhigh } from "../models.js";
|
|
4
|
+
import { AssistantMessageEventStream } from "../utils/event-stream.js";
|
|
5
|
+
import { convertResponsesMessages, convertResponsesTools, processResponsesStream } from "./openai-responses-shared.js";
|
|
6
|
+
import { buildBaseOptions, clampReasoning } from "./simple-options.js";
|
|
7
|
+
const DEFAULT_AZURE_API_VERSION = "v1";
|
|
8
|
+
const AZURE_TOOL_CALL_PROVIDERS = new Set(["openai", "openai-codex", "opencode", "azure-openai-responses"]);
|
|
9
|
+
function parseDeploymentNameMap(value) {
|
|
10
|
+
const map = new Map();
|
|
11
|
+
if (!value)
|
|
12
|
+
return map;
|
|
13
|
+
for (const entry of value.split(",")) {
|
|
14
|
+
const trimmed = entry.trim();
|
|
15
|
+
if (!trimmed)
|
|
16
|
+
continue;
|
|
17
|
+
const [modelId, deploymentName] = trimmed.split("=", 2);
|
|
18
|
+
if (!modelId || !deploymentName)
|
|
19
|
+
continue;
|
|
20
|
+
map.set(modelId.trim(), deploymentName.trim());
|
|
21
|
+
}
|
|
22
|
+
return map;
|
|
23
|
+
}
|
|
24
|
+
function resolveDeploymentName(model, options) {
|
|
25
|
+
if (options?.azureDeploymentName) {
|
|
26
|
+
return options.azureDeploymentName;
|
|
27
|
+
}
|
|
28
|
+
const mappedDeployment = parseDeploymentNameMap(process.env.AZURE_OPENAI_DEPLOYMENT_NAME_MAP).get(model.id);
|
|
29
|
+
return mappedDeployment || model.id;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Generate function for Azure OpenAI Responses API
|
|
33
|
+
*/
|
|
34
|
+
export const streamAzureOpenAIResponses = (model, context, options) => {
|
|
35
|
+
const stream = new AssistantMessageEventStream();
|
|
36
|
+
// Start async processing
|
|
37
|
+
(async () => {
|
|
38
|
+
const deploymentName = resolveDeploymentName(model, options);
|
|
39
|
+
const output = {
|
|
40
|
+
role: "assistant",
|
|
41
|
+
content: [],
|
|
42
|
+
api: "azure-openai-responses",
|
|
43
|
+
provider: model.provider,
|
|
44
|
+
model: model.id,
|
|
45
|
+
usage: {
|
|
46
|
+
input: 0,
|
|
47
|
+
output: 0,
|
|
48
|
+
cacheRead: 0,
|
|
49
|
+
cacheWrite: 0,
|
|
50
|
+
totalTokens: 0,
|
|
51
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
52
|
+
},
|
|
53
|
+
stopReason: "stop",
|
|
54
|
+
timestamp: Date.now(),
|
|
55
|
+
};
|
|
56
|
+
try {
|
|
57
|
+
// Create Azure OpenAI client
|
|
58
|
+
const apiKey = options?.apiKey || getEnvApiKey(model.provider) || "";
|
|
59
|
+
const client = createClient(model, apiKey, options);
|
|
60
|
+
const params = buildParams(model, context, options, deploymentName);
|
|
61
|
+
options?.onPayload?.(params);
|
|
62
|
+
const openaiStream = await client.responses.create(params, options?.signal ? { signal: options.signal } : undefined);
|
|
63
|
+
stream.push({ type: "start", partial: output });
|
|
64
|
+
await processResponsesStream(openaiStream, output, stream, model);
|
|
65
|
+
if (options?.signal?.aborted) {
|
|
66
|
+
throw new Error("Request was aborted");
|
|
67
|
+
}
|
|
68
|
+
if (output.stopReason === "aborted" || output.stopReason === "error") {
|
|
69
|
+
throw new Error("An unknown error occurred");
|
|
70
|
+
}
|
|
71
|
+
stream.push({ type: "done", reason: output.stopReason, message: output });
|
|
72
|
+
stream.end();
|
|
73
|
+
}
|
|
74
|
+
catch (error) {
|
|
75
|
+
for (const block of output.content)
|
|
76
|
+
delete block.index;
|
|
77
|
+
output.stopReason = options?.signal?.aborted ? "aborted" : "error";
|
|
78
|
+
output.errorMessage = error instanceof Error ? error.message : JSON.stringify(error);
|
|
79
|
+
stream.push({ type: "error", reason: output.stopReason, error: output });
|
|
80
|
+
stream.end();
|
|
81
|
+
}
|
|
82
|
+
})();
|
|
83
|
+
return stream;
|
|
84
|
+
};
|
|
85
|
+
export const streamSimpleAzureOpenAIResponses = (model, context, options) => {
|
|
86
|
+
const apiKey = options?.apiKey || getEnvApiKey(model.provider);
|
|
87
|
+
if (!apiKey) {
|
|
88
|
+
throw new Error(`No API key for provider: ${model.provider}`);
|
|
89
|
+
}
|
|
90
|
+
const base = buildBaseOptions(model, options, apiKey);
|
|
91
|
+
const reasoningEffort = supportsXhigh(model) ? options?.reasoning : clampReasoning(options?.reasoning);
|
|
92
|
+
return streamAzureOpenAIResponses(model, context, {
|
|
93
|
+
...base,
|
|
94
|
+
reasoningEffort,
|
|
95
|
+
});
|
|
96
|
+
};
|
|
97
|
+
function normalizeAzureBaseUrl(baseUrl) {
|
|
98
|
+
return baseUrl.replace(/\/+$/, "");
|
|
99
|
+
}
|
|
100
|
+
function buildDefaultBaseUrl(resourceName) {
|
|
101
|
+
return `https://${resourceName}.openai.azure.com/openai/v1`;
|
|
102
|
+
}
|
|
103
|
+
function resolveAzureConfig(model, options) {
|
|
104
|
+
const apiVersion = options?.azureApiVersion || process.env.AZURE_OPENAI_API_VERSION || DEFAULT_AZURE_API_VERSION;
|
|
105
|
+
const baseUrl = options?.azureBaseUrl?.trim() || process.env.AZURE_OPENAI_BASE_URL?.trim() || undefined;
|
|
106
|
+
const resourceName = options?.azureResourceName || process.env.AZURE_OPENAI_RESOURCE_NAME;
|
|
107
|
+
let resolvedBaseUrl = baseUrl;
|
|
108
|
+
if (!resolvedBaseUrl && resourceName) {
|
|
109
|
+
resolvedBaseUrl = buildDefaultBaseUrl(resourceName);
|
|
110
|
+
}
|
|
111
|
+
if (!resolvedBaseUrl && model.baseUrl) {
|
|
112
|
+
resolvedBaseUrl = model.baseUrl;
|
|
113
|
+
}
|
|
114
|
+
if (!resolvedBaseUrl) {
|
|
115
|
+
throw new Error("Azure OpenAI base URL is required. Set AZURE_OPENAI_BASE_URL or AZURE_OPENAI_RESOURCE_NAME, or pass azureBaseUrl, azureResourceName, or model.baseUrl.");
|
|
116
|
+
}
|
|
117
|
+
return {
|
|
118
|
+
baseUrl: normalizeAzureBaseUrl(resolvedBaseUrl),
|
|
119
|
+
apiVersion,
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
function createClient(model, apiKey, options) {
|
|
123
|
+
if (!apiKey) {
|
|
124
|
+
if (!process.env.AZURE_OPENAI_API_KEY) {
|
|
125
|
+
throw new Error("Azure OpenAI API key is required. Set AZURE_OPENAI_API_KEY environment variable or pass it as an argument.");
|
|
126
|
+
}
|
|
127
|
+
apiKey = process.env.AZURE_OPENAI_API_KEY;
|
|
128
|
+
}
|
|
129
|
+
const headers = { ...model.headers };
|
|
130
|
+
if (options?.headers) {
|
|
131
|
+
Object.assign(headers, options.headers);
|
|
132
|
+
}
|
|
133
|
+
const { baseUrl, apiVersion } = resolveAzureConfig(model, options);
|
|
134
|
+
return new AzureOpenAI({
|
|
135
|
+
apiKey,
|
|
136
|
+
apiVersion,
|
|
137
|
+
dangerouslyAllowBrowser: true,
|
|
138
|
+
defaultHeaders: headers,
|
|
139
|
+
baseURL: baseUrl,
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
function buildParams(model, context, options, deploymentName) {
|
|
143
|
+
const messages = convertResponsesMessages(model, context, AZURE_TOOL_CALL_PROVIDERS);
|
|
144
|
+
const params = {
|
|
145
|
+
model: deploymentName,
|
|
146
|
+
input: messages,
|
|
147
|
+
stream: true,
|
|
148
|
+
prompt_cache_key: options?.sessionId,
|
|
149
|
+
};
|
|
150
|
+
if (options?.maxTokens) {
|
|
151
|
+
params.max_output_tokens = options?.maxTokens;
|
|
152
|
+
}
|
|
153
|
+
if (options?.temperature !== undefined) {
|
|
154
|
+
params.temperature = options?.temperature;
|
|
155
|
+
}
|
|
156
|
+
if (context.tools) {
|
|
157
|
+
params.tools = convertResponsesTools(context.tools);
|
|
158
|
+
}
|
|
159
|
+
if (model.reasoning) {
|
|
160
|
+
if (options?.reasoningEffort || options?.reasoningSummary) {
|
|
161
|
+
params.reasoning = {
|
|
162
|
+
effort: options?.reasoningEffort || "medium",
|
|
163
|
+
summary: options?.reasoningSummary || "auto",
|
|
164
|
+
};
|
|
165
|
+
params.include = ["reasoning.encrypted_content"];
|
|
166
|
+
}
|
|
167
|
+
else {
|
|
168
|
+
if (model.name.toLowerCase().startsWith("gpt-5")) {
|
|
169
|
+
// Jesus Christ, see https://community.openai.com/t/need-reasoning-false-option-for-gpt-5/1351588/7
|
|
170
|
+
messages.push({
|
|
171
|
+
role: "developer",
|
|
172
|
+
content: [
|
|
173
|
+
{
|
|
174
|
+
type: "input_text",
|
|
175
|
+
text: "# Juice: 0 !important",
|
|
176
|
+
},
|
|
177
|
+
],
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
return params;
|
|
183
|
+
}
|
|
184
|
+
//# sourceMappingURL=azure-openai-responses.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"azure-openai-responses.js","sourceRoot":"","sources":["../../src/providers/azure-openai-responses.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,QAAQ,CAAC;AAErC,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAU7C,OAAO,EAAE,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;AACvE,OAAO,EAAE,wBAAwB,EAAE,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IAAI,CAAC;oBACb,IAAI,EAAE,WAAW;oBACjB,OAAO,EAAE;wBACR;4BACC,IAAI,EAAE,YAAY;4BAClB,IAAI,EAAE,uBAAuB;yBAC7B;qBACD;iBACD,CAAC,CAAC;YACJ,CAAC;QACF,CAAC;IACF,CAAC;IAED,OAAO,MAAM,CAAC;AAAA,CACd","sourcesContent":["import { AzureOpenAI } from \"openai\";\nimport type { ResponseCreateParamsStreaming } from \"openai/resources/responses/responses.js\";\nimport { getEnvApiKey } from \"../env-api-keys.js\";\nimport { supportsXhigh } from \"../models.js\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tContext,\n\tModel,\n\tSimpleStreamOptions,\n\tStreamFunction,\n\tStreamOptions,\n} from \"../types.js\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.js\";\nimport { convertResponsesMessages, convertResponsesTools, processResponsesStream } from \"./openai-responses-shared.js\";\nimport { buildBaseOptions, clampReasoning } from \"./simple-options.js\";\n\nconst DEFAULT_AZURE_API_VERSION = \"v1\";\nconst AZURE_TOOL_CALL_PROVIDERS = new Set([\"openai\", \"openai-codex\", \"opencode\", \"azure-openai-responses\"]);\n\nfunction parseDeploymentNameMap(value: string | undefined): Map<string, string> {\n\tconst map = new Map<string, string>();\n\tif (!value) return map;\n\tfor (const entry of value.split(\",\")) {\n\t\tconst trimmed = entry.trim();\n\t\tif (!trimmed) continue;\n\t\tconst [modelId, deploymentName] = trimmed.split(\"=\", 2);\n\t\tif (!modelId || !deploymentName) continue;\n\t\tmap.set(modelId.trim(), deploymentName.trim());\n\t}\n\treturn map;\n}\n\nfunction resolveDeploymentName(model: Model<\"azure-openai-responses\">, options?: AzureOpenAIResponsesOptions): string {\n\tif (options?.azureDeploymentName) {\n\t\treturn options.azureDeploymentName;\n\t}\n\tconst mappedDeployment = parseDeploymentNameMap(process.env.AZURE_OPENAI_DEPLOYMENT_NAME_MAP).get(model.id);\n\treturn mappedDeployment || model.id;\n}\n\n// Azure OpenAI Responses-specific options\nexport interface AzureOpenAIResponsesOptions extends StreamOptions {\n\treasoningEffort?: \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\";\n\treasoningSummary?: \"auto\" | \"detailed\" | \"concise\" | null;\n\tazureApiVersion?: string;\n\tazureResourceName?: string;\n\tazureBaseUrl?: string;\n\tazureDeploymentName?: string;\n}\n\n/**\n * Generate function for Azure OpenAI Responses API\n */\nexport const streamAzureOpenAIResponses: StreamFunction<\"azure-openai-responses\", AzureOpenAIResponsesOptions> = (\n\tmodel: Model<\"azure-openai-responses\">,\n\tcontext: Context,\n\toptions?: AzureOpenAIResponsesOptions,\n): AssistantMessageEventStream => {\n\tconst stream = new AssistantMessageEventStream();\n\n\t// Start async processing\n\t(async () => {\n\t\tconst deploymentName = resolveDeploymentName(model, options);\n\n\t\tconst output: AssistantMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [],\n\t\t\tapi: \"azure-openai-responses\" 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\t// Create Azure OpenAI client\n\t\t\tconst apiKey = options?.apiKey || getEnvApiKey(model.provider) || \"\";\n\t\t\tconst client = createClient(model, apiKey, options);\n\t\t\tconst params = buildParams(model, context, options, deploymentName);\n\t\t\toptions?.onPayload?.(params);\n\t\t\tconst openaiStream = await client.responses.create(\n\t\t\t\tparams,\n\t\t\t\toptions?.signal ? { signal: options.signal } : undefined,\n\t\t\t);\n\t\t\tstream.push({ type: \"start\", partial: output });\n\n\t\t\tawait processResponsesStream(openaiStream, output, stream, model);\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 { index?: number }).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\nexport const streamSimpleAzureOpenAIResponses: StreamFunction<\"azure-openai-responses\", SimpleStreamOptions> = (\n\tmodel: Model<\"azure-openai-responses\">,\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\tconst reasoningEffort = supportsXhigh(model) ? options?.reasoning : clampReasoning(options?.reasoning);\n\n\treturn streamAzureOpenAIResponses(model, context, {\n\t\t...base,\n\t\treasoningEffort,\n\t} satisfies AzureOpenAIResponsesOptions);\n};\n\nfunction normalizeAzureBaseUrl(baseUrl: string): string {\n\treturn baseUrl.replace(/\\/+$/, \"\");\n}\n\nfunction buildDefaultBaseUrl(resourceName: string): string {\n\treturn `https://${resourceName}.openai.azure.com/openai/v1`;\n}\n\nfunction resolveAzureConfig(\n\tmodel: Model<\"azure-openai-responses\">,\n\toptions?: AzureOpenAIResponsesOptions,\n): { baseUrl: string; apiVersion: string } {\n\tconst apiVersion = options?.azureApiVersion || process.env.AZURE_OPENAI_API_VERSION || DEFAULT_AZURE_API_VERSION;\n\n\tconst baseUrl = options?.azureBaseUrl?.trim() || process.env.AZURE_OPENAI_BASE_URL?.trim() || undefined;\n\tconst resourceName = options?.azureResourceName || process.env.AZURE_OPENAI_RESOURCE_NAME;\n\n\tlet resolvedBaseUrl = baseUrl;\n\n\tif (!resolvedBaseUrl && resourceName) {\n\t\tresolvedBaseUrl = buildDefaultBaseUrl(resourceName);\n\t}\n\n\tif (!resolvedBaseUrl && model.baseUrl) {\n\t\tresolvedBaseUrl = model.baseUrl;\n\t}\n\n\tif (!resolvedBaseUrl) {\n\t\tthrow new Error(\n\t\t\t\"Azure OpenAI base URL is required. Set AZURE_OPENAI_BASE_URL or AZURE_OPENAI_RESOURCE_NAME, or pass azureBaseUrl, azureResourceName, or model.baseUrl.\",\n\t\t);\n\t}\n\n\treturn {\n\t\tbaseUrl: normalizeAzureBaseUrl(resolvedBaseUrl),\n\t\tapiVersion,\n\t};\n}\n\nfunction createClient(model: Model<\"azure-openai-responses\">, apiKey: string, options?: AzureOpenAIResponsesOptions) {\n\tif (!apiKey) {\n\t\tif (!process.env.AZURE_OPENAI_API_KEY) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Azure OpenAI API key is required. Set AZURE_OPENAI_API_KEY environment variable or pass it as an argument.\",\n\t\t\t);\n\t\t}\n\t\tapiKey = process.env.AZURE_OPENAI_API_KEY;\n\t}\n\n\tconst headers = { ...model.headers };\n\n\tif (options?.headers) {\n\t\tObject.assign(headers, options.headers);\n\t}\n\n\tconst { baseUrl, apiVersion } = resolveAzureConfig(model, options);\n\n\treturn new AzureOpenAI({\n\t\tapiKey,\n\t\tapiVersion,\n\t\tdangerouslyAllowBrowser: true,\n\t\tdefaultHeaders: headers,\n\t\tbaseURL: baseUrl,\n\t});\n}\n\nfunction buildParams(\n\tmodel: Model<\"azure-openai-responses\">,\n\tcontext: Context,\n\toptions: AzureOpenAIResponsesOptions | undefined,\n\tdeploymentName: string,\n) {\n\tconst messages = convertResponsesMessages(model, context, AZURE_TOOL_CALL_PROVIDERS);\n\n\tconst params: ResponseCreateParamsStreaming = {\n\t\tmodel: deploymentName,\n\t\tinput: messages,\n\t\tstream: true,\n\t\tprompt_cache_key: options?.sessionId,\n\t};\n\n\tif (options?.maxTokens) {\n\t\tparams.max_output_tokens = options?.maxTokens;\n\t}\n\n\tif (options?.temperature !== undefined) {\n\t\tparams.temperature = options?.temperature;\n\t}\n\n\tif (context.tools) {\n\t\tparams.tools = convertResponsesTools(context.tools);\n\t}\n\n\tif (model.reasoning) {\n\t\tif (options?.reasoningEffort || options?.reasoningSummary) {\n\t\t\tparams.reasoning = {\n\t\t\t\teffort: options?.reasoningEffort || \"medium\",\n\t\t\t\tsummary: options?.reasoningSummary || \"auto\",\n\t\t\t};\n\t\t\tparams.include = [\"reasoning.encrypted_content\"];\n\t\t} else {\n\t\t\tif (model.name.toLowerCase().startsWith(\"gpt-5\")) {\n\t\t\t\t// Jesus Christ, see https://community.openai.com/t/need-reasoning-false-option-for-gpt-5/1351588/7\n\t\t\t\tmessages.push({\n\t\t\t\t\trole: \"developer\",\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"input_text\",\n\t\t\t\t\t\t\ttext: \"# Juice: 0 !important\",\n\t\t\t\t\t\t},\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"]}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { Message } from "../types.js";
|
|
2
|
+
export declare function inferCopilotInitiator(messages: Message[]): "user" | "agent";
|
|
3
|
+
export declare function hasCopilotVisionInput(messages: Message[]): boolean;
|
|
4
|
+
export declare function buildCopilotDynamicHeaders(params: {
|
|
5
|
+
messages: Message[];
|
|
6
|
+
hasImages: boolean;
|
|
7
|
+
}): Record<string, string>;
|
|
8
|
+
//# sourceMappingURL=github-copilot-headers.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"github-copilot-headers.d.ts","sourceRoot":"","sources":["../../src/providers/github-copilot-headers.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAI3C,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,OAAO,EAAE,GAAG,MAAM,GAAG,OAAO,CAG3E;AAGD,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,OAAO,EAAE,GAAG,OAAO,CAUlE;AAED,wBAAgB,0BAA0B,CAAC,MAAM,EAAE;IAClD,QAAQ,EAAE,OAAO,EAAE,CAAC;IACpB,SAAS,EAAE,OAAO,CAAC;CACnB,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAWzB","sourcesContent":["import type { Message } from \"../types.js\";\n\n// Copilot expects X-Initiator to indicate whether the request is user-initiated\n// or agent-initiated (e.g. follow-up after assistant/tool messages).\nexport function inferCopilotInitiator(messages: Message[]): \"user\" | \"agent\" {\n\tconst last = messages[messages.length - 1];\n\treturn last && last.role !== \"user\" ? \"agent\" : \"user\";\n}\n\n// Copilot requires Copilot-Vision-Request header when sending images\nexport function hasCopilotVisionInput(messages: Message[]): boolean {\n\treturn messages.some((msg) => {\n\t\tif (msg.role === \"user\" && Array.isArray(msg.content)) {\n\t\t\treturn msg.content.some((c) => c.type === \"image\");\n\t\t}\n\t\tif (msg.role === \"toolResult\" && Array.isArray(msg.content)) {\n\t\t\treturn msg.content.some((c) => c.type === \"image\");\n\t\t}\n\t\treturn false;\n\t});\n}\n\nexport function buildCopilotDynamicHeaders(params: {\n\tmessages: Message[];\n\thasImages: boolean;\n}): Record<string, string> {\n\tconst headers: Record<string, string> = {\n\t\t\"X-Initiator\": inferCopilotInitiator(params.messages),\n\t\t\"Openai-Intent\": \"conversation-edits\",\n\t};\n\n\tif (params.hasImages) {\n\t\theaders[\"Copilot-Vision-Request\"] = \"true\";\n\t}\n\n\treturn headers;\n}\n"]}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// Copilot expects X-Initiator to indicate whether the request is user-initiated
|
|
2
|
+
// or agent-initiated (e.g. follow-up after assistant/tool messages).
|
|
3
|
+
export function inferCopilotInitiator(messages) {
|
|
4
|
+
const last = messages[messages.length - 1];
|
|
5
|
+
return last && last.role !== "user" ? "agent" : "user";
|
|
6
|
+
}
|
|
7
|
+
// Copilot requires Copilot-Vision-Request header when sending images
|
|
8
|
+
export function hasCopilotVisionInput(messages) {
|
|
9
|
+
return messages.some((msg) => {
|
|
10
|
+
if (msg.role === "user" && Array.isArray(msg.content)) {
|
|
11
|
+
return msg.content.some((c) => c.type === "image");
|
|
12
|
+
}
|
|
13
|
+
if (msg.role === "toolResult" && Array.isArray(msg.content)) {
|
|
14
|
+
return msg.content.some((c) => c.type === "image");
|
|
15
|
+
}
|
|
16
|
+
return false;
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
export function buildCopilotDynamicHeaders(params) {
|
|
20
|
+
const headers = {
|
|
21
|
+
"X-Initiator": inferCopilotInitiator(params.messages),
|
|
22
|
+
"Openai-Intent": "conversation-edits",
|
|
23
|
+
};
|
|
24
|
+
if (params.hasImages) {
|
|
25
|
+
headers["Copilot-Vision-Request"] = "true";
|
|
26
|
+
}
|
|
27
|
+
return headers;
|
|
28
|
+
}
|
|
29
|
+
//# sourceMappingURL=github-copilot-headers.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"github-copilot-headers.js","sourceRoot":"","sources":["../../src/providers/github-copilot-headers.ts"],"names":[],"mappings":"AAEA,gFAAgF;AAChF,qEAAqE;AACrE,MAAM,UAAU,qBAAqB,CAAC,QAAmB,EAAoB;IAC5E,MAAM,IAAI,GAAG,QAAQ,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IAC3C,OAAO,IAAI,IAAI,IAAI,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC;AAAA,CACvD;AAED,qEAAqE;AACrE,MAAM,UAAU,qBAAqB,CAAC,QAAmB,EAAW;IACnE,OAAO,QAAQ,CAAC,IAAI,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC;QAC7B,IAAI,GAAG,CAAC,IAAI,KAAK,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,CAAC;YACvD,OAAO,GAAG,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,OAAO,CAAC,CAAC;QACpD,CAAC;QACD,IAAI,GAAG,CAAC,IAAI,KAAK,YAAY,IAAI,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,CAAC;YAC7D,OAAO,GAAG,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,OAAO,CAAC,CAAC;QACpD,CAAC;QACD,OAAO,KAAK,CAAC;IAAA,CACb,CAAC,CAAC;AAAA,CACH;AAED,MAAM,UAAU,0BAA0B,CAAC,MAG1C,EAA0B;IAC1B,MAAM,OAAO,GAA2B;QACvC,aAAa,EAAE,qBAAqB,CAAC,MAAM,CAAC,QAAQ,CAAC;QACrD,eAAe,EAAE,oBAAoB;KACrC,CAAC;IAEF,IAAI,MAAM,CAAC,SAAS,EAAE,CAAC;QACtB,OAAO,CAAC,wBAAwB,CAAC,GAAG,MAAM,CAAC;IAC5C,CAAC;IAED,OAAO,OAAO,CAAC;AAAA,CACf","sourcesContent":["import type { Message } from \"../types.js\";\n\n// Copilot expects X-Initiator to indicate whether the request is user-initiated\n// or agent-initiated (e.g. follow-up after assistant/tool messages).\nexport function inferCopilotInitiator(messages: Message[]): \"user\" | \"agent\" {\n\tconst last = messages[messages.length - 1];\n\treturn last && last.role !== \"user\" ? \"agent\" : \"user\";\n}\n\n// Copilot requires Copilot-Vision-Request header when sending images\nexport function hasCopilotVisionInput(messages: Message[]): boolean {\n\treturn messages.some((msg) => {\n\t\tif (msg.role === \"user\" && Array.isArray(msg.content)) {\n\t\t\treturn msg.content.some((c) => c.type === \"image\");\n\t\t}\n\t\tif (msg.role === \"toolResult\" && Array.isArray(msg.content)) {\n\t\t\treturn msg.content.some((c) => c.type === \"image\");\n\t\t}\n\t\treturn false;\n\t});\n}\n\nexport function buildCopilotDynamicHeaders(params: {\n\tmessages: Message[];\n\thasImages: boolean;\n}): Record<string, string> {\n\tconst headers: Record<string, string> = {\n\t\t\"X-Initiator\": inferCopilotInitiator(params.messages),\n\t\t\"Openai-Intent\": \"conversation-edits\",\n\t};\n\n\tif (params.hasImages) {\n\t\theaders[\"Copilot-Vision-Request\"] = \"true\";\n\t}\n\n\treturn headers;\n}\n"]}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Google Gemini CLI / Antigravity provider.
|
|
3
|
+
* Shared implementation for both google-gemini-cli and google-antigravity providers.
|
|
4
|
+
* Uses the Cloud Code Assist API endpoint to access Gemini and Claude models.
|
|
5
|
+
*/
|
|
6
|
+
import type { Content, ThinkingConfig } from "@google/genai";
|
|
7
|
+
import type { Context, Model, SimpleStreamOptions, StreamFunction, StreamOptions } from "../types.js";
|
|
8
|
+
import { convertTools, mapToolChoice } from "./google-shared.js";
|
|
9
|
+
/**
|
|
10
|
+
* Thinking level for Gemini 3 models.
|
|
11
|
+
* Mirrors Google's ThinkingLevel enum values.
|
|
12
|
+
*/
|
|
13
|
+
export type GoogleThinkingLevel = "THINKING_LEVEL_UNSPECIFIED" | "MINIMAL" | "LOW" | "MEDIUM" | "HIGH";
|
|
14
|
+
export interface GoogleGeminiCliOptions extends StreamOptions {
|
|
15
|
+
toolChoice?: "auto" | "none" | "any";
|
|
16
|
+
/**
|
|
17
|
+
* Thinking/reasoning configuration.
|
|
18
|
+
* - Gemini 2.x models: use `budgetTokens` to set the thinking budget
|
|
19
|
+
* - Gemini 3 models (gemini-3-pro-*, gemini-3-flash-*): use `level` instead
|
|
20
|
+
*
|
|
21
|
+
* When using `streamSimple`, this is handled automatically based on the model.
|
|
22
|
+
*/
|
|
23
|
+
thinking?: {
|
|
24
|
+
enabled: boolean;
|
|
25
|
+
/** Thinking budget in tokens. Use for Gemini 2.x models. */
|
|
26
|
+
budgetTokens?: number;
|
|
27
|
+
/** Thinking level. Use for Gemini 3 models (LOW/HIGH for Pro, MINIMAL/LOW/MEDIUM/HIGH for Flash). */
|
|
28
|
+
level?: GoogleThinkingLevel;
|
|
29
|
+
};
|
|
30
|
+
projectId?: string;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Extract retry delay from Gemini error response (in milliseconds).
|
|
34
|
+
* Checks headers first (Retry-After, x-ratelimit-reset, x-ratelimit-reset-after),
|
|
35
|
+
* then parses body patterns like:
|
|
36
|
+
* - "Your quota will reset after 39s"
|
|
37
|
+
* - "Your quota will reset after 18h31m10s"
|
|
38
|
+
* - "Please retry in Xs" or "Please retry in Xms"
|
|
39
|
+
* - "retryDelay": "34.074824224s" (JSON field)
|
|
40
|
+
*/
|
|
41
|
+
export declare function extractRetryDelay(errorText: string, response?: Response | Headers): number | undefined;
|
|
42
|
+
interface CloudCodeAssistRequest {
|
|
43
|
+
project: string;
|
|
44
|
+
model: string;
|
|
45
|
+
request: {
|
|
46
|
+
contents: Content[];
|
|
47
|
+
sessionId?: string;
|
|
48
|
+
systemInstruction?: {
|
|
49
|
+
role?: string;
|
|
50
|
+
parts: {
|
|
51
|
+
text: string;
|
|
52
|
+
}[];
|
|
53
|
+
};
|
|
54
|
+
generationConfig?: {
|
|
55
|
+
maxOutputTokens?: number;
|
|
56
|
+
temperature?: number;
|
|
57
|
+
thinkingConfig?: ThinkingConfig;
|
|
58
|
+
};
|
|
59
|
+
tools?: ReturnType<typeof convertTools>;
|
|
60
|
+
toolConfig?: {
|
|
61
|
+
functionCallingConfig: {
|
|
62
|
+
mode: ReturnType<typeof mapToolChoice>;
|
|
63
|
+
};
|
|
64
|
+
};
|
|
65
|
+
};
|
|
66
|
+
requestType?: string;
|
|
67
|
+
userAgent?: string;
|
|
68
|
+
requestId?: string;
|
|
69
|
+
}
|
|
70
|
+
export declare const streamGoogleGeminiCli: StreamFunction<"google-gemini-cli", GoogleGeminiCliOptions>;
|
|
71
|
+
export declare const streamSimpleGoogleGeminiCli: StreamFunction<"google-gemini-cli", SimpleStreamOptions>;
|
|
72
|
+
export declare function buildRequest(model: Model<"google-gemini-cli">, context: Context, projectId: string, options?: GoogleGeminiCliOptions, isAntigravity?: boolean): CloudCodeAssistRequest;
|
|
73
|
+
export {};
|
|
74
|
+
//# sourceMappingURL=google-gemini-cli.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"google-gemini-cli.d.ts","sourceRoot":"","sources":["../../src/providers/google-gemini-cli.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAE7D,OAAO,KAAK,EAGX,OAAO,EACP,KAAK,EACL,mBAAmB,EACnB,cAAc,EACd,aAAa,EAMb,MAAM,aAAa,CAAC;AAGrB,OAAO,EAEN,YAAY,EAGZ,aAAa,EAEb,MAAM,oBAAoB,CAAC;AAG5B;;;GAGG;AACH,MAAM,MAAM,mBAAmB,GAAG,4BAA4B,GAAG,SAAS,GAAG,KAAK,GAAG,QAAQ,GAAG,MAAM,CAAC;AAEvG,MAAM,WAAW,sBAAuB,SAAQ,aAAa;IAC5D,UAAU,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,KAAK,CAAC;IACrC;;;;;;OAMG;IACH,QAAQ,CAAC,EAAE;QACV,OAAO,EAAE,OAAO,CAAC;QACjB,4DAA4D;QAC5D,YAAY,CAAC,EAAE,MAAM,CAAC;QACtB,qGAAqG;QACrG,KAAK,CAAC,EAAE,mBAAmB,CAAC;KAC5B,CAAC;IACF,SAAS,CAAC,EAAE,MAAM,CAAC;CACnB;AAiDD;;;;;;;;GAQG;AACH,wBAAgB,iBAAiB,C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Gemini CLI / Antigravity provider.\n * Shared implementation for both google-gemini-cli and google-antigravity providers.\n * Uses the Cloud Code Assist API endpoint to access Gemini and Claude models.\n */\n\nimport type { Content, ThinkingConfig } from \"@google/genai\";\nimport { calculateCost } from \"../models.js\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tContext,\n\tModel,\n\tSimpleStreamOptions,\n\tStreamFunction,\n\tStreamOptions,\n\tTextContent,\n\tThinkingBudgets,\n\tThinkingContent,\n\tThinkingLevel,\n\tToolCall,\n} from \"../types.js\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.js\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.js\";\nimport {\n\tconvertMessages,\n\tconvertTools,\n\tisThinkingPart,\n\tmapStopReasonString,\n\tmapToolChoice,\n\tretainThoughtSignature,\n} from \"./google-shared.js\";\nimport { buildBaseOptions, clampReasoning } from \"./simple-options.js\";\n\n/**\n * Thinking level for Gemini 3 models.\n * Mirrors Google's ThinkingLevel enum values.\n */\nexport type GoogleThinkingLevel = \"THINKING_LEVEL_UNSPECIFIED\" | \"MINIMAL\" | \"LOW\" | \"MEDIUM\" | \"HIGH\";\n\nexport interface GoogleGeminiCliOptions extends StreamOptions {\n\ttoolChoice?: \"auto\" | \"none\" | \"any\";\n\t/**\n\t * Thinking/reasoning configuration.\n\t * - Gemini 2.x models: use `budgetTokens` to set the thinking budget\n\t * - Gemini 3 models (gemini-3-pro-*, gemini-3-flash-*): use `level` instead\n\t *\n\t * When using `streamSimple`, this is handled automatically based on the model.\n\t */\n\tthinking?: {\n\t\tenabled: boolean;\n\t\t/** Thinking budget in tokens. Use for Gemini 2.x models. */\n\t\tbudgetTokens?: number;\n\t\t/** Thinking level. Use for Gemini 3 models (LOW/HIGH for Pro, MINIMAL/LOW/MEDIUM/HIGH for Flash). */\n\t\tlevel?: GoogleThinkingLevel;\n\t};\n\tprojectId?: string;\n}\n\nconst DEFAULT_ENDPOINT = \"https://cloudcode-pa.googleapis.com\";\nconst ANTIGRAVITY_DAILY_ENDPOINT = \"https://daily-cloudcode-pa.sandbox.googleapis.com\";\nconst ANTIGRAVITY_ENDPOINT_FALLBACKS = [ANTIGRAVITY_DAILY_ENDPOINT, DEFAULT_ENDPOINT] as const;\n// Headers for Gemini CLI (prod endpoint)\nconst GEMINI_CLI_HEADERS = {\n\t\"User-Agent\": \"google-cloud-sdk vscode_cloudshelleditor/0.1\",\n\t\"X-Goog-Api-Client\": \"gl-node/22.17.0\",\n\t\"Client-Metadata\": JSON.stringify({\n\t\tideType: \"IDE_UNSPECIFIED\",\n\t\tplatform: \"PLATFORM_UNSPECIFIED\",\n\t\tpluginType: \"GEMINI\",\n\t}),\n};\n\n// Headers for Antigravity (sandbox endpoint) - requires specific User-Agent\nconst DEFAULT_ANTIGRAVITY_VERSION = \"1.15.8\";\n\nfunction getAntigravityHeaders() {\n\tconst version = process.env.DRAHT_AI_ANTIGRAVITY_VERSION || DEFAULT_ANTIGRAVITY_VERSION;\n\treturn {\n\t\t\"User-Agent\": `antigravity/${version} darwin/arm64`,\n\t\t\"X-Goog-Api-Client\": \"google-cloud-sdk vscode_cloudshelleditor/0.1\",\n\t\t\"Client-Metadata\": JSON.stringify({\n\t\t\tideType: \"IDE_UNSPECIFIED\",\n\t\t\tplatform: \"PLATFORM_UNSPECIFIED\",\n\t\t\tpluginType: \"GEMINI\",\n\t\t}),\n\t};\n}\n\n// Antigravity system instruction (compact version from CLIProxyAPI).\nconst ANTIGRAVITY_SYSTEM_INSTRUCTION =\n\t\"You are Antigravity, a powerful agentic AI coding assistant designed by the Google Deepmind team working on Advanced Agentic Coding.\" +\n\t\"You are pair programming with a USER to solve their coding task. The task may require creating a new codebase, modifying or debugging an existing codebase, or simply answering a question.\" +\n\t\"**Absolute paths only**\" +\n\t\"**Proactiveness**\";\n\n// Counter for generating unique tool call IDs\nlet toolCallCounter = 0;\n\n// Retry configuration\nconst MAX_RETRIES = 3;\nconst BASE_DELAY_MS = 1000;\nconst MAX_EMPTY_STREAM_RETRIES = 2;\nconst EMPTY_STREAM_BASE_DELAY_MS = 500;\nconst CLAUDE_THINKING_BETA_HEADER = \"interleaved-thinking-2025-05-14\";\n\n/**\n * Extract retry delay from Gemini error response (in milliseconds).\n * Checks headers first (Retry-After, x-ratelimit-reset, x-ratelimit-reset-after),\n * then parses body patterns like:\n * - \"Your quota will reset after 39s\"\n * - \"Your quota will reset after 18h31m10s\"\n * - \"Please retry in Xs\" or \"Please retry in Xms\"\n * - \"retryDelay\": \"34.074824224s\" (JSON field)\n */\nexport function extractRetryDelay(errorText: string, response?: Response | Headers): number | undefined {\n\tconst normalizeDelay = (ms: number): number | undefined => (ms > 0 ? Math.ceil(ms + 1000) : undefined);\n\n\tconst headers = response instanceof Headers ? response : response?.headers;\n\tif (headers) {\n\t\tconst retryAfter = headers.get(\"retry-after\");\n\t\tif (retryAfter) {\n\t\t\tconst retryAfterSeconds = Number(retryAfter);\n\t\t\tif (Number.isFinite(retryAfterSeconds)) {\n\t\t\t\tconst delay = normalizeDelay(retryAfterSeconds * 1000);\n\t\t\t\tif (delay !== undefined) {\n\t\t\t\t\treturn delay;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst retryAfterDate = new Date(retryAfter);\n\t\t\tconst retryAfterMs = retryAfterDate.getTime();\n\t\t\tif (!Number.isNaN(retryAfterMs)) {\n\t\t\t\tconst delay = normalizeDelay(retryAfterMs - Date.now());\n\t\t\t\tif (delay !== undefined) {\n\t\t\t\t\treturn delay;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst rateLimitReset = headers.get(\"x-ratelimit-reset\");\n\t\tif (rateLimitReset) {\n\t\t\tconst resetSeconds = Number.parseInt(rateLimitReset, 10);\n\t\t\tif (!Number.isNaN(resetSeconds)) {\n\t\t\t\tconst delay = normalizeDelay(resetSeconds * 1000 - Date.now());\n\t\t\t\tif (delay !== undefined) {\n\t\t\t\t\treturn delay;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst rateLimitResetAfter = headers.get(\"x-ratelimit-reset-after\");\n\t\tif (rateLimitResetAfter) {\n\t\t\tconst resetAfterSeconds = Number(rateLimitResetAfter);\n\t\t\tif (Number.isFinite(resetAfterSeconds)) {\n\t\t\t\tconst delay = normalizeDelay(resetAfterSeconds * 1000);\n\t\t\t\tif (delay !== undefined) {\n\t\t\t\t\treturn delay;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Pattern 1: \"Your quota will reset after ...\" (formats: \"18h31m10s\", \"10m15s\", \"6s\", \"39s\")\n\tconst durationMatch = errorText.match(/reset after (?:(\\d+)h)?(?:(\\d+)m)?(\\d+(?:\\.\\d+)?)s/i);\n\tif (durationMatch) {\n\t\tconst hours = durationMatch[1] ? parseInt(durationMatch[1], 10) : 0;\n\t\tconst minutes = durationMatch[2] ? parseInt(durationMatch[2], 10) : 0;\n\t\tconst seconds = parseFloat(durationMatch[3]);\n\t\tif (!Number.isNaN(seconds)) {\n\t\t\tconst totalMs = ((hours * 60 + minutes) * 60 + seconds) * 1000;\n\t\t\tconst delay = normalizeDelay(totalMs);\n\t\t\tif (delay !== undefined) {\n\t\t\t\treturn delay;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Pattern 2: \"Please retry in X[ms|s]\"\n\tconst retryInMatch = errorText.match(/Please retry in ([0-9.]+)(ms|s)/i);\n\tif (retryInMatch?.[1]) {\n\t\tconst value = parseFloat(retryInMatch[1]);\n\t\tif (!Number.isNaN(value) && value > 0) {\n\t\t\tconst ms = retryInMatch[2].toLowerCase() === \"ms\" ? value : value * 1000;\n\t\t\tconst delay = normalizeDelay(ms);\n\t\t\tif (delay !== undefined) {\n\t\t\t\treturn delay;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Pattern 3: \"retryDelay\": \"34.074824224s\" (JSON field in error details)\n\tconst retryDelayMatch = errorText.match(/\"retryDelay\":\\s*\"([0-9.]+)(ms|s)\"/i);\n\tif (retryDelayMatch?.[1]) {\n\t\tconst value = parseFloat(retryDelayMatch[1]);\n\t\tif (!Number.isNaN(value) && value > 0) {\n\t\t\tconst ms = retryDelayMatch[2].toLowerCase() === \"ms\" ? value : value * 1000;\n\t\t\tconst delay = normalizeDelay(ms);\n\t\t\tif (delay !== undefined) {\n\t\t\t\treturn delay;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn undefined;\n}\n\nfunction isClaudeThinkingModel(modelId: string): boolean {\n\tconst normalized = modelId.toLowerCase();\n\treturn normalized.includes(\"claude\") && normalized.includes(\"thinking\");\n}\n\n/**\n * Check if an error is retryable (rate limit, server error, network error, etc.)\n */\nfunction isRetryableError(status: number, errorText: string): boolean {\n\tif (status === 429 || status === 500 || status === 502 || status === 503 || status === 504) {\n\t\treturn true;\n\t}\n\treturn /resource.?exhausted|rate.?limit|overloaded|service.?unavailable|other.?side.?closed/i.test(errorText);\n}\n\n/**\n * Extract a clean, user-friendly error message from Google API error response.\n * Parses JSON error responses and returns just the message field.\n */\nfunction extractErrorMessage(errorText: string): string {\n\ttry {\n\t\tconst parsed = JSON.parse(errorText) as { error?: { message?: string } };\n\t\tif (parsed.error?.message) {\n\t\t\treturn parsed.error.message;\n\t\t}\n\t} catch {\n\t\t// Not JSON, return as-is\n\t}\n\treturn errorText;\n}\n\n/**\n * Sleep for a given number of milliseconds, respecting abort signal.\n */\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(new Error(\"Request was aborted\"));\n\t\t\treturn;\n\t\t}\n\t\tconst timeout = setTimeout(resolve, ms);\n\t\tsignal?.addEventListener(\"abort\", () => {\n\t\t\tclearTimeout(timeout);\n\t\t\treject(new Error(\"Request was aborted\"));\n\t\t});\n\t});\n}\n\ninterface CloudCodeAssistRequest {\n\tproject: string;\n\tmodel: string;\n\trequest: {\n\t\tcontents: Content[];\n\t\tsessionId?: string;\n\t\tsystemInstruction?: { role?: string; parts: { text: string }[] };\n\t\tgenerationConfig?: {\n\t\t\tmaxOutputTokens?: number;\n\t\t\ttemperature?: number;\n\t\t\tthinkingConfig?: ThinkingConfig;\n\t\t};\n\t\ttools?: ReturnType<typeof convertTools>;\n\t\ttoolConfig?: {\n\t\t\tfunctionCallingConfig: {\n\t\t\t\tmode: ReturnType<typeof mapToolChoice>;\n\t\t\t};\n\t\t};\n\t};\n\trequestType?: string;\n\tuserAgent?: string;\n\trequestId?: string;\n}\n\ninterface CloudCodeAssistResponseChunk {\n\tresponse?: {\n\t\tcandidates?: Array<{\n\t\t\tcontent?: {\n\t\t\t\trole: string;\n\t\t\t\tparts?: Array<{\n\t\t\t\t\ttext?: string;\n\t\t\t\t\tthought?: boolean;\n\t\t\t\t\tthoughtSignature?: string;\n\t\t\t\t\tfunctionCall?: {\n\t\t\t\t\t\tname: string;\n\t\t\t\t\t\targs: Record<string, unknown>;\n\t\t\t\t\t\tid?: string;\n\t\t\t\t\t};\n\t\t\t\t}>;\n\t\t\t};\n\t\t\tfinishReason?: string;\n\t\t}>;\n\t\tusageMetadata?: {\n\t\t\tpromptTokenCount?: number;\n\t\t\tcandidatesTokenCount?: number;\n\t\t\tthoughtsTokenCount?: number;\n\t\t\ttotalTokenCount?: number;\n\t\t\tcachedContentTokenCount?: number;\n\t\t};\n\t\tmodelVersion?: string;\n\t\tresponseId?: string;\n\t};\n\ttraceId?: string;\n}\n\nexport const streamGoogleGeminiCli: StreamFunction<\"google-gemini-cli\", GoogleGeminiCliOptions> = (\n\tmodel: Model<\"google-gemini-cli\">,\n\tcontext: Context,\n\toptions?: GoogleGeminiCliOptions,\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: \"google-gemini-cli\" 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\t// apiKey is JSON-encoded: { token, projectId }\n\t\t\tconst apiKeyRaw = options?.apiKey;\n\t\t\tif (!apiKeyRaw) {\n\t\t\t\tthrow new Error(\"Google Cloud Code Assist requires OAuth authentication. Use /login to authenticate.\");\n\t\t\t}\n\n\t\t\tlet accessToken: string;\n\t\t\tlet projectId: string;\n\n\t\t\ttry {\n\t\t\t\tconst parsed = JSON.parse(apiKeyRaw) as { token: string; projectId: string };\n\t\t\t\taccessToken = parsed.token;\n\t\t\t\tprojectId = parsed.projectId;\n\t\t\t} catch {\n\t\t\t\tthrow new Error(\"Invalid Google Cloud Code Assist credentials. Use /login to re-authenticate.\");\n\t\t\t}\n\n\t\t\tif (!accessToken || !projectId) {\n\t\t\t\tthrow new Error(\"Missing token or projectId in Google Cloud credentials. Use /login to re-authenticate.\");\n\t\t\t}\n\n\t\t\tconst isAntigravity = model.provider === \"google-antigravity\";\n\t\t\tconst baseUrl = model.baseUrl?.trim();\n\t\t\tconst endpoints = baseUrl ? [baseUrl] : isAntigravity ? ANTIGRAVITY_ENDPOINT_FALLBACKS : [DEFAULT_ENDPOINT];\n\n\t\t\tconst requestBody = buildRequest(model, context, projectId, options, isAntigravity);\n\t\t\toptions?.onPayload?.(requestBody);\n\t\t\tconst headers = isAntigravity ? getAntigravityHeaders() : GEMINI_CLI_HEADERS;\n\n\t\t\tconst requestHeaders = {\n\t\t\t\tAuthorization: `Bearer ${accessToken}`,\n\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\tAccept: \"text/event-stream\",\n\t\t\t\t...headers,\n\t\t\t\t...(isClaudeThinkingModel(model.id) ? { \"anthropic-beta\": CLAUDE_THINKING_BETA_HEADER } : {}),\n\t\t\t\t...options?.headers,\n\t\t\t};\n\t\t\tconst requestBodyJson = JSON.stringify(requestBody);\n\n\t\t\t// Fetch with retry logic for rate limits and transient errors\n\t\t\tlet response: Response | undefined;\n\t\t\tlet lastError: Error | undefined;\n\t\t\tlet requestUrl: string | undefined;\n\n\t\t\tfor (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {\n\t\t\t\tif (options?.signal?.aborted) {\n\t\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tconst endpoint = endpoints[Math.min(attempt, endpoints.length - 1)];\n\t\t\t\t\trequestUrl = `${endpoint}/v1internal:streamGenerateContent?alt=sse`;\n\t\t\t\t\tresponse = await fetch(requestUrl, {\n\t\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\t\theaders: requestHeaders,\n\t\t\t\t\t\tbody: requestBodyJson,\n\t\t\t\t\t\tsignal: options?.signal,\n\t\t\t\t\t});\n\n\t\t\t\t\tif (response.ok) {\n\t\t\t\t\t\tbreak; // Success, exit retry loop\n\t\t\t\t\t}\n\n\t\t\t\t\tconst errorText = await response.text();\n\n\t\t\t\t\t// Check if retryable\n\t\t\t\t\tif (attempt < MAX_RETRIES && isRetryableError(response.status, errorText)) {\n\t\t\t\t\t\t// Use server-provided delay or exponential backoff\n\t\t\t\t\t\tconst serverDelay = extractRetryDelay(errorText, response);\n\t\t\t\t\t\tconst delayMs = serverDelay ?? BASE_DELAY_MS * 2 ** attempt;\n\n\t\t\t\t\t\t// Check if server delay exceeds max allowed (default: 60s)\n\t\t\t\t\t\tconst maxDelayMs = options?.maxRetryDelayMs ?? 60000;\n\t\t\t\t\t\tif (maxDelayMs > 0 && serverDelay && serverDelay > maxDelayMs) {\n\t\t\t\t\t\t\tconst delaySeconds = Math.ceil(serverDelay / 1000);\n\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t`Server requested ${delaySeconds}s retry delay (max: ${Math.ceil(maxDelayMs / 1000)}s). ${extractErrorMessage(errorText)}`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tawait sleep(delayMs, options?.signal);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Not retryable or max retries exceeded\n\t\t\t\t\tthrow new Error(`Cloud Code Assist API error (${response.status}): ${extractErrorMessage(errorText)}`);\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// Check for abort - fetch throws AbortError, our code throws \"Request was aborted\"\n\t\t\t\t\tif (error instanceof Error) {\n\t\t\t\t\t\tif (error.name === \"AbortError\" || error.message === \"Request was aborted\") {\n\t\t\t\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t// Extract detailed error message from fetch errors (Node includes cause)\n\t\t\t\t\tlastError = error instanceof Error ? error : new Error(String(error));\n\t\t\t\t\tif (lastError.message === \"fetch failed\" && lastError.cause instanceof Error) {\n\t\t\t\t\t\tlastError = new Error(`Network error: ${lastError.cause.message}`);\n\t\t\t\t\t}\n\t\t\t\t\t// Network errors are retryable\n\t\t\t\t\tif (attempt < MAX_RETRIES) {\n\t\t\t\t\t\tconst delayMs = BASE_DELAY_MS * 2 ** attempt;\n\t\t\t\t\t\tawait sleep(delayMs, options?.signal);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tthrow lastError;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!response || !response.ok) {\n\t\t\t\tthrow lastError ?? new Error(\"Failed to get response after retries\");\n\t\t\t}\n\n\t\t\tlet started = false;\n\t\t\tconst ensureStarted = () => {\n\t\t\t\tif (!started) {\n\t\t\t\t\tstream.push({ type: \"start\", partial: output });\n\t\t\t\t\tstarted = true;\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tconst resetOutput = () => {\n\t\t\t\toutput.content = [];\n\t\t\t\toutput.usage = {\n\t\t\t\t\tinput: 0,\n\t\t\t\t\toutput: 0,\n\t\t\t\t\tcacheRead: 0,\n\t\t\t\t\tcacheWrite: 0,\n\t\t\t\t\ttotalTokens: 0,\n\t\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t\t};\n\t\t\t\toutput.stopReason = \"stop\";\n\t\t\t\toutput.errorMessage = undefined;\n\t\t\t\toutput.timestamp = Date.now();\n\t\t\t\tstarted = false;\n\t\t\t};\n\n\t\t\tconst streamResponse = async (activeResponse: Response): Promise<boolean> => {\n\t\t\t\tif (!activeResponse.body) {\n\t\t\t\t\tthrow new Error(\"No response body\");\n\t\t\t\t}\n\n\t\t\t\tlet hasContent = false;\n\t\t\t\tlet currentBlock: TextContent | ThinkingContent | null = null;\n\t\t\t\tconst blocks = output.content;\n\t\t\t\tconst blockIndex = () => blocks.length - 1;\n\n\t\t\t\t// Read SSE stream\n\t\t\t\tconst reader = activeResponse.body.getReader();\n\t\t\t\tconst decoder = new TextDecoder();\n\t\t\t\tlet buffer = \"\";\n\n\t\t\t\t// Set up abort handler to cancel reader when signal fires\n\t\t\t\tconst abortHandler = () => {\n\t\t\t\t\tvoid reader.cancel().catch(() => {});\n\t\t\t\t};\n\t\t\t\toptions?.signal?.addEventListener(\"abort\", abortHandler);\n\n\t\t\t\ttry {\n\t\t\t\t\twhile (true) {\n\t\t\t\t\t\t// Check abort signal before each read\n\t\t\t\t\t\tif (options?.signal?.aborted) {\n\t\t\t\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\t\t\tif (done) break;\n\n\t\t\t\t\t\tbuffer += decoder.decode(value, { stream: true });\n\t\t\t\t\t\tconst lines = buffer.split(\"\\n\");\n\t\t\t\t\t\tbuffer = lines.pop() || \"\";\n\n\t\t\t\t\t\tfor (const line of lines) {\n\t\t\t\t\t\t\tif (!line.startsWith(\"data:\")) continue;\n\n\t\t\t\t\t\t\tconst jsonStr = line.slice(5).trim();\n\t\t\t\t\t\t\tif (!jsonStr) continue;\n\n\t\t\t\t\t\t\tlet chunk: CloudCodeAssistResponseChunk;\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tchunk = JSON.parse(jsonStr);\n\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// Unwrap the response\n\t\t\t\t\t\t\tconst responseData = chunk.response;\n\t\t\t\t\t\t\tif (!responseData) continue;\n\n\t\t\t\t\t\t\tconst candidate = responseData.candidates?.[0];\n\t\t\t\t\t\t\tif (candidate?.content?.parts) {\n\t\t\t\t\t\t\t\tfor (const part of candidate.content.parts) {\n\t\t\t\t\t\t\t\t\tif (part.text !== undefined) {\n\t\t\t\t\t\t\t\t\t\thasContent = true;\n\t\t\t\t\t\t\t\t\t\tconst isThinking = isThinkingPart(part);\n\t\t\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\t\t\t!currentBlock ||\n\t\t\t\t\t\t\t\t\t\t\t(isThinking && currentBlock.type !== \"thinking\") ||\n\t\t\t\t\t\t\t\t\t\t\t(!isThinking && currentBlock.type !== \"text\")\n\t\t\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\t\t\tif (currentBlock) {\n\t\t\t\t\t\t\t\t\t\t\t\tif (currentBlock.type === \"text\") {\n\t\t\t\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\t\t\t\ttype: \"text_end\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcontentIndex: blocks.length - 1,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcontent: currentBlock.text,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\t\t\t\ttype: \"thinking_end\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcontent: currentBlock.thinking,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\tif (isThinking) {\n\t\t\t\t\t\t\t\t\t\t\t\tcurrentBlock = { type: \"thinking\", thinking: \"\", thinkingSignature: undefined };\n\t\t\t\t\t\t\t\t\t\t\t\toutput.content.push(currentBlock);\n\t\t\t\t\t\t\t\t\t\t\t\tensureStarted();\n\t\t\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\t\t\ttype: \"thinking_start\",\n\t\t\t\t\t\t\t\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\t\tcurrentBlock = { type: \"text\", text: \"\" };\n\t\t\t\t\t\t\t\t\t\t\t\toutput.content.push(currentBlock);\n\t\t\t\t\t\t\t\t\t\t\t\tensureStarted();\n\t\t\t\t\t\t\t\t\t\t\t\tstream.push({ type: \"text_start\", contentIndex: blockIndex(), partial: output });\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tif (currentBlock.type === \"thinking\") {\n\t\t\t\t\t\t\t\t\t\t\tcurrentBlock.thinking += part.text;\n\t\t\t\t\t\t\t\t\t\t\tcurrentBlock.thinkingSignature = retainThoughtSignature(\n\t\t\t\t\t\t\t\t\t\t\t\tcurrentBlock.thinkingSignature,\n\t\t\t\t\t\t\t\t\t\t\t\tpart.thoughtSignature,\n\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\t\t\t\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\t\t\t\t\t\t\tdelta: part.text,\n\t\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\tcurrentBlock.text += part.text;\n\t\t\t\t\t\t\t\t\t\t\tcurrentBlock.textSignature = retainThoughtSignature(\n\t\t\t\t\t\t\t\t\t\t\t\tcurrentBlock.textSignature,\n\t\t\t\t\t\t\t\t\t\t\t\tpart.thoughtSignature,\n\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\t\ttype: \"text_delta\",\n\t\t\t\t\t\t\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\t\t\t\t\t\t\tdelta: part.text,\n\t\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tif (part.functionCall) {\n\t\t\t\t\t\t\t\t\t\thasContent = true;\n\t\t\t\t\t\t\t\t\t\tif (currentBlock) {\n\t\t\t\t\t\t\t\t\t\t\tif (currentBlock.type === \"text\") {\n\t\t\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\t\t\ttype: \"text_end\",\n\t\t\t\t\t\t\t\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\t\t\t\t\t\t\t\tcontent: currentBlock.text,\n\t\t\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\t\t\ttype: \"thinking_end\",\n\t\t\t\t\t\t\t\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\t\t\t\t\t\t\t\tcontent: currentBlock.thinking,\n\t\t\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\tcurrentBlock = null;\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tconst providedId = part.functionCall.id;\n\t\t\t\t\t\t\t\t\t\tconst needsNewId =\n\t\t\t\t\t\t\t\t\t\t\t!providedId ||\n\t\t\t\t\t\t\t\t\t\t\toutput.content.some((b) => b.type === \"toolCall\" && b.id === providedId);\n\t\t\t\t\t\t\t\t\t\tconst toolCallId = needsNewId\n\t\t\t\t\t\t\t\t\t\t\t? `${part.functionCall.name}_${Date.now()}_${++toolCallCounter}`\n\t\t\t\t\t\t\t\t\t\t\t: providedId;\n\n\t\t\t\t\t\t\t\t\t\tconst toolCall: ToolCall = {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"toolCall\",\n\t\t\t\t\t\t\t\t\t\t\tid: toolCallId,\n\t\t\t\t\t\t\t\t\t\t\tname: part.functionCall.name || \"\",\n\t\t\t\t\t\t\t\t\t\t\targuments: (part.functionCall.args as Record<string, unknown>) ?? {},\n\t\t\t\t\t\t\t\t\t\t\t...(part.thoughtSignature && { thoughtSignature: part.thoughtSignature }),\n\t\t\t\t\t\t\t\t\t\t};\n\n\t\t\t\t\t\t\t\t\t\toutput.content.push(toolCall);\n\t\t\t\t\t\t\t\t\t\tensureStarted();\n\t\t\t\t\t\t\t\t\t\tstream.push({ type: \"toolcall_start\", contentIndex: blockIndex(), partial: output });\n\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\ttype: \"toolcall_delta\",\n\t\t\t\t\t\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\t\t\t\t\t\tdelta: JSON.stringify(toolCall.arguments),\n\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\ttype: \"toolcall_end\",\n\t\t\t\t\t\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\t\t\t\t\t\ttoolCall,\n\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t});\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\n\t\t\t\t\t\t\tif (candidate?.finishReason) {\n\t\t\t\t\t\t\t\toutput.stopReason = mapStopReasonString(candidate.finishReason);\n\t\t\t\t\t\t\t\tif (output.content.some((b) => b.type === \"toolCall\")) {\n\t\t\t\t\t\t\t\t\toutput.stopReason = \"toolUse\";\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (responseData.usageMetadata) {\n\t\t\t\t\t\t\t\t// promptTokenCount includes cachedContentTokenCount, so subtract to get fresh input\n\t\t\t\t\t\t\t\tconst promptTokens = responseData.usageMetadata.promptTokenCount || 0;\n\t\t\t\t\t\t\t\tconst cacheReadTokens = responseData.usageMetadata.cachedContentTokenCount || 0;\n\t\t\t\t\t\t\t\toutput.usage = {\n\t\t\t\t\t\t\t\t\tinput: promptTokens - cacheReadTokens,\n\t\t\t\t\t\t\t\t\toutput:\n\t\t\t\t\t\t\t\t\t\t(responseData.usageMetadata.candidatesTokenCount || 0) +\n\t\t\t\t\t\t\t\t\t\t(responseData.usageMetadata.thoughtsTokenCount || 0),\n\t\t\t\t\t\t\t\t\tcacheRead: cacheReadTokens,\n\t\t\t\t\t\t\t\t\tcacheWrite: 0,\n\t\t\t\t\t\t\t\t\ttotalTokens: responseData.usageMetadata.totalTokenCount || 0,\n\t\t\t\t\t\t\t\t\tcost: {\n\t\t\t\t\t\t\t\t\t\tinput: 0,\n\t\t\t\t\t\t\t\t\t\toutput: 0,\n\t\t\t\t\t\t\t\t\t\tcacheRead: 0,\n\t\t\t\t\t\t\t\t\t\tcacheWrite: 0,\n\t\t\t\t\t\t\t\t\t\ttotal: 0,\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\tcalculateCost(model, output.usage);\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} finally {\n\t\t\t\t\toptions?.signal?.removeEventListener(\"abort\", abortHandler);\n\t\t\t\t}\n\n\t\t\t\tif (currentBlock) {\n\t\t\t\t\tif (currentBlock.type === \"text\") {\n\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\ttype: \"text_end\",\n\t\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\t\tcontent: currentBlock.text,\n\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t});\n\t\t\t\t\t} else {\n\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\ttype: \"thinking_end\",\n\t\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\t\tcontent: currentBlock.thinking,\n\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn hasContent;\n\t\t\t};\n\n\t\t\tlet receivedContent = false;\n\t\t\tlet currentResponse = response;\n\n\t\t\tfor (let emptyAttempt = 0; emptyAttempt <= MAX_EMPTY_STREAM_RETRIES; emptyAttempt++) {\n\t\t\t\tif (options?.signal?.aborted) {\n\t\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t\t}\n\n\t\t\t\tif (emptyAttempt > 0) {\n\t\t\t\t\tconst backoffMs = EMPTY_STREAM_BASE_DELAY_MS * 2 ** (emptyAttempt - 1);\n\t\t\t\t\tawait sleep(backoffMs, options?.signal);\n\n\t\t\t\t\tif (!requestUrl) {\n\t\t\t\t\t\tthrow new Error(\"Missing request URL\");\n\t\t\t\t\t}\n\n\t\t\t\t\tcurrentResponse = await fetch(requestUrl, {\n\t\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\t\theaders: requestHeaders,\n\t\t\t\t\t\tbody: requestBodyJson,\n\t\t\t\t\t\tsignal: options?.signal,\n\t\t\t\t\t});\n\n\t\t\t\t\tif (!currentResponse.ok) {\n\t\t\t\t\t\tconst retryErrorText = await currentResponse.text();\n\t\t\t\t\t\tthrow new Error(`Cloud Code Assist API error (${currentResponse.status}): ${retryErrorText}`);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst streamed = await streamResponse(currentResponse);\n\t\t\t\tif (streamed) {\n\t\t\t\t\treceivedContent = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif (emptyAttempt < MAX_EMPTY_STREAM_RETRIES) {\n\t\t\t\t\tresetOutput();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!receivedContent) {\n\t\t\t\tthrow new Error(\"Cloud Code Assist API returned an empty response\");\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) {\n\t\t\t\tif (\"index\" in block) {\n\t\t\t\t\tdelete (block as { index?: number }).index;\n\t\t\t\t}\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 streamSimpleGoogleGeminiCli: StreamFunction<\"google-gemini-cli\", SimpleStreamOptions> = (\n\tmodel: Model<\"google-gemini-cli\">,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): AssistantMessageEventStream => {\n\tconst apiKey = options?.apiKey;\n\tif (!apiKey) {\n\t\tthrow new Error(\"Google Cloud Code Assist requires OAuth authentication. Use /login to authenticate.\");\n\t}\n\n\tconst base = buildBaseOptions(model, options, apiKey);\n\tif (!options?.reasoning) {\n\t\treturn streamGoogleGeminiCli(model, context, {\n\t\t\t...base,\n\t\t\tthinking: { enabled: false },\n\t\t} satisfies GoogleGeminiCliOptions);\n\t}\n\n\tconst effort = clampReasoning(options.reasoning)!;\n\tif (model.id.includes(\"3-pro\") || model.id.includes(\"3-flash\")) {\n\t\treturn streamGoogleGeminiCli(model, context, {\n\t\t\t...base,\n\t\t\tthinking: {\n\t\t\t\tenabled: true,\n\t\t\t\tlevel: getGeminiCliThinkingLevel(effort, model.id),\n\t\t\t},\n\t\t} satisfies GoogleGeminiCliOptions);\n\t}\n\n\tconst defaultBudgets: ThinkingBudgets = {\n\t\tminimal: 1024,\n\t\tlow: 2048,\n\t\tmedium: 8192,\n\t\thigh: 16384,\n\t};\n\tconst budgets = { ...defaultBudgets, ...options.thinkingBudgets };\n\n\tconst minOutputTokens = 1024;\n\tlet thinkingBudget = budgets[effort]!;\n\tconst maxTokens = Math.min((base.maxTokens || 0) + thinkingBudget, model.maxTokens);\n\n\tif (maxTokens <= thinkingBudget) {\n\t\tthinkingBudget = Math.max(0, maxTokens - minOutputTokens);\n\t}\n\n\treturn streamGoogleGeminiCli(model, context, {\n\t\t...base,\n\t\tmaxTokens,\n\t\tthinking: {\n\t\t\tenabled: true,\n\t\t\tbudgetTokens: thinkingBudget,\n\t\t},\n\t} satisfies GoogleGeminiCliOptions);\n};\n\nexport function buildRequest(\n\tmodel: Model<\"google-gemini-cli\">,\n\tcontext: Context,\n\tprojectId: string,\n\toptions: GoogleGeminiCliOptions = {},\n\tisAntigravity = false,\n): CloudCodeAssistRequest {\n\tconst contents = convertMessages(model, context);\n\n\tconst generationConfig: CloudCodeAssistRequest[\"request\"][\"generationConfig\"] = {};\n\tif (options.temperature !== undefined) {\n\t\tgenerationConfig.temperature = options.temperature;\n\t}\n\tif (options.maxTokens !== undefined) {\n\t\tgenerationConfig.maxOutputTokens = options.maxTokens;\n\t}\n\n\t// Thinking config\n\tif (options.thinking?.enabled && model.reasoning) {\n\t\tgenerationConfig.thinkingConfig = {\n\t\t\tincludeThoughts: true,\n\t\t};\n\t\t// Gemini 3 models use thinkingLevel, older models use thinkingBudget\n\t\tif (options.thinking.level !== undefined) {\n\t\t\t// Cast to any since our GoogleThinkingLevel mirrors Google's ThinkingLevel enum values\n\t\t\tgenerationConfig.thinkingConfig.thinkingLevel = options.thinking.level as any;\n\t\t} else if (options.thinking.budgetTokens !== undefined) {\n\t\t\tgenerationConfig.thinkingConfig.thinkingBudget = options.thinking.budgetTokens;\n\t\t}\n\t}\n\n\tconst request: CloudCodeAssistRequest[\"request\"] = {\n\t\tcontents,\n\t};\n\n\trequest.sessionId = options.sessionId;\n\n\t// System instruction must be object with parts, not plain string\n\tif (context.systemPrompt) {\n\t\trequest.systemInstruction = {\n\t\t\tparts: [{ text: sanitizeSurrogates(context.systemPrompt) }],\n\t\t};\n\t}\n\n\tif (Object.keys(generationConfig).length > 0) {\n\t\trequest.generationConfig = generationConfig;\n\t}\n\n\tif (context.tools && context.tools.length > 0) {\n\t\t// Claude models on Cloud Code Assist need the legacy `parameters` field;\n\t\t// the API translates it into Anthropic's `input_schema`.\n\t\tconst useParameters = model.id.startsWith(\"claude-\");\n\t\trequest.tools = convertTools(context.tools, useParameters);\n\t\tif (options.toolChoice) {\n\t\t\trequest.toolConfig = {\n\t\t\t\tfunctionCallingConfig: {\n\t\t\t\t\tmode: mapToolChoice(options.toolChoice),\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t}\n\n\tif (isAntigravity) {\n\t\tconst existingParts = request.systemInstruction?.parts ?? [];\n\t\trequest.systemInstruction = {\n\t\t\trole: \"user\",\n\t\t\tparts: [\n\t\t\t\t{ text: ANTIGRAVITY_SYSTEM_INSTRUCTION },\n\t\t\t\t{ text: `Please ignore following [ignore]${ANTIGRAVITY_SYSTEM_INSTRUCTION}[/ignore]` },\n\t\t\t\t...existingParts,\n\t\t\t],\n\t\t};\n\t}\n\n\treturn {\n\t\tproject: projectId,\n\t\tmodel: model.id,\n\t\trequest,\n\t\t...(isAntigravity ? { requestType: \"agent\" } : {}),\n\t\tuserAgent: isAntigravity ? \"antigravity\" : \"pi-coding-agent\",\n\t\trequestId: `${isAntigravity ? \"agent\" : \"draht\"}-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`,\n\t};\n}\n\ntype ClampedThinkingLevel = Exclude<ThinkingLevel, \"xhigh\">;\n\nfunction getGeminiCliThinkingLevel(effort: ClampedThinkingLevel, modelId: string): GoogleThinkingLevel {\n\tif (modelId.includes(\"3-pro\")) {\n\t\tswitch (effort) {\n\t\t\tcase \"minimal\":\n\t\t\tcase \"low\":\n\t\t\t\treturn \"LOW\";\n\t\t\tcase \"medium\":\n\t\t\tcase \"high\":\n\t\t\t\treturn \"HIGH\";\n\t\t}\n\t}\n\tswitch (effort) {\n\t\tcase \"minimal\":\n\t\t\treturn \"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}\n}\n"]}
|