@zenmux/rosetta-ai 1.0.32 → 1.0.34

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.
@@ -0,0 +1,591 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ResponsesToInteractionsConverter = void 0;
4
+ const types_1 = require("../interactions/types");
5
+ const usage_1 = require("../interactions/usage");
6
+ const events_1 = require("../interactions/events");
7
+ const steps_1 = require("../interactions/steps");
8
+ const interactions_request_1 = require("./interactions-request");
9
+ /** Direct Responses ↔ Interactions V1 conversion; only standard target content is returned. */
10
+ class ResponsesToInteractionsConverter {
11
+ params;
12
+ request;
13
+ id = "";
14
+ model = "";
15
+ created = Math.floor(Date.now() / 1000);
16
+ sequence = 0;
17
+ started = false;
18
+ finished = false;
19
+ terminal;
20
+ usage;
21
+ steps = new Map();
22
+ seen = new Set();
23
+ convertRequest(params) {
24
+ this.params = structuredClone(params);
25
+ this.model = params.model ?? "";
26
+ const request = (0, interactions_request_1.convertResponsesInteractionRequest)(params);
27
+ this.setEffectiveRequest(request);
28
+ return request;
29
+ }
30
+ /** Gateways call this after applying the effective request defaults, before reading any response. */
31
+ setEffectiveRequest(request) {
32
+ this.request = structuredClone(request);
33
+ }
34
+ getUsage() {
35
+ return this.usage;
36
+ }
37
+ convertResponse(response) {
38
+ this.usage = response.usage && structuredClone(response.usage);
39
+ this.checkStatus(response);
40
+ this.identity(response);
41
+ for (const [index, step] of (response.steps ?? []).entries())
42
+ this.startStep(index, step);
43
+ this.terminal = response;
44
+ const events = this.finishStream();
45
+ const last = events.at(-1);
46
+ if (!("response" in last))
47
+ throw new types_1.InteractionsResponseError("Missing final response");
48
+ return last.response;
49
+ }
50
+ async *convertStream(stream) {
51
+ for await (const event of stream)
52
+ yield* this.convertStreamEvent(event);
53
+ yield* this.finishStream();
54
+ }
55
+ convertStreamEvent(event) {
56
+ if (event.event_id && this.seen.has(event.event_id))
57
+ return [];
58
+ if (event.event_id)
59
+ this.seen.add(event.event_id);
60
+ if (this.finished)
61
+ throw new types_1.InteractionsResponseError("Received event after stream end");
62
+ const usage = (0, events_1.eventUsage)(event);
63
+ const interaction = (0, events_1.eventInteraction)(event);
64
+ const status = (0, events_1.eventStatus)(event);
65
+ if (usage)
66
+ this.usage = { ...this.usage, ...structuredClone(usage) };
67
+ if (event.event_type === "error")
68
+ throw new types_1.InteractionsResponseError(event.error?.message ?? "Interactions stream failed", event.error?.code);
69
+ if (["failed", "cancelled"].includes(status ?? "")) {
70
+ throw new types_1.InteractionsResponseError(interaction?.errors?.[0]?.message ?? `Interaction ${status}`, interaction?.errors?.[0]?.code);
71
+ }
72
+ // A terminal event may precede late cumulative usage metadata. Delay Responses' terminal
73
+ // event until EOF; never report success before the entire upstream stream is validated.
74
+ if (this.terminal) {
75
+ if (event.event_type === "interaction.completed")
76
+ throw new types_1.InteractionsResponseError("Duplicate interaction.completed without event_id");
77
+ if (event.event_type.startsWith("step.") || interaction)
78
+ throw new types_1.InteractionsResponseError("Output event after interaction.completed");
79
+ return [];
80
+ }
81
+ this.identity(interaction, (0, events_1.eventInteractionId)(event));
82
+ const events = [];
83
+ if (!this.started) {
84
+ this.started = true;
85
+ events.push(this.event({ type: "response.created", response: this.response("in_progress") }));
86
+ events.push(this.event({ type: "response.in_progress", response: this.response("in_progress") }));
87
+ }
88
+ if (event.event_type === "step.start") {
89
+ if (!Number.isSafeInteger(event.index) || event.index < 0 || !event.step)
90
+ throw new types_1.InteractionsResponseError("Invalid step.start");
91
+ if (this.steps.has(event.index))
92
+ throw new types_1.InteractionsResponseError("Duplicate step.start without event_id");
93
+ events.push(...this.startStep(event.index, event.step));
94
+ }
95
+ else if (event.event_type === "step.delta") {
96
+ const state = event.index == null ? undefined : this.steps.get(event.index);
97
+ if (!state || state.stopped || !event.delta)
98
+ throw new types_1.InteractionsResponseError("step.delta has no active step");
99
+ const delta = event.delta;
100
+ if (delta.type === "text") {
101
+ if (state.kind !== "output" || state.step.type !== "model_output")
102
+ throw new types_1.InteractionsResponseError("Text delta outside model output");
103
+ const text = delta.text ?? "";
104
+ const content = (state.step.content ??= []);
105
+ const last = content.at(-1);
106
+ if (last?.type === "text")
107
+ last.text = (last.text ?? "") + text;
108
+ else
109
+ content.push({ type: "text", text });
110
+ events.push(...this.appendText(state, text));
111
+ }
112
+ else if (delta.type === "thought_summary") {
113
+ if (state.kind !== "thought" || delta.content?.type !== "text")
114
+ throw new types_1.InteractionsResponseError("Unsupported thought summary delta");
115
+ (state.step.summary ??= []).push(structuredClone(delta.content));
116
+ events.push(...this.appendText(state, delta.content.text ?? ""));
117
+ }
118
+ else if (delta.type === "thought_signature") {
119
+ if (state.kind !== "thought" || typeof delta.signature !== "string")
120
+ throw new types_1.InteractionsResponseError("Invalid thought signature delta");
121
+ state.step.signature = delta.signature;
122
+ }
123
+ else if (delta.type === "arguments_delta") {
124
+ if (state.kind !== "function_call")
125
+ throw new types_1.InteractionsResponseError("Arguments delta outside function call");
126
+ state.hasArgumentDeltas = true;
127
+ state.arguments += delta.arguments ?? "";
128
+ events.push(this.event({
129
+ type: "response.function_call_arguments.delta",
130
+ item_id: state.item.id,
131
+ output_index: state.outputIndex,
132
+ delta: delta.arguments ?? "",
133
+ }));
134
+ }
135
+ else if (delta.type === "text_annotation_delta") {
136
+ if (state.kind !== "output" || state.step.type !== "model_output")
137
+ throw new types_1.InteractionsResponseError("Text annotation outside model output");
138
+ const last = (state.step.content ?? []).filter(part => part.type === "text").at(-1);
139
+ if (!last)
140
+ throw new types_1.InteractionsResponseError("Annotation without text");
141
+ last.annotations = [
142
+ ...(last.annotations ?? []),
143
+ ...structuredClone(delta.annotations ?? []),
144
+ ];
145
+ }
146
+ else if (delta.type === "image" ||
147
+ delta.type === "audio" ||
148
+ delta.type === "video" ||
149
+ delta.type === "document") {
150
+ if (state.kind !== "output" || state.step.type !== "model_output")
151
+ throw new types_1.InteractionsResponseError("Media delta outside model output");
152
+ this.unmapped(delta.type);
153
+ (state.step.content ??= []).push(structuredClone(delta));
154
+ }
155
+ else
156
+ throw new types_1.InteractionsResponseError(`Unsupported Interactions delta: ${delta.type}`);
157
+ }
158
+ else if (event.event_type === "step.stop") {
159
+ const state = event.index == null ? undefined : this.steps.get(event.index);
160
+ if (!state || state.stopped)
161
+ throw new types_1.InteractionsResponseError("step.stop has no active step");
162
+ state.stopped = true;
163
+ // Done events wait for the final snapshot, which may complete signatures/annotations.
164
+ }
165
+ else if (event.event_type === "interaction.completed") {
166
+ if (!event.interaction)
167
+ throw new types_1.InteractionsResponseError("Missing completed interaction");
168
+ this.checkStatus(event.interaction);
169
+ for (const [index, step] of (event.interaction.steps ?? []).entries()) {
170
+ const state = this.steps.get(index);
171
+ if (!state)
172
+ events.push(...this.startStep(index, step));
173
+ else
174
+ events.push(...this.reconcile(state, step));
175
+ }
176
+ this.terminal = structuredClone(event.interaction);
177
+ }
178
+ else if (!["interaction.created", "interaction.status_update", "metadata"].includes(event.event_type) &&
179
+ !usage) {
180
+ throw new types_1.InteractionsResponseError(`Unsupported Interactions event: ${event.event_type}`);
181
+ }
182
+ return events;
183
+ }
184
+ finishStream() {
185
+ if (this.finished)
186
+ return [];
187
+ if (!this.terminal)
188
+ throw new types_1.InteractionsResponseError("Interactions stream ended before interaction.completed");
189
+ const events = [];
190
+ const status = this.terminal.status === "incomplete" ? "incomplete" : "completed";
191
+ if (this.terminal.status === "requires_action" &&
192
+ ![...this.steps.values()].some(state => state.item.type === "function_call"))
193
+ throw new types_1.InteractionsResponseError("requires_action omitted function calls");
194
+ for (const state of this.steps.values()) {
195
+ const { item, outputIndex } = state;
196
+ if (state.kind === "function_call" && item.type === "function_call") {
197
+ const args = state.hasArgumentDeltas
198
+ ? state.arguments
199
+ : JSON.stringify(state.step.arguments ?? {});
200
+ if (status !== "incomplete") {
201
+ const parsed = this.arguments(args);
202
+ if (state.hasArgumentDeltas &&
203
+ state.hasFinalArguments &&
204
+ !(0, steps_1.sameJson)(parsed, state.step.arguments))
205
+ throw new types_1.InteractionsResponseError("Final arguments disagree with streamed arguments");
206
+ state.step.arguments = parsed;
207
+ }
208
+ if (!state.hasArgumentDeltas)
209
+ events.push(this.event({
210
+ type: "response.function_call_arguments.delta",
211
+ item_id: item.id,
212
+ output_index: outputIndex,
213
+ delta: args,
214
+ }));
215
+ item.arguments = args;
216
+ events.push(this.event({
217
+ type: "response.function_call_arguments.done",
218
+ item_id: item.id,
219
+ output_index: outputIndex,
220
+ arguments: args,
221
+ }));
222
+ }
223
+ else if (item.type === "message" && state.textStarted) {
224
+ const part = {
225
+ type: "output_text",
226
+ text: state.text,
227
+ annotations: this.annotations(state.step),
228
+ logprobs: [],
229
+ };
230
+ item.content = [part];
231
+ for (const [annotation_index, annotation] of part.annotations.entries())
232
+ events.push(this.event({
233
+ type: "response.output_text.annotation.added",
234
+ item_id: item.id,
235
+ output_index: outputIndex,
236
+ content_index: 0,
237
+ annotation_index,
238
+ annotation,
239
+ }));
240
+ events.push(this.event({
241
+ type: "response.output_text.done",
242
+ item_id: item.id,
243
+ output_index: outputIndex,
244
+ content_index: 0,
245
+ text: state.text,
246
+ logprobs: [],
247
+ }));
248
+ events.push(this.event({
249
+ type: "response.content_part.done",
250
+ item_id: item.id,
251
+ output_index: outputIndex,
252
+ content_index: 0,
253
+ part,
254
+ }));
255
+ }
256
+ else if (item.type === "reasoning" && state.textStarted) {
257
+ const part = { type: "summary_text", text: state.text };
258
+ item.summary = [part];
259
+ events.push(this.event({
260
+ type: "response.reasoning_summary_text.done",
261
+ item_id: item.id,
262
+ output_index: outputIndex,
263
+ summary_index: 0,
264
+ text: state.text,
265
+ }));
266
+ events.push(this.event({
267
+ type: "response.reasoning_summary_part.done",
268
+ item_id: item.id,
269
+ output_index: outputIndex,
270
+ summary_index: 0,
271
+ part,
272
+ }));
273
+ }
274
+ if (item.type === "message" || item.type === "reasoning" || item.type === "function_call")
275
+ item.status = status;
276
+ events.push(this.event({
277
+ type: "response.output_item.done",
278
+ output_index: outputIndex,
279
+ item: structuredClone(item),
280
+ }));
281
+ }
282
+ this.finished = true;
283
+ events.push(this.event({
284
+ type: status === "incomplete" ? "response.incomplete" : "response.completed",
285
+ response: this.response(status),
286
+ }));
287
+ return events;
288
+ }
289
+ startStep(index, raw) {
290
+ const step = structuredClone(raw);
291
+ const fields = {
292
+ outputIndex: this.steps.size,
293
+ text: "",
294
+ textStarted: false,
295
+ stopped: false,
296
+ };
297
+ let state;
298
+ if (step.type === "function_call") {
299
+ if (!step.id || !step.name)
300
+ throw new types_1.InteractionsResponseError("Function call omitted id or name");
301
+ if ([...this.steps.values()].some(s => s.item.type === "function_call" && s.item.call_id === step.id))
302
+ throw new types_1.InteractionsResponseError("Duplicate function call ID");
303
+ state = {
304
+ ...fields,
305
+ kind: "function_call",
306
+ step,
307
+ arguments: "",
308
+ hasArgumentDeltas: false,
309
+ hasFinalArguments: false,
310
+ item: {
311
+ type: "function_call",
312
+ id: this.newId("fc"),
313
+ call_id: step.id,
314
+ name: step.name,
315
+ arguments: "",
316
+ status: "in_progress",
317
+ },
318
+ };
319
+ }
320
+ else if (step.type === "thought") {
321
+ if (step.summary?.some(part => part.type !== "text"))
322
+ this.unmapped("thought summary content");
323
+ state = {
324
+ ...fields,
325
+ kind: "thought",
326
+ step,
327
+ item: { type: "reasoning", id: this.newId("rs"), summary: [], status: "in_progress" },
328
+ };
329
+ }
330
+ else {
331
+ if (step.type !== "model_output")
332
+ this.unmapped(step.type);
333
+ for (const part of (0, steps_1.interactionStepContent)(step))
334
+ if (part.type !== "text")
335
+ this.unmapped(part.type);
336
+ state = {
337
+ ...fields,
338
+ kind: "output",
339
+ step,
340
+ item: {
341
+ type: "message",
342
+ id: this.newId("msg"),
343
+ role: "assistant",
344
+ status: "in_progress",
345
+ content: [],
346
+ },
347
+ };
348
+ }
349
+ this.steps.set(index, state);
350
+ const events = [
351
+ this.event({
352
+ type: "response.output_item.added",
353
+ output_index: state.outputIndex,
354
+ item: structuredClone(state.item),
355
+ }),
356
+ ];
357
+ const text = this.text(step);
358
+ if (text || (0, steps_1.interactionStepContent)(step).some(part => part.type === "text"))
359
+ events.push(...this.appendText(state, text));
360
+ return events;
361
+ }
362
+ appendText(state, text) {
363
+ const { item, outputIndex } = state;
364
+ const events = [];
365
+ if (!state.textStarted) {
366
+ state.textStarted = true;
367
+ if (item.type === "message")
368
+ events.push(this.event({
369
+ type: "response.content_part.added",
370
+ item_id: item.id,
371
+ output_index: outputIndex,
372
+ content_index: 0,
373
+ part: { type: "output_text", text: "", annotations: [], logprobs: [] },
374
+ }));
375
+ else if (item.type === "reasoning")
376
+ events.push(this.event({
377
+ type: "response.reasoning_summary_part.added",
378
+ item_id: item.id,
379
+ output_index: outputIndex,
380
+ summary_index: 0,
381
+ part: { type: "summary_text", text: "" },
382
+ }));
383
+ }
384
+ state.text += text;
385
+ if (item.type === "message")
386
+ events.push(this.event({
387
+ type: "response.output_text.delta",
388
+ item_id: item.id,
389
+ output_index: outputIndex,
390
+ content_index: 0,
391
+ delta: text,
392
+ logprobs: [],
393
+ }));
394
+ else if (item.type === "reasoning")
395
+ events.push(this.event({
396
+ type: "response.reasoning_summary_text.delta",
397
+ item_id: item.id,
398
+ output_index: outputIndex,
399
+ summary_index: 0,
400
+ delta: text,
401
+ }));
402
+ return events;
403
+ }
404
+ reconcile(state, step) {
405
+ (0, steps_1.validateFinalStep)(state.step, step);
406
+ if (state.kind === "function_call" && step.type === "function_call") {
407
+ state.step = { ...state.step, ...structuredClone(step) };
408
+ state.hasFinalArguments = step.arguments != null;
409
+ return [];
410
+ }
411
+ if (state.kind === "thought" && step.type === "thought") {
412
+ state.step = { ...state.step, ...structuredClone(step) };
413
+ }
414
+ else if (state.kind === "output" &&
415
+ step.type !== "thought" &&
416
+ step.type !== "function_call") {
417
+ for (const part of (0, steps_1.interactionStepContent)(step))
418
+ if (part.type !== "text")
419
+ this.unmapped(part.type);
420
+ // Only model/user output has content to accumulate; other native steps are opaque.
421
+ if (state.step.type === "model_output" && step.type === "model_output")
422
+ state.step = { ...state.step, ...structuredClone(step) };
423
+ else if (state.step.type === "user_input" && step.type === "user_input")
424
+ state.step = { ...state.step, ...structuredClone(step) };
425
+ else
426
+ Object.assign(state.step, structuredClone(step));
427
+ }
428
+ const text = this.text(state.step);
429
+ if (!text.startsWith(state.text))
430
+ throw new types_1.InteractionsResponseError("Final output disagrees with streamed text");
431
+ const events = text.length > state.text.length ? this.appendText(state, text.slice(state.text.length)) : [];
432
+ return events;
433
+ }
434
+ response(status) {
435
+ const p = this.params;
436
+ return {
437
+ id: this.id,
438
+ object: "response",
439
+ created_at: this.created,
440
+ model: this.model,
441
+ status,
442
+ output: status === "in_progress" ? [] : [...this.steps.values()].map(s => structuredClone(s.item)),
443
+ output_text: status === "in_progress"
444
+ ? ""
445
+ : [...this.steps.values()]
446
+ .filter(s => s.item.type === "message")
447
+ .map(s => s.text)
448
+ .join(""),
449
+ error: null,
450
+ incomplete_details: null,
451
+ instructions: this.request?.system_instruction ?? null,
452
+ metadata: this.request?.labels ?? {},
453
+ temperature: null,
454
+ top_p: null,
455
+ max_output_tokens: this.request?.generation_config?.max_output_tokens ?? null,
456
+ previous_response_id: null,
457
+ parallel_tool_calls: p?.parallel_tool_calls ?? true,
458
+ ...this.responseConfig(),
459
+ truncation: p?.truncation ?? "disabled",
460
+ store: this.request?.store ?? true,
461
+ background: false,
462
+ access_programs: null,
463
+ usage: status === "in_progress" ? null : (0, usage_1.convertInteractionResponseUsage)(this.usage),
464
+ };
465
+ }
466
+ responseConfig() {
467
+ const request = this.request;
468
+ const config = request?.generation_config;
469
+ const choice = config?.tool_choice;
470
+ const format = request?.response_format;
471
+ // Native-only options have no standard echo. Gateways retain the native request.
472
+ const text = format == null ||
473
+ (!Array.isArray(format) && "mime_type" in format && format.mime_type === "text/plain")
474
+ ? { format: { type: "text" } }
475
+ : !Array.isArray(format) &&
476
+ format.type === "text" &&
477
+ "mime_type" in format &&
478
+ format.mime_type === "application/json"
479
+ ? {
480
+ format: "schema" in format && format.schema
481
+ ? {
482
+ type: "json_schema",
483
+ name: this.params?.text?.format?.type === "json_schema"
484
+ ? this.params.text.format.name
485
+ : "response",
486
+ schema: format.schema,
487
+ }
488
+ : { type: "json_object" },
489
+ }
490
+ : undefined;
491
+ return {
492
+ tool_choice: choice == null
493
+ ? "auto"
494
+ : choice === "any"
495
+ ? "required"
496
+ : typeof choice === "object"
497
+ ? choice.allowed_tools?.tools
498
+ ? {
499
+ type: "allowed_tools",
500
+ mode: choice.allowed_tools.mode === "any" ? "required" : "auto",
501
+ tools: choice.allowed_tools.tools.map(name => ({ type: "function", name })),
502
+ }
503
+ : undefined
504
+ : choice === "validated"
505
+ ? undefined
506
+ : choice,
507
+ tools: request?.tools?.every(tool => ["function", "google_search"].includes(tool.type))
508
+ ? request.tools.map(tool => tool.type === "google_search" ? { type: "web_search" } : { ...tool })
509
+ : request?.tools?.length
510
+ ? undefined
511
+ : [],
512
+ text,
513
+ reasoning: config?.thinking_level || config?.thinking_summaries === "auto"
514
+ ? {
515
+ ...(config.thinking_level && { effort: config.thinking_level }),
516
+ ...(config.thinking_summaries === "auto" && { summary: "auto" }),
517
+ }
518
+ : null,
519
+ };
520
+ }
521
+ event(event) {
522
+ return { ...event, sequence_number: this.sequence++ };
523
+ }
524
+ identity(response, id) {
525
+ if (!this.id)
526
+ this.id = response?.id || id || this.newId("resp");
527
+ if (response?.model)
528
+ this.model = response.model;
529
+ const time = response?.created ? Date.parse(response.created) : NaN;
530
+ if (!this.started && Number.isFinite(time))
531
+ this.created = Math.floor(time / 1000);
532
+ }
533
+ newId(prefix) {
534
+ return `${prefix}_${Math.random().toString(36).slice(2)}`;
535
+ }
536
+ checkStatus(response) {
537
+ if (typeof response.id !== "string")
538
+ throw new types_1.InteractionsResponseError("Missing interaction ID");
539
+ if (!["completed", "requires_action", "incomplete"].includes(response.status))
540
+ throw new types_1.InteractionsResponseError(response.errors?.[0]?.message ?? `Unexpected interaction status: ${response.status}`, response.errors?.[0]?.code);
541
+ }
542
+ unmapped(type) {
543
+ throw new types_1.InteractionsResponseError(`Interactions ${type} is not supported by Responses conversion`);
544
+ }
545
+ text(step) {
546
+ return (0, steps_1.interactionStepContent)(step)
547
+ .filter(part => part.type === "text")
548
+ .map(part => part.text ?? "")
549
+ .join("");
550
+ }
551
+ arguments(value) {
552
+ try {
553
+ const parsed = JSON.parse(value);
554
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
555
+ throw new Error();
556
+ return parsed;
557
+ }
558
+ catch {
559
+ throw new types_1.InteractionsResponseError("Incomplete or invalid function arguments in stream");
560
+ }
561
+ }
562
+ annotations(step) {
563
+ let offset = 0;
564
+ return (0, steps_1.interactionStepContent)(step).flatMap(part => {
565
+ if (part.type !== "text")
566
+ return [];
567
+ const text = part.text ?? "";
568
+ const annotations = (part.annotations ?? []).flatMap((annotation) => {
569
+ if (annotation.type !== "url_citation" ||
570
+ !annotation.url ||
571
+ annotation.start_index == null ||
572
+ annotation.end_index == null)
573
+ return [];
574
+ const index = (bytes) => Array.from(new TextDecoder().decode(new TextEncoder().encode(text).slice(0, bytes)))
575
+ .length;
576
+ return [
577
+ {
578
+ type: "url_citation",
579
+ url: annotation.url,
580
+ title: annotation.title ?? annotation.url,
581
+ start_index: offset + index(annotation.start_index),
582
+ end_index: offset + index(annotation.end_index),
583
+ },
584
+ ];
585
+ });
586
+ offset += Array.from(text).length;
587
+ return annotations;
588
+ });
589
+ }
590
+ }
591
+ exports.ResponsesToInteractionsConverter = ResponsesToInteractionsConverter;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zenmux/rosetta-ai",
3
- "version": "1.0.32",
3
+ "version": "1.0.34",
4
4
  "description": "Universal translator between AI provider protocols",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",