pi2dsh 0.3.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/README.md +31 -11
  2. package/README.zh.md +31 -11
  3. package/dist/all-Rt4K68QA.mjs +28512 -0
  4. package/dist/all-Rt4K68QA.mjs.map +1 -0
  5. package/dist/anthropic-messages-Beym0_aC.mjs +6438 -0
  6. package/dist/anthropic-messages-Beym0_aC.mjs.map +1 -0
  7. package/dist/azure-openai-responses-cHqZTgLD.mjs +209 -0
  8. package/dist/azure-openai-responses-cHqZTgLD.mjs.map +1 -0
  9. package/dist/{build-DsGYAgiT.mjs → build-BG7p2Lbr.mjs} +2 -2
  10. package/dist/{build-DsGYAgiT.mjs.map → build-BG7p2Lbr.mjs.map} +1 -1
  11. package/dist/cli.mjs +1 -1
  12. package/dist/compat/pi-ai.d.mts +25 -3
  13. package/dist/compat/pi-ai.d.mts.map +1 -1
  14. package/dist/compat/pi-ai.mjs +3 -2919
  15. package/dist/compat/pi-coding-agent.d.mts +12 -1
  16. package/dist/compat/pi-coding-agent.d.mts.map +1 -1
  17. package/dist/compat/pi-coding-agent.mjs +2 -2
  18. package/dist/credentials-oauth.d.mts +27 -0
  19. package/dist/credentials-oauth.d.mts.map +1 -0
  20. package/dist/credentials-oauth.mjs +91 -0
  21. package/dist/credentials-oauth.mjs.map +1 -0
  22. package/dist/deferred-tools-BD4g5QUx.mjs +32 -0
  23. package/dist/deferred-tools-BD4g5QUx.mjs.map +1 -0
  24. package/dist/diagnostics-CJye1UFh.mjs +99 -0
  25. package/dist/diagnostics-CJye1UFh.mjs.map +1 -0
  26. package/dist/dist-IQKOgQyt.mjs +10035 -0
  27. package/dist/dist-IQKOgQyt.mjs.map +1 -0
  28. package/dist/dist-QBBA-dL_.mjs +1246 -0
  29. package/dist/dist-QBBA-dL_.mjs.map +1 -0
  30. package/dist/error-body-DKA3lknR.mjs +104 -0
  31. package/dist/error-body-DKA3lknR.mjs.map +1 -0
  32. package/dist/github-copilot-headers-CZo2QHrt.mjs +25 -0
  33. package/dist/github-copilot-headers-CZo2QHrt.mjs.map +1 -0
  34. package/dist/google-generative-ai-B7OZs5lu.mjs +358 -0
  35. package/dist/google-generative-ai-B7OZs5lu.mjs.map +1 -0
  36. package/dist/google-shared-CRsAUItF.mjs +29042 -0
  37. package/dist/google-shared-CRsAUItF.mjs.map +1 -0
  38. package/dist/google-vertex-DmdaHQtB.mjs +402 -0
  39. package/dist/google-vertex-DmdaHQtB.mjs.map +1 -0
  40. package/dist/hash-Dbggamac.mjs +19 -0
  41. package/dist/hash-Dbggamac.mjs.map +1 -0
  42. package/dist/headers-CPzZhJQn.mjs +17 -0
  43. package/dist/headers-CPzZhJQn.mjs.map +1 -0
  44. package/dist/host.d.mts.map +1 -1
  45. package/dist/host.mjs +15 -3
  46. package/dist/host.mjs.map +1 -1
  47. package/dist/images-models-DJtHo9Rp.mjs +1068 -0
  48. package/dist/images-models-DJtHo9Rp.mjs.map +1 -0
  49. package/dist/index.d.mts.map +1 -1
  50. package/dist/index.mjs +1 -1
  51. package/dist/json-parse-CFyFZSLJ.mjs +384 -0
  52. package/dist/json-parse-CFyFZSLJ.mjs.map +1 -0
  53. package/dist/{mcp-config-gqg7GJEE.mjs → mcp-config-D2B3kv-Z.mjs} +34 -16
  54. package/dist/mcp-config-D2B3kv-Z.mjs.map +1 -0
  55. package/dist/mistral-conversations-HHZCcFv_.mjs +42007 -0
  56. package/dist/mistral-conversations-HHZCcFv_.mjs.map +1 -0
  57. package/dist/multipart-parser-CIa5BbwO.mjs +301 -0
  58. package/dist/multipart-parser-CIa5BbwO.mjs.map +1 -0
  59. package/dist/oauth-bridge-C6fL1qSv.mjs +375 -0
  60. package/dist/oauth-bridge-C6fL1qSv.mjs.map +1 -0
  61. package/dist/openai-DkzRh5_G.mjs +6732 -0
  62. package/dist/openai-DkzRh5_G.mjs.map +1 -0
  63. package/dist/openai-codex-responses-vmovNu-q.mjs +1169 -0
  64. package/dist/openai-codex-responses-vmovNu-q.mjs.map +1 -0
  65. package/dist/openai-completions-fXHhRolF.mjs +947 -0
  66. package/dist/openai-completions-fXHhRolF.mjs.map +1 -0
  67. package/dist/openai-prompt-cache-BDWtZRKh.mjs +11 -0
  68. package/dist/openai-prompt-cache-BDWtZRKh.mjs.map +1 -0
  69. package/dist/openai-responses-DKdCYf3h.mjs +247 -0
  70. package/dist/openai-responses-DKdCYf3h.mjs.map +1 -0
  71. package/dist/openai-responses-shared-D0Jq7yVP.mjs +572 -0
  72. package/dist/openai-responses-shared-D0Jq7yVP.mjs.map +1 -0
  73. package/dist/openrouter-images-fG3Aj6M4.mjs +127 -0
  74. package/dist/openrouter-images-fG3Aj6M4.mjs.map +1 -0
  75. package/dist/otel-BQSQRBLF.mjs +24935 -0
  76. package/dist/otel-BQSQRBLF.mjs.map +1 -0
  77. package/dist/pi-ai-DhYGgq4Y.mjs +2984 -0
  78. package/dist/pi-ai-DhYGgq4Y.mjs.map +1 -0
  79. package/dist/{pi-coding-agent-Z1hTs61i.mjs → pi-coding-agent-fPHwKP4d.mjs} +27 -3
  80. package/dist/{pi-coding-agent-Z1hTs61i.mjs.map → pi-coding-agent-fPHwKP4d.mjs.map} +1 -1
  81. package/dist/pi-messages-CV-Ts8An.mjs +306 -0
  82. package/dist/pi-messages-CV-Ts8An.mjs.map +1 -0
  83. package/dist/provider-env-C72pF4vP.mjs +40 -0
  84. package/dist/provider-env-C72pF4vP.mjs.map +1 -0
  85. package/dist/provider-retry-Cw6YJ4cr.mjs +80 -0
  86. package/dist/provider-retry-Cw6YJ4cr.mjs.map +1 -0
  87. package/dist/rolldown-runtime-CTfmNlz1.mjs +44 -0
  88. package/dist/{runtime-oLd2EInK.mjs → runtime-B9R7bDWT.mjs} +838 -345
  89. package/dist/runtime-B9R7bDWT.mjs.map +1 -0
  90. package/dist/runtime.d.mts.map +1 -1
  91. package/dist/runtime.mjs +1 -1
  92. package/dist/sanitize-unicode-wLA11KvZ.mjs +29 -0
  93. package/dist/sanitize-unicode-wLA11KvZ.mjs.map +1 -0
  94. package/dist/src-C3WBfOks.mjs +5031 -0
  95. package/dist/src-C3WBfOks.mjs.map +1 -0
  96. package/dist/transform-messages-DGq9mvhA.mjs +379 -0
  97. package/dist/transform-messages-DGq9mvhA.mjs.map +1 -0
  98. package/dist/uuid-DtFT7tOE.mjs +65 -0
  99. package/dist/uuid-DtFT7tOE.mjs.map +1 -0
  100. package/package.json +11 -1
  101. package/dist/compat/pi-ai.mjs.map +0 -1
  102. package/dist/mcp-config-gqg7GJEE.mjs.map +0 -1
  103. package/dist/rolldown-runtime-D-uZhY3_.mjs +0 -16
  104. package/dist/runtime-oLd2EInK.mjs.map +0 -1
@@ -0,0 +1,572 @@
1
+
2
+ import { a as calculateCost } from "./images-models-DJtHo9Rp.mjs";
3
+ import { n as parseStreamingJson } from "./json-parse-CFyFZSLJ.mjs";
4
+ import { t as sanitizeSurrogates } from "./sanitize-unicode-wLA11KvZ.mjs";
5
+ import { d as resolveJsonSchemaStrictSampling, l as getGrammarToolInput, s as appendGrammarToolInputJsonDelta, t as transformMessages, u as resolveGrammarConstrainedSampling } from "./transform-messages-DGq9mvhA.mjs";
6
+ import { t as shortHash } from "./hash-Dbggamac.mjs";
7
+ //#region node_modules/.pnpm/@earendil-works+pi-ai@0.84.1_ws@8.21.3_zod@4.4.3/node_modules/@earendil-works/pi-ai/dist/api/openai-responses-shared.js
8
+ function encodeTextSignatureV1(id, phase) {
9
+ const payload = {
10
+ v: 1,
11
+ id
12
+ };
13
+ if (phase) payload.phase = phase;
14
+ return JSON.stringify(payload);
15
+ }
16
+ function parseTextSignature(signature) {
17
+ if (!signature) return void 0;
18
+ if (signature.startsWith("{")) try {
19
+ const parsed = JSON.parse(signature);
20
+ if (parsed.v === 1 && typeof parsed.id === "string") {
21
+ if (parsed.phase === "commentary" || parsed.phase === "final_answer") return {
22
+ id: parsed.id,
23
+ phase: parsed.phase
24
+ };
25
+ return { id: parsed.id };
26
+ }
27
+ } catch {}
28
+ return { id: signature };
29
+ }
30
+ function convertToolResultOutput(model, content) {
31
+ const textResult = content.filter((c) => c.type === "text").map((c) => c.text).join("\n");
32
+ const images = content.filter((c) => c.type === "image");
33
+ const hasText = textResult.length > 0;
34
+ if (images.length === 0 || !model.input.includes("image")) return sanitizeSurrogates(hasText ? textResult : images.length > 0 ? "(see attached image)" : "(no tool output)");
35
+ const output = [];
36
+ if (hasText) output.push({
37
+ type: "input_text",
38
+ text: sanitizeSurrogates(textResult)
39
+ });
40
+ for (const image of images) output.push({
41
+ type: "input_image",
42
+ detail: "auto",
43
+ image_url: `data:${image.mimeType};base64,${image.data}`
44
+ });
45
+ return output;
46
+ }
47
+ function convertResponsesMessages(model, context, allowedToolCallProviders, options) {
48
+ const messages = [];
49
+ const loadedToolNames = /* @__PURE__ */ new Set();
50
+ const normalizeIdPart = (part) => {
51
+ const sanitized = part.replace(/[^a-zA-Z0-9_-]/g, "_");
52
+ return (sanitized.length > 64 ? sanitized.slice(0, 64) : sanitized).replace(/_+$/, "");
53
+ };
54
+ const buildForeignResponsesItemId = (itemId) => {
55
+ const normalized = `fc_${shortHash(itemId)}`;
56
+ return normalized.length > 64 ? normalized.slice(0, 64) : normalized;
57
+ };
58
+ const normalizeToolCallId = (id, _targetModel, source) => {
59
+ if (!allowedToolCallProviders.has(model.provider)) return normalizeIdPart(id);
60
+ if (!id.includes("|")) return normalizeIdPart(id);
61
+ const [callId, itemId] = id.split("|");
62
+ const normalizedCallId = normalizeIdPart(callId);
63
+ let normalizedItemId = source.provider !== model.provider || source.api !== model.api ? buildForeignResponsesItemId(itemId) : normalizeIdPart(itemId);
64
+ if (!normalizedItemId.startsWith("fc_")) normalizedItemId = normalizeIdPart(`fc_${normalizedItemId}`);
65
+ return `${normalizedCallId}|${normalizedItemId}`;
66
+ };
67
+ const transformedMessages = transformMessages(context.messages, model, normalizeToolCallId);
68
+ if ((options?.includeSystemPrompt ?? true) && context.systemPrompt) {
69
+ const compat = model.compat;
70
+ const role = model.reasoning && compat?.supportsDeveloperRole !== false ? "developer" : "system";
71
+ messages.push({
72
+ role,
73
+ content: sanitizeSurrogates(context.systemPrompt)
74
+ });
75
+ }
76
+ let msgIndex = 0;
77
+ for (const msg of transformedMessages) {
78
+ if (msg.role === "user") {
79
+ if (typeof msg.content === "string") messages.push({
80
+ role: "user",
81
+ content: [{
82
+ type: "input_text",
83
+ text: sanitizeSurrogates(msg.content)
84
+ }]
85
+ });
86
+ else {
87
+ const content = msg.content.map((item) => {
88
+ if (item.type === "text") return {
89
+ type: "input_text",
90
+ text: sanitizeSurrogates(item.text)
91
+ };
92
+ return {
93
+ type: "input_image",
94
+ detail: "auto",
95
+ image_url: `data:${item.mimeType};base64,${item.data}`
96
+ };
97
+ });
98
+ if (content.length === 0) continue;
99
+ messages.push({
100
+ role: "user",
101
+ content
102
+ });
103
+ }
104
+ } else if (msg.role === "assistant") {
105
+ const output = [];
106
+ const assistantMsg = msg;
107
+ const isDifferentModel = assistantMsg.model !== model.id && assistantMsg.provider === model.provider && assistantMsg.api === model.api;
108
+ let textBlockIndex = 0;
109
+ for (const block of msg.content) if (block.type === "thinking") {
110
+ if (block.thinkingSignature) {
111
+ const reasoningItem = JSON.parse(block.thinkingSignature);
112
+ output.push(reasoningItem);
113
+ }
114
+ } else if (block.type === "text") {
115
+ const textBlock = block;
116
+ const parsedSignature = parseTextSignature(textBlock.textSignature);
117
+ const fallbackMessageId = textBlockIndex === 0 ? `msg_pi_${msgIndex}` : `msg_pi_${msgIndex}_${textBlockIndex}`;
118
+ textBlockIndex++;
119
+ let msgId = parsedSignature?.id;
120
+ if (!msgId) msgId = fallbackMessageId;
121
+ else if (msgId.length > 64) msgId = `msg_${shortHash(msgId)}`;
122
+ output.push({
123
+ type: "message",
124
+ role: "assistant",
125
+ content: [{
126
+ type: "output_text",
127
+ text: sanitizeSurrogates(textBlock.text),
128
+ annotations: []
129
+ }],
130
+ status: "completed",
131
+ id: msgId,
132
+ phase: parsedSignature?.phase
133
+ });
134
+ } else if (block.type === "toolCall") {
135
+ const toolCall = block;
136
+ const [callId, itemIdRaw] = toolCall.id.split("|");
137
+ const customInputProperty = options?.grammarToolInputProperties?.get(toolCall.name);
138
+ let itemId = itemIdRaw;
139
+ if (isDifferentModel && itemId?.startsWith("fc_") || customInputProperty === void 0 && !itemId?.startsWith("fc_")) itemId = void 0;
140
+ if (customInputProperty !== void 0) output.push({
141
+ type: "custom_tool_call",
142
+ id: itemId,
143
+ call_id: callId,
144
+ name: toolCall.name,
145
+ input: sanitizeSurrogates(getGrammarToolInput(toolCall.name, toolCall.arguments, customInputProperty))
146
+ });
147
+ else output.push({
148
+ type: "function_call",
149
+ id: itemId,
150
+ call_id: callId,
151
+ name: toolCall.name,
152
+ arguments: JSON.stringify(toolCall.arguments)
153
+ });
154
+ }
155
+ if (output.length === 0) continue;
156
+ messages.push(...output);
157
+ } else if (msg.role === "toolResult") {
158
+ const [callId] = msg.toolCallId.split("|");
159
+ const output = convertToolResultOutput(model, msg.content);
160
+ if (options?.grammarToolInputProperties?.has(msg.toolName)) messages.push({
161
+ type: "custom_tool_call_output",
162
+ call_id: callId,
163
+ output
164
+ });
165
+ else messages.push({
166
+ type: "function_call_output",
167
+ call_id: callId,
168
+ output
169
+ });
170
+ const deferredTools = [];
171
+ for (const name of msg.addedToolNames ?? []) {
172
+ const tool = options?.deferredTools?.get(name);
173
+ if (!tool || loadedToolNames.has(name)) continue;
174
+ loadedToolNames.add(name);
175
+ deferredTools.push(tool);
176
+ }
177
+ if (deferredTools.length > 0) {
178
+ const names = deferredTools.map((tool) => tool.name);
179
+ const searchCallId = `pi_tool_load_${shortHash(`${msg.toolCallId}:${names.join(",")}`)}`;
180
+ messages.push({
181
+ type: "tool_search_call",
182
+ call_id: searchCallId,
183
+ execution: "client",
184
+ status: "completed",
185
+ arguments: {
186
+ query: names.join(" "),
187
+ limit: names.length
188
+ }
189
+ });
190
+ messages.push({
191
+ type: "tool_search_output",
192
+ call_id: searchCallId,
193
+ execution: "client",
194
+ status: "completed",
195
+ tools: convertResponsesTools(deferredTools, {
196
+ ...options?.toolOptions,
197
+ deferLoading: true
198
+ })
199
+ });
200
+ }
201
+ }
202
+ msgIndex++;
203
+ }
204
+ return messages;
205
+ }
206
+ function convertResponsesTools(tools, options) {
207
+ const defaultStrict = options?.strict === void 0 ? false : options.strict;
208
+ const supportsStrictMode = options?.supportsStrictMode ?? true;
209
+ const supportsOpenAIGrammarTools = options?.supportsOpenAIGrammarTools ?? false;
210
+ return tools.map((tool) => {
211
+ const grammar = resolveGrammarConstrainedSampling(tool, supportsOpenAIGrammarTools);
212
+ if (grammar) return {
213
+ type: "custom",
214
+ name: tool.name,
215
+ description: tool.description,
216
+ format: {
217
+ type: "grammar",
218
+ syntax: grammar.format,
219
+ definition: grammar.definition
220
+ },
221
+ ...options?.deferLoading ? { defer_loading: true } : {}
222
+ };
223
+ const constrainedStrict = resolveJsonSchemaStrictSampling(tool, supportsStrictMode);
224
+ const functionTool = {
225
+ type: "function",
226
+ name: tool.name,
227
+ description: tool.description,
228
+ parameters: tool.parameters,
229
+ ...options?.deferLoading ? { defer_loading: true } : {}
230
+ };
231
+ if (supportsStrictMode) functionTool.strict = constrainedStrict ?? defaultStrict;
232
+ return functionTool;
233
+ });
234
+ }
235
+ function getCustomToolCallInput(block) {
236
+ const property = block.customInput?.property;
237
+ if (property === void 0) return "";
238
+ const value = block.arguments[property];
239
+ return typeof value === "string" ? value : "";
240
+ }
241
+ function appendCustomToolCallInput(block, nextInput, close) {
242
+ const customInput = block.customInput;
243
+ if (!customInput) return void 0;
244
+ const delta = appendGrammarToolInputJsonDelta(customInput.jsonBuffer, customInput.property, nextInput, close);
245
+ block.arguments = { [customInput.property]: nextInput };
246
+ return delta;
247
+ }
248
+ async function processResponsesStream(openaiStream, output, stream, model, options) {
249
+ let sawTerminalResponseEvent = false;
250
+ const outputSlots = /* @__PURE__ */ new Map();
251
+ const reasoningBlocksById = /* @__PURE__ */ new Map();
252
+ const applyMessagePhaseStopReason = (item) => {
253
+ if (item.type === "message" && item.phase === "final_answer") output.stopReason = "stop";
254
+ };
255
+ const getSlot = (outputIndex, type) => {
256
+ const slot = outputSlots.get(outputIndex);
257
+ return slot?.type === type ? slot : void 0;
258
+ };
259
+ const pushToolCallDelta = (slot, delta) => {
260
+ if (delta === void 0) return;
261
+ stream.push({
262
+ type: "toolcall_delta",
263
+ contentIndex: slot.contentIndex,
264
+ delta,
265
+ partial: output
266
+ });
267
+ };
268
+ const createSlot = (outputIndex, item) => {
269
+ if (item.type === "reasoning") {
270
+ const block = {
271
+ type: "thinking",
272
+ thinking: ""
273
+ };
274
+ output.content.push(block);
275
+ const slot = {
276
+ type: "thinking",
277
+ block,
278
+ contentIndex: output.content.length - 1
279
+ };
280
+ outputSlots.set(outputIndex, slot);
281
+ stream.push({
282
+ type: "thinking_start",
283
+ contentIndex: slot.contentIndex,
284
+ partial: output
285
+ });
286
+ return slot;
287
+ }
288
+ if (item.type === "message") {
289
+ applyMessagePhaseStopReason(item);
290
+ const block = {
291
+ type: "text",
292
+ text: ""
293
+ };
294
+ output.content.push(block);
295
+ const slot = {
296
+ type: "text",
297
+ block,
298
+ contentIndex: output.content.length - 1
299
+ };
300
+ outputSlots.set(outputIndex, slot);
301
+ stream.push({
302
+ type: "text_start",
303
+ contentIndex: slot.contentIndex,
304
+ partial: output
305
+ });
306
+ return slot;
307
+ }
308
+ if (item.type === "function_call") {
309
+ const block = {
310
+ type: "toolCall",
311
+ id: `${item.call_id}|${item.id}`,
312
+ name: item.name,
313
+ arguments: {},
314
+ partialJson: item.arguments || ""
315
+ };
316
+ output.content.push(block);
317
+ const slot = {
318
+ type: "toolCall",
319
+ block,
320
+ contentIndex: output.content.length - 1
321
+ };
322
+ outputSlots.set(outputIndex, slot);
323
+ stream.push({
324
+ type: "toolcall_start",
325
+ contentIndex: slot.contentIndex,
326
+ partial: output
327
+ });
328
+ return slot;
329
+ }
330
+ if (item.type === "custom_tool_call") {
331
+ const inputProperty = options?.grammarToolInputProperties?.get(item.name) ?? "input";
332
+ const input = item.input || "";
333
+ const block = {
334
+ type: "toolCall",
335
+ id: `${item.call_id}|${item.id}`,
336
+ name: item.name,
337
+ arguments: { [inputProperty]: input },
338
+ customInput: {
339
+ property: inputProperty,
340
+ jsonBuffer: {
341
+ input: "",
342
+ started: false,
343
+ closed: false
344
+ }
345
+ }
346
+ };
347
+ output.content.push(block);
348
+ const slot = {
349
+ type: "toolCall",
350
+ block,
351
+ contentIndex: output.content.length - 1
352
+ };
353
+ outputSlots.set(outputIndex, slot);
354
+ stream.push({
355
+ type: "toolcall_start",
356
+ contentIndex: slot.contentIndex,
357
+ partial: output
358
+ });
359
+ return slot;
360
+ }
361
+ };
362
+ const getOrCreateSlot = (outputIndex, item) => {
363
+ return outputSlots.get(outputIndex) ?? createSlot(outputIndex, item);
364
+ };
365
+ const backfillReasoningSignatures = (responseOutput) => {
366
+ for (const item of responseOutput) {
367
+ if (item.type !== "reasoning" || !item.encrypted_content) continue;
368
+ const block = reasoningBlocksById.get(item.id);
369
+ if (!block?.thinkingSignature) continue;
370
+ const storedItem = JSON.parse(block.thinkingSignature);
371
+ if (storedItem.encrypted_content) continue;
372
+ block.thinkingSignature = JSON.stringify({
373
+ ...storedItem,
374
+ encrypted_content: item.encrypted_content
375
+ });
376
+ }
377
+ };
378
+ const finalizeResponse = (response) => {
379
+ sawTerminalResponseEvent = true;
380
+ backfillReasoningSignatures(response.output ?? []);
381
+ if (response?.id) output.responseId = response.id;
382
+ if (response?.usage) {
383
+ const inputDetails = response.usage.input_tokens_details;
384
+ const cachedTokens = inputDetails?.cached_tokens || 0;
385
+ const cacheWriteTokens = inputDetails?.cache_write_tokens || 0;
386
+ output.usage = {
387
+ input: Math.max(0, (response.usage.input_tokens || 0) - cachedTokens - cacheWriteTokens),
388
+ output: response.usage.output_tokens || 0,
389
+ cacheRead: cachedTokens,
390
+ cacheWrite: cacheWriteTokens,
391
+ reasoning: response.usage.output_tokens_details?.reasoning_tokens || 0,
392
+ totalTokens: response.usage.total_tokens || 0,
393
+ cost: {
394
+ input: 0,
395
+ output: 0,
396
+ cacheRead: 0,
397
+ cacheWrite: 0,
398
+ total: 0
399
+ }
400
+ };
401
+ }
402
+ calculateCost(model, output.usage);
403
+ if (options?.applyServiceTierPricing) {
404
+ const serviceTier = options.resolveServiceTier ? options.resolveServiceTier(response?.service_tier, options.serviceTier) : response?.service_tier ?? options.serviceTier;
405
+ options.applyServiceTierPricing(output.usage, serviceTier);
406
+ }
407
+ const status = response?.status;
408
+ const incompleteDetails = response?.incomplete_details;
409
+ const incompleteReason = typeof incompleteDetails?.reason === "string" ? incompleteDetails.reason : void 0;
410
+ output.rawStopReason = incompleteReason ? `${status}.${incompleteReason}` : status;
411
+ const mappedStop = mapStopReason(status, incompleteReason);
412
+ output.stopReason = mappedStop.stopReason;
413
+ output.errorMessage = mappedStop.errorMessage;
414
+ if (output.content.some((b) => b.type === "toolCall") && output.stopReason === "stop") output.stopReason = "toolUse";
415
+ };
416
+ for await (const event of openaiStream) if (event.type === "response.created") output.responseId = event.response.id;
417
+ else if (event.type === "response.output_item.added") createSlot(event.output_index, event.item);
418
+ else if (event.type === "response.reasoning_summary_text.delta") {
419
+ const slot = getSlot(event.output_index, "thinking");
420
+ if (!slot) continue;
421
+ slot.block.thinking += event.delta;
422
+ stream.push({
423
+ type: "thinking_delta",
424
+ contentIndex: slot.contentIndex,
425
+ delta: event.delta,
426
+ partial: output
427
+ });
428
+ } else if (event.type === "response.reasoning_summary_part.done") {
429
+ const slot = getSlot(event.output_index, "thinking");
430
+ if (!slot) continue;
431
+ slot.block.thinking += "\n\n";
432
+ stream.push({
433
+ type: "thinking_delta",
434
+ contentIndex: slot.contentIndex,
435
+ delta: "\n\n",
436
+ partial: output
437
+ });
438
+ } else if (event.type === "response.reasoning_text.delta") {
439
+ const slot = getSlot(event.output_index, "thinking");
440
+ if (!slot) continue;
441
+ slot.block.thinking += event.delta;
442
+ stream.push({
443
+ type: "thinking_delta",
444
+ contentIndex: slot.contentIndex,
445
+ delta: event.delta,
446
+ partial: output
447
+ });
448
+ } else if (event.type === "response.output_text.delta") {
449
+ const slot = getSlot(event.output_index, "text");
450
+ if (!slot) continue;
451
+ slot.block.text += event.delta;
452
+ stream.push({
453
+ type: "text_delta",
454
+ contentIndex: slot.contentIndex,
455
+ delta: event.delta,
456
+ partial: output
457
+ });
458
+ } else if (event.type === "response.refusal.delta") {
459
+ const slot = getSlot(event.output_index, "text");
460
+ if (!slot) continue;
461
+ slot.block.text += event.delta;
462
+ stream.push({
463
+ type: "text_delta",
464
+ contentIndex: slot.contentIndex,
465
+ delta: event.delta,
466
+ partial: output
467
+ });
468
+ } else if (event.type === "response.function_call_arguments.delta") {
469
+ const slot = getSlot(event.output_index, "toolCall");
470
+ if (!slot || slot.block.partialJson === void 0) continue;
471
+ slot.block.partialJson += event.delta;
472
+ slot.block.arguments = parseStreamingJson(slot.block.partialJson);
473
+ pushToolCallDelta(slot, event.delta);
474
+ } else if (event.type === "response.function_call_arguments.done") {
475
+ const slot = getSlot(event.output_index, "toolCall");
476
+ if (!slot || slot.block.partialJson === void 0) continue;
477
+ const previousPartialJson = slot.block.partialJson;
478
+ slot.block.partialJson = event.arguments;
479
+ slot.block.arguments = parseStreamingJson(slot.block.partialJson);
480
+ if (event.arguments.startsWith(previousPartialJson)) {
481
+ const delta = event.arguments.slice(previousPartialJson.length);
482
+ if (delta.length > 0) pushToolCallDelta(slot, delta);
483
+ }
484
+ } else if (event.type === "response.custom_tool_call_input.delta") {
485
+ const slot = getSlot(event.output_index, "toolCall");
486
+ if (!slot || !slot.block.customInput) continue;
487
+ pushToolCallDelta(slot, appendCustomToolCallInput(slot.block, getCustomToolCallInput(slot.block) + event.delta, false));
488
+ } else if (event.type === "response.custom_tool_call_input.done") {
489
+ const slot = getSlot(event.output_index, "toolCall");
490
+ if (!slot || !slot.block.customInput) continue;
491
+ pushToolCallDelta(slot, appendCustomToolCallInput(slot.block, event.input, true));
492
+ } else if (event.type === "response.output_item.done") {
493
+ const item = event.item;
494
+ applyMessagePhaseStopReason(item);
495
+ const slot = getOrCreateSlot(event.output_index, item);
496
+ if (item.type === "reasoning" && slot?.type === "thinking") {
497
+ const summaryText = item.summary?.map((s) => s.text).join("\n\n") || "";
498
+ const contentText = item.content?.map((c) => c.text).join("\n\n") || "";
499
+ slot.block.thinking = summaryText || contentText || slot.block.thinking;
500
+ slot.block.thinkingSignature = JSON.stringify(item);
501
+ reasoningBlocksById.set(item.id, slot.block);
502
+ stream.push({
503
+ type: "thinking_end",
504
+ contentIndex: slot.contentIndex,
505
+ content: slot.block.thinking,
506
+ partial: output
507
+ });
508
+ outputSlots.delete(event.output_index);
509
+ } else if (item.type === "message" && slot?.type === "text") {
510
+ slot.block.text = item.content?.map((c) => c.type === "output_text" ? c.text : c.refusal).join("") || "";
511
+ slot.block.textSignature = encodeTextSignatureV1(item.id, item.phase ?? void 0);
512
+ stream.push({
513
+ type: "text_end",
514
+ contentIndex: slot.contentIndex,
515
+ content: slot.block.text,
516
+ partial: output
517
+ });
518
+ outputSlots.delete(event.output_index);
519
+ } else if (item.type === "function_call" && slot?.type === "toolCall" && slot.block.partialJson !== void 0) {
520
+ slot.block.arguments = parseStreamingJson(item.arguments || slot.block.partialJson || "{}");
521
+ delete slot.block.partialJson;
522
+ stream.push({
523
+ type: "toolcall_end",
524
+ contentIndex: slot.contentIndex,
525
+ toolCall: slot.block,
526
+ partial: output
527
+ });
528
+ outputSlots.delete(event.output_index);
529
+ } else if (item.type === "custom_tool_call" && slot?.type === "toolCall" && slot.block.customInput) {
530
+ pushToolCallDelta(slot, appendCustomToolCallInput(slot.block, item.input ?? getCustomToolCallInput(slot.block), true));
531
+ delete slot.block.customInput;
532
+ stream.push({
533
+ type: "toolcall_end",
534
+ contentIndex: slot.contentIndex,
535
+ toolCall: slot.block,
536
+ partial: output
537
+ });
538
+ outputSlots.delete(event.output_index);
539
+ }
540
+ } else if (event.type === "response.completed" || event.type === "response.incomplete") finalizeResponse(event.response);
541
+ else if (event.type === "error") throw new Error(`Error Code ${event.code}: ${event.message}` || "Unknown error");
542
+ else if (event.type === "response.failed") {
543
+ sawTerminalResponseEvent = true;
544
+ output.rawStopReason = event.response?.status;
545
+ const error = event.response?.error;
546
+ const details = event.response?.incomplete_details;
547
+ const msg = error ? `${error.code || "unknown"}: ${error.message || "no message"}` : details?.reason ? `incomplete: ${details.reason}` : "Unknown error (no error details in response)";
548
+ throw new Error(msg);
549
+ }
550
+ if (!sawTerminalResponseEvent) throw new Error("OpenAI Responses stream ended before a terminal response event");
551
+ }
552
+ function mapStopReason(status, incompleteReason) {
553
+ if (!status) return { stopReason: "stop" };
554
+ switch (status) {
555
+ case "completed": return { stopReason: "stop" };
556
+ case "incomplete":
557
+ if (incompleteReason === "max_output_tokens") return { stopReason: "length" };
558
+ return {
559
+ stopReason: "error",
560
+ errorMessage: incompleteReason ? `Response incomplete: ${incompleteReason}` : "Response incomplete without a provider reason"
561
+ };
562
+ case "failed":
563
+ case "cancelled": return { stopReason: "error" };
564
+ case "in_progress":
565
+ case "queued": return { stopReason: "stop" };
566
+ default: throw new Error(`Unhandled stop reason: ${status}`);
567
+ }
568
+ }
569
+ //#endregion
570
+ export { convertResponsesTools as n, processResponsesStream as r, convertResponsesMessages as t };
571
+
572
+ //# sourceMappingURL=openai-responses-shared-D0Jq7yVP.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"openai-responses-shared-D0Jq7yVP.mjs","names":["_exhaustive"],"sources":["../node_modules/.pnpm/@earendil-works+pi-ai@0.84.1_ws@8.21.3_zod@4.4.3/node_modules/@earendil-works/pi-ai/dist/api/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 { appendGrammarToolInputJsonDelta, getGrammarToolInput, resolveGrammarConstrainedSampling, resolveJsonSchemaStrictSampling, } from \"./constrained-sampling.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}\nfunction convertToolResultOutput(model, content) {\n const textResult = content\n .filter((c) => c.type === \"text\")\n .map((c) => c.text)\n .join(\"\\n\");\n const images = content.filter((c) => c.type === \"image\");\n const hasText = textResult.length > 0;\n if (images.length === 0 || !model.input.includes(\"image\")) {\n return sanitizeSurrogates(hasText ? textResult : images.length > 0 ? \"(see attached image)\" : \"(no tool output)\");\n }\n const output = [];\n if (hasText) {\n output.push({ type: \"input_text\", text: sanitizeSurrogates(textResult) });\n }\n for (const image of images) {\n output.push({\n type: \"input_image\",\n detail: \"auto\",\n image_url: `data:${image.mimeType};base64,${image.data}`,\n });\n }\n return output;\n}\n// =============================================================================\n// Message conversion\n// =============================================================================\nexport function convertResponsesMessages(model, context, allowedToolCallProviders, options) {\n const messages = [];\n const loadedToolNames = new Set();\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 compat = model.compat;\n const role = model.reasoning && compat?.supportsDeveloperRole !== false ? \"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 let textBlockIndex = 0;\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 const fallbackMessageId = textBlockIndex === 0 ? `msg_pi_${msgIndex}` : `msg_pi_${msgIndex}_${textBlockIndex}`;\n textBlockIndex++;\n // OpenAI requires id to be max 64 characters\n let msgId = parsedSignature?.id;\n if (!msgId) {\n msgId = fallbackMessageId;\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 const customInputProperty = options?.grammarToolInputProperties?.get(toolCall.name);\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 // When replaying custom-tool calls as a function_call, also drop non-fc_* ids such as\n // ctc_* custom-tool ids because function_call item ids must be fc_*.\n if ((isDifferentModel && itemId?.startsWith(\"fc_\")) ||\n (customInputProperty === undefined && !itemId?.startsWith(\"fc_\"))) {\n itemId = undefined;\n }\n if (customInputProperty !== undefined) {\n output.push({\n type: \"custom_tool_call\",\n id: itemId,\n call_id: callId,\n name: toolCall.name,\n input: sanitizeSurrogates(getGrammarToolInput(toolCall.name, toolCall.arguments, customInputProperty)),\n });\n }\n else {\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 }\n if (output.length === 0)\n continue;\n messages.push(...output);\n }\n else if (msg.role === \"toolResult\") {\n const [callId] = msg.toolCallId.split(\"|\");\n const output = convertToolResultOutput(model, msg.content);\n if (options?.grammarToolInputProperties?.has(msg.toolName)) {\n messages.push({\n type: \"custom_tool_call_output\",\n call_id: callId,\n output,\n });\n }\n else {\n messages.push({\n type: \"function_call_output\",\n call_id: callId,\n output,\n });\n }\n const deferredTools = [];\n for (const name of msg.addedToolNames ?? []) {\n const tool = options?.deferredTools?.get(name);\n if (!tool || loadedToolNames.has(name))\n continue;\n loadedToolNames.add(name);\n deferredTools.push(tool);\n }\n if (deferredTools.length > 0) {\n const names = deferredTools.map((tool) => tool.name);\n const searchCallId = `pi_tool_load_${shortHash(`${msg.toolCallId}:${names.join(\",\")}`)}`;\n messages.push({\n type: \"tool_search_call\",\n call_id: searchCallId,\n execution: \"client\",\n status: \"completed\",\n arguments: { query: names.join(\" \"), limit: names.length },\n });\n messages.push({\n type: \"tool_search_output\",\n call_id: searchCallId,\n execution: \"client\",\n status: \"completed\",\n tools: convertResponsesTools(deferredTools, {\n ...options?.toolOptions,\n deferLoading: true,\n }),\n });\n }\n }\n msgIndex++;\n }\n return messages;\n}\n// =============================================================================\n// Tool conversion\n// =============================================================================\nexport function convertResponsesTools(tools, options) {\n const defaultStrict = options?.strict === undefined ? false : options.strict;\n const supportsStrictMode = options?.supportsStrictMode ?? true;\n const supportsOpenAIGrammarTools = options?.supportsOpenAIGrammarTools ?? false;\n return tools.map((tool) => {\n const grammar = resolveGrammarConstrainedSampling(tool, supportsOpenAIGrammarTools);\n if (grammar) {\n return {\n type: \"custom\",\n name: tool.name,\n description: tool.description,\n format: {\n type: \"grammar\",\n syntax: grammar.format,\n definition: grammar.definition,\n },\n ...(options?.deferLoading ? { defer_loading: true } : {}),\n };\n }\n const constrainedStrict = resolveJsonSchemaStrictSampling(tool, supportsStrictMode);\n const functionTool = {\n type: \"function\",\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters, // TypeBox already generates JSON Schema\n ...(options?.deferLoading ? { defer_loading: true } : {}),\n };\n if (supportsStrictMode) {\n functionTool.strict = constrainedStrict ?? defaultStrict;\n }\n return functionTool;\n });\n}\nfunction getCustomToolCallInput(block) {\n const property = block.customInput?.property;\n if (property === undefined)\n return \"\";\n const value = block.arguments[property];\n return typeof value === \"string\" ? value : \"\";\n}\nfunction appendCustomToolCallInput(block, nextInput, close) {\n const customInput = block.customInput;\n if (!customInput)\n return undefined;\n const delta = appendGrammarToolInputJsonDelta(customInput.jsonBuffer, customInput.property, nextInput, close);\n block.arguments = { [customInput.property]: nextInput };\n return delta;\n}\nexport async function processResponsesStream(openaiStream, output, stream, model, options) {\n let sawTerminalResponseEvent = false;\n const outputSlots = new Map();\n const reasoningBlocksById = new Map();\n const applyMessagePhaseStopReason = (item) => {\n if (item.type === \"message\" && item.phase === \"final_answer\") {\n output.stopReason = \"stop\";\n }\n };\n const getSlot = (outputIndex, type) => {\n const slot = outputSlots.get(outputIndex);\n return slot?.type === type ? slot : undefined;\n };\n const pushToolCallDelta = (slot, delta) => {\n if (delta === undefined)\n return;\n stream.push({\n type: \"toolcall_delta\",\n contentIndex: slot.contentIndex,\n delta,\n partial: output,\n });\n };\n const createSlot = (outputIndex, item) => {\n if (item.type === \"reasoning\") {\n const block = { type: \"thinking\", thinking: \"\" };\n output.content.push(block);\n const slot = {\n type: \"thinking\",\n block,\n contentIndex: output.content.length - 1,\n };\n outputSlots.set(outputIndex, slot);\n stream.push({ type: \"thinking_start\", contentIndex: slot.contentIndex, partial: output });\n return slot;\n }\n if (item.type === \"message\") {\n applyMessagePhaseStopReason(item);\n const block = { type: \"text\", text: \"\" };\n output.content.push(block);\n const slot = { type: \"text\", block, contentIndex: output.content.length - 1 };\n outputSlots.set(outputIndex, slot);\n stream.push({ type: \"text_start\", contentIndex: slot.contentIndex, partial: output });\n return slot;\n }\n if (item.type === \"function_call\") {\n const block = {\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(block);\n const slot = {\n type: \"toolCall\",\n block,\n contentIndex: output.content.length - 1,\n };\n outputSlots.set(outputIndex, slot);\n stream.push({ type: \"toolcall_start\", contentIndex: slot.contentIndex, partial: output });\n return slot;\n }\n if (item.type === \"custom_tool_call\") {\n const inputProperty = options?.grammarToolInputProperties?.get(item.name) ?? \"input\";\n const input = item.input || \"\";\n const block = {\n type: \"toolCall\",\n id: `${item.call_id}|${item.id}`,\n name: item.name,\n arguments: { [inputProperty]: input },\n customInput: {\n property: inputProperty,\n jsonBuffer: { input: \"\", started: false, closed: false },\n },\n };\n output.content.push(block);\n const slot = {\n type: \"toolCall\",\n block,\n contentIndex: output.content.length - 1,\n };\n outputSlots.set(outputIndex, slot);\n stream.push({ type: \"toolcall_start\", contentIndex: slot.contentIndex, partial: output });\n return slot;\n }\n return undefined;\n };\n const getOrCreateSlot = (outputIndex, item) => {\n return outputSlots.get(outputIndex) ?? createSlot(outputIndex, item);\n };\n // Azure OpenAI can omit reasoning.encrypted_content from response.output_item.done\n // and provide it only in response.completed.response.output. Backfill the\n // persisted reasoning signature from the terminal response to keep store:false\n // multi-turn replay stateless. See https://github.com/earendil-works/pi/issues/6409.\n const backfillReasoningSignatures = (responseOutput) => {\n for (const item of responseOutput) {\n if (item.type !== \"reasoning\" || !item.encrypted_content)\n continue;\n const block = reasoningBlocksById.get(item.id);\n if (!block?.thinkingSignature)\n continue;\n const storedItem = JSON.parse(block.thinkingSignature);\n if (storedItem.encrypted_content)\n continue;\n block.thinkingSignature = JSON.stringify({\n ...storedItem,\n encrypted_content: item.encrypted_content,\n });\n }\n };\n const finalizeResponse = (response) => {\n sawTerminalResponseEvent = true;\n backfillReasoningSignatures(response.output ?? []);\n if (response?.id) {\n output.responseId = response.id;\n }\n if (response?.usage) {\n const inputDetails = response.usage.input_tokens_details;\n const cachedTokens = inputDetails?.cached_tokens || 0;\n const cacheWriteTokens = inputDetails?.cache_write_tokens || 0;\n output.usage = {\n // OpenAI includes cached and cache-write tokens in input_tokens, so subtract both.\n input: Math.max(0, (response.usage.input_tokens || 0) - cachedTokens - cacheWriteTokens),\n output: response.usage.output_tokens || 0,\n cacheRead: cachedTokens,\n cacheWrite: cacheWriteTokens,\n reasoning: response.usage.output_tokens_details?.reasoning_tokens || 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. For incomplete responses, retain the provider's\n // specific reason so max-output truncation and content filtering stay distinct.\n const status = response?.status;\n const incompleteDetails = response?.incomplete_details;\n const incompleteReason = typeof incompleteDetails?.reason === \"string\" ? incompleteDetails.reason : undefined;\n output.rawStopReason = incompleteReason ? `${status}.${incompleteReason}` : status;\n const mappedStop = mapStopReason(status, incompleteReason);\n output.stopReason = mappedStop.stopReason;\n output.errorMessage = mappedStop.errorMessage;\n if (output.content.some((b) => b.type === \"toolCall\") && output.stopReason === \"stop\") {\n output.stopReason = \"toolUse\";\n }\n };\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 createSlot(event.output_index, event.item);\n }\n else if (event.type === \"response.reasoning_summary_text.delta\") {\n const slot = getSlot(event.output_index, \"thinking\");\n if (!slot)\n continue;\n slot.block.thinking += event.delta;\n stream.push({\n type: \"thinking_delta\",\n contentIndex: slot.contentIndex,\n delta: event.delta,\n partial: output,\n });\n }\n else if (event.type === \"response.reasoning_summary_part.done\") {\n const slot = getSlot(event.output_index, \"thinking\");\n if (!slot)\n continue;\n slot.block.thinking += \"\\n\\n\";\n stream.push({\n type: \"thinking_delta\",\n contentIndex: slot.contentIndex,\n delta: \"\\n\\n\",\n partial: output,\n });\n }\n else if (event.type === \"response.reasoning_text.delta\") {\n const slot = getSlot(event.output_index, \"thinking\");\n if (!slot)\n continue;\n slot.block.thinking += event.delta;\n stream.push({\n type: \"thinking_delta\",\n contentIndex: slot.contentIndex,\n delta: event.delta,\n partial: output,\n });\n }\n else if (event.type === \"response.output_text.delta\") {\n const slot = getSlot(event.output_index, \"text\");\n if (!slot)\n continue;\n slot.block.text += event.delta;\n stream.push({\n type: \"text_delta\",\n contentIndex: slot.contentIndex,\n delta: event.delta,\n partial: output,\n });\n }\n else if (event.type === \"response.refusal.delta\") {\n const slot = getSlot(event.output_index, \"text\");\n if (!slot)\n continue;\n slot.block.text += event.delta;\n stream.push({\n type: \"text_delta\",\n contentIndex: slot.contentIndex,\n delta: event.delta,\n partial: output,\n });\n }\n else if (event.type === \"response.function_call_arguments.delta\") {\n const slot = getSlot(event.output_index, \"toolCall\");\n if (!slot || slot.block.partialJson === undefined)\n continue;\n slot.block.partialJson += event.delta;\n slot.block.arguments = parseStreamingJson(slot.block.partialJson);\n pushToolCallDelta(slot, event.delta);\n }\n else if (event.type === \"response.function_call_arguments.done\") {\n const slot = getSlot(event.output_index, \"toolCall\");\n if (!slot || slot.block.partialJson === undefined)\n continue;\n const previousPartialJson = slot.block.partialJson;\n slot.block.partialJson = event.arguments;\n slot.block.arguments = parseStreamingJson(slot.block.partialJson);\n if (event.arguments.startsWith(previousPartialJson)) {\n const delta = event.arguments.slice(previousPartialJson.length);\n if (delta.length > 0)\n pushToolCallDelta(slot, delta);\n }\n }\n else if (event.type === \"response.custom_tool_call_input.delta\") {\n const slot = getSlot(event.output_index, \"toolCall\");\n if (!slot || !slot.block.customInput)\n continue;\n pushToolCallDelta(slot, appendCustomToolCallInput(slot.block, getCustomToolCallInput(slot.block) + event.delta, false));\n }\n else if (event.type === \"response.custom_tool_call_input.done\") {\n const slot = getSlot(event.output_index, \"toolCall\");\n if (!slot || !slot.block.customInput)\n continue;\n pushToolCallDelta(slot, appendCustomToolCallInput(slot.block, event.input, true));\n }\n else if (event.type === \"response.output_item.done\") {\n const item = event.item;\n applyMessagePhaseStopReason(item);\n const slot = getOrCreateSlot(event.output_index, item);\n if (item.type === \"reasoning\" && slot?.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 slot.block.thinking = summaryText || contentText || slot.block.thinking;\n slot.block.thinkingSignature = JSON.stringify(item);\n reasoningBlocksById.set(item.id, slot.block);\n stream.push({\n type: \"thinking_end\",\n contentIndex: slot.contentIndex,\n content: slot.block.thinking,\n partial: output,\n });\n outputSlots.delete(event.output_index);\n }\n else if (item.type === \"message\" && slot?.type === \"text\") {\n slot.block.text = item.content?.map((c) => (c.type === \"output_text\" ? c.text : c.refusal)).join(\"\") || \"\";\n slot.block.textSignature = encodeTextSignatureV1(item.id, item.phase ?? undefined);\n stream.push({\n type: \"text_end\",\n contentIndex: slot.contentIndex,\n content: slot.block.text,\n partial: output,\n });\n outputSlots.delete(event.output_index);\n }\n else if (item.type === \"function_call\" &&\n slot?.type === \"toolCall\" &&\n slot.block.partialJson !== undefined) {\n slot.block.arguments = parseStreamingJson(item.arguments || slot.block.partialJson || \"{}\");\n // Finalize in-place and strip the scratch buffer so replay only\n // carries parsed arguments.\n delete slot.block.partialJson;\n stream.push({\n type: \"toolcall_end\",\n contentIndex: slot.contentIndex,\n toolCall: slot.block,\n partial: output,\n });\n outputSlots.delete(event.output_index);\n }\n else if (item.type === \"custom_tool_call\" && slot?.type === \"toolCall\" && slot.block.customInput) {\n pushToolCallDelta(slot, appendCustomToolCallInput(slot.block, item.input ?? getCustomToolCallInput(slot.block), true));\n delete slot.block.customInput;\n stream.push({\n type: \"toolcall_end\",\n contentIndex: slot.contentIndex,\n toolCall: slot.block,\n partial: output,\n });\n outputSlots.delete(event.output_index);\n }\n }\n else if (event.type === \"response.completed\" || event.type === \"response.incomplete\") {\n finalizeResponse(event.response);\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 sawTerminalResponseEvent = true;\n output.rawStopReason = event.response?.status;\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 if (!sawTerminalResponseEvent) {\n throw new Error(\"OpenAI Responses stream ended before a terminal response event\");\n }\n}\nfunction mapStopReason(status, incompleteReason) {\n if (!status)\n return { stopReason: \"stop\" };\n switch (status) {\n case \"completed\":\n return { stopReason: \"stop\" };\n case \"incomplete\":\n if (incompleteReason === \"max_output_tokens\") {\n return { stopReason: \"length\" };\n }\n return {\n stopReason: \"error\",\n errorMessage: incompleteReason\n ? `Response incomplete: ${incompleteReason}`\n : \"Response incomplete without a provider reason\",\n };\n case \"failed\":\n case \"cancelled\":\n return { stopReason: \"error\" };\n // These two are wonky ...\n case \"in_progress\":\n case \"queued\":\n return { stopReason: \"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":";;;;;;;AASA,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,IAAI,OAAO;IAAI,OAAO,OAAO;GAAM;GAEhD,OAAO,EAAE,IAAI,OAAO,GAAG;EAC3B;CACJ,QACM,CAEN;CAEJ,OAAO,EAAE,IAAI,UAAU;AAC3B;AACA,SAAS,wBAAwB,OAAO,SAAS;CAC7C,MAAM,aAAa,QACd,QAA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