@zenmux/rosetta-ai 1.0.5 → 1.0.7

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.
@@ -3,13 +3,65 @@ type RespResponse = OpenAI.Responses.Response;
3
3
  type RespStreamEvent = OpenAI.Responses.ResponseStreamEvent;
4
4
  export declare class ResponsesToChatCompletionConverter {
5
5
  private streamState;
6
+ /**
7
+ * The original Responses request params, stashed during `convertRequest` so
8
+ * the streaming terminal event can echo request-scoped fields onto the
9
+ * `response.completed` / `response.incomplete` payload. Only populated when
10
+ * `convertRequest` ran before streaming (the normal gateway flow).
11
+ */
12
+ private requestParams?;
6
13
  constructor();
7
14
  convertRequest(params: OpenAI.Responses.ResponseCreateParams): OpenAI.Chat.Completions.ChatCompletionCreateParams;
8
- convertResponse(response: OpenAI.ChatCompletion): RespResponse;
15
+ /**
16
+ * Convert a ChatCompletion response back to a Responses Response.
17
+ *
18
+ * @param response The upstream ChatCompletion.
19
+ * @param params Optional original Responses request params. When provided,
20
+ * request-scoped fields (instructions, parallel_tool_calls, tool_choice,
21
+ * tools, reasoning, temperature, text, etc.) are echoed back onto the
22
+ * response — matching the behavior of a gateway that round-trips the
23
+ * request through the Responses API. When omitted, these fields fall back
24
+ * to protocol defaults.
25
+ */
26
+ convertResponse(response: OpenAI.ChatCompletion, params?: OpenAI.Responses.ResponseCreateParams): RespResponse;
27
+ /**
28
+ * Compute the request-scoped field values to echo onto a converted response,
29
+ * mirroring the legacy `toOpenAIRespResponse(params, result)` mapping. Returns
30
+ * protocol defaults when `params` is absent.
31
+ */
32
+ private echoRequestFields;
33
+ /**
34
+ * Map a Responses request tool back to a Responses response tool, preserving
35
+ * function / web_search / custom tools. Mirrors the legacy `toRespTool`.
36
+ */
37
+ private toRespTool;
38
+ /**
39
+ * Compute `output_text` — the concatenation of all `output_text` content
40
+ * parts across the response's message output items, matching the Responses
41
+ * API convention. Returns "" when there are no text parts (e.g. tool-only
42
+ * or refusal-only responses), matching the legacy `toOpenAIRespResponse`
43
+ * default of `output_text: ""`.
44
+ */
45
+ private collectOutputText;
9
46
  convertStream(stream: AsyncIterable<OpenAI.ChatCompletionChunk>): AsyncIterable<RespStreamEvent>;
10
47
  convertStreamChunk(chunk: OpenAI.ChatCompletionChunk): RespStreamEvent[];
48
+ /** Open a message output item and its first content part. */
49
+ private openMessage;
50
+ /**
51
+ * Close the currently open output item, emitting the `*.done` and
52
+ * `response.output_item.done` events. Mirrors the legacy converter's
53
+ * stopReasoning / stopOutputTextRefusal / stopFunctionCallArguments /
54
+ * stopCustomToolCallInput helpers.
55
+ */
56
+ private closeCurrent;
11
57
  private convertInput;
12
58
  private convertInputContent;
59
+ /**
60
+ * Normalize a Responses tool-call output payload to a CC tool message
61
+ * content. A string passes through; an array of input parts is reduced to
62
+ * its `input_text` items as CC text parts. Mirrors the legacy `toToolContent`.
63
+ */
64
+ private toToolContent;
13
65
  private convertTools;
14
66
  private isWebSearch;
15
67
  private convertToolChoice;
@@ -3,11 +3,19 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ResponsesToChatCompletionConverter = void 0;
4
4
  class ResponsesToChatCompletionConverter {
5
5
  streamState;
6
+ /**
7
+ * The original Responses request params, stashed during `convertRequest` so
8
+ * the streaming terminal event can echo request-scoped fields onto the
9
+ * `response.completed` / `response.incomplete` payload. Only populated when
10
+ * `convertRequest` ran before streaming (the normal gateway flow).
11
+ */
12
+ requestParams;
6
13
  constructor() {
7
14
  this.streamState = this.createStreamState();
8
15
  }
9
16
  // --- Request conversion (Responses → CC, forward) ---
10
17
  convertRequest(params) {
18
+ this.requestParams = params;
11
19
  const messages = [];
12
20
  if (params.instructions) {
13
21
  messages.push({ role: "system", content: params.instructions });
@@ -79,10 +87,27 @@ class ResponsesToChatCompletionConverter {
79
87
  result.stream_options = params.stream_options;
80
88
  }
81
89
  }
90
+ else if (params.stream_options?.include_obfuscation != null) {
91
+ // include_obfuscation is meaningful even for non-streaming Responses
92
+ // requests (it governs how the gateway streams back to the client).
93
+ // Forward it so it is not dropped when params.stream is falsy.
94
+ result.stream_options = { include_obfuscation: params.stream_options.include_obfuscation };
95
+ }
82
96
  return result;
83
97
  }
84
98
  // --- Response conversion (CC → Responses, backward) ---
85
- convertResponse(response) {
99
+ /**
100
+ * Convert a ChatCompletion response back to a Responses Response.
101
+ *
102
+ * @param response The upstream ChatCompletion.
103
+ * @param params Optional original Responses request params. When provided,
104
+ * request-scoped fields (instructions, parallel_tool_calls, tool_choice,
105
+ * tools, reasoning, temperature, text, etc.) are echoed back onto the
106
+ * response — matching the behavior of a gateway that round-trips the
107
+ * request through the Responses API. When omitted, these fields fall back
108
+ * to protocol defaults.
109
+ */
110
+ convertResponse(response, params) {
86
111
  const choice = response.choices[0];
87
112
  const msg = choice?.message;
88
113
  const output = [];
@@ -142,28 +167,49 @@ class ResponsesToChatCompletionConverter {
142
167
  });
143
168
  }
144
169
  const status = this.finishReasonToStatus(choice?.finish_reason);
170
+ // Request-scoped fields echoed back onto the response. When `params` is
171
+ // absent, fall back to protocol defaults so behavior matches a gateway
172
+ // that does not round-trip the request.
173
+ const echoed = this.echoRequestFields(params);
145
174
  return {
146
175
  id: response.id,
147
176
  object: "response",
148
177
  created_at: response.created,
149
178
  model: response.model,
150
179
  output,
180
+ output_text: this.collectOutputText(output),
151
181
  status,
152
182
  error: null,
153
183
  incomplete_details: status === "incomplete" ? { reason: "max_output_tokens" } : null,
154
- instructions: null,
184
+ instructions: echoed.instructions,
155
185
  metadata: {},
156
- temperature: null,
157
- top_p: null,
158
- max_output_tokens: null,
159
- previous_response_id: null,
160
- parallel_tool_calls: true,
161
- tool_choice: "auto",
162
- tools: [],
163
- text: { format: { type: "text" } },
164
- reasoning: null,
165
- truncation: null,
186
+ temperature: echoed.temperature,
187
+ top_p: echoed.top_p,
188
+ max_output_tokens: echoed.max_output_tokens,
189
+ previous_response_id: echoed.previous_response_id,
190
+ parallel_tool_calls: echoed.parallel_tool_calls,
191
+ tool_choice: echoed.tool_choice,
192
+ tools: echoed.tools,
193
+ text: echoed.text,
194
+ reasoning: echoed.reasoning,
195
+ truncation: echoed.truncation,
166
196
  user: undefined,
197
+ // Non-standard echoes (top_logprobs / safety_identifier / service_tier)
198
+ // are attached via cast; the Responses Response type does not declare them.
199
+ ...(echoed.top_logprobs !== undefined
200
+ ? { top_logprobs: echoed.top_logprobs }
201
+ : {}),
202
+ ...(echoed.safety_identifier !== undefined
203
+ ? { safety_identifier: echoed.safety_identifier }
204
+ : {}),
205
+ ...(echoed.service_tier !== undefined ? { service_tier: echoed.service_tier } : {}),
206
+ ...(params?.background != null ? { background: params.background } : {}),
207
+ ...(params?.prompt_cache_key !== undefined
208
+ ? { prompt_cache_key: params.prompt_cache_key }
209
+ : {}),
210
+ ...(params?.prompt_cache_retention !== undefined
211
+ ? { prompt_cache_retention: params.prompt_cache_retention }
212
+ : {}),
167
213
  usage: response.usage
168
214
  ? {
169
215
  input_tokens: response.usage.prompt_tokens,
@@ -179,6 +225,103 @@ class ResponsesToChatCompletionConverter {
179
225
  : undefined,
180
226
  };
181
227
  }
228
+ /**
229
+ * Compute the request-scoped field values to echo onto a converted response,
230
+ * mirroring the legacy `toOpenAIRespResponse(params, result)` mapping. Returns
231
+ * protocol defaults when `params` is absent.
232
+ */
233
+ echoRequestFields(params) {
234
+ if (!params) {
235
+ return {
236
+ instructions: null,
237
+ temperature: null,
238
+ top_p: null,
239
+ max_output_tokens: null,
240
+ previous_response_id: null,
241
+ parallel_tool_calls: true,
242
+ tool_choice: "auto",
243
+ tools: [],
244
+ text: { format: { type: "text" } },
245
+ reasoning: null,
246
+ truncation: null,
247
+ };
248
+ }
249
+ const tools = (params.tools ?? [])
250
+ .map(t => this.toRespTool(t))
251
+ .filter(Boolean);
252
+ return {
253
+ instructions: params.instructions ?? null,
254
+ temperature: params.temperature ?? null,
255
+ top_p: params.top_p ?? null,
256
+ max_output_tokens: params.max_output_tokens ?? null,
257
+ previous_response_id: params.previous_response_id ?? null,
258
+ parallel_tool_calls: params.parallel_tool_calls ?? true,
259
+ tool_choice: params.tool_choice ?? "auto",
260
+ tools,
261
+ text: params.text ?? { format: { type: "text" } },
262
+ reasoning: params.reasoning ?? null,
263
+ truncation: params.truncation ?? null,
264
+ top_logprobs: params.top_logprobs,
265
+ safety_identifier: params.safety_identifier,
266
+ // service_tier is normally returned by the upstream model; echo the
267
+ // request's value as a fallback (the legacy converter did the same).
268
+ service_tier: params.service_tier,
269
+ };
270
+ }
271
+ /**
272
+ * Map a Responses request tool back to a Responses response tool, preserving
273
+ * function / web_search / custom tools. Mirrors the legacy `toRespTool`.
274
+ */
275
+ toRespTool(tool) {
276
+ const t = tool;
277
+ if (t.type === "function") {
278
+ return {
279
+ type: "function",
280
+ name: t.name,
281
+ description: t.description,
282
+ parameters: !t.parameters
283
+ ? { additionalProperties: false, type: "object", properties: {}, required: [] }
284
+ : {
285
+ additionalProperties: t.parameters.additionalProperties ?? false,
286
+ type: t.parameters.type ?? "object",
287
+ properties: t.parameters.properties ?? {},
288
+ required: t.parameters.required ?? [],
289
+ },
290
+ strict: t.strict,
291
+ };
292
+ }
293
+ if (t.type === "web_search" ||
294
+ t.type === "web_search_preview" ||
295
+ t.type === "web_search_2025_08_26" ||
296
+ t.type === "web_search_preview_2025_03_11" ||
297
+ t.type === "custom") {
298
+ return t;
299
+ }
300
+ return undefined;
301
+ }
302
+ /**
303
+ * Compute `output_text` — the concatenation of all `output_text` content
304
+ * parts across the response's message output items, matching the Responses
305
+ * API convention. Returns "" when there are no text parts (e.g. tool-only
306
+ * or refusal-only responses), matching the legacy `toOpenAIRespResponse`
307
+ * default of `output_text: ""`.
308
+ */
309
+ collectOutputText(output) {
310
+ let text = "";
311
+ for (const item of output ?? []) {
312
+ if (item.type !== "message")
313
+ continue;
314
+ const content = item.content;
315
+ if (!Array.isArray(content))
316
+ continue;
317
+ for (const part of content) {
318
+ if (part?.type === "output_text" && typeof part.text === "string") {
319
+ text += part.text;
320
+ }
321
+ }
322
+ }
323
+ return text;
324
+ }
182
325
  // --- Stream conversion (CC → Responses, backward) ---
183
326
  async *convertStream(stream) {
184
327
  for await (const chunk of stream) {
@@ -217,111 +360,216 @@ class ResponsesToChatCompletionConverter {
217
360
  return events;
218
361
  }
219
362
  const delta = choice.delta;
220
- // Reasoning delta
363
+ // Reasoning delta — open a reasoning item if not already open.
221
364
  const reasoning = delta?.reasoning || delta?.reasoning_content;
222
365
  if (reasoning) {
223
- if (!state.reasoningStarted) {
224
- state.reasoningStarted = true;
366
+ if (!state.current || state.current.type !== "reasoning") {
367
+ // Close any other open item before starting reasoning.
368
+ events.push(...this.closeCurrent());
369
+ const itemId = `rs_${this.generateId()}`;
370
+ state.current = {
371
+ type: "reasoning",
372
+ itemId,
373
+ outputIndex: state.outputIndex,
374
+ summaryIndex: 0,
375
+ text: "",
376
+ };
225
377
  events.push({
226
378
  type: "response.output_item.added",
227
- item: {
228
- type: "reasoning",
229
- id: `rs_${this.generateId()}`,
230
- summary: [],
231
- },
379
+ item: { type: "reasoning", id: itemId, summary: [] },
232
380
  output_index: state.outputIndex,
233
381
  sequence_number: state.seq++,
234
382
  });
235
383
  events.push({
236
384
  type: "response.reasoning_summary_part.added",
237
- item_id: `rs_${this.generateId()}`,
385
+ item_id: itemId,
238
386
  output_index: state.outputIndex,
239
387
  summary_index: 0,
240
388
  part: { type: "summary_text", text: "" },
241
389
  sequence_number: state.seq++,
242
390
  });
243
391
  }
392
+ state.current.text += reasoning;
244
393
  events.push({
245
394
  type: "response.reasoning_summary_text.delta",
246
- item_id: `rs_${this.generateId()}`,
395
+ item_id: state.current.itemId,
247
396
  output_index: state.outputIndex,
248
397
  summary_index: 0,
249
398
  delta: reasoning,
250
399
  sequence_number: state.seq++,
251
400
  });
252
401
  }
253
- // Tool call start
402
+ // Tool calls — function or custom.
254
403
  if (delta?.tool_calls) {
255
404
  for (const tc of delta.tool_calls) {
256
- if (tc.id && tc.function?.name) {
257
- if (state.reasoningStarted && !state.toolCallStarted) {
258
- state.outputIndex++;
405
+ const isCustom = tc.type === "custom" || tc.custom;
406
+ // A new tool call begins when an id + name arrive.
407
+ if (tc.id && ((tc.function?.name && !isCustom) || (tc.custom?.name && isCustom))) {
408
+ const callId = tc.id;
409
+ const name = isCustom ? tc.custom.name : tc.function.name;
410
+ // Close any open reasoning/message item before starting a tool call.
411
+ if (state.current &&
412
+ state.current.type !== "function_call" &&
413
+ state.current.type !== "custom_tool_call") {
414
+ events.push(...this.closeCurrent());
415
+ }
416
+ // If a tool call of a different type/id is already open, close it.
417
+ if (state.current &&
418
+ ((state.current.type === "function_call" && isCustom) ||
419
+ (state.current.type === "custom_tool_call" && !isCustom) ||
420
+ (state.current.type !== "custom_tool_call" && state.current.type !== "function_call"))) {
421
+ events.push(...this.closeCurrent());
422
+ }
423
+ if (state.current &&
424
+ (state.current.type === "function_call" || state.current.type === "custom_tool_call") &&
425
+ state.current.callId !== callId) {
426
+ events.push(...this.closeCurrent());
259
427
  }
260
- state.toolCallStarted = true;
261
428
  state.toolCallCount++;
262
- events.push({
263
- type: "response.output_item.added",
264
- item: {
429
+ // Tool calls live at output_index = outputIndex + toolCallCount - 1,
430
+ // matching the legacy converter's output_index math.
431
+ const outputIndex = state.outputIndex + state.toolCallCount - 1;
432
+ if (isCustom) {
433
+ const itemId = `ct_${this.generateId()}`;
434
+ state.current = {
435
+ type: "custom_tool_call",
436
+ itemId,
437
+ outputIndex,
438
+ callId,
439
+ name,
440
+ input: "",
441
+ };
442
+ events.push({
443
+ type: "response.output_item.added",
444
+ item: {
445
+ type: "custom_tool_call",
446
+ id: itemId,
447
+ call_id: callId,
448
+ name,
449
+ input: "",
450
+ status: "in_progress",
451
+ },
452
+ output_index: outputIndex,
453
+ sequence_number: state.seq++,
454
+ });
455
+ }
456
+ else {
457
+ const itemId = `fc_${this.generateId()}`;
458
+ state.current = {
265
459
  type: "function_call",
266
- id: `fc_${this.generateId()}`,
267
- call_id: tc.id,
268
- name: tc.function.name,
460
+ itemId,
461
+ outputIndex,
462
+ callId,
463
+ name,
269
464
  arguments: "",
270
- status: "in_progress",
271
- },
272
- output_index: state.outputIndex + state.toolCallCount - 1,
273
- sequence_number: state.seq++,
274
- });
465
+ };
466
+ events.push({
467
+ type: "response.output_item.added",
468
+ item: {
469
+ type: "function_call",
470
+ id: itemId,
471
+ call_id: callId,
472
+ name,
473
+ arguments: "",
474
+ status: "in_progress",
475
+ },
476
+ output_index: outputIndex,
477
+ sequence_number: state.seq++,
478
+ });
479
+ }
275
480
  }
276
- // Tool call arguments delta
277
- if (tc.function?.arguments) {
481
+ // Arguments/input delta.
482
+ if (state.current?.type === "function_call" && tc.function?.arguments) {
483
+ state.current.arguments += tc.function.arguments;
278
484
  events.push({
279
485
  type: "response.function_call_arguments.delta",
280
- item_id: `fc_${this.generateId()}`,
281
- output_index: state.outputIndex + state.toolCallCount - 1,
486
+ item_id: state.current.itemId,
487
+ output_index: state.current.outputIndex,
282
488
  delta: tc.function.arguments,
283
489
  sequence_number: state.seq++,
284
490
  });
285
491
  }
492
+ else if (state.current?.type === "custom_tool_call") {
493
+ const inputDelta = tc.custom?.input ?? tc.function?.arguments ?? "";
494
+ if (inputDelta) {
495
+ state.current.input += inputDelta;
496
+ events.push({
497
+ type: "response.custom_tool_call_input.delta",
498
+ item_id: state.current.itemId,
499
+ output_index: state.current.outputIndex,
500
+ delta: inputDelta,
501
+ sequence_number: state.seq++,
502
+ });
503
+ }
504
+ }
505
+ }
506
+ }
507
+ // Refusal delta.
508
+ const refusalDelta = delta?.refusal;
509
+ if (refusalDelta) {
510
+ if (!state.current || state.current.type !== "message" || state.current.kind !== "refusal") {
511
+ events.push(...this.closeCurrent());
512
+ this.openMessage(state, "refusal", events);
286
513
  }
514
+ const msgCtx = state.current;
515
+ msgCtx.refusal += refusalDelta;
516
+ events.push({
517
+ type: "response.refusal.delta",
518
+ item_id: msgCtx.itemId,
519
+ output_index: msgCtx.outputIndex,
520
+ content_index: msgCtx.contentIndex,
521
+ delta: refusalDelta,
522
+ sequence_number: state.seq++,
523
+ });
287
524
  }
288
- // Text content delta
525
+ // Text content delta.
289
526
  if (delta?.content && delta.content !== "") {
290
- if (!state.messageStarted) {
291
- state.messageStarted = true;
292
- const msgOutputIndex = state.outputIndex + (state.reasoningStarted ? 1 : 0) + state.toolCallCount;
293
- events.push({
294
- type: "response.output_item.added",
295
- item: {
296
- type: "message",
297
- id: `msg_${this.generateId()}`,
298
- role: "assistant",
299
- status: "in_progress",
300
- content: [],
301
- },
302
- output_index: msgOutputIndex,
303
- sequence_number: state.seq++,
304
- });
305
- events.push({
306
- type: "response.content_part.added",
307
- item_id: `msg_${this.generateId()}`,
308
- output_index: msgOutputIndex,
309
- content_index: 0,
310
- part: { type: "output_text", text: "", annotations: [] },
311
- sequence_number: state.seq++,
312
- });
527
+ if (!state.current ||
528
+ state.current.type !== "message" ||
529
+ state.current.kind !== "output_text") {
530
+ events.push(...this.closeCurrent());
531
+ this.openMessage(state, "output_text", events);
313
532
  }
533
+ state.current.outputText += delta.content;
314
534
  events.push({
315
535
  type: "response.output_text.delta",
316
- item_id: `msg_${this.generateId()}`,
317
- output_index: state.outputIndex + (state.reasoningStarted ? 1 : 0) + state.toolCallCount,
318
- content_index: 0,
536
+ item_id: state.current.itemId,
537
+ output_index: state.current.outputIndex,
538
+ content_index: state.current.contentIndex,
319
539
  delta: delta.content,
540
+ logprobs: [],
320
541
  sequence_number: state.seq++,
321
542
  });
322
543
  }
323
- // Finish reason
544
+ // Annotations on the message delta.
545
+ const annotations = delta?.annotations;
546
+ if (annotations && state.current?.type === "message") {
547
+ for (const a of annotations) {
548
+ if (a?.type !== "url_citation" || !a.url_citation)
549
+ continue;
550
+ state.annotationIndex++;
551
+ const annotation = {
552
+ type: "url_citation",
553
+ url: a.url_citation.url,
554
+ title: a.url_citation.title,
555
+ start_index: a.url_citation.start_index,
556
+ end_index: a.url_citation.end_index,
557
+ };
558
+ state.current.annotations.push(annotation);
559
+ events.push({
560
+ type: "response.output_text.annotation.added",
561
+ item_id: state.current.itemId,
562
+ output_index: state.current.outputIndex,
563
+ content_index: state.current.contentIndex,
564
+ annotation_index: state.annotationIndex,
565
+ annotation,
566
+ sequence_number: state.seq++,
567
+ });
568
+ }
569
+ }
570
+ // Finish reason — close the open item, then emit the terminal event.
324
571
  if (choice.finish_reason) {
572
+ events.push(...this.closeCurrent());
325
573
  const status = this.finishReasonToStatus(choice.finish_reason);
326
574
  if (chunk.usage) {
327
575
  events.push(...this.emitCompleted(chunk.usage, status));
@@ -332,6 +580,192 @@ class ResponsesToChatCompletionConverter {
332
580
  }
333
581
  return events;
334
582
  }
583
+ /** Open a message output item and its first content part. */
584
+ openMessage(state, kind, events) {
585
+ state.messageStarted = true;
586
+ const itemId = `msg_${this.generateId()}`;
587
+ const msgOutputIndex = state.outputIndex + state.toolCallCount;
588
+ state.current = {
589
+ type: "message",
590
+ itemId,
591
+ outputIndex: msgOutputIndex,
592
+ contentIndex: state.contentIndex,
593
+ kind,
594
+ outputText: "",
595
+ refusal: "",
596
+ annotations: [],
597
+ };
598
+ events.push({
599
+ type: "response.output_item.added",
600
+ item: {
601
+ type: "message",
602
+ id: itemId,
603
+ role: "assistant",
604
+ status: "in_progress",
605
+ content: [],
606
+ },
607
+ output_index: msgOutputIndex,
608
+ sequence_number: state.seq++,
609
+ });
610
+ events.push({
611
+ type: "response.content_part.added",
612
+ item_id: itemId,
613
+ output_index: msgOutputIndex,
614
+ content_index: state.contentIndex,
615
+ part: kind === "output_text"
616
+ ? { type: "output_text", text: "", annotations: [] }
617
+ : { type: "refusal", refusal: "" },
618
+ sequence_number: state.seq++,
619
+ });
620
+ }
621
+ /**
622
+ * Close the currently open output item, emitting the `*.done` and
623
+ * `response.output_item.done` events. Mirrors the legacy converter's
624
+ * stopReasoning / stopOutputTextRefusal / stopFunctionCallArguments /
625
+ * stopCustomToolCallInput helpers.
626
+ */
627
+ closeCurrent() {
628
+ const state = this.streamState;
629
+ const ctx = state.current;
630
+ if (!ctx)
631
+ return [];
632
+ const events = [];
633
+ if (ctx.type === "reasoning") {
634
+ events.push({
635
+ type: "response.reasoning_summary_text.done",
636
+ item_id: ctx.itemId,
637
+ output_index: ctx.outputIndex,
638
+ summary_index: ctx.summaryIndex,
639
+ text: ctx.text,
640
+ sequence_number: state.seq++,
641
+ });
642
+ events.push({
643
+ type: "response.reasoning_summary_part.done",
644
+ item_id: ctx.itemId,
645
+ output_index: ctx.outputIndex,
646
+ summary_index: ctx.summaryIndex,
647
+ part: { type: "summary_text", text: ctx.text },
648
+ sequence_number: state.seq++,
649
+ });
650
+ const item = {
651
+ id: ctx.itemId,
652
+ type: "reasoning",
653
+ summary: [{ type: "summary_text", text: ctx.text }],
654
+ };
655
+ state.output.push(item);
656
+ events.push({
657
+ type: "response.output_item.done",
658
+ item,
659
+ output_index: ctx.outputIndex,
660
+ sequence_number: state.seq++,
661
+ });
662
+ state.outputIndex++;
663
+ }
664
+ else if (ctx.type === "message") {
665
+ const status = "completed";
666
+ const part = ctx.kind === "output_text"
667
+ ? {
668
+ type: "output_text",
669
+ annotations: ctx.annotations,
670
+ logprobs: [],
671
+ text: ctx.outputText,
672
+ }
673
+ : { type: "refusal", refusal: ctx.refusal };
674
+ events.push(ctx.kind === "output_text"
675
+ ? {
676
+ type: "response.output_text.done",
677
+ item_id: ctx.itemId,
678
+ output_index: ctx.outputIndex,
679
+ content_index: ctx.contentIndex,
680
+ text: ctx.outputText,
681
+ logprobs: [],
682
+ sequence_number: state.seq++,
683
+ }
684
+ : {
685
+ type: "response.refusal.done",
686
+ item_id: ctx.itemId,
687
+ output_index: ctx.outputIndex,
688
+ content_index: ctx.contentIndex,
689
+ refusal: ctx.refusal,
690
+ sequence_number: state.seq++,
691
+ });
692
+ events.push({
693
+ type: "response.content_part.done",
694
+ item_id: ctx.itemId,
695
+ output_index: ctx.outputIndex,
696
+ content_index: ctx.contentIndex,
697
+ part,
698
+ sequence_number: state.seq++,
699
+ });
700
+ const item = {
701
+ id: ctx.itemId,
702
+ type: "message",
703
+ role: "assistant",
704
+ status,
705
+ content: [part],
706
+ };
707
+ state.output.push(item);
708
+ events.push({
709
+ type: "response.output_item.done",
710
+ item,
711
+ output_index: ctx.outputIndex,
712
+ sequence_number: state.seq++,
713
+ });
714
+ state.outputIndex++;
715
+ }
716
+ else if (ctx.type === "function_call") {
717
+ events.push({
718
+ type: "response.function_call_arguments.done",
719
+ item_id: ctx.itemId,
720
+ output_index: ctx.outputIndex,
721
+ name: ctx.name,
722
+ arguments: ctx.arguments,
723
+ sequence_number: state.seq++,
724
+ });
725
+ const item = {
726
+ id: ctx.itemId,
727
+ type: "function_call",
728
+ status: "completed",
729
+ call_id: ctx.callId,
730
+ name: ctx.name,
731
+ arguments: ctx.arguments,
732
+ };
733
+ state.output.push(item);
734
+ events.push({
735
+ type: "response.output_item.done",
736
+ item,
737
+ output_index: ctx.outputIndex,
738
+ sequence_number: state.seq++,
739
+ });
740
+ state.outputIndex++;
741
+ }
742
+ else if (ctx.type === "custom_tool_call") {
743
+ events.push({
744
+ type: "response.custom_tool_call_input.done",
745
+ item_id: ctx.itemId,
746
+ output_index: ctx.outputIndex,
747
+ input: ctx.input,
748
+ sequence_number: state.seq++,
749
+ });
750
+ const item = {
751
+ id: ctx.itemId,
752
+ type: "custom_tool_call",
753
+ call_id: ctx.callId,
754
+ name: ctx.name,
755
+ input: ctx.input,
756
+ };
757
+ state.output.push(item);
758
+ events.push({
759
+ type: "response.output_item.done",
760
+ item,
761
+ output_index: ctx.outputIndex,
762
+ sequence_number: state.seq++,
763
+ });
764
+ state.outputIndex++;
765
+ }
766
+ state.current = null;
767
+ return events;
768
+ }
335
769
  // --- Private: request helpers ---
336
770
  convertInput(messages, input) {
337
771
  if (typeof input === "string") {
@@ -418,7 +852,18 @@ class ResponsesToChatCompletionConverter {
418
852
  messages.push({
419
853
  role: "tool",
420
854
  tool_call_id: typed.call_id,
421
- content: typed.output,
855
+ content: this.toToolContent(typed.output),
856
+ });
857
+ }
858
+ else if (typed.type === "custom_tool_call_output") {
859
+ // A custom tool's output. There is no CC "custom tool" message role;
860
+ // surface it as a tool message keyed by the call id, matching the
861
+ // legacy converter's behavior.
862
+ flushToolCalls();
863
+ messages.push({
864
+ role: "tool",
865
+ tool_call_id: typed.call_id,
866
+ content: this.toToolContent(typed.output),
422
867
  });
423
868
  }
424
869
  }
@@ -437,7 +882,11 @@ class ResponsesToChatCompletionConverter {
437
882
  if (part.type === "input_image") {
438
883
  return {
439
884
  type: "image_url",
440
- image_url: { url: part.image_url || part.file_id || "" },
885
+ image_url: {
886
+ url: part.image_url || part.file_id || "",
887
+ // "original" is not a valid CC image_url.detail; omit it to use the default.
888
+ ...(part.detail && part.detail !== "original" ? { detail: part.detail } : {}),
889
+ },
441
890
  };
442
891
  }
443
892
  if (part.type === "input_file") {
@@ -446,13 +895,47 @@ class ResponsesToChatCompletionConverter {
446
895
  file: {
447
896
  file_data: part.file_data || part.file_url || "",
448
897
  filename: part.filename,
449
- file_id: part.file_id,
898
+ file_id: part.file_id || undefined,
899
+ },
900
+ };
901
+ }
902
+ if (part.type === "input_audio") {
903
+ return {
904
+ type: "input_audio",
905
+ input_audio: {
906
+ data: part.input_audio?.data,
907
+ format: part.input_audio?.format,
450
908
  },
451
909
  };
452
910
  }
911
+ // Non-standard extension: ZenMux supports input_video on Responses user
912
+ // input. Map to a video_url content part (not in the SDK types).
913
+ if (part.type === "input_video") {
914
+ const v = part.input_video;
915
+ const url = v?.data ? `data:video/${v?.format ?? "mp4"};base64,${v.data}` : (v?.url ?? "");
916
+ return {
917
+ type: "video_url",
918
+ video_url: { url: url || null },
919
+ };
920
+ }
453
921
  return { type: "text", text: "" };
454
922
  });
455
923
  }
924
+ /**
925
+ * Normalize a Responses tool-call output payload to a CC tool message
926
+ * content. A string passes through; an array of input parts is reduced to
927
+ * its `input_text` items as CC text parts. Mirrors the legacy `toToolContent`.
928
+ */
929
+ toToolContent(output) {
930
+ if (typeof output === "string")
931
+ return output;
932
+ if (!Array.isArray(output))
933
+ return "";
934
+ const parts = output
935
+ .filter((item) => item.type === "input_text")
936
+ .map((item) => ({ type: "text", text: item.text }));
937
+ return parts.length ? parts : "";
938
+ }
456
939
  convertTools(tools) {
457
940
  if (!tools)
458
941
  return { tools: [] };
@@ -471,6 +954,25 @@ class ResponsesToChatCompletionConverter {
471
954
  },
472
955
  });
473
956
  }
957
+ else if (tt.type === "custom") {
958
+ // Responses custom tool → CC custom tool.
959
+ const custom = { name: tt.name };
960
+ if (tt.description != null)
961
+ custom.description = tt.description;
962
+ if (tt.format != null) {
963
+ custom.format =
964
+ tt.format.type === "text"
965
+ ? { type: "text" }
966
+ : {
967
+ type: "grammar",
968
+ grammar: {
969
+ definition: tt.format.definition,
970
+ syntax: tt.format.syntax,
971
+ },
972
+ };
973
+ }
974
+ ccTools.push({ type: "custom", custom });
975
+ }
474
976
  else if (this.isWebSearch(tt)) {
475
977
  webSearchOptions = {};
476
978
  if (tt.search_context_size) {
@@ -501,18 +1003,34 @@ class ResponsesToChatCompletionConverter {
501
1003
  if (c.type === "function" && c.name) {
502
1004
  return { type: "function", function: { name: c.name } };
503
1005
  }
1006
+ if (c.type === "custom" && c.name) {
1007
+ return { type: "custom", custom: { name: c.name } };
1008
+ }
1009
+ if (c.type === "allowed_tools") {
1010
+ return {
1011
+ type: "allowed_tools",
1012
+ allowed_tools: {
1013
+ mode: c.mode,
1014
+ tools: c.tools,
1015
+ },
1016
+ };
1017
+ }
504
1018
  }
505
1019
  return "auto";
506
1020
  }
507
1021
  convertTextFormat(format) {
508
1022
  if (format.type === "json_schema") {
1023
+ const json_schema = {
1024
+ name: format.name || "response",
1025
+ schema: format.schema,
1026
+ strict: format.strict,
1027
+ };
1028
+ // description is optional but supported by the CC json_schema format.
1029
+ if (format.description != null)
1030
+ json_schema.description = format.description;
509
1031
  return {
510
1032
  type: "json_schema",
511
- json_schema: {
512
- name: format.name || "response",
513
- schema: format.schema,
514
- strict: format.strict,
515
- },
1033
+ json_schema,
516
1034
  };
517
1035
  }
518
1036
  if (format.type === "json_object") {
@@ -546,8 +1064,9 @@ class ResponsesToChatCompletionConverter {
546
1064
  seq: 0,
547
1065
  outputIndex: 0,
548
1066
  contentIndex: 0,
549
- toolCallStarted: false,
550
- reasoningStarted: false,
1067
+ annotationIndex: -1,
1068
+ output: [],
1069
+ current: null,
551
1070
  messageStarted: false,
552
1071
  toolCallCount: 0,
553
1072
  };
@@ -582,6 +1101,37 @@ class ResponsesToChatCompletionConverter {
582
1101
  const finalStatus = status ?? "completed";
583
1102
  const resp = this.makeSkeletonResponse();
584
1103
  resp.status = finalStatus;
1104
+ // Carry the output items accumulated during the stream.
1105
+ resp.output = [...state.output];
1106
+ resp.output_text = this.collectOutputText(resp.output);
1107
+ // Echo request-scoped fields onto the terminal response when available.
1108
+ const echoed = this.echoRequestFields(this.requestParams);
1109
+ resp.instructions = echoed.instructions;
1110
+ resp.temperature = echoed.temperature;
1111
+ resp.top_p = echoed.top_p;
1112
+ resp.max_output_tokens = echoed.max_output_tokens;
1113
+ resp.previous_response_id = echoed.previous_response_id;
1114
+ resp.parallel_tool_calls = echoed.parallel_tool_calls;
1115
+ resp.tool_choice = echoed.tool_choice;
1116
+ resp.tools = echoed.tools;
1117
+ resp.text = echoed.text;
1118
+ resp.reasoning = echoed.reasoning;
1119
+ resp.truncation = echoed.truncation;
1120
+ if (echoed.top_logprobs !== undefined)
1121
+ resp.top_logprobs = echoed.top_logprobs;
1122
+ if (echoed.safety_identifier !== undefined)
1123
+ resp.safety_identifier = echoed.safety_identifier;
1124
+ if (echoed.service_tier !== undefined)
1125
+ resp.service_tier = echoed.service_tier;
1126
+ if (this.requestParams?.background != null)
1127
+ resp.background = this.requestParams.background;
1128
+ if (this.requestParams?.prompt_cache_key !== undefined)
1129
+ resp.prompt_cache_key = this.requestParams.prompt_cache_key;
1130
+ if (this.requestParams?.prompt_cache_retention !== undefined)
1131
+ resp.prompt_cache_retention = this.requestParams.prompt_cache_retention;
1132
+ if (finalStatus === "incomplete") {
1133
+ resp.incomplete_details = { reason: "max_output_tokens" };
1134
+ }
585
1135
  if (usage) {
586
1136
  resp.usage = {
587
1137
  input_tokens: usage.prompt_tokens,
@@ -595,6 +1145,15 @@ class ResponsesToChatCompletionConverter {
595
1145
  },
596
1146
  };
597
1147
  }
1148
+ if (finalStatus === "failed") {
1149
+ return [
1150
+ {
1151
+ type: "response.failed",
1152
+ response: resp,
1153
+ sequence_number: state.seq++,
1154
+ },
1155
+ ];
1156
+ }
598
1157
  if (finalStatus === "incomplete") {
599
1158
  return [
600
1159
  {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zenmux/rosetta-ai",
3
- "version": "1.0.5",
3
+ "version": "1.0.7",
4
4
  "description": "Universal translator between AI provider protocols",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",