@mariozechner/pi-ai 0.24.5 → 0.25.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/README.md +120 -10
  2. package/dist/agent/agent-loop.d.ts.map +1 -1
  3. package/dist/agent/agent-loop.js +58 -5
  4. package/dist/agent/agent-loop.js.map +1 -1
  5. package/dist/index.d.ts +2 -0
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +2 -0
  8. package/dist/index.js.map +1 -1
  9. package/dist/models.generated.d.ts +179 -22
  10. package/dist/models.generated.d.ts.map +1 -1
  11. package/dist/models.generated.js +205 -48
  12. package/dist/models.generated.js.map +1 -1
  13. package/dist/providers/anthropic.d.ts.map +1 -1
  14. package/dist/providers/anthropic.js +0 -2
  15. package/dist/providers/anthropic.js.map +1 -1
  16. package/dist/providers/google-gemini-cli.d.ts +16 -0
  17. package/dist/providers/google-gemini-cli.d.ts.map +1 -0
  18. package/dist/providers/google-gemini-cli.js +347 -0
  19. package/dist/providers/google-gemini-cli.js.map +1 -0
  20. package/dist/providers/google-shared.d.ts +34 -0
  21. package/dist/providers/google-shared.d.ts.map +1 -0
  22. package/dist/providers/google-shared.js +218 -0
  23. package/dist/providers/google-shared.js.map +1 -0
  24. package/dist/providers/google.d.ts.map +1 -1
  25. package/dist/providers/google.js +3 -162
  26. package/dist/providers/google.js.map +1 -1
  27. package/dist/providers/openai-completions.d.ts.map +1 -1
  28. package/dist/providers/openai-completions.js +25 -0
  29. package/dist/providers/openai-completions.js.map +1 -1
  30. package/dist/providers/openai-responses.d.ts.map +1 -1
  31. package/dist/providers/openai-responses.js +24 -1
  32. package/dist/providers/openai-responses.js.map +1 -1
  33. package/dist/providers/transorm-messages.d.ts.map +1 -1
  34. package/dist/providers/transorm-messages.js +62 -43
  35. package/dist/providers/transorm-messages.js.map +1 -1
  36. package/dist/stream.d.ts +15 -0
  37. package/dist/stream.d.ts.map +1 -1
  38. package/dist/stream.js +39 -0
  39. package/dist/stream.js.map +1 -1
  40. package/dist/types.d.ts +4 -2
  41. package/dist/types.d.ts.map +1 -1
  42. package/dist/types.js.map +1 -1
  43. package/dist/utils/oauth/anthropic.d.ts +16 -0
  44. package/dist/utils/oauth/anthropic.d.ts.map +1 -0
  45. package/dist/utils/oauth/anthropic.js +103 -0
  46. package/dist/utils/oauth/anthropic.js.map +1 -0
  47. package/dist/utils/oauth/github-copilot.d.ts +43 -0
  48. package/dist/utils/oauth/github-copilot.d.ts.map +1 -0
  49. package/dist/utils/oauth/github-copilot.js +237 -0
  50. package/dist/utils/oauth/github-copilot.js.map +1 -0
  51. package/dist/utils/oauth/google-antigravity.d.ts +24 -0
  52. package/dist/utils/oauth/google-antigravity.d.ts.map +1 -0
  53. package/dist/utils/oauth/google-antigravity.js +273 -0
  54. package/dist/utils/oauth/google-antigravity.js.map +1 -0
  55. package/dist/utils/oauth/google-gemini-cli.d.ts +24 -0
  56. package/dist/utils/oauth/google-gemini-cli.d.ts.map +1 -0
  57. package/dist/utils/oauth/google-gemini-cli.js +286 -0
  58. package/dist/utils/oauth/google-gemini-cli.js.map +1 -0
  59. package/dist/utils/oauth/index.d.ts +54 -0
  60. package/dist/utils/oauth/index.d.ts.map +1 -0
  61. package/dist/utils/oauth/index.js +147 -0
  62. package/dist/utils/oauth/index.js.map +1 -0
  63. package/dist/utils/oauth/storage.d.ts +81 -0
  64. package/dist/utils/oauth/storage.d.ts.map +1 -0
  65. package/dist/utils/oauth/storage.js +119 -0
  66. package/dist/utils/oauth/storage.js.map +1 -0
  67. package/dist/utils/overflow.d.ts +2 -2
  68. package/dist/utils/overflow.d.ts.map +1 -1
  69. package/dist/utils/overflow.js +7 -4
  70. package/dist/utils/overflow.js.map +1 -1
  71. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"openai-responses.js","sourceRoot":"","sources":["../../src/providers/openai-responses.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,QAAQ,CAAC;A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,EAAE,CAAC;QAChB,KAAK,WAAW;YACf,OAAO,MAAM,CAAC;QACf,KAAK,YAAY;YAChB,OAAO,QAAQ,CAAC;QACjB,KAAK,QAAQ,CAAC;QACd,KAAK,WAAW;YACf,OAAO,OAAO,CAAC;QAChB,0BAA0B;QAC1B,KAAK,aAAa,CAAC;QACnB,KAAK,QAAQ;YACZ,OAAO,MAAM,CAAC;QACf,SAAS,CAAC;YACT,MAAM,WAAW,GAAU,MAAM,CAAC;YAClC,MAAM,IAAI,KAAK,CAAC,0BAA0B,WAAW,EAAE,CAAC,CAAC;QAC1D,CAAC;IACF,CAAC;AAAA,CACD","sourcesContent":["import OpenAI from \"openai\";\nimport type {\n\tTool as OpenAITool,\n\tResponseCreateParamsStreaming,\n\tResponseFunctionToolCall,\n\tResponseInput,\n\tResponseInputContent,\n\tResponseInputImage,\n\tResponseInputText,\n\tResponseOutputMessage,\n\tResponseReasoningItem,\n} from \"openai/resources/responses/responses.js\";\nimport { calculateCost } from \"../models.js\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tContext,\n\tModel,\n\tStopReason,\n\tStreamFunction,\n\tStreamOptions,\n\tTextContent,\n\tThinkingContent,\n\tTool,\n\tToolCall,\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 { transformMessages } from \"./transorm-messages.js\";\n\n// OpenAI Responses-specific options\nexport interface OpenAIResponsesOptions extends StreamOptions {\n\treasoningEffort?: \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\";\n\treasoningSummary?: \"auto\" | \"detailed\" | \"concise\" | null;\n}\n\n/**\n * Generate function for OpenAI Responses API\n */\nexport const streamOpenAIResponses: StreamFunction<\"openai-responses\"> = (\n\tmodel: Model<\"openai-responses\">,\n\tcontext: Context,\n\toptions?: OpenAIResponsesOptions,\n): AssistantMessageEventStream => {\n\tconst stream = new AssistantMessageEventStream();\n\n\t// Start async processing\n\t(async () => {\n\t\tconst output: AssistantMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [],\n\t\t\tapi: \"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 OpenAI client\n\t\t\tconst client = createClient(model, context, options?.apiKey);\n\t\t\tconst params = buildParams(model, context, options);\n\t\t\tconst openaiStream = await client.responses.create(params, { signal: options?.signal });\n\t\t\tstream.push({ type: \"start\", partial: output });\n\n\t\t\tlet currentItem: ResponseReasoningItem | ResponseOutputMessage | ResponseFunctionToolCall | null = null;\n\t\t\tlet currentBlock: ThinkingContent | TextContent | (ToolCall & { partialJson: string }) | null = null;\n\t\t\tconst blocks = output.content;\n\t\t\tconst blockIndex = () => blocks.length - 1;\n\n\t\t\tfor await (const event of openaiStream) {\n\t\t\t\t// Handle output item start\n\t\t\t\tif (event.type === \"response.output_item.added\") {\n\t\t\t\t\tconst item = event.item;\n\t\t\t\t\tif (item.type === \"reasoning\") {\n\t\t\t\t\t\tcurrentItem = item;\n\t\t\t\t\t\tcurrentBlock = { type: \"thinking\", thinking: \"\" };\n\t\t\t\t\t\toutput.content.push(currentBlock);\n\t\t\t\t\t\tstream.push({ type: \"thinking_start\", contentIndex: blockIndex(), partial: output });\n\t\t\t\t\t} else if (item.type === \"message\") {\n\t\t\t\t\t\tcurrentItem = item;\n\t\t\t\t\t\tcurrentBlock = { type: \"text\", text: \"\" };\n\t\t\t\t\t\toutput.content.push(currentBlock);\n\t\t\t\t\t\tstream.push({ type: \"text_start\", contentIndex: blockIndex(), partial: output });\n\t\t\t\t\t} else if (item.type === \"function_call\") {\n\t\t\t\t\t\tcurrentItem = item;\n\t\t\t\t\t\tcurrentBlock = {\n\t\t\t\t\t\t\ttype: \"toolCall\",\n\t\t\t\t\t\t\tid: item.call_id + \"|\" + item.id,\n\t\t\t\t\t\t\tname: item.name,\n\t\t\t\t\t\t\targuments: {},\n\t\t\t\t\t\t\tpartialJson: item.arguments || \"\",\n\t\t\t\t\t\t};\n\t\t\t\t\t\toutput.content.push(currentBlock);\n\t\t\t\t\t\tstream.push({ type: \"toolcall_start\", contentIndex: blockIndex(), partial: output });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Handle reasoning summary deltas\n\t\t\t\telse if (event.type === \"response.reasoning_summary_part.added\") {\n\t\t\t\t\tif (currentItem && currentItem.type === \"reasoning\") {\n\t\t\t\t\t\tcurrentItem.summary = currentItem.summary || [];\n\t\t\t\t\t\tcurrentItem.summary.push(event.part);\n\t\t\t\t\t}\n\t\t\t\t} else if (event.type === \"response.reasoning_summary_text.delta\") {\n\t\t\t\t\tif (\n\t\t\t\t\t\tcurrentItem &&\n\t\t\t\t\t\tcurrentItem.type === \"reasoning\" &&\n\t\t\t\t\t\tcurrentBlock &&\n\t\t\t\t\t\tcurrentBlock.type === \"thinking\"\n\t\t\t\t\t) {\n\t\t\t\t\t\tcurrentItem.summary = currentItem.summary || [];\n\t\t\t\t\t\tconst lastPart = currentItem.summary[currentItem.summary.length - 1];\n\t\t\t\t\t\tif (lastPart) {\n\t\t\t\t\t\t\tcurrentBlock.thinking += event.delta;\n\t\t\t\t\t\t\tlastPart.text += event.delta;\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: blockIndex(),\n\t\t\t\t\t\t\t\tdelta: event.delta,\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}\n\t\t\t\t// Add a new line between summary parts (hack...)\n\t\t\t\telse if (event.type === \"response.reasoning_summary_part.done\") {\n\t\t\t\t\tif (\n\t\t\t\t\t\tcurrentItem &&\n\t\t\t\t\t\tcurrentItem.type === \"reasoning\" &&\n\t\t\t\t\t\tcurrentBlock &&\n\t\t\t\t\t\tcurrentBlock.type === \"thinking\"\n\t\t\t\t\t) {\n\t\t\t\t\t\tcurrentItem.summary = currentItem.summary || [];\n\t\t\t\t\t\tconst lastPart = currentItem.summary[currentItem.summary.length - 1];\n\t\t\t\t\t\tif (lastPart) {\n\t\t\t\t\t\t\tcurrentBlock.thinking += \"\\n\\n\";\n\t\t\t\t\t\t\tlastPart.text += \"\\n\\n\";\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: blockIndex(),\n\t\t\t\t\t\t\t\tdelta: \"\\n\\n\",\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}\n\t\t\t\t// Handle text output deltas\n\t\t\t\telse if (event.type === \"response.content_part.added\") {\n\t\t\t\t\tif (currentItem && currentItem.type === \"message\") {\n\t\t\t\t\t\tcurrentItem.content = currentItem.content || [];\n\t\t\t\t\t\t// Filter out ReasoningText, only accept output_text and refusal\n\t\t\t\t\t\tif (event.part.type === \"output_text\" || event.part.type === \"refusal\") {\n\t\t\t\t\t\t\tcurrentItem.content.push(event.part);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else if (event.type === \"response.output_text.delta\") {\n\t\t\t\t\tif (currentItem && currentItem.type === \"message\" && currentBlock && currentBlock.type === \"text\") {\n\t\t\t\t\t\tconst lastPart = currentItem.content[currentItem.content.length - 1];\n\t\t\t\t\t\tif (lastPart && lastPart.type === \"output_text\") {\n\t\t\t\t\t\t\tcurrentBlock.text += event.delta;\n\t\t\t\t\t\t\tlastPart.text += event.delta;\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: blockIndex(),\n\t\t\t\t\t\t\t\tdelta: event.delta,\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 === \"response.refusal.delta\") {\n\t\t\t\t\tif (currentItem && currentItem.type === \"message\" && currentBlock && currentBlock.type === \"text\") {\n\t\t\t\t\t\tconst lastPart = currentItem.content[currentItem.content.length - 1];\n\t\t\t\t\t\tif (lastPart && lastPart.type === \"refusal\") {\n\t\t\t\t\t\t\tcurrentBlock.text += event.delta;\n\t\t\t\t\t\t\tlastPart.refusal += event.delta;\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: blockIndex(),\n\t\t\t\t\t\t\t\tdelta: event.delta,\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}\n\t\t\t\t// Handle function call argument deltas\n\t\t\t\telse if (event.type === \"response.function_call_arguments.delta\") {\n\t\t\t\t\tif (\n\t\t\t\t\t\tcurrentItem &&\n\t\t\t\t\t\tcurrentItem.type === \"function_call\" &&\n\t\t\t\t\t\tcurrentBlock &&\n\t\t\t\t\t\tcurrentBlock.type === \"toolCall\"\n\t\t\t\t\t) {\n\t\t\t\t\t\tcurrentBlock.partialJson += event.delta;\n\t\t\t\t\t\tcurrentBlock.arguments = parseStreamingJson(currentBlock.partialJson);\n\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\ttype: \"toolcall_delta\",\n\t\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\t\tdelta: event.delta,\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\t\t\t\t// Handle output item completion\n\t\t\t\telse if (event.type === \"response.output_item.done\") {\n\t\t\t\t\tconst item = event.item;\n\n\t\t\t\t\tif (item.type === \"reasoning\" && currentBlock && currentBlock.type === \"thinking\") {\n\t\t\t\t\t\tcurrentBlock.thinking = item.summary?.map((s) => s.text).join(\"\\n\\n\") || \"\";\n\t\t\t\t\t\tcurrentBlock.thinkingSignature = JSON.stringify(item);\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\tcurrentBlock = null;\n\t\t\t\t\t} else if (item.type === \"message\" && currentBlock && currentBlock.type === \"text\") {\n\t\t\t\t\t\tcurrentBlock.text = item.content.map((c) => (c.type === \"output_text\" ? c.text : c.refusal)).join(\"\");\n\t\t\t\t\t\tcurrentBlock.textSignature = item.id;\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\tcurrentBlock = null;\n\t\t\t\t\t} else if (item.type === \"function_call\") {\n\t\t\t\t\t\tconst toolCall: ToolCall = {\n\t\t\t\t\t\t\ttype: \"toolCall\",\n\t\t\t\t\t\t\tid: item.call_id + \"|\" + item.id,\n\t\t\t\t\t\t\tname: item.name,\n\t\t\t\t\t\t\targuments: JSON.parse(item.arguments),\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tstream.push({ type: \"toolcall_end\", contentIndex: blockIndex(), toolCall, partial: output });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Handle completion\n\t\t\t\telse if (event.type === \"response.completed\") {\n\t\t\t\t\tconst response = event.response;\n\t\t\t\t\tif (response?.usage) {\n\t\t\t\t\t\tconst cachedTokens = response.usage.input_tokens_details?.cached_tokens || 0;\n\t\t\t\t\t\toutput.usage = {\n\t\t\t\t\t\t\t// OpenAI includes cached tokens in input_tokens, so subtract to get non-cached input\n\t\t\t\t\t\t\tinput: (response.usage.input_tokens || 0) - cachedTokens,\n\t\t\t\t\t\t\toutput: response.usage.output_tokens || 0,\n\t\t\t\t\t\t\tcacheRead: cachedTokens,\n\t\t\t\t\t\t\tcacheWrite: 0,\n\t\t\t\t\t\t\ttotalTokens: response.usage.total_tokens || 0,\n\t\t\t\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tcalculateCost(model, output.usage);\n\t\t\t\t\t// Map status to stop reason\n\t\t\t\t\toutput.stopReason = mapStopReason(response?.status);\n\t\t\t\t\tif (output.content.some((b) => b.type === \"toolCall\") && output.stopReason === \"stop\") {\n\t\t\t\t\t\toutput.stopReason = \"toolUse\";\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Handle errors\n\t\t\t\telse if (event.type === \"error\") {\n\t\t\t\t\tthrow new Error(`Error Code ${event.code}: ${event.message}` || \"Unknown error\");\n\t\t\t\t} else if (event.type === \"response.failed\") {\n\t\t\t\t\tthrow new Error(\"Unknown error\");\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 unkown error ocurred\");\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\nfunction createClient(model: Model<\"openai-responses\">, context: Context, apiKey?: string) {\n\tif (!apiKey) {\n\t\tif (!process.env.OPENAI_API_KEY) {\n\t\t\tthrow new Error(\n\t\t\t\t\"OpenAI API key is required. Set OPENAI_API_KEY environment variable or pass it as an argument.\",\n\t\t\t);\n\t\t}\n\t\tapiKey = process.env.OPENAI_API_KEY;\n\t}\n\n\tconst headers = { ...model.headers };\n\tif (model.provider === \"github-copilot\") {\n\t\t// Copilot expects X-Initiator to indicate whether the request is user-initiated\n\t\t// or agent-initiated (e.g. follow-up after assistant/tool messages). If there is\n\t\t// no prior message, default to user-initiated.\n\t\tconst messages = context.messages || [];\n\t\tconst lastMessage = messages[messages.length - 1];\n\t\tconst isAgentCall = lastMessage ? lastMessage.role !== \"user\" : false;\n\t\theaders[\"X-Initiator\"] = isAgentCall ? \"agent\" : \"user\";\n\t\theaders[\"Openai-Intent\"] = \"conversation-edits\";\n\n\t\t// Copilot requires this header when sending images\n\t\tconst hasImages = messages.some((msg) => {\n\t\t\tif (msg.role === \"user\" && Array.isArray(msg.content)) {\n\t\t\t\treturn msg.content.some((c) => c.type === \"image\");\n\t\t\t}\n\t\t\tif (msg.role === \"toolResult\" && Array.isArray(msg.content)) {\n\t\t\t\treturn msg.content.some((c) => c.type === \"image\");\n\t\t\t}\n\t\t\treturn false;\n\t\t});\n\t\tif (hasImages) {\n\t\t\theaders[\"Copilot-Vision-Request\"] = \"true\";\n\t\t}\n\t}\n\n\treturn new OpenAI({\n\t\tapiKey,\n\t\tbaseURL: model.baseUrl,\n\t\tdangerouslyAllowBrowser: true,\n\t\tdefaultHeaders: headers,\n\t});\n}\n\nfunction buildParams(model: Model<\"openai-responses\">, context: Context, options?: OpenAIResponsesOptions) {\n\tconst messages = convertMessages(model, context);\n\n\tconst params: ResponseCreateParamsStreaming = {\n\t\tmodel: model.id,\n\t\tinput: messages,\n\t\tstream: true,\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 = convertTools(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.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\nfunction convertMessages(model: Model<\"openai-responses\">, context: Context): ResponseInput {\n\tconst messages: ResponseInput = [];\n\n\tconst transformedMessages = transformMessages(context.messages, model);\n\n\tif (context.systemPrompt) {\n\t\tconst role = model.reasoning ? \"developer\" : \"system\";\n\t\tmessages.push({\n\t\t\trole,\n\t\t\tcontent: sanitizeSurrogates(context.systemPrompt),\n\t\t});\n\t}\n\n\tfor (const msg of transformedMessages) {\n\t\tif (msg.role === \"user\") {\n\t\t\tif (typeof msg.content === \"string\") {\n\t\t\t\tmessages.push({\n\t\t\t\t\trole: \"user\",\n\t\t\t\t\tcontent: [{ type: \"input_text\", text: sanitizeSurrogates(msg.content) }],\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tconst content: ResponseInputContent[] = msg.content.map((item): ResponseInputContent => {\n\t\t\t\t\tif (item.type === \"text\") {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\ttype: \"input_text\",\n\t\t\t\t\t\t\ttext: sanitizeSurrogates(item.text),\n\t\t\t\t\t\t} satisfies ResponseInputText;\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\ttype: \"input_image\",\n\t\t\t\t\t\t\tdetail: \"auto\",\n\t\t\t\t\t\t\timage_url: `data:${item.mimeType};base64,${item.data}`,\n\t\t\t\t\t\t} satisfies ResponseInputImage;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tconst filteredContent = !model.input.includes(\"image\")\n\t\t\t\t\t? content.filter((c) => c.type !== \"input_image\")\n\t\t\t\t\t: content;\n\t\t\t\tif (filteredContent.length === 0) continue;\n\t\t\t\tmessages.push({\n\t\t\t\t\trole: \"user\",\n\t\t\t\t\tcontent: filteredContent,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (msg.role === \"assistant\") {\n\t\t\tconst output: ResponseInput = [];\n\n\t\t\tfor (const block of msg.content) {\n\t\t\t\t// Do not submit thinking blocks if the completion had an error (i.e. abort)\n\t\t\t\tif (block.type === \"thinking\" && msg.stopReason !== \"error\") {\n\t\t\t\t\tif (block.thinkingSignature) {\n\t\t\t\t\t\tconst reasoningItem = JSON.parse(block.thinkingSignature);\n\t\t\t\t\t\toutput.push(reasoningItem);\n\t\t\t\t\t}\n\t\t\t\t} else if (block.type === \"text\") {\n\t\t\t\t\tconst textBlock = block as TextContent;\n\t\t\t\t\toutput.push({\n\t\t\t\t\t\ttype: \"message\",\n\t\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\t\tcontent: [{ type: \"output_text\", text: sanitizeSurrogates(textBlock.text), annotations: [] }],\n\t\t\t\t\t\tstatus: \"completed\",\n\t\t\t\t\t\tid: textBlock.textSignature || \"msg_\" + Math.random().toString(36).substring(2, 15),\n\t\t\t\t\t} satisfies ResponseOutputMessage);\n\t\t\t\t\t// Do not submit toolcall blocks if the completion had an error (i.e. abort)\n\t\t\t\t} else if (block.type === \"toolCall\" && msg.stopReason !== \"error\") {\n\t\t\t\t\tconst toolCall = block as ToolCall;\n\t\t\t\t\toutput.push({\n\t\t\t\t\t\ttype: \"function_call\",\n\t\t\t\t\t\tid: toolCall.id.split(\"|\")[1],\n\t\t\t\t\t\tcall_id: toolCall.id.split(\"|\")[0],\n\t\t\t\t\t\tname: toolCall.name,\n\t\t\t\t\t\targuments: JSON.stringify(toolCall.arguments),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (output.length === 0) continue;\n\t\t\tmessages.push(...output);\n\t\t} else if (msg.role === \"toolResult\") {\n\t\t\t// Extract text and image content\n\t\t\tconst textResult = msg.content\n\t\t\t\t.filter((c) => c.type === \"text\")\n\t\t\t\t.map((c) => (c as any).text)\n\t\t\t\t.join(\"\\n\");\n\t\t\tconst hasImages = msg.content.some((c) => c.type === \"image\");\n\n\t\t\t// Always send function_call_output with text (or placeholder if only images)\n\t\t\tconst hasText = textResult.length > 0;\n\t\t\tmessages.push({\n\t\t\t\ttype: \"function_call_output\",\n\t\t\t\tcall_id: msg.toolCallId.split(\"|\")[0],\n\t\t\t\toutput: sanitizeSurrogates(hasText ? textResult : \"(see attached image)\"),\n\t\t\t});\n\n\t\t\t// If there are images and model supports them, send a follow-up user message with images\n\t\t\tif (hasImages && model.input.includes(\"image\")) {\n\t\t\t\tconst contentParts: ResponseInputContent[] = [];\n\n\t\t\t\t// Add text prefix\n\t\t\t\tcontentParts.push({\n\t\t\t\t\ttype: \"input_text\",\n\t\t\t\t\ttext: \"Attached image(s) from tool result:\",\n\t\t\t\t} satisfies ResponseInputText);\n\n\t\t\t\t// Add images\n\t\t\t\tfor (const block of msg.content) {\n\t\t\t\t\tif (block.type === \"image\") {\n\t\t\t\t\t\tcontentParts.push({\n\t\t\t\t\t\t\ttype: \"input_image\",\n\t\t\t\t\t\t\tdetail: \"auto\",\n\t\t\t\t\t\t\timage_url: `data:${(block as any).mimeType};base64,${(block as any).data}`,\n\t\t\t\t\t\t} satisfies ResponseInputImage);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tmessages.push({\n\t\t\t\t\trole: \"user\",\n\t\t\t\t\tcontent: contentParts,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\treturn messages;\n}\n\nfunction convertTools(tools: Tool[]): OpenAITool[] {\n\treturn tools.map((tool) => ({\n\t\ttype: \"function\",\n\t\tname: tool.name,\n\t\tdescription: tool.description,\n\t\tparameters: tool.parameters as any, // TypeBox already generates JSON Schema\n\t\tstrict: null,\n\t}));\n}\n\nfunction mapStopReason(status: OpenAI.Responses.ResponseStatus | undefined): StopReason {\n\tif (!status) return \"stop\";\n\tswitch (status) {\n\t\tcase \"completed\":\n\t\t\treturn \"stop\";\n\t\tcase \"incomplete\":\n\t\t\treturn \"length\";\n\t\tcase \"failed\":\n\t\tcase \"cancelled\":\n\t\t\treturn \"error\";\n\t\t// These two are wonky ...\n\t\tcase \"in_progress\":\n\t\tcase \"queued\":\n\t\t\treturn \"stop\";\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = status;\n\t\t\tthrow new Error(`Unhandled stop reason: ${_exhaustive}`);\n\t\t}\n\t}\n}\n"]}
1
+ {"version":3,"file":"openai-responses.js","sourceRoot":"","sources":["../../src/providers/openai-responses.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,QAAQ,CAAC;AAY5B,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAc7C,OAAO,EAAE,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;AACvE,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAC5D,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAElE,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAw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MAAM,CAAC;QACf,SAAS,CAAC;YACT,MAAM,WAAW,GAAU,MAAM,CAAC;YAClC,MAAM,IAAI,KAAK,CAAC,0BAA0B,WAAW,EAAE,CAAC,CAAC;QAC1D,CAAC;IACF,CAAC;AAAA,CACD","sourcesContent":["import OpenAI from \"openai\";\nimport type {\n\tTool as OpenAITool,\n\tResponseCreateParamsStreaming,\n\tResponseFunctionToolCall,\n\tResponseInput,\n\tResponseInputContent,\n\tResponseInputImage,\n\tResponseInputText,\n\tResponseOutputMessage,\n\tResponseReasoningItem,\n} from \"openai/resources/responses/responses.js\";\nimport { calculateCost } from \"../models.js\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tContext,\n\tModel,\n\tStopReason,\n\tStreamFunction,\n\tStreamOptions,\n\tTextContent,\n\tThinkingContent,\n\tTool,\n\tToolCall,\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 { transformMessages } from \"./transorm-messages.js\";\n\n/** Fast deterministic hash to shorten long strings */\nfunction shortHash(str: string): string {\n\tlet h1 = 0xdeadbeef;\n\tlet h2 = 0x41c6ce57;\n\tfor (let i = 0; i < str.length; i++) {\n\t\tconst ch = str.charCodeAt(i);\n\t\th1 = Math.imul(h1 ^ ch, 2654435761);\n\t\th2 = Math.imul(h2 ^ ch, 1597334677);\n\t}\n\th1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);\n\th2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);\n\treturn (h2 >>> 0).toString(36) + (h1 >>> 0).toString(36);\n}\n\n// OpenAI Responses-specific options\nexport interface OpenAIResponsesOptions extends StreamOptions {\n\treasoningEffort?: \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\";\n\treasoningSummary?: \"auto\" | \"detailed\" | \"concise\" | null;\n}\n\n/**\n * Generate function for OpenAI Responses API\n */\nexport const streamOpenAIResponses: StreamFunction<\"openai-responses\"> = (\n\tmodel: Model<\"openai-responses\">,\n\tcontext: Context,\n\toptions?: OpenAIResponsesOptions,\n): AssistantMessageEventStream => {\n\tconst stream = new AssistantMessageEventStream();\n\n\t// Start async processing\n\t(async () => {\n\t\tconst output: AssistantMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [],\n\t\t\tapi: \"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 OpenAI client\n\t\t\tconst client = createClient(model, context, options?.apiKey);\n\t\t\tconst params = buildParams(model, context, options);\n\t\t\tconst openaiStream = await client.responses.create(params, { signal: options?.signal });\n\t\t\tstream.push({ type: \"start\", partial: output });\n\n\t\t\tlet currentItem: ResponseReasoningItem | ResponseOutputMessage | ResponseFunctionToolCall | null = null;\n\t\t\tlet currentBlock: ThinkingContent | TextContent | (ToolCall & { partialJson: string }) | null = null;\n\t\t\tconst blocks = output.content;\n\t\t\tconst blockIndex = () => blocks.length - 1;\n\n\t\t\tfor await (const event of openaiStream) {\n\t\t\t\t// Handle output item start\n\t\t\t\tif (event.type === \"response.output_item.added\") {\n\t\t\t\t\tconst item = event.item;\n\t\t\t\t\tif (item.type === \"reasoning\") {\n\t\t\t\t\t\tcurrentItem = item;\n\t\t\t\t\t\tcurrentBlock = { type: \"thinking\", thinking: \"\" };\n\t\t\t\t\t\toutput.content.push(currentBlock);\n\t\t\t\t\t\tstream.push({ type: \"thinking_start\", contentIndex: blockIndex(), partial: output });\n\t\t\t\t\t} else if (item.type === \"message\") {\n\t\t\t\t\t\tcurrentItem = item;\n\t\t\t\t\t\tcurrentBlock = { type: \"text\", text: \"\" };\n\t\t\t\t\t\toutput.content.push(currentBlock);\n\t\t\t\t\t\tstream.push({ type: \"text_start\", contentIndex: blockIndex(), partial: output });\n\t\t\t\t\t} else if (item.type === \"function_call\") {\n\t\t\t\t\t\tcurrentItem = item;\n\t\t\t\t\t\tcurrentBlock = {\n\t\t\t\t\t\t\ttype: \"toolCall\",\n\t\t\t\t\t\t\tid: item.call_id + \"|\" + item.id,\n\t\t\t\t\t\t\tname: item.name,\n\t\t\t\t\t\t\targuments: {},\n\t\t\t\t\t\t\tpartialJson: item.arguments || \"\",\n\t\t\t\t\t\t};\n\t\t\t\t\t\toutput.content.push(currentBlock);\n\t\t\t\t\t\tstream.push({ type: \"toolcall_start\", contentIndex: blockIndex(), partial: output });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Handle reasoning summary deltas\n\t\t\t\telse if (event.type === \"response.reasoning_summary_part.added\") {\n\t\t\t\t\tif (currentItem && currentItem.type === \"reasoning\") {\n\t\t\t\t\t\tcurrentItem.summary = currentItem.summary || [];\n\t\t\t\t\t\tcurrentItem.summary.push(event.part);\n\t\t\t\t\t}\n\t\t\t\t} else if (event.type === \"response.reasoning_summary_text.delta\") {\n\t\t\t\t\tif (\n\t\t\t\t\t\tcurrentItem &&\n\t\t\t\t\t\tcurrentItem.type === \"reasoning\" &&\n\t\t\t\t\t\tcurrentBlock &&\n\t\t\t\t\t\tcurrentBlock.type === \"thinking\"\n\t\t\t\t\t) {\n\t\t\t\t\t\tcurrentItem.summary = currentItem.summary || [];\n\t\t\t\t\t\tconst lastPart = currentItem.summary[currentItem.summary.length - 1];\n\t\t\t\t\t\tif (lastPart) {\n\t\t\t\t\t\t\tcurrentBlock.thinking += event.delta;\n\t\t\t\t\t\t\tlastPart.text += event.delta;\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: blockIndex(),\n\t\t\t\t\t\t\t\tdelta: event.delta,\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}\n\t\t\t\t// Add a new line between summary parts (hack...)\n\t\t\t\telse if (event.type === \"response.reasoning_summary_part.done\") {\n\t\t\t\t\tif (\n\t\t\t\t\t\tcurrentItem &&\n\t\t\t\t\t\tcurrentItem.type === \"reasoning\" &&\n\t\t\t\t\t\tcurrentBlock &&\n\t\t\t\t\t\tcurrentBlock.type === \"thinking\"\n\t\t\t\t\t) {\n\t\t\t\t\t\tcurrentItem.summary = currentItem.summary || [];\n\t\t\t\t\t\tconst lastPart = currentItem.summary[currentItem.summary.length - 1];\n\t\t\t\t\t\tif (lastPart) {\n\t\t\t\t\t\t\tcurrentBlock.thinking += \"\\n\\n\";\n\t\t\t\t\t\t\tlastPart.text += \"\\n\\n\";\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: blockIndex(),\n\t\t\t\t\t\t\t\tdelta: \"\\n\\n\",\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}\n\t\t\t\t// Handle text output deltas\n\t\t\t\telse if (event.type === \"response.content_part.added\") {\n\t\t\t\t\tif (currentItem && currentItem.type === \"message\") {\n\t\t\t\t\t\tcurrentItem.content = currentItem.content || [];\n\t\t\t\t\t\t// Filter out ReasoningText, only accept output_text and refusal\n\t\t\t\t\t\tif (event.part.type === \"output_text\" || event.part.type === \"refusal\") {\n\t\t\t\t\t\t\tcurrentItem.content.push(event.part);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else if (event.type === \"response.output_text.delta\") {\n\t\t\t\t\tif (currentItem && currentItem.type === \"message\" && currentBlock && currentBlock.type === \"text\") {\n\t\t\t\t\t\tconst lastPart = currentItem.content[currentItem.content.length - 1];\n\t\t\t\t\t\tif (lastPart && lastPart.type === \"output_text\") {\n\t\t\t\t\t\t\tcurrentBlock.text += event.delta;\n\t\t\t\t\t\t\tlastPart.text += event.delta;\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: blockIndex(),\n\t\t\t\t\t\t\t\tdelta: event.delta,\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 === \"response.refusal.delta\") {\n\t\t\t\t\tif (currentItem && currentItem.type === \"message\" && currentBlock && currentBlock.type === \"text\") {\n\t\t\t\t\t\tconst lastPart = currentItem.content[currentItem.content.length - 1];\n\t\t\t\t\t\tif (lastPart && lastPart.type === \"refusal\") {\n\t\t\t\t\t\t\tcurrentBlock.text += event.delta;\n\t\t\t\t\t\t\tlastPart.refusal += event.delta;\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: blockIndex(),\n\t\t\t\t\t\t\t\tdelta: event.delta,\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}\n\t\t\t\t// Handle function call argument deltas\n\t\t\t\telse if (event.type === \"response.function_call_arguments.delta\") {\n\t\t\t\t\tif (\n\t\t\t\t\t\tcurrentItem &&\n\t\t\t\t\t\tcurrentItem.type === \"function_call\" &&\n\t\t\t\t\t\tcurrentBlock &&\n\t\t\t\t\t\tcurrentBlock.type === \"toolCall\"\n\t\t\t\t\t) {\n\t\t\t\t\t\tcurrentBlock.partialJson += event.delta;\n\t\t\t\t\t\tcurrentBlock.arguments = parseStreamingJson(currentBlock.partialJson);\n\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\ttype: \"toolcall_delta\",\n\t\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\t\tdelta: event.delta,\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\t\t\t\t// Handle output item completion\n\t\t\t\telse if (event.type === \"response.output_item.done\") {\n\t\t\t\t\tconst item = event.item;\n\n\t\t\t\t\tif (item.type === \"reasoning\" && currentBlock && currentBlock.type === \"thinking\") {\n\t\t\t\t\t\tcurrentBlock.thinking = item.summary?.map((s) => s.text).join(\"\\n\\n\") || \"\";\n\t\t\t\t\t\tcurrentBlock.thinkingSignature = JSON.stringify(item);\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\tcurrentBlock = null;\n\t\t\t\t\t} else if (item.type === \"message\" && currentBlock && currentBlock.type === \"text\") {\n\t\t\t\t\t\tcurrentBlock.text = item.content.map((c) => (c.type === \"output_text\" ? c.text : c.refusal)).join(\"\");\n\t\t\t\t\t\tcurrentBlock.textSignature = item.id;\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\tcurrentBlock = null;\n\t\t\t\t\t} else if (item.type === \"function_call\") {\n\t\t\t\t\t\tconst toolCall: ToolCall = {\n\t\t\t\t\t\t\ttype: \"toolCall\",\n\t\t\t\t\t\t\tid: item.call_id + \"|\" + item.id,\n\t\t\t\t\t\t\tname: item.name,\n\t\t\t\t\t\t\targuments: JSON.parse(item.arguments),\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tstream.push({ type: \"toolcall_end\", contentIndex: blockIndex(), toolCall, partial: output });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Handle completion\n\t\t\t\telse if (event.type === \"response.completed\") {\n\t\t\t\t\tconst response = event.response;\n\t\t\t\t\tif (response?.usage) {\n\t\t\t\t\t\tconst cachedTokens = response.usage.input_tokens_details?.cached_tokens || 0;\n\t\t\t\t\t\toutput.usage = {\n\t\t\t\t\t\t\t// OpenAI includes cached tokens in input_tokens, so subtract to get non-cached input\n\t\t\t\t\t\t\tinput: (response.usage.input_tokens || 0) - cachedTokens,\n\t\t\t\t\t\t\toutput: response.usage.output_tokens || 0,\n\t\t\t\t\t\t\tcacheRead: cachedTokens,\n\t\t\t\t\t\t\tcacheWrite: 0,\n\t\t\t\t\t\t\ttotalTokens: response.usage.total_tokens || 0,\n\t\t\t\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tcalculateCost(model, output.usage);\n\t\t\t\t\t// Map status to stop reason\n\t\t\t\t\toutput.stopReason = mapStopReason(response?.status);\n\t\t\t\t\tif (output.content.some((b) => b.type === \"toolCall\") && output.stopReason === \"stop\") {\n\t\t\t\t\t\toutput.stopReason = \"toolUse\";\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Handle errors\n\t\t\t\telse if (event.type === \"error\") {\n\t\t\t\t\tthrow new Error(`Error Code ${event.code}: ${event.message}` || \"Unknown error\");\n\t\t\t\t} else if (event.type === \"response.failed\") {\n\t\t\t\t\tthrow new Error(\"Unknown error\");\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 unkown error ocurred\");\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\nfunction createClient(model: Model<\"openai-responses\">, context: Context, apiKey?: string) {\n\tif (!apiKey) {\n\t\tif (!process.env.OPENAI_API_KEY) {\n\t\t\tthrow new Error(\n\t\t\t\t\"OpenAI API key is required. Set OPENAI_API_KEY environment variable or pass it as an argument.\",\n\t\t\t);\n\t\t}\n\t\tapiKey = process.env.OPENAI_API_KEY;\n\t}\n\n\tconst headers = { ...model.headers };\n\tif (model.provider === \"github-copilot\") {\n\t\t// Copilot expects X-Initiator to indicate whether the request is user-initiated\n\t\t// or agent-initiated (e.g. follow-up after assistant/tool messages). If there is\n\t\t// no prior message, default to user-initiated.\n\t\tconst messages = context.messages || [];\n\t\tconst lastMessage = messages[messages.length - 1];\n\t\tconst isAgentCall = lastMessage ? lastMessage.role !== \"user\" : false;\n\t\theaders[\"X-Initiator\"] = isAgentCall ? \"agent\" : \"user\";\n\t\theaders[\"Openai-Intent\"] = \"conversation-edits\";\n\n\t\t// Copilot requires this header when sending images\n\t\tconst hasImages = messages.some((msg) => {\n\t\t\tif (msg.role === \"user\" && Array.isArray(msg.content)) {\n\t\t\t\treturn msg.content.some((c) => c.type === \"image\");\n\t\t\t}\n\t\t\tif (msg.role === \"toolResult\" && Array.isArray(msg.content)) {\n\t\t\t\treturn msg.content.some((c) => c.type === \"image\");\n\t\t\t}\n\t\t\treturn false;\n\t\t});\n\t\tif (hasImages) {\n\t\t\theaders[\"Copilot-Vision-Request\"] = \"true\";\n\t\t}\n\t}\n\n\treturn new OpenAI({\n\t\tapiKey,\n\t\tbaseURL: model.baseUrl,\n\t\tdangerouslyAllowBrowser: true,\n\t\tdefaultHeaders: headers,\n\t});\n}\n\nfunction buildParams(model: Model<\"openai-responses\">, context: Context, options?: OpenAIResponsesOptions) {\n\tconst messages = convertMessages(model, context);\n\n\tconst params: ResponseCreateParamsStreaming = {\n\t\tmodel: model.id,\n\t\tinput: messages,\n\t\tstream: true,\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 = convertTools(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.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\nfunction convertMessages(model: Model<\"openai-responses\">, context: Context): ResponseInput {\n\tconst messages: ResponseInput = [];\n\n\tconst transformedMessages = transformMessages(context.messages, model);\n\n\tif (context.systemPrompt) {\n\t\tconst role = model.reasoning ? \"developer\" : \"system\";\n\t\tmessages.push({\n\t\t\trole,\n\t\t\tcontent: sanitizeSurrogates(context.systemPrompt),\n\t\t});\n\t}\n\n\tlet msgIndex = 0;\n\tfor (const msg of transformedMessages) {\n\t\tif (msg.role === \"user\") {\n\t\t\tif (typeof msg.content === \"string\") {\n\t\t\t\tmessages.push({\n\t\t\t\t\trole: \"user\",\n\t\t\t\t\tcontent: [{ type: \"input_text\", text: sanitizeSurrogates(msg.content) }],\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tconst content: ResponseInputContent[] = msg.content.map((item): ResponseInputContent => {\n\t\t\t\t\tif (item.type === \"text\") {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\ttype: \"input_text\",\n\t\t\t\t\t\t\ttext: sanitizeSurrogates(item.text),\n\t\t\t\t\t\t} satisfies ResponseInputText;\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\ttype: \"input_image\",\n\t\t\t\t\t\t\tdetail: \"auto\",\n\t\t\t\t\t\t\timage_url: `data:${item.mimeType};base64,${item.data}`,\n\t\t\t\t\t\t} satisfies ResponseInputImage;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tconst filteredContent = !model.input.includes(\"image\")\n\t\t\t\t\t? content.filter((c) => c.type !== \"input_image\")\n\t\t\t\t\t: content;\n\t\t\t\tif (filteredContent.length === 0) continue;\n\t\t\t\tmessages.push({\n\t\t\t\t\trole: \"user\",\n\t\t\t\t\tcontent: filteredContent,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (msg.role === \"assistant\") {\n\t\t\tconst output: ResponseInput = [];\n\n\t\t\tfor (const block of msg.content) {\n\t\t\t\t// Do not submit thinking blocks if the completion had an error (i.e. abort)\n\t\t\t\tif (block.type === \"thinking\" && msg.stopReason !== \"error\") {\n\t\t\t\t\tif (block.thinkingSignature) {\n\t\t\t\t\t\tconst reasoningItem = JSON.parse(block.thinkingSignature);\n\t\t\t\t\t\toutput.push(reasoningItem);\n\t\t\t\t\t}\n\t\t\t\t} else if (block.type === \"text\") {\n\t\t\t\t\tconst textBlock = block as TextContent;\n\t\t\t\t\t// OpenAI requires id to be max 64 characters\n\t\t\t\t\tlet msgId = textBlock.textSignature;\n\t\t\t\t\tif (!msgId) {\n\t\t\t\t\t\tmsgId = \"msg_\" + msgIndex;\n\t\t\t\t\t} else if (msgId.length > 64) {\n\t\t\t\t\t\tmsgId = \"msg_\" + shortHash(msgId);\n\t\t\t\t\t}\n\t\t\t\t\toutput.push({\n\t\t\t\t\t\ttype: \"message\",\n\t\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\t\tcontent: [{ type: \"output_text\", text: sanitizeSurrogates(textBlock.text), annotations: [] }],\n\t\t\t\t\t\tstatus: \"completed\",\n\t\t\t\t\t\tid: msgId,\n\t\t\t\t\t} satisfies ResponseOutputMessage);\n\t\t\t\t\t// Do not submit toolcall blocks if the completion had an error (i.e. abort)\n\t\t\t\t} else if (block.type === \"toolCall\" && msg.stopReason !== \"error\") {\n\t\t\t\t\tconst toolCall = block as ToolCall;\n\t\t\t\t\toutput.push({\n\t\t\t\t\t\ttype: \"function_call\",\n\t\t\t\t\t\tid: toolCall.id.split(\"|\")[1],\n\t\t\t\t\t\tcall_id: toolCall.id.split(\"|\")[0],\n\t\t\t\t\t\tname: toolCall.name,\n\t\t\t\t\t\targuments: JSON.stringify(toolCall.arguments),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (output.length === 0) continue;\n\t\t\tmessages.push(...output);\n\t\t} else if (msg.role === \"toolResult\") {\n\t\t\t// Extract text and image content\n\t\t\tconst textResult = msg.content\n\t\t\t\t.filter((c) => c.type === \"text\")\n\t\t\t\t.map((c) => (c as any).text)\n\t\t\t\t.join(\"\\n\");\n\t\t\tconst hasImages = msg.content.some((c) => c.type === \"image\");\n\n\t\t\t// Always send function_call_output with text (or placeholder if only images)\n\t\t\tconst hasText = textResult.length > 0;\n\t\t\tmessages.push({\n\t\t\t\ttype: \"function_call_output\",\n\t\t\t\tcall_id: msg.toolCallId.split(\"|\")[0],\n\t\t\t\toutput: sanitizeSurrogates(hasText ? textResult : \"(see attached image)\"),\n\t\t\t});\n\n\t\t\t// If there are images and model supports them, send a follow-up user message with images\n\t\t\tif (hasImages && model.input.includes(\"image\")) {\n\t\t\t\tconst contentParts: ResponseInputContent[] = [];\n\n\t\t\t\t// Add text prefix\n\t\t\t\tcontentParts.push({\n\t\t\t\t\ttype: \"input_text\",\n\t\t\t\t\ttext: \"Attached image(s) from tool result:\",\n\t\t\t\t} satisfies ResponseInputText);\n\n\t\t\t\t// Add images\n\t\t\t\tfor (const block of msg.content) {\n\t\t\t\t\tif (block.type === \"image\") {\n\t\t\t\t\t\tcontentParts.push({\n\t\t\t\t\t\t\ttype: \"input_image\",\n\t\t\t\t\t\t\tdetail: \"auto\",\n\t\t\t\t\t\t\timage_url: `data:${(block as any).mimeType};base64,${(block as any).data}`,\n\t\t\t\t\t\t} satisfies ResponseInputImage);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tmessages.push({\n\t\t\t\t\trole: \"user\",\n\t\t\t\t\tcontent: contentParts,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tmsgIndex++;\n\t}\n\n\treturn messages;\n}\n\nfunction convertTools(tools: Tool[]): OpenAITool[] {\n\treturn tools.map((tool) => ({\n\t\ttype: \"function\",\n\t\tname: tool.name,\n\t\tdescription: tool.description,\n\t\tparameters: tool.parameters as any, // TypeBox already generates JSON Schema\n\t\tstrict: null,\n\t}));\n}\n\nfunction mapStopReason(status: OpenAI.Responses.ResponseStatus | undefined): StopReason {\n\tif (!status) return \"stop\";\n\tswitch (status) {\n\t\tcase \"completed\":\n\t\t\treturn \"stop\";\n\t\tcase \"incomplete\":\n\t\t\treturn \"length\";\n\t\tcase \"failed\":\n\t\tcase \"cancelled\":\n\t\t\treturn \"error\";\n\t\t// These two are wonky ...\n\t\tcase \"in_progress\":\n\t\tcase \"queued\":\n\t\t\treturn \"stop\";\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = status;\n\t\t\tthrow new Error(`Unhandled stop reason: ${_exhaustive}`);\n\t\t}\n\t}\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"transorm-messages.d.ts","sourceRoot":"","sources":["../../src/providers/transorm-messages.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAoB,OAAO,EAAE,KAAK,EAAY,MAAM,aAAa,CAAC;AAWnF,wBAAgB,iBAAiB,CAAC,IAAI,SAAS,GAAG,EAAE,QAAQ,EAAE,OAAO,EAAE,EAAE,KAAK,EAAE,KAAK,CAAC,IAAI,CAAC,GAAG,OAAO,EAAE,CAsHtG","sourcesContent":["import type { Api, AssistantMessage, Message, Model, ToolCall } from \"../types.js\";\n\n/**\n * Normalize tool call ID for GitHub Copilot cross-API compatibility.\n * OpenAI Responses API generates IDs that are 450+ chars with special characters like `|`.\n * Other APIs (Claude, etc.) require max 40 chars and only alphanumeric + underscore + hyphen.\n */\nfunction normalizeCopilotToolCallId(id: string): string {\n\treturn id.replace(/[^a-zA-Z0-9_-]/g, \"\").slice(0, 40);\n}\n\nexport function transformMessages<TApi extends Api>(messages: Message[], model: Model<TApi>): Message[] {\n\t// Build a map of original tool call IDs to normalized IDs for github-copilot cross-API switches\n\tconst toolCallIdMap = new Map<string, string>();\n\n\treturn messages\n\t\t.map((msg) => {\n\t\t\t// User messages pass through unchanged\n\t\t\tif (msg.role === \"user\") {\n\t\t\t\treturn msg;\n\t\t\t}\n\n\t\t\t// Handle toolResult messages - normalize toolCallId if we have a mapping\n\t\t\tif (msg.role === \"toolResult\") {\n\t\t\t\tconst normalizedId = toolCallIdMap.get(msg.toolCallId);\n\t\t\t\tif (normalizedId && normalizedId !== msg.toolCallId) {\n\t\t\t\t\treturn { ...msg, toolCallId: normalizedId };\n\t\t\t\t}\n\t\t\t\treturn msg;\n\t\t\t}\n\n\t\t\t// Assistant messages need transformation check\n\t\t\tif (msg.role === \"assistant\") {\n\t\t\t\tconst assistantMsg = msg as AssistantMessage;\n\n\t\t\t\t// If message is from the same provider and API, keep as is\n\t\t\t\tif (assistantMsg.provider === model.provider && assistantMsg.api === model.api) {\n\t\t\t\t\treturn msg;\n\t\t\t\t}\n\n\t\t\t\t// Check if we need to normalize tool call IDs (github-copilot cross-API)\n\t\t\t\tconst needsToolCallIdNormalization =\n\t\t\t\t\tassistantMsg.provider === \"github-copilot\" &&\n\t\t\t\t\tmodel.provider === \"github-copilot\" &&\n\t\t\t\t\tassistantMsg.api !== model.api;\n\n\t\t\t\t// Transform message from different provider/model\n\t\t\t\tconst transformedContent = assistantMsg.content.map((block) => {\n\t\t\t\t\tif (block.type === \"thinking\") {\n\t\t\t\t\t\t// Convert thinking block to text block with <thinking> tags\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\t\t\ttext: `<thinking>\\n${block.thinking}\\n</thinking>`,\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\t// Normalize tool call IDs for github-copilot cross-API switches\n\t\t\t\t\tif (block.type === \"toolCall\" && needsToolCallIdNormalization) {\n\t\t\t\t\t\tconst toolCall = block as ToolCall;\n\t\t\t\t\t\tconst normalizedId = normalizeCopilotToolCallId(toolCall.id);\n\t\t\t\t\t\tif (normalizedId !== toolCall.id) {\n\t\t\t\t\t\t\ttoolCallIdMap.set(toolCall.id, normalizedId);\n\t\t\t\t\t\t\treturn { ...toolCall, id: normalizedId };\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t// All other blocks pass through unchanged\n\t\t\t\t\treturn block;\n\t\t\t\t});\n\n\t\t\t\t// Return transformed assistant message\n\t\t\t\treturn {\n\t\t\t\t\t...assistantMsg,\n\t\t\t\t\tcontent: transformedContent,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn msg;\n\t\t})\n\t\t.map((msg, index, allMessages) => {\n\t\t\t// Second pass: filter out tool calls without corresponding tool results\n\t\t\tif (msg.role !== \"assistant\") {\n\t\t\t\treturn msg;\n\t\t\t}\n\n\t\t\tconst assistantMsg = msg as AssistantMessage;\n\t\t\tconst isLastMessage = index === allMessages.length - 1;\n\n\t\t\t// If this is the last message, keep all tool calls (ongoing turn)\n\t\t\tif (isLastMessage) {\n\t\t\t\treturn msg;\n\t\t\t}\n\n\t\t\t// Extract tool call IDs from this message\n\t\t\tconst toolCallIds = assistantMsg.content\n\t\t\t\t.filter((block) => block.type === \"toolCall\")\n\t\t\t\t.map((block) => (block.type === \"toolCall\" ? block.id : \"\"));\n\n\t\t\t// If no tool calls, return as is\n\t\t\tif (toolCallIds.length === 0) {\n\t\t\t\treturn msg;\n\t\t\t}\n\n\t\t\t// Scan forward through subsequent messages to find matching tool results\n\t\t\tconst matchedToolCallIds = new Set<string>();\n\t\t\tfor (let i = index + 1; i < allMessages.length; i++) {\n\t\t\t\tconst nextMsg = allMessages[i];\n\n\t\t\t\t// Stop scanning when we hit another assistant message\n\t\t\t\tif (nextMsg.role === \"assistant\") {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\t// Check tool result messages for matching IDs\n\t\t\t\tif (nextMsg.role === \"toolResult\") {\n\t\t\t\t\tmatchedToolCallIds.add(nextMsg.toolCallId);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Filter out tool calls that don't have corresponding results\n\t\t\tconst filteredContent = assistantMsg.content.filter((block) => {\n\t\t\t\tif (block.type === \"toolCall\") {\n\t\t\t\t\treturn matchedToolCallIds.has(block.id);\n\t\t\t\t}\n\t\t\t\treturn true; // Keep all non-toolCall blocks\n\t\t\t});\n\n\t\t\treturn {\n\t\t\t\t...assistantMsg,\n\t\t\t\tcontent: filteredContent,\n\t\t\t};\n\t\t});\n}\n"]}
1
+ {"version":3,"file":"transorm-messages.d.ts","sourceRoot":"","sources":["../../src/providers/transorm-messages.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAoB,OAAO,EAAE,KAAK,EAA+B,MAAM,aAAa,CAAC;AAWtG,wBAAgB,iBAAiB,CAAC,IAAI,SAAS,GAAG,EAAE,QAAQ,EAAE,OAAO,EAAE,EAAE,KAAK,EAAE,KAAK,CAAC,IAAI,CAAC,GAAG,OAAO,EAAE,CAmItG","sourcesContent":["import type { Api, AssistantMessage, Message, Model, ToolCall, ToolResultMessage } from \"../types.js\";\n\n/**\n * Normalize tool call ID for GitHub Copilot cross-API compatibility.\n * OpenAI Responses API generates IDs that are 450+ chars with special characters like `|`.\n * Other APIs (Claude, etc.) require max 40 chars and only alphanumeric + underscore + hyphen.\n */\nfunction normalizeCopilotToolCallId(id: string): string {\n\treturn id.replace(/[^a-zA-Z0-9_-]/g, \"\").slice(0, 40);\n}\n\nexport function transformMessages<TApi extends Api>(messages: Message[], model: Model<TApi>): Message[] {\n\t// Build a map of original tool call IDs to normalized IDs for github-copilot cross-API switches\n\tconst toolCallIdMap = new Map<string, string>();\n\n\t// First pass: transform messages (thinking blocks, tool call ID normalization)\n\tconst transformed = messages.map((msg) => {\n\t\t// User messages pass through unchanged\n\t\tif (msg.role === \"user\") {\n\t\t\treturn msg;\n\t\t}\n\n\t\t// Handle toolResult messages - normalize toolCallId if we have a mapping\n\t\tif (msg.role === \"toolResult\") {\n\t\t\tconst normalizedId = toolCallIdMap.get(msg.toolCallId);\n\t\t\tif (normalizedId && normalizedId !== msg.toolCallId) {\n\t\t\t\treturn { ...msg, toolCallId: normalizedId };\n\t\t\t}\n\t\t\treturn msg;\n\t\t}\n\n\t\t// Assistant messages need transformation check\n\t\tif (msg.role === \"assistant\") {\n\t\t\tconst assistantMsg = msg as AssistantMessage;\n\n\t\t\t// If message is from the same provider and API, keep as is\n\t\t\tif (assistantMsg.provider === model.provider && assistantMsg.api === model.api) {\n\t\t\t\treturn msg;\n\t\t\t}\n\n\t\t\t// Check if we need to normalize tool call IDs (github-copilot cross-API)\n\t\t\tconst needsToolCallIdNormalization =\n\t\t\t\tassistantMsg.provider === \"github-copilot\" &&\n\t\t\t\tmodel.provider === \"github-copilot\" &&\n\t\t\t\tassistantMsg.api !== model.api;\n\n\t\t\t// Transform message from different provider/model\n\t\t\tconst transformedContent = assistantMsg.content.map((block) => {\n\t\t\t\tif (block.type === \"thinking\") {\n\t\t\t\t\t// Convert thinking block to text block with <thinking> tags\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\t\ttext: `<thinking>\\n${block.thinking}\\n</thinking>`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\t// Normalize tool call IDs for github-copilot cross-API switches\n\t\t\t\tif (block.type === \"toolCall\" && needsToolCallIdNormalization) {\n\t\t\t\t\tconst toolCall = block as ToolCall;\n\t\t\t\t\tconst normalizedId = normalizeCopilotToolCallId(toolCall.id);\n\t\t\t\t\tif (normalizedId !== toolCall.id) {\n\t\t\t\t\t\ttoolCallIdMap.set(toolCall.id, normalizedId);\n\t\t\t\t\t\treturn { ...toolCall, id: normalizedId };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// All other blocks pass through unchanged\n\t\t\t\treturn block;\n\t\t\t});\n\n\t\t\t// Return transformed assistant message\n\t\t\treturn {\n\t\t\t\t...assistantMsg,\n\t\t\t\tcontent: transformedContent,\n\t\t\t};\n\t\t}\n\t\treturn msg;\n\t});\n\n\t// Second pass: insert synthetic empty tool results for orphaned tool calls\n\t// This preserves thinking signatures and satisfies API requirements\n\tconst result: Message[] = [];\n\tlet pendingToolCalls: ToolCall[] = [];\n\tlet existingToolResultIds = new Set<string>();\n\n\tfor (let i = 0; i < transformed.length; i++) {\n\t\tconst msg = transformed[i];\n\n\t\tif (msg.role === \"assistant\") {\n\t\t\t// If we have pending orphaned tool calls from a previous assistant, insert synthetic results now\n\t\t\tif (pendingToolCalls.length > 0) {\n\t\t\t\tfor (const tc of pendingToolCalls) {\n\t\t\t\t\tif (!existingToolResultIds.has(tc.id)) {\n\t\t\t\t\t\tresult.push({\n\t\t\t\t\t\t\trole: \"toolResult\",\n\t\t\t\t\t\t\ttoolCallId: tc.id,\n\t\t\t\t\t\t\ttoolName: tc.name,\n\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: \"No result provided\" }],\n\t\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\t} as ToolResultMessage);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tpendingToolCalls = [];\n\t\t\t\texistingToolResultIds = new Set();\n\t\t\t}\n\n\t\t\t// Track tool calls from this assistant message\n\t\t\tconst assistantMsg = msg as AssistantMessage;\n\t\t\tconst toolCalls = assistantMsg.content.filter((b) => b.type === \"toolCall\") as ToolCall[];\n\t\t\tif (toolCalls.length > 0) {\n\t\t\t\tpendingToolCalls = toolCalls;\n\t\t\t\texistingToolResultIds = new Set();\n\t\t\t}\n\n\t\t\tresult.push(msg);\n\t\t} else if (msg.role === \"toolResult\") {\n\t\t\texistingToolResultIds.add(msg.toolCallId);\n\t\t\tresult.push(msg);\n\t\t} else if (msg.role === \"user\") {\n\t\t\t// User message interrupts tool flow - insert synthetic results for orphaned calls\n\t\t\tif (pendingToolCalls.length > 0) {\n\t\t\t\tfor (const tc of pendingToolCalls) {\n\t\t\t\t\tif (!existingToolResultIds.has(tc.id)) {\n\t\t\t\t\t\tresult.push({\n\t\t\t\t\t\t\trole: \"toolResult\",\n\t\t\t\t\t\t\ttoolCallId: tc.id,\n\t\t\t\t\t\t\ttoolName: tc.name,\n\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: \"No result provided\" }],\n\t\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\t} as ToolResultMessage);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tpendingToolCalls = [];\n\t\t\t\texistingToolResultIds = new Set();\n\t\t\t}\n\t\t\tresult.push(msg);\n\t\t} else {\n\t\t\tresult.push(msg);\n\t\t}\n\t}\n\n\treturn result;\n}\n"]}
@@ -9,8 +9,8 @@ function normalizeCopilotToolCallId(id) {
9
9
  export function transformMessages(messages, model) {
10
10
  // Build a map of original tool call IDs to normalized IDs for github-copilot cross-API switches
11
11
  const toolCallIdMap = new Map();
12
- return messages
13
- .map((msg) => {
12
+ // First pass: transform messages (thinking blocks, tool call ID normalization)
13
+ const transformed = messages.map((msg) => {
14
14
  // User messages pass through unchanged
15
15
  if (msg.role === "user") {
16
16
  return msg;
@@ -62,50 +62,69 @@ export function transformMessages(messages, model) {
62
62
  };
63
63
  }
64
64
  return msg;
65
- })
66
- .map((msg, index, allMessages) => {
67
- // Second pass: filter out tool calls without corresponding tool results
68
- if (msg.role !== "assistant") {
69
- return msg;
70
- }
71
- const assistantMsg = msg;
72
- const isLastMessage = index === allMessages.length - 1;
73
- // If this is the last message, keep all tool calls (ongoing turn)
74
- if (isLastMessage) {
75
- return msg;
76
- }
77
- // Extract tool call IDs from this message
78
- const toolCallIds = assistantMsg.content
79
- .filter((block) => block.type === "toolCall")
80
- .map((block) => (block.type === "toolCall" ? block.id : ""));
81
- // If no tool calls, return as is
82
- if (toolCallIds.length === 0) {
83
- return msg;
84
- }
85
- // Scan forward through subsequent messages to find matching tool results
86
- const matchedToolCallIds = new Set();
87
- for (let i = index + 1; i < allMessages.length; i++) {
88
- const nextMsg = allMessages[i];
89
- // Stop scanning when we hit another assistant message
90
- if (nextMsg.role === "assistant") {
91
- break;
65
+ });
66
+ // Second pass: insert synthetic empty tool results for orphaned tool calls
67
+ // This preserves thinking signatures and satisfies API requirements
68
+ const result = [];
69
+ let pendingToolCalls = [];
70
+ let existingToolResultIds = new Set();
71
+ for (let i = 0; i < transformed.length; i++) {
72
+ const msg = transformed[i];
73
+ if (msg.role === "assistant") {
74
+ // If we have pending orphaned tool calls from a previous assistant, insert synthetic results now
75
+ if (pendingToolCalls.length > 0) {
76
+ for (const tc of pendingToolCalls) {
77
+ if (!existingToolResultIds.has(tc.id)) {
78
+ result.push({
79
+ role: "toolResult",
80
+ toolCallId: tc.id,
81
+ toolName: tc.name,
82
+ content: [{ type: "text", text: "No result provided" }],
83
+ isError: true,
84
+ timestamp: Date.now(),
85
+ });
86
+ }
87
+ }
88
+ pendingToolCalls = [];
89
+ existingToolResultIds = new Set();
92
90
  }
93
- // Check tool result messages for matching IDs
94
- if (nextMsg.role === "toolResult") {
95
- matchedToolCallIds.add(nextMsg.toolCallId);
91
+ // Track tool calls from this assistant message
92
+ const assistantMsg = msg;
93
+ const toolCalls = assistantMsg.content.filter((b) => b.type === "toolCall");
94
+ if (toolCalls.length > 0) {
95
+ pendingToolCalls = toolCalls;
96
+ existingToolResultIds = new Set();
96
97
  }
98
+ result.push(msg);
97
99
  }
98
- // Filter out tool calls that don't have corresponding results
99
- const filteredContent = assistantMsg.content.filter((block) => {
100
- if (block.type === "toolCall") {
101
- return matchedToolCallIds.has(block.id);
100
+ else if (msg.role === "toolResult") {
101
+ existingToolResultIds.add(msg.toolCallId);
102
+ result.push(msg);
103
+ }
104
+ else if (msg.role === "user") {
105
+ // User message interrupts tool flow - insert synthetic results for orphaned calls
106
+ if (pendingToolCalls.length > 0) {
107
+ for (const tc of pendingToolCalls) {
108
+ if (!existingToolResultIds.has(tc.id)) {
109
+ result.push({
110
+ role: "toolResult",
111
+ toolCallId: tc.id,
112
+ toolName: tc.name,
113
+ content: [{ type: "text", text: "No result provided" }],
114
+ isError: true,
115
+ timestamp: Date.now(),
116
+ });
117
+ }
118
+ }
119
+ pendingToolCalls = [];
120
+ existingToolResultIds = new Set();
102
121
  }
103
- return true; // Keep all non-toolCall blocks
104
- });
105
- return {
106
- ...assistantMsg,
107
- content: filteredContent,
108
- };
109
- });
122
+ result.push(msg);
123
+ }
124
+ else {
125
+ result.push(msg);
126
+ }
127
+ }
128
+ return result;
110
129
  }
111
130
  //# sourceMappingURL=transorm-messages.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"transorm-messages.js","sourceRoot":"","sources":["../../src/providers/transorm-messages.ts"],"names":[],"mappings":"AAEA;;;;GAIG;AACH,SAAS,0BAA0B,CAAC,EAAU,EAAU;IACvD,OAAO,EAAE,C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OAAO,EAAE,eAAe;SACxB,CAAC;IAAA,CACF,CAAC,CAAC;AAAA,CACJ","sourcesContent":["import type { Api, AssistantMessage, Message, Model, ToolCall } from \"../types.js\";\n\n/**\n * Normalize tool call ID for GitHub Copilot cross-API compatibility.\n * OpenAI Responses API generates IDs that are 450+ chars with special characters like `|`.\n * Other APIs (Claude, etc.) require max 40 chars and only alphanumeric + underscore + hyphen.\n */\nfunction normalizeCopilotToolCallId(id: string): string {\n\treturn id.replace(/[^a-zA-Z0-9_-]/g, \"\").slice(0, 40);\n}\n\nexport function transformMessages<TApi extends Api>(messages: Message[], model: Model<TApi>): Message[] {\n\t// Build a map of original tool call IDs to normalized IDs for github-copilot cross-API switches\n\tconst toolCallIdMap = new Map<string, string>();\n\n\treturn messages\n\t\t.map((msg) => {\n\t\t\t// User messages pass through unchanged\n\t\t\tif (msg.role === \"user\") {\n\t\t\t\treturn msg;\n\t\t\t}\n\n\t\t\t// Handle toolResult messages - normalize toolCallId if we have a mapping\n\t\t\tif (msg.role === \"toolResult\") {\n\t\t\t\tconst normalizedId = toolCallIdMap.get(msg.toolCallId);\n\t\t\t\tif (normalizedId && normalizedId !== msg.toolCallId) {\n\t\t\t\t\treturn { ...msg, toolCallId: normalizedId };\n\t\t\t\t}\n\t\t\t\treturn msg;\n\t\t\t}\n\n\t\t\t// Assistant messages need transformation check\n\t\t\tif (msg.role === \"assistant\") {\n\t\t\t\tconst assistantMsg = msg as AssistantMessage;\n\n\t\t\t\t// If message is from the same provider and API, keep as is\n\t\t\t\tif (assistantMsg.provider === model.provider && assistantMsg.api === model.api) {\n\t\t\t\t\treturn msg;\n\t\t\t\t}\n\n\t\t\t\t// Check if we need to normalize tool call IDs (github-copilot cross-API)\n\t\t\t\tconst needsToolCallIdNormalization =\n\t\t\t\t\tassistantMsg.provider === \"github-copilot\" &&\n\t\t\t\t\tmodel.provider === \"github-copilot\" &&\n\t\t\t\t\tassistantMsg.api !== model.api;\n\n\t\t\t\t// Transform message from different provider/model\n\t\t\t\tconst transformedContent = assistantMsg.content.map((block) => {\n\t\t\t\t\tif (block.type === \"thinking\") {\n\t\t\t\t\t\t// Convert thinking block to text block with <thinking> tags\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\t\t\ttext: `<thinking>\\n${block.thinking}\\n</thinking>`,\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\t// Normalize tool call IDs for github-copilot cross-API switches\n\t\t\t\t\tif (block.type === \"toolCall\" && needsToolCallIdNormalization) {\n\t\t\t\t\t\tconst toolCall = block as ToolCall;\n\t\t\t\t\t\tconst normalizedId = normalizeCopilotToolCallId(toolCall.id);\n\t\t\t\t\t\tif (normalizedId !== toolCall.id) {\n\t\t\t\t\t\t\ttoolCallIdMap.set(toolCall.id, normalizedId);\n\t\t\t\t\t\t\treturn { ...toolCall, id: normalizedId };\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t// All other blocks pass through unchanged\n\t\t\t\t\treturn block;\n\t\t\t\t});\n\n\t\t\t\t// Return transformed assistant message\n\t\t\t\treturn {\n\t\t\t\t\t...assistantMsg,\n\t\t\t\t\tcontent: transformedContent,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn msg;\n\t\t})\n\t\t.map((msg, index, allMessages) => {\n\t\t\t// Second pass: filter out tool calls without corresponding tool results\n\t\t\tif (msg.role !== \"assistant\") {\n\t\t\t\treturn msg;\n\t\t\t}\n\n\t\t\tconst assistantMsg = msg as AssistantMessage;\n\t\t\tconst isLastMessage = index === allMessages.length - 1;\n\n\t\t\t// If this is the last message, keep all tool calls (ongoing turn)\n\t\t\tif (isLastMessage) {\n\t\t\t\treturn msg;\n\t\t\t}\n\n\t\t\t// Extract tool call IDs from this message\n\t\t\tconst toolCallIds = assistantMsg.content\n\t\t\t\t.filter((block) => block.type === \"toolCall\")\n\t\t\t\t.map((block) => (block.type === \"toolCall\" ? block.id : \"\"));\n\n\t\t\t// If no tool calls, return as is\n\t\t\tif (toolCallIds.length === 0) {\n\t\t\t\treturn msg;\n\t\t\t}\n\n\t\t\t// Scan forward through subsequent messages to find matching tool results\n\t\t\tconst matchedToolCallIds = new Set<string>();\n\t\t\tfor (let i = index + 1; i < allMessages.length; i++) {\n\t\t\t\tconst nextMsg = allMessages[i];\n\n\t\t\t\t// Stop scanning when we hit another assistant message\n\t\t\t\tif (nextMsg.role === \"assistant\") {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\t// Check tool result messages for matching IDs\n\t\t\t\tif (nextMsg.role === \"toolResult\") {\n\t\t\t\t\tmatchedToolCallIds.add(nextMsg.toolCallId);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Filter out tool calls that don't have corresponding results\n\t\t\tconst filteredContent = assistantMsg.content.filter((block) => {\n\t\t\t\tif (block.type === \"toolCall\") {\n\t\t\t\t\treturn matchedToolCallIds.has(block.id);\n\t\t\t\t}\n\t\t\t\treturn true; // Keep all non-toolCall blocks\n\t\t\t});\n\n\t\t\treturn {\n\t\t\t\t...assistantMsg,\n\t\t\t\tcontent: filteredContent,\n\t\t\t};\n\t\t});\n}\n"]}
1
+ {"version":3,"file":"transorm-messages.js","sourceRoot":"","sources":["../../src/providers/transorm-messages.ts"],"names":[],"mappings":"AAEA;;;;GAIG;AACH,SAAS,0BAA0B,CAAC,EAAU,EAAU;IACvD,OAAO,EAAE,CAAC,OAAO,CAAC,iBAAiB,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;AAAA,CACtD;AAED,MAAM,UAAU,iBAAiB,CAAmB,QAAmB,EAAE,KAAkB,EAAa;IACvG,gGAAgG;IAChG,MAAM,aAAa,GAAG,IAAI,GAAG,EAAkB,CAAC;IAEhD,+EAA+E;IAC/E,MAAM,WAAW,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC;QACzC,uCAAuC;QACvC,IAAI,GAAG,CAAC,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AAQ,EAAE,EAAE,CAAC,IAAI;4BACjB,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,oBAAoB,EAAE,CAAC;4BACvD,OAAO,EAAE,IAAI;4BACb,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;yBACA,CAAC,CAAC;oBACzB,CAAC;gBACF,CAAC;gBACD,gBAAgB,GAAG,EAAE,CAAC;gBACtB,qBAAqB,GAAG,IAAI,GAAG,EAAE,CAAC;YACnC,CAAC;YACD,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAClB,CAAC;aAAM,CAAC;YACP,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAClB,CAAC;IACF,CAAC;IAED,OAAO,MAAM,CAAC;AAAA,CACd","sourcesContent":["import type { Api, AssistantMessage, Message, Model, ToolCall, ToolResultMessage } from \"../types.js\";\n\n/**\n * Normalize tool call ID for GitHub Copilot cross-API compatibility.\n * OpenAI Responses API generates IDs that are 450+ chars with special characters like `|`.\n * Other APIs (Claude, etc.) require max 40 chars and only alphanumeric + underscore + hyphen.\n */\nfunction normalizeCopilotToolCallId(id: string): string {\n\treturn id.replace(/[^a-zA-Z0-9_-]/g, \"\").slice(0, 40);\n}\n\nexport function transformMessages<TApi extends Api>(messages: Message[], model: Model<TApi>): Message[] {\n\t// Build a map of original tool call IDs to normalized IDs for github-copilot cross-API switches\n\tconst toolCallIdMap = new Map<string, string>();\n\n\t// First pass: transform messages (thinking blocks, tool call ID normalization)\n\tconst transformed = messages.map((msg) => {\n\t\t// User messages pass through unchanged\n\t\tif (msg.role === \"user\") {\n\t\t\treturn msg;\n\t\t}\n\n\t\t// Handle toolResult messages - normalize toolCallId if we have a mapping\n\t\tif (msg.role === \"toolResult\") {\n\t\t\tconst normalizedId = toolCallIdMap.get(msg.toolCallId);\n\t\t\tif (normalizedId && normalizedId !== msg.toolCallId) {\n\t\t\t\treturn { ...msg, toolCallId: normalizedId };\n\t\t\t}\n\t\t\treturn msg;\n\t\t}\n\n\t\t// Assistant messages need transformation check\n\t\tif (msg.role === \"assistant\") {\n\t\t\tconst assistantMsg = msg as AssistantMessage;\n\n\t\t\t// If message is from the same provider and API, keep as is\n\t\t\tif (assistantMsg.provider === model.provider && assistantMsg.api === model.api) {\n\t\t\t\treturn msg;\n\t\t\t}\n\n\t\t\t// Check if we need to normalize tool call IDs (github-copilot cross-API)\n\t\t\tconst needsToolCallIdNormalization =\n\t\t\t\tassistantMsg.provider === \"github-copilot\" &&\n\t\t\t\tmodel.provider === \"github-copilot\" &&\n\t\t\t\tassistantMsg.api !== model.api;\n\n\t\t\t// Transform message from different provider/model\n\t\t\tconst transformedContent = assistantMsg.content.map((block) => {\n\t\t\t\tif (block.type === \"thinking\") {\n\t\t\t\t\t// Convert thinking block to text block with <thinking> tags\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\t\ttext: `<thinking>\\n${block.thinking}\\n</thinking>`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\t// Normalize tool call IDs for github-copilot cross-API switches\n\t\t\t\tif (block.type === \"toolCall\" && needsToolCallIdNormalization) {\n\t\t\t\t\tconst toolCall = block as ToolCall;\n\t\t\t\t\tconst normalizedId = normalizeCopilotToolCallId(toolCall.id);\n\t\t\t\t\tif (normalizedId !== toolCall.id) {\n\t\t\t\t\t\ttoolCallIdMap.set(toolCall.id, normalizedId);\n\t\t\t\t\t\treturn { ...toolCall, id: normalizedId };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// All other blocks pass through unchanged\n\t\t\t\treturn block;\n\t\t\t});\n\n\t\t\t// Return transformed assistant message\n\t\t\treturn {\n\t\t\t\t...assistantMsg,\n\t\t\t\tcontent: transformedContent,\n\t\t\t};\n\t\t}\n\t\treturn msg;\n\t});\n\n\t// Second pass: insert synthetic empty tool results for orphaned tool calls\n\t// This preserves thinking signatures and satisfies API requirements\n\tconst result: Message[] = [];\n\tlet pendingToolCalls: ToolCall[] = [];\n\tlet existingToolResultIds = new Set<string>();\n\n\tfor (let i = 0; i < transformed.length; i++) {\n\t\tconst msg = transformed[i];\n\n\t\tif (msg.role === \"assistant\") {\n\t\t\t// If we have pending orphaned tool calls from a previous assistant, insert synthetic results now\n\t\t\tif (pendingToolCalls.length > 0) {\n\t\t\t\tfor (const tc of pendingToolCalls) {\n\t\t\t\t\tif (!existingToolResultIds.has(tc.id)) {\n\t\t\t\t\t\tresult.push({\n\t\t\t\t\t\t\trole: \"toolResult\",\n\t\t\t\t\t\t\ttoolCallId: tc.id,\n\t\t\t\t\t\t\ttoolName: tc.name,\n\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: \"No result provided\" }],\n\t\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\t} as ToolResultMessage);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tpendingToolCalls = [];\n\t\t\t\texistingToolResultIds = new Set();\n\t\t\t}\n\n\t\t\t// Track tool calls from this assistant message\n\t\t\tconst assistantMsg = msg as AssistantMessage;\n\t\t\tconst toolCalls = assistantMsg.content.filter((b) => b.type === \"toolCall\") as ToolCall[];\n\t\t\tif (toolCalls.length > 0) {\n\t\t\t\tpendingToolCalls = toolCalls;\n\t\t\t\texistingToolResultIds = new Set();\n\t\t\t}\n\n\t\t\tresult.push(msg);\n\t\t} else if (msg.role === \"toolResult\") {\n\t\t\texistingToolResultIds.add(msg.toolCallId);\n\t\t\tresult.push(msg);\n\t\t} else if (msg.role === \"user\") {\n\t\t\t// User message interrupts tool flow - insert synthetic results for orphaned calls\n\t\t\tif (pendingToolCalls.length > 0) {\n\t\t\t\tfor (const tc of pendingToolCalls) {\n\t\t\t\t\tif (!existingToolResultIds.has(tc.id)) {\n\t\t\t\t\t\tresult.push({\n\t\t\t\t\t\t\trole: \"toolResult\",\n\t\t\t\t\t\t\ttoolCallId: tc.id,\n\t\t\t\t\t\t\ttoolName: tc.name,\n\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: \"No result provided\" }],\n\t\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\t} as ToolResultMessage);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tpendingToolCalls = [];\n\t\t\t\texistingToolResultIds = new Set();\n\t\t\t}\n\t\t\tresult.push(msg);\n\t\t} else {\n\t\t\tresult.push(msg);\n\t\t}\n\t}\n\n\treturn result;\n}\n"]}
package/dist/stream.d.ts CHANGED
@@ -1,8 +1,23 @@
1
1
  import type { Api, AssistantMessage, AssistantMessageEventStream, Context, KnownProvider, Model, OptionsForApi, SimpleStreamOptions } from "./types.js";
2
2
  export declare function setApiKey(provider: KnownProvider, key: string): void;
3
3
  export declare function setApiKey(provider: string, key: string): void;
4
+ /**
5
+ * Get API key from environment variables (sync).
6
+ * Does NOT check OAuth credentials - use getApiKeyAsync for that.
7
+ */
4
8
  export declare function getApiKey(provider: KnownProvider): string | undefined;
5
9
  export declare function getApiKey(provider: string): string | undefined;
10
+ /**
11
+ * Resolve API key from OAuth credentials or environment (async).
12
+ * Automatically refreshes expired OAuth tokens.
13
+ *
14
+ * Priority:
15
+ * 1. Explicitly set keys (via setApiKey)
16
+ * 2. OAuth credentials from ~/.pi/agent/oauth.json
17
+ * 3. Environment variables
18
+ */
19
+ export declare function resolveApiKey(provider: KnownProvider): Promise<string | undefined>;
20
+ export declare function resolveApiKey(provider: string): Promise<string | undefined>;
6
21
  export declare function stream<TApi extends Api>(model: Model<TApi>, context: Context, options?: OptionsForApi<TApi>): AssistantMessageEventStream;
7
22
  export declare function complete<TApi extends Api>(model: Model<TApi>, context: Context, options?: OptionsForApi<TApi>): Promise<AssistantMessage>;
8
23
  export declare function streamSimple<TApi extends Api>(model: Model<TApi>, context: Context, options?: SimpleStreamOptions): AssistantMessageEventStream;
@@ -1 +1 @@
1
- {"version":3,"file":"stream.d.ts","sourceRoot":"","sources":["../src/st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Content":["import { ThinkingLevel } from \"@google/genai\";\nimport { supportsXhigh } from \"./models.js\";\nimport { type AnthropicOptions, streamAnthropic } from \"./providers/anthropic.js\";\nimport { type GoogleOptions, streamGoogle } from \"./providers/google.js\";\nimport { type OpenAICompletionsOptions, streamOpenAICompletions } from \"./providers/openai-completions.js\";\nimport { type OpenAIResponsesOptions, streamOpenAIResponses } from \"./providers/openai-responses.js\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tAssistantMessageEventStream,\n\tContext,\n\tKnownProvider,\n\tModel,\n\tOptionsForApi,\n\tReasoningEffort,\n\tSimpleStreamOptions,\n} from \"./types.js\";\n\nconst apiKeys: Map<string, string> = new Map();\n\nexport function setApiKey(provider: KnownProvider, key: string): void;\nexport function setApiKey(provider: string, key: string): void;\nexport function setApiKey(provider: any, key: string): void {\n\tapiKeys.set(provider, key);\n}\n\nexport function getApiKey(provider: KnownProvider): string | undefined;\nexport function getApiKey(provider: string): string | undefined;\nexport function getApiKey(provider: any): string | undefined {\n\t// Check explicit keys first\n\tconst key = apiKeys.get(provider);\n\tif (key) return key;\n\n\t// Fall back to environment variables\n\tif (provider === \"github-copilot\") {\n\t\treturn process.env.COPILOT_GITHUB_TOKEN || process.env.GH_TOKEN || process.env.GITHUB_TOKEN;\n\t}\n\n\tconst envMap: Record<string, string> = {\n\t\topenai: \"OPENAI_API_KEY\",\n\t\tanthropic: \"ANTHROPIC_API_KEY\",\n\t\tgoogle: \"GEMINI_API_KEY\",\n\t\tgroq: \"GROQ_API_KEY\",\n\t\tcerebras: \"CEREBRAS_API_KEY\",\n\t\txai: \"XAI_API_KEY\",\n\t\topenrouter: \"OPENROUTER_API_KEY\",\n\t\tzai: \"ZAI_API_KEY\",\n\t\tmistral: \"MISTRAL_API_KEY\",\n\t};\n\n\tconst envVar = envMap[provider];\n\treturn envVar ? process.env[envVar] : undefined;\n}\n\nexport function stream<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\toptions?: OptionsForApi<TApi>,\n): AssistantMessageEventStream {\n\tconst apiKey = options?.apiKey || getApiKey(model.provider);\n\tif (!apiKey) {\n\t\tthrow new Error(`No API key for provider: ${model.provider}`);\n\t}\n\tconst providerOptions = { ...options, apiKey };\n\n\tconst api: Api = model.api;\n\tswitch (api) {\n\t\tcase \"anthropic-messages\":\n\t\t\treturn streamAnthropic(model as Model<\"anthropic-messages\">, context, providerOptions);\n\n\t\tcase \"openai-completions\":\n\t\t\treturn streamOpenAICompletions(model as Model<\"openai-completions\">, context, providerOptions as any);\n\n\t\tcase \"openai-responses\":\n\t\t\treturn streamOpenAIResponses(model as Model<\"openai-responses\">, context, providerOptions as any);\n\n\t\tcase \"google-generative-ai\":\n\t\t\treturn streamGoogle(model as Model<\"google-generative-ai\">, context, providerOptions);\n\n\t\tdefault: {\n\t\t\t// This should never be reached if all Api cases are handled\n\t\t\tconst _exhaustive: never = api;\n\t\t\tthrow new Error(`Unhandled API: ${_exhaustive}`);\n\t\t}\n\t}\n}\n\nexport async function complete<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\toptions?: OptionsForApi<TApi>,\n): Promise<AssistantMessage> {\n\tconst s = stream(model, context, options);\n\treturn s.result();\n}\n\nexport function streamSimple<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): AssistantMessageEventStream {\n\tconst apiKey = options?.apiKey || getApiKey(model.provider);\n\tif (!apiKey) {\n\t\tthrow new Error(`No API key for provider: ${model.provider}`);\n\t}\n\n\tconst providerOptions = mapOptionsForApi(model, options, apiKey);\n\treturn stream(model, context, providerOptions);\n}\n\nexport async function completeSimple<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): Promise<AssistantMessage> {\n\tconst s = streamSimple(model, context, options);\n\treturn s.result();\n}\n\nfunction mapOptionsForApi<TApi extends Api>(\n\tmodel: Model<TApi>,\n\toptions?: SimpleStreamOptions,\n\tapiKey?: string,\n): OptionsForApi<TApi> {\n\tconst base = {\n\t\ttemperature: options?.temperature,\n\t\tmaxTokens: options?.maxTokens || Math.min(model.maxTokens, 32000),\n\t\tsignal: options?.signal,\n\t\tapiKey: apiKey || options?.apiKey,\n\t};\n\n\t// Helper to clamp xhigh to high for providers that don't support it\n\tconst clampReasoning = (effort: ReasoningEffort | undefined) => (effort === \"xhigh\" ? \"high\" : effort);\n\n\tswitch (model.api) {\n\t\tcase \"anthropic-messages\": {\n\t\t\t// Explicitly disable thinking when reasoning is not specified\n\t\t\tif (!options?.reasoning) {\n\t\t\t\treturn { ...base, thinkingEnabled: false } satisfies AnthropicOptions;\n\t\t\t}\n\n\t\t\tconst anthropicBudgets = {\n\t\t\t\tminimal: 1024,\n\t\t\t\tlow: 2048,\n\t\t\t\tmedium: 8192,\n\t\t\t\thigh: 16384,\n\t\t\t};\n\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\tthinkingEnabled: true,\n\t\t\t\tthinkingBudgetTokens: anthropicBudgets[clampReasoning(options.reasoning)!],\n\t\t\t} satisfies AnthropicOptions;\n\t\t}\n\n\t\tcase \"openai-completions\":\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\treasoningEffort: supportsXhigh(model) ? options?.reasoning : clampReasoning(options?.reasoning),\n\t\t\t} satisfies OpenAICompletionsOptions;\n\n\t\tcase \"openai-responses\":\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\treasoningEffort: supportsXhigh(model) ? options?.reasoning : clampReasoning(options?.reasoning),\n\t\t\t} satisfies OpenAIResponsesOptions;\n\n\t\tcase \"google-generative-ai\": {\n\t\t\t// Explicitly disable thinking when reasoning is not specified\n\t\t\t// This is needed because Gemini has \"dynamic thinking\" enabled by default\n\t\t\tif (!options?.reasoning) {\n\t\t\t\treturn { ...base, thinking: { enabled: false } } satisfies GoogleOptions;\n\t\t\t}\n\n\t\t\tconst googleModel = model as Model<\"google-generative-ai\">;\n\t\t\tconst effort = clampReasoning(options.reasoning)!;\n\n\t\t\t// Gemini 3 models use thinkingLevel exclusively instead of thinkingBudget.\n\t\t\t// https://ai.google.dev/gemini-api/docs/thinking#set-budget\n\t\t\tif (isGemini3ProModel(googleModel) || isGemini3FlashModel(googleModel)) {\n\t\t\t\treturn {\n\t\t\t\t\t...base,\n\t\t\t\t\tthinking: {\n\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\tlevel: getGemini3ThinkingLevel(effort, googleModel),\n\t\t\t\t\t},\n\t\t\t\t} satisfies GoogleOptions;\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\tthinking: {\n\t\t\t\t\tenabled: true,\n\t\t\t\t\tbudgetTokens: getGoogleBudget(googleModel, effort),\n\t\t\t\t},\n\t\t\t} satisfies GoogleOptions;\n\t\t}\n\n\t\tdefault: {\n\t\t\t// Exhaustiveness check\n\t\t\tconst _exhaustive: never = model.api;\n\t\t\tthrow new Error(`Unhandled API in mapOptionsForApi: ${_exhaustive}`);\n\t\t}\n\t}\n}\n\ntype ClampedReasoningEffort = Exclude<ReasoningEffort, \"xhigh\">;\n\nfunction isGemini3ProModel(model: Model<\"google-generative-ai\">): boolean {\n\t// Covers gemini-3-pro, gemini-3-pro-preview, and possible other prefixed ids in the future\n\treturn model.id.includes(\"3-pro\");\n}\n\nfunction isGemini3FlashModel(model: Model<\"google-generative-ai\">): boolean {\n\t// Covers gemini-3-flash, gemini-3-flash-preview, and possible other prefixed ids in the future\n\treturn model.id.includes(\"3-flash\");\n}\n\nfunction getGemini3ThinkingLevel(effort: ClampedReasoningEffort, model: Model<\"google-generative-ai\">): ThinkingLevel {\n\tif (isGemini3ProModel(model)) {\n\t\t// Gemini 3 Pro only supports LOW/HIGH (for now)\n\t\tswitch (effort) {\n\t\t\tcase \"minimal\":\n\t\t\tcase \"low\":\n\t\t\t\treturn ThinkingLevel.LOW;\n\t\t\tcase \"medium\":\n\t\t\tcase \"high\":\n\t\t\t\treturn ThinkingLevel.HIGH;\n\t\t}\n\t}\n\t// Gemini 3 Flash supports all four levels\n\tswitch (effort) {\n\t\tcase \"minimal\":\n\t\t\treturn ThinkingLevel.MINIMAL;\n\t\tcase \"low\":\n\t\t\treturn ThinkingLevel.LOW;\n\t\tcase \"medium\":\n\t\t\treturn ThinkingLevel.MEDIUM;\n\t\tcase \"high\":\n\t\t\treturn ThinkingLevel.HIGH;\n\t}\n}\n\nfunction getGoogleBudget(model: Model<\"google-generative-ai\">, effort: ClampedReasoningEffort): number {\n\t// See https://ai.google.dev/gemini-api/docs/thinking#set-budget\n\tif (model.id.includes(\"2.5-pro\")) {\n\t\tconst budgets: Record<ClampedReasoningEffort, number> = {\n\t\t\tminimal: 128,\n\t\t\tlow: 2048,\n\t\t\tmedium: 8192,\n\t\t\thigh: 32768,\n\t\t};\n\t\treturn budgets[effort];\n\t}\n\n\tif (model.id.includes(\"2.5-flash\")) {\n\t\t// Covers 2.5-flash-lite as well\n\t\tconst budgets: Record<ClampedReasoningEffort, number> = {\n\t\t\tminimal: 128,\n\t\t\tlow: 2048,\n\t\t\tmedium: 8192,\n\t\t\thigh: 24576,\n\t\t};\n\t\treturn budgets[effort];\n\t}\n\n\t// Unknown model - use dynamic\n\treturn -1;\n}\n"]}
1
+ {"version":3,"file":"stream.d.ts","sourceRoot":"","sources":["../src/stream.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EACX,GAAG,EACH,gBAAgB,EAChB,2BAA2B,EAC3B,OAAO,EACP,aAAa,EACb,KAAK,EACL,aAAa,EAEb,mBAAmB,EACnB,MAAM,YAAY,CAAC;AAKpB,wBAAgB,SAAS,CAAC,QAAQ,EAAE,aAAa,EAAE,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC;AACtE,wBAAgB,SAAS,CAAC,QAAQ,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC;AAK/D;;;GAGG;AACH,wBAAgB,SAAS,CAAC,QAAQ,EAAE,aAAa,GAAG,MAAM,GAAG,SAAS,CAAC;AACvE,wBAAgB,SAAS,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAAC;AA2BhE;;;;;;;;GAQG;AACH,wBAAsB,aAAa,CAAC,QAAQ,EAAE,aAAa,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;AAC1F,wBAAsB,aAAa,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;AAiBnF,wBAAgB,MAAM,CAAC,IAAI,SAAS,GAAG,EACtC,KAAK,EAAE,KAAK,CAAC,IAAI,CAAC,EAClB,OAAO,EAAE,OAAO,EAChB,OAAO,CAAC,EAAE,aAAa,CAAC,IAAI,CAAC,GAC3B,2BAA2B,CAkC7B;AAED,wBAAsB,QAAQ,CAAC,IAAI,SAAS,GAAG,EAC9C,KAAK,EAAE,KAAK,CAAC,IAAI,CAAC,EAClB,OAAO,EAAE,OAAO,EAChB,OAAO,CAAC,EAAE,aAAa,CAAC,IAAI,CAAC,GAC3B,OAAO,CAAC,gBAAgB,CAAC,CAG3B;AAED,wBAAgB,YAAY,CAAC,IAAI,SAAS,GAAG,EAC5C,KAAK,EAAE,KAAK,CAAC,IAAI,CAAC,EAClB,OAAO,EAAE,OAAO,EAChB,OAAO,CAAC,EAAE,mBAAmB,GAC3B,2BAA2B,CAQ7B;AAED,wBAAsB,cAAc,CAAC,IAAI,SAAS,GAAG,EACpD,KAAK,EAAE,KAAK,CAAC,IAAI,CAAC,EAClB,OAAO,EAAE,OAAO,EAChB,OAAO,CAAC,EAAE,mBAAmB,GAC3B,OAAO,CAAC,gBAAgB,CAAC,CAG3B","sourcesContent":["import { ThinkingLevel } from \"@google/genai\";\nimport { supportsXhigh } from \"./models.js\";\nimport { type AnthropicOptions, streamAnthropic } from \"./providers/anthropic.js\";\nimport { type GoogleOptions, streamGoogle } from \"./providers/google.js\";\nimport { type GoogleGeminiCliOptions, streamGoogleGeminiCli } from \"./providers/google-gemini-cli.js\";\nimport { type OpenAICompletionsOptions, streamOpenAICompletions } from \"./providers/openai-completions.js\";\nimport { type OpenAIResponsesOptions, streamOpenAIResponses } from \"./providers/openai-responses.js\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tAssistantMessageEventStream,\n\tContext,\n\tKnownProvider,\n\tModel,\n\tOptionsForApi,\n\tReasoningEffort,\n\tSimpleStreamOptions,\n} from \"./types.js\";\nimport { getOAuthApiKey, getOAuthProviderForModelProvider } from \"./utils/oauth/index.js\";\n\nconst apiKeys: Map<string, string> = new Map();\n\nexport function setApiKey(provider: KnownProvider, key: string): void;\nexport function setApiKey(provider: string, key: string): void;\nexport function setApiKey(provider: any, key: string): void {\n\tapiKeys.set(provider, key);\n}\n\n/**\n * Get API key from environment variables (sync).\n * Does NOT check OAuth credentials - use getApiKeyAsync for that.\n */\nexport function getApiKey(provider: KnownProvider): string | undefined;\nexport function getApiKey(provider: string): string | undefined;\nexport function getApiKey(provider: any): string | undefined {\n\t// Check explicit keys first\n\tconst key = apiKeys.get(provider);\n\tif (key) return key;\n\n\t// Fall back to environment variables\n\tif (provider === \"github-copilot\") {\n\t\treturn process.env.COPILOT_GITHUB_TOKEN || process.env.GH_TOKEN || process.env.GITHUB_TOKEN;\n\t}\n\n\tconst envMap: Record<string, string> = {\n\t\topenai: \"OPENAI_API_KEY\",\n\t\tanthropic: \"ANTHROPIC_API_KEY\",\n\t\tgoogle: \"GEMINI_API_KEY\",\n\t\tgroq: \"GROQ_API_KEY\",\n\t\tcerebras: \"CEREBRAS_API_KEY\",\n\t\txai: \"XAI_API_KEY\",\n\t\topenrouter: \"OPENROUTER_API_KEY\",\n\t\tzai: \"ZAI_API_KEY\",\n\t\tmistral: \"MISTRAL_API_KEY\",\n\t};\n\n\tconst envVar = envMap[provider];\n\treturn envVar ? process.env[envVar] : undefined;\n}\n\n/**\n * Resolve API key from OAuth credentials or environment (async).\n * Automatically refreshes expired OAuth tokens.\n *\n * Priority:\n * 1. Explicitly set keys (via setApiKey)\n * 2. OAuth credentials from ~/.pi/agent/oauth.json\n * 3. Environment variables\n */\nexport async function resolveApiKey(provider: KnownProvider): Promise<string | undefined>;\nexport async function resolveApiKey(provider: string): Promise<string | undefined>;\nexport async function resolveApiKey(provider: any): Promise<string | undefined> {\n\t// Check explicit keys first\n\tconst key = apiKeys.get(provider);\n\tif (key) return key;\n\n\t// Check OAuth credentials (auto-refresh if expired)\n\tconst oauthProvider = getOAuthProviderForModelProvider(provider);\n\tif (oauthProvider) {\n\t\tconst oauthKey = await getOAuthApiKey(oauthProvider);\n\t\tif (oauthKey) return oauthKey;\n\t}\n\n\t// Fall back to sync getApiKey for env vars\n\treturn getApiKey(provider);\n}\n\nexport function stream<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\toptions?: OptionsForApi<TApi>,\n): AssistantMessageEventStream {\n\tconst apiKey = options?.apiKey || getApiKey(model.provider);\n\tif (!apiKey) {\n\t\tthrow new Error(`No API key for provider: ${model.provider}`);\n\t}\n\tconst providerOptions = { ...options, apiKey };\n\n\tconst api: Api = model.api;\n\tswitch (api) {\n\t\tcase \"anthropic-messages\":\n\t\t\treturn streamAnthropic(model as Model<\"anthropic-messages\">, context, providerOptions);\n\n\t\tcase \"openai-completions\":\n\t\t\treturn streamOpenAICompletions(model as Model<\"openai-completions\">, context, providerOptions as any);\n\n\t\tcase \"openai-responses\":\n\t\t\treturn streamOpenAIResponses(model as Model<\"openai-responses\">, context, providerOptions as any);\n\n\t\tcase \"google-generative-ai\":\n\t\t\treturn streamGoogle(model as Model<\"google-generative-ai\">, context, providerOptions);\n\n\t\tcase \"google-gemini-cli\":\n\t\t\treturn streamGoogleGeminiCli(\n\t\t\t\tmodel as Model<\"google-gemini-cli\">,\n\t\t\t\tcontext,\n\t\t\t\tproviderOptions as GoogleGeminiCliOptions,\n\t\t\t);\n\n\t\tdefault: {\n\t\t\t// This should never be reached if all Api cases are handled\n\t\t\tconst _exhaustive: never = api;\n\t\t\tthrow new Error(`Unhandled API: ${_exhaustive}`);\n\t\t}\n\t}\n}\n\nexport async function complete<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\toptions?: OptionsForApi<TApi>,\n): Promise<AssistantMessage> {\n\tconst s = stream(model, context, options);\n\treturn s.result();\n}\n\nexport function streamSimple<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): AssistantMessageEventStream {\n\tconst apiKey = options?.apiKey || getApiKey(model.provider);\n\tif (!apiKey) {\n\t\tthrow new Error(`No API key for provider: ${model.provider}`);\n\t}\n\n\tconst providerOptions = mapOptionsForApi(model, options, apiKey);\n\treturn stream(model, context, providerOptions);\n}\n\nexport async function completeSimple<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): Promise<AssistantMessage> {\n\tconst s = streamSimple(model, context, options);\n\treturn s.result();\n}\n\nfunction mapOptionsForApi<TApi extends Api>(\n\tmodel: Model<TApi>,\n\toptions?: SimpleStreamOptions,\n\tapiKey?: string,\n): OptionsForApi<TApi> {\n\tconst base = {\n\t\ttemperature: options?.temperature,\n\t\tmaxTokens: options?.maxTokens || Math.min(model.maxTokens, 32000),\n\t\tsignal: options?.signal,\n\t\tapiKey: apiKey || options?.apiKey,\n\t};\n\n\t// Helper to clamp xhigh to high for providers that don't support it\n\tconst clampReasoning = (effort: ReasoningEffort | undefined) => (effort === \"xhigh\" ? \"high\" : effort);\n\n\tswitch (model.api) {\n\t\tcase \"anthropic-messages\": {\n\t\t\t// Explicitly disable thinking when reasoning is not specified\n\t\t\tif (!options?.reasoning) {\n\t\t\t\treturn { ...base, thinkingEnabled: false } satisfies AnthropicOptions;\n\t\t\t}\n\n\t\t\tconst anthropicBudgets = {\n\t\t\t\tminimal: 1024,\n\t\t\t\tlow: 2048,\n\t\t\t\tmedium: 8192,\n\t\t\t\thigh: 16384,\n\t\t\t};\n\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\tthinkingEnabled: true,\n\t\t\t\tthinkingBudgetTokens: anthropicBudgets[clampReasoning(options.reasoning)!],\n\t\t\t} satisfies AnthropicOptions;\n\t\t}\n\n\t\tcase \"openai-completions\":\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\treasoningEffort: supportsXhigh(model) ? options?.reasoning : clampReasoning(options?.reasoning),\n\t\t\t} satisfies OpenAICompletionsOptions;\n\n\t\tcase \"openai-responses\":\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\treasoningEffort: supportsXhigh(model) ? options?.reasoning : clampReasoning(options?.reasoning),\n\t\t\t} satisfies OpenAIResponsesOptions;\n\n\t\tcase \"google-generative-ai\": {\n\t\t\t// Explicitly disable thinking when reasoning is not specified\n\t\t\t// This is needed because Gemini has \"dynamic thinking\" enabled by default\n\t\t\tif (!options?.reasoning) {\n\t\t\t\treturn { ...base, thinking: { enabled: false } } satisfies GoogleOptions;\n\t\t\t}\n\n\t\t\tconst googleModel = model as Model<\"google-generative-ai\">;\n\t\t\tconst effort = clampReasoning(options.reasoning)!;\n\n\t\t\t// Gemini 3 models use thinkingLevel exclusively instead of thinkingBudget.\n\t\t\t// https://ai.google.dev/gemini-api/docs/thinking#set-budget\n\t\t\tif (isGemini3ProModel(googleModel) || isGemini3FlashModel(googleModel)) {\n\t\t\t\treturn {\n\t\t\t\t\t...base,\n\t\t\t\t\tthinking: {\n\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\tlevel: getGemini3ThinkingLevel(effort, googleModel),\n\t\t\t\t\t},\n\t\t\t\t} satisfies GoogleOptions;\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\tthinking: {\n\t\t\t\t\tenabled: true,\n\t\t\t\t\tbudgetTokens: getGoogleBudget(googleModel, effort),\n\t\t\t\t},\n\t\t\t} satisfies GoogleOptions;\n\t\t}\n\n\t\tcase \"google-gemini-cli\": {\n\t\t\t// Cloud Code Assist uses thinking budget tokens like Gemini 2.5\n\t\t\tif (!options?.reasoning) {\n\t\t\t\treturn { ...base, thinking: { enabled: false } } satisfies GoogleGeminiCliOptions;\n\t\t\t}\n\n\t\t\tconst effort = clampReasoning(options.reasoning)!;\n\t\t\tconst budgets: Record<ClampedReasoningEffort, number> = {\n\t\t\t\tminimal: 1024,\n\t\t\t\tlow: 2048,\n\t\t\t\tmedium: 8192,\n\t\t\t\thigh: 16384,\n\t\t\t};\n\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\tthinking: {\n\t\t\t\t\tenabled: true,\n\t\t\t\t\tbudgetTokens: budgets[effort],\n\t\t\t\t},\n\t\t\t} satisfies GoogleGeminiCliOptions;\n\t\t}\n\n\t\tdefault: {\n\t\t\t// Exhaustiveness check\n\t\t\tconst _exhaustive: never = model.api;\n\t\t\tthrow new Error(`Unhandled API in mapOptionsForApi: ${_exhaustive}`);\n\t\t}\n\t}\n}\n\ntype ClampedReasoningEffort = Exclude<ReasoningEffort, \"xhigh\">;\n\nfunction isGemini3ProModel(model: Model<\"google-generative-ai\">): boolean {\n\t// Covers gemini-3-pro, gemini-3-pro-preview, and possible other prefixed ids in the future\n\treturn model.id.includes(\"3-pro\");\n}\n\nfunction isGemini3FlashModel(model: Model<\"google-generative-ai\">): boolean {\n\t// Covers gemini-3-flash, gemini-3-flash-preview, and possible other prefixed ids in the future\n\treturn model.id.includes(\"3-flash\");\n}\n\nfunction getGemini3ThinkingLevel(effort: ClampedReasoningEffort, model: Model<\"google-generative-ai\">): ThinkingLevel {\n\tif (isGemini3ProModel(model)) {\n\t\t// Gemini 3 Pro only supports LOW/HIGH (for now)\n\t\tswitch (effort) {\n\t\t\tcase \"minimal\":\n\t\t\tcase \"low\":\n\t\t\t\treturn ThinkingLevel.LOW;\n\t\t\tcase \"medium\":\n\t\t\tcase \"high\":\n\t\t\t\treturn ThinkingLevel.HIGH;\n\t\t}\n\t}\n\t// Gemini 3 Flash supports all four levels\n\tswitch (effort) {\n\t\tcase \"minimal\":\n\t\t\treturn ThinkingLevel.MINIMAL;\n\t\tcase \"low\":\n\t\t\treturn ThinkingLevel.LOW;\n\t\tcase \"medium\":\n\t\t\treturn ThinkingLevel.MEDIUM;\n\t\tcase \"high\":\n\t\t\treturn ThinkingLevel.HIGH;\n\t}\n}\n\nfunction getGoogleBudget(model: Model<\"google-generative-ai\">, effort: ClampedReasoningEffort): number {\n\t// See https://ai.google.dev/gemini-api/docs/thinking#set-budget\n\tif (model.id.includes(\"2.5-pro\")) {\n\t\tconst budgets: Record<ClampedReasoningEffort, number> = {\n\t\t\tminimal: 128,\n\t\t\tlow: 2048,\n\t\t\tmedium: 8192,\n\t\t\thigh: 32768,\n\t\t};\n\t\treturn budgets[effort];\n\t}\n\n\tif (model.id.includes(\"2.5-flash\")) {\n\t\t// Covers 2.5-flash-lite as well\n\t\tconst budgets: Record<ClampedReasoningEffort, number> = {\n\t\t\tminimal: 128,\n\t\t\tlow: 2048,\n\t\t\tmedium: 8192,\n\t\t\thigh: 24576,\n\t\t};\n\t\treturn budgets[effort];\n\t}\n\n\t// Unknown model - use dynamic\n\treturn -1;\n}\n"]}
package/dist/stream.js CHANGED
@@ -2,8 +2,10 @@ import { ThinkingLevel } from "@google/genai";
2
2
  import { supportsXhigh } from "./models.js";
3
3
  import { streamAnthropic } from "./providers/anthropic.js";
4
4
  import { streamGoogle } from "./providers/google.js";
5
+ import { streamGoogleGeminiCli } from "./providers/google-gemini-cli.js";
5
6
  import { streamOpenAICompletions } from "./providers/openai-completions.js";
6
7
  import { streamOpenAIResponses } from "./providers/openai-responses.js";
8
+ import { getOAuthApiKey, getOAuthProviderForModelProvider } from "./utils/oauth/index.js";
7
9
  const apiKeys = new Map();
8
10
  export function setApiKey(provider, key) {
9
11
  apiKeys.set(provider, key);
@@ -31,6 +33,21 @@ export function getApiKey(provider) {
31
33
  const envVar = envMap[provider];
32
34
  return envVar ? process.env[envVar] : undefined;
33
35
  }
36
+ export async function resolveApiKey(provider) {
37
+ // Check explicit keys first
38
+ const key = apiKeys.get(provider);
39
+ if (key)
40
+ return key;
41
+ // Check OAuth credentials (auto-refresh if expired)
42
+ const oauthProvider = getOAuthProviderForModelProvider(provider);
43
+ if (oauthProvider) {
44
+ const oauthKey = await getOAuthApiKey(oauthProvider);
45
+ if (oauthKey)
46
+ return oauthKey;
47
+ }
48
+ // Fall back to sync getApiKey for env vars
49
+ return getApiKey(provider);
50
+ }
34
51
  export function stream(model, context, options) {
35
52
  const apiKey = options?.apiKey || getApiKey(model.provider);
36
53
  if (!apiKey) {
@@ -47,6 +64,8 @@ export function stream(model, context, options) {
47
64
  return streamOpenAIResponses(model, context, providerOptions);
48
65
  case "google-generative-ai":
49
66
  return streamGoogle(model, context, providerOptions);
67
+ case "google-gemini-cli":
68
+ return streamGoogleGeminiCli(model, context, providerOptions);
50
69
  default: {
51
70
  // This should never be reached if all Api cases are handled
52
71
  const _exhaustive = api;
@@ -134,6 +153,26 @@ function mapOptionsForApi(model, options, apiKey) {
134
153
  },
135
154
  };
136
155
  }
156
+ case "google-gemini-cli": {
157
+ // Cloud Code Assist uses thinking budget tokens like Gemini 2.5
158
+ if (!options?.reasoning) {
159
+ return { ...base, thinking: { enabled: false } };
160
+ }
161
+ const effort = clampReasoning(options.reasoning);
162
+ const budgets = {
163
+ minimal: 1024,
164
+ low: 2048,
165
+ medium: 8192,
166
+ high: 16384,
167
+ };
168
+ return {
169
+ ...base,
170
+ thinking: {
171
+ enabled: true,
172
+ budgetTokens: budgets[effort],
173
+ },
174
+ };
175
+ }
137
176
  default: {
138
177
  // Exhaustiveness check
139
178
  const _exhaustive = model.api;