@keystrokehq/cli 0.0.53 → 0.0.54

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 (77) hide show
  1. package/dist/{anthropic-BW7tKfye.mjs → anthropic-OIjNEgxk.mjs} +3 -3
  2. package/dist/{anthropic-BW7tKfye.mjs.map → anthropic-OIjNEgxk.mjs.map} +1 -1
  3. package/dist/{azure-openai-responses-CbpqfHpG.mjs → azure-openai-responses-J2iGyy4d.mjs} +3 -3
  4. package/dist/{azure-openai-responses-CbpqfHpG.mjs.map → azure-openai-responses-J2iGyy4d.mjs.map} +1 -1
  5. package/dist/{cat-TSFMZVYS-BfwZOafs.mjs → cat-TSFMZVYS-BUlDi5Qf.mjs} +2 -2
  6. package/dist/{cat-TSFMZVYS-BfwZOafs.mjs.map → cat-TSFMZVYS-BUlDi5Qf.mjs.map} +1 -1
  7. package/dist/{cut-OKARJCCV-Cm3OStWG.mjs → cut-OKARJCCV-p9v-ig7a.mjs} +2 -2
  8. package/dist/{cut-OKARJCCV-Cm3OStWG.mjs.map → cut-OKARJCCV-p9v-ig7a.mjs.map} +1 -1
  9. package/dist/{dist-BSgBg_mF.mjs → dist-OeT0Z7by.mjs} +3 -3
  10. package/dist/{dist-BSgBg_mF.mjs.map → dist-OeT0Z7by.mjs.map} +1 -1
  11. package/dist/{du-572XNP42-DeJ11TW7.mjs → du-572XNP42-Br0wC4cR.mjs} +2 -2
  12. package/dist/{du-572XNP42-DeJ11TW7.mjs.map → du-572XNP42-Br0wC4cR.mjs.map} +1 -1
  13. package/dist/{emit-route-manifest-DRcNXHCP-CSOVo0UZ.mjs → emit-route-manifest-DRcNXHCP-CuH5IaKl.mjs} +210 -209
  14. package/dist/emit-route-manifest-DRcNXHCP-CuH5IaKl.mjs.map +1 -0
  15. package/dist/{env-api-keys-CjsGqLnm.mjs → env-api-keys-Dj0phNAZ.mjs} +2 -2
  16. package/dist/{env-api-keys-CjsGqLnm.mjs.map → env-api-keys-Dj0phNAZ.mjs.map} +1 -1
  17. package/dist/{from-BVavsm7Y.mjs → from-CM85M090.mjs} +2 -2
  18. package/dist/{from-BVavsm7Y.mjs.map → from-CM85M090.mjs.map} +1 -1
  19. package/dist/{google-B3pBIkED.mjs → google-CZqUzYLL.mjs} +3 -3
  20. package/dist/{google-B3pBIkED.mjs.map → google-CZqUzYLL.mjs.map} +1 -1
  21. package/dist/{google-shared-CZrnlDVf.mjs → google-shared-DpSg5iXi.mjs} +5 -5
  22. package/dist/{google-shared-CZrnlDVf.mjs.map → google-shared-DpSg5iXi.mjs.map} +1 -1
  23. package/dist/{google-vertex-CK79qwUV.mjs → google-vertex-BM9RkknB.mjs} +2 -2
  24. package/dist/{google-vertex-CK79qwUV.mjs.map → google-vertex-BM9RkknB.mjs.map} +1 -1
  25. package/dist/{html-to-markdown-JW4MSQZO-CvfnlE0t.mjs → html-to-markdown-JW4MSQZO-CL7jZmA2.mjs} +2 -2
  26. package/dist/{html-to-markdown-JW4MSQZO-CvfnlE0t.mjs.map → html-to-markdown-JW4MSQZO-CL7jZmA2.mjs.map} +1 -1
  27. package/dist/index.mjs +712 -6
  28. package/dist/index.mjs.map +1 -1
  29. package/dist/{jq-4XLYLOS5-DrYXLsYH.mjs → jq-4XLYLOS5-KSRW1t5y.mjs} +2 -2
  30. package/dist/{jq-4XLYLOS5-DrYXLsYH.mjs.map → jq-4XLYLOS5-KSRW1t5y.mjs.map} +1 -1
  31. package/dist/{json-parse-4wvL0yab.mjs → json-parse-D7gmIw6y.mjs} +2 -2
  32. package/dist/{json-parse-4wvL0yab.mjs.map → json-parse-D7gmIw6y.mjs.map} +1 -1
  33. package/dist/{lib-L8rwARiF.mjs → lib-15JvMO_y.mjs} +2 -2
  34. package/dist/{lib-L8rwARiF.mjs.map → lib-15JvMO_y.mjs.map} +1 -1
  35. package/dist/{ls-ZJGQER7M-C_1bAeGq.mjs → ls-ZJGQER7M-CvMghjGY.mjs} +2 -2
  36. package/dist/{ls-ZJGQER7M-C_1bAeGq.mjs.map → ls-ZJGQER7M-CvMghjGY.mjs.map} +1 -1
  37. package/dist/{mistral-CO6JoIDU.mjs → mistral-BMK3QxKa.mjs} +3 -3
  38. package/dist/{mistral-CO6JoIDU.mjs.map → mistral-BMK3QxKa.mjs.map} +1 -1
  39. package/dist/{multipart-parser-CybO63Pn.mjs → multipart-parser-ChdFj-Tf.mjs} +3 -3
  40. package/dist/{multipart-parser-CybO63Pn.mjs.map → multipart-parser-ChdFj-Tf.mjs.map} +1 -1
  41. package/dist/{openai-codex-responses-BsV2OXkO.mjs → openai-codex-responses-FPOFDQCI.mjs} +3 -3
  42. package/dist/{openai-codex-responses-BsV2OXkO.mjs.map → openai-codex-responses-FPOFDQCI.mjs.map} +1 -1
  43. package/dist/{openai-completions-DtKMQJXz.mjs → openai-completions-DaFkurXZ.mjs} +3 -3
  44. package/dist/{openai-completions-DtKMQJXz.mjs.map → openai-completions-DaFkurXZ.mjs.map} +1 -1
  45. package/dist/{openai-responses-Dn8IOWpx.mjs → openai-responses-DjcjpFVd.mjs} +3 -3
  46. package/dist/{openai-responses-Dn8IOWpx.mjs.map → openai-responses-DjcjpFVd.mjs.map} +1 -1
  47. package/dist/{openai-responses-shared-rmpfdSMl.mjs → openai-responses-shared-DOajVKFM.mjs} +2 -2
  48. package/dist/{openai-responses-shared-rmpfdSMl.mjs.map → openai-responses-shared-DOajVKFM.mjs.map} +1 -1
  49. package/dist/{openrouter-Cq37VS4X.mjs → openrouter-BD82J9ov.mjs} +2 -2
  50. package/dist/{openrouter-Cq37VS4X.mjs.map → openrouter-BD82J9ov.mjs.map} +1 -1
  51. package/dist/{printf-TWGXF445-BcIEiMjE.mjs → printf-TWGXF445-CtbOGcY-.mjs} +2 -2
  52. package/dist/{printf-TWGXF445-BcIEiMjE.mjs.map → printf-TWGXF445-CtbOGcY-.mjs.map} +1 -1
  53. package/dist/{sort-SW2YEO5B-D08jaQ5v.mjs → sort-SW2YEO5B-BT2dtrqE.mjs} +2 -2
  54. package/dist/{sort-SW2YEO5B-D08jaQ5v.mjs.map → sort-SW2YEO5B-BT2dtrqE.mjs.map} +1 -1
  55. package/dist/{sqlite3-CGOEFJAO-DVuaAgm0.mjs → sqlite3-CGOEFJAO-DKaf3b_T.mjs} +2 -2
  56. package/dist/{sqlite3-CGOEFJAO-DVuaAgm0.mjs.map → sqlite3-CGOEFJAO-DKaf3b_T.mjs.map} +1 -1
  57. package/dist/{src-xQsWiElt.mjs → src-BhFu0wxf.mjs} +4 -4
  58. package/dist/{src-xQsWiElt.mjs.map → src-BhFu0wxf.mjs.map} +1 -1
  59. package/dist/{src-DuFA6S6A.mjs → src-CO4ATuDw.mjs} +2 -2
  60. package/dist/{src-DuFA6S6A.mjs.map → src-CO4ATuDw.mjs.map} +1 -1
  61. package/dist/{tar-STHHZTZ6-C7-gpnmi.mjs → tar-STHHZTZ6-Cy8WppFl.mjs} +3 -3
  62. package/dist/{tar-STHHZTZ6-C7-gpnmi.mjs.map → tar-STHHZTZ6-Cy8WppFl.mjs.map} +1 -1
  63. package/dist/{tree-YLD52CNT-DiHyiFBi.mjs → tree-YLD52CNT-CFtEJCzO.mjs} +2 -2
  64. package/dist/{tree-YLD52CNT-DiHyiFBi.mjs.map → tree-YLD52CNT-CFtEJCzO.mjs.map} +1 -1
  65. package/dist/{uniq-XSIZR6PB-BA-vRB1O.mjs → uniq-XSIZR6PB-ERG9Mu92.mjs} +2 -2
  66. package/dist/{uniq-XSIZR6PB-BA-vRB1O.mjs.map → uniq-XSIZR6PB-ERG9Mu92.mjs.map} +1 -1
  67. package/dist/{watch-app-DTIeKrbl-BdEadl4m.mjs → watch-app-DTIeKrbl-C-BThJEO.mjs} +2 -2
  68. package/dist/{watch-app-DTIeKrbl-BdEadl4m.mjs.map → watch-app-DTIeKrbl-C-BThJEO.mjs.map} +1 -1
  69. package/dist/{wc-LF7NU4LA-BWoItyXd.mjs → wc-LF7NU4LA-CsPoPEAk.mjs} +2 -2
  70. package/dist/{wc-LF7NU4LA-BWoItyXd.mjs.map → wc-LF7NU4LA-CsPoPEAk.mjs.map} +1 -1
  71. package/dist/{websocket-server-DBCa1Df9.mjs → websocket-server-m6wiYSFm.mjs} +2 -2
  72. package/dist/{websocket-server-DBCa1Df9.mjs.map → websocket-server-m6wiYSFm.mjs.map} +1 -1
  73. package/dist/{xan-Y6WF3IRG-BilR2MsH.mjs → xan-Y6WF3IRG-ovCpFLkA.mjs} +2 -2
  74. package/dist/{xan-Y6WF3IRG-BilR2MsH.mjs.map → xan-Y6WF3IRG-ovCpFLkA.mjs.map} +1 -1
  75. package/package.json +4 -4
  76. package/dist/chunk-lXUa1qmO.mjs +0 -37
  77. package/dist/emit-route-manifest-DRcNXHCP-CSOVo0UZ.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"openai-completions-DtKMQJXz.mjs","names":[],"sources":["../../../node_modules/.pnpm/@earendil-works+pi-ai@0.75.4_@modelcontextprotocol+sdk@1.29.0_zod@4.4.3__ws@8.20.1_zod@4.4.3/node_modules/@earendil-works/pi-ai/dist/providers/openai-completions.js"],"sourcesContent":["import OpenAI from \"openai\";\nimport { getEnvApiKey } from \"../env-api-keys.js\";\nimport { calculateCost, clampThinkingLevel } from \"../models.js\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.js\";\nimport { headersToRecord } from \"../utils/headers.js\";\nimport { parseStreamingJson } from \"../utils/json-parse.js\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.js\";\nimport { isCloudflareProvider, resolveCloudflareBaseUrl } from \"./cloudflare.js\";\nimport { buildCopilotDynamicHeaders, hasCopilotVisionInput } from \"./github-copilot-headers.js\";\nimport { clampOpenAIPromptCacheKey } from \"./openai-prompt-cache.js\";\nimport { buildBaseOptions } from \"./simple-options.js\";\nimport { transformMessages } from \"./transform-messages.js\";\n/**\n * Check if conversation messages contain tool calls or tool results.\n * This is needed because Anthropic (via proxy) requires the tools param\n * to be present when messages include tool_calls or tool role messages.\n */\nfunction hasToolHistory(messages) {\n for (const msg of messages) {\n if (msg.role === \"toolResult\") {\n return true;\n }\n if (msg.role === \"assistant\") {\n if (msg.content.some((block) => block.type === \"toolCall\")) {\n return true;\n }\n }\n }\n return false;\n}\nfunction isTextContentBlock(block) {\n return block.type === \"text\";\n}\nfunction isThinkingContentBlock(block) {\n return block.type === \"thinking\";\n}\nfunction isToolCallBlock(block) {\n return block.type === \"toolCall\";\n}\nfunction isImageContentBlock(block) {\n return block.type === \"image\";\n}\nfunction resolveCacheRetention(cacheRetention) {\n if (cacheRetention) {\n return cacheRetention;\n }\n if (typeof process !== \"undefined\" && process.env.PI_CACHE_RETENTION === \"long\") {\n return \"long\";\n }\n return \"short\";\n}\nexport const streamOpenAICompletions = (model, context, options) => {\n const stream = new AssistantMessageEventStream();\n (async () => {\n const output = {\n role: \"assistant\",\n content: [],\n api: model.api,\n provider: model.provider,\n model: model.id,\n usage: {\n input: 0,\n output: 0,\n cacheRead: 0,\n cacheWrite: 0,\n totalTokens: 0,\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n },\n stopReason: \"stop\",\n timestamp: Date.now(),\n };\n try {\n const apiKey = options?.apiKey || getEnvApiKey(model.provider) || \"\";\n const compat = getCompat(model);\n const cacheRetention = resolveCacheRetention(options?.cacheRetention);\n const cacheSessionId = cacheRetention === \"none\" ? undefined : options?.sessionId;\n const client = createClient(model, context, apiKey, options?.headers, cacheSessionId, compat);\n let params = buildParams(model, context, options, compat, cacheRetention);\n const nextParams = await options?.onPayload?.(params, model);\n if (nextParams !== undefined) {\n params = nextParams;\n }\n const requestOptions = {\n ...(options?.signal ? { signal: options.signal } : {}),\n ...(options?.timeoutMs !== undefined ? { timeout: options.timeoutMs } : {}),\n ...(options?.maxRetries !== undefined ? { maxRetries: options.maxRetries } : {}),\n };\n const { data: openaiStream, response } = await client.chat.completions\n .create(params, requestOptions)\n .withResponse();\n await options?.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model);\n stream.push({ type: \"start\", partial: output });\n let textBlock = null;\n let thinkingBlock = null;\n let hasFinishReason = false;\n const toolCallBlocksByIndex = new Map();\n const toolCallBlocksById = new Map();\n const blocks = output.content;\n const getContentIndex = (block) => blocks.indexOf(block);\n const finishBlock = (block) => {\n const contentIndex = getContentIndex(block);\n if (contentIndex === -1) {\n return;\n }\n if (block.type === \"text\") {\n stream.push({\n type: \"text_end\",\n contentIndex,\n content: block.text,\n partial: output,\n });\n }\n else if (block.type === \"thinking\") {\n stream.push({\n type: \"thinking_end\",\n contentIndex,\n content: block.thinking,\n partial: output,\n });\n }\n else if (block.type === \"toolCall\") {\n block.arguments = parseStreamingJson(block.partialArgs);\n // Finalize in-place and strip the scratch buffers so replay only\n // carries parsed arguments.\n delete block.partialArgs;\n delete block.streamIndex;\n stream.push({\n type: \"toolcall_end\",\n contentIndex,\n toolCall: block,\n partial: output,\n });\n }\n };\n const ensureTextBlock = () => {\n if (!textBlock) {\n textBlock = { type: \"text\", text: \"\" };\n blocks.push(textBlock);\n stream.push({ type: \"text_start\", contentIndex: getContentIndex(textBlock), partial: output });\n }\n return textBlock;\n };\n const ensureThinkingBlock = (thinkingSignature) => {\n if (!thinkingBlock) {\n thinkingBlock = {\n type: \"thinking\",\n thinking: \"\",\n thinkingSignature,\n };\n blocks.push(thinkingBlock);\n stream.push({ type: \"thinking_start\", contentIndex: getContentIndex(thinkingBlock), partial: output });\n }\n return thinkingBlock;\n };\n const ensureToolCallBlock = (toolCall) => {\n const streamIndex = typeof toolCall.index === \"number\" ? toolCall.index : undefined;\n let block = streamIndex !== undefined ? toolCallBlocksByIndex.get(streamIndex) : undefined;\n if (!block && toolCall.id) {\n block = toolCallBlocksById.get(toolCall.id);\n }\n if (!block) {\n block = {\n type: \"toolCall\",\n id: toolCall.id || \"\",\n name: toolCall.function?.name || \"\",\n arguments: {},\n partialArgs: \"\",\n streamIndex,\n };\n if (streamIndex !== undefined) {\n toolCallBlocksByIndex.set(streamIndex, block);\n }\n if (toolCall.id) {\n toolCallBlocksById.set(toolCall.id, block);\n }\n blocks.push(block);\n stream.push({\n type: \"toolcall_start\",\n contentIndex: getContentIndex(block),\n partial: output,\n });\n }\n if (streamIndex !== undefined && block.streamIndex === undefined) {\n block.streamIndex = streamIndex;\n toolCallBlocksByIndex.set(streamIndex, block);\n }\n if (toolCall.id) {\n toolCallBlocksById.set(toolCall.id, block);\n }\n return block;\n };\n for await (const chunk of openaiStream) {\n if (!chunk || typeof chunk !== \"object\")\n continue;\n // OpenAI documents ChatCompletionChunk.id as the unique chat completion identifier,\n // and each chunk in a streamed completion carries the same id.\n output.responseId ||= chunk.id;\n if (typeof chunk.model === \"string\" && chunk.model.length > 0 && chunk.model !== model.id) {\n output.responseModel ||= chunk.model;\n }\n if (chunk.usage) {\n output.usage = parseChunkUsage(chunk.usage, model);\n }\n const choice = Array.isArray(chunk.choices) ? chunk.choices[0] : undefined;\n if (!choice)\n continue;\n // Fallback: some providers (e.g., Moonshot) return usage\n // in choice.usage instead of the standard chunk.usage\n if (!chunk.usage && choice.usage) {\n output.usage = parseChunkUsage(choice.usage, model);\n }\n if (choice.finish_reason) {\n const finishReasonResult = mapStopReason(choice.finish_reason);\n output.stopReason = finishReasonResult.stopReason;\n if (finishReasonResult.errorMessage) {\n output.errorMessage = finishReasonResult.errorMessage;\n }\n hasFinishReason = true;\n }\n if (choice.delta) {\n if (choice.delta.content !== null &&\n choice.delta.content !== undefined &&\n choice.delta.content.length > 0) {\n const block = ensureTextBlock();\n block.text += choice.delta.content;\n stream.push({\n type: \"text_delta\",\n contentIndex: getContentIndex(block),\n delta: choice.delta.content,\n partial: output,\n });\n }\n // Some endpoints return reasoning in reasoning_content (llama.cpp),\n // or reasoning (other openai compatible endpoints)\n // Use the first non-empty reasoning field to avoid duplication\n // (e.g., chutes.ai returns both reasoning_content and reasoning with same content)\n const reasoningFields = [\"reasoning_content\", \"reasoning\", \"reasoning_text\"];\n const deltaFields = choice.delta;\n let foundReasoningField = null;\n for (const field of reasoningFields) {\n const value = deltaFields[field];\n if (typeof value === \"string\" && value.length > 0) {\n foundReasoningField = field;\n break;\n }\n }\n if (foundReasoningField) {\n const delta = deltaFields[foundReasoningField];\n if (typeof delta === \"string\" && delta.length > 0) {\n const thinkingSignature = model.provider === \"opencode-go\" && foundReasoningField === \"reasoning\"\n ? \"reasoning_content\"\n : foundReasoningField;\n const block = ensureThinkingBlock(thinkingSignature);\n block.thinking += delta;\n stream.push({\n type: \"thinking_delta\",\n contentIndex: getContentIndex(block),\n delta,\n partial: output,\n });\n }\n }\n if (choice?.delta?.tool_calls) {\n for (const toolCall of choice.delta.tool_calls) {\n const block = ensureToolCallBlock(toolCall);\n if (!block.id && toolCall.id) {\n block.id = toolCall.id;\n toolCallBlocksById.set(toolCall.id, block);\n }\n if (!block.name && toolCall.function?.name) {\n block.name = toolCall.function.name;\n }\n let delta = \"\";\n if (toolCall.function?.arguments) {\n delta = toolCall.function.arguments;\n block.partialArgs = (block.partialArgs ?? \"\") + toolCall.function.arguments;\n block.arguments = parseStreamingJson(block.partialArgs);\n }\n stream.push({\n type: \"toolcall_delta\",\n contentIndex: getContentIndex(block),\n delta,\n partial: output,\n });\n }\n }\n const reasoningDetails = choice.delta.reasoning_details;\n if (reasoningDetails && Array.isArray(reasoningDetails)) {\n for (const detail of reasoningDetails) {\n if (detail.type === \"reasoning.encrypted\" && detail.id && detail.data) {\n const matchingToolCall = output.content.find((b) => b.type === \"toolCall\" && b.id === detail.id);\n if (matchingToolCall) {\n matchingToolCall.thoughtSignature = JSON.stringify(detail);\n }\n }\n }\n }\n }\n }\n for (const block of blocks) {\n finishBlock(block);\n }\n if (options?.signal?.aborted) {\n throw new Error(\"Request was aborted\");\n }\n if (output.stopReason === \"aborted\") {\n throw new Error(\"Request was aborted\");\n }\n if (output.stopReason === \"error\") {\n throw new Error(output.errorMessage || \"Provider returned an error stop reason\");\n }\n if (!hasFinishReason) {\n throw new Error(\"Stream ended without finish_reason\");\n }\n stream.push({ type: \"done\", reason: output.stopReason, message: output });\n stream.end();\n }\n catch (error) {\n for (const block of output.content) {\n delete block.index;\n // Streaming scratch buffers are only used during parsing; never persist them.\n delete block.partialArgs;\n delete block.streamIndex;\n }\n output.stopReason = options?.signal?.aborted ? \"aborted\" : \"error\";\n output.errorMessage = error instanceof Error ? error.message : JSON.stringify(error);\n // Some providers via OpenRouter give additional information in this field.\n const rawMetadata = error?.error?.metadata?.raw;\n if (rawMetadata)\n output.errorMessage += `\\n${rawMetadata}`;\n stream.push({ type: \"error\", reason: output.stopReason, error: output });\n stream.end();\n }\n })();\n return stream;\n};\nexport const streamSimpleOpenAICompletions = (model, context, options) => {\n const apiKey = options?.apiKey || getEnvApiKey(model.provider);\n if (!apiKey) {\n throw new Error(`No API key for provider: ${model.provider}`);\n }\n const base = buildBaseOptions(model, options, apiKey);\n const clampedReasoning = options?.reasoning ? clampThinkingLevel(model, options.reasoning) : undefined;\n const reasoningEffort = clampedReasoning === \"off\" ? undefined : clampedReasoning;\n const toolChoice = options?.toolChoice;\n return streamOpenAICompletions(model, context, {\n ...base,\n reasoningEffort,\n toolChoice,\n });\n};\nfunction createClient(model, context, apiKey, optionsHeaders, sessionId, compat = getCompat(model)) {\n if (!apiKey) {\n if (!process.env.OPENAI_API_KEY) {\n throw new Error(\"OpenAI API key is required. Set OPENAI_API_KEY environment variable or pass it as an argument.\");\n }\n apiKey = process.env.OPENAI_API_KEY;\n }\n const headers = { ...model.headers };\n if (model.provider === \"github-copilot\") {\n const hasImages = hasCopilotVisionInput(context.messages);\n const copilotHeaders = buildCopilotDynamicHeaders({\n messages: context.messages,\n hasImages,\n });\n Object.assign(headers, copilotHeaders);\n }\n if (sessionId && compat.sendSessionAffinityHeaders) {\n headers.session_id = sessionId;\n headers[\"x-client-request-id\"] = sessionId;\n headers[\"x-session-affinity\"] = sessionId;\n }\n // Merge options headers last so they can override defaults\n if (optionsHeaders) {\n Object.assign(headers, optionsHeaders);\n }\n const defaultHeaders = model.provider === \"cloudflare-ai-gateway\"\n ? {\n ...headers,\n Authorization: headers.Authorization ?? null,\n \"cf-aig-authorization\": `Bearer ${apiKey}`,\n }\n : headers;\n return new OpenAI({\n apiKey,\n baseURL: isCloudflareProvider(model.provider) ? resolveCloudflareBaseUrl(model) : model.baseUrl,\n dangerouslyAllowBrowser: true,\n defaultHeaders,\n });\n}\nfunction buildParams(model, context, options, compat = getCompat(model), cacheRetention = resolveCacheRetention(options?.cacheRetention)) {\n const messages = convertMessages(model, context, compat);\n const cacheControl = getCompatCacheControl(compat, cacheRetention);\n const params = {\n model: model.id,\n messages,\n stream: true,\n prompt_cache_key: (model.baseUrl.includes(\"api.openai.com\") && cacheRetention !== \"none\") ||\n (cacheRetention === \"long\" && compat.supportsLongCacheRetention)\n ? clampOpenAIPromptCacheKey(options?.sessionId)\n : undefined,\n prompt_cache_retention: cacheRetention === \"long\" && compat.supportsLongCacheRetention ? \"24h\" : undefined,\n };\n if (compat.supportsUsageInStreaming !== false) {\n params.stream_options = { include_usage: true };\n }\n if (compat.supportsStore) {\n params.store = false;\n }\n if (options?.maxTokens) {\n if (compat.maxTokensField === \"max_tokens\") {\n params.max_tokens = options.maxTokens;\n }\n else {\n params.max_completion_tokens = options.maxTokens;\n }\n }\n if (options?.temperature !== undefined) {\n params.temperature = options.temperature;\n }\n if (context.tools && context.tools.length > 0) {\n params.tools = convertTools(context.tools, compat);\n if (compat.zaiToolStream) {\n params.tool_stream = true;\n }\n }\n else if (hasToolHistory(context.messages)) {\n // Anthropic (via LiteLLM/proxy) requires tools param when conversation has tool_calls/tool_results\n params.tools = [];\n }\n if (cacheControl) {\n applyAnthropicCacheControl(messages, params.tools, cacheControl);\n }\n if (options?.toolChoice) {\n params.tool_choice = options.toolChoice;\n }\n if (compat.thinkingFormat === \"zai\" && model.reasoning) {\n params.enable_thinking = !!options?.reasoningEffort;\n }\n else if (compat.thinkingFormat === \"qwen\" && model.reasoning) {\n params.enable_thinking = !!options?.reasoningEffort;\n }\n else if (compat.thinkingFormat === \"qwen-chat-template\" && model.reasoning) {\n params.chat_template_kwargs = {\n enable_thinking: !!options?.reasoningEffort,\n preserve_thinking: true,\n };\n }\n else if (compat.thinkingFormat === \"deepseek\" && model.reasoning) {\n params.thinking = { type: options?.reasoningEffort ? \"enabled\" : \"disabled\" };\n if (options?.reasoningEffort) {\n params.reasoning_effort =\n model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort;\n }\n }\n else if (compat.thinkingFormat === \"openrouter\" && model.reasoning) {\n // OpenRouter normalizes reasoning across providers via a nested reasoning object.\n const openRouterParams = params;\n if (options?.reasoningEffort) {\n openRouterParams.reasoning = {\n effort: model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort,\n };\n }\n else if (model.thinkingLevelMap?.off !== null) {\n openRouterParams.reasoning = { effort: model.thinkingLevelMap?.off ?? \"none\" };\n }\n }\n else if (compat.thinkingFormat === \"together\" && model.reasoning) {\n const togetherParams = params;\n togetherParams.reasoning = { enabled: !!options?.reasoningEffort };\n if (options?.reasoningEffort && compat.supportsReasoningEffort) {\n togetherParams.reasoning_effort = model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort;\n }\n }\n else if (options?.reasoningEffort && model.reasoning && compat.supportsReasoningEffort) {\n // OpenAI-style reasoning_effort\n params.reasoning_effort = model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort;\n }\n else if (!options?.reasoningEffort && model.reasoning && compat.supportsReasoningEffort) {\n const offValue = model.thinkingLevelMap?.off;\n if (typeof offValue === \"string\") {\n params.reasoning_effort = offValue;\n }\n }\n // OpenRouter provider routing preferences\n if (model.baseUrl.includes(\"openrouter.ai\") && model.compat?.openRouterRouting) {\n params.provider = model.compat.openRouterRouting;\n }\n // Vercel AI Gateway provider routing preferences\n if (model.baseUrl.includes(\"ai-gateway.vercel.sh\") && model.compat?.vercelGatewayRouting) {\n const routing = model.compat.vercelGatewayRouting;\n if (routing.only || routing.order) {\n const gatewayOptions = {};\n if (routing.only)\n gatewayOptions.only = routing.only;\n if (routing.order)\n gatewayOptions.order = routing.order;\n params.providerOptions = { gateway: gatewayOptions };\n }\n }\n return params;\n}\nfunction getCompatCacheControl(compat, cacheRetention) {\n if (compat.cacheControlFormat !== \"anthropic\" || cacheRetention === \"none\") {\n return undefined;\n }\n const ttl = cacheRetention === \"long\" && compat.supportsLongCacheRetention ? \"1h\" : undefined;\n return { type: \"ephemeral\", ...(ttl ? { ttl } : {}) };\n}\nfunction applyAnthropicCacheControl(messages, tools, cacheControl) {\n addCacheControlToSystemPrompt(messages, cacheControl);\n addCacheControlToLastTool(tools, cacheControl);\n addCacheControlToLastConversationMessage(messages, cacheControl);\n}\nfunction addCacheControlToSystemPrompt(messages, cacheControl) {\n for (const message of messages) {\n if (message.role === \"system\" || message.role === \"developer\") {\n addCacheControlToInstructionMessage(message, cacheControl);\n return;\n }\n }\n}\nfunction addCacheControlToLastConversationMessage(messages, cacheControl) {\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n if (message.role === \"user\" || message.role === \"assistant\") {\n if (addCacheControlToMessage(message, cacheControl)) {\n return;\n }\n }\n }\n}\nfunction addCacheControlToLastTool(tools, cacheControl) {\n if (!tools || tools.length === 0) {\n return;\n }\n const lastTool = tools[tools.length - 1];\n lastTool.cache_control = cacheControl;\n}\nfunction addCacheControlToInstructionMessage(message, cacheControl) {\n return addCacheControlToTextContent(message, cacheControl);\n}\nfunction addCacheControlToMessage(message, cacheControl) {\n if (message.role === \"user\" || message.role === \"assistant\") {\n return addCacheControlToTextContent(message, cacheControl);\n }\n return false;\n}\nfunction addCacheControlToTextContent(message, cacheControl) {\n const content = message.content;\n if (typeof content === \"string\") {\n if (content.length === 0) {\n return false;\n }\n message.content = [\n {\n type: \"text\",\n text: content,\n cache_control: cacheControl,\n },\n ];\n return true;\n }\n if (!Array.isArray(content)) {\n return false;\n }\n for (let i = content.length - 1; i >= 0; i--) {\n const part = content[i];\n if (part?.type === \"text\") {\n const textPart = part;\n textPart.cache_control = cacheControl;\n return true;\n }\n }\n return false;\n}\nexport function convertMessages(model, context, compat) {\n const params = [];\n const normalizeToolCallId = (id) => {\n // Handle pipe-separated IDs from OpenAI Responses API\n // Format: {call_id}|{id} where {id} can be 400+ chars with special chars (+, /, =)\n // These come from providers like github-copilot, openai-codex, opencode\n // Extract just the call_id part and normalize it\n if (id.includes(\"|\")) {\n const [callId] = id.split(\"|\");\n // Sanitize to allowed chars and truncate to 40 chars (OpenAI limit)\n return callId.replace(/[^a-zA-Z0-9_-]/g, \"_\").slice(0, 40);\n }\n if (model.provider === \"openai\")\n return id.length > 40 ? id.slice(0, 40) : id;\n return id;\n };\n const transformedMessages = transformMessages(context.messages, model, (id) => normalizeToolCallId(id));\n if (context.systemPrompt) {\n const useDeveloperRole = model.reasoning && compat.supportsDeveloperRole;\n const role = useDeveloperRole ? \"developer\" : \"system\";\n params.push({ role: role, content: sanitizeSurrogates(context.systemPrompt) });\n }\n let lastRole = null;\n for (let i = 0; i < transformedMessages.length; i++) {\n const msg = transformedMessages[i];\n // Some providers don't allow user messages directly after tool results\n // Insert a synthetic assistant message to bridge the gap\n if (compat.requiresAssistantAfterToolResult && lastRole === \"toolResult\" && msg.role === \"user\") {\n params.push({\n role: \"assistant\",\n content: \"I have processed the tool results.\",\n });\n }\n if (msg.role === \"user\") {\n if (typeof msg.content === \"string\") {\n params.push({\n role: \"user\",\n content: sanitizeSurrogates(msg.content),\n });\n }\n else {\n const content = msg.content.map((item) => {\n if (item.type === \"text\") {\n return {\n type: \"text\",\n text: sanitizeSurrogates(item.text),\n };\n }\n else {\n return {\n type: \"image_url\",\n image_url: {\n url: `data:${item.mimeType};base64,${item.data}`,\n },\n };\n }\n });\n if (content.length === 0)\n continue;\n params.push({\n role: \"user\",\n content,\n });\n }\n }\n else if (msg.role === \"assistant\") {\n // Some providers don't accept null content, use empty string instead\n const assistantMsg = {\n role: \"assistant\",\n content: compat.requiresAssistantAfterToolResult ? \"\" : null,\n };\n const assistantTextParts = msg.content\n .filter(isTextContentBlock)\n .filter((block) => block.text.trim().length > 0)\n .map((block) => ({\n type: \"text\",\n text: sanitizeSurrogates(block.text),\n }));\n const assistantText = assistantTextParts.map((part) => part.text).join(\"\");\n const nonEmptyThinkingBlocks = msg.content\n .filter(isThinkingContentBlock)\n .filter((block) => block.thinking.trim().length > 0);\n if (nonEmptyThinkingBlocks.length > 0) {\n if (compat.requiresThinkingAsText) {\n // Convert thinking blocks to plain text (no tags to avoid model mimicking them)\n const thinkingText = nonEmptyThinkingBlocks\n .map((block) => sanitizeSurrogates(block.thinking))\n .join(\"\\n\\n\");\n assistantMsg.content = [{ type: \"text\", text: thinkingText }, ...assistantTextParts];\n }\n else {\n // Always send assistant content as a plain string (OpenAI Chat Completions\n // API standard format). Sending as an array of {type:\"text\", text:\"...\"}\n // objects is non-standard and causes some models (e.g. DeepSeek V3.2 via\n // NVIDIA NIM) to mirror the content-block structure literally in their\n // output, producing recursive nesting like [{'type':'text','text':'[{...}]'}].\n if (assistantText.length > 0) {\n assistantMsg.content = assistantText;\n }\n // Use the signature from the first thinking block if available (for llama.cpp server + gpt-oss)\n let signature = nonEmptyThinkingBlocks[0].thinkingSignature;\n if (model.provider === \"opencode-go\" && signature === \"reasoning\") {\n signature = \"reasoning_content\";\n }\n if (signature && signature.length > 0) {\n assistantMsg[signature] = nonEmptyThinkingBlocks.map((block) => block.thinking).join(\"\\n\");\n }\n }\n }\n else if (assistantText.length > 0) {\n // Always send assistant content as a plain string (OpenAI Chat Completions\n // API standard format). Sending as an array of {type:\"text\", text:\"...\"}\n // objects is non-standard and causes some models (e.g. DeepSeek V3.2 via\n // NVIDIA NIM) to mirror the content-block structure literally in their\n // output, producing recursive nesting like [{'type':'text','text':'[{...}]'}].\n assistantMsg.content = assistantText;\n }\n const toolCalls = msg.content.filter(isToolCallBlock);\n if (toolCalls.length > 0) {\n assistantMsg.tool_calls = toolCalls.map((tc) => ({\n id: tc.id,\n type: \"function\",\n function: {\n name: tc.name,\n arguments: JSON.stringify(tc.arguments),\n },\n }));\n const reasoningDetails = toolCalls\n .filter((tc) => tc.thoughtSignature)\n .map((tc) => {\n try {\n return JSON.parse(tc.thoughtSignature);\n }\n catch {\n return null;\n }\n })\n .filter(Boolean);\n if (reasoningDetails.length > 0) {\n assistantMsg.reasoning_details = reasoningDetails;\n }\n }\n if (compat.requiresReasoningContentOnAssistantMessages &&\n model.reasoning &&\n assistantMsg.reasoning_content === undefined) {\n assistantMsg.reasoning_content = \"\";\n }\n // Skip assistant messages that have no content and no tool calls.\n // Some providers require \"either content or tool_calls, but not none\".\n // Other providers also don't accept empty assistant messages.\n // This handles aborted assistant responses that got no content.\n const content = assistantMsg.content;\n const hasContent = content !== null &&\n content !== undefined &&\n (typeof content === \"string\" ? content.length > 0 : content.length > 0);\n if (!hasContent && !assistantMsg.tool_calls) {\n continue;\n }\n params.push(assistantMsg);\n }\n else if (msg.role === \"toolResult\") {\n const imageBlocks = [];\n let j = i;\n for (; j < transformedMessages.length && transformedMessages[j].role === \"toolResult\"; j++) {\n const toolMsg = transformedMessages[j];\n // Extract text and image content\n const textResult = toolMsg.content\n .filter(isTextContentBlock)\n .map((block) => block.text)\n .join(\"\\n\");\n const hasImages = toolMsg.content.some((c) => c.type === \"image\");\n // Always send tool result with text (or placeholder if only images)\n const hasText = textResult.length > 0;\n // Some providers require the 'name' field in tool results\n const toolResultMsg = {\n role: \"tool\",\n content: sanitizeSurrogates(hasText ? textResult : \"(see attached image)\"),\n tool_call_id: toolMsg.toolCallId,\n };\n if (compat.requiresToolResultName && toolMsg.toolName) {\n toolResultMsg.name = toolMsg.toolName;\n }\n params.push(toolResultMsg);\n if (hasImages && model.input.includes(\"image\")) {\n for (const block of toolMsg.content) {\n if (isImageContentBlock(block)) {\n imageBlocks.push({\n type: \"image_url\",\n image_url: {\n url: `data:${block.mimeType};base64,${block.data}`,\n },\n });\n }\n }\n }\n }\n i = j - 1;\n if (imageBlocks.length > 0) {\n if (compat.requiresAssistantAfterToolResult) {\n params.push({\n role: \"assistant\",\n content: \"I have processed the tool results.\",\n });\n }\n params.push({\n role: \"user\",\n content: [\n {\n type: \"text\",\n text: \"Attached image(s) from tool result:\",\n },\n ...imageBlocks,\n ],\n });\n lastRole = \"user\";\n }\n else {\n lastRole = \"toolResult\";\n }\n continue;\n }\n lastRole = msg.role;\n }\n return params;\n}\nfunction convertTools(tools, compat) {\n return tools.map((tool) => ({\n type: \"function\",\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters, // TypeBox already generates JSON Schema\n // Only include strict if provider supports it. Some reject unknown fields.\n ...(compat.supportsStrictMode !== false && { strict: false }),\n },\n }));\n}\nfunction parseChunkUsage(rawUsage, model) {\n const promptTokens = rawUsage.prompt_tokens || 0;\n const cacheReadTokens = rawUsage.prompt_tokens_details?.cached_tokens ?? rawUsage.prompt_cache_hit_tokens ?? 0;\n const cacheWriteTokens = rawUsage.prompt_tokens_details?.cache_write_tokens || 0;\n // Follow documented OpenAI/OpenRouter semantics: cached_tokens is cache-read\n // tokens (hits). OpenAI does not document or emit cache_write_tokens, but\n // OpenRouter-compatible providers can include it as a separate write count.\n // OpenRouter's own provider/tests affirm the separate mapping:\n // https://github.com/OpenRouterTeam/ai-sdk-provider/pull/409\n // Do not subtract writes from cached_tokens, otherwise spec-compliant\n // providers are under-reported. DS4 mirrors this contract too:\n // https://github.com/antirez/ds4/pull/29\n const input = Math.max(0, promptTokens - cacheReadTokens - cacheWriteTokens);\n // OpenAI completion_tokens already includes reasoning_tokens.\n const outputTokens = rawUsage.completion_tokens || 0;\n const usage = {\n input,\n output: outputTokens,\n cacheRead: cacheReadTokens,\n cacheWrite: cacheWriteTokens,\n totalTokens: input + outputTokens + cacheReadTokens + cacheWriteTokens,\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n };\n calculateCost(model, usage);\n return usage;\n}\nfunction mapStopReason(reason) {\n if (reason === null)\n return { stopReason: \"stop\" };\n switch (reason) {\n case \"stop\":\n case \"end\":\n return { stopReason: \"stop\" };\n case \"length\":\n return { stopReason: \"length\" };\n case \"function_call\":\n case \"tool_calls\":\n return { stopReason: \"toolUse\" };\n case \"content_filter\":\n return { stopReason: \"error\", errorMessage: \"Provider finish_reason: content_filter\" };\n case \"network_error\":\n return { stopReason: \"error\", errorMessage: \"Provider finish_reason: network_error\" };\n default:\n return {\n stopReason: \"error\",\n errorMessage: `Provider finish_reason: ${reason}`,\n };\n }\n}\n/**\n * Detect compatibility settings from provider and baseUrl for known providers.\n * Provider takes precedence over URL-based detection since it's explicitly configured.\n * Returns a fully resolved OpenAICompletionsCompat object with all fields set.\n */\nfunction detectCompat(model) {\n const provider = model.provider;\n const baseUrl = model.baseUrl;\n const isZai = provider === \"zai\" || baseUrl.includes(\"api.z.ai\");\n const isTogether = provider === \"together\" || baseUrl.includes(\"api.together.ai\") || baseUrl.includes(\"api.together.xyz\");\n const isMoonshot = provider === \"moonshotai\" || provider === \"moonshotai-cn\" || baseUrl.includes(\"api.moonshot.\");\n const isCloudflareWorkersAI = provider === \"cloudflare-workers-ai\" || baseUrl.includes(\"api.cloudflare.com\");\n const isCloudflareAiGateway = provider === \"cloudflare-ai-gateway\" || baseUrl.includes(\"gateway.ai.cloudflare.com\");\n const isNonStandard = provider === \"cerebras\" ||\n baseUrl.includes(\"cerebras.ai\") ||\n provider === \"xai\" ||\n baseUrl.includes(\"api.x.ai\") ||\n isTogether ||\n baseUrl.includes(\"chutes.ai\") ||\n baseUrl.includes(\"deepseek.com\") ||\n isZai ||\n isMoonshot ||\n provider === \"opencode\" ||\n baseUrl.includes(\"opencode.ai\") ||\n isCloudflareWorkersAI ||\n isCloudflareAiGateway;\n const useMaxTokens = baseUrl.includes(\"chutes.ai\") || isMoonshot || isCloudflareAiGateway || isTogether;\n const isGrok = provider === \"xai\" || baseUrl.includes(\"api.x.ai\");\n const isDeepSeek = provider === \"deepseek\" || baseUrl.includes(\"deepseek.com\");\n const cacheControlFormat = provider === \"openrouter\" && model.id.startsWith(\"anthropic/\") ? \"anthropic\" : undefined;\n return {\n supportsStore: !isNonStandard,\n supportsDeveloperRole: !isNonStandard,\n supportsReasoningEffort: !isGrok && !isZai && !isMoonshot && !isTogether && !isCloudflareAiGateway,\n supportsUsageInStreaming: true,\n maxTokensField: useMaxTokens ? \"max_tokens\" : \"max_completion_tokens\",\n requiresToolResultName: false,\n requiresAssistantAfterToolResult: false,\n requiresThinkingAsText: false,\n requiresReasoningContentOnAssistantMessages: isDeepSeek,\n thinkingFormat: isDeepSeek\n ? \"deepseek\"\n : isZai\n ? \"zai\"\n : isTogether\n ? \"together\"\n : provider === \"openrouter\" || baseUrl.includes(\"openrouter.ai\")\n ? \"openrouter\"\n : \"openai\",\n openRouterRouting: {},\n vercelGatewayRouting: {},\n zaiToolStream: false,\n supportsStrictMode: !isMoonshot && !isTogether && !isCloudflareAiGateway,\n cacheControlFormat,\n sendSessionAffinityHeaders: false,\n supportsLongCacheRetention: !(isTogether || isCloudflareWorkersAI || isCloudflareAiGateway),\n };\n}\n/**\n * Get resolved compatibility settings for a model.\n * Uses explicit model.compat if provided, otherwise auto-detects from provider/URL.\n */\nfunction getCompat(model) {\n const detected = detectCompat(model);\n if (!model.compat)\n return detected;\n return {\n supportsStore: model.compat.supportsStore ?? detected.supportsStore,\n supportsDeveloperRole: model.compat.supportsDeveloperRole ?? detected.supportsDeveloperRole,\n supportsReasoningEffort: model.compat.supportsReasoningEffort ?? detected.supportsReasoningEffort,\n supportsUsageInStreaming: model.compat.supportsUsageInStreaming ?? detected.supportsUsageInStreaming,\n maxTokensField: model.compat.maxTokensField ?? detected.maxTokensField,\n requiresToolResultName: model.compat.requiresToolResultName ?? detected.requiresToolResultName,\n requiresAssistantAfterToolResult: model.compat.requiresAssistantAfterToolResult ?? detected.requiresAssistantAfterToolResult,\n requiresThinkingAsText: model.compat.requiresThinkingAsText ?? detected.requiresThinkingAsText,\n requiresReasoningContentOnAssistantMessages: model.compat.requiresReasoningContentOnAssistantMessages ??\n detected.requiresReasoningContentOnAssistantMessages,\n thinkingFormat: model.compat.thinkingFormat ?? detected.thinkingFormat,\n openRouterRouting: model.compat.openRouterRouting ?? {},\n vercelGatewayRouting: model.compat.vercelGatewayRouting ?? detected.vercelGatewayRouting,\n zaiToolStream: model.compat.zaiToolStream ?? detected.zaiToolStream,\n supportsStrictMode: model.compat.supportsStrictMode ?? detected.supportsStrictMode,\n cacheControlFormat: model.compat.cacheControlFormat ?? detected.cacheControlFormat,\n sendSessionAffinityHeaders: model.compat.sendSessionAffinityHeaders ?? detected.sendSessionAffinityHeaders,\n supportsLongCacheRetention: model.compat.supportsLongCacheRetention ?? detected.supportsLongCacheRetention,\n };\n}\n//# sourceMappingURL=openai-completions.js.map"],"x_google_ignoreList":[0],"mappings":";;;;;;;;;;;;;;;;AAiBA,SAAS,eAAe,UAAU;CAC9B,KAAK,MAAM,OAAO,UAAU;EACxB,IAAI,IAAI,SAAS,cACb,OAAO;EAEX,IAAI,IAAI,SAAS;OACT,IAAI,QAAQ,MAAM,UAAU,MAAM,SAAS,UAAU,GACrD,OAAO;EAAA;CAGnB;CACA,OAAO;AACX;AACA,SAAS,mBAAmB,OAAO;CAC/B,OAAO,MAAM,SAAS;AAC1B;AACA,SAAS,uBAAuB,OAAO;CACnC,OAAO,MAAM,SAAS;AAC1B;AACA,SAAS,gBAAgB,OAAO;CAC5B,OAAO,MAAM,SAAS;AAC1B;AACA,SAAS,oBAAoB,OAAO;CAChC,OAAO,MAAM,SAAS;AAC1B;AACA,SAAS,sBAAsB,gBAAgB;CAC3C,IAAI,gBACA,OAAO;CAEX,IAAI,OAAO,YAAY,eAAe,QAAQ,IAAI,uBAAuB,QACrE,OAAO;CAEX,OAAO;AACX;AACA,MAAa,2BAA2B,OAAO,SAAS,YAAY;CAChE,MAAM,SAAS,IAAI,4BAA4B;CAC/C,CAAC,YAAY;EACT,MAAM,SAAS;GACX,MAAM;GACN,SAAS,CAAC;GACV,KAAK,MAAM;GACX,UAAU,MAAM;GAChB,OAAO,MAAM;GACb,O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wBAAwB;EACxB,kCAAkC;EAClC,wBAAwB;EACxB,6CAA6C;EAC7C,gBAAgB,aACV,aACA,QACI,QACA,aACI,aACA,aAAa,gBAAgB,QAAQ,SAAS,eAAe,IACzD,eACA;EAClB,mBAAmB,CAAC;EACpB,sBAAsB,CAAC;EACvB,eAAe;EACf,oBAAoB,CAAC,cAAc,CAAC,cAAc,CAAC;EACnD;EACA,4BAA4B;EAC5B,4BAA4B,EAAE,cAAc,yBAAyB;CACzE;AACJ;;;;;AAKA,SAAS,UAAU,OAAO;CACtB,MAAM,WAAW,aAAa,KAAK;CACnC,IAAI,CAAC,MAAM,QACP,OAAO;CACX,OAAO;EACH,eAAe,MAAM,OAAO,iBAAiB,SAAS;EACtD,uBAAuB,MAAM,OAAO,yBAAyB,SAAS;EACtE,yBAAyB,MAAM,OAAO,2BAA2B,SAAS;EAC1E,0BAA0B,MAAM,OAAO,4BAA4B,SAAS;EAC5E,gBAAgB,MAAM,OAAO,kBAAkB,SAAS;EACxD,wBAAwB,MAAM,OAAO,0BAA0B,SAAS;EACxE,kCAAkC,MAAM,OAAO,oCAAoC,SAAS;EAC5F,wBAAwB,MAAM,OAAO,0BAA0B,SAAS;EACxE,6CAA6C,MAAM,OAAO,+CACtD,SAAS;EACb,gBAAgB,MAAM,OAAO,kBAAkB,SAAS;EACxD,mBAAmB,MAAM,OAAO,qBAAqB,CAAC;EACtD,sBAAsB,MAAM,OAAO,wBAAwB,SAAS;EACpE,eAAe,MAAM,OAAO,iBAAiB,SAAS;EACtD,oBAAoB,MAAM,OAAO,sBAAsB,SAAS;EAChE,oBAAoB,MAAM,OAAO,sBAAsB,SAAS;EAChE,4BAA4B,MAAM,OAAO,8BAA8B,SAAS;EAChF,4BAA4B,MAAM,OAAO,8BAA8B,SAAS;CACpF;AACJ"}
1
+ {"version":3,"file":"openai-completions-DaFkurXZ.mjs","names":[],"sources":["../../../node_modules/.pnpm/@earendil-works+pi-ai@0.75.4_@modelcontextprotocol+sdk@1.29.0_zod@4.4.3__ws@8.20.1_zod@4.4.3/node_modules/@earendil-works/pi-ai/dist/providers/openai-completions.js"],"sourcesContent":["import OpenAI from \"openai\";\nimport { getEnvApiKey } from \"../env-api-keys.js\";\nimport { calculateCost, clampThinkingLevel } from \"../models.js\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.js\";\nimport { headersToRecord } from \"../utils/headers.js\";\nimport { parseStreamingJson } from \"../utils/json-parse.js\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.js\";\nimport { isCloudflareProvider, resolveCloudflareBaseUrl } from \"./cloudflare.js\";\nimport { buildCopilotDynamicHeaders, hasCopilotVisionInput } from \"./github-copilot-headers.js\";\nimport { clampOpenAIPromptCacheKey } from \"./openai-prompt-cache.js\";\nimport { buildBaseOptions } from \"./simple-options.js\";\nimport { transformMessages } from \"./transform-messages.js\";\n/**\n * Check if conversation messages contain tool calls or tool results.\n * This is needed because Anthropic (via proxy) requires the tools param\n * to be present when messages include tool_calls or tool role messages.\n */\nfunction hasToolHistory(messages) {\n for (const msg of messages) {\n if (msg.role === \"toolResult\") {\n return true;\n }\n if (msg.role === \"assistant\") {\n if (msg.content.some((block) => block.type === \"toolCall\")) {\n return true;\n }\n }\n }\n return false;\n}\nfunction isTextContentBlock(block) {\n return block.type === \"text\";\n}\nfunction isThinkingContentBlock(block) {\n return block.type === \"thinking\";\n}\nfunction isToolCallBlock(block) {\n return block.type === \"toolCall\";\n}\nfunction isImageContentBlock(block) {\n return block.type === \"image\";\n}\nfunction resolveCacheRetention(cacheRetention) {\n if (cacheRetention) {\n return cacheRetention;\n }\n if (typeof process !== \"undefined\" && process.env.PI_CACHE_RETENTION === \"long\") {\n return \"long\";\n }\n return \"short\";\n}\nexport const streamOpenAICompletions = (model, context, options) => {\n const stream = new AssistantMessageEventStream();\n (async () => {\n const output = {\n role: \"assistant\",\n content: [],\n api: model.api,\n provider: model.provider,\n model: model.id,\n usage: {\n input: 0,\n output: 0,\n cacheRead: 0,\n cacheWrite: 0,\n totalTokens: 0,\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n },\n stopReason: \"stop\",\n timestamp: Date.now(),\n };\n try {\n const apiKey = options?.apiKey || getEnvApiKey(model.provider) || \"\";\n const compat = getCompat(model);\n const cacheRetention = resolveCacheRetention(options?.cacheRetention);\n const cacheSessionId = cacheRetention === \"none\" ? undefined : options?.sessionId;\n const client = createClient(model, context, apiKey, options?.headers, cacheSessionId, compat);\n let params = buildParams(model, context, options, compat, cacheRetention);\n const nextParams = await options?.onPayload?.(params, model);\n if (nextParams !== undefined) {\n params = nextParams;\n }\n const requestOptions = {\n ...(options?.signal ? { signal: options.signal } : {}),\n ...(options?.timeoutMs !== undefined ? { timeout: options.timeoutMs } : {}),\n ...(options?.maxRetries !== undefined ? { maxRetries: options.maxRetries } : {}),\n };\n const { data: openaiStream, response } = await client.chat.completions\n .create(params, requestOptions)\n .withResponse();\n await options?.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model);\n stream.push({ type: \"start\", partial: output });\n let textBlock = null;\n let thinkingBlock = null;\n let hasFinishReason = false;\n const toolCallBlocksByIndex = new Map();\n const toolCallBlocksById = new Map();\n const blocks = output.content;\n const getContentIndex = (block) => blocks.indexOf(block);\n const finishBlock = (block) => {\n const contentIndex = getContentIndex(block);\n if (contentIndex === -1) {\n return;\n }\n if (block.type === \"text\") {\n stream.push({\n type: \"text_end\",\n contentIndex,\n content: block.text,\n partial: output,\n });\n }\n else if (block.type === \"thinking\") {\n stream.push({\n type: \"thinking_end\",\n contentIndex,\n content: block.thinking,\n partial: output,\n });\n }\n else if (block.type === \"toolCall\") {\n block.arguments = parseStreamingJson(block.partialArgs);\n // Finalize in-place and strip the scratch buffers so replay only\n // carries parsed arguments.\n delete block.partialArgs;\n delete block.streamIndex;\n stream.push({\n type: \"toolcall_end\",\n contentIndex,\n toolCall: block,\n partial: output,\n });\n }\n };\n const ensureTextBlock = () => {\n if (!textBlock) {\n textBlock = { type: \"text\", text: \"\" };\n blocks.push(textBlock);\n stream.push({ type: \"text_start\", contentIndex: getContentIndex(textBlock), partial: output });\n }\n return textBlock;\n };\n const ensureThinkingBlock = (thinkingSignature) => {\n if (!thinkingBlock) {\n thinkingBlock = {\n type: \"thinking\",\n thinking: \"\",\n thinkingSignature,\n };\n blocks.push(thinkingBlock);\n stream.push({ type: \"thinking_start\", contentIndex: getContentIndex(thinkingBlock), partial: output });\n }\n return thinkingBlock;\n };\n const ensureToolCallBlock = (toolCall) => {\n const streamIndex = typeof toolCall.index === \"number\" ? toolCall.index : undefined;\n let block = streamIndex !== undefined ? toolCallBlocksByIndex.get(streamIndex) : undefined;\n if (!block && toolCall.id) {\n block = toolCallBlocksById.get(toolCall.id);\n }\n if (!block) {\n block = {\n type: \"toolCall\",\n id: toolCall.id || \"\",\n name: toolCall.function?.name || \"\",\n arguments: {},\n partialArgs: \"\",\n streamIndex,\n };\n if (streamIndex !== undefined) {\n toolCallBlocksByIndex.set(streamIndex, block);\n }\n if (toolCall.id) {\n toolCallBlocksById.set(toolCall.id, block);\n }\n blocks.push(block);\n stream.push({\n type: \"toolcall_start\",\n contentIndex: getContentIndex(block),\n partial: output,\n });\n }\n if (streamIndex !== undefined && block.streamIndex === undefined) {\n block.streamIndex = streamIndex;\n toolCallBlocksByIndex.set(streamIndex, block);\n }\n if (toolCall.id) {\n toolCallBlocksById.set(toolCall.id, block);\n }\n return block;\n };\n for await (const chunk of openaiStream) {\n if (!chunk || typeof chunk !== \"object\")\n continue;\n // OpenAI documents ChatCompletionChunk.id as the unique chat completion identifier,\n // and each chunk in a streamed completion carries the same id.\n output.responseId ||= chunk.id;\n if (typeof chunk.model === \"string\" && chunk.model.length > 0 && chunk.model !== model.id) {\n output.responseModel ||= chunk.model;\n }\n if (chunk.usage) {\n output.usage = parseChunkUsage(chunk.usage, model);\n }\n const choice = Array.isArray(chunk.choices) ? chunk.choices[0] : undefined;\n if (!choice)\n continue;\n // Fallback: some providers (e.g., Moonshot) return usage\n // in choice.usage instead of the standard chunk.usage\n if (!chunk.usage && choice.usage) {\n output.usage = parseChunkUsage(choice.usage, model);\n }\n if (choice.finish_reason) {\n const finishReasonResult = mapStopReason(choice.finish_reason);\n output.stopReason = finishReasonResult.stopReason;\n if (finishReasonResult.errorMessage) {\n output.errorMessage = finishReasonResult.errorMessage;\n }\n hasFinishReason = true;\n }\n if (choice.delta) {\n if (choice.delta.content !== null &&\n choice.delta.content !== undefined &&\n choice.delta.content.length > 0) {\n const block = ensureTextBlock();\n block.text += choice.delta.content;\n stream.push({\n type: \"text_delta\",\n contentIndex: getContentIndex(block),\n delta: choice.delta.content,\n partial: output,\n });\n }\n // Some endpoints return reasoning in reasoning_content (llama.cpp),\n // or reasoning (other openai compatible endpoints)\n // Use the first non-empty reasoning field to avoid duplication\n // (e.g., chutes.ai returns both reasoning_content and reasoning with same content)\n const reasoningFields = [\"reasoning_content\", \"reasoning\", \"reasoning_text\"];\n const deltaFields = choice.delta;\n let foundReasoningField = null;\n for (const field of reasoningFields) {\n const value = deltaFields[field];\n if (typeof value === \"string\" && value.length > 0) {\n foundReasoningField = field;\n break;\n }\n }\n if (foundReasoningField) {\n const delta = deltaFields[foundReasoningField];\n if (typeof delta === \"string\" && delta.length > 0) {\n const thinkingSignature = model.provider === \"opencode-go\" && foundReasoningField === \"reasoning\"\n ? \"reasoning_content\"\n : foundReasoningField;\n const block = ensureThinkingBlock(thinkingSignature);\n block.thinking += delta;\n stream.push({\n type: \"thinking_delta\",\n contentIndex: getContentIndex(block),\n delta,\n partial: output,\n });\n }\n }\n if (choice?.delta?.tool_calls) {\n for (const toolCall of choice.delta.tool_calls) {\n const block = ensureToolCallBlock(toolCall);\n if (!block.id && toolCall.id) {\n block.id = toolCall.id;\n toolCallBlocksById.set(toolCall.id, block);\n }\n if (!block.name && toolCall.function?.name) {\n block.name = toolCall.function.name;\n }\n let delta = \"\";\n if (toolCall.function?.arguments) {\n delta = toolCall.function.arguments;\n block.partialArgs = (block.partialArgs ?? \"\") + toolCall.function.arguments;\n block.arguments = parseStreamingJson(block.partialArgs);\n }\n stream.push({\n type: \"toolcall_delta\",\n contentIndex: getContentIndex(block),\n delta,\n partial: output,\n });\n }\n }\n const reasoningDetails = choice.delta.reasoning_details;\n if (reasoningDetails && Array.isArray(reasoningDetails)) {\n for (const detail of reasoningDetails) {\n if (detail.type === \"reasoning.encrypted\" && detail.id && detail.data) {\n const matchingToolCall = output.content.find((b) => b.type === \"toolCall\" && b.id === detail.id);\n if (matchingToolCall) {\n matchingToolCall.thoughtSignature = JSON.stringify(detail);\n }\n }\n }\n }\n }\n }\n for (const block of blocks) {\n finishBlock(block);\n }\n if (options?.signal?.aborted) {\n throw new Error(\"Request was aborted\");\n }\n if (output.stopReason === \"aborted\") {\n throw new Error(\"Request was aborted\");\n }\n if (output.stopReason === \"error\") {\n throw new Error(output.errorMessage || \"Provider returned an error stop reason\");\n }\n if (!hasFinishReason) {\n throw new Error(\"Stream ended without finish_reason\");\n }\n stream.push({ type: \"done\", reason: output.stopReason, message: output });\n stream.end();\n }\n catch (error) {\n for (const block of output.content) {\n delete block.index;\n // Streaming scratch buffers are only used during parsing; never persist them.\n delete block.partialArgs;\n delete block.streamIndex;\n }\n output.stopReason = options?.signal?.aborted ? \"aborted\" : \"error\";\n output.errorMessage = error instanceof Error ? error.message : JSON.stringify(error);\n // Some providers via OpenRouter give additional information in this field.\n const rawMetadata = error?.error?.metadata?.raw;\n if (rawMetadata)\n output.errorMessage += `\\n${rawMetadata}`;\n stream.push({ type: \"error\", reason: output.stopReason, error: output });\n stream.end();\n }\n })();\n return stream;\n};\nexport const streamSimpleOpenAICompletions = (model, context, options) => {\n const apiKey = options?.apiKey || getEnvApiKey(model.provider);\n if (!apiKey) {\n throw new Error(`No API key for provider: ${model.provider}`);\n }\n const base = buildBaseOptions(model, options, apiKey);\n const clampedReasoning = options?.reasoning ? clampThinkingLevel(model, options.reasoning) : undefined;\n const reasoningEffort = clampedReasoning === \"off\" ? undefined : clampedReasoning;\n const toolChoice = options?.toolChoice;\n return streamOpenAICompletions(model, context, {\n ...base,\n reasoningEffort,\n toolChoice,\n });\n};\nfunction createClient(model, context, apiKey, optionsHeaders, sessionId, compat = getCompat(model)) {\n if (!apiKey) {\n if (!process.env.OPENAI_API_KEY) {\n throw new Error(\"OpenAI API key is required. Set OPENAI_API_KEY environment variable or pass it as an argument.\");\n }\n apiKey = process.env.OPENAI_API_KEY;\n }\n const headers = { ...model.headers };\n if (model.provider === \"github-copilot\") {\n const hasImages = hasCopilotVisionInput(context.messages);\n const copilotHeaders = buildCopilotDynamicHeaders({\n messages: context.messages,\n hasImages,\n });\n Object.assign(headers, copilotHeaders);\n }\n if (sessionId && compat.sendSessionAffinityHeaders) {\n headers.session_id = sessionId;\n headers[\"x-client-request-id\"] = sessionId;\n headers[\"x-session-affinity\"] = sessionId;\n }\n // Merge options headers last so they can override defaults\n if (optionsHeaders) {\n Object.assign(headers, optionsHeaders);\n }\n const defaultHeaders = model.provider === \"cloudflare-ai-gateway\"\n ? {\n ...headers,\n Authorization: headers.Authorization ?? null,\n \"cf-aig-authorization\": `Bearer ${apiKey}`,\n }\n : headers;\n return new OpenAI({\n apiKey,\n baseURL: isCloudflareProvider(model.provider) ? resolveCloudflareBaseUrl(model) : model.baseUrl,\n dangerouslyAllowBrowser: true,\n defaultHeaders,\n });\n}\nfunction buildParams(model, context, options, compat = getCompat(model), cacheRetention = resolveCacheRetention(options?.cacheRetention)) {\n const messages = convertMessages(model, context, compat);\n const cacheControl = getCompatCacheControl(compat, cacheRetention);\n const params = {\n model: model.id,\n messages,\n stream: true,\n prompt_cache_key: (model.baseUrl.includes(\"api.openai.com\") && cacheRetention !== \"none\") ||\n (cacheRetention === \"long\" && compat.supportsLongCacheRetention)\n ? clampOpenAIPromptCacheKey(options?.sessionId)\n : undefined,\n prompt_cache_retention: cacheRetention === \"long\" && compat.supportsLongCacheRetention ? \"24h\" : undefined,\n };\n if (compat.supportsUsageInStreaming !== false) {\n params.stream_options = { include_usage: true };\n }\n if (compat.supportsStore) {\n params.store = false;\n }\n if (options?.maxTokens) {\n if (compat.maxTokensField === \"max_tokens\") {\n params.max_tokens = options.maxTokens;\n }\n else {\n params.max_completion_tokens = options.maxTokens;\n }\n }\n if (options?.temperature !== undefined) {\n params.temperature = options.temperature;\n }\n if (context.tools && context.tools.length > 0) {\n params.tools = convertTools(context.tools, compat);\n if (compat.zaiToolStream) {\n params.tool_stream = true;\n }\n }\n else if (hasToolHistory(context.messages)) {\n // Anthropic (via LiteLLM/proxy) requires tools param when conversation has tool_calls/tool_results\n params.tools = [];\n }\n if (cacheControl) {\n applyAnthropicCacheControl(messages, params.tools, cacheControl);\n }\n if (options?.toolChoice) {\n params.tool_choice = options.toolChoice;\n }\n if (compat.thinkingFormat === \"zai\" && model.reasoning) {\n params.enable_thinking = !!options?.reasoningEffort;\n }\n else if (compat.thinkingFormat === \"qwen\" && model.reasoning) {\n params.enable_thinking = !!options?.reasoningEffort;\n }\n else if (compat.thinkingFormat === \"qwen-chat-template\" && model.reasoning) {\n params.chat_template_kwargs = {\n enable_thinking: !!options?.reasoningEffort,\n preserve_thinking: true,\n };\n }\n else if (compat.thinkingFormat === \"deepseek\" && model.reasoning) {\n params.thinking = { type: options?.reasoningEffort ? \"enabled\" : \"disabled\" };\n if (options?.reasoningEffort) {\n params.reasoning_effort =\n model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort;\n }\n }\n else if (compat.thinkingFormat === \"openrouter\" && model.reasoning) {\n // OpenRouter normalizes reasoning across providers via a nested reasoning object.\n const openRouterParams = params;\n if (options?.reasoningEffort) {\n openRouterParams.reasoning = {\n effort: model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort,\n };\n }\n else if (model.thinkingLevelMap?.off !== null) {\n openRouterParams.reasoning = { effort: model.thinkingLevelMap?.off ?? \"none\" };\n }\n }\n else if (compat.thinkingFormat === \"together\" && model.reasoning) {\n const togetherParams = params;\n togetherParams.reasoning = { enabled: !!options?.reasoningEffort };\n if (options?.reasoningEffort && compat.supportsReasoningEffort) {\n togetherParams.reasoning_effort = model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort;\n }\n }\n else if (options?.reasoningEffort && model.reasoning && compat.supportsReasoningEffort) {\n // OpenAI-style reasoning_effort\n params.reasoning_effort = model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort;\n }\n else if (!options?.reasoningEffort && model.reasoning && compat.supportsReasoningEffort) {\n const offValue = model.thinkingLevelMap?.off;\n if (typeof offValue === \"string\") {\n params.reasoning_effort = offValue;\n }\n }\n // OpenRouter provider routing preferences\n if (model.baseUrl.includes(\"openrouter.ai\") && model.compat?.openRouterRouting) {\n params.provider = model.compat.openRouterRouting;\n }\n // Vercel AI Gateway provider routing preferences\n if (model.baseUrl.includes(\"ai-gateway.vercel.sh\") && model.compat?.vercelGatewayRouting) {\n const routing = model.compat.vercelGatewayRouting;\n if (routing.only || routing.order) {\n const gatewayOptions = {};\n if (routing.only)\n gatewayOptions.only = routing.only;\n if (routing.order)\n gatewayOptions.order = routing.order;\n params.providerOptions = { gateway: gatewayOptions };\n }\n }\n return params;\n}\nfunction getCompatCacheControl(compat, cacheRetention) {\n if (compat.cacheControlFormat !== \"anthropic\" || cacheRetention === \"none\") {\n return undefined;\n }\n const ttl = cacheRetention === \"long\" && compat.supportsLongCacheRetention ? \"1h\" : undefined;\n return { type: \"ephemeral\", ...(ttl ? { ttl } : {}) };\n}\nfunction applyAnthropicCacheControl(messages, tools, cacheControl) {\n addCacheControlToSystemPrompt(messages, cacheControl);\n addCacheControlToLastTool(tools, cacheControl);\n addCacheControlToLastConversationMessage(messages, cacheControl);\n}\nfunction addCacheControlToSystemPrompt(messages, cacheControl) {\n for (const message of messages) {\n if (message.role === \"system\" || message.role === \"developer\") {\n addCacheControlToInstructionMessage(message, cacheControl);\n return;\n }\n }\n}\nfunction addCacheControlToLastConversationMessage(messages, cacheControl) {\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n if (message.role === \"user\" || message.role === \"assistant\") {\n if (addCacheControlToMessage(message, cacheControl)) {\n return;\n }\n }\n }\n}\nfunction addCacheControlToLastTool(tools, cacheControl) {\n if (!tools || tools.length === 0) {\n return;\n }\n const lastTool = tools[tools.length - 1];\n lastTool.cache_control = cacheControl;\n}\nfunction addCacheControlToInstructionMessage(message, cacheControl) {\n return addCacheControlToTextContent(message, cacheControl);\n}\nfunction addCacheControlToMessage(message, cacheControl) {\n if (message.role === \"user\" || message.role === \"assistant\") {\n return addCacheControlToTextContent(message, cacheControl);\n }\n return false;\n}\nfunction addCacheControlToTextContent(message, cacheControl) {\n const content = message.content;\n if (typeof content === \"string\") {\n if (content.length === 0) {\n return false;\n }\n message.content = [\n {\n type: \"text\",\n text: content,\n cache_control: cacheControl,\n },\n ];\n return true;\n }\n if (!Array.isArray(content)) {\n return false;\n }\n for (let i = content.length - 1; i >= 0; i--) {\n const part = content[i];\n if (part?.type === \"text\") {\n const textPart = part;\n textPart.cache_control = cacheControl;\n return true;\n }\n }\n return false;\n}\nexport function convertMessages(model, context, compat) {\n const params = [];\n const normalizeToolCallId = (id) => {\n // Handle pipe-separated IDs from OpenAI Responses API\n // Format: {call_id}|{id} where {id} can be 400+ chars with special chars (+, /, =)\n // These come from providers like github-copilot, openai-codex, opencode\n // Extract just the call_id part and normalize it\n if (id.includes(\"|\")) {\n const [callId] = id.split(\"|\");\n // Sanitize to allowed chars and truncate to 40 chars (OpenAI limit)\n return callId.replace(/[^a-zA-Z0-9_-]/g, \"_\").slice(0, 40);\n }\n if (model.provider === \"openai\")\n return id.length > 40 ? id.slice(0, 40) : id;\n return id;\n };\n const transformedMessages = transformMessages(context.messages, model, (id) => normalizeToolCallId(id));\n if (context.systemPrompt) {\n const useDeveloperRole = model.reasoning && compat.supportsDeveloperRole;\n const role = useDeveloperRole ? \"developer\" : \"system\";\n params.push({ role: role, content: sanitizeSurrogates(context.systemPrompt) });\n }\n let lastRole = null;\n for (let i = 0; i < transformedMessages.length; i++) {\n const msg = transformedMessages[i];\n // Some providers don't allow user messages directly after tool results\n // Insert a synthetic assistant message to bridge the gap\n if (compat.requiresAssistantAfterToolResult && lastRole === \"toolResult\" && msg.role === \"user\") {\n params.push({\n role: \"assistant\",\n content: \"I have processed the tool results.\",\n });\n }\n if (msg.role === \"user\") {\n if (typeof msg.content === \"string\") {\n params.push({\n role: \"user\",\n content: sanitizeSurrogates(msg.content),\n });\n }\n else {\n const content = msg.content.map((item) => {\n if (item.type === \"text\") {\n return {\n type: \"text\",\n text: sanitizeSurrogates(item.text),\n };\n }\n else {\n return {\n type: \"image_url\",\n image_url: {\n url: `data:${item.mimeType};base64,${item.data}`,\n },\n };\n }\n });\n if (content.length === 0)\n continue;\n params.push({\n role: \"user\",\n content,\n });\n }\n }\n else if (msg.role === \"assistant\") {\n // Some providers don't accept null content, use empty string instead\n const assistantMsg = {\n role: \"assistant\",\n content: compat.requiresAssistantAfterToolResult ? \"\" : null,\n };\n const assistantTextParts = msg.content\n .filter(isTextContentBlock)\n .filter((block) => block.text.trim().length > 0)\n .map((block) => ({\n type: \"text\",\n text: sanitizeSurrogates(block.text),\n }));\n const assistantText = assistantTextParts.map((part) => part.text).join(\"\");\n const nonEmptyThinkingBlocks = msg.content\n .filter(isThinkingContentBlock)\n .filter((block) => block.thinking.trim().length > 0);\n if (nonEmptyThinkingBlocks.length > 0) {\n if (compat.requiresThinkingAsText) {\n // Convert thinking blocks to plain text (no tags to avoid model mimicking them)\n const thinkingText = nonEmptyThinkingBlocks\n .map((block) => sanitizeSurrogates(block.thinking))\n .join(\"\\n\\n\");\n assistantMsg.content = [{ type: \"text\", text: thinkingText }, ...assistantTextParts];\n }\n else {\n // Always send assistant content as a plain string (OpenAI Chat Completions\n // API standard format). Sending as an array of {type:\"text\", text:\"...\"}\n // objects is non-standard and causes some models (e.g. DeepSeek V3.2 via\n // NVIDIA NIM) to mirror the content-block structure literally in their\n // output, producing recursive nesting like [{'type':'text','text':'[{...}]'}].\n if (assistantText.length > 0) {\n assistantMsg.content = assistantText;\n }\n // Use the signature from the first thinking block if available (for llama.cpp server + gpt-oss)\n let signature = nonEmptyThinkingBlocks[0].thinkingSignature;\n if (model.provider === \"opencode-go\" && signature === \"reasoning\") {\n signature = \"reasoning_content\";\n }\n if (signature && signature.length > 0) {\n assistantMsg[signature] = nonEmptyThinkingBlocks.map((block) => block.thinking).join(\"\\n\");\n }\n }\n }\n else if (assistantText.length > 0) {\n // Always send assistant content as a plain string (OpenAI Chat Completions\n // API standard format). Sending as an array of {type:\"text\", text:\"...\"}\n // objects is non-standard and causes some models (e.g. DeepSeek V3.2 via\n // NVIDIA NIM) to mirror the content-block structure literally in their\n // output, producing recursive nesting like [{'type':'text','text':'[{...}]'}].\n assistantMsg.content = assistantText;\n }\n const toolCalls = msg.content.filter(isToolCallBlock);\n if (toolCalls.length > 0) {\n assistantMsg.tool_calls = toolCalls.map((tc) => ({\n id: tc.id,\n type: \"function\",\n function: {\n name: tc.name,\n arguments: JSON.stringify(tc.arguments),\n },\n }));\n const reasoningDetails = toolCalls\n .filter((tc) => tc.thoughtSignature)\n .map((tc) => {\n try {\n return JSON.parse(tc.thoughtSignature);\n }\n catch {\n return null;\n }\n })\n .filter(Boolean);\n if (reasoningDetails.length > 0) {\n assistantMsg.reasoning_details = reasoningDetails;\n }\n }\n if (compat.requiresReasoningContentOnAssistantMessages &&\n model.reasoning &&\n assistantMsg.reasoning_content === undefined) {\n assistantMsg.reasoning_content = \"\";\n }\n // Skip assistant messages that have no content and no tool calls.\n // Some providers require \"either content or tool_calls, but not none\".\n // Other providers also don't accept empty assistant messages.\n // This handles aborted assistant responses that got no content.\n const content = assistantMsg.content;\n const hasContent = content !== null &&\n content !== undefined &&\n (typeof content === \"string\" ? content.length > 0 : content.length > 0);\n if (!hasContent && !assistantMsg.tool_calls) {\n continue;\n }\n params.push(assistantMsg);\n }\n else if (msg.role === \"toolResult\") {\n const imageBlocks = [];\n let j = i;\n for (; j < transformedMessages.length && transformedMessages[j].role === \"toolResult\"; j++) {\n const toolMsg = transformedMessages[j];\n // Extract text and image content\n const textResult = toolMsg.content\n .filter(isTextContentBlock)\n .map((block) => block.text)\n .join(\"\\n\");\n const hasImages = toolMsg.content.some((c) => c.type === \"image\");\n // Always send tool result with text (or placeholder if only images)\n const hasText = textResult.length > 0;\n // Some providers require the 'name' field in tool results\n const toolResultMsg = {\n role: \"tool\",\n content: sanitizeSurrogates(hasText ? textResult : \"(see attached image)\"),\n tool_call_id: toolMsg.toolCallId,\n };\n if (compat.requiresToolResultName && toolMsg.toolName) {\n toolResultMsg.name = toolMsg.toolName;\n }\n params.push(toolResultMsg);\n if (hasImages && model.input.includes(\"image\")) {\n for (const block of toolMsg.content) {\n if (isImageContentBlock(block)) {\n imageBlocks.push({\n type: \"image_url\",\n image_url: {\n url: `data:${block.mimeType};base64,${block.data}`,\n },\n });\n }\n }\n }\n }\n i = j - 1;\n if (imageBlocks.length > 0) {\n if (compat.requiresAssistantAfterToolResult) {\n params.push({\n role: \"assistant\",\n content: \"I have processed the tool results.\",\n });\n }\n params.push({\n role: \"user\",\n content: [\n {\n type: \"text\",\n text: \"Attached image(s) from tool result:\",\n },\n ...imageBlocks,\n ],\n });\n lastRole = \"user\";\n }\n else {\n lastRole = \"toolResult\";\n }\n continue;\n }\n lastRole = msg.role;\n }\n return params;\n}\nfunction convertTools(tools, compat) {\n return tools.map((tool) => ({\n type: \"function\",\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters, // TypeBox already generates JSON Schema\n // Only include strict if provider supports it. Some reject unknown fields.\n ...(compat.supportsStrictMode !== false && { strict: false }),\n },\n }));\n}\nfunction parseChunkUsage(rawUsage, model) {\n const promptTokens = rawUsage.prompt_tokens || 0;\n const cacheReadTokens = rawUsage.prompt_tokens_details?.cached_tokens ?? rawUsage.prompt_cache_hit_tokens ?? 0;\n const cacheWriteTokens = rawUsage.prompt_tokens_details?.cache_write_tokens || 0;\n // Follow documented OpenAI/OpenRouter semantics: cached_tokens is cache-read\n // tokens (hits). OpenAI does not document or emit cache_write_tokens, but\n // OpenRouter-compatible providers can include it as a separate write count.\n // OpenRouter's own provider/tests affirm the separate mapping:\n // https://github.com/OpenRouterTeam/ai-sdk-provider/pull/409\n // Do not subtract writes from cached_tokens, otherwise spec-compliant\n // providers are under-reported. DS4 mirrors this contract too:\n // https://github.com/antirez/ds4/pull/29\n const input = Math.max(0, promptTokens - cacheReadTokens - cacheWriteTokens);\n // OpenAI completion_tokens already includes reasoning_tokens.\n const outputTokens = rawUsage.completion_tokens || 0;\n const usage = {\n input,\n output: outputTokens,\n cacheRead: cacheReadTokens,\n cacheWrite: cacheWriteTokens,\n totalTokens: input + outputTokens + cacheReadTokens + cacheWriteTokens,\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n };\n calculateCost(model, usage);\n return usage;\n}\nfunction mapStopReason(reason) {\n if (reason === null)\n return { stopReason: \"stop\" };\n switch (reason) {\n case \"stop\":\n case \"end\":\n return { stopReason: \"stop\" };\n case \"length\":\n return { stopReason: \"length\" };\n case \"function_call\":\n case \"tool_calls\":\n return { stopReason: \"toolUse\" };\n case \"content_filter\":\n return { stopReason: \"error\", errorMessage: \"Provider finish_reason: content_filter\" };\n case \"network_error\":\n return { stopReason: \"error\", errorMessage: \"Provider finish_reason: network_error\" };\n default:\n return {\n stopReason: \"error\",\n errorMessage: `Provider finish_reason: ${reason}`,\n };\n }\n}\n/**\n * Detect compatibility settings from provider and baseUrl for known providers.\n * Provider takes precedence over URL-based detection since it's explicitly configured.\n * Returns a fully resolved OpenAICompletionsCompat object with all fields set.\n */\nfunction detectCompat(model) {\n const provider = model.provider;\n const baseUrl = model.baseUrl;\n const isZai = provider === \"zai\" || baseUrl.includes(\"api.z.ai\");\n const isTogether = provider === \"together\" || baseUrl.includes(\"api.together.ai\") || baseUrl.includes(\"api.together.xyz\");\n const isMoonshot = provider === \"moonshotai\" || provider === \"moonshotai-cn\" || baseUrl.includes(\"api.moonshot.\");\n const isCloudflareWorkersAI = provider === \"cloudflare-workers-ai\" || baseUrl.includes(\"api.cloudflare.com\");\n const isCloudflareAiGateway = provider === \"cloudflare-ai-gateway\" || baseUrl.includes(\"gateway.ai.cloudflare.com\");\n const isNonStandard = provider === \"cerebras\" ||\n baseUrl.includes(\"cerebras.ai\") ||\n provider === \"xai\" ||\n baseUrl.includes(\"api.x.ai\") ||\n isTogether ||\n baseUrl.includes(\"chutes.ai\") ||\n baseUrl.includes(\"deepseek.com\") ||\n isZai ||\n isMoonshot ||\n provider === \"opencode\" ||\n baseUrl.includes(\"opencode.ai\") ||\n isCloudflareWorkersAI ||\n isCloudflareAiGateway;\n const useMaxTokens = baseUrl.includes(\"chutes.ai\") || isMoonshot || isCloudflareAiGateway || isTogether;\n const isGrok = provider === \"xai\" || baseUrl.includes(\"api.x.ai\");\n const isDeepSeek = provider === \"deepseek\" || baseUrl.includes(\"deepseek.com\");\n const cacheControlFormat = provider === \"openrouter\" && model.id.startsWith(\"anthropic/\") ? \"anthropic\" : undefined;\n return {\n supportsStore: !isNonStandard,\n supportsDeveloperRole: !isNonStandard,\n supportsReasoningEffort: !isGrok && !isZai && !isMoonshot && !isTogether && !isCloudflareAiGateway,\n supportsUsageInStreaming: true,\n maxTokensField: useMaxTokens ? \"max_tokens\" : \"max_completion_tokens\",\n requiresToolResultName: false,\n requiresAssistantAfterToolResult: false,\n requiresThinkingAsText: false,\n requiresReasoningContentOnAssistantMessages: isDeepSeek,\n thinkingFormat: isDeepSeek\n ? \"deepseek\"\n : isZai\n ? \"zai\"\n : isTogether\n ? \"together\"\n : provider === \"openrouter\" || baseUrl.includes(\"openrouter.ai\")\n ? \"openrouter\"\n : \"openai\",\n openRouterRouting: {},\n vercelGatewayRouting: {},\n zaiToolStream: false,\n supportsStrictMode: !isMoonshot && !isTogether && !isCloudflareAiGateway,\n cacheControlFormat,\n sendSessionAffinityHeaders: false,\n supportsLongCacheRetention: !(isTogether || isCloudflareWorkersAI || isCloudflareAiGateway),\n };\n}\n/**\n * Get resolved compatibility settings for a model.\n * Uses explicit model.compat if provided, otherwise auto-detects from provider/URL.\n */\nfunction getCompat(model) {\n const detected = detectCompat(model);\n if (!model.compat)\n return detected;\n return {\n supportsStore: model.compat.supportsStore ?? detected.supportsStore,\n supportsDeveloperRole: model.compat.supportsDeveloperRole ?? detected.supportsDeveloperRole,\n supportsReasoningEffort: model.compat.supportsReasoningEffort ?? detected.supportsReasoningEffort,\n supportsUsageInStreaming: model.compat.supportsUsageInStreaming ?? detected.supportsUsageInStreaming,\n maxTokensField: model.compat.maxTokensField ?? detected.maxTokensField,\n requiresToolResultName: model.compat.requiresToolResultName ?? detected.requiresToolResultName,\n requiresAssistantAfterToolResult: model.compat.requiresAssistantAfterToolResult ?? detected.requiresAssistantAfterToolResult,\n requiresThinkingAsText: model.compat.requiresThinkingAsText ?? detected.requiresThinkingAsText,\n requiresReasoningContentOnAssistantMessages: model.compat.requiresReasoningContentOnAssistantMessages ??\n detected.requiresReasoningContentOnAssistantMessages,\n thinkingFormat: model.compat.thinkingFormat ?? detected.thinkingFormat,\n openRouterRouting: model.compat.openRouterRouting ?? {},\n vercelGatewayRouting: model.compat.vercelGatewayRouting ?? detected.vercelGatewayRouting,\n zaiToolStream: model.compat.zaiToolStream ?? detected.zaiToolStream,\n supportsStrictMode: model.compat.supportsStrictMode ?? detected.supportsStrictMode,\n cacheControlFormat: model.compat.cacheControlFormat ?? detected.cacheControlFormat,\n sendSessionAffinityHeaders: model.compat.sendSessionAffinityHeaders ?? detected.sendSessionAffinityHeaders,\n supportsLongCacheRetention: model.compat.supportsLongCacheRetention ?? detected.supportsLongCacheRetention,\n };\n}\n//# sourceMappingURL=openai-completions.js.map"],"x_google_ignoreList":[0],"mappings":";;;;;;;;;;;;;;;;AAiBA,SAAS,eAAe,UAAU;CAC9B,KAAK,MAAM,OAAO,UAAU;EACxB,IAAI,IAAI,SAAS,cACb,OAAO;EAEX,IAAI,IAAI,SAAS;OACT,IAAI,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AAkB,SAAS;EACxD,wBAAwB,MAAM,OAAO,0BAA0B,SAAS;EACxE,kCAAkC,MAAM,OAAO,oCAAoC,SAAS;EAC5F,wBAAwB,MAAM,OAAO,0BAA0B,SAAS;EACxE,6CAA6C,MAAM,OAAO,+CACtD,SAAS;EACb,gBAAgB,MAAM,OAAO,kBAAkB,SAAS;EACxD,mBAAmB,MAAM,OAAO,qBAAqB,CAAC;EACtD,sBAAsB,MAAM,OAAO,wBAAwB,SAAS;EACpE,eAAe,MAAM,OAAO,iBAAiB,SAAS;EACtD,oBAAoB,MAAM,OAAO,sBAAsB,SAAS;EAChE,oBAAoB,MAAM,OAAO,sBAAsB,SAAS;EAChE,4BAA4B,MAAM,OAAO,8BAA8B,SAAS;EAChF,4BAA4B,MAAM,OAAO,8BAA8B,SAAS;CACpF;AACJ"}
@@ -1,12 +1,12 @@
1
1
  #!/usr/bin/env node
2
- import { t as getEnvApiKey } from "./env-api-keys-CjsGqLnm.mjs";
2
+ import { t as getEnvApiKey } from "./env-api-keys-Dj0phNAZ.mjs";
3
3
  import { r as clampThinkingLevel, t as AssistantMessageEventStream } from "./event-stream-FOdgPz2L.mjs";
4
4
  import { t as headersToRecord } from "./headers-CFU1lxB-.mjs";
5
5
  import { i as resolveCloudflareBaseUrl, n as hasCopilotVisionInput, r as isCloudflareProvider, t as buildCopilotDynamicHeaders } from "./github-copilot-headers-DMo9BAWw.mjs";
6
6
  import { r as buildBaseOptions } from "./transform-messages-B-d7Y4P2.mjs";
7
7
  import { n as OpenAI } from "./openai-DtgBmu_h.mjs";
8
8
  import { t as clampOpenAIPromptCacheKey } from "./openai-prompt-cache-BxDT7VXm.mjs";
9
- import { n as convertResponsesTools, r as processResponsesStream, t as convertResponsesMessages } from "./openai-responses-shared-rmpfdSMl.mjs";
9
+ import { n as convertResponsesTools, r as processResponsesStream, t as convertResponsesMessages } from "./openai-responses-shared-DOajVKFM.mjs";
10
10
  //#region ../../node_modules/.pnpm/@earendil-works+pi-ai@0.75.4_@modelcontextprotocol+sdk@1.29.0_zod@4.4.3__ws@8.20.1_zod@4.4.3/node_modules/@earendil-works/pi-ai/dist/providers/openai-responses.js
11
11
  const OPENAI_TOOL_CALL_PROVIDERS = new Set([
12
12
  "openai",
@@ -212,4 +212,4 @@ function applyServiceTierPricing(usage, serviceTier, model) {
212
212
  //#endregion
213
213
  export { streamOpenAIResponses, streamSimpleOpenAIResponses };
214
214
 
215
- //# sourceMappingURL=openai-responses-Dn8IOWpx.mjs.map
215
+ //# sourceMappingURL=openai-responses-DjcjpFVd.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"openai-responses-Dn8IOWpx.mjs","names":[],"sources":["../../../node_modules/.pnpm/@earendil-works+pi-ai@0.75.4_@modelcontextprotocol+sdk@1.29.0_zod@4.4.3__ws@8.20.1_zod@4.4.3/node_modules/@earendil-works/pi-ai/dist/providers/openai-responses.js"],"sourcesContent":["import OpenAI from \"openai\";\nimport { getEnvApiKey } from \"../env-api-keys.js\";\nimport { clampThinkingLevel } from \"../models.js\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.js\";\nimport { headersToRecord } from \"../utils/headers.js\";\nimport { isCloudflareProvider, resolveCloudflareBaseUrl } from \"./cloudflare.js\";\nimport { buildCopilotDynamicHeaders, hasCopilotVisionInput } from \"./github-copilot-headers.js\";\nimport { clampOpenAIPromptCacheKey } from \"./openai-prompt-cache.js\";\nimport { convertResponsesMessages, convertResponsesTools, processResponsesStream } from \"./openai-responses-shared.js\";\nimport { buildBaseOptions } from \"./simple-options.js\";\nconst OPENAI_TOOL_CALL_PROVIDERS = new Set([\"openai\", \"openai-codex\", \"opencode\"]);\n/**\n * Resolve cache retention preference.\n * Defaults to \"short\" and uses PI_CACHE_RETENTION for backward compatibility.\n */\nfunction resolveCacheRetention(cacheRetention) {\n if (cacheRetention) {\n return cacheRetention;\n }\n if (typeof process !== \"undefined\" && process.env.PI_CACHE_RETENTION === \"long\") {\n return \"long\";\n }\n return \"short\";\n}\nfunction getCompat(model) {\n return {\n sendSessionIdHeader: model.compat?.sendSessionIdHeader ?? true,\n supportsLongCacheRetention: model.compat?.supportsLongCacheRetention ?? true,\n };\n}\nfunction getPromptCacheRetention(compat, cacheRetention) {\n return cacheRetention === \"long\" && compat.supportsLongCacheRetention ? \"24h\" : undefined;\n}\nfunction formatOpenAIResponsesError(error) {\n if (error instanceof Error) {\n const status = error.status;\n const statusCode = typeof status === \"number\" ? status : undefined;\n if (statusCode !== undefined) {\n return `OpenAI API error (${statusCode}): ${error.message}`;\n }\n return error.message;\n }\n try {\n return JSON.stringify(error);\n }\n catch {\n return String(error);\n }\n}\n/**\n * Generate function for OpenAI Responses API\n */\nexport const streamOpenAIResponses = (model, context, options) => {\n const stream = new AssistantMessageEventStream();\n // Start async processing\n (async () => {\n const output = {\n role: \"assistant\",\n content: [],\n api: model.api,\n provider: model.provider,\n model: model.id,\n usage: {\n input: 0,\n output: 0,\n cacheRead: 0,\n cacheWrite: 0,\n totalTokens: 0,\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n },\n stopReason: \"stop\",\n timestamp: Date.now(),\n };\n try {\n // Create OpenAI client\n const apiKey = options?.apiKey || getEnvApiKey(model.provider) || \"\";\n const cacheRetention = resolveCacheRetention(options?.cacheRetention);\n const cacheSessionId = cacheRetention === \"none\" ? undefined : options?.sessionId;\n const client = createClient(model, context, apiKey, options?.headers, cacheSessionId);\n let params = buildParams(model, context, options);\n const nextParams = await options?.onPayload?.(params, model);\n if (nextParams !== undefined) {\n params = nextParams;\n }\n const requestOptions = {\n ...(options?.signal ? { signal: options.signal } : {}),\n ...(options?.timeoutMs !== undefined ? { timeout: options.timeoutMs } : {}),\n ...(options?.maxRetries !== undefined ? { maxRetries: options.maxRetries } : {}),\n };\n const { data: openaiStream, response } = await client.responses.create(params, requestOptions).withResponse();\n await options?.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model);\n stream.push({ type: \"start\", partial: output });\n await processResponsesStream(openaiStream, output, stream, model, {\n serviceTier: options?.serviceTier,\n applyServiceTierPricing: (usage, serviceTier) => applyServiceTierPricing(usage, serviceTier, model),\n });\n if (options?.signal?.aborted) {\n throw new Error(\"Request was aborted\");\n }\n if (output.stopReason === \"aborted\" || output.stopReason === \"error\") {\n throw new Error(\"An unknown error occurred\");\n }\n stream.push({ type: \"done\", reason: output.stopReason, message: output });\n stream.end();\n }\n catch (error) {\n for (const block of output.content) {\n delete block.index;\n // partialJson is only a streaming scratch buffer; never persist it.\n delete block.partialJson;\n }\n output.stopReason = options?.signal?.aborted ? \"aborted\" : \"error\";\n output.errorMessage = formatOpenAIResponsesError(error);\n stream.push({ type: \"error\", reason: output.stopReason, error: output });\n stream.end();\n }\n })();\n return stream;\n};\nexport const streamSimpleOpenAIResponses = (model, context, options) => {\n const apiKey = options?.apiKey || getEnvApiKey(model.provider);\n if (!apiKey) {\n throw new Error(`No API key for provider: ${model.provider}`);\n }\n const base = buildBaseOptions(model, options, apiKey);\n const clampedReasoning = options?.reasoning ? clampThinkingLevel(model, options.reasoning) : undefined;\n const reasoningEffort = clampedReasoning === \"off\" ? undefined : clampedReasoning;\n return streamOpenAIResponses(model, context, {\n ...base,\n reasoningEffort,\n });\n};\nfunction createClient(model, context, apiKey, optionsHeaders, sessionId) {\n if (!apiKey) {\n if (!process.env.OPENAI_API_KEY) {\n throw new Error(\"OpenAI API key is required. Set OPENAI_API_KEY environment variable or pass it as an argument.\");\n }\n apiKey = process.env.OPENAI_API_KEY;\n }\n const compat = getCompat(model);\n const headers = { ...model.headers };\n if (model.provider === \"github-copilot\") {\n const hasImages = hasCopilotVisionInput(context.messages);\n const copilotHeaders = buildCopilotDynamicHeaders({\n messages: context.messages,\n hasImages,\n });\n Object.assign(headers, copilotHeaders);\n }\n if (sessionId) {\n if (compat.sendSessionIdHeader) {\n headers.session_id = sessionId;\n }\n headers[\"x-client-request-id\"] = sessionId;\n }\n // Merge options headers last so they can override defaults\n if (optionsHeaders) {\n Object.assign(headers, optionsHeaders);\n }\n const defaultHeaders = model.provider === \"cloudflare-ai-gateway\"\n ? {\n ...headers,\n Authorization: headers.Authorization ?? null,\n \"cf-aig-authorization\": `Bearer ${apiKey}`,\n }\n : headers;\n return new OpenAI({\n apiKey,\n baseURL: isCloudflareProvider(model.provider) ? resolveCloudflareBaseUrl(model) : model.baseUrl,\n dangerouslyAllowBrowser: true,\n defaultHeaders,\n });\n}\nfunction buildParams(model, context, options) {\n const messages = convertResponsesMessages(model, context, OPENAI_TOOL_CALL_PROVIDERS);\n const cacheRetention = resolveCacheRetention(options?.cacheRetention);\n const compat = getCompat(model);\n const params = {\n model: model.id,\n input: messages,\n stream: true,\n prompt_cache_key: cacheRetention === \"none\" ? undefined : clampOpenAIPromptCacheKey(options?.sessionId),\n prompt_cache_retention: getPromptCacheRetention(compat, cacheRetention),\n store: false,\n };\n if (options?.maxTokens) {\n params.max_output_tokens = options?.maxTokens;\n }\n if (options?.temperature !== undefined) {\n params.temperature = options?.temperature;\n }\n if (options?.serviceTier !== undefined) {\n params.service_tier = options.serviceTier;\n }\n if (context.tools && context.tools.length > 0) {\n params.tools = convertResponsesTools(context.tools);\n }\n if (model.reasoning) {\n if (options?.reasoningEffort || options?.reasoningSummary) {\n const effort = options?.reasoningEffort\n ? (model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort)\n : \"medium\";\n params.reasoning = {\n effort: effort,\n summary: options?.reasoningSummary || \"auto\",\n };\n params.include = [\"reasoning.encrypted_content\"];\n }\n else if (model.provider !== \"github-copilot\" && model.thinkingLevelMap?.off !== null) {\n params.reasoning = {\n effort: (model.thinkingLevelMap?.off ?? \"none\"),\n };\n }\n }\n return params;\n}\nfunction getServiceTierCostMultiplier(model, serviceTier) {\n switch (serviceTier) {\n case \"flex\":\n return 0.5;\n case \"priority\":\n return model.id === \"gpt-5.5\" ? 2.5 : 2;\n default:\n return 1;\n }\n}\nfunction applyServiceTierPricing(usage, serviceTier, model) {\n const multiplier = getServiceTierCostMultiplier(model, serviceTier);\n if (multiplier === 1)\n return;\n usage.cost.input *= multiplier;\n usage.cost.output *= multiplier;\n usage.cost.cacheRead *= multiplier;\n usage.cost.cacheWrite *= multiplier;\n usage.cost.total = usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite;\n}\n//# sourceMappingURL=openai-responses.js.map"],"x_google_ignoreList":[0],"mappings":";;;;;;;;;;AAUA,MAAM,6BAA6B,IAAI,IAAI;CAAC;CAAU;CAAgB;AAAU,CAAC;;;;;AAKjF,SAAS,sBAAsB,gBAAgB;CAC3C,IAAI,gBACA,OAAO;CAEX,IAAI,OAAO,YAAY,eAAe,QAAQ,IAAI,uBAAuB,QACrE,OAAO;CAEX,OAAO;AACX;AACA,SAAS,UAAU,OAAO;CACtB,OAAO;EACH,qBAAqB,MAAM,QAAQ,uBAAuB;EAC1D,4BAA4B,MAAM,QAAQ,8BAA8B;CAC5E;AACJ;AACA,SAAS,wBAAwB,QAAQ,gBAAgB;CACrD,OAAO,mBAAmB,UAAU,OAAO,6BAA6B,QAAQ,KAAA;AACpF;AACA,SAAS,2BAA2B,OAAO;CACvC,IAAI,iBAAiB,OAAO;EACxB,MAAM,SAAS,MAAM;EACrB,MAAM,aAAa,OAAO,WAAW,WAAW,SAAS,KAAA;EACzD,IAAI,eAAe,KAAA,GACf,OAAO,qBAAqB,WAAW,KAAK,MAAM;EAEtD,OAAO,MAAM;CACjB;CACA,IAAI;EACA,OAAO,KAAK,UAAU,KAAK;CAC/B,QACM;EACF,OAAO,OAAO,KAAK;CACvB;AACJ;;;;AAIA,MAAa,yBAAyB,OAAO,SAAS,YAAY;CAC9D,MAAM,SAAS,IAAI,4BAA4B;CAE/C,CAAC,YAAY;EACT,MAAM,SAAS;GACX,MAAM;GACN,SAAS,CAAC;GACV,KAAK,MAAM;GACX,UAAU,MAAM;GAChB,OAAO,MAAM;GACb,OAAO;IACH,OAAO;IACP,QAAQ;IACR,WAAW;IACX,YAAY;IACZ,aAAa;IACb,MAAM;KAA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KAAK,QACD,OAAO;EACX,KAAK,YACD,OAAO,MAAM,OAAO,YAAY,MAAM;EAC1C,SACI,OAAO;CACf;AACJ;AACA,SAAS,wBAAwB,OAAO,aAAa,OAAO;CACxD,MAAM,aAAa,6BAA6B,OAAO,WAAW;CAClE,IAAI,eAAe,GACf;CACJ,MAAM,KAAK,SAAS;CACpB,MAAM,KAAK,UAAU;CACrB,MAAM,KAAK,aAAa;CACxB,MAAM,KAAK,cAAc;CACzB,MAAM,KAAK,QAAQ,MAAM,KAAK,QAAQ,MAAM,KAAK,SAAS,MAAM,KAAK,YAAY,MAAM,KAAK;AAChG"}
1
+ {"version":3,"file":"openai-responses-DjcjpFVd.mjs","names":[],"sources":["../../../node_modules/.pnpm/@earendil-works+pi-ai@0.75.4_@modelcontextprotocol+sdk@1.29.0_zod@4.4.3__ws@8.20.1_zod@4.4.3/node_modules/@earendil-works/pi-ai/dist/providers/openai-responses.js"],"sourcesContent":["import OpenAI from \"openai\";\nimport { getEnvApiKey } from \"../env-api-keys.js\";\nimport { clampThinkingLevel } from \"../models.js\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.js\";\nimport { headersToRecord } from \"../utils/headers.js\";\nimport { isCloudflareProvider, resolveCloudflareBaseUrl } from \"./cloudflare.js\";\nimport { buildCopilotDynamicHeaders, hasCopilotVisionInput } from \"./github-copilot-headers.js\";\nimport { clampOpenAIPromptCacheKey } from \"./openai-prompt-cache.js\";\nimport { convertResponsesMessages, convertResponsesTools, processResponsesStream } from \"./openai-responses-shared.js\";\nimport { buildBaseOptions } from \"./simple-options.js\";\nconst OPENAI_TOOL_CALL_PROVIDERS = new Set([\"openai\", \"openai-codex\", \"opencode\"]);\n/**\n * Resolve cache retention preference.\n * Defaults to \"short\" and uses PI_CACHE_RETENTION for backward compatibility.\n */\nfunction resolveCacheRetention(cacheRetention) {\n if (cacheRetention) {\n return cacheRetention;\n }\n if (typeof process !== \"undefined\" && process.env.PI_CACHE_RETENTION === \"long\") {\n return \"long\";\n }\n return \"short\";\n}\nfunction getCompat(model) {\n return {\n sendSessionIdHeader: model.compat?.sendSessionIdHeader ?? true,\n supportsLongCacheRetention: model.compat?.supportsLongCacheRetention ?? true,\n };\n}\nfunction getPromptCacheRetention(compat, cacheRetention) {\n return cacheRetention === \"long\" && compat.supportsLongCacheRetention ? \"24h\" : undefined;\n}\nfunction formatOpenAIResponsesError(error) {\n if (error instanceof Error) {\n const status = error.status;\n const statusCode = typeof status === \"number\" ? status : undefined;\n if (statusCode !== undefined) {\n return `OpenAI API error (${statusCode}): ${error.message}`;\n }\n return error.message;\n }\n try {\n return JSON.stringify(error);\n }\n catch {\n return String(error);\n }\n}\n/**\n * Generate function for OpenAI Responses API\n */\nexport const streamOpenAIResponses = (model, context, options) => {\n const stream = new AssistantMessageEventStream();\n // Start async processing\n (async () => {\n const output = {\n role: \"assistant\",\n content: [],\n api: model.api,\n provider: model.provider,\n model: model.id,\n usage: {\n input: 0,\n output: 0,\n cacheRead: 0,\n cacheWrite: 0,\n totalTokens: 0,\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n },\n stopReason: \"stop\",\n timestamp: Date.now(),\n };\n try {\n // Create OpenAI client\n const apiKey = options?.apiKey || getEnvApiKey(model.provider) || \"\";\n const cacheRetention = resolveCacheRetention(options?.cacheRetention);\n const cacheSessionId = cacheRetention === \"none\" ? undefined : options?.sessionId;\n const client = createClient(model, context, apiKey, options?.headers, cacheSessionId);\n let params = buildParams(model, context, options);\n const nextParams = await options?.onPayload?.(params, model);\n if (nextParams !== undefined) {\n params = nextParams;\n }\n const requestOptions = {\n ...(options?.signal ? { signal: options.signal } : {}),\n ...(options?.timeoutMs !== undefined ? { timeout: options.timeoutMs } : {}),\n ...(options?.maxRetries !== undefined ? { maxRetries: options.maxRetries } : {}),\n };\n const { data: openaiStream, response } = await client.responses.create(params, requestOptions).withResponse();\n await options?.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model);\n stream.push({ type: \"start\", partial: output });\n await processResponsesStream(openaiStream, output, stream, model, {\n serviceTier: options?.serviceTier,\n applyServiceTierPricing: (usage, serviceTier) => applyServiceTierPricing(usage, serviceTier, model),\n });\n if (options?.signal?.aborted) {\n throw new Error(\"Request was aborted\");\n }\n if (output.stopReason === \"aborted\" || output.stopReason === \"error\") {\n throw new Error(\"An unknown error occurred\");\n }\n stream.push({ type: \"done\", reason: output.stopReason, message: output });\n stream.end();\n }\n catch (error) {\n for (const block of output.content) {\n delete block.index;\n // partialJson is only a streaming scratch buffer; never persist it.\n delete block.partialJson;\n }\n output.stopReason = options?.signal?.aborted ? \"aborted\" : \"error\";\n output.errorMessage = formatOpenAIResponsesError(error);\n stream.push({ type: \"error\", reason: output.stopReason, error: output });\n stream.end();\n }\n })();\n return stream;\n};\nexport const streamSimpleOpenAIResponses = (model, context, options) => {\n const apiKey = options?.apiKey || getEnvApiKey(model.provider);\n if (!apiKey) {\n throw new Error(`No API key for provider: ${model.provider}`);\n }\n const base = buildBaseOptions(model, options, apiKey);\n const clampedReasoning = options?.reasoning ? clampThinkingLevel(model, options.reasoning) : undefined;\n const reasoningEffort = clampedReasoning === \"off\" ? undefined : clampedReasoning;\n return streamOpenAIResponses(model, context, {\n ...base,\n reasoningEffort,\n });\n};\nfunction createClient(model, context, apiKey, optionsHeaders, sessionId) {\n if (!apiKey) {\n if (!process.env.OPENAI_API_KEY) {\n throw new Error(\"OpenAI API key is required. Set OPENAI_API_KEY environment variable or pass it as an argument.\");\n }\n apiKey = process.env.OPENAI_API_KEY;\n }\n const compat = getCompat(model);\n const headers = { ...model.headers };\n if (model.provider === \"github-copilot\") {\n const hasImages = hasCopilotVisionInput(context.messages);\n const copilotHeaders = buildCopilotDynamicHeaders({\n messages: context.messages,\n hasImages,\n });\n Object.assign(headers, copilotHeaders);\n }\n if (sessionId) {\n if (compat.sendSessionIdHeader) {\n headers.session_id = sessionId;\n }\n headers[\"x-client-request-id\"] = sessionId;\n }\n // Merge options headers last so they can override defaults\n if (optionsHeaders) {\n Object.assign(headers, optionsHeaders);\n }\n const defaultHeaders = model.provider === \"cloudflare-ai-gateway\"\n ? {\n ...headers,\n Authorization: headers.Authorization ?? null,\n \"cf-aig-authorization\": `Bearer ${apiKey}`,\n }\n : headers;\n return new OpenAI({\n apiKey,\n baseURL: isCloudflareProvider(model.provider) ? resolveCloudflareBaseUrl(model) : model.baseUrl,\n dangerouslyAllowBrowser: true,\n defaultHeaders,\n });\n}\nfunction buildParams(model, context, options) {\n const messages = convertResponsesMessages(model, context, OPENAI_TOOL_CALL_PROVIDERS);\n const cacheRetention = resolveCacheRetention(options?.cacheRetention);\n const compat = getCompat(model);\n const params = {\n model: model.id,\n input: messages,\n stream: true,\n prompt_cache_key: cacheRetention === \"none\" ? undefined : clampOpenAIPromptCacheKey(options?.sessionId),\n prompt_cache_retention: getPromptCacheRetention(compat, cacheRetention),\n store: false,\n };\n if (options?.maxTokens) {\n params.max_output_tokens = options?.maxTokens;\n }\n if (options?.temperature !== undefined) {\n params.temperature = options?.temperature;\n }\n if (options?.serviceTier !== undefined) {\n params.service_tier = options.serviceTier;\n }\n if (context.tools && context.tools.length > 0) {\n params.tools = convertResponsesTools(context.tools);\n }\n if (model.reasoning) {\n if (options?.reasoningEffort || options?.reasoningSummary) {\n const effort = options?.reasoningEffort\n ? (model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort)\n : \"medium\";\n params.reasoning = {\n effort: effort,\n summary: options?.reasoningSummary || \"auto\",\n };\n params.include = [\"reasoning.encrypted_content\"];\n }\n else if (model.provider !== \"github-copilot\" && model.thinkingLevelMap?.off !== null) {\n params.reasoning = {\n effort: (model.thinkingLevelMap?.off ?? \"none\"),\n };\n }\n }\n return params;\n}\nfunction getServiceTierCostMultiplier(model, serviceTier) {\n switch (serviceTier) {\n case \"flex\":\n return 0.5;\n case \"priority\":\n return model.id === \"gpt-5.5\" ? 2.5 : 2;\n default:\n return 1;\n }\n}\nfunction applyServiceTierPricing(usage, serviceTier, model) {\n const multiplier = getServiceTierCostMultiplier(model, serviceTier);\n if (multiplier === 1)\n return;\n usage.cost.input *= multiplier;\n usage.cost.output *= multiplier;\n usage.cost.cacheRead *= multiplier;\n usage.cost.cacheWrite *= multiplier;\n usage.cost.total = usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite;\n}\n//# sourceMappingURL=openai-responses.js.map"],"x_google_ignoreList":[0],"mappings":";;;;;;;;;;AAUA,MAAM,6BAA6B,IAAI,IAAI;CAAC;CAAU;CAAgB;AAAU,CAAC;;;;;AAKjF,SAAS,sBAAsB,gBAAgB;CAC3C,IAAI,gBACA,OAAO;CAEX,IAAI,OAAO,YAAY,eAAe,QAAQ,IAAI,uBAAuB,QACrE,OAAO;CAEX,OAAO;AACX;AACA,SAAS,UAAU,OAAO;CACtB,OAAO;EACH,qBAAqB,MAAM,QAAQ,uBAAuB;EAC1D,4BAA4B,MAAM,QAAQ,8BAA8B;CAC5E;AACJ;AACA,SAAS,wBAAwB,QAAQ,gBAAgB;CACrD,OAAO,mBAAmB,UAAU,OAAO,6BAA6B,QAAQ,KAAA;AACpF;AACA,SAAS,2BAA2B,OAAO;CACvC,IAAI,iBAAiB,OAAO;EACxB,MAAM,SAAS,MAAM;EACrB,MAAM,aAAa,OAAO,WAAW,WAAW,SAAS,KAAA;EACzD,IAAI,eAAe,KAAA,GACf,OAAO,qBAAqB,WAAW,KAAK,MAAM;EAEtD,OAAO,MAAM;CACjB;CACA,IAAI;EACA,OAAO,KAAK,UAAU,KAAK;CAC/B,QACM;EACF,OAAO,OAAO,KAAK;CACvB;AACJ;;;;AAIA,MAAa,yBAAyB,OAAO,SAAS,YAAY;CAC9D,MAAM,SAAS,IAAI,4BAA4B;CAE/C,CAAC,YAAY;EACT,MAAM,SAAS;GACX,MAAM;GACN,SAAS,CAAC;GACV,KAAK,MAAM;GACX,UAAU,MAAM;GAChB,OAAO,MAAM;GACb,OAAO;IACH,OAAO;IACP,QAAQ;IACR,WAAW;IACX,YAAY;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a;CACtD,QAAQ,aAAR;EACI,KAAK,QACD,OAAO;EACX,KAAK,YACD,OAAO,MAAM,OAAO,YAAY,MAAM;EAC1C,SACI,OAAO;CACf;AACJ;AACA,SAAS,wBAAwB,OAAO,aAAa,OAAO;CACxD,MAAM,aAAa,6BAA6B,OAAO,WAAW;CAClE,IAAI,eAAe,GACf;CACJ,MAAM,KAAK,SAAS;CACpB,MAAM,KAAK,UAAU;CACrB,MAAM,KAAK,aAAa;CACxB,MAAM,KAAK,cAAc;CACzB,MAAM,KAAK,QAAQ,MAAM,KAAK,QAAQ,MAAM,KAAK,SAAS,MAAM,KAAK,YAAY,MAAM,KAAK;AAChG"}
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { n as calculateCost } from "./event-stream-FOdgPz2L.mjs";
3
- import { n as parseStreamingJson } from "./json-parse-4wvL0yab.mjs";
3
+ import { n as parseStreamingJson } from "./json-parse-D7gmIw6y.mjs";
4
4
  import { t as sanitizeSurrogates } from "./sanitize-unicode-DH1T1t81.mjs";
5
5
  import { t as transformMessages } from "./transform-messages-B-d7Y4P2.mjs";
6
6
  import { t as shortHash } from "./hash-BmUcU4LB.mjs";
@@ -411,4 +411,4 @@ function mapStopReason(status) {
411
411
  //#endregion
412
412
  export { convertResponsesTools as n, processResponsesStream as r, convertResponsesMessages as t };
413
413
 
414
- //# sourceMappingURL=openai-responses-shared-rmpfdSMl.mjs.map
414
+ //# sourceMappingURL=openai-responses-shared-DOajVKFM.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"openai-responses-shared-rmpfdSMl.mjs","names":["_exhaustive"],"sources":["../../../node_modules/.pnpm/@earendil-works+pi-ai@0.75.4_@modelcontextprotocol+sdk@1.29.0_zod@4.4.3__ws@8.20.1_zod@4.4.3/node_modules/@earendil-works/pi-ai/dist/providers/openai-responses-shared.js"],"sourcesContent":["import { calculateCost } from \"../models.js\";\nimport { shortHash } from \"../utils/hash.js\";\nimport { parseStreamingJson } from \"../utils/json-parse.js\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.js\";\nimport { transformMessages } from \"./transform-messages.js\";\n// =============================================================================\n// Utilities\n// =============================================================================\nfunction encodeTextSignatureV1(id, phase) {\n const payload = { v: 1, id };\n if (phase)\n payload.phase = phase;\n return JSON.stringify(payload);\n}\nfunction parseTextSignature(signature) {\n if (!signature)\n return undefined;\n if (signature.startsWith(\"{\")) {\n try {\n const parsed = JSON.parse(signature);\n if (parsed.v === 1 && typeof parsed.id === \"string\") {\n if (parsed.phase === \"commentary\" || parsed.phase === \"final_answer\") {\n return { id: parsed.id, phase: parsed.phase };\n }\n return { id: parsed.id };\n }\n }\n catch {\n // Fall through to legacy plain-string handling.\n }\n }\n return { id: signature };\n}\n// =============================================================================\n// Message conversion\n// =============================================================================\nexport function convertResponsesMessages(model, context, allowedToolCallProviders, options) {\n const messages = [];\n const normalizeIdPart = (part) => {\n const sanitized = part.replace(/[^a-zA-Z0-9_-]/g, \"_\");\n const normalized = sanitized.length > 64 ? sanitized.slice(0, 64) : sanitized;\n return normalized.replace(/_+$/, \"\");\n };\n const buildForeignResponsesItemId = (itemId) => {\n const normalized = `fc_${shortHash(itemId)}`;\n return normalized.length > 64 ? normalized.slice(0, 64) : normalized;\n };\n const normalizeToolCallId = (id, _targetModel, source) => {\n if (!allowedToolCallProviders.has(model.provider))\n return normalizeIdPart(id);\n if (!id.includes(\"|\"))\n return normalizeIdPart(id);\n const [callId, itemId] = id.split(\"|\");\n const normalizedCallId = normalizeIdPart(callId);\n const isForeignToolCall = source.provider !== model.provider || source.api !== model.api;\n let normalizedItemId = isForeignToolCall ? buildForeignResponsesItemId(itemId) : normalizeIdPart(itemId);\n // OpenAI Responses API requires item id to start with \"fc\"\n if (!normalizedItemId.startsWith(\"fc_\")) {\n normalizedItemId = normalizeIdPart(`fc_${normalizedItemId}`);\n }\n return `${normalizedCallId}|${normalizedItemId}`;\n };\n const transformedMessages = transformMessages(context.messages, model, normalizeToolCallId);\n const includeSystemPrompt = options?.includeSystemPrompt ?? true;\n if (includeSystemPrompt && context.systemPrompt) {\n const role = model.reasoning ? \"developer\" : \"system\";\n messages.push({\n role,\n content: sanitizeSurrogates(context.systemPrompt),\n });\n }\n let msgIndex = 0;\n for (const msg of transformedMessages) {\n if (msg.role === \"user\") {\n if (typeof msg.content === \"string\") {\n messages.push({\n role: \"user\",\n content: [{ type: \"input_text\", text: sanitizeSurrogates(msg.content) }],\n });\n }\n else {\n const content = msg.content.map((item) => {\n if (item.type === \"text\") {\n return {\n type: \"input_text\",\n text: sanitizeSurrogates(item.text),\n };\n }\n return {\n type: \"input_image\",\n detail: \"auto\",\n image_url: `data:${item.mimeType};base64,${item.data}`,\n };\n });\n if (content.length === 0)\n continue;\n messages.push({\n role: \"user\",\n content,\n });\n }\n }\n else if (msg.role === \"assistant\") {\n const output = [];\n const assistantMsg = msg;\n const isDifferentModel = assistantMsg.model !== model.id &&\n assistantMsg.provider === model.provider &&\n assistantMsg.api === model.api;\n for (const block of msg.content) {\n if (block.type === \"thinking\") {\n if (block.thinkingSignature) {\n const reasoningItem = JSON.parse(block.thinkingSignature);\n output.push(reasoningItem);\n }\n }\n else if (block.type === \"text\") {\n const textBlock = block;\n const parsedSignature = parseTextSignature(textBlock.textSignature);\n // OpenAI requires id to be max 64 characters\n let msgId = parsedSignature?.id;\n if (!msgId) {\n msgId = `msg_${msgIndex}`;\n }\n else if (msgId.length > 64) {\n msgId = `msg_${shortHash(msgId)}`;\n }\n output.push({\n type: \"message\",\n role: \"assistant\",\n content: [{ type: \"output_text\", text: sanitizeSurrogates(textBlock.text), annotations: [] }],\n status: \"completed\",\n id: msgId,\n phase: parsedSignature?.phase,\n });\n }\n else if (block.type === \"toolCall\") {\n const toolCall = block;\n const [callId, itemIdRaw] = toolCall.id.split(\"|\");\n let itemId = itemIdRaw;\n // For different-model messages, set id to undefined to avoid pairing validation.\n // OpenAI tracks which fc_xxx IDs were paired with rs_xxx reasoning items.\n // By omitting the id, we avoid triggering that validation (like cross-provider does).\n if (isDifferentModel && itemId?.startsWith(\"fc_\")) {\n itemId = undefined;\n }\n output.push({\n type: \"function_call\",\n id: itemId,\n call_id: callId,\n name: toolCall.name,\n arguments: JSON.stringify(toolCall.arguments),\n });\n }\n }\n if (output.length === 0)\n continue;\n messages.push(...output);\n }\n else if (msg.role === \"toolResult\") {\n const textResult = msg.content\n .filter((c) => c.type === \"text\")\n .map((c) => c.text)\n .join(\"\\n\");\n const hasImages = msg.content.some((c) => c.type === \"image\");\n const hasText = textResult.length > 0;\n const [callId] = msg.toolCallId.split(\"|\");\n let output;\n if (hasImages && model.input.includes(\"image\")) {\n const contentParts = [];\n if (hasText) {\n contentParts.push({\n type: \"input_text\",\n text: sanitizeSurrogates(textResult),\n });\n }\n for (const block of msg.content) {\n if (block.type === \"image\") {\n contentParts.push({\n type: \"input_image\",\n detail: \"auto\",\n image_url: `data:${block.mimeType};base64,${block.data}`,\n });\n }\n }\n output = contentParts;\n }\n else {\n output = sanitizeSurrogates(hasText ? textResult : \"(see attached image)\");\n }\n messages.push({\n type: \"function_call_output\",\n call_id: callId,\n output,\n });\n }\n msgIndex++;\n }\n return messages;\n}\n// =============================================================================\n// Tool conversion\n// =============================================================================\nexport function convertResponsesTools(tools, options) {\n const strict = options?.strict === undefined ? false : options.strict;\n return tools.map((tool) => ({\n type: \"function\",\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters, // TypeBox already generates JSON Schema\n strict,\n }));\n}\n// =============================================================================\n// Stream processing\n// =============================================================================\nexport async function processResponsesStream(openaiStream, output, stream, model, options) {\n let currentItem = null;\n let currentBlock = null;\n const blocks = output.content;\n const blockIndex = () => blocks.length - 1;\n for await (const event of openaiStream) {\n if (event.type === \"response.created\") {\n output.responseId = event.response.id;\n }\n else if (event.type === \"response.output_item.added\") {\n const item = event.item;\n if (item.type === \"reasoning\") {\n currentItem = item;\n currentBlock = { type: \"thinking\", thinking: \"\" };\n output.content.push(currentBlock);\n stream.push({ type: \"thinking_start\", contentIndex: blockIndex(), partial: output });\n }\n else if (item.type === \"message\") {\n currentItem = item;\n currentBlock = { type: \"text\", text: \"\" };\n output.content.push(currentBlock);\n stream.push({ type: \"text_start\", contentIndex: blockIndex(), partial: output });\n }\n else if (item.type === \"function_call\") {\n currentItem = item;\n currentBlock = {\n type: \"toolCall\",\n id: `${item.call_id}|${item.id}`,\n name: item.name,\n arguments: {},\n partialJson: item.arguments || \"\",\n };\n output.content.push(currentBlock);\n stream.push({ type: \"toolcall_start\", contentIndex: blockIndex(), partial: output });\n }\n }\n else if (event.type === \"response.reasoning_summary_part.added\") {\n if (currentItem && currentItem.type === \"reasoning\") {\n currentItem.summary = currentItem.summary || [];\n currentItem.summary.push(event.part);\n }\n }\n else if (event.type === \"response.reasoning_summary_text.delta\") {\n if (currentItem?.type === \"reasoning\" && currentBlock?.type === \"thinking\") {\n currentItem.summary = currentItem.summary || [];\n const lastPart = currentItem.summary[currentItem.summary.length - 1];\n if (lastPart) {\n currentBlock.thinking += event.delta;\n lastPart.text += event.delta;\n stream.push({\n type: \"thinking_delta\",\n contentIndex: blockIndex(),\n delta: event.delta,\n partial: output,\n });\n }\n }\n }\n else if (event.type === \"response.reasoning_summary_part.done\") {\n if (currentItem?.type === \"reasoning\" && currentBlock?.type === \"thinking\") {\n currentItem.summary = currentItem.summary || [];\n const lastPart = currentItem.summary[currentItem.summary.length - 1];\n if (lastPart) {\n currentBlock.thinking += \"\\n\\n\";\n lastPart.text += \"\\n\\n\";\n stream.push({\n type: \"thinking_delta\",\n contentIndex: blockIndex(),\n delta: \"\\n\\n\",\n partial: output,\n });\n }\n }\n }\n else if (event.type === \"response.reasoning_text.delta\") {\n if (currentItem?.type === \"reasoning\" && currentBlock?.type === \"thinking\") {\n currentBlock.thinking += event.delta;\n stream.push({\n type: \"thinking_delta\",\n contentIndex: blockIndex(),\n delta: event.delta,\n partial: output,\n });\n }\n }\n else if (event.type === \"response.content_part.added\") {\n if (currentItem?.type === \"message\") {\n currentItem.content = currentItem.content || [];\n // Filter out ReasoningText, only accept output_text and refusal\n if (event.part.type === \"output_text\" || event.part.type === \"refusal\") {\n currentItem.content.push(event.part);\n }\n }\n }\n else if (event.type === \"response.output_text.delta\") {\n if (currentItem?.type === \"message\" && currentBlock?.type === \"text\") {\n if (!currentItem.content || currentItem.content.length === 0) {\n continue;\n }\n const lastPart = currentItem.content[currentItem.content.length - 1];\n if (lastPart?.type === \"output_text\") {\n currentBlock.text += event.delta;\n lastPart.text += event.delta;\n stream.push({\n type: \"text_delta\",\n contentIndex: blockIndex(),\n delta: event.delta,\n partial: output,\n });\n }\n }\n }\n else if (event.type === \"response.refusal.delta\") {\n if (currentItem?.type === \"message\" && currentBlock?.type === \"text\") {\n if (!currentItem.content || currentItem.content.length === 0) {\n continue;\n }\n const lastPart = currentItem.content[currentItem.content.length - 1];\n if (lastPart?.type === \"refusal\") {\n currentBlock.text += event.delta;\n lastPart.refusal += event.delta;\n stream.push({\n type: \"text_delta\",\n contentIndex: blockIndex(),\n delta: event.delta,\n partial: output,\n });\n }\n }\n }\n else if (event.type === \"response.function_call_arguments.delta\") {\n if (currentItem?.type === \"function_call\" && currentBlock?.type === \"toolCall\") {\n currentBlock.partialJson += event.delta;\n currentBlock.arguments = parseStreamingJson(currentBlock.partialJson);\n stream.push({\n type: \"toolcall_delta\",\n contentIndex: blockIndex(),\n delta: event.delta,\n partial: output,\n });\n }\n }\n else if (event.type === \"response.function_call_arguments.done\") {\n if (currentItem?.type === \"function_call\" && currentBlock?.type === \"toolCall\") {\n const previousPartialJson = currentBlock.partialJson;\n currentBlock.partialJson = event.arguments;\n currentBlock.arguments = parseStreamingJson(currentBlock.partialJson);\n if (event.arguments.startsWith(previousPartialJson)) {\n const delta = event.arguments.slice(previousPartialJson.length);\n if (delta.length > 0) {\n stream.push({\n type: \"toolcall_delta\",\n contentIndex: blockIndex(),\n delta,\n partial: output,\n });\n }\n }\n }\n }\n else if (event.type === \"response.output_item.done\") {\n const item = event.item;\n if (item.type === \"reasoning\" && currentBlock?.type === \"thinking\") {\n const summaryText = item.summary?.map((s) => s.text).join(\"\\n\\n\") || \"\";\n const contentText = item.content?.map((c) => c.text).join(\"\\n\\n\") || \"\";\n currentBlock.thinking = summaryText || contentText || currentBlock.thinking;\n currentBlock.thinkingSignature = JSON.stringify(item);\n stream.push({\n type: \"thinking_end\",\n contentIndex: blockIndex(),\n content: currentBlock.thinking,\n partial: output,\n });\n currentBlock = null;\n }\n else if (item.type === \"message\" && currentBlock?.type === \"text\") {\n currentBlock.text = item.content.map((c) => (c.type === \"output_text\" ? c.text : c.refusal)).join(\"\");\n currentBlock.textSignature = encodeTextSignatureV1(item.id, item.phase ?? undefined);\n stream.push({\n type: \"text_end\",\n contentIndex: blockIndex(),\n content: currentBlock.text,\n partial: output,\n });\n currentBlock = null;\n }\n else if (item.type === \"function_call\") {\n const args = currentBlock?.type === \"toolCall\" && currentBlock.partialJson\n ? parseStreamingJson(currentBlock.partialJson)\n : parseStreamingJson(item.arguments || \"{}\");\n let toolCall;\n if (currentBlock?.type === \"toolCall\") {\n // Finalize in-place and strip the scratch buffer so replay only\n // carries parsed arguments.\n currentBlock.arguments = args;\n delete currentBlock.partialJson;\n toolCall = currentBlock;\n }\n else {\n toolCall = {\n type: \"toolCall\",\n id: `${item.call_id}|${item.id}`,\n name: item.name,\n arguments: args,\n };\n }\n currentBlock = null;\n stream.push({ type: \"toolcall_end\", contentIndex: blockIndex(), toolCall, partial: output });\n }\n }\n else if (event.type === \"response.completed\") {\n const response = event.response;\n if (response?.id) {\n output.responseId = response.id;\n }\n if (response?.usage) {\n const cachedTokens = response.usage.input_tokens_details?.cached_tokens || 0;\n output.usage = {\n // OpenAI includes cached tokens in input_tokens, so subtract to get non-cached input\n input: (response.usage.input_tokens || 0) - cachedTokens,\n output: response.usage.output_tokens || 0,\n cacheRead: cachedTokens,\n cacheWrite: 0,\n totalTokens: response.usage.total_tokens || 0,\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n };\n }\n calculateCost(model, output.usage);\n if (options?.applyServiceTierPricing) {\n const serviceTier = options.resolveServiceTier\n ? options.resolveServiceTier(response?.service_tier, options.serviceTier)\n : (response?.service_tier ?? options.serviceTier);\n options.applyServiceTierPricing(output.usage, serviceTier);\n }\n // Map status to stop reason\n output.stopReason = mapStopReason(response?.status);\n if (output.content.some((b) => b.type === \"toolCall\") && output.stopReason === \"stop\") {\n output.stopReason = \"toolUse\";\n }\n }\n else if (event.type === \"error\") {\n throw new Error(`Error Code ${event.code}: ${event.message}` || \"Unknown error\");\n }\n else if (event.type === \"response.failed\") {\n const error = event.response?.error;\n const details = event.response?.incomplete_details;\n const msg = error\n ? `${error.code || \"unknown\"}: ${error.message || \"no message\"}`\n : details?.reason\n ? `incomplete: ${details.reason}`\n : \"Unknown error (no error details in response)\";\n throw new Error(msg);\n }\n }\n}\nfunction mapStopReason(status) {\n if (!status)\n return \"stop\";\n switch (status) {\n case \"completed\":\n return \"stop\";\n case \"incomplete\":\n return \"length\";\n case \"failed\":\n case \"cancelled\":\n return \"error\";\n // These two are wonky ...\n case \"in_progress\":\n case \"queued\":\n return \"stop\";\n default: {\n const _exhaustive = status;\n throw new Error(`Unhandled stop reason: ${_exhaustive}`);\n }\n }\n}\n//# sourceMappingURL=openai-responses-shared.js.map"],"x_google_ignoreList":[0],"mappings":";;;;;;;AAQA,SAAS,sBAAsB,IAAI,OAAO;CACtC,MAAM,UAAU;EAAE,GAAG;EAAG;CAAG;CAC3B,IAAI,OACA,QAAQ,QAAQ;CACpB,OAAO,KAAK,UAAU,OAAO;AACjC;AACA,SAAS,mBAAmB,WAAW;CACnC,IAAI,CAAC,WACD,OAAO,KAAA;CACX,IAAI,UAAU,WAAW,GAAG,GACxB,IAAI;EACA,MAAM,SAAS,KAAK,MAAM,SAAS;EACnC,IAAI,OAAO,MAAM,KAAK,OAAO,OAAO,OAAO,UAAU;GACjD,IAAI,OAAO,UAAU,gBAAgB,OAAO,UAAU,gBAClD,OAAO;IAAE,IAA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AS,MAAM,gBAAgB;IAC5C,MAAM;KAAE,OAAO;KAAG,QAAQ;KAAG,WAAW;KAAG,YAAY;KAAG,OAAO;IAAE;GACvE;EACJ;EACA,cAAc,OAAO,OAAO,KAAK;EACjC,IAAI,SAAS,yBAAyB;GAClC,MAAM,cAAc,QAAQ,qBACtB,QAAQ,mBAAmB,UAAU,cAAc,QAAQ,WAAW,IACrE,UAAU,gBAAgB,QAAQ;GACzC,QAAQ,wBAAwB,OAAO,OAAO,WAAW;EAC7D;EAEA,OAAO,aAAa,cAAc,UAAU,MAAM;EAClD,IAAI,OAAO,QAAQ,MAAM,MAAM,EAAE,SAAS,UAAU,KAAK,OAAO,eAAe,QAC3E,OAAO,aAAa;CAE5B,OACK,IAAI,MAAM,SAAS,SACpB,MAAM,IAAI,MAAM,cAAc,MAAM,KAAK,IAAI,MAAM,aAAa,eAAe;MAE9E,IAAI,MAAM,SAAS,mBAAmB;EACvC,MAAM,QAAQ,MAAM,UAAU;EAC9B,MAAM,UAAU,MAAM,UAAU;EAChC,MAAM,MAAM,QACN,GAAG,MAAM,QAAQ,UAAU,IAAI,MAAM,WAAW,iBAChD,SAAS,SACL,eAAe,QAAQ,WACvB;EACV,MAAM,IAAI,MAAM,GAAG;CACvB;AAER;AACA,SAAS,cAAc,QAAQ;CAC3B,IAAI,CAAC,QACD,OAAO;CACX,QAAQ,QAAR;EACI,KAAK,aACD,OAAO;EACX,KAAK,cACD,OAAO;EACX,KAAK;EACL,KAAK,aACD,OAAO;EAEX,KAAK;EACL,KAAK,UACD,OAAO;EACX,SAEI,MAAM,IAAI,MAAM,0BAA0BA,QAAa;CAE/D;AACJ"}
1
+ {"version":3,"file":"openai-responses-shared-DOajVKFM.mjs","names":["_exhaustive"],"sources":["../../../node_modules/.pnpm/@earendil-works+pi-ai@0.75.4_@modelcontextprotocol+sdk@1.29.0_zod@4.4.3__ws@8.20.1_zod@4.4.3/node_modules/@earendil-works/pi-ai/dist/providers/openai-responses-shared.js"],"sourcesContent":["import { calculateCost } from \"../models.js\";\nimport { shortHash } from \"../utils/hash.js\";\nimport { parseStreamingJson } from \"../utils/json-parse.js\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.js\";\nimport { transformMessages } from \"./transform-messages.js\";\n// =============================================================================\n// Utilities\n// =============================================================================\nfunction encodeTextSignatureV1(id, phase) {\n const payload = { v: 1, id };\n if (phase)\n payload.phase = phase;\n return JSON.stringify(payload);\n}\nfunction parseTextSignature(signature) {\n if (!signature)\n return undefined;\n if (signature.startsWith(\"{\")) {\n try {\n const parsed = JSON.parse(signature);\n if (parsed.v === 1 && typeof parsed.id === \"string\") {\n if (parsed.phase === \"commentary\" || parsed.phase === \"final_answer\") {\n return { id: parsed.id, phase: parsed.phase };\n }\n return { id: parsed.id };\n }\n }\n catch {\n // Fall through to legacy plain-string handling.\n }\n }\n return { id: signature };\n}\n// =============================================================================\n// Message conversion\n// =============================================================================\nexport function convertResponsesMessages(model, context, allowedToolCallProviders, options) {\n const messages = [];\n const normalizeIdPart = (part) => {\n const sanitized = part.replace(/[^a-zA-Z0-9_-]/g, \"_\");\n const normalized = sanitized.length > 64 ? sanitized.slice(0, 64) : sanitized;\n return normalized.replace(/_+$/, \"\");\n };\n const buildForeignResponsesItemId = (itemId) => {\n const normalized = `fc_${shortHash(itemId)}`;\n return normalized.length > 64 ? normalized.slice(0, 64) : normalized;\n };\n const normalizeToolCallId = (id, _targetModel, source) => {\n if (!allowedToolCallProviders.has(model.provider))\n return normalizeIdPart(id);\n if (!id.includes(\"|\"))\n return normalizeIdPart(id);\n const [callId, itemId] = id.split(\"|\");\n const normalizedCallId = normalizeIdPart(callId);\n const isForeignToolCall = source.provider !== model.provider || source.api !== model.api;\n let normalizedItemId = isForeignToolCall ? buildForeignResponsesItemId(itemId) : normalizeIdPart(itemId);\n // OpenAI Responses API requires item id to start with \"fc\"\n if (!normalizedItemId.startsWith(\"fc_\")) {\n normalizedItemId = normalizeIdPart(`fc_${normalizedItemId}`);\n }\n return `${normalizedCallId}|${normalizedItemId}`;\n };\n const transformedMessages = transformMessages(context.messages, model, normalizeToolCallId);\n const includeSystemPrompt = options?.includeSystemPrompt ?? true;\n if (includeSystemPrompt && context.systemPrompt) {\n const role = model.reasoning ? \"developer\" : \"system\";\n messages.push({\n role,\n content: sanitizeSurrogates(context.systemPrompt),\n });\n }\n let msgIndex = 0;\n for (const msg of transformedMessages) {\n if (msg.role === \"user\") {\n if (typeof msg.content === \"string\") {\n messages.push({\n role: \"user\",\n content: [{ type: \"input_text\", text: sanitizeSurrogates(msg.content) }],\n });\n }\n else {\n const content = msg.content.map((item) => {\n if (item.type === \"text\") {\n return {\n type: \"input_text\",\n text: sanitizeSurrogates(item.text),\n };\n }\n return {\n type: \"input_image\",\n detail: \"auto\",\n image_url: `data:${item.mimeType};base64,${item.data}`,\n };\n });\n if (content.length === 0)\n continue;\n messages.push({\n role: \"user\",\n content,\n });\n }\n }\n else if (msg.role === \"assistant\") {\n const output = [];\n const assistantMsg = msg;\n const isDifferentModel = assistantMsg.model !== model.id &&\n assistantMsg.provider === model.provider &&\n assistantMsg.api === model.api;\n for (const block of msg.content) {\n if (block.type === \"thinking\") {\n if (block.thinkingSignature) {\n const reasoningItem = JSON.parse(block.thinkingSignature);\n output.push(reasoningItem);\n }\n }\n else if (block.type === \"text\") {\n const textBlock = block;\n const parsedSignature = parseTextSignature(textBlock.textSignature);\n // OpenAI requires id to be max 64 characters\n let msgId = parsedSignature?.id;\n if (!msgId) {\n msgId = `msg_${msgIndex}`;\n }\n else if (msgId.length > 64) {\n msgId = `msg_${shortHash(msgId)}`;\n }\n output.push({\n type: \"message\",\n role: \"assistant\",\n content: [{ type: \"output_text\", text: sanitizeSurrogates(textBlock.text), annotations: [] }],\n status: \"completed\",\n id: msgId,\n phase: parsedSignature?.phase,\n });\n }\n else if (block.type === \"toolCall\") {\n const toolCall = block;\n const [callId, itemIdRaw] = toolCall.id.split(\"|\");\n let itemId = itemIdRaw;\n // For different-model messages, set id to undefined to avoid pairing validation.\n // OpenAI tracks which fc_xxx IDs were paired with rs_xxx reasoning items.\n // By omitting the id, we avoid triggering that validation (like cross-provider does).\n if (isDifferentModel && itemId?.startsWith(\"fc_\")) {\n itemId = undefined;\n }\n output.push({\n type: \"function_call\",\n id: itemId,\n call_id: callId,\n name: toolCall.name,\n arguments: JSON.stringify(toolCall.arguments),\n });\n }\n }\n if (output.length === 0)\n continue;\n messages.push(...output);\n }\n else if (msg.role === \"toolResult\") {\n const textResult = msg.content\n .filter((c) => c.type === \"text\")\n .map((c) => c.text)\n .join(\"\\n\");\n const hasImages = msg.content.some((c) => c.type === \"image\");\n const hasText = textResult.length > 0;\n const [callId] = msg.toolCallId.split(\"|\");\n let output;\n if (hasImages && model.input.includes(\"image\")) {\n const contentParts = [];\n if (hasText) {\n contentParts.push({\n type: \"input_text\",\n text: sanitizeSurrogates(textResult),\n });\n }\n for (const block of msg.content) {\n if (block.type === \"image\") {\n contentParts.push({\n type: \"input_image\",\n detail: \"auto\",\n image_url: `data:${block.mimeType};base64,${block.data}`,\n });\n }\n }\n output = contentParts;\n }\n else {\n output = sanitizeSurrogates(hasText ? textResult : \"(see attached image)\");\n }\n messages.push({\n type: \"function_call_output\",\n call_id: callId,\n output,\n });\n }\n msgIndex++;\n }\n return messages;\n}\n// =============================================================================\n// Tool conversion\n// =============================================================================\nexport function convertResponsesTools(tools, options) {\n const strict = options?.strict === undefined ? false : options.strict;\n return tools.map((tool) => ({\n type: \"function\",\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters, // TypeBox already generates JSON Schema\n strict,\n }));\n}\n// =============================================================================\n// Stream processing\n// =============================================================================\nexport async function processResponsesStream(openaiStream, output, stream, model, options) {\n let currentItem = null;\n let currentBlock = null;\n const blocks = output.content;\n const blockIndex = () => blocks.length - 1;\n for await (const event of openaiStream) {\n if (event.type === \"response.created\") {\n output.responseId = event.response.id;\n }\n else if (event.type === \"response.output_item.added\") {\n const item = event.item;\n if (item.type === \"reasoning\") {\n currentItem = item;\n currentBlock = { type: \"thinking\", thinking: \"\" };\n output.content.push(currentBlock);\n stream.push({ type: \"thinking_start\", contentIndex: blockIndex(), partial: output });\n }\n else if (item.type === \"message\") {\n currentItem = item;\n currentBlock = { type: \"text\", text: \"\" };\n output.content.push(currentBlock);\n stream.push({ type: \"text_start\", contentIndex: blockIndex(), partial: output });\n }\n else if (item.type === \"function_call\") {\n currentItem = item;\n currentBlock = {\n type: \"toolCall\",\n id: `${item.call_id}|${item.id}`,\n name: item.name,\n arguments: {},\n partialJson: item.arguments || \"\",\n };\n output.content.push(currentBlock);\n stream.push({ type: \"toolcall_start\", contentIndex: blockIndex(), partial: output });\n }\n }\n else if (event.type === \"response.reasoning_summary_part.added\") {\n if (currentItem && currentItem.type === \"reasoning\") {\n currentItem.summary = currentItem.summary || [];\n currentItem.summary.push(event.part);\n }\n }\n else if (event.type === \"response.reasoning_summary_text.delta\") {\n if (currentItem?.type === \"reasoning\" && currentBlock?.type === \"thinking\") {\n currentItem.summary = currentItem.summary || [];\n const lastPart = currentItem.summary[currentItem.summary.length - 1];\n if (lastPart) {\n currentBlock.thinking += event.delta;\n lastPart.text += event.delta;\n stream.push({\n type: \"thinking_delta\",\n contentIndex: blockIndex(),\n delta: event.delta,\n partial: output,\n });\n }\n }\n }\n else if (event.type === \"response.reasoning_summary_part.done\") {\n if (currentItem?.type === \"reasoning\" && currentBlock?.type === \"thinking\") {\n currentItem.summary = currentItem.summary || [];\n const lastPart = currentItem.summary[currentItem.summary.length - 1];\n if (lastPart) {\n currentBlock.thinking += \"\\n\\n\";\n lastPart.text += \"\\n\\n\";\n stream.push({\n type: \"thinking_delta\",\n contentIndex: blockIndex(),\n delta: \"\\n\\n\",\n partial: output,\n });\n }\n }\n }\n else if (event.type === \"response.reasoning_text.delta\") {\n if (currentItem?.type === \"reasoning\" && currentBlock?.type === \"thinking\") {\n currentBlock.thinking += event.delta;\n stream.push({\n type: \"thinking_delta\",\n contentIndex: blockIndex(),\n delta: event.delta,\n partial: output,\n });\n }\n }\n else if (event.type === \"response.content_part.added\") {\n if (currentItem?.type === \"message\") {\n currentItem.content = currentItem.content || [];\n // Filter out ReasoningText, only accept output_text and refusal\n if (event.part.type === \"output_text\" || event.part.type === \"refusal\") {\n currentItem.content.push(event.part);\n }\n }\n }\n else if (event.type === \"response.output_text.delta\") {\n if (currentItem?.type === \"message\" && currentBlock?.type === \"text\") {\n if (!currentItem.content || currentItem.content.length === 0) {\n continue;\n }\n const lastPart = currentItem.content[currentItem.content.length - 1];\n if (lastPart?.type === \"output_text\") {\n currentBlock.text += event.delta;\n lastPart.text += event.delta;\n stream.push({\n type: \"text_delta\",\n contentIndex: blockIndex(),\n delta: event.delta,\n partial: output,\n });\n }\n }\n }\n else if (event.type === \"response.refusal.delta\") {\n if (currentItem?.type === \"message\" && currentBlock?.type === \"text\") {\n if (!currentItem.content || currentItem.content.length === 0) {\n continue;\n }\n const lastPart = currentItem.content[currentItem.content.length - 1];\n if (lastPart?.type === \"refusal\") {\n currentBlock.text += event.delta;\n lastPart.refusal += event.delta;\n stream.push({\n type: \"text_delta\",\n contentIndex: blockIndex(),\n delta: event.delta,\n partial: output,\n });\n }\n }\n }\n else if (event.type === \"response.function_call_arguments.delta\") {\n if (currentItem?.type === \"function_call\" && currentBlock?.type === \"toolCall\") {\n currentBlock.partialJson += event.delta;\n currentBlock.arguments = parseStreamingJson(currentBlock.partialJson);\n stream.push({\n type: \"toolcall_delta\",\n contentIndex: blockIndex(),\n delta: event.delta,\n partial: output,\n });\n }\n }\n else if (event.type === \"response.function_call_arguments.done\") {\n if (currentItem?.type === \"function_call\" && currentBlock?.type === \"toolCall\") {\n const previousPartialJson = currentBlock.partialJson;\n currentBlock.partialJson = event.arguments;\n currentBlock.arguments = parseStreamingJson(currentBlock.partialJson);\n if (event.arguments.startsWith(previousPartialJson)) {\n const delta = event.arguments.slice(previousPartialJson.length);\n if (delta.length > 0) {\n stream.push({\n type: \"toolcall_delta\",\n contentIndex: blockIndex(),\n delta,\n partial: output,\n });\n }\n }\n }\n }\n else if (event.type === \"response.output_item.done\") {\n const item = event.item;\n if (item.type === \"reasoning\" && currentBlock?.type === \"thinking\") {\n const summaryText = item.summary?.map((s) => s.text).join(\"\\n\\n\") || \"\";\n const contentText = item.content?.map((c) => c.text).join(\"\\n\\n\") || \"\";\n currentBlock.thinking = summaryText || contentText || currentBlock.thinking;\n currentBlock.thinkingSignature = JSON.stringify(item);\n stream.push({\n type: \"thinking_end\",\n contentIndex: blockIndex(),\n content: currentBlock.thinking,\n partial: output,\n });\n currentBlock = null;\n }\n else if (item.type === \"message\" && currentBlock?.type === \"text\") {\n currentBlock.text = item.content.map((c) => (c.type === \"output_text\" ? c.text : c.refusal)).join(\"\");\n currentBlock.textSignature = encodeTextSignatureV1(item.id, item.phase ?? undefined);\n stream.push({\n type: \"text_end\",\n contentIndex: blockIndex(),\n content: currentBlock.text,\n partial: output,\n });\n currentBlock = null;\n }\n else if (item.type === \"function_call\") {\n const args = currentBlock?.type === \"toolCall\" && currentBlock.partialJson\n ? parseStreamingJson(currentBlock.partialJson)\n : parseStreamingJson(item.arguments || \"{}\");\n let toolCall;\n if (currentBlock?.type === \"toolCall\") {\n // Finalize in-place and strip the scratch buffer so replay only\n // carries parsed arguments.\n currentBlock.arguments = args;\n delete currentBlock.partialJson;\n toolCall = currentBlock;\n }\n else {\n toolCall = {\n type: \"toolCall\",\n id: `${item.call_id}|${item.id}`,\n name: item.name,\n arguments: args,\n };\n }\n currentBlock = null;\n stream.push({ type: \"toolcall_end\", contentIndex: blockIndex(), toolCall, partial: output });\n }\n }\n else if (event.type === \"response.completed\") {\n const response = event.response;\n if (response?.id) {\n output.responseId = response.id;\n }\n if (response?.usage) {\n const cachedTokens = response.usage.input_tokens_details?.cached_tokens || 0;\n output.usage = {\n // OpenAI includes cached tokens in input_tokens, so subtract to get non-cached input\n input: (response.usage.input_tokens || 0) - cachedTokens,\n output: response.usage.output_tokens || 0,\n cacheRead: cachedTokens,\n cacheWrite: 0,\n totalTokens: response.usage.total_tokens || 0,\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n };\n }\n calculateCost(model, output.usage);\n if (options?.applyServiceTierPricing) {\n const serviceTier = options.resolveServiceTier\n ? options.resolveServiceTier(response?.service_tier, options.serviceTier)\n : (response?.service_tier ?? options.serviceTier);\n options.applyServiceTierPricing(output.usage, serviceTier);\n }\n // Map status to stop reason\n output.stopReason = mapStopReason(response?.status);\n if (output.content.some((b) => b.type === \"toolCall\") && output.stopReason === \"stop\") {\n output.stopReason = \"toolUse\";\n }\n }\n else if (event.type === \"error\") {\n throw new Error(`Error Code ${event.code}: ${event.message}` || \"Unknown error\");\n }\n else if (event.type === \"response.failed\") {\n const error = event.response?.error;\n const details = event.response?.incomplete_details;\n const msg = error\n ? `${error.code || \"unknown\"}: ${error.message || \"no message\"}`\n : details?.reason\n ? `incomplete: ${details.reason}`\n : \"Unknown error (no error details in response)\";\n throw new Error(msg);\n }\n }\n}\nfunction mapStopReason(status) {\n if (!status)\n return \"stop\";\n switch (status) {\n case \"completed\":\n return \"stop\";\n case \"incomplete\":\n return \"length\";\n case \"failed\":\n case \"cancelled\":\n return \"error\";\n // These two are wonky ...\n case \"in_progress\":\n case \"queued\":\n return \"stop\";\n default: {\n const _exhaustive = status;\n throw new Error(`Unhandled stop reason: ${_exhaustive}`);\n }\n }\n}\n//# sourceMappingURL=openai-responses-shared.js.map"],"x_google_ignoreList":[0],"mappings":";;;;;;;AAQA,SAAS,sBAAsB,IAAI,OAAO;CACtC,MAAM,UAAU;EAAE,GAAG;EAAG;CAAG;CAC3B,IAAI,OACA,QAAQ,QAAQ;CACpB,OAAO,KAAK,UAAU,OAAO;AACjC;AACA,SAAS,mBAAmB,WAAW;CACnC,IAAI,CAAC,WACD,OAAO,KAAA;CACX,IAAI,UAAU,WAAW,GAAG,GACxB,IAAI;EACA,MAAM,SAAS,KAAK,MAAM,SAAS;EACnC,IAAI,OAAO,MAAM,KAAK,OAAO,OAAO,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mjs";
3
3
  import { t as headersToRecord } from "./headers-CFU1lxB-.mjs";
4
4
  import { t as sanitizeSurrogates } from "./sanitize-unicode-DH1T1t81.mjs";
5
5
  import { n as OpenAI } from "./openai-DtgBmu_h.mjs";
@@ -118,4 +118,4 @@ function parseUsage(rawUsage, model) {
118
118
  //#endregion
119
119
  export { generateImagesOpenRouter };
120
120
 
121
- //# sourceMappingURL=openrouter-Cq37VS4X.mjs.map
121
+ //# sourceMappingURL=openrouter-BD82J9ov.mjs.map