@alvin0/ai-agent-sdk-protocol-responses 0.1.10 → 0.1.12

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.
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { CONTEXT_WINDOW_EXCEEDED_CODE, MODEL_ERROR_CODES, ModelError, QUOTA_EXCEEDED_CODE, ToolCallId, isJsonValue, isNativeToolSchema } from "@alvin0/ai-agent-sdk-core";
2
2
 
3
- //#region src/serialize.ts
4
- /** Read the reasoning state back off a block, tolerating anything unexpected. */
3
+ //#region src/request-content.ts
4
+ const DEFAULT_DOCUMENT_FILENAME = "document.pdf";
5
5
  function reasoningStateOf(value) {
6
6
  if (typeof value !== "object" || value === null) return {};
7
7
  const state = value;
@@ -33,8 +33,6 @@ function imagePart(block) {
33
33
  ...detail === void 0 ? {} : { detail }
34
34
  };
35
35
  }
36
- /** Fallback file name for an inline document, since the API infers type from it. */
37
- const DEFAULT_DOCUMENT_FILENAME = "document.pdf";
38
36
  function documentPart(block) {
39
37
  if (block.source.kind === "file") return {
40
38
  type: "input_file",
@@ -50,7 +48,6 @@ function documentPart(block) {
50
48
  file_data: `data:${block.source.mediaType};base64,${block.source.data}`
51
49
  };
52
50
  }
53
- /** Convert one content block to a request-side content part. */
54
51
  function contentPart(block, role) {
55
52
  if (block.type === "text") {
56
53
  if (role !== "assistant") return {
@@ -67,92 +64,122 @@ function contentPart(block, role) {
67
64
  if (block.type === "image") return imagePart(block);
68
65
  if (block.type === "document") return documentPart(block);
69
66
  }
70
- /** Render a tool result's blocks as the wire's polymorphic `output` value. */
71
67
  function toolResultOutput(blocks) {
72
68
  if (!blocks.some((block) => block.type === "image" || block.type === "document")) return blocks.filter((block) => block.type === "text").map((block) => block.text).join("\n");
73
69
  return blocks.map((block) => contentPart(block, "user")).filter((part) => part !== void 0);
74
70
  }
75
- /**
76
- * Expand one message into zero or more wire items, appending them in order.
77
- *
78
- * Content parts accumulate into a single message item, which is FLUSHED whenever
79
- * a block appears that has to become its own top-level item. That flushing is
80
- * what preserves "spoke, then called a tool, then spoke again" as three items in
81
- * the right order instead of collapsing it.
82
- */
71
+ function nativeReplayItem(block) {
72
+ const value = block.providerState;
73
+ if (typeof value !== "object" || value === null) return void 0;
74
+ const item = value;
75
+ if (item.type === "web_search_call") return {
76
+ type: "web_search_call",
77
+ ...typeof item.id === "string" ? { id: item.id } : {},
78
+ ...typeof item.status === "string" ? { status: item.status } : {},
79
+ ...item.action === void 0 ? {} : { action: structuredClone(item.action) }
80
+ };
81
+ if (item.type === "image_generation_call") return imageReplayItem(item, generatedImage(block));
82
+ }
83
+ /** The generated image, as base64; histories recorded before it moved there keep it in the item. */
84
+ function generatedImage(block) {
85
+ const image = block.content.find((content) => content.type === "image" && content.source.kind === "base64");
86
+ return image?.type === "image" && image.source.kind === "base64" ? image.source.data : void 0;
87
+ }
88
+ function imageReplayItem(item, image) {
89
+ const result = image ?? item.result;
90
+ return {
91
+ type: "image_generation_call",
92
+ ...typeof item.id === "string" ? { id: item.id } : {},
93
+ ...typeof item.status === "string" ? { status: item.status } : {},
94
+ ...typeof result === "string" || result === null ? { result } : {}
95
+ };
96
+ }
97
+
98
+ //#endregion
99
+ //#region src/request-messages.ts
100
+ /** Flush content at standalone-item boundaries to preserve conversation order. */
83
101
  function appendMessage(message, items, dialectMessagePhase) {
84
- const role = message.role === "assistant" ? "assistant" : "user";
85
- let parts = [];
86
- let phase;
87
- const flush = () => {
88
- if (parts.length === 0) return;
89
- items.push({
90
- type: "message",
91
- role,
92
- content: parts,
93
- ...role === "assistant" && dialectMessagePhase && phase !== void 0 ? { phase: phase === "final-answer" ? "final_answer" : phase } : {}
94
- });
95
- parts = [];
96
- phase = void 0;
97
- };
98
- for (const block of message.content) switch (block.type) {
99
- case "text":
100
- case "image":
101
- case "document": {
102
- if (block.type === "text" && block.phase !== void 0 && phase !== void 0 && phase !== block.phase) flush();
103
- if (block.type === "text" && block.phase !== void 0) phase = block.phase;
104
- const part = contentPart(block, role);
105
- if (part !== void 0) parts.push(part);
106
- break;
107
- }
108
- case "reasoning": {
109
- flush();
110
- const state = reasoningStateOf(block.providerState);
111
- if (state.id === void 0 && state.encryptedContent === void 0) break;
112
- const summary = state.summary !== void 0 && state.summary.length > 0 ? state.summary : block.text.length > 0 ? [block.text] : [];
113
- items.push({
114
- type: "reasoning",
115
- ...state.id === void 0 ? {} : { id: state.id },
116
- summary: summary.map((text) => ({
117
- type: "summary_text",
118
- text
119
- })),
120
- ...state.encryptedContent === void 0 ? {} : { encrypted_content: state.encryptedContent }
121
- });
122
- break;
123
- }
102
+ const state = {
103
+ role: message.role === "assistant" ? "assistant" : "user",
104
+ parts: [],
105
+ phase: void 0,
106
+ items,
107
+ dialectMessagePhase
108
+ };
109
+ for (const block of message.content) if (block.type === "text" || block.type === "image" || block.type === "document") appendContent(block, state);
110
+ else appendControl(block, state);
111
+ flushMessage(state);
112
+ }
113
+ function flushMessage(state) {
114
+ if (state.parts.length === 0) return;
115
+ state.items.push({
116
+ type: "message",
117
+ role: state.role,
118
+ content: state.parts,
119
+ ...state.role === "assistant" && state.dialectMessagePhase && state.phase !== void 0 ? { phase: state.phase === "final-answer" ? "final_answer" : state.phase } : {}
120
+ });
121
+ state.parts = [];
122
+ state.phase = void 0;
123
+ }
124
+ function appendContent(block, state) {
125
+ if (block.type === "text" && block.phase !== void 0 && state.phase !== void 0 && state.phase !== block.phase) flushMessage(state);
126
+ if (block.type === "text" && block.phase !== void 0) state.phase = block.phase;
127
+ const part = contentPart(block, state.role);
128
+ if (part !== void 0) state.parts.push(part);
129
+ }
130
+ function appendControl(block, state) {
131
+ switch (block.type) {
132
+ case "reasoning":
133
+ flushMessage(state);
134
+ appendReasoning(block, state.items);
135
+ return;
124
136
  case "tool-call":
125
- flush();
126
- items.push({
137
+ flushMessage(state);
138
+ state.items.push({
127
139
  type: "function_call",
128
140
  call_id: block.id,
129
141
  name: block.name,
130
142
  arguments: block.arguments.length > 0 ? block.arguments : "{}"
131
143
  });
132
- break;
144
+ return;
133
145
  case "tool-result":
134
- flush();
135
- items.push({
146
+ flushMessage(state);
147
+ state.items.push({
136
148
  type: "function_call_output",
137
149
  call_id: block.toolCallId,
138
150
  output: toolResultOutput(block.content)
139
151
  });
140
- break;
152
+ return;
141
153
  case "native-tool-call": {
142
- flush();
143
- const replay = nativeReplayItem(block.providerState);
144
- if (replay !== void 0) items.push(replay);
145
- break;
154
+ flushMessage(state);
155
+ const replay = nativeReplayItem(block);
156
+ if (replay !== void 0) state.items.push(replay);
157
+ return;
146
158
  }
159
+ default: return;
147
160
  }
148
- flush();
149
161
  }
150
- /** Collect the system prompt from the request plus any system-role messages. */
151
- function instructionsOf(request) {
152
- const fromMessages = request.options.messages.filter((message) => message.role === "system").flatMap((message) => message.content).filter((block) => block.type === "text").map((block) => block.text);
153
- return (request.options.system === void 0 ? fromMessages : [request.options.system, ...fromMessages]).join("\n\n");
162
+ function appendReasoning(block, items) {
163
+ const state = reasoningStateOf(block.providerState);
164
+ if (state.id === void 0 && state.encryptedContent === void 0) return;
165
+ const summary = reasoningSummary(state, block.text);
166
+ items.push({
167
+ type: "reasoning",
168
+ ...state.id === void 0 ? {} : { id: state.id },
169
+ summary: summary.map((text) => ({
170
+ type: "summary_text",
171
+ text
172
+ })),
173
+ ...state.encryptedContent === void 0 ? {} : { encrypted_content: state.encryptedContent }
174
+ });
175
+ }
176
+ function reasoningSummary(state, text) {
177
+ if (state.summary !== void 0 && state.summary.length > 0) return state.summary;
178
+ return text.length > 0 ? [text] : [];
154
179
  }
155
- /** Map the neutral tool-choice vocabulary onto this API's. */
180
+
181
+ //#endregion
182
+ //#region src/serialize-options.ts
156
183
  function toolChoiceOf(choice) {
157
184
  if (typeof choice === "string") return choice;
158
185
  if (choice.type === "native") return { type: nativeWireType(choice.name) };
@@ -161,7 +188,6 @@ function toolChoiceOf(choice) {
161
188
  name: choice.name
162
189
  };
163
190
  }
164
- /** Map a tool schema; `strict: false` because caller schemas are not vetted. */
165
191
  function functionTool(tool) {
166
192
  return {
167
193
  type: "function",
@@ -186,7 +212,8 @@ function webSearchTool(tool) {
186
212
  ...tool.userLocation === void 0 ? {} : { user_location: {
187
213
  type: "approximate",
188
214
  ...tool.userLocation
189
- } }
215
+ } },
216
+ ...tool.searchContentTypes === void 0 ? {} : { search_content_types: [...tool.searchContentTypes] }
190
217
  };
191
218
  }
192
219
  function imageGenerationTool(tool) {
@@ -215,86 +242,74 @@ function textControls(format, dialect) {
215
242
  strict: true
216
243
  } };
217
244
  }
218
- function nativeReplayItem(value) {
219
- if (typeof value !== "object" || value === null) return void 0;
220
- const item = value;
221
- if (item.type === "web_search_call") return {
222
- type: "web_search_call",
223
- ...typeof item.id === "string" ? { id: item.id } : {},
224
- ...typeof item.status === "string" ? { status: item.status } : {},
225
- ...item.action === void 0 ? {} : { action: structuredClone(item.action) }
245
+ function toolsOptions(request) {
246
+ const options = request.options;
247
+ const tools = options.tools === void 0 || options.tools.length === 0 ? void 0 : options.tools.map(toolOf);
248
+ return {
249
+ ...tools === void 0 ? {} : {
250
+ tools,
251
+ parallel_tool_calls: true
252
+ },
253
+ ...options.toolChoice === void 0 ? {} : { tool_choice: toolChoiceOf(options.toolChoice) }
226
254
  };
227
- if (item.type === "image_generation_call") return {
228
- type: "image_generation_call",
229
- ...typeof item.id === "string" ? { id: item.id } : {},
230
- ...typeof item.status === "string" ? { status: item.status } : {},
231
- ...typeof item.result === "string" || item.result === null ? { result: item.result } : {}
255
+ }
256
+ function reasoningOptions(request, dialect) {
257
+ const effort = request.options.reasoningEffort;
258
+ if (effort === void 0 && dialect.reasoningSummary === void 0) return {};
259
+ return { reasoning: {
260
+ ...effort === void 0 ? {} : { effort: String(effort) },
261
+ ...dialect.reasoningSummary === void 0 ? {} : { summary: dialect.reasoningSummary }
262
+ } };
263
+ }
264
+ function dialectOptions(request, dialect) {
265
+ const text = textControls(request.options.outputFormat, dialect);
266
+ return {
267
+ ...text === void 0 ? {} : { text },
268
+ ...dialect.store === void 0 ? {} : { store: dialect.store },
269
+ ...dialect.include.length === 0 ? {} : { include: [...dialect.include] },
270
+ ...dialect.promptCacheKey === void 0 ? {} : { prompt_cache_key: dialect.promptCacheKey },
271
+ ...dialect.maxOutputTokens && request.maxTokens !== void 0 ? { max_output_tokens: request.maxTokens } : {}
232
272
  };
233
273
  }
234
- /**
235
- * Build the Responses request body.
236
- * @param request - the resolved request, model, and connection.
237
- * @param dialect - which optional fields this endpoint accepts.
238
- * @returns the wire body, ready to serialize.
239
- */
274
+ function samplingOptions(request, dialect) {
275
+ const options = request.options;
276
+ return {
277
+ ...dialect.sampling && options.temperature !== void 0 ? { temperature: options.temperature } : {},
278
+ ...dialect.sampling && options.topP !== void 0 ? { top_p: options.topP } : {}
279
+ };
280
+ }
281
+
282
+ //#endregion
283
+ //#region src/serialize.ts
284
+ function instructionsOf(request) {
285
+ const fromMessages = request.options.messages.filter((message) => message.role === "system").flatMap((message) => message.content).filter((block) => block.type === "text").map((block) => block.text);
286
+ return (request.options.system === void 0 ? fromMessages : [request.options.system, ...fromMessages]).join("\n\n");
287
+ }
240
288
  function serializeResponsesRequest(request, dialect) {
241
- const { options } = request;
242
289
  const input = [];
243
- for (const message of options.messages) {
290
+ for (const message of request.options.messages) {
244
291
  if (message.role === "system") continue;
245
292
  appendMessage(message, input, dialect.messagePhase === true);
246
293
  }
247
294
  const instructions = instructionsOf(request);
248
- const tools = options.tools === void 0 || options.tools.length === 0 ? void 0 : options.tools.map(toolOf);
249
- const text = textControls(options.outputFormat, dialect);
250
295
  return {
251
- model: options.model,
296
+ model: request.options.model,
252
297
  ...instructions.length === 0 ? {} : { instructions },
253
298
  input,
254
- ...tools === void 0 ? {} : { tools },
255
- ...options.toolChoice === void 0 ? {} : { tool_choice: toolChoiceOf(options.toolChoice) },
256
- ...tools === void 0 ? {} : { parallel_tool_calls: true },
257
- ...options.reasoningEffort === void 0 && dialect.reasoningSummary === void 0 ? {} : { reasoning: {
258
- ...options.reasoningEffort === void 0 ? {} : { effort: String(options.reasoningEffort) },
259
- ...dialect.reasoningSummary === void 0 ? {} : { summary: dialect.reasoningSummary }
260
- } },
261
- ...text === void 0 ? {} : { text },
262
- ...dialect.store === void 0 ? {} : { store: dialect.store },
263
- stream: true,
264
- ...dialect.include.length === 0 ? {} : { include: [...dialect.include] },
265
- ...dialect.promptCacheKey === void 0 ? {} : { prompt_cache_key: dialect.promptCacheKey },
266
- ...dialect.maxOutputTokens && request.maxTokens !== void 0 ? { max_output_tokens: request.maxTokens } : {},
267
- ...dialect.sampling && options.temperature !== void 0 ? { temperature: options.temperature } : {},
268
- ...dialect.sampling && options.topP !== void 0 ? { top_p: options.topP } : {}
299
+ ...toolsOptions(request),
300
+ ...reasoningOptions(request, dialect),
301
+ ...dialectOptions(request, dialect),
302
+ ...samplingOptions(request, dialect),
303
+ stream: true
269
304
  };
270
305
  }
271
306
 
272
307
  //#endregion
273
- //#region src/translate.ts
274
- /**
275
- * Responses API SSE events to the SDK's chunk protocol.
276
- *
277
- * Two design notes worth reading before changing anything here.
278
- *
279
- * First, block correlation is keyed on `item_id`, not on the provider's
280
- * `output_index`. Item ids are stable and present on every delta event, whereas
281
- * index fields vary by event type, so keying on the id and assigning our OWN
282
- * indices in first-seen order is both simpler and closer to what our protocol
283
- * promises.
284
- *
285
- * Second, reasoning state is carried on the reasoning BLOCK
286
- * (`ReasoningBlock.providerState`) rather than in the stream's `replayState`
287
- * envelope. The envelope has to stay positionally aligned with emitted blocks and
288
- * is discarded whole when it drifts; attaching the state to the block it belongs
289
- * to cannot drift, and it survives assembly for free.
290
- *
291
- * @module ai-agent-sdk/providers/responses/translate
292
- */
308
+ //#region src/stream-items.ts
293
309
  function textPhase(value) {
294
310
  if (value === "commentary") return "commentary";
295
311
  if (value === "final_answer") return "final-answer";
296
312
  }
297
- /** Map an output item's wire type onto one of our block types. */
298
313
  function itemKind(type) {
299
314
  switch (type) {
300
315
  case "message": return "text";
@@ -330,7 +345,6 @@ function textAnnotations(item) {
330
345
  });
331
346
  });
332
347
  }
333
- /** Collect the text of a done item's `content` array. */
334
348
  function itemText(item) {
335
349
  const content = item.content;
336
350
  if (!Array.isArray(content)) return "";
@@ -340,7 +354,6 @@ function itemText(item) {
340
354
  return typeof record.text === "string" ? record.text : "";
341
355
  }).join("");
342
356
  }
343
- /** Collect the summary paragraphs of a done reasoning item. */
344
357
  function itemSummary(item) {
345
358
  const summary = item.summary;
346
359
  if (!Array.isArray(summary)) return [];
@@ -350,24 +363,94 @@ function itemSummary(item) {
350
363
  return typeof record.text === "string" ? record.text : "";
351
364
  }).filter((text) => text.length > 0);
352
365
  }
353
- /**
354
- * Normalize usage, honouring the SDK's disjoint-count convention.
355
- *
356
- * This API reports `input_tokens` as the TOTAL input and
357
- * `input_tokens_details.cached_tokens` as a subset of it. Our convention is that
358
- * the three input figures are disjoint and sum to what is billed, so the cached
359
- * portion is subtracted back out here. Skip that and every cost estimate
360
- * double-counts cache hits.
361
- */
366
+ function doneBlock(item, open, imageMediaType) {
367
+ switch (open.kind) {
368
+ case "text": return doneText(item, open);
369
+ case "reasoning": return doneReasoning(item, open);
370
+ case "tool-call": return doneTool(item, open);
371
+ case "native-tool-call": return doneNative(item, open, imageMediaType);
372
+ default: return;
373
+ }
374
+ }
375
+ function doneText(item, open) {
376
+ const text = itemText(item);
377
+ const phase = textPhase(item.phase) ?? open.phase;
378
+ return {
379
+ type: "text",
380
+ text: text.length > 0 ? text : open.text,
381
+ ...phase === void 0 ? {} : { phase },
382
+ ...textAnnotations(item).length === 0 ? {} : { annotations: textAnnotations(item) }
383
+ };
384
+ }
385
+ function doneReasoning(item, open) {
386
+ const summary = itemSummary(item);
387
+ const state = {
388
+ ...typeof item.id === "string" ? { id: item.id } : {},
389
+ ...typeof item.encrypted_content === "string" ? { encryptedContent: item.encrypted_content } : {},
390
+ ...summary.length > 0 ? { summary } : {}
391
+ };
392
+ const streamed = open.reasoningKind === "mixed" ? void 0 : open.reasoningKind;
393
+ const kind = summary.length > 0 ? "summary" : streamed;
394
+ return {
395
+ type: "reasoning",
396
+ text: summary.length > 0 ? summary.join("\n\n") : open.text,
397
+ ...kind === void 0 ? {} : { kind },
398
+ providerState: state
399
+ };
400
+ }
401
+ function doneTool(item, open) {
402
+ const args = typeof item.arguments === "string" && item.arguments.length > 0 ? item.arguments : open.args;
403
+ return {
404
+ type: "tool-call",
405
+ id: ToolCallId(item.call_id ?? open.callId),
406
+ name: item.name ?? open.name,
407
+ arguments: args.length > 0 ? args : "{}"
408
+ };
409
+ }
410
+ function doneNative(item, open, imageMediaType) {
411
+ const content = open.nativeName === "image-generation" && typeof item.result === "string" && item.result.length > 0 ? [{
412
+ type: "image",
413
+ source: {
414
+ kind: "base64",
415
+ mediaType: imageMediaType,
416
+ data: item.result
417
+ }
418
+ }] : [];
419
+ return {
420
+ type: "native-tool-call",
421
+ id: item.id ?? open.callId,
422
+ name: open.nativeName,
423
+ ...typeof item.status === "string" ? { status: item.status } : {},
424
+ ...isJsonValue(item.action) ? { arguments: item.action } : {},
425
+ content,
426
+ providerState: content.length > 0 ? withoutResult(item) : item
427
+ };
428
+ }
429
+ function withoutResult(item) {
430
+ const { result: _result, ...rest } = item;
431
+ return rest;
432
+ }
433
+ function kindToBlockType(kind) {
434
+ return kind;
435
+ }
436
+ function requestedImageMediaType(request) {
437
+ const tool = request?.options.tools?.find((candidate) => "type" in candidate && candidate.type === "native" && candidate.name === "image-generation");
438
+ if (tool === void 0 || !("format" in tool)) return "image/png";
439
+ if (tool.format === "jpeg") return "image/jpeg";
440
+ if (tool.format === "webp") return "image/webp";
441
+ return "image/png";
442
+ }
443
+
444
+ //#endregion
445
+ //#region src/stream-usage.ts
362
446
  function mapUsage(usage) {
363
447
  const source = usage;
364
448
  const details = recordOrUndefined(source.input_tokens_details);
365
- const outputDetails = recordOrUndefined(source.output_tokens_details);
366
449
  const rawInput = source.input_tokens;
367
450
  const outputTokens = source.output_tokens;
368
451
  const cacheRead = details?.cached_tokens;
369
452
  const cacheWrite = details?.cache_write_tokens;
370
- const reasoning = outputDetails?.reasoning_tokens;
453
+ const reasoning = reasoningCounter(source);
371
454
  const totalTokens = source.total_tokens;
372
455
  if (![
373
456
  rawInput,
@@ -380,17 +463,28 @@ function mapUsage(usage) {
380
463
  const normalized = {
381
464
  ...outputTokens === void 0 ? {} : { outputTokens },
382
465
  ...totalTokens === void 0 ? {} : { totalTokens },
383
- ...cacheRead === void 0 || cacheRead === 0 ? {} : { cacheReadTokens: cacheRead },
384
- ...cacheWrite === void 0 || cacheWrite === 0 ? {} : { cacheWriteTokens: cacheWrite },
385
- ...reasoning === void 0 || reasoning === 0 ? {} : { reasoningTokens: reasoning }
466
+ ...omittedCounter(cacheRead) ? {} : { cacheReadTokens: cacheRead },
467
+ ...omittedCounter(cacheWrite) ? {} : { cacheWriteTokens: cacheWrite },
468
+ ...omittedCounter(reasoning) ? {} : { reasoningTokens: reasoning }
386
469
  };
387
- if (rawInput !== void 0) normalized.inputTokens = typeof rawInput === "number" && (cacheRead === void 0 || typeof cacheRead === "number") ? rawInput - (cacheRead ?? 0) : rawInput;
470
+ if (rawInput !== void 0) normalized.inputTokens = disjointInput(rawInput, cacheRead);
388
471
  return normalized;
389
472
  }
390
473
  function recordOrUndefined(value) {
391
474
  return typeof value === "object" && value !== null ? value : void 0;
392
475
  }
393
- /** Codes that mean "do not retry this"; everything else stays retryable. */
476
+ function omittedCounter(value) {
477
+ return value === void 0 || value === 0;
478
+ }
479
+ function disjointInput(rawInput, cacheRead) {
480
+ return typeof rawInput === "number" && (cacheRead === void 0 || typeof cacheRead === "number") ? rawInput - (cacheRead ?? 0) : rawInput;
481
+ }
482
+ function reasoningCounter(source) {
483
+ return recordOrUndefined(source.output_tokens_details)?.reasoning_tokens;
484
+ }
485
+
486
+ //#endregion
487
+ //#region src/stream-errors.ts
394
488
  const TERMINAL_ERROR_CODES = Object.freeze({
395
489
  context_length_exceeded: CONTEXT_WINDOW_EXCEEDED_CODE,
396
490
  insufficient_quota: QUOTA_EXCEEDED_CODE,
@@ -400,7 +494,6 @@ const TERMINAL_ERROR_CODES = Object.freeze({
400
494
  misalignment_policy_violation: MODEL_ERROR_CODES.INVALID_REQUEST,
401
495
  rate_limit_exceeded: MODEL_ERROR_CODES.RATE_LIMIT
402
496
  });
403
- /** Turn a `response.failed` payload into a typed, correctly classified error. */
404
497
  function failedError(response, displayName) {
405
498
  const error = response?.error ?? void 0;
406
499
  const code = error?.code ?? error?.type;
@@ -408,11 +501,6 @@ function failedError(response, displayName) {
408
501
  const mapped = code === void 0 ? void 0 : TERMINAL_ERROR_CODES[code];
409
502
  return new ModelError(message, mapped ?? MODEL_ERROR_CODES.SERVER, {});
410
503
  }
411
- /**
412
- * What little a bare `response.failed` does carry. Under load Codex fails a
413
- * response with no error body at all; the response id and status are then the
414
- * only facts that let an operator match the failure to the provider's side.
415
- */
416
504
  function failureContext(response, code) {
417
505
  return ` (${[
418
506
  code === void 0 ? "no error detail" : `code ${code}`,
@@ -420,250 +508,252 @@ function failureContext(response, code) {
420
508
  ...typeof response?.status === "string" && /^[\w-]{1,32}$/.test(response.status) ? [`status ${response.status}`] : []
421
509
  ].join(", ")})`;
422
510
  }
423
- /** Build the authoritative block for a completed item. */
424
- function doneBlock(item, open, imageMediaType) {
425
- switch (open.kind) {
426
- case "text": {
427
- const text = itemText(item);
428
- const phase = textPhase(item.phase) ?? open.phase;
429
- return {
430
- type: "text",
431
- text: text.length > 0 ? text : open.text,
432
- ...phase === void 0 ? {} : { phase },
433
- ...textAnnotations(item).length === 0 ? {} : { annotations: textAnnotations(item) }
434
- };
435
- }
436
- case "reasoning": {
437
- const summary = itemSummary(item);
438
- const state = {
439
- ...typeof item.id === "string" ? { id: item.id } : {},
440
- ...typeof item.encrypted_content === "string" ? { encryptedContent: item.encrypted_content } : {},
441
- ...summary.length > 0 ? { summary } : {}
442
- };
443
- return {
444
- type: "reasoning",
445
- text: summary.length > 0 ? summary.join("\n\n") : open.text,
446
- providerState: state
447
- };
448
- }
449
- case "tool-call": {
450
- const args = typeof item.arguments === "string" && item.arguments.length > 0 ? item.arguments : open.args;
451
- return {
452
- type: "tool-call",
453
- id: ToolCallId(item.call_id ?? open.callId),
454
- name: item.name ?? open.name,
455
- arguments: args.length > 0 ? args : "{}"
456
- };
457
- }
458
- case "native-tool-call": {
459
- const content = open.nativeName === "image-generation" && typeof item.result === "string" && item.result.length > 0 ? [{
460
- type: "image",
461
- source: {
462
- kind: "base64",
463
- mediaType: imageMediaType,
464
- data: item.result
465
- }
466
- }] : [];
467
- return {
468
- type: "native-tool-call",
469
- id: item.id ?? open.callId,
470
- name: open.nativeName,
471
- ...typeof item.status === "string" ? { status: item.status } : {},
472
- ...isJsonValue(item.action) ? { arguments: item.action } : {},
473
- content,
474
- providerState: item
475
- };
476
- }
511
+
512
+ //#endregion
513
+ //#region src/stream-events.ts
514
+ function* translateEvent(state, event, displayName) {
515
+ switch (event.type) {
516
+ case "response.output_item.added":
517
+ yield* itemAdded(state, event);
518
+ return;
519
+ case "response.output_item.done":
520
+ yield* itemDone(state, event);
521
+ return;
522
+ case "response.completed":
523
+ yield* completed(state, event);
524
+ return;
525
+ case "response.incomplete":
526
+ yield* incomplete(event, displayName);
527
+ return;
528
+ case "response.failed":
529
+ yield* failed(event, displayName);
530
+ return;
531
+ case "error":
532
+ yield* inlineError(event, displayName);
533
+ return;
534
+ default:
535
+ yield* deltaEvent(state, event);
536
+ return;
537
+ }
538
+ }
539
+ function* itemAdded(state, event) {
540
+ const item = event.item;
541
+ const id = item?.id ?? event.item_id;
542
+ const kind = itemKind(item?.type);
543
+ if (item === void 0 || id === void 0 || kind === void 0) return;
544
+ if (state.open.has(id)) return;
545
+ const entry = createOpenItem(state, item, {
546
+ id,
547
+ kind
548
+ });
549
+ state.open.set(id, entry);
550
+ if (kind === "tool-call") state.sawToolCall = true;
551
+ yield {
552
+ type: "block-start",
553
+ index: entry.index,
554
+ blockType: kindToBlockType(kind)
555
+ };
556
+ }
557
+ function* textDelta(state, event) {
558
+ const entry = event.item_id === void 0 ? void 0 : state.open.get(event.item_id);
559
+ if (entry === void 0 || event.delta === void 0) return;
560
+ entry.text += event.delta;
561
+ yield {
562
+ type: "text-delta",
563
+ index: entry.index,
564
+ text: event.delta,
565
+ ...entry.phase === void 0 ? {} : { phase: entry.phase }
566
+ };
567
+ }
568
+ function* summaryDelta(state, event) {
569
+ const entry = event.item_id === void 0 ? void 0 : state.open.get(event.item_id);
570
+ if (entry === void 0 || event.delta === void 0) return;
571
+ const separator = entry.summaryIndex !== void 0 && event.summary_index !== void 0 && event.summary_index !== entry.summaryIndex ? "\n\n" : "";
572
+ entry.summaryIndex = event.summary_index;
573
+ const text = `${separator}${event.delta}`;
574
+ entry.text += text;
575
+ entry.reasoningKind = mergeKind(entry.reasoningKind, "summary");
576
+ yield {
577
+ type: "reasoning-delta",
578
+ index: entry.index,
579
+ text,
580
+ kind: "summary"
581
+ };
582
+ }
583
+ function* reasoningDelta(state, event) {
584
+ const entry = event.item_id === void 0 ? void 0 : state.open.get(event.item_id);
585
+ if (entry === void 0 || event.delta === void 0) return;
586
+ entry.text += event.delta;
587
+ entry.reasoningKind = mergeKind(entry.reasoningKind, "content");
588
+ yield {
589
+ type: "reasoning-delta",
590
+ index: entry.index,
591
+ text: event.delta,
592
+ kind: "content"
593
+ };
594
+ }
595
+ function mergeKind(current, next) {
596
+ return current === void 0 || current === next ? next : "mixed";
597
+ }
598
+ function* toolDelta(state, event) {
599
+ const entry = event.item_id === void 0 ? void 0 : state.open.get(event.item_id);
600
+ if (entry === void 0 || event.delta === void 0) return;
601
+ entry.args += event.delta;
602
+ yield {
603
+ type: "tool-call-delta",
604
+ index: entry.index,
605
+ id: ToolCallId(entry.callId),
606
+ ...entry.name.length > 0 ? { name: entry.name } : {},
607
+ argumentsDelta: event.delta
608
+ };
609
+ }
610
+ function* partialImage(state, event) {
611
+ const itemId = event.item_id;
612
+ const entry = itemId === void 0 ? void 0 : state.open.get(itemId);
613
+ if (itemId === void 0 || entry === void 0 || event.partial_image_b64 === void 0) return;
614
+ yield {
615
+ type: "image-delta",
616
+ index: entry.index,
617
+ itemId,
618
+ data: event.partial_image_b64,
619
+ mediaType: state.imageMediaType,
620
+ ...event.partial_image_index === void 0 ? {} : { partialIndex: event.partial_image_index }
621
+ };
622
+ }
623
+ function* itemDone(state, event) {
624
+ const item = event.item;
625
+ const id = item?.id ?? event.item_id;
626
+ const entry = id === void 0 ? void 0 : state.open.get(id);
627
+ if (item === void 0 || entry === void 0) return;
628
+ const block = doneBlock(item, entry, state.imageMediaType);
629
+ if (block !== void 0) yield {
630
+ type: "block-end",
631
+ index: entry.index,
632
+ block
633
+ };
634
+ }
635
+ function* completed(state, event) {
636
+ const usage = event.response?.usage ?? void 0;
637
+ const mapped = usage === void 0 ? void 0 : mapUsage(usage);
638
+ if (mapped !== void 0) yield {
639
+ type: "usage",
640
+ usage: mapped
641
+ };
642
+ yield {
643
+ type: "finish",
644
+ reason: state.sawToolCall ? { kind: "tool-calls" } : { kind: "stop" }
645
+ };
646
+ }
647
+ function* incomplete(event, displayName) {
648
+ const usage = event.response?.usage ?? void 0;
649
+ const mapped = usage === void 0 ? void 0 : mapUsage(usage);
650
+ if (mapped !== void 0) yield {
651
+ type: "usage",
652
+ usage: mapped
653
+ };
654
+ const why = event.response?.incomplete_details?.reason;
655
+ if (why === "max_output_tokens") {
656
+ yield {
657
+ type: "finish",
658
+ reason: { kind: "max-tokens" }
659
+ };
660
+ return;
661
+ }
662
+ throw new ModelError(`${displayName} returned an incomplete response (${why ?? "unknown reason"})`, MODEL_ERROR_CODES.SERVER);
663
+ }
664
+ function* failed(event, displayName) {
665
+ const usage = event.response?.usage ?? void 0;
666
+ const mapped = usage === void 0 ? void 0 : mapUsage(usage);
667
+ if (mapped !== void 0) yield {
668
+ type: "usage",
669
+ usage: mapped
670
+ };
671
+ throw failedError(event.response, displayName);
672
+ }
673
+ function* inlineError(event, displayName) {
674
+ const inline = {
675
+ ...event.code === void 0 ? {} : { code: event.code },
676
+ ...event.message === void 0 ? {} : { message: event.message }
677
+ };
678
+ throw failedError({ error: inline }, displayName);
679
+ }
680
+ function* deltaEvent(state, event) {
681
+ switch (event.type) {
682
+ case "response.output_text.delta":
683
+ yield* textDelta(state, event);
684
+ return;
685
+ case "response.reasoning_summary_text.delta":
686
+ yield* summaryDelta(state, event);
687
+ return;
688
+ case "response.reasoning_text.delta":
689
+ yield* reasoningDelta(state, event);
690
+ return;
691
+ case "response.function_call_arguments.delta":
692
+ yield* toolDelta(state, event);
693
+ return;
694
+ case "response.image_generation_call.partial_image":
695
+ yield* partialImage(state, event);
696
+ return;
477
697
  default: return;
478
698
  }
479
699
  }
700
+ function createOpenItem(state, item, identity) {
701
+ const { id, kind } = identity;
702
+ return {
703
+ index: state.nextIndex++,
704
+ kind,
705
+ text: "",
706
+ args: "",
707
+ callId: item.call_id ?? id,
708
+ name: item.name ?? "",
709
+ nativeName: nativeName(item.type),
710
+ summaryIndex: void 0,
711
+ phase: textPhase(item.phase),
712
+ reasoningKind: void 0
713
+ };
714
+ }
715
+
716
+ //#endregion
717
+ //#region src/translate.ts
480
718
  /**
481
- * Translate one Responses SSE stream.
719
+ * Responses API SSE events to the SDK's chunk protocol.
482
720
  *
483
- * Owns termination. This API sends no `[DONE]` sentinel: the stream ends on
484
- * `response.completed`, `response.failed`, or `response.incomplete`, and a body
485
- * that ends without one of those was truncated — which is a failure, not an
486
- * empty success, because a truncated turn cannot be trusted.
487
- * @param events - decoded SSE events.
488
- * @param displayName - provider name, used in diagnostics.
489
- * @returns the chunk stream.
721
+ * Two design notes worth reading before changing anything here.
722
+ *
723
+ * First, block correlation is keyed on `item_id`, not on the provider's
724
+ * `output_index`. Item ids are stable and present on every delta event, whereas
725
+ * index fields vary by event type, so keying on the id and assigning our OWN
726
+ * indices in first-seen order is both simpler and closer to what our protocol
727
+ * promises.
728
+ *
729
+ * Second, reasoning state is carried on the reasoning BLOCK
730
+ * (`ReasoningBlock.providerState`) rather than in the stream's `replayState`
731
+ * envelope. The envelope has to stay positionally aligned with emitted blocks and
732
+ * is discarded whole when it drifts; attaching the state to the block it belongs
733
+ * to cannot drift, and it survives assembly for free.
734
+ *
735
+ * @module ai-agent-sdk/providers/responses/translate
490
736
  */
491
737
  async function* translateResponsesStream(events, displayName, request) {
492
- const open = /* @__PURE__ */ new Map();
493
- let nextIndex = 0;
494
- let sawToolCall = false;
495
- let terminated = false;
496
- const imageMediaType = requestedImageMediaType(request);
738
+ const state = {
739
+ open: /* @__PURE__ */ new Map(),
740
+ nextIndex: 0,
741
+ sawToolCall: false,
742
+ imageMediaType: requestedImageMediaType(request)
743
+ };
497
744
  for await (const raw of events) {
498
- let event;
499
- try {
500
- event = JSON.parse(raw.data);
501
- } catch (error) {
502
- throw new ModelError(`${displayName} sent a malformed stream event`, MODEL_ERROR_CODES.MALFORMED_RESPONSE, { cause: error });
503
- }
504
- switch (event.type) {
505
- case "response.output_item.added": {
506
- const item = event.item;
507
- const id = item?.id ?? event.item_id;
508
- const kind = itemKind(item?.type);
509
- if (item === void 0 || id === void 0 || kind === void 0) break;
510
- if (open.has(id)) break;
511
- const entry = {
512
- index: nextIndex++,
513
- kind,
514
- text: "",
515
- args: "",
516
- callId: item.call_id ?? id,
517
- name: item.name ?? "",
518
- nativeName: nativeName(item.type),
519
- summaryIndex: void 0,
520
- phase: textPhase(item.phase)
521
- };
522
- open.set(id, entry);
523
- if (kind === "tool-call") sawToolCall = true;
524
- yield {
525
- type: "block-start",
526
- index: entry.index,
527
- blockType: kindToBlockType(kind)
528
- };
529
- break;
530
- }
531
- case "response.output_text.delta": {
532
- const entry = event.item_id === void 0 ? void 0 : open.get(event.item_id);
533
- if (entry === void 0 || event.delta === void 0) break;
534
- entry.text += event.delta;
535
- yield {
536
- type: "text-delta",
537
- index: entry.index,
538
- text: event.delta,
539
- ...entry.phase === void 0 ? {} : { phase: entry.phase }
540
- };
541
- break;
542
- }
543
- case "response.reasoning_summary_text.delta": {
544
- const entry = event.item_id === void 0 ? void 0 : open.get(event.item_id);
545
- if (entry === void 0 || event.delta === void 0) break;
546
- const separator = entry.summaryIndex !== void 0 && event.summary_index !== void 0 && event.summary_index !== entry.summaryIndex ? "\n\n" : "";
547
- entry.summaryIndex = event.summary_index;
548
- const text = `${separator}${event.delta}`;
549
- entry.text += text;
550
- yield {
551
- type: "reasoning-delta",
552
- index: entry.index,
553
- text
554
- };
555
- break;
556
- }
557
- case "response.reasoning_text.delta": {
558
- const entry = event.item_id === void 0 ? void 0 : open.get(event.item_id);
559
- if (entry === void 0 || event.delta === void 0) break;
560
- entry.text += event.delta;
561
- yield {
562
- type: "reasoning-delta",
563
- index: entry.index,
564
- text: event.delta
565
- };
566
- break;
567
- }
568
- case "response.function_call_arguments.delta": {
569
- const entry = event.item_id === void 0 ? void 0 : open.get(event.item_id);
570
- if (entry === void 0 || event.delta === void 0) break;
571
- entry.args += event.delta;
572
- yield {
573
- type: "tool-call-delta",
574
- index: entry.index,
575
- id: ToolCallId(entry.callId),
576
- ...entry.name.length > 0 ? { name: entry.name } : {},
577
- argumentsDelta: event.delta
578
- };
579
- break;
580
- }
581
- case "response.image_generation_call.partial_image": {
582
- const itemId = event.item_id;
583
- const entry = itemId === void 0 ? void 0 : open.get(itemId);
584
- if (itemId === void 0 || entry === void 0 || event.partial_image_b64 === void 0) break;
585
- yield {
586
- type: "image-delta",
587
- index: entry.index,
588
- itemId,
589
- data: event.partial_image_b64,
590
- mediaType: imageMediaType,
591
- ...event.partial_image_index === void 0 ? {} : { partialIndex: event.partial_image_index }
592
- };
593
- break;
594
- }
595
- case "response.output_item.done": {
596
- const item = event.item;
597
- const id = item?.id ?? event.item_id;
598
- const entry = id === void 0 ? void 0 : open.get(id);
599
- if (item === void 0 || entry === void 0) break;
600
- const block = doneBlock(item, entry, imageMediaType);
601
- if (block !== void 0) yield {
602
- type: "block-end",
603
- index: entry.index,
604
- block
605
- };
606
- break;
607
- }
608
- case "response.completed": {
609
- const usage = event.response?.usage ?? void 0;
610
- const mapped = usage === void 0 ? void 0 : mapUsage(usage);
611
- if (mapped !== void 0) yield {
612
- type: "usage",
613
- usage: mapped
614
- };
615
- yield {
616
- type: "finish",
617
- reason: sawToolCall ? { kind: "tool-calls" } : { kind: "stop" }
618
- };
619
- terminated = true;
620
- return;
621
- }
622
- case "response.incomplete": {
623
- const usage = event.response?.usage ?? void 0;
624
- const mapped = usage === void 0 ? void 0 : mapUsage(usage);
625
- if (mapped !== void 0) yield {
626
- type: "usage",
627
- usage: mapped
628
- };
629
- const why = event.response?.incomplete_details?.reason;
630
- if (why === "max_output_tokens") {
631
- yield {
632
- type: "finish",
633
- reason: { kind: "max-tokens" }
634
- };
635
- terminated = true;
636
- return;
637
- }
638
- throw new ModelError(`${displayName} returned an incomplete response (${why ?? "unknown reason"})`, MODEL_ERROR_CODES.SERVER);
639
- }
640
- case "response.failed": {
641
- const usage = event.response?.usage ?? void 0;
642
- const mapped = usage === void 0 ? void 0 : mapUsage(usage);
643
- if (mapped !== void 0) yield {
644
- type: "usage",
645
- usage: mapped
646
- };
647
- throw failedError(event.response, displayName);
648
- }
649
- case "error": throw failedError({ error: {
650
- ...event.code === void 0 ? {} : { code: event.code },
651
- ...event.message === void 0 ? {} : { message: event.message }
652
- } }, displayName);
653
- }
745
+ const event = parseEvent(raw, displayName);
746
+ yield* translateEvent(state, event, displayName);
747
+ if (event.type === "response.completed" || event.type === "response.incomplete") return;
654
748
  }
655
- if (!terminated) throw new ModelError(`${displayName} stream ended before the response completed`, MODEL_ERROR_CODES.STREAM_CLOSED);
749
+ throw new ModelError(`${displayName} stream ended before the response completed`, MODEL_ERROR_CODES.STREAM_CLOSED);
656
750
  }
657
- /** Our block-type tag for one item kind. */
658
- function kindToBlockType(kind) {
659
- return kind;
660
- }
661
- function requestedImageMediaType(request) {
662
- const tool = request?.options.tools?.find((candidate) => "type" in candidate && candidate.type === "native" && candidate.name === "image-generation");
663
- if (tool === void 0 || !("format" in tool)) return "image/png";
664
- if (tool.format === "jpeg") return "image/jpeg";
665
- if (tool.format === "webp") return "image/webp";
666
- return "image/png";
751
+ function parseEvent(raw, displayName) {
752
+ try {
753
+ return JSON.parse(raw.data);
754
+ } catch (error) {
755
+ throw new ModelError(`${displayName} sent a malformed stream event`, MODEL_ERROR_CODES.MALFORMED_RESPONSE, { cause: error });
756
+ }
667
757
  }
668
758
 
669
759
  //#endregion