@mariozechner/pi-ai 0.49.3 → 0.50.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 (108) hide show
  1. package/README.md +32 -22
  2. package/dist/api-registry.d.ts +20 -0
  3. package/dist/api-registry.d.ts.map +1 -0
  4. package/dist/api-registry.js +44 -0
  5. package/dist/api-registry.js.map +1 -0
  6. package/dist/cli.d.ts.map +1 -1
  7. package/dist/cli.js +22 -67
  8. package/dist/cli.js.map +1 -1
  9. package/dist/env-api-keys.d.ts +9 -0
  10. package/dist/env-api-keys.d.ts.map +1 -0
  11. package/dist/env-api-keys.js +91 -0
  12. package/dist/env-api-keys.js.map +1 -0
  13. package/dist/index.d.ts +4 -0
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +4 -0
  16. package/dist/index.js.map +1 -1
  17. package/dist/models.generated.d.ts +583 -105
  18. package/dist/models.generated.d.ts.map +1 -1
  19. package/dist/models.generated.js +605 -127
  20. package/dist/models.generated.js.map +1 -1
  21. package/dist/providers/amazon-bedrock.d.ts +3 -2
  22. package/dist/providers/amazon-bedrock.d.ts.map +1 -1
  23. package/dist/providers/amazon-bedrock.js +52 -5
  24. package/dist/providers/amazon-bedrock.js.map +1 -1
  25. package/dist/providers/anthropic.d.ts +3 -2
  26. package/dist/providers/anthropic.d.ts.map +1 -1
  27. package/dist/providers/anthropic.js +20 -2
  28. package/dist/providers/anthropic.js.map +1 -1
  29. package/dist/providers/azure-openai-responses.d.ts +15 -0
  30. package/dist/providers/azure-openai-responses.d.ts.map +1 -0
  31. package/dist/providers/azure-openai-responses.js +184 -0
  32. package/dist/providers/azure-openai-responses.js.map +1 -0
  33. package/dist/providers/google-gemini-cli.d.ts +3 -2
  34. package/dist/providers/google-gemini-cli.d.ts.map +1 -1
  35. package/dist/providers/google-gemini-cli.js +68 -1
  36. package/dist/providers/google-gemini-cli.js.map +1 -1
  37. package/dist/providers/google-vertex.d.ts +3 -2
  38. package/dist/providers/google-vertex.d.ts.map +1 -1
  39. package/dist/providers/google-vertex.js +81 -1
  40. package/dist/providers/google-vertex.js.map +1 -1
  41. package/dist/providers/google.d.ts +3 -2
  42. package/dist/providers/google.d.ts.map +1 -1
  43. package/dist/providers/google.js +84 -3
  44. package/dist/providers/google.js.map +1 -1
  45. package/dist/providers/openai-codex-responses.d.ts +3 -2
  46. package/dist/providers/openai-codex-responses.d.ts.map +1 -1
  47. package/dist/providers/openai-codex-responses.js +57 -307
  48. package/dist/providers/openai-codex-responses.js.map +1 -1
  49. package/dist/providers/openai-completions.d.ts +5 -2
  50. package/dist/providers/openai-completions.d.ts.map +1 -1
  51. package/dist/providers/openai-completions.js +78 -41
  52. package/dist/providers/openai-completions.js.map +1 -1
  53. package/dist/providers/openai-responses-shared.d.ts +17 -0
  54. package/dist/providers/openai-responses-shared.d.ts.map +1 -0
  55. package/dist/providers/openai-responses-shared.js +424 -0
  56. package/dist/providers/openai-responses-shared.js.map +1 -0
  57. package/dist/providers/openai-responses.d.ts +3 -2
  58. package/dist/providers/openai-responses.d.ts.map +1 -1
  59. package/dist/providers/openai-responses.js +25 -415
  60. package/dist/providers/openai-responses.js.map +1 -1
  61. package/dist/providers/register-builtins.d.ts +3 -0
  62. package/dist/providers/register-builtins.d.ts.map +1 -0
  63. package/dist/providers/register-builtins.js +63 -0
  64. package/dist/providers/register-builtins.js.map +1 -0
  65. package/dist/providers/simple-options.d.ts +8 -0
  66. package/dist/providers/simple-options.d.ts.map +1 -0
  67. package/dist/providers/simple-options.js +32 -0
  68. package/dist/providers/simple-options.js.map +1 -0
  69. package/dist/stream.d.ts +5 -10
  70. package/dist/stream.d.ts.map +1 -1
  71. package/dist/stream.js +17 -420
  72. package/dist/stream.js.map +1 -1
  73. package/dist/types.d.ts +18 -22
  74. package/dist/types.d.ts.map +1 -1
  75. package/dist/types.js +0 -1
  76. package/dist/types.js.map +1 -1
  77. package/dist/utils/event-stream.d.ts +2 -0
  78. package/dist/utils/event-stream.d.ts.map +1 -1
  79. package/dist/utils/event-stream.js +4 -0
  80. package/dist/utils/event-stream.js.map +1 -1
  81. package/dist/utils/oauth/anthropic.d.ts +2 -1
  82. package/dist/utils/oauth/anthropic.d.ts.map +1 -1
  83. package/dist/utils/oauth/anthropic.js +13 -0
  84. package/dist/utils/oauth/anthropic.js.map +1 -1
  85. package/dist/utils/oauth/github-copilot.d.ts +2 -1
  86. package/dist/utils/oauth/github-copilot.d.ts.map +1 -1
  87. package/dist/utils/oauth/github-copilot.js +25 -0
  88. package/dist/utils/oauth/github-copilot.js.map +1 -1
  89. package/dist/utils/oauth/google-antigravity.d.ts +2 -1
  90. package/dist/utils/oauth/google-antigravity.d.ts.map +1 -1
  91. package/dist/utils/oauth/google-antigravity.js +19 -0
  92. package/dist/utils/oauth/google-antigravity.js.map +1 -1
  93. package/dist/utils/oauth/google-gemini-cli.d.ts +2 -1
  94. package/dist/utils/oauth/google-gemini-cli.d.ts.map +1 -1
  95. package/dist/utils/oauth/google-gemini-cli.js +19 -0
  96. package/dist/utils/oauth/google-gemini-cli.js.map +1 -1
  97. package/dist/utils/oauth/index.d.ts +26 -16
  98. package/dist/utils/oauth/index.d.ts.map +1 -1
  99. package/dist/utils/oauth/index.js +65 -84
  100. package/dist/utils/oauth/index.js.map +1 -1
  101. package/dist/utils/oauth/openai-codex.d.ts +2 -1
  102. package/dist/utils/oauth/openai-codex.d.ts.map +1 -1
  103. package/dist/utils/oauth/openai-codex.js +20 -1
  104. package/dist/utils/oauth/openai-codex.js.map +1 -1
  105. package/dist/utils/oauth/types.d.ts +28 -6
  106. package/dist/utils/oauth/types.d.ts.map +1 -1
  107. package/dist/utils/oauth/types.js.map +1 -1
  108. package/package.json +3 -1
@@ -0,0 +1,17 @@
1
+ import type { Tool as OpenAITool, ResponseCreateParamsStreaming, ResponseInput, ResponseStreamEvent } from "openai/resources/responses/responses.js";
2
+ import type { Api, AssistantMessage, Context, Model, Tool, Usage } from "../types.js";
3
+ import type { AssistantMessageEventStream } from "../utils/event-stream.js";
4
+ export interface OpenAIResponsesStreamOptions {
5
+ serviceTier?: ResponseCreateParamsStreaming["service_tier"];
6
+ applyServiceTierPricing?: (usage: Usage, serviceTier: ResponseCreateParamsStreaming["service_tier"] | undefined) => void;
7
+ }
8
+ export interface ConvertResponsesMessagesOptions {
9
+ includeSystemPrompt?: boolean;
10
+ }
11
+ export interface ConvertResponsesToolsOptions {
12
+ strict?: boolean | null;
13
+ }
14
+ export declare function convertResponsesMessages<TApi extends Api>(model: Model<TApi>, context: Context, allowedToolCallProviders: ReadonlySet<string>, options?: ConvertResponsesMessagesOptions): ResponseInput;
15
+ export declare function convertResponsesTools(tools: Tool[], options?: ConvertResponsesToolsOptions): OpenAITool[];
16
+ export declare function processResponsesStream<TApi extends Api>(openaiStream: AsyncIterable<ResponseStreamEvent>, output: AssistantMessage, stream: AssistantMessageEventStream, model: Model<TApi>, options?: OpenAIResponsesStreamOptions): Promise<void>;
17
+ //# sourceMappingURL=openai-responses-shared.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"openai-responses-shared.d.ts","sourceRoot":"","sources":["../../src/providers/openai-responses-shared.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACX,IAAI,IAAI,UAAU,EAClB,6BAA6B,EAE7B,aAAa,EAMb,mBAAmB,EACnB,MAAM,yCAAyC,CAAC;AAEjD,OAAO,KAAK,EACX,GAAG,EACH,gBAAgB,EAChB,OAAO,EAEP,KAAK,EAIL,IAAI,EAEJ,KAAK,EACL,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;AAuB5E,MAAM,WAAW,4BAA4B;IAC5C,WAAW,CAAC,EAAE,6BAA6B,CAAC,cAAc,CAAC,CAAC;IAC5D,uBAAuB,CAAC,EAAE,CACzB,KAAK,EAAE,KAAK,EACZ,WAAW,EAAE,6BAA6B,CAAC,cAAc,CAAC,GAAG,SAAS,KAClE,IAAI,CAAC;CACV;AAED,MAAM,WAAW,+BAA+B;IAC/C,mBAAmB,CAAC,EAAE,OAAO,CAAC;CAC9B;AAED,MAAM,WAAW,4BAA4B;IAC5C,MAAM,CAAC,EAAE,OAAO,GAAG,IAAI,CAAC;CACxB;AAMD,wBAAgB,wBAAwB,CAAC,IAAI,SAAS,GAAG,EACxD,KAAK,EAAE,KAAK,CAAC,IAAI,CAAC,EAClB,OAAO,EAAE,OAAO,EAChB,wBAAwB,EAAE,WAAW,CAAC,MAAM,CAAC,EAC7C,OAAO,CAAC,EAAE,+BAA+B,GACvC,aAAa,CAiKf;AAMD,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,IAAI,EAAE,EAAE,OAAO,CAAC,EAAE,4BAA4B,GAAG,UAAU,EAAE,CASzG;AAMD,wBAAsB,sBAAsB,CAAC,IAAI,SAAS,GAAG,EAC5D,YAAY,EAAE,aAAa,CAAC,mBAAmB,CAAC,EAChD,MAAM,EAAE,gBAAgB,EACxB,MAAM,EAAE,2BAA2B,EACnC,KAAK,EAAE,KAAK,CAAC,IAAI,CAAC,EAClB,OAAO,CAAC,EAAE,4BAA4B,GACpC,OAAO,CAAC,IAAI,CAAC,CAgMf","sourcesContent":["import type 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\tResponseStreamEvent,\n} from \"openai/resources/responses/responses.js\";\nimport { calculateCost } from \"../models.js\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tContext,\n\tImageContent,\n\tModel,\n\tStopReason,\n\tTextContent,\n\tThinkingContent,\n\tTool,\n\tToolCall,\n\tUsage,\n} from \"../types.js\";\nimport type { AssistantMessageEventStream } from \"../utils/event-stream.js\";\nimport { parseStreamingJson } from \"../utils/json-parse.js\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.js\";\nimport { transformMessages } from \"./transform-messages.js\";\n\n// =============================================================================\n// Utilities\n// =============================================================================\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\nexport interface OpenAIResponsesStreamOptions {\n\tserviceTier?: ResponseCreateParamsStreaming[\"service_tier\"];\n\tapplyServiceTierPricing?: (\n\t\tusage: Usage,\n\t\tserviceTier: ResponseCreateParamsStreaming[\"service_tier\"] | undefined,\n\t) => void;\n}\n\nexport interface ConvertResponsesMessagesOptions {\n\tincludeSystemPrompt?: boolean;\n}\n\nexport interface ConvertResponsesToolsOptions {\n\tstrict?: boolean | null;\n}\n\n// =============================================================================\n// Message conversion\n// =============================================================================\n\nexport function convertResponsesMessages<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\tallowedToolCallProviders: ReadonlySet<string>,\n\toptions?: ConvertResponsesMessagesOptions,\n): ResponseInput {\n\tconst messages: ResponseInput = [];\n\n\tconst normalizeToolCallId = (id: string): string => {\n\t\tif (!allowedToolCallProviders.has(model.provider)) return id;\n\t\tif (!id.includes(\"|\")) return id;\n\t\tconst [callId, itemId] = id.split(\"|\");\n\t\tconst sanitizedCallId = callId.replace(/[^a-zA-Z0-9_-]/g, \"_\");\n\t\tlet sanitizedItemId = itemId.replace(/[^a-zA-Z0-9_-]/g, \"_\");\n\t\t// OpenAI Responses API requires item id to start with \"fc\"\n\t\tif (!sanitizedItemId.startsWith(\"fc\")) {\n\t\t\tsanitizedItemId = `fc_${sanitizedItemId}`;\n\t\t}\n\t\tconst normalizedCallId = sanitizedCallId.length > 64 ? sanitizedCallId.slice(0, 64) : sanitizedCallId;\n\t\tconst normalizedItemId = sanitizedItemId.length > 64 ? sanitizedItemId.slice(0, 64) : sanitizedItemId;\n\t\treturn `${normalizedCallId}|${normalizedItemId}`;\n\t};\n\n\tconst transformedMessages = transformMessages(context.messages, model, normalizeToolCallId);\n\n\tconst includeSystemPrompt = options?.includeSystemPrompt ?? true;\n\tif (includeSystemPrompt && 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}\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"input_image\",\n\t\t\t\t\t\tdetail: \"auto\",\n\t\t\t\t\t\timage_url: `data:${item.mimeType};base64,${item.data}`,\n\t\t\t\t\t} satisfies ResponseInputImage;\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\t\t\tconst assistantMsg = msg as AssistantMessage;\n\t\t\tconst isDifferentModel =\n\t\t\t\tassistantMsg.model !== model.id &&\n\t\t\t\tassistantMsg.provider === model.provider &&\n\t\t\t\tassistantMsg.api === model.api;\n\n\t\t\tfor (const block of msg.content) {\n\t\t\t\tif (block.type === \"thinking\") {\n\t\t\t\t\tif (block.thinkingSignature) {\n\t\t\t\t\t\tconst reasoningItem = JSON.parse(block.thinkingSignature) as ResponseReasoningItem;\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} else if (block.type === \"toolCall\") {\n\t\t\t\t\tconst toolCall = block as ToolCall;\n\t\t\t\t\tconst [callId, itemIdRaw] = toolCall.id.split(\"|\");\n\t\t\t\t\tlet itemId: string | undefined = itemIdRaw;\n\n\t\t\t\t\t// For different-model messages, set id to undefined to avoid pairing validation.\n\t\t\t\t\t// OpenAI tracks which fc_xxx IDs were paired with rs_xxx reasoning items.\n\t\t\t\t\t// By omitting the id, we avoid triggering that validation (like cross-provider does).\n\t\t\t\t\tif (isDifferentModel && itemId?.startsWith(\"fc_\")) {\n\t\t\t\t\t\titemId = undefined;\n\t\t\t\t\t}\n\n\t\t\t\t\toutput.push({\n\t\t\t\t\t\ttype: \"function_call\",\n\t\t\t\t\t\tid: itemId,\n\t\t\t\t\t\tcall_id: callId,\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 is TextContent => c.type === \"text\")\n\t\t\t\t.map((c) => c.text)\n\t\t\t\t.join(\"\\n\");\n\t\t\tconst hasImages = msg.content.some((c): c is ImageContent => 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\tconst [callId] = msg.toolCallId.split(\"|\");\n\t\t\tmessages.push({\n\t\t\t\ttype: \"function_call_output\",\n\t\t\t\tcall_id: callId,\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.mimeType};base64,${block.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\n// =============================================================================\n// Tool conversion\n// =============================================================================\n\nexport function convertResponsesTools(tools: Tool[], options?: ConvertResponsesToolsOptions): OpenAITool[] {\n\tconst strict = options?.strict === undefined ? false : options.strict;\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,\n\t}));\n}\n\n// =============================================================================\n// Stream processing\n// =============================================================================\n\nexport async function processResponsesStream<TApi extends Api>(\n\topenaiStream: AsyncIterable<ResponseStreamEvent>,\n\toutput: AssistantMessage,\n\tstream: AssistantMessageEventStream,\n\tmodel: Model<TApi>,\n\toptions?: OpenAIResponsesStreamOptions,\n): Promise<void> {\n\tlet currentItem: ResponseReasoningItem | ResponseOutputMessage | ResponseFunctionToolCall | null = null;\n\tlet currentBlock: ThinkingContent | TextContent | (ToolCall & { partialJson: string }) | null = null;\n\tconst blocks = output.content;\n\tconst blockIndex = () => blocks.length - 1;\n\n\tfor await (const event of openaiStream) {\n\t\tif (event.type === \"response.output_item.added\") {\n\t\t\tconst item = event.item;\n\t\t\tif (item.type === \"reasoning\") {\n\t\t\t\tcurrentItem = item;\n\t\t\t\tcurrentBlock = { type: \"thinking\", thinking: \"\" };\n\t\t\t\toutput.content.push(currentBlock);\n\t\t\t\tstream.push({ type: \"thinking_start\", contentIndex: blockIndex(), partial: output });\n\t\t\t} else if (item.type === \"message\") {\n\t\t\t\tcurrentItem = item;\n\t\t\t\tcurrentBlock = { type: \"text\", text: \"\" };\n\t\t\t\toutput.content.push(currentBlock);\n\t\t\t\tstream.push({ type: \"text_start\", contentIndex: blockIndex(), partial: output });\n\t\t\t} else if (item.type === \"function_call\") {\n\t\t\t\tcurrentItem = item;\n\t\t\t\tcurrentBlock = {\n\t\t\t\t\ttype: \"toolCall\",\n\t\t\t\t\tid: `${item.call_id}|${item.id}`,\n\t\t\t\t\tname: item.name,\n\t\t\t\t\targuments: {},\n\t\t\t\t\tpartialJson: item.arguments || \"\",\n\t\t\t\t};\n\t\t\t\toutput.content.push(currentBlock);\n\t\t\t\tstream.push({ type: \"toolcall_start\", contentIndex: blockIndex(), partial: output });\n\t\t\t}\n\t\t} else if (event.type === \"response.reasoning_summary_part.added\") {\n\t\t\tif (currentItem && currentItem.type === \"reasoning\") {\n\t\t\t\tcurrentItem.summary = currentItem.summary || [];\n\t\t\t\tcurrentItem.summary.push(event.part);\n\t\t\t}\n\t\t} else if (event.type === \"response.reasoning_summary_text.delta\") {\n\t\t\tif (currentItem?.type === \"reasoning\" && currentBlock?.type === \"thinking\") {\n\t\t\t\tcurrentItem.summary = currentItem.summary || [];\n\t\t\t\tconst lastPart = currentItem.summary[currentItem.summary.length - 1];\n\t\t\t\tif (lastPart) {\n\t\t\t\t\tcurrentBlock.thinking += event.delta;\n\t\t\t\t\tlastPart.text += event.delta;\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\tdelta: event.delta,\n\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (event.type === \"response.reasoning_summary_part.done\") {\n\t\t\tif (currentItem?.type === \"reasoning\" && currentBlock?.type === \"thinking\") {\n\t\t\t\tcurrentItem.summary = currentItem.summary || [];\n\t\t\t\tconst lastPart = currentItem.summary[currentItem.summary.length - 1];\n\t\t\t\tif (lastPart) {\n\t\t\t\t\tcurrentBlock.thinking += \"\\n\\n\";\n\t\t\t\t\tlastPart.text += \"\\n\\n\";\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\tdelta: \"\\n\\n\",\n\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (event.type === \"response.content_part.added\") {\n\t\t\tif (currentItem?.type === \"message\") {\n\t\t\t\tcurrentItem.content = currentItem.content || [];\n\t\t\t\t// Filter out ReasoningText, only accept output_text and refusal\n\t\t\t\tif (event.part.type === \"output_text\" || event.part.type === \"refusal\") {\n\t\t\t\t\tcurrentItem.content.push(event.part);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (event.type === \"response.output_text.delta\") {\n\t\t\tif (currentItem?.type === \"message\" && currentBlock?.type === \"text\") {\n\t\t\t\tif (!currentItem.content || currentItem.content.length === 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst lastPart = currentItem.content[currentItem.content.length - 1];\n\t\t\t\tif (lastPart?.type === \"output_text\") {\n\t\t\t\t\tcurrentBlock.text += event.delta;\n\t\t\t\t\tlastPart.text += event.delta;\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"text_delta\",\n\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\tdelta: event.delta,\n\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (event.type === \"response.refusal.delta\") {\n\t\t\tif (currentItem?.type === \"message\" && currentBlock?.type === \"text\") {\n\t\t\t\tif (!currentItem.content || currentItem.content.length === 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst lastPart = currentItem.content[currentItem.content.length - 1];\n\t\t\t\tif (lastPart?.type === \"refusal\") {\n\t\t\t\t\tcurrentBlock.text += event.delta;\n\t\t\t\t\tlastPart.refusal += event.delta;\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"text_delta\",\n\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\tdelta: event.delta,\n\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (event.type === \"response.function_call_arguments.delta\") {\n\t\t\tif (currentItem?.type === \"function_call\" && currentBlock?.type === \"toolCall\") {\n\t\t\t\tcurrentBlock.partialJson += event.delta;\n\t\t\t\tcurrentBlock.arguments = parseStreamingJson(currentBlock.partialJson);\n\t\t\t\tstream.push({\n\t\t\t\t\ttype: \"toolcall_delta\",\n\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\tdelta: event.delta,\n\t\t\t\t\tpartial: output,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (event.type === \"response.function_call_arguments.done\") {\n\t\t\tif (currentItem?.type === \"function_call\" && currentBlock?.type === \"toolCall\") {\n\t\t\t\tcurrentBlock.partialJson = event.arguments;\n\t\t\t\tcurrentBlock.arguments = parseStreamingJson(currentBlock.partialJson);\n\t\t\t}\n\t\t} else if (event.type === \"response.output_item.done\") {\n\t\t\tconst item = event.item;\n\n\t\t\tif (item.type === \"reasoning\" && currentBlock?.type === \"thinking\") {\n\t\t\t\tcurrentBlock.thinking = item.summary?.map((s) => s.text).join(\"\\n\\n\") || \"\";\n\t\t\t\tcurrentBlock.thinkingSignature = JSON.stringify(item);\n\t\t\t\tstream.push({\n\t\t\t\t\ttype: \"thinking_end\",\n\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\tcontent: currentBlock.thinking,\n\t\t\t\t\tpartial: output,\n\t\t\t\t});\n\t\t\t\tcurrentBlock = null;\n\t\t\t} else if (item.type === \"message\" && currentBlock?.type === \"text\") {\n\t\t\t\tcurrentBlock.text = item.content.map((c) => (c.type === \"output_text\" ? c.text : c.refusal)).join(\"\");\n\t\t\t\tcurrentBlock.textSignature = item.id;\n\t\t\t\tstream.push({\n\t\t\t\t\ttype: \"text_end\",\n\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\tcontent: currentBlock.text,\n\t\t\t\t\tpartial: output,\n\t\t\t\t});\n\t\t\t\tcurrentBlock = null;\n\t\t\t} else if (item.type === \"function_call\") {\n\t\t\t\tconst args =\n\t\t\t\t\tcurrentBlock?.type === \"toolCall\" && currentBlock.partialJson\n\t\t\t\t\t\t? JSON.parse(currentBlock.partialJson)\n\t\t\t\t\t\t: JSON.parse(item.arguments);\n\t\t\t\tconst toolCall: ToolCall = {\n\t\t\t\t\ttype: \"toolCall\",\n\t\t\t\t\tid: `${item.call_id}|${item.id}`,\n\t\t\t\t\tname: item.name,\n\t\t\t\t\targuments: args,\n\t\t\t\t};\n\n\t\t\t\tcurrentBlock = null;\n\t\t\t\tstream.push({ type: \"toolcall_end\", contentIndex: blockIndex(), toolCall, partial: output });\n\t\t\t}\n\t\t} else if (event.type === \"response.completed\") {\n\t\t\tconst response = event.response;\n\t\t\tif (response?.usage) {\n\t\t\t\tconst cachedTokens = response.usage.input_tokens_details?.cached_tokens || 0;\n\t\t\t\toutput.usage = {\n\t\t\t\t\t// OpenAI includes cached tokens in input_tokens, so subtract to get non-cached input\n\t\t\t\t\tinput: (response.usage.input_tokens || 0) - cachedTokens,\n\t\t\t\t\toutput: response.usage.output_tokens || 0,\n\t\t\t\t\tcacheRead: cachedTokens,\n\t\t\t\t\tcacheWrite: 0,\n\t\t\t\t\ttotalTokens: response.usage.total_tokens || 0,\n\t\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t\t};\n\t\t\t}\n\t\t\tcalculateCost(model, output.usage);\n\t\t\tif (options?.applyServiceTierPricing) {\n\t\t\t\tconst serviceTier = response?.service_tier ?? options.serviceTier;\n\t\t\t\toptions.applyServiceTierPricing(output.usage, serviceTier);\n\t\t\t}\n\t\t\t// Map status to stop reason\n\t\t\toutput.stopReason = mapStopReason(response?.status);\n\t\t\tif (output.content.some((b) => b.type === \"toolCall\") && output.stopReason === \"stop\") {\n\t\t\t\toutput.stopReason = \"toolUse\";\n\t\t\t}\n\t\t} else if (event.type === \"error\") {\n\t\t\tthrow new Error(`Error Code ${event.code}: ${event.message}` || \"Unknown error\");\n\t\t} else if (event.type === \"response.failed\") {\n\t\t\tthrow new Error(\"Unknown error\");\n\t\t}\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"]}
@@ -0,0 +1,424 @@
1
+ import { calculateCost } from "../models.js";
2
+ import { parseStreamingJson } from "../utils/json-parse.js";
3
+ import { sanitizeSurrogates } from "../utils/sanitize-unicode.js";
4
+ import { transformMessages } from "./transform-messages.js";
5
+ // =============================================================================
6
+ // Utilities
7
+ // =============================================================================
8
+ /** Fast deterministic hash to shorten long strings */
9
+ function shortHash(str) {
10
+ let h1 = 0xdeadbeef;
11
+ let h2 = 0x41c6ce57;
12
+ for (let i = 0; i < str.length; i++) {
13
+ const ch = str.charCodeAt(i);
14
+ h1 = Math.imul(h1 ^ ch, 2654435761);
15
+ h2 = Math.imul(h2 ^ ch, 1597334677);
16
+ }
17
+ h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
18
+ h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
19
+ return (h2 >>> 0).toString(36) + (h1 >>> 0).toString(36);
20
+ }
21
+ // =============================================================================
22
+ // Message conversion
23
+ // =============================================================================
24
+ export function convertResponsesMessages(model, context, allowedToolCallProviders, options) {
25
+ const messages = [];
26
+ const normalizeToolCallId = (id) => {
27
+ if (!allowedToolCallProviders.has(model.provider))
28
+ return id;
29
+ if (!id.includes("|"))
30
+ return id;
31
+ const [callId, itemId] = id.split("|");
32
+ const sanitizedCallId = callId.replace(/[^a-zA-Z0-9_-]/g, "_");
33
+ let sanitizedItemId = itemId.replace(/[^a-zA-Z0-9_-]/g, "_");
34
+ // OpenAI Responses API requires item id to start with "fc"
35
+ if (!sanitizedItemId.startsWith("fc")) {
36
+ sanitizedItemId = `fc_${sanitizedItemId}`;
37
+ }
38
+ const normalizedCallId = sanitizedCallId.length > 64 ? sanitizedCallId.slice(0, 64) : sanitizedCallId;
39
+ const normalizedItemId = sanitizedItemId.length > 64 ? sanitizedItemId.slice(0, 64) : sanitizedItemId;
40
+ return `${normalizedCallId}|${normalizedItemId}`;
41
+ };
42
+ const transformedMessages = transformMessages(context.messages, model, normalizeToolCallId);
43
+ const includeSystemPrompt = options?.includeSystemPrompt ?? true;
44
+ if (includeSystemPrompt && context.systemPrompt) {
45
+ const role = model.reasoning ? "developer" : "system";
46
+ messages.push({
47
+ role,
48
+ content: sanitizeSurrogates(context.systemPrompt),
49
+ });
50
+ }
51
+ let msgIndex = 0;
52
+ for (const msg of transformedMessages) {
53
+ if (msg.role === "user") {
54
+ if (typeof msg.content === "string") {
55
+ messages.push({
56
+ role: "user",
57
+ content: [{ type: "input_text", text: sanitizeSurrogates(msg.content) }],
58
+ });
59
+ }
60
+ else {
61
+ const content = msg.content.map((item) => {
62
+ if (item.type === "text") {
63
+ return {
64
+ type: "input_text",
65
+ text: sanitizeSurrogates(item.text),
66
+ };
67
+ }
68
+ return {
69
+ type: "input_image",
70
+ detail: "auto",
71
+ image_url: `data:${item.mimeType};base64,${item.data}`,
72
+ };
73
+ });
74
+ const filteredContent = !model.input.includes("image")
75
+ ? content.filter((c) => c.type !== "input_image")
76
+ : content;
77
+ if (filteredContent.length === 0)
78
+ continue;
79
+ messages.push({
80
+ role: "user",
81
+ content: filteredContent,
82
+ });
83
+ }
84
+ }
85
+ else if (msg.role === "assistant") {
86
+ const output = [];
87
+ const assistantMsg = msg;
88
+ const isDifferentModel = assistantMsg.model !== model.id &&
89
+ assistantMsg.provider === model.provider &&
90
+ assistantMsg.api === model.api;
91
+ for (const block of msg.content) {
92
+ if (block.type === "thinking") {
93
+ if (block.thinkingSignature) {
94
+ const reasoningItem = JSON.parse(block.thinkingSignature);
95
+ output.push(reasoningItem);
96
+ }
97
+ }
98
+ else if (block.type === "text") {
99
+ const textBlock = block;
100
+ // OpenAI requires id to be max 64 characters
101
+ let msgId = textBlock.textSignature;
102
+ if (!msgId) {
103
+ msgId = `msg_${msgIndex}`;
104
+ }
105
+ else if (msgId.length > 64) {
106
+ msgId = `msg_${shortHash(msgId)}`;
107
+ }
108
+ output.push({
109
+ type: "message",
110
+ role: "assistant",
111
+ content: [{ type: "output_text", text: sanitizeSurrogates(textBlock.text), annotations: [] }],
112
+ status: "completed",
113
+ id: msgId,
114
+ });
115
+ }
116
+ else if (block.type === "toolCall") {
117
+ const toolCall = block;
118
+ const [callId, itemIdRaw] = toolCall.id.split("|");
119
+ let itemId = itemIdRaw;
120
+ // For different-model messages, set id to undefined to avoid pairing validation.
121
+ // OpenAI tracks which fc_xxx IDs were paired with rs_xxx reasoning items.
122
+ // By omitting the id, we avoid triggering that validation (like cross-provider does).
123
+ if (isDifferentModel && itemId?.startsWith("fc_")) {
124
+ itemId = undefined;
125
+ }
126
+ output.push({
127
+ type: "function_call",
128
+ id: itemId,
129
+ call_id: callId,
130
+ name: toolCall.name,
131
+ arguments: JSON.stringify(toolCall.arguments),
132
+ });
133
+ }
134
+ }
135
+ if (output.length === 0)
136
+ continue;
137
+ messages.push(...output);
138
+ }
139
+ else if (msg.role === "toolResult") {
140
+ // Extract text and image content
141
+ const textResult = msg.content
142
+ .filter((c) => c.type === "text")
143
+ .map((c) => c.text)
144
+ .join("\n");
145
+ const hasImages = msg.content.some((c) => c.type === "image");
146
+ // Always send function_call_output with text (or placeholder if only images)
147
+ const hasText = textResult.length > 0;
148
+ const [callId] = msg.toolCallId.split("|");
149
+ messages.push({
150
+ type: "function_call_output",
151
+ call_id: callId,
152
+ output: sanitizeSurrogates(hasText ? textResult : "(see attached image)"),
153
+ });
154
+ // If there are images and model supports them, send a follow-up user message with images
155
+ if (hasImages && model.input.includes("image")) {
156
+ const contentParts = [];
157
+ // Add text prefix
158
+ contentParts.push({
159
+ type: "input_text",
160
+ text: "Attached image(s) from tool result:",
161
+ });
162
+ // Add images
163
+ for (const block of msg.content) {
164
+ if (block.type === "image") {
165
+ contentParts.push({
166
+ type: "input_image",
167
+ detail: "auto",
168
+ image_url: `data:${block.mimeType};base64,${block.data}`,
169
+ });
170
+ }
171
+ }
172
+ messages.push({
173
+ role: "user",
174
+ content: contentParts,
175
+ });
176
+ }
177
+ }
178
+ msgIndex++;
179
+ }
180
+ return messages;
181
+ }
182
+ // =============================================================================
183
+ // Tool conversion
184
+ // =============================================================================
185
+ export function convertResponsesTools(tools, options) {
186
+ const strict = options?.strict === undefined ? false : options.strict;
187
+ return tools.map((tool) => ({
188
+ type: "function",
189
+ name: tool.name,
190
+ description: tool.description,
191
+ parameters: tool.parameters, // TypeBox already generates JSON Schema
192
+ strict,
193
+ }));
194
+ }
195
+ // =============================================================================
196
+ // Stream processing
197
+ // =============================================================================
198
+ export async function processResponsesStream(openaiStream, output, stream, model, options) {
199
+ let currentItem = null;
200
+ let currentBlock = null;
201
+ const blocks = output.content;
202
+ const blockIndex = () => blocks.length - 1;
203
+ for await (const event of openaiStream) {
204
+ if (event.type === "response.output_item.added") {
205
+ const item = event.item;
206
+ if (item.type === "reasoning") {
207
+ currentItem = item;
208
+ currentBlock = { type: "thinking", thinking: "" };
209
+ output.content.push(currentBlock);
210
+ stream.push({ type: "thinking_start", contentIndex: blockIndex(), partial: output });
211
+ }
212
+ else if (item.type === "message") {
213
+ currentItem = item;
214
+ currentBlock = { type: "text", text: "" };
215
+ output.content.push(currentBlock);
216
+ stream.push({ type: "text_start", contentIndex: blockIndex(), partial: output });
217
+ }
218
+ else if (item.type === "function_call") {
219
+ currentItem = item;
220
+ currentBlock = {
221
+ type: "toolCall",
222
+ id: `${item.call_id}|${item.id}`,
223
+ name: item.name,
224
+ arguments: {},
225
+ partialJson: item.arguments || "",
226
+ };
227
+ output.content.push(currentBlock);
228
+ stream.push({ type: "toolcall_start", contentIndex: blockIndex(), partial: output });
229
+ }
230
+ }
231
+ else if (event.type === "response.reasoning_summary_part.added") {
232
+ if (currentItem && currentItem.type === "reasoning") {
233
+ currentItem.summary = currentItem.summary || [];
234
+ currentItem.summary.push(event.part);
235
+ }
236
+ }
237
+ else if (event.type === "response.reasoning_summary_text.delta") {
238
+ if (currentItem?.type === "reasoning" && currentBlock?.type === "thinking") {
239
+ currentItem.summary = currentItem.summary || [];
240
+ const lastPart = currentItem.summary[currentItem.summary.length - 1];
241
+ if (lastPart) {
242
+ currentBlock.thinking += event.delta;
243
+ lastPart.text += event.delta;
244
+ stream.push({
245
+ type: "thinking_delta",
246
+ contentIndex: blockIndex(),
247
+ delta: event.delta,
248
+ partial: output,
249
+ });
250
+ }
251
+ }
252
+ }
253
+ else if (event.type === "response.reasoning_summary_part.done") {
254
+ if (currentItem?.type === "reasoning" && currentBlock?.type === "thinking") {
255
+ currentItem.summary = currentItem.summary || [];
256
+ const lastPart = currentItem.summary[currentItem.summary.length - 1];
257
+ if (lastPart) {
258
+ currentBlock.thinking += "\n\n";
259
+ lastPart.text += "\n\n";
260
+ stream.push({
261
+ type: "thinking_delta",
262
+ contentIndex: blockIndex(),
263
+ delta: "\n\n",
264
+ partial: output,
265
+ });
266
+ }
267
+ }
268
+ }
269
+ else if (event.type === "response.content_part.added") {
270
+ if (currentItem?.type === "message") {
271
+ currentItem.content = currentItem.content || [];
272
+ // Filter out ReasoningText, only accept output_text and refusal
273
+ if (event.part.type === "output_text" || event.part.type === "refusal") {
274
+ currentItem.content.push(event.part);
275
+ }
276
+ }
277
+ }
278
+ else if (event.type === "response.output_text.delta") {
279
+ if (currentItem?.type === "message" && currentBlock?.type === "text") {
280
+ if (!currentItem.content || currentItem.content.length === 0) {
281
+ continue;
282
+ }
283
+ const lastPart = currentItem.content[currentItem.content.length - 1];
284
+ if (lastPart?.type === "output_text") {
285
+ currentBlock.text += event.delta;
286
+ lastPart.text += event.delta;
287
+ stream.push({
288
+ type: "text_delta",
289
+ contentIndex: blockIndex(),
290
+ delta: event.delta,
291
+ partial: output,
292
+ });
293
+ }
294
+ }
295
+ }
296
+ else if (event.type === "response.refusal.delta") {
297
+ if (currentItem?.type === "message" && currentBlock?.type === "text") {
298
+ if (!currentItem.content || currentItem.content.length === 0) {
299
+ continue;
300
+ }
301
+ const lastPart = currentItem.content[currentItem.content.length - 1];
302
+ if (lastPart?.type === "refusal") {
303
+ currentBlock.text += event.delta;
304
+ lastPart.refusal += event.delta;
305
+ stream.push({
306
+ type: "text_delta",
307
+ contentIndex: blockIndex(),
308
+ delta: event.delta,
309
+ partial: output,
310
+ });
311
+ }
312
+ }
313
+ }
314
+ else if (event.type === "response.function_call_arguments.delta") {
315
+ if (currentItem?.type === "function_call" && currentBlock?.type === "toolCall") {
316
+ currentBlock.partialJson += event.delta;
317
+ currentBlock.arguments = parseStreamingJson(currentBlock.partialJson);
318
+ stream.push({
319
+ type: "toolcall_delta",
320
+ contentIndex: blockIndex(),
321
+ delta: event.delta,
322
+ partial: output,
323
+ });
324
+ }
325
+ }
326
+ else if (event.type === "response.function_call_arguments.done") {
327
+ if (currentItem?.type === "function_call" && currentBlock?.type === "toolCall") {
328
+ currentBlock.partialJson = event.arguments;
329
+ currentBlock.arguments = parseStreamingJson(currentBlock.partialJson);
330
+ }
331
+ }
332
+ else if (event.type === "response.output_item.done") {
333
+ const item = event.item;
334
+ if (item.type === "reasoning" && currentBlock?.type === "thinking") {
335
+ currentBlock.thinking = item.summary?.map((s) => s.text).join("\n\n") || "";
336
+ currentBlock.thinkingSignature = JSON.stringify(item);
337
+ stream.push({
338
+ type: "thinking_end",
339
+ contentIndex: blockIndex(),
340
+ content: currentBlock.thinking,
341
+ partial: output,
342
+ });
343
+ currentBlock = null;
344
+ }
345
+ else if (item.type === "message" && currentBlock?.type === "text") {
346
+ currentBlock.text = item.content.map((c) => (c.type === "output_text" ? c.text : c.refusal)).join("");
347
+ currentBlock.textSignature = item.id;
348
+ stream.push({
349
+ type: "text_end",
350
+ contentIndex: blockIndex(),
351
+ content: currentBlock.text,
352
+ partial: output,
353
+ });
354
+ currentBlock = null;
355
+ }
356
+ else if (item.type === "function_call") {
357
+ const args = currentBlock?.type === "toolCall" && currentBlock.partialJson
358
+ ? JSON.parse(currentBlock.partialJson)
359
+ : JSON.parse(item.arguments);
360
+ const toolCall = {
361
+ type: "toolCall",
362
+ id: `${item.call_id}|${item.id}`,
363
+ name: item.name,
364
+ arguments: args,
365
+ };
366
+ currentBlock = null;
367
+ stream.push({ type: "toolcall_end", contentIndex: blockIndex(), toolCall, partial: output });
368
+ }
369
+ }
370
+ else if (event.type === "response.completed") {
371
+ const response = event.response;
372
+ if (response?.usage) {
373
+ const cachedTokens = response.usage.input_tokens_details?.cached_tokens || 0;
374
+ output.usage = {
375
+ // OpenAI includes cached tokens in input_tokens, so subtract to get non-cached input
376
+ input: (response.usage.input_tokens || 0) - cachedTokens,
377
+ output: response.usage.output_tokens || 0,
378
+ cacheRead: cachedTokens,
379
+ cacheWrite: 0,
380
+ totalTokens: response.usage.total_tokens || 0,
381
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
382
+ };
383
+ }
384
+ calculateCost(model, output.usage);
385
+ if (options?.applyServiceTierPricing) {
386
+ const serviceTier = response?.service_tier ?? options.serviceTier;
387
+ options.applyServiceTierPricing(output.usage, serviceTier);
388
+ }
389
+ // Map status to stop reason
390
+ output.stopReason = mapStopReason(response?.status);
391
+ if (output.content.some((b) => b.type === "toolCall") && output.stopReason === "stop") {
392
+ output.stopReason = "toolUse";
393
+ }
394
+ }
395
+ else if (event.type === "error") {
396
+ throw new Error(`Error Code ${event.code}: ${event.message}` || "Unknown error");
397
+ }
398
+ else if (event.type === "response.failed") {
399
+ throw new Error("Unknown error");
400
+ }
401
+ }
402
+ }
403
+ function mapStopReason(status) {
404
+ if (!status)
405
+ return "stop";
406
+ switch (status) {
407
+ case "completed":
408
+ return "stop";
409
+ case "incomplete":
410
+ return "length";
411
+ case "failed":
412
+ case "cancelled":
413
+ return "error";
414
+ // These two are wonky ...
415
+ case "in_progress":
416
+ case "queued":
417
+ return "stop";
418
+ default: {
419
+ const _exhaustive = status;
420
+ throw new Error(`Unhandled stop reason: ${_exhaustive}`);
421
+ }
422
+ }
423
+ }
424
+ //# sourceMappingURL=openai-responses-shared.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"openai-responses-shared.js","sourceRoot":"","sources":["../../src/providers/openai-responses-shared.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAe7C,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAC5D,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAE5D,gFAAgF;AAChF,YAAY;AACZ,gFAAgF;AAEhF,sDAAsD;AACtD,SAAS,SAAS,CAAC,GAAW,EAAU;IACvC,IAAI,EAAE,GAAG,UAAU,CAAC;IACpB,IAAI,EAAE,GAAG,UAAU,CAAC;IACpB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QACrC,MAAM,EAAE,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;QAC7B,EAAE,GAAG,I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,EAAE,IAAI,eAAe,CAAC,CAAC;QAClF,CAAC;aAAM,IAAI,KAAK,CAAC,IAAI,KAAK,iBAAiB,EAAE,CAAC;YAC7C,MAAM,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC;QAClC,CAAC;IACF,CAAC;AAAA,CACD;AAED,SAAS,aAAa,CAAC,MAAmD,EAAc;IACvF,IAAI,CAAC,MAAM;QAAE,OAAO,MAAM,CAAC;IAC3B,QAAQ,MAAM,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 type 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\tResponseStreamEvent,\n} from \"openai/resources/responses/responses.js\";\nimport { calculateCost } from \"../models.js\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tContext,\n\tImageContent,\n\tModel,\n\tStopReason,\n\tTextContent,\n\tThinkingContent,\n\tTool,\n\tToolCall,\n\tUsage,\n} from \"../types.js\";\nimport type { AssistantMessageEventStream } from \"../utils/event-stream.js\";\nimport { parseStreamingJson } from \"../utils/json-parse.js\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.js\";\nimport { transformMessages } from \"./transform-messages.js\";\n\n// =============================================================================\n// Utilities\n// =============================================================================\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\nexport interface OpenAIResponsesStreamOptions {\n\tserviceTier?: ResponseCreateParamsStreaming[\"service_tier\"];\n\tapplyServiceTierPricing?: (\n\t\tusage: Usage,\n\t\tserviceTier: ResponseCreateParamsStreaming[\"service_tier\"] | undefined,\n\t) => void;\n}\n\nexport interface ConvertResponsesMessagesOptions {\n\tincludeSystemPrompt?: boolean;\n}\n\nexport interface ConvertResponsesToolsOptions {\n\tstrict?: boolean | null;\n}\n\n// =============================================================================\n// Message conversion\n// =============================================================================\n\nexport function convertResponsesMessages<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\tallowedToolCallProviders: ReadonlySet<string>,\n\toptions?: ConvertResponsesMessagesOptions,\n): ResponseInput {\n\tconst messages: ResponseInput = [];\n\n\tconst normalizeToolCallId = (id: string): string => {\n\t\tif (!allowedToolCallProviders.has(model.provider)) return id;\n\t\tif (!id.includes(\"|\")) return id;\n\t\tconst [callId, itemId] = id.split(\"|\");\n\t\tconst sanitizedCallId = callId.replace(/[^a-zA-Z0-9_-]/g, \"_\");\n\t\tlet sanitizedItemId = itemId.replace(/[^a-zA-Z0-9_-]/g, \"_\");\n\t\t// OpenAI Responses API requires item id to start with \"fc\"\n\t\tif (!sanitizedItemId.startsWith(\"fc\")) {\n\t\t\tsanitizedItemId = `fc_${sanitizedItemId}`;\n\t\t}\n\t\tconst normalizedCallId = sanitizedCallId.length > 64 ? sanitizedCallId.slice(0, 64) : sanitizedCallId;\n\t\tconst normalizedItemId = sanitizedItemId.length > 64 ? sanitizedItemId.slice(0, 64) : sanitizedItemId;\n\t\treturn `${normalizedCallId}|${normalizedItemId}`;\n\t};\n\n\tconst transformedMessages = transformMessages(context.messages, model, normalizeToolCallId);\n\n\tconst includeSystemPrompt = options?.includeSystemPrompt ?? true;\n\tif (includeSystemPrompt && 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}\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"input_image\",\n\t\t\t\t\t\tdetail: \"auto\",\n\t\t\t\t\t\timage_url: `data:${item.mimeType};base64,${item.data}`,\n\t\t\t\t\t} satisfies ResponseInputImage;\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\t\t\tconst assistantMsg = msg as AssistantMessage;\n\t\t\tconst isDifferentModel =\n\t\t\t\tassistantMsg.model !== model.id &&\n\t\t\t\tassistantMsg.provider === model.provider &&\n\t\t\t\tassistantMsg.api === model.api;\n\n\t\t\tfor (const block of msg.content) {\n\t\t\t\tif (block.type === \"thinking\") {\n\t\t\t\t\tif (block.thinkingSignature) {\n\t\t\t\t\t\tconst reasoningItem = JSON.parse(block.thinkingSignature) as ResponseReasoningItem;\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} else if (block.type === \"toolCall\") {\n\t\t\t\t\tconst toolCall = block as ToolCall;\n\t\t\t\t\tconst [callId, itemIdRaw] = toolCall.id.split(\"|\");\n\t\t\t\t\tlet itemId: string | undefined = itemIdRaw;\n\n\t\t\t\t\t// For different-model messages, set id to undefined to avoid pairing validation.\n\t\t\t\t\t// OpenAI tracks which fc_xxx IDs were paired with rs_xxx reasoning items.\n\t\t\t\t\t// By omitting the id, we avoid triggering that validation (like cross-provider does).\n\t\t\t\t\tif (isDifferentModel && itemId?.startsWith(\"fc_\")) {\n\t\t\t\t\t\titemId = undefined;\n\t\t\t\t\t}\n\n\t\t\t\t\toutput.push({\n\t\t\t\t\t\ttype: \"function_call\",\n\t\t\t\t\t\tid: itemId,\n\t\t\t\t\t\tcall_id: callId,\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 is TextContent => c.type === \"text\")\n\t\t\t\t.map((c) => c.text)\n\t\t\t\t.join(\"\\n\");\n\t\t\tconst hasImages = msg.content.some((c): c is ImageContent => 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\tconst [callId] = msg.toolCallId.split(\"|\");\n\t\t\tmessages.push({\n\t\t\t\ttype: \"function_call_output\",\n\t\t\t\tcall_id: callId,\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.mimeType};base64,${block.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\n// =============================================================================\n// Tool conversion\n// =============================================================================\n\nexport function convertResponsesTools(tools: Tool[], options?: ConvertResponsesToolsOptions): OpenAITool[] {\n\tconst strict = options?.strict === undefined ? false : options.strict;\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,\n\t}));\n}\n\n// =============================================================================\n// Stream processing\n// =============================================================================\n\nexport async function processResponsesStream<TApi extends Api>(\n\topenaiStream: AsyncIterable<ResponseStreamEvent>,\n\toutput: AssistantMessage,\n\tstream: AssistantMessageEventStream,\n\tmodel: Model<TApi>,\n\toptions?: OpenAIResponsesStreamOptions,\n): Promise<void> {\n\tlet currentItem: ResponseReasoningItem | ResponseOutputMessage | ResponseFunctionToolCall | null = null;\n\tlet currentBlock: ThinkingContent | TextContent | (ToolCall & { partialJson: string }) | null = null;\n\tconst blocks = output.content;\n\tconst blockIndex = () => blocks.length - 1;\n\n\tfor await (const event of openaiStream) {\n\t\tif (event.type === \"response.output_item.added\") {\n\t\t\tconst item = event.item;\n\t\t\tif (item.type === \"reasoning\") {\n\t\t\t\tcurrentItem = item;\n\t\t\t\tcurrentBlock = { type: \"thinking\", thinking: \"\" };\n\t\t\t\toutput.content.push(currentBlock);\n\t\t\t\tstream.push({ type: \"thinking_start\", contentIndex: blockIndex(), partial: output });\n\t\t\t} else if (item.type === \"message\") {\n\t\t\t\tcurrentItem = item;\n\t\t\t\tcurrentBlock = { type: \"text\", text: \"\" };\n\t\t\t\toutput.content.push(currentBlock);\n\t\t\t\tstream.push({ type: \"text_start\", contentIndex: blockIndex(), partial: output });\n\t\t\t} else if (item.type === \"function_call\") {\n\t\t\t\tcurrentItem = item;\n\t\t\t\tcurrentBlock = {\n\t\t\t\t\ttype: \"toolCall\",\n\t\t\t\t\tid: `${item.call_id}|${item.id}`,\n\t\t\t\t\tname: item.name,\n\t\t\t\t\targuments: {},\n\t\t\t\t\tpartialJson: item.arguments || \"\",\n\t\t\t\t};\n\t\t\t\toutput.content.push(currentBlock);\n\t\t\t\tstream.push({ type: \"toolcall_start\", contentIndex: blockIndex(), partial: output });\n\t\t\t}\n\t\t} else if (event.type === \"response.reasoning_summary_part.added\") {\n\t\t\tif (currentItem && currentItem.type === \"reasoning\") {\n\t\t\t\tcurrentItem.summary = currentItem.summary || [];\n\t\t\t\tcurrentItem.summary.push(event.part);\n\t\t\t}\n\t\t} else if (event.type === \"response.reasoning_summary_text.delta\") {\n\t\t\tif (currentItem?.type === \"reasoning\" && currentBlock?.type === \"thinking\") {\n\t\t\t\tcurrentItem.summary = currentItem.summary || [];\n\t\t\t\tconst lastPart = currentItem.summary[currentItem.summary.length - 1];\n\t\t\t\tif (lastPart) {\n\t\t\t\t\tcurrentBlock.thinking += event.delta;\n\t\t\t\t\tlastPart.text += event.delta;\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\tdelta: event.delta,\n\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (event.type === \"response.reasoning_summary_part.done\") {\n\t\t\tif (currentItem?.type === \"reasoning\" && currentBlock?.type === \"thinking\") {\n\t\t\t\tcurrentItem.summary = currentItem.summary || [];\n\t\t\t\tconst lastPart = currentItem.summary[currentItem.summary.length - 1];\n\t\t\t\tif (lastPart) {\n\t\t\t\t\tcurrentBlock.thinking += \"\\n\\n\";\n\t\t\t\t\tlastPart.text += \"\\n\\n\";\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\tdelta: \"\\n\\n\",\n\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (event.type === \"response.content_part.added\") {\n\t\t\tif (currentItem?.type === \"message\") {\n\t\t\t\tcurrentItem.content = currentItem.content || [];\n\t\t\t\t// Filter out ReasoningText, only accept output_text and refusal\n\t\t\t\tif (event.part.type === \"output_text\" || event.part.type === \"refusal\") {\n\t\t\t\t\tcurrentItem.content.push(event.part);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (event.type === \"response.output_text.delta\") {\n\t\t\tif (currentItem?.type === \"message\" && currentBlock?.type === \"text\") {\n\t\t\t\tif (!currentItem.content || currentItem.content.length === 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst lastPart = currentItem.content[currentItem.content.length - 1];\n\t\t\t\tif (lastPart?.type === \"output_text\") {\n\t\t\t\t\tcurrentBlock.text += event.delta;\n\t\t\t\t\tlastPart.text += event.delta;\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"text_delta\",\n\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\tdelta: event.delta,\n\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (event.type === \"response.refusal.delta\") {\n\t\t\tif (currentItem?.type === \"message\" && currentBlock?.type === \"text\") {\n\t\t\t\tif (!currentItem.content || currentItem.content.length === 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst lastPart = currentItem.content[currentItem.content.length - 1];\n\t\t\t\tif (lastPart?.type === \"refusal\") {\n\t\t\t\t\tcurrentBlock.text += event.delta;\n\t\t\t\t\tlastPart.refusal += event.delta;\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"text_delta\",\n\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\tdelta: event.delta,\n\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (event.type === \"response.function_call_arguments.delta\") {\n\t\t\tif (currentItem?.type === \"function_call\" && currentBlock?.type === \"toolCall\") {\n\t\t\t\tcurrentBlock.partialJson += event.delta;\n\t\t\t\tcurrentBlock.arguments = parseStreamingJson(currentBlock.partialJson);\n\t\t\t\tstream.push({\n\t\t\t\t\ttype: \"toolcall_delta\",\n\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\tdelta: event.delta,\n\t\t\t\t\tpartial: output,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (event.type === \"response.function_call_arguments.done\") {\n\t\t\tif (currentItem?.type === \"function_call\" && currentBlock?.type === \"toolCall\") {\n\t\t\t\tcurrentBlock.partialJson = event.arguments;\n\t\t\t\tcurrentBlock.arguments = parseStreamingJson(currentBlock.partialJson);\n\t\t\t}\n\t\t} else if (event.type === \"response.output_item.done\") {\n\t\t\tconst item = event.item;\n\n\t\t\tif (item.type === \"reasoning\" && currentBlock?.type === \"thinking\") {\n\t\t\t\tcurrentBlock.thinking = item.summary?.map((s) => s.text).join(\"\\n\\n\") || \"\";\n\t\t\t\tcurrentBlock.thinkingSignature = JSON.stringify(item);\n\t\t\t\tstream.push({\n\t\t\t\t\ttype: \"thinking_end\",\n\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\tcontent: currentBlock.thinking,\n\t\t\t\t\tpartial: output,\n\t\t\t\t});\n\t\t\t\tcurrentBlock = null;\n\t\t\t} else if (item.type === \"message\" && currentBlock?.type === \"text\") {\n\t\t\t\tcurrentBlock.text = item.content.map((c) => (c.type === \"output_text\" ? c.text : c.refusal)).join(\"\");\n\t\t\t\tcurrentBlock.textSignature = item.id;\n\t\t\t\tstream.push({\n\t\t\t\t\ttype: \"text_end\",\n\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\tcontent: currentBlock.text,\n\t\t\t\t\tpartial: output,\n\t\t\t\t});\n\t\t\t\tcurrentBlock = null;\n\t\t\t} else if (item.type === \"function_call\") {\n\t\t\t\tconst args =\n\t\t\t\t\tcurrentBlock?.type === \"toolCall\" && currentBlock.partialJson\n\t\t\t\t\t\t? JSON.parse(currentBlock.partialJson)\n\t\t\t\t\t\t: JSON.parse(item.arguments);\n\t\t\t\tconst toolCall: ToolCall = {\n\t\t\t\t\ttype: \"toolCall\",\n\t\t\t\t\tid: `${item.call_id}|${item.id}`,\n\t\t\t\t\tname: item.name,\n\t\t\t\t\targuments: args,\n\t\t\t\t};\n\n\t\t\t\tcurrentBlock = null;\n\t\t\t\tstream.push({ type: \"toolcall_end\", contentIndex: blockIndex(), toolCall, partial: output });\n\t\t\t}\n\t\t} else if (event.type === \"response.completed\") {\n\t\t\tconst response = event.response;\n\t\t\tif (response?.usage) {\n\t\t\t\tconst cachedTokens = response.usage.input_tokens_details?.cached_tokens || 0;\n\t\t\t\toutput.usage = {\n\t\t\t\t\t// OpenAI includes cached tokens in input_tokens, so subtract to get non-cached input\n\t\t\t\t\tinput: (response.usage.input_tokens || 0) - cachedTokens,\n\t\t\t\t\toutput: response.usage.output_tokens || 0,\n\t\t\t\t\tcacheRead: cachedTokens,\n\t\t\t\t\tcacheWrite: 0,\n\t\t\t\t\ttotalTokens: response.usage.total_tokens || 0,\n\t\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t\t};\n\t\t\t}\n\t\t\tcalculateCost(model, output.usage);\n\t\t\tif (options?.applyServiceTierPricing) {\n\t\t\t\tconst serviceTier = response?.service_tier ?? options.serviceTier;\n\t\t\t\toptions.applyServiceTierPricing(output.usage, serviceTier);\n\t\t\t}\n\t\t\t// Map status to stop reason\n\t\t\toutput.stopReason = mapStopReason(response?.status);\n\t\t\tif (output.content.some((b) => b.type === \"toolCall\") && output.stopReason === \"stop\") {\n\t\t\t\toutput.stopReason = \"toolUse\";\n\t\t\t}\n\t\t} else if (event.type === \"error\") {\n\t\t\tthrow new Error(`Error Code ${event.code}: ${event.message}` || \"Unknown error\");\n\t\t} else if (event.type === \"response.failed\") {\n\t\t\tthrow new Error(\"Unknown error\");\n\t\t}\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,5 +1,5 @@
1
1
  import type { ResponseCreateParamsStreaming } from "openai/resources/responses/responses.js";
2
- import type { StreamFunction, StreamOptions } from "../types.js";
2
+ import type { SimpleStreamOptions, StreamFunction, StreamOptions } from "../types.js";
3
3
  export interface OpenAIResponsesOptions extends StreamOptions {
4
4
  reasoningEffort?: "minimal" | "low" | "medium" | "high" | "xhigh";
5
5
  reasoningSummary?: "auto" | "detailed" | "concise" | null;
@@ -8,5 +8,6 @@ export interface OpenAIResponsesOptions extends StreamOptions {
8
8
  /**
9
9
  * Generate function for OpenAI Responses API
10
10
  */
11
- export declare const streamOpenAIResponses: StreamFunction<"openai-responses">;
11
+ export declare const streamOpenAIResponses: StreamFunction<"openai-responses", OpenAIResponsesOptions>;
12
+ export declare const streamSimpleOpenAIResponses: StreamFunction<"openai-responses", SimpleStreamOptions>;
12
13
  //# sourceMappingURL=openai-responses.d.ts.map