@nexface/agent 0.1.15-alpha.0 → 0.1.15-alpha.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 (99) hide show
  1. package/dist/agent.d.ts +1 -2
  2. package/dist/agent.js +918 -333
  3. package/dist/browser-policy/gpt.js +36 -12
  4. package/dist/browser-policy/jev.js +21 -9
  5. package/dist/browser-policy/response-error.js +4 -2
  6. package/dist/browser-policy/shared.js +49 -21
  7. package/dist/browser-prompt.generated.js +0 -1
  8. package/dist/browser-prompt.js +0 -1
  9. package/dist/errors.d.ts +2 -2
  10. package/dist/errors.js +3 -4
  11. package/dist/history-compaction.js +47 -26
  12. package/dist/history-version.js +11 -4
  13. package/dist/index.js +0 -1
  14. package/dist/model/binding.js +0 -1
  15. package/dist/model/error.js +0 -1
  16. package/dist/model/internal-adapter.js +1 -2
  17. package/dist/model/types.js +0 -1
  18. package/dist/models/3.js +5553 -0
  19. package/dist/models/3e.js +4 -0
  20. package/dist/models/6.js +506 -0
  21. package/dist/models/anthropic-messages.js +5 -20
  22. package/dist/models/anthropic-messages~1.js +5629 -0
  23. package/dist/models/deferred-tools.js +28 -0
  24. package/dist/models/error-body.js +64 -0
  25. package/dist/models/google-generative-ai.js +4 -19
  26. package/dist/models/google-generative-ai~1.js +18305 -0
  27. package/dist/models/google-generative-ai~1.js.LICENSE.txt +5 -0
  28. package/dist/models/{39.js → k.js} +168 -336
  29. package/dist/models/openai-completions.js +3 -10
  30. package/dist/models/openai-completions~1.js +987 -0
  31. package/dist/models/openai-responses.js +3 -10
  32. package/dist/models/openai-responses~1.js +848 -0
  33. package/dist/models/rslib-runtime.js +32 -56
  34. package/dist/models/v.js +346 -0
  35. package/dist/page-decision.js +197 -59
  36. package/dist/page-decisions/gpt.js +0 -1
  37. package/dist/page-decisions/jev.js +0 -1
  38. package/dist/page-decisions/shared.js +26 -9
  39. package/dist/page-diagnostics.js +8 -3
  40. package/dist/page-observation.js +11 -6
  41. package/dist/request.js +169 -41
  42. package/dist/shared/definition.js +2 -3
  43. package/dist/shared/errors.d.ts +1 -1
  44. package/dist/shared/errors.js +0 -1
  45. package/dist/shared/page-protocol.js +0 -1
  46. package/dist/shared/page-tools.js +0 -1
  47. package/dist/shared/runtime-controller.d.ts +1 -0
  48. package/dist/shared/runtime-controller.js +0 -1
  49. package/dist/shared/runtime-execution.js +0 -1
  50. package/dist/shared/schema.js +45 -19
  51. package/dist/tool-catalog.js +23 -25
  52. package/dist/tool-result.js +7 -3
  53. package/dist/types.js +0 -1
  54. package/package.json +6 -2
  55. package/dist/agent.js.map +0 -1
  56. package/dist/browser-policy/gpt.js.map +0 -1
  57. package/dist/browser-policy/jev.js.map +0 -1
  58. package/dist/browser-policy/response-error.js.map +0 -1
  59. package/dist/browser-policy/shared.js.map +0 -1
  60. package/dist/browser-prompt.generated.js.map +0 -1
  61. package/dist/browser-prompt.js.map +0 -1
  62. package/dist/errors.js.map +0 -1
  63. package/dist/history-compaction.js.map +0 -1
  64. package/dist/history-version.js.map +0 -1
  65. package/dist/index.js.map +0 -1
  66. package/dist/model/binding.js.map +0 -1
  67. package/dist/model/error.js.map +0 -1
  68. package/dist/model/internal-adapter.js.map +0 -1
  69. package/dist/model/types.js.map +0 -1
  70. package/dist/models/851.js +0 -10
  71. package/dist/models/_chunks/360-7e580bb2.js +0 -1189
  72. package/dist/models/_chunks/474-e1813138.js +0 -8304
  73. package/dist/models/_chunks/86-c0c5ac98.js +0 -453
  74. package/dist/models/_chunks/anthropic-messages~1-d35e3e7d.js +0 -8057
  75. package/dist/models/_chunks/deferred-tools-90f3c977.js +0 -37
  76. package/dist/models/_chunks/error-body-8bee35c2.js +0 -134
  77. package/dist/models/_chunks/google-generative-ai~1-2ba71457.js +0 -22104
  78. package/dist/models/_chunks/openai-completions~1-b340f0e0.js +0 -1285
  79. package/dist/models/_chunks/openai-responses~1-b53c65c2.js +0 -958
  80. package/dist/page-decision.js.map +0 -1
  81. package/dist/page-decisions/gpt.js.map +0 -1
  82. package/dist/page-decisions/jev.js.map +0 -1
  83. package/dist/page-decisions/shared.js.map +0 -1
  84. package/dist/page-diagnostics.js.map +0 -1
  85. package/dist/page-observation.js.map +0 -1
  86. package/dist/request.js.map +0 -1
  87. package/dist/shared/definition.js.map +0 -1
  88. package/dist/shared/errors.js.map +0 -1
  89. package/dist/shared/page-protocol.js.map +0 -1
  90. package/dist/shared/page-tools.js.map +0 -1
  91. package/dist/shared/runtime-controller.js.map +0 -1
  92. package/dist/shared/runtime-execution.js.map +0 -1
  93. package/dist/shared/schema.js.map +0 -1
  94. package/dist/shared/tool-registry.d.ts +0 -6
  95. package/dist/shared/tool-registry.js +0 -10
  96. package/dist/shared/tool-registry.js.map +0 -1
  97. package/dist/tool-catalog.js.map +0 -1
  98. package/dist/tool-result.js.map +0 -1
  99. package/dist/types.js.map +0 -1
@@ -0,0 +1,848 @@
1
+ import { definePropertyGetters, makeNamespaceObject } from "./rslib-runtime.js";
2
+ import { sanitizeSurrogates, appendGrammarToolInputJsonDelta, resolveGrammarConstrainedSampling, getGrammarToolInput, headersToRecord, clampThinkingLevel, resolveJsonSchemaStrictSampling, transformMessages, calculateCost, buildBaseOptions, retryProviderRequest, createGrammarToolInputProperties } from "./6.js";
3
+ import { OpenAI, shortHash, clampOpenAIPromptCacheKey } from "./3.js";
4
+ import { getProviderEnvValue, buildCopilotDynamicHeaders, parseStreamingJson, hasCopilotVisionInput } from "./v.js";
5
+ import { formatProviderError, normalizeProviderError } from "./error-body.js";
6
+ import { AssistantMessageEventStream } from "./k.js";
7
+ import { splitDeferredTools } from "./deferred-tools.js";
8
+ var openai_responses_namespaceObject = {};
9
+ makeNamespaceObject(openai_responses_namespaceObject);
10
+ definePropertyGetters(openai_responses_namespaceObject, {
11
+ stream: ()=>openai_responses_stream,
12
+ streamSimple: ()=>streamSimple
13
+ });
14
+ function encodeTextSignatureV1(id, phase) {
15
+ const payload = {
16
+ v: 1,
17
+ id
18
+ };
19
+ if (phase) payload.phase = phase;
20
+ return JSON.stringify(payload);
21
+ }
22
+ function parseTextSignature(signature) {
23
+ if (!signature) return;
24
+ if (signature.startsWith("{")) try {
25
+ const parsed = JSON.parse(signature);
26
+ if (1 === parsed.v && "string" == typeof parsed.id) {
27
+ if ("commentary" === parsed.phase || "final_answer" === parsed.phase) return {
28
+ id: parsed.id,
29
+ phase: parsed.phase
30
+ };
31
+ return {
32
+ id: parsed.id
33
+ };
34
+ }
35
+ } catch {}
36
+ return {
37
+ id: signature
38
+ };
39
+ }
40
+ function convertToolResultOutput(model, content) {
41
+ const textResult = content.filter((c)=>"text" === c.type).map((c)=>c.text).join("\n");
42
+ const images = content.filter((c)=>"image" === c.type);
43
+ const hasText = textResult.length > 0;
44
+ if (0 === images.length || !model.input.includes("image")) return sanitizeSurrogates(hasText ? textResult : images.length > 0 ? "(see attached image)" : "(no tool output)");
45
+ const output = [];
46
+ if (hasText) output.push({
47
+ type: "input_text",
48
+ text: sanitizeSurrogates(textResult)
49
+ });
50
+ for (const image of images)output.push({
51
+ type: "input_image",
52
+ detail: "auto",
53
+ image_url: `data:${image.mimeType};base64,${image.data}`
54
+ });
55
+ return output;
56
+ }
57
+ function convertResponsesMessages(model, context, allowedToolCallProviders, options) {
58
+ const messages = [];
59
+ const loadedToolNames = new Set();
60
+ const normalizeIdPart = (part)=>{
61
+ const sanitized = part.replace(/[^a-zA-Z0-9_-]/g, "_");
62
+ const normalized = sanitized.length > 64 ? sanitized.slice(0, 64) : sanitized;
63
+ return normalized.replace(/_+$/, "");
64
+ };
65
+ const buildForeignResponsesItemId = (itemId)=>{
66
+ const normalized = `fc_${shortHash(itemId)}`;
67
+ return normalized.length > 64 ? normalized.slice(0, 64) : normalized;
68
+ };
69
+ const normalizeToolCallId = (id, _targetModel, source)=>{
70
+ if (!allowedToolCallProviders.has(model.provider)) return normalizeIdPart(id);
71
+ if (!id.includes("|")) return normalizeIdPart(id);
72
+ const [callId, itemId] = id.split("|");
73
+ const normalizedCallId = normalizeIdPart(callId);
74
+ const isForeignToolCall = source.provider !== model.provider || source.api !== model.api;
75
+ let normalizedItemId = isForeignToolCall ? buildForeignResponsesItemId(itemId) : normalizeIdPart(itemId);
76
+ if (!normalizedItemId.startsWith("fc_")) normalizedItemId = normalizeIdPart(`fc_${normalizedItemId}`);
77
+ return `${normalizedCallId}|${normalizedItemId}`;
78
+ };
79
+ const transformedMessages = transformMessages(context.messages, model, normalizeToolCallId);
80
+ const includeSystemPrompt = options?.includeSystemPrompt ?? true;
81
+ if (includeSystemPrompt && context.systemPrompt) {
82
+ const compat = model.compat;
83
+ const role = model.reasoning && compat?.supportsDeveloperRole !== false ? "developer" : "system";
84
+ messages.push({
85
+ role,
86
+ content: sanitizeSurrogates(context.systemPrompt)
87
+ });
88
+ }
89
+ let msgIndex = 0;
90
+ for (const msg of transformedMessages){
91
+ if ("user" === msg.role) if ("string" == typeof msg.content) messages.push({
92
+ role: "user",
93
+ content: [
94
+ {
95
+ type: "input_text",
96
+ text: sanitizeSurrogates(msg.content)
97
+ }
98
+ ]
99
+ });
100
+ else {
101
+ const content = msg.content.map((item)=>{
102
+ if ("text" === item.type) return {
103
+ type: "input_text",
104
+ text: sanitizeSurrogates(item.text)
105
+ };
106
+ return {
107
+ type: "input_image",
108
+ detail: "auto",
109
+ image_url: `data:${item.mimeType};base64,${item.data}`
110
+ };
111
+ });
112
+ if (0 === content.length) continue;
113
+ messages.push({
114
+ role: "user",
115
+ content
116
+ });
117
+ }
118
+ else if ("assistant" === msg.role) {
119
+ const output = [];
120
+ const assistantMsg = msg;
121
+ const isDifferentModel = assistantMsg.model !== model.id && assistantMsg.provider === model.provider && assistantMsg.api === model.api;
122
+ let textBlockIndex = 0;
123
+ for (const block of msg.content)if ("thinking" === block.type) {
124
+ if (block.thinkingSignature) {
125
+ const reasoningItem = JSON.parse(block.thinkingSignature);
126
+ output.push(reasoningItem);
127
+ }
128
+ } else if ("text" === block.type) {
129
+ const textBlock = block;
130
+ const parsedSignature = parseTextSignature(textBlock.textSignature);
131
+ const fallbackMessageId = 0 === textBlockIndex ? `msg_pi_${msgIndex}` : `msg_pi_${msgIndex}_${textBlockIndex}`;
132
+ textBlockIndex++;
133
+ let msgId = parsedSignature?.id;
134
+ if (msgId) {
135
+ if (msgId.length > 64) msgId = `msg_${shortHash(msgId)}`;
136
+ } else msgId = fallbackMessageId;
137
+ output.push({
138
+ type: "message",
139
+ role: "assistant",
140
+ content: [
141
+ {
142
+ type: "output_text",
143
+ text: sanitizeSurrogates(textBlock.text),
144
+ annotations: []
145
+ }
146
+ ],
147
+ status: "completed",
148
+ id: msgId,
149
+ phase: parsedSignature?.phase
150
+ });
151
+ } else if ("toolCall" === block.type) {
152
+ const toolCall = block;
153
+ const [callId, itemIdRaw] = toolCall.id.split("|");
154
+ const customInputProperty = options?.grammarToolInputProperties?.get(toolCall.name);
155
+ let itemId = itemIdRaw;
156
+ if (isDifferentModel && itemId?.startsWith("fc_") || void 0 === customInputProperty && !itemId?.startsWith("fc_")) itemId = void 0;
157
+ if (void 0 !== customInputProperty) output.push({
158
+ type: "custom_tool_call",
159
+ id: itemId,
160
+ call_id: callId,
161
+ name: toolCall.name,
162
+ input: sanitizeSurrogates(getGrammarToolInput(toolCall.name, toolCall.arguments, customInputProperty))
163
+ });
164
+ else output.push({
165
+ type: "function_call",
166
+ id: itemId,
167
+ call_id: callId,
168
+ name: toolCall.name,
169
+ arguments: JSON.stringify(toolCall.arguments)
170
+ });
171
+ }
172
+ if (0 === output.length) continue;
173
+ messages.push(...output);
174
+ } else if ("toolResult" === msg.role) {
175
+ const [callId] = msg.toolCallId.split("|");
176
+ const output = convertToolResultOutput(model, msg.content);
177
+ if (options?.grammarToolInputProperties?.has(msg.toolName)) messages.push({
178
+ type: "custom_tool_call_output",
179
+ call_id: callId,
180
+ output
181
+ });
182
+ else messages.push({
183
+ type: "function_call_output",
184
+ call_id: callId,
185
+ output
186
+ });
187
+ const deferredTools = [];
188
+ for (const name of msg.addedToolNames ?? []){
189
+ const tool = options?.deferredTools?.get(name);
190
+ if (!(!tool || loadedToolNames.has(name))) {
191
+ loadedToolNames.add(name);
192
+ deferredTools.push(tool);
193
+ }
194
+ }
195
+ if (deferredTools.length > 0) {
196
+ const names = deferredTools.map((tool)=>tool.name);
197
+ const searchCallId = `pi_tool_load_${shortHash(`${msg.toolCallId}:${names.join(",")}`)}`;
198
+ messages.push({
199
+ type: "tool_search_call",
200
+ call_id: searchCallId,
201
+ execution: "client",
202
+ status: "completed",
203
+ arguments: {
204
+ query: names.join(" "),
205
+ limit: names.length
206
+ }
207
+ });
208
+ messages.push({
209
+ type: "tool_search_output",
210
+ call_id: searchCallId,
211
+ execution: "client",
212
+ status: "completed",
213
+ tools: convertResponsesTools(deferredTools, {
214
+ ...options?.toolOptions,
215
+ deferLoading: true
216
+ })
217
+ });
218
+ }
219
+ }
220
+ msgIndex++;
221
+ }
222
+ return messages;
223
+ }
224
+ function convertResponsesTools(tools, options) {
225
+ const defaultStrict = options?.strict === void 0 ? false : options.strict;
226
+ const supportsStrictMode = options?.supportsStrictMode ?? true;
227
+ const supportsOpenAIGrammarTools = options?.supportsOpenAIGrammarTools ?? false;
228
+ return tools.map((tool)=>{
229
+ const grammar = resolveGrammarConstrainedSampling(tool, supportsOpenAIGrammarTools);
230
+ if (grammar) return {
231
+ type: "custom",
232
+ name: tool.name,
233
+ description: tool.description,
234
+ format: {
235
+ type: "grammar",
236
+ syntax: grammar.format,
237
+ definition: grammar.definition
238
+ },
239
+ ...options?.deferLoading ? {
240
+ defer_loading: true
241
+ } : {}
242
+ };
243
+ const constrainedStrict = resolveJsonSchemaStrictSampling(tool, supportsStrictMode);
244
+ const functionTool = {
245
+ type: "function",
246
+ name: tool.name,
247
+ description: tool.description,
248
+ parameters: tool.parameters,
249
+ ...options?.deferLoading ? {
250
+ defer_loading: true
251
+ } : {}
252
+ };
253
+ if (supportsStrictMode) functionTool.strict = constrainedStrict ?? defaultStrict;
254
+ return functionTool;
255
+ });
256
+ }
257
+ function getCustomToolCallInput(block) {
258
+ const property = block.customInput?.property;
259
+ if (void 0 === property) return "";
260
+ const value = block.arguments[property];
261
+ return "string" == typeof value ? value : "";
262
+ }
263
+ function appendCustomToolCallInput(block, nextInput, close) {
264
+ const customInput = block.customInput;
265
+ if (!customInput) return;
266
+ const delta = appendGrammarToolInputJsonDelta(customInput.jsonBuffer, customInput.property, nextInput, close);
267
+ block.arguments = {
268
+ [customInput.property]: nextInput
269
+ };
270
+ return delta;
271
+ }
272
+ async function processResponsesStream(openaiStream, output, stream, model, options) {
273
+ let sawTerminalResponseEvent = false;
274
+ const outputSlots = new Map();
275
+ const reasoningBlocksById = new Map();
276
+ const applyMessagePhaseStopReason = (item)=>{
277
+ if ("message" === item.type && "final_answer" === item.phase) output.stopReason = "stop";
278
+ };
279
+ const getSlot = (outputIndex, type)=>{
280
+ const slot = outputSlots.get(outputIndex);
281
+ return slot?.type === type ? slot : void 0;
282
+ };
283
+ const pushToolCallDelta = (slot, delta)=>{
284
+ if (void 0 === delta) return;
285
+ stream.push({
286
+ type: "toolcall_delta",
287
+ contentIndex: slot.contentIndex,
288
+ delta,
289
+ partial: output
290
+ });
291
+ };
292
+ const createSlot = (outputIndex, item)=>{
293
+ if ("reasoning" === item.type) {
294
+ const block = {
295
+ type: "thinking",
296
+ thinking: ""
297
+ };
298
+ output.content.push(block);
299
+ const slot = {
300
+ type: "thinking",
301
+ block,
302
+ contentIndex: output.content.length - 1
303
+ };
304
+ outputSlots.set(outputIndex, slot);
305
+ stream.push({
306
+ type: "thinking_start",
307
+ contentIndex: slot.contentIndex,
308
+ partial: output
309
+ });
310
+ return slot;
311
+ }
312
+ if ("message" === item.type) {
313
+ applyMessagePhaseStopReason(item);
314
+ const block = {
315
+ type: "text",
316
+ text: ""
317
+ };
318
+ output.content.push(block);
319
+ const slot = {
320
+ type: "text",
321
+ block,
322
+ contentIndex: output.content.length - 1
323
+ };
324
+ outputSlots.set(outputIndex, slot);
325
+ stream.push({
326
+ type: "text_start",
327
+ contentIndex: slot.contentIndex,
328
+ partial: output
329
+ });
330
+ return slot;
331
+ }
332
+ if ("function_call" === item.type) {
333
+ const block = {
334
+ type: "toolCall",
335
+ id: `${item.call_id}|${item.id}`,
336
+ name: item.name,
337
+ arguments: {},
338
+ partialJson: item.arguments || ""
339
+ };
340
+ output.content.push(block);
341
+ const slot = {
342
+ type: "toolCall",
343
+ block,
344
+ contentIndex: output.content.length - 1
345
+ };
346
+ outputSlots.set(outputIndex, slot);
347
+ stream.push({
348
+ type: "toolcall_start",
349
+ contentIndex: slot.contentIndex,
350
+ partial: output
351
+ });
352
+ return slot;
353
+ }
354
+ if ("custom_tool_call" === item.type) {
355
+ const inputProperty = options?.grammarToolInputProperties?.get(item.name) ?? "input";
356
+ const input = item.input || "";
357
+ const block = {
358
+ type: "toolCall",
359
+ id: `${item.call_id}|${item.id}`,
360
+ name: item.name,
361
+ arguments: {
362
+ [inputProperty]: input
363
+ },
364
+ customInput: {
365
+ property: inputProperty,
366
+ jsonBuffer: {
367
+ input: "",
368
+ started: false,
369
+ closed: false
370
+ }
371
+ }
372
+ };
373
+ output.content.push(block);
374
+ const slot = {
375
+ type: "toolCall",
376
+ block,
377
+ contentIndex: output.content.length - 1
378
+ };
379
+ outputSlots.set(outputIndex, slot);
380
+ stream.push({
381
+ type: "toolcall_start",
382
+ contentIndex: slot.contentIndex,
383
+ partial: output
384
+ });
385
+ return slot;
386
+ }
387
+ };
388
+ const getOrCreateSlot = (outputIndex, item)=>outputSlots.get(outputIndex) ?? createSlot(outputIndex, item);
389
+ const backfillReasoningSignatures = (responseOutput)=>{
390
+ for (const item of responseOutput){
391
+ if ("reasoning" !== item.type || !item.encrypted_content) continue;
392
+ const block = reasoningBlocksById.get(item.id);
393
+ if (!block?.thinkingSignature) continue;
394
+ const storedItem = JSON.parse(block.thinkingSignature);
395
+ if (!storedItem.encrypted_content) block.thinkingSignature = JSON.stringify({
396
+ ...storedItem,
397
+ encrypted_content: item.encrypted_content
398
+ });
399
+ }
400
+ };
401
+ const finalizeResponse = (response)=>{
402
+ sawTerminalResponseEvent = true;
403
+ backfillReasoningSignatures(response.output ?? []);
404
+ if (response?.id) output.responseId = response.id;
405
+ if (response?.usage) {
406
+ const inputDetails = response.usage.input_tokens_details;
407
+ const cachedTokens = inputDetails?.cached_tokens || 0;
408
+ const cacheWriteTokens = inputDetails?.cache_write_tokens || 0;
409
+ output.usage = {
410
+ input: Math.max(0, (response.usage.input_tokens || 0) - cachedTokens - cacheWriteTokens),
411
+ output: response.usage.output_tokens || 0,
412
+ cacheRead: cachedTokens,
413
+ cacheWrite: cacheWriteTokens,
414
+ reasoning: response.usage.output_tokens_details?.reasoning_tokens || 0,
415
+ totalTokens: response.usage.total_tokens || 0,
416
+ cost: {
417
+ input: 0,
418
+ output: 0,
419
+ cacheRead: 0,
420
+ cacheWrite: 0,
421
+ total: 0
422
+ }
423
+ };
424
+ }
425
+ calculateCost(model, output.usage);
426
+ if (options?.applyServiceTierPricing) {
427
+ const serviceTier = options.resolveServiceTier ? options.resolveServiceTier(response?.service_tier, options.serviceTier) : response?.service_tier ?? options.serviceTier;
428
+ options.applyServiceTierPricing(output.usage, serviceTier);
429
+ }
430
+ const status = response?.status;
431
+ const incompleteDetails = response?.incomplete_details;
432
+ const incompleteReason = "string" == typeof incompleteDetails?.reason ? incompleteDetails.reason : void 0;
433
+ output.rawStopReason = incompleteReason ? `${status}.${incompleteReason}` : status;
434
+ const mappedStop = mapStopReason(status, incompleteReason);
435
+ output.stopReason = mappedStop.stopReason;
436
+ output.errorMessage = mappedStop.errorMessage;
437
+ if (output.content.some((b)=>"toolCall" === b.type) && "stop" === output.stopReason) output.stopReason = "toolUse";
438
+ };
439
+ for await (const event of openaiStream)if ("response.created" === event.type) output.responseId = event.response.id;
440
+ else if ("response.output_item.added" === event.type) createSlot(event.output_index, event.item);
441
+ else if ("response.reasoning_summary_text.delta" === event.type) {
442
+ const slot = getSlot(event.output_index, "thinking");
443
+ if (!slot) continue;
444
+ slot.block.thinking += event.delta;
445
+ stream.push({
446
+ type: "thinking_delta",
447
+ contentIndex: slot.contentIndex,
448
+ delta: event.delta,
449
+ partial: output
450
+ });
451
+ } else if ("response.reasoning_summary_part.done" === event.type) {
452
+ const slot = getSlot(event.output_index, "thinking");
453
+ if (!slot) continue;
454
+ slot.block.thinking += "\n\n";
455
+ stream.push({
456
+ type: "thinking_delta",
457
+ contentIndex: slot.contentIndex,
458
+ delta: "\n\n",
459
+ partial: output
460
+ });
461
+ } else if ("response.reasoning_text.delta" === event.type) {
462
+ const slot = getSlot(event.output_index, "thinking");
463
+ if (!slot) continue;
464
+ slot.block.thinking += event.delta;
465
+ stream.push({
466
+ type: "thinking_delta",
467
+ contentIndex: slot.contentIndex,
468
+ delta: event.delta,
469
+ partial: output
470
+ });
471
+ } else if ("response.output_text.delta" === event.type) {
472
+ const slot = getSlot(event.output_index, "text");
473
+ if (!slot) continue;
474
+ slot.block.text += event.delta;
475
+ stream.push({
476
+ type: "text_delta",
477
+ contentIndex: slot.contentIndex,
478
+ delta: event.delta,
479
+ partial: output
480
+ });
481
+ } else if ("response.refusal.delta" === event.type) {
482
+ const slot = getSlot(event.output_index, "text");
483
+ if (!slot) continue;
484
+ slot.block.text += event.delta;
485
+ stream.push({
486
+ type: "text_delta",
487
+ contentIndex: slot.contentIndex,
488
+ delta: event.delta,
489
+ partial: output
490
+ });
491
+ } else if ("response.function_call_arguments.delta" === event.type) {
492
+ const slot = getSlot(event.output_index, "toolCall");
493
+ if (!slot || void 0 === slot.block.partialJson) continue;
494
+ slot.block.partialJson += event.delta;
495
+ slot.block.arguments = parseStreamingJson(slot.block.partialJson);
496
+ pushToolCallDelta(slot, event.delta);
497
+ } else if ("response.function_call_arguments.done" === event.type) {
498
+ const slot = getSlot(event.output_index, "toolCall");
499
+ if (!slot || void 0 === slot.block.partialJson) continue;
500
+ const previousPartialJson = slot.block.partialJson;
501
+ slot.block.partialJson = event.arguments;
502
+ slot.block.arguments = parseStreamingJson(slot.block.partialJson);
503
+ if (event.arguments.startsWith(previousPartialJson)) {
504
+ const delta = event.arguments.slice(previousPartialJson.length);
505
+ if (delta.length > 0) pushToolCallDelta(slot, delta);
506
+ }
507
+ } else if ("response.custom_tool_call_input.delta" === event.type) {
508
+ const slot = getSlot(event.output_index, "toolCall");
509
+ if (!slot || !slot.block.customInput) continue;
510
+ pushToolCallDelta(slot, appendCustomToolCallInput(slot.block, getCustomToolCallInput(slot.block) + event.delta, false));
511
+ } else if ("response.custom_tool_call_input.done" === event.type) {
512
+ const slot = getSlot(event.output_index, "toolCall");
513
+ if (!slot || !slot.block.customInput) continue;
514
+ pushToolCallDelta(slot, appendCustomToolCallInput(slot.block, event.input, true));
515
+ } else if ("response.output_item.done" === event.type) {
516
+ const item = event.item;
517
+ applyMessagePhaseStopReason(item);
518
+ const slot = getOrCreateSlot(event.output_index, item);
519
+ if ("reasoning" === item.type && slot?.type === "thinking") {
520
+ const summaryText = item.summary?.map((s)=>s.text).join("\n\n") || "";
521
+ const contentText = item.content?.map((c)=>c.text).join("\n\n") || "";
522
+ slot.block.thinking = summaryText || contentText || slot.block.thinking;
523
+ slot.block.thinkingSignature = JSON.stringify(item);
524
+ reasoningBlocksById.set(item.id, slot.block);
525
+ stream.push({
526
+ type: "thinking_end",
527
+ contentIndex: slot.contentIndex,
528
+ content: slot.block.thinking,
529
+ partial: output
530
+ });
531
+ outputSlots.delete(event.output_index);
532
+ } else if ("message" === item.type && slot?.type === "text") {
533
+ slot.block.text = item.content?.map((c)=>"output_text" === c.type ? c.text : c.refusal).join("") || "";
534
+ slot.block.textSignature = encodeTextSignatureV1(item.id, item.phase ?? void 0);
535
+ stream.push({
536
+ type: "text_end",
537
+ contentIndex: slot.contentIndex,
538
+ content: slot.block.text,
539
+ partial: output
540
+ });
541
+ outputSlots.delete(event.output_index);
542
+ } else if ("function_call" === item.type && slot?.type === "toolCall" && void 0 !== slot.block.partialJson) {
543
+ slot.block.arguments = parseStreamingJson(item.arguments || slot.block.partialJson || "{}");
544
+ delete slot.block.partialJson;
545
+ stream.push({
546
+ type: "toolcall_end",
547
+ contentIndex: slot.contentIndex,
548
+ toolCall: slot.block,
549
+ partial: output
550
+ });
551
+ outputSlots.delete(event.output_index);
552
+ } else if ("custom_tool_call" === item.type && slot?.type === "toolCall" && slot.block.customInput) {
553
+ pushToolCallDelta(slot, appendCustomToolCallInput(slot.block, item.input ?? getCustomToolCallInput(slot.block), true));
554
+ delete slot.block.customInput;
555
+ stream.push({
556
+ type: "toolcall_end",
557
+ contentIndex: slot.contentIndex,
558
+ toolCall: slot.block,
559
+ partial: output
560
+ });
561
+ outputSlots.delete(event.output_index);
562
+ }
563
+ } else if ("response.completed" === event.type || "response.incomplete" === event.type) finalizeResponse(event.response);
564
+ else if ("error" === event.type) throw new Error(`Error Code ${event.code}: ${event.message}` || "Unknown error");
565
+ else if ("response.failed" === event.type) {
566
+ sawTerminalResponseEvent = true;
567
+ output.rawStopReason = event.response?.status;
568
+ const error = event.response?.error;
569
+ const details = event.response?.incomplete_details;
570
+ const msg = error ? `${error.code || "unknown"}: ${error.message || "no message"}` : details?.reason ? `incomplete: ${details.reason}` : "Unknown error (no error details in response)";
571
+ throw new Error(msg);
572
+ }
573
+ if (!sawTerminalResponseEvent) throw new Error("OpenAI Responses stream ended before a terminal response event");
574
+ }
575
+ function mapStopReason(status, incompleteReason) {
576
+ if (!status) return {
577
+ stopReason: "stop"
578
+ };
579
+ switch(status){
580
+ case "completed":
581
+ return {
582
+ stopReason: "stop"
583
+ };
584
+ case "incomplete":
585
+ if ("max_output_tokens" === incompleteReason) return {
586
+ stopReason: "length"
587
+ };
588
+ return {
589
+ stopReason: "error",
590
+ errorMessage: incompleteReason ? `Response incomplete: ${incompleteReason}` : "Response incomplete without a provider reason"
591
+ };
592
+ case "failed":
593
+ case "cancelled":
594
+ return {
595
+ stopReason: "error"
596
+ };
597
+ case "in_progress":
598
+ case "queued":
599
+ return {
600
+ stopReason: "stop"
601
+ };
602
+ default:
603
+ {
604
+ const _exhaustive = status;
605
+ throw new Error(`Unhandled stop reason: ${_exhaustive}`);
606
+ }
607
+ }
608
+ }
609
+ const OPENAI_TOOL_CALL_PROVIDERS = new Set([
610
+ "openai",
611
+ "openai-codex",
612
+ "opencode"
613
+ ]);
614
+ const OPENAI_RESPONSES_MIN_OUTPUT_TOKENS = 16;
615
+ function hasHeader(headers, name) {
616
+ if (!headers) return false;
617
+ const expected = name.toLowerCase();
618
+ for (const [key, value] of Object.entries(headers))if (key.toLowerCase() === expected && null !== value && value.trim().length > 0) return true;
619
+ return false;
620
+ }
621
+ function getClientApiKey(provider, apiKey, headers) {
622
+ if (apiKey) return apiKey;
623
+ if (hasHeader(headers, "authorization") || hasHeader(headers, "cf-aig-authorization")) return "unused";
624
+ throw new Error(`No API key for provider: ${provider}`);
625
+ }
626
+ function detectSessionAffinityFormat(model) {
627
+ return "openrouter" === model.provider || model.baseUrl.includes("openrouter.ai") ? "openrouter" : "openai";
628
+ }
629
+ function resolveCacheRetention(cacheRetention, env) {
630
+ if (cacheRetention) return cacheRetention;
631
+ if ("long" === getProviderEnvValue("PI_CACHE_RETENTION", env)) return "long";
632
+ return "short";
633
+ }
634
+ function getCompat(model) {
635
+ return {
636
+ supportsDeveloperRole: model.compat?.supportsDeveloperRole ?? true,
637
+ sessionAffinityFormat: model.compat?.sessionAffinityFormat ?? detectSessionAffinityFormat(model),
638
+ supportsLongCacheRetention: model.compat?.supportsLongCacheRetention ?? true,
639
+ supportsStrictMode: model.compat?.supportsStrictMode ?? false,
640
+ supportsOpenAIGrammarTools: model.compat?.supportsOpenAIGrammarTools ?? false,
641
+ supportsToolSearch: model.compat?.supportsToolSearch ?? false,
642
+ supportsExplicitPromptCacheMode: model.compat?.supportsExplicitPromptCacheMode ?? false
643
+ };
644
+ }
645
+ function getPromptCacheRetention(compat, cacheRetention) {
646
+ return "long" === cacheRetention && compat.supportsLongCacheRetention ? "24h" : void 0;
647
+ }
648
+ function formatOpenAIResponsesError(error) {
649
+ return formatProviderError(normalizeProviderError(error), "OpenAI API error");
650
+ }
651
+ const openai_responses_stream = (model, context, options)=>{
652
+ const stream = new AssistantMessageEventStream();
653
+ (async ()=>{
654
+ const output = {
655
+ role: "assistant",
656
+ content: [],
657
+ api: model.api,
658
+ provider: model.provider,
659
+ model: model.id,
660
+ usage: {
661
+ input: 0,
662
+ output: 0,
663
+ cacheRead: 0,
664
+ cacheWrite: 0,
665
+ totalTokens: 0,
666
+ cost: {
667
+ input: 0,
668
+ output: 0,
669
+ cacheRead: 0,
670
+ cacheWrite: 0,
671
+ total: 0
672
+ }
673
+ },
674
+ stopReason: "pending",
675
+ timestamp: Date.now()
676
+ };
677
+ try {
678
+ const apiKey = getClientApiKey(model.provider, options?.apiKey, options?.headers);
679
+ const cacheRetention = resolveCacheRetention(options?.cacheRetention, options?.env);
680
+ const cacheSessionId = "none" === cacheRetention ? void 0 : options?.sessionId;
681
+ const compat = getCompat(model);
682
+ const grammarToolInputProperties = createGrammarToolInputProperties(context.tools, compat.supportsOpenAIGrammarTools);
683
+ const client = createClient(model, context, apiKey, options?.headers, options?.fetch, cacheSessionId);
684
+ let params = buildParams(model, context, options, compat, grammarToolInputProperties);
685
+ const nextParams = await options?.onPayload?.(params, model);
686
+ if (void 0 !== nextParams) params = nextParams;
687
+ const requestOptions = {
688
+ ...options?.signal ? {
689
+ signal: options.signal
690
+ } : {},
691
+ ...options?.timeoutMs !== void 0 ? {
692
+ timeout: options.timeoutMs
693
+ } : {},
694
+ maxRetries: 0
695
+ };
696
+ const { data: openaiStream, response } = await retryProviderRequest(()=>client.responses.create(params, requestOptions).withResponse(), {
697
+ maxRetries: options?.maxRetries,
698
+ maxRetryDelayMs: options?.maxRetryDelayMs,
699
+ signal: options?.signal
700
+ });
701
+ await options?.onResponse?.({
702
+ status: response.status,
703
+ headers: headersToRecord(response.headers)
704
+ }, model);
705
+ stream.push({
706
+ type: "start",
707
+ partial: output
708
+ });
709
+ await processResponsesStream(openaiStream, output, stream, model, {
710
+ serviceTier: options?.serviceTier,
711
+ grammarToolInputProperties,
712
+ applyServiceTierPricing: (usage, serviceTier)=>applyServiceTierPricing(usage, serviceTier, model)
713
+ });
714
+ if (options?.signal?.aborted) throw new Error("Request was aborted");
715
+ if ("pending" === output.stopReason) throw new Error("OpenAI Responses stream ended without a stop reason");
716
+ if ("aborted" === output.stopReason || "error" === output.stopReason) throw new Error(output.errorMessage || "An unknown error occurred");
717
+ stream.push({
718
+ type: "done",
719
+ reason: output.stopReason,
720
+ message: output
721
+ });
722
+ stream.end();
723
+ } catch (error) {
724
+ for (const block of output.content){
725
+ delete block.index;
726
+ delete block.partialJson;
727
+ delete block.customInput;
728
+ }
729
+ output.stopReason = options?.signal?.aborted ? "aborted" : "error";
730
+ output.errorMessage = formatOpenAIResponsesError(error);
731
+ stream.push({
732
+ type: "error",
733
+ reason: output.stopReason,
734
+ error: output
735
+ });
736
+ stream.end();
737
+ }
738
+ })();
739
+ return stream;
740
+ };
741
+ const streamSimple = (model, context, options)=>{
742
+ getClientApiKey(model.provider, options?.apiKey, options?.headers);
743
+ const base = buildBaseOptions(model, context, options, options?.apiKey);
744
+ const clampedReasoning = options?.reasoning ? clampThinkingLevel(model, options.reasoning) : void 0;
745
+ const reasoningEffort = "off" === clampedReasoning ? void 0 : clampedReasoning;
746
+ return openai_responses_stream(model, context, {
747
+ ...base,
748
+ reasoningEffort
749
+ });
750
+ };
751
+ function createClient(model, context, apiKey, optionsHeaders, fetch, sessionId) {
752
+ const compat = getCompat(model);
753
+ const headers = {
754
+ ...model.headers
755
+ };
756
+ if ("github-copilot" === model.provider) {
757
+ const hasImages = hasCopilotVisionInput(context.messages);
758
+ const copilotHeaders = buildCopilotDynamicHeaders({
759
+ messages: context.messages,
760
+ hasImages
761
+ });
762
+ Object.assign(headers, copilotHeaders);
763
+ }
764
+ if (sessionId) if ("openrouter" === compat.sessionAffinityFormat) headers["x-session-id"] = sessionId;
765
+ else {
766
+ if ("openai" === compat.sessionAffinityFormat) headers.session_id = sessionId;
767
+ headers["x-client-request-id"] = sessionId;
768
+ }
769
+ if (optionsHeaders) Object.assign(headers, optionsHeaders);
770
+ return new OpenAI({
771
+ apiKey,
772
+ baseURL: model.baseUrl,
773
+ dangerouslyAllowBrowser: true,
774
+ fetch,
775
+ defaultHeaders: headers
776
+ });
777
+ }
778
+ function buildParams(model, context, options, compat = getCompat(model), grammarToolInputProperties = createGrammarToolInputProperties(context.tools, compat.supportsOpenAIGrammarTools)) {
779
+ const toolPlacement = splitDeferredTools(context, compat.supportsToolSearch);
780
+ const messages = convertResponsesMessages(model, context, OPENAI_TOOL_CALL_PROVIDERS, {
781
+ grammarToolInputProperties,
782
+ deferredTools: toolPlacement.deferred,
783
+ toolOptions: {
784
+ supportsStrictMode: compat.supportsStrictMode,
785
+ supportsOpenAIGrammarTools: compat.supportsOpenAIGrammarTools
786
+ }
787
+ });
788
+ const cacheRetention = resolveCacheRetention(options?.cacheRetention, options?.env);
789
+ const disableImplicitPromptCache = "none" === cacheRetention && compat.supportsExplicitPromptCacheMode;
790
+ const params = {
791
+ model: model.id,
792
+ input: messages,
793
+ stream: true,
794
+ prompt_cache_key: "none" === cacheRetention ? void 0 : clampOpenAIPromptCacheKey(options?.sessionId),
795
+ prompt_cache_retention: getPromptCacheRetention(compat, cacheRetention),
796
+ prompt_cache_options: disableImplicitPromptCache ? {
797
+ mode: "explicit"
798
+ } : void 0,
799
+ store: false
800
+ };
801
+ if (options?.maxTokens) params.max_output_tokens = Math.max(options.maxTokens, OPENAI_RESPONSES_MIN_OUTPUT_TOKENS);
802
+ if (options?.temperature !== void 0) params.temperature = options?.temperature;
803
+ if (options?.serviceTier !== void 0) params.service_tier = options.serviceTier;
804
+ if (toolPlacement.immediate.length > 0) params.tools = convertResponsesTools(toolPlacement.immediate, {
805
+ supportsStrictMode: compat.supportsStrictMode,
806
+ supportsOpenAIGrammarTools: compat.supportsOpenAIGrammarTools
807
+ });
808
+ if (options?.toolChoice !== void 0) params.tool_choice = options.toolChoice;
809
+ if (model.reasoning) {
810
+ if (options?.reasoningEffort || options?.reasoningSummary) {
811
+ const effort = options?.reasoningEffort ? model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort : "medium";
812
+ params.reasoning = {
813
+ effort: effort,
814
+ summary: options?.reasoningSummary || "auto"
815
+ };
816
+ params.include = [
817
+ "reasoning.encrypted_content"
818
+ ];
819
+ } else if ("github-copilot" !== model.provider && model.thinkingLevelMap?.off !== null) params.reasoning = {
820
+ effort: model.thinkingLevelMap?.off ?? "none"
821
+ };
822
+ if ("xai" === model.provider) params.include = [
823
+ "reasoning.encrypted_content"
824
+ ];
825
+ }
826
+ if (options?.samplingParams) Object.assign(params, options.samplingParams);
827
+ return params;
828
+ }
829
+ function getServiceTierCostMultiplier(model, serviceTier) {
830
+ switch(serviceTier){
831
+ case "flex":
832
+ return 0.5;
833
+ case "priority":
834
+ return "gpt-5.5" === model.id ? 2.5 : 2;
835
+ default:
836
+ return 1;
837
+ }
838
+ }
839
+ function applyServiceTierPricing(usage, serviceTier, model) {
840
+ const multiplier = getServiceTierCostMultiplier(model, serviceTier);
841
+ if (1 === multiplier) return;
842
+ usage.cost.input *= multiplier;
843
+ usage.cost.output *= multiplier;
844
+ usage.cost.cacheRead *= multiplier;
845
+ usage.cost.cacheWrite *= multiplier;
846
+ usage.cost.total = usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite;
847
+ }
848
+ export { openai_responses_namespaceObject };