pi2dsh 0.13.2 → 0.13.3

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 (106) hide show
  1. package/README.md +22 -19
  2. package/README.zh.md +18 -15
  3. package/dist/{analyzer-CJFwQlSG.mjs → analyzer-DBtUYKI1.mjs} +2 -2
  4. package/dist/{analyzer-CJFwQlSG.mjs.map → analyzer-DBtUYKI1.mjs.map} +1 -1
  5. package/dist/anthropic-messages-CaYTgvLF.mjs +6436 -0
  6. package/dist/anthropic-messages-CaYTgvLF.mjs.map +1 -0
  7. package/dist/azure-openai-responses-HKWkzl2m.mjs +208 -0
  8. package/dist/azure-openai-responses-HKWkzl2m.mjs.map +1 -0
  9. package/dist/cli.mjs +3 -2
  10. package/dist/cli.mjs.map +1 -1
  11. package/dist/compat/pi-ai.d.mts +3 -2636
  12. package/dist/compat/pi-ai.mjs +3 -2
  13. package/dist/compat/pi-coding-agent.d.mts +2 -2
  14. package/dist/compat/pi-coding-agent.mjs +2 -2
  15. package/dist/{mcp-config-_idn-pzI.mjs → compatibility-Bz6ZXA7F.mjs} +8 -185
  16. package/dist/compatibility-Bz6ZXA7F.mjs.map +1 -0
  17. package/dist/completionchunk-Dhk56lZl.mjs +5212 -0
  18. package/dist/completionchunk-Dhk56lZl.mjs.map +1 -0
  19. package/dist/{credentials-oauth-Txs6oew8.mjs → credentials-oauth-CAohSLcB.mjs} +3 -3
  20. package/dist/{credentials-oauth-Txs6oew8.mjs.map → credentials-oauth-CAohSLcB.mjs.map} +1 -1
  21. package/dist/credentials-oauth.mjs +1 -1
  22. package/dist/deferred-tools-BD4g5QUx.mjs +32 -0
  23. package/dist/deferred-tools-BD4g5QUx.mjs.map +1 -0
  24. package/dist/diagnostics-BqYkodgB.mjs +35 -0
  25. package/dist/diagnostics-BqYkodgB.mjs.map +1 -0
  26. package/dist/dist-QBBA-dL_.mjs +1246 -0
  27. package/dist/dist-QBBA-dL_.mjs.map +1 -0
  28. package/dist/error-body-DKA3lknR.mjs +104 -0
  29. package/dist/error-body-DKA3lknR.mjs.map +1 -0
  30. package/dist/event-stream-QxN1yvIF.mjs +64 -0
  31. package/dist/event-stream-QxN1yvIF.mjs.map +1 -0
  32. package/dist/from-BCscBQ9P.mjs +3856 -0
  33. package/dist/from-BCscBQ9P.mjs.map +1 -0
  34. package/dist/github-copilot-headers-CZo2QHrt.mjs +25 -0
  35. package/dist/github-copilot-headers-CZo2QHrt.mjs.map +1 -0
  36. package/dist/google-generative-ai-2gCFYp-t.mjs +356 -0
  37. package/dist/google-generative-ai-2gCFYp-t.mjs.map +1 -0
  38. package/dist/google-shared-75IdVyrx.mjs +29041 -0
  39. package/dist/google-shared-75IdVyrx.mjs.map +1 -0
  40. package/dist/google-vertex-Bhyo4z2i.mjs +400 -0
  41. package/dist/google-vertex-Bhyo4z2i.mjs.map +1 -0
  42. package/dist/hash-Dbggamac.mjs +19 -0
  43. package/dist/hash-Dbggamac.mjs.map +1 -0
  44. package/dist/headers-CPzZhJQn.mjs +17 -0
  45. package/dist/headers-CPzZhJQn.mjs.map +1 -0
  46. package/dist/host.d.mts +12 -2
  47. package/dist/host.d.mts.map +1 -1
  48. package/dist/host.mjs +43 -5
  49. package/dist/host.mjs.map +1 -1
  50. package/dist/index.d.mts +5 -3
  51. package/dist/index.d.mts.map +1 -1
  52. package/dist/index.mjs +40 -16
  53. package/dist/index.mjs.map +1 -1
  54. package/dist/json-parse-CZ0U0sj_.mjs +384 -0
  55. package/dist/json-parse-CZ0U0sj_.mjs.map +1 -0
  56. package/dist/mcp-config-jmzbgdHa.mjs +181 -0
  57. package/dist/mcp-config-jmzbgdHa.mjs.map +1 -0
  58. package/dist/mistral-conversations-DJyeTo8C.mjs +36921 -0
  59. package/dist/mistral-conversations-DJyeTo8C.mjs.map +1 -0
  60. package/dist/multipart-parser-SRcGkVuX.mjs +301 -0
  61. package/dist/multipart-parser-SRcGkVuX.mjs.map +1 -0
  62. package/dist/{pi-ai-D7PqVeWs.mjs → openai-DkzRh5_G.mjs} +78 -5063
  63. package/dist/openai-DkzRh5_G.mjs.map +1 -0
  64. package/dist/openai-codex-responses-DedxQjNG.mjs +1220 -0
  65. package/dist/openai-codex-responses-DedxQjNG.mjs.map +1 -0
  66. package/dist/openai-completions-DrjrWRdX.mjs +945 -0
  67. package/dist/openai-completions-DrjrWRdX.mjs.map +1 -0
  68. package/dist/openai-prompt-cache-BDWtZRKh.mjs +11 -0
  69. package/dist/openai-prompt-cache-BDWtZRKh.mjs.map +1 -0
  70. package/dist/openai-responses-BRdGpBX6.mjs +251 -0
  71. package/dist/openai-responses-BRdGpBX6.mjs.map +1 -0
  72. package/dist/openai-responses-shared-BmnSvdKL.mjs +570 -0
  73. package/dist/openai-responses-shared-BmnSvdKL.mjs.map +1 -0
  74. package/dist/otel-CBhmS-NR.mjs +24935 -0
  75. package/dist/otel-CBhmS-NR.mjs.map +1 -0
  76. package/dist/pi-ai-CfokFhIL.d.mts +2673 -0
  77. package/dist/pi-ai-CfokFhIL.d.mts.map +1 -0
  78. package/dist/pi-ai-Dh7HUxbt.mjs +3239 -0
  79. package/dist/pi-ai-Dh7HUxbt.mjs.map +1 -0
  80. package/dist/{pi-coding-agent-B0PT23gE.d.mts → pi-coding-agent-69yY0ke-.d.mts} +4 -2
  81. package/dist/{pi-coding-agent-B0PT23gE.d.mts.map → pi-coding-agent-69yY0ke-.d.mts.map} +1 -1
  82. package/dist/{pi-coding-agent-BVZu0dHG.mjs → pi-coding-agent-Cvez0jkF.mjs} +0 -0
  83. package/dist/{pi-coding-agent-BVZu0dHG.mjs.map → pi-coding-agent-Cvez0jkF.mjs.map} +1 -1
  84. package/dist/pi-messages-D61G2tgs.mjs +307 -0
  85. package/dist/pi-messages-D61G2tgs.mjs.map +1 -0
  86. package/dist/provider-env-C72pF4vP.mjs +40 -0
  87. package/dist/provider-env-C72pF4vP.mjs.map +1 -0
  88. package/dist/provider-retry-Cw6YJ4cr.mjs +80 -0
  89. package/dist/provider-retry-Cw6YJ4cr.mjs.map +1 -0
  90. package/dist/rolldown-runtime-CTfmNlz1.mjs +44 -0
  91. package/dist/{runtime-DEjs_Qlf.mjs → runtime-Dd2KhoX-.mjs} +659 -125
  92. package/dist/runtime-Dd2KhoX-.mjs.map +1 -0
  93. package/dist/runtime.d.mts +135 -26
  94. package/dist/runtime.d.mts.map +1 -1
  95. package/dist/runtime.mjs +1 -1
  96. package/dist/simple-options-B_GO8FDE.mjs +456 -0
  97. package/dist/simple-options-B_GO8FDE.mjs.map +1 -0
  98. package/dist/src-DlTagfW5.mjs +1186 -0
  99. package/dist/src-DlTagfW5.mjs.map +1 -0
  100. package/dist/{types-7IWJPPvS.d.mts → types-B9VBF8le.d.mts} +2 -9
  101. package/dist/{types-7IWJPPvS.d.mts.map → types-B9VBF8le.d.mts.map} +1 -1
  102. package/package.json +2 -2
  103. package/dist/compat/pi-ai.d.mts.map +0 -1
  104. package/dist/mcp-config-_idn-pzI.mjs.map +0 -1
  105. package/dist/pi-ai-D7PqVeWs.mjs.map +0 -1
  106. package/dist/runtime-DEjs_Qlf.mjs.map +0 -1
@@ -0,0 +1,570 @@
1
+
2
+ import { c as appendGrammarToolInputJsonDelta, d as resolveGrammarConstrainedSampling, f as resolveJsonSchemaStrictSampling, o as transformMessages, p as calculateCost, s as sanitizeSurrogates, u as getGrammarToolInput } from "./simple-options-B_GO8FDE.mjs";
3
+ import { t as shortHash } from "./hash-Dbggamac.mjs";
4
+ import { n as parseStreamingJson } from "./json-parse-CZ0U0sj_.mjs";
5
+ //#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
6
+ function encodeTextSignatureV1(id, phase) {
7
+ const payload = {
8
+ v: 1,
9
+ id
10
+ };
11
+ if (phase) payload.phase = phase;
12
+ return JSON.stringify(payload);
13
+ }
14
+ function parseTextSignature(signature) {
15
+ if (!signature) return void 0;
16
+ if (signature.startsWith("{")) try {
17
+ const parsed = JSON.parse(signature);
18
+ if (parsed.v === 1 && typeof parsed.id === "string") {
19
+ if (parsed.phase === "commentary" || parsed.phase === "final_answer") return {
20
+ id: parsed.id,
21
+ phase: parsed.phase
22
+ };
23
+ return { id: parsed.id };
24
+ }
25
+ } catch {}
26
+ return { id: signature };
27
+ }
28
+ function convertToolResultOutput(model, content) {
29
+ const textResult = content.filter((c) => c.type === "text").map((c) => c.text).join("\n");
30
+ const images = content.filter((c) => c.type === "image");
31
+ const hasText = textResult.length > 0;
32
+ if (images.length === 0 || !model.input.includes("image")) return sanitizeSurrogates(hasText ? textResult : images.length > 0 ? "(see attached image)" : "(no tool output)");
33
+ const output = [];
34
+ if (hasText) output.push({
35
+ type: "input_text",
36
+ text: sanitizeSurrogates(textResult)
37
+ });
38
+ for (const image of images) output.push({
39
+ type: "input_image",
40
+ detail: "auto",
41
+ image_url: `data:${image.mimeType};base64,${image.data}`
42
+ });
43
+ return output;
44
+ }
45
+ function convertResponsesMessages(model, context, allowedToolCallProviders, options) {
46
+ const messages = [];
47
+ const loadedToolNames = /* @__PURE__ */ new Set();
48
+ const normalizeIdPart = (part) => {
49
+ const sanitized = part.replace(/[^a-zA-Z0-9_-]/g, "_");
50
+ return (sanitized.length > 64 ? sanitized.slice(0, 64) : sanitized).replace(/_+$/, "");
51
+ };
52
+ const buildForeignResponsesItemId = (itemId) => {
53
+ const normalized = `fc_${shortHash(itemId)}`;
54
+ return normalized.length > 64 ? normalized.slice(0, 64) : normalized;
55
+ };
56
+ const normalizeToolCallId = (id, _targetModel, source) => {
57
+ if (!allowedToolCallProviders.has(model.provider)) return normalizeIdPart(id);
58
+ if (!id.includes("|")) return normalizeIdPart(id);
59
+ const [callId, itemId] = id.split("|");
60
+ const normalizedCallId = normalizeIdPart(callId);
61
+ let normalizedItemId = source.provider !== model.provider || source.api !== model.api ? buildForeignResponsesItemId(itemId) : normalizeIdPart(itemId);
62
+ if (!normalizedItemId.startsWith("fc_")) normalizedItemId = normalizeIdPart(`fc_${normalizedItemId}`);
63
+ return `${normalizedCallId}|${normalizedItemId}`;
64
+ };
65
+ const transformedMessages = transformMessages(context.messages, model, normalizeToolCallId);
66
+ if ((options?.includeSystemPrompt ?? true) && context.systemPrompt) {
67
+ const compat = model.compat;
68
+ const role = model.reasoning && compat?.supportsDeveloperRole !== false ? "developer" : "system";
69
+ messages.push({
70
+ role,
71
+ content: sanitizeSurrogates(context.systemPrompt)
72
+ });
73
+ }
74
+ let msgIndex = 0;
75
+ for (const msg of transformedMessages) {
76
+ if (msg.role === "user") {
77
+ if (typeof msg.content === "string") messages.push({
78
+ role: "user",
79
+ content: [{
80
+ type: "input_text",
81
+ text: sanitizeSurrogates(msg.content)
82
+ }]
83
+ });
84
+ else {
85
+ const content = msg.content.map((item) => {
86
+ if (item.type === "text") return {
87
+ type: "input_text",
88
+ text: sanitizeSurrogates(item.text)
89
+ };
90
+ return {
91
+ type: "input_image",
92
+ detail: "auto",
93
+ image_url: `data:${item.mimeType};base64,${item.data}`
94
+ };
95
+ });
96
+ if (content.length === 0) continue;
97
+ messages.push({
98
+ role: "user",
99
+ content
100
+ });
101
+ }
102
+ } else if (msg.role === "assistant") {
103
+ const output = [];
104
+ const assistantMsg = msg;
105
+ const isDifferentModel = assistantMsg.model !== model.id && assistantMsg.provider === model.provider && assistantMsg.api === model.api;
106
+ let textBlockIndex = 0;
107
+ for (const block of msg.content) if (block.type === "thinking") {
108
+ if (block.thinkingSignature) {
109
+ const reasoningItem = JSON.parse(block.thinkingSignature);
110
+ output.push(reasoningItem);
111
+ }
112
+ } else if (block.type === "text") {
113
+ const textBlock = block;
114
+ const parsedSignature = parseTextSignature(textBlock.textSignature);
115
+ const fallbackMessageId = textBlockIndex === 0 ? `msg_pi_${msgIndex}` : `msg_pi_${msgIndex}_${textBlockIndex}`;
116
+ textBlockIndex++;
117
+ let msgId = parsedSignature?.id;
118
+ if (!msgId) msgId = fallbackMessageId;
119
+ else if (msgId.length > 64) msgId = `msg_${shortHash(msgId)}`;
120
+ output.push({
121
+ type: "message",
122
+ role: "assistant",
123
+ content: [{
124
+ type: "output_text",
125
+ text: sanitizeSurrogates(textBlock.text),
126
+ annotations: []
127
+ }],
128
+ status: "completed",
129
+ id: msgId,
130
+ phase: parsedSignature?.phase
131
+ });
132
+ } else if (block.type === "toolCall") {
133
+ const toolCall = block;
134
+ const [callId, itemIdRaw] = toolCall.id.split("|");
135
+ const customInputProperty = options?.grammarToolInputProperties?.get(toolCall.name);
136
+ let itemId = itemIdRaw;
137
+ if (isDifferentModel && itemId?.startsWith("fc_") || customInputProperty === void 0 && !itemId?.startsWith("fc_")) itemId = void 0;
138
+ if (customInputProperty !== void 0) output.push({
139
+ type: "custom_tool_call",
140
+ id: itemId,
141
+ call_id: callId,
142
+ name: toolCall.name,
143
+ input: sanitizeSurrogates(getGrammarToolInput(toolCall.name, toolCall.arguments, customInputProperty))
144
+ });
145
+ else output.push({
146
+ type: "function_call",
147
+ id: itemId,
148
+ call_id: callId,
149
+ name: toolCall.name,
150
+ arguments: JSON.stringify(toolCall.arguments)
151
+ });
152
+ }
153
+ if (output.length === 0) continue;
154
+ messages.push(...output);
155
+ } else if (msg.role === "toolResult") {
156
+ const [callId] = msg.toolCallId.split("|");
157
+ const output = convertToolResultOutput(model, msg.content);
158
+ if (options?.grammarToolInputProperties?.has(msg.toolName)) messages.push({
159
+ type: "custom_tool_call_output",
160
+ call_id: callId,
161
+ output
162
+ });
163
+ else messages.push({
164
+ type: "function_call_output",
165
+ call_id: callId,
166
+ output
167
+ });
168
+ const deferredTools = [];
169
+ for (const name of msg.addedToolNames ?? []) {
170
+ const tool = options?.deferredTools?.get(name);
171
+ if (!tool || loadedToolNames.has(name)) continue;
172
+ loadedToolNames.add(name);
173
+ deferredTools.push(tool);
174
+ }
175
+ if (deferredTools.length > 0) {
176
+ const names = deferredTools.map((tool) => tool.name);
177
+ const searchCallId = `pi_tool_load_${shortHash(`${msg.toolCallId}:${names.join(",")}`)}`;
178
+ messages.push({
179
+ type: "tool_search_call",
180
+ call_id: searchCallId,
181
+ execution: "client",
182
+ status: "completed",
183
+ arguments: {
184
+ query: names.join(" "),
185
+ limit: names.length
186
+ }
187
+ });
188
+ messages.push({
189
+ type: "tool_search_output",
190
+ call_id: searchCallId,
191
+ execution: "client",
192
+ status: "completed",
193
+ tools: convertResponsesTools(deferredTools, {
194
+ ...options?.toolOptions,
195
+ deferLoading: true
196
+ })
197
+ });
198
+ }
199
+ }
200
+ msgIndex++;
201
+ }
202
+ return messages;
203
+ }
204
+ function convertResponsesTools(tools, options) {
205
+ const defaultStrict = options?.strict === void 0 ? false : options.strict;
206
+ const supportsStrictMode = options?.supportsStrictMode ?? true;
207
+ const supportsOpenAIGrammarTools = options?.supportsOpenAIGrammarTools ?? false;
208
+ return tools.map((tool) => {
209
+ const grammar = resolveGrammarConstrainedSampling(tool, supportsOpenAIGrammarTools);
210
+ if (grammar) return {
211
+ type: "custom",
212
+ name: tool.name,
213
+ description: tool.description,
214
+ format: {
215
+ type: "grammar",
216
+ syntax: grammar.format,
217
+ definition: grammar.definition
218
+ },
219
+ ...options?.deferLoading ? { defer_loading: true } : {}
220
+ };
221
+ const constrainedStrict = resolveJsonSchemaStrictSampling(tool, supportsStrictMode);
222
+ const functionTool = {
223
+ type: "function",
224
+ name: tool.name,
225
+ description: tool.description,
226
+ parameters: tool.parameters,
227
+ ...options?.deferLoading ? { defer_loading: true } : {}
228
+ };
229
+ if (supportsStrictMode) functionTool.strict = constrainedStrict ?? defaultStrict;
230
+ return functionTool;
231
+ });
232
+ }
233
+ function getCustomToolCallInput(block) {
234
+ const property = block.customInput?.property;
235
+ if (property === void 0) return "";
236
+ const value = block.arguments[property];
237
+ return typeof value === "string" ? value : "";
238
+ }
239
+ function appendCustomToolCallInput(block, nextInput, close) {
240
+ const customInput = block.customInput;
241
+ if (!customInput) return void 0;
242
+ const delta = appendGrammarToolInputJsonDelta(customInput.jsonBuffer, customInput.property, nextInput, close);
243
+ block.arguments = { [customInput.property]: nextInput };
244
+ return delta;
245
+ }
246
+ async function processResponsesStream(openaiStream, output, stream, model, options) {
247
+ let sawTerminalResponseEvent = false;
248
+ const outputSlots = /* @__PURE__ */ new Map();
249
+ const reasoningBlocksById = /* @__PURE__ */ new Map();
250
+ const applyMessagePhaseStopReason = (item) => {
251
+ if (item.type === "message" && item.phase === "final_answer") output.stopReason = "stop";
252
+ };
253
+ const getSlot = (outputIndex, type) => {
254
+ const slot = outputSlots.get(outputIndex);
255
+ return slot?.type === type ? slot : void 0;
256
+ };
257
+ const pushToolCallDelta = (slot, delta) => {
258
+ if (delta === void 0) return;
259
+ stream.push({
260
+ type: "toolcall_delta",
261
+ contentIndex: slot.contentIndex,
262
+ delta,
263
+ partial: output
264
+ });
265
+ };
266
+ const createSlot = (outputIndex, item) => {
267
+ if (item.type === "reasoning") {
268
+ const block = {
269
+ type: "thinking",
270
+ thinking: ""
271
+ };
272
+ output.content.push(block);
273
+ const slot = {
274
+ type: "thinking",
275
+ block,
276
+ contentIndex: output.content.length - 1
277
+ };
278
+ outputSlots.set(outputIndex, slot);
279
+ stream.push({
280
+ type: "thinking_start",
281
+ contentIndex: slot.contentIndex,
282
+ partial: output
283
+ });
284
+ return slot;
285
+ }
286
+ if (item.type === "message") {
287
+ applyMessagePhaseStopReason(item);
288
+ const block = {
289
+ type: "text",
290
+ text: ""
291
+ };
292
+ output.content.push(block);
293
+ const slot = {
294
+ type: "text",
295
+ block,
296
+ contentIndex: output.content.length - 1
297
+ };
298
+ outputSlots.set(outputIndex, slot);
299
+ stream.push({
300
+ type: "text_start",
301
+ contentIndex: slot.contentIndex,
302
+ partial: output
303
+ });
304
+ return slot;
305
+ }
306
+ if (item.type === "function_call") {
307
+ const block = {
308
+ type: "toolCall",
309
+ id: `${item.call_id}|${item.id}`,
310
+ name: item.name,
311
+ arguments: {},
312
+ partialJson: item.arguments || ""
313
+ };
314
+ output.content.push(block);
315
+ const slot = {
316
+ type: "toolCall",
317
+ block,
318
+ contentIndex: output.content.length - 1
319
+ };
320
+ outputSlots.set(outputIndex, slot);
321
+ stream.push({
322
+ type: "toolcall_start",
323
+ contentIndex: slot.contentIndex,
324
+ partial: output
325
+ });
326
+ return slot;
327
+ }
328
+ if (item.type === "custom_tool_call") {
329
+ const inputProperty = options?.grammarToolInputProperties?.get(item.name) ?? "input";
330
+ const input = item.input || "";
331
+ const block = {
332
+ type: "toolCall",
333
+ id: `${item.call_id}|${item.id}`,
334
+ name: item.name,
335
+ arguments: { [inputProperty]: input },
336
+ customInput: {
337
+ property: inputProperty,
338
+ jsonBuffer: {
339
+ input: "",
340
+ started: false,
341
+ closed: false
342
+ }
343
+ }
344
+ };
345
+ output.content.push(block);
346
+ const slot = {
347
+ type: "toolCall",
348
+ block,
349
+ contentIndex: output.content.length - 1
350
+ };
351
+ outputSlots.set(outputIndex, slot);
352
+ stream.push({
353
+ type: "toolcall_start",
354
+ contentIndex: slot.contentIndex,
355
+ partial: output
356
+ });
357
+ return slot;
358
+ }
359
+ };
360
+ const getOrCreateSlot = (outputIndex, item) => {
361
+ return outputSlots.get(outputIndex) ?? createSlot(outputIndex, item);
362
+ };
363
+ const backfillReasoningSignatures = (responseOutput) => {
364
+ for (const item of responseOutput) {
365
+ if (item.type !== "reasoning" || !item.encrypted_content) continue;
366
+ const block = reasoningBlocksById.get(item.id);
367
+ if (!block?.thinkingSignature) continue;
368
+ const storedItem = JSON.parse(block.thinkingSignature);
369
+ if (storedItem.encrypted_content) continue;
370
+ block.thinkingSignature = JSON.stringify({
371
+ ...storedItem,
372
+ encrypted_content: item.encrypted_content
373
+ });
374
+ }
375
+ };
376
+ const finalizeResponse = (response) => {
377
+ sawTerminalResponseEvent = true;
378
+ backfillReasoningSignatures(response.output ?? []);
379
+ if (response?.id) output.responseId = response.id;
380
+ if (response?.usage) {
381
+ const inputDetails = response.usage.input_tokens_details;
382
+ const cachedTokens = inputDetails?.cached_tokens || 0;
383
+ const cacheWriteTokens = inputDetails?.cache_write_tokens || 0;
384
+ output.usage = {
385
+ input: Math.max(0, (response.usage.input_tokens || 0) - cachedTokens - cacheWriteTokens),
386
+ output: response.usage.output_tokens || 0,
387
+ cacheRead: cachedTokens,
388
+ cacheWrite: cacheWriteTokens,
389
+ reasoning: response.usage.output_tokens_details?.reasoning_tokens || 0,
390
+ totalTokens: response.usage.total_tokens || 0,
391
+ cost: {
392
+ input: 0,
393
+ output: 0,
394
+ cacheRead: 0,
395
+ cacheWrite: 0,
396
+ total: 0
397
+ }
398
+ };
399
+ }
400
+ calculateCost(model, output.usage);
401
+ if (options?.applyServiceTierPricing) {
402
+ const serviceTier = options.resolveServiceTier ? options.resolveServiceTier(response?.service_tier, options.serviceTier) : response?.service_tier ?? options.serviceTier;
403
+ options.applyServiceTierPricing(output.usage, serviceTier);
404
+ }
405
+ const status = response?.status;
406
+ const incompleteDetails = response?.incomplete_details;
407
+ const incompleteReason = typeof incompleteDetails?.reason === "string" ? incompleteDetails.reason : void 0;
408
+ output.rawStopReason = incompleteReason ? `${status}.${incompleteReason}` : status;
409
+ const mappedStop = mapStopReason(status, incompleteReason);
410
+ output.stopReason = mappedStop.stopReason;
411
+ output.errorMessage = mappedStop.errorMessage;
412
+ if (output.content.some((b) => b.type === "toolCall") && output.stopReason === "stop") output.stopReason = "toolUse";
413
+ };
414
+ for await (const event of openaiStream) if (event.type === "response.created") output.responseId = event.response.id;
415
+ else if (event.type === "response.output_item.added") createSlot(event.output_index, event.item);
416
+ else if (event.type === "response.reasoning_summary_text.delta") {
417
+ const slot = getSlot(event.output_index, "thinking");
418
+ if (!slot) continue;
419
+ slot.block.thinking += event.delta;
420
+ stream.push({
421
+ type: "thinking_delta",
422
+ contentIndex: slot.contentIndex,
423
+ delta: event.delta,
424
+ partial: output
425
+ });
426
+ } else if (event.type === "response.reasoning_summary_part.done") {
427
+ const slot = getSlot(event.output_index, "thinking");
428
+ if (!slot) continue;
429
+ slot.block.thinking += "\n\n";
430
+ stream.push({
431
+ type: "thinking_delta",
432
+ contentIndex: slot.contentIndex,
433
+ delta: "\n\n",
434
+ partial: output
435
+ });
436
+ } else if (event.type === "response.reasoning_text.delta") {
437
+ const slot = getSlot(event.output_index, "thinking");
438
+ if (!slot) continue;
439
+ slot.block.thinking += event.delta;
440
+ stream.push({
441
+ type: "thinking_delta",
442
+ contentIndex: slot.contentIndex,
443
+ delta: event.delta,
444
+ partial: output
445
+ });
446
+ } else if (event.type === "response.output_text.delta") {
447
+ const slot = getSlot(event.output_index, "text");
448
+ if (!slot) continue;
449
+ slot.block.text += event.delta;
450
+ stream.push({
451
+ type: "text_delta",
452
+ contentIndex: slot.contentIndex,
453
+ delta: event.delta,
454
+ partial: output
455
+ });
456
+ } else if (event.type === "response.refusal.delta") {
457
+ const slot = getSlot(event.output_index, "text");
458
+ if (!slot) continue;
459
+ slot.block.text += event.delta;
460
+ stream.push({
461
+ type: "text_delta",
462
+ contentIndex: slot.contentIndex,
463
+ delta: event.delta,
464
+ partial: output
465
+ });
466
+ } else if (event.type === "response.function_call_arguments.delta") {
467
+ const slot = getSlot(event.output_index, "toolCall");
468
+ if (!slot || slot.block.partialJson === void 0) continue;
469
+ slot.block.partialJson += event.delta;
470
+ slot.block.arguments = parseStreamingJson(slot.block.partialJson);
471
+ pushToolCallDelta(slot, event.delta);
472
+ } else if (event.type === "response.function_call_arguments.done") {
473
+ const slot = getSlot(event.output_index, "toolCall");
474
+ if (!slot || slot.block.partialJson === void 0) continue;
475
+ const previousPartialJson = slot.block.partialJson;
476
+ slot.block.partialJson = event.arguments;
477
+ slot.block.arguments = parseStreamingJson(slot.block.partialJson);
478
+ if (event.arguments.startsWith(previousPartialJson)) {
479
+ const delta = event.arguments.slice(previousPartialJson.length);
480
+ if (delta.length > 0) pushToolCallDelta(slot, delta);
481
+ }
482
+ } else if (event.type === "response.custom_tool_call_input.delta") {
483
+ const slot = getSlot(event.output_index, "toolCall");
484
+ if (!slot || !slot.block.customInput) continue;
485
+ pushToolCallDelta(slot, appendCustomToolCallInput(slot.block, getCustomToolCallInput(slot.block) + event.delta, false));
486
+ } else if (event.type === "response.custom_tool_call_input.done") {
487
+ const slot = getSlot(event.output_index, "toolCall");
488
+ if (!slot || !slot.block.customInput) continue;
489
+ pushToolCallDelta(slot, appendCustomToolCallInput(slot.block, event.input, true));
490
+ } else if (event.type === "response.output_item.done") {
491
+ const item = event.item;
492
+ applyMessagePhaseStopReason(item);
493
+ const slot = getOrCreateSlot(event.output_index, item);
494
+ if (item.type === "reasoning" && slot?.type === "thinking") {
495
+ const summaryText = item.summary?.map((s) => s.text).join("\n\n") || "";
496
+ const contentText = item.content?.map((c) => c.text).join("\n\n") || "";
497
+ slot.block.thinking = summaryText || contentText || slot.block.thinking;
498
+ slot.block.thinkingSignature = JSON.stringify(item);
499
+ reasoningBlocksById.set(item.id, slot.block);
500
+ stream.push({
501
+ type: "thinking_end",
502
+ contentIndex: slot.contentIndex,
503
+ content: slot.block.thinking,
504
+ partial: output
505
+ });
506
+ outputSlots.delete(event.output_index);
507
+ } else if (item.type === "message" && slot?.type === "text") {
508
+ slot.block.text = item.content?.map((c) => c.type === "output_text" ? c.text : c.refusal).join("") || "";
509
+ slot.block.textSignature = encodeTextSignatureV1(item.id, item.phase ?? void 0);
510
+ stream.push({
511
+ type: "text_end",
512
+ contentIndex: slot.contentIndex,
513
+ content: slot.block.text,
514
+ partial: output
515
+ });
516
+ outputSlots.delete(event.output_index);
517
+ } else if (item.type === "function_call" && slot?.type === "toolCall" && slot.block.partialJson !== void 0) {
518
+ slot.block.arguments = parseStreamingJson(item.arguments || slot.block.partialJson || "{}");
519
+ delete slot.block.partialJson;
520
+ stream.push({
521
+ type: "toolcall_end",
522
+ contentIndex: slot.contentIndex,
523
+ toolCall: slot.block,
524
+ partial: output
525
+ });
526
+ outputSlots.delete(event.output_index);
527
+ } else if (item.type === "custom_tool_call" && slot?.type === "toolCall" && slot.block.customInput) {
528
+ pushToolCallDelta(slot, appendCustomToolCallInput(slot.block, item.input ?? getCustomToolCallInput(slot.block), true));
529
+ delete slot.block.customInput;
530
+ stream.push({
531
+ type: "toolcall_end",
532
+ contentIndex: slot.contentIndex,
533
+ toolCall: slot.block,
534
+ partial: output
535
+ });
536
+ outputSlots.delete(event.output_index);
537
+ }
538
+ } else if (event.type === "response.completed" || event.type === "response.incomplete") finalizeResponse(event.response);
539
+ else if (event.type === "error") throw new Error(`Error Code ${event.code}: ${event.message}` || "Unknown error");
540
+ else if (event.type === "response.failed") {
541
+ sawTerminalResponseEvent = true;
542
+ output.rawStopReason = event.response?.status;
543
+ const error = event.response?.error;
544
+ const details = event.response?.incomplete_details;
545
+ const msg = error ? `${error.code || "unknown"}: ${error.message || "no message"}` : details?.reason ? `incomplete: ${details.reason}` : "Unknown error (no error details in response)";
546
+ throw new Error(msg);
547
+ }
548
+ if (!sawTerminalResponseEvent) throw new Error("OpenAI Responses stream ended before a terminal response event");
549
+ }
550
+ function mapStopReason(status, incompleteReason) {
551
+ if (!status) return { stopReason: "stop" };
552
+ switch (status) {
553
+ case "completed": return { stopReason: "stop" };
554
+ case "incomplete":
555
+ if (incompleteReason === "max_output_tokens") return { stopReason: "length" };
556
+ return {
557
+ stopReason: "error",
558
+ errorMessage: incompleteReason ? `Response incomplete: ${incompleteReason}` : "Response incomplete without a provider reason"
559
+ };
560
+ case "failed":
561
+ case "cancelled": return { stopReason: "error" };
562
+ case "in_progress":
563
+ case "queued": return { stopReason: "stop" };
564
+ default: throw new Error(`Unhandled stop reason: ${status}`);
565
+ }
566
+ }
567
+ //#endregion
568
+ export { convertResponsesTools as n, processResponsesStream as r, convertResponsesMessages as t };
569
+
570
+ //# sourceMappingURL=openai-responses-shared-BmnSvdKL.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"openai-responses-shared-BmnSvdKL.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;GAE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