@zenmux/rosetta-ai 1.0.31 → 1.0.33

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,390 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MessagesToInteractionsConverter = 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 Messages ↔ Interactions V1; only target-protocol content is returned. */
10
+ class MessagesToInteractionsConverter {
11
+ model = "";
12
+ id = "";
13
+ started = false;
14
+ finished = false;
15
+ terminal;
16
+ usage;
17
+ states = new Map();
18
+ seen = new Set();
19
+ convertRequest(params) {
20
+ this.model = params.model;
21
+ return (0, interactions_request_1.convertMessagesInteractionRequest)(params);
22
+ }
23
+ getUsage() {
24
+ return this.usage;
25
+ }
26
+ getStatus() {
27
+ return this.terminal?.status;
28
+ }
29
+ convertResponse(raw) {
30
+ this.usage = structuredClone(raw.usage);
31
+ this.checkStatus(raw);
32
+ this.identity(raw);
33
+ for (const [index, step] of (raw.steps ?? []).entries())
34
+ this.start(index, step);
35
+ this.terminal = structuredClone(raw);
36
+ this.finishStream();
37
+ return this.message(true);
38
+ }
39
+ async *convertStream(stream) {
40
+ for await (const event of stream)
41
+ yield* this.convertStreamEvent(event);
42
+ yield* this.finishStream();
43
+ }
44
+ convertStreamEvent(event) {
45
+ if (event.event_id && this.seen.has(event.event_id))
46
+ return [];
47
+ if (event.event_id)
48
+ this.seen.add(event.event_id);
49
+ if (this.finished)
50
+ fail("Received event after stream end");
51
+ const usage = (0, events_1.eventUsage)(event);
52
+ const interaction = (0, events_1.eventInteraction)(event);
53
+ const status = (0, events_1.eventStatus)(event);
54
+ if (usage)
55
+ this.usage = { ...this.usage, ...structuredClone(usage) };
56
+ if (event.event_type === "error")
57
+ throw new types_1.InteractionsResponseError(event.error?.message ?? "Interactions stream failed", event.error?.code);
58
+ if (["failed", "cancelled"].includes(status ?? ""))
59
+ throw new types_1.InteractionsResponseError(interaction?.errors?.[0]?.message ?? `Interaction ${status}`, interaction?.errors?.[0]?.code);
60
+ if (this.terminal) {
61
+ if (event.event_type === "interaction.completed" ||
62
+ event.event_type.startsWith("step.") ||
63
+ interaction)
64
+ fail("Output event after interaction.completed");
65
+ return [];
66
+ }
67
+ this.identity(interaction, (0, events_1.eventInteractionId)(event));
68
+ const events = [];
69
+ if (!this.started) {
70
+ this.started = true;
71
+ events.push({
72
+ type: "message_start",
73
+ message: {
74
+ ...this.message(false),
75
+ usage: (0, usage_1.convertInteractionMessageUsage)(this.usage) ?? { output_tokens_details: null },
76
+ },
77
+ });
78
+ }
79
+ if (event.event_type === "step.start") {
80
+ if (!Number.isSafeInteger(event.index) || event.index < 0 || !event.step)
81
+ fail("Invalid step.start");
82
+ if (this.states.has(event.index))
83
+ fail("Duplicate step.start without event_id");
84
+ events.push(...this.start(event.index, event.step));
85
+ }
86
+ else if (event.event_type === "step.delta") {
87
+ const state = event.index == null ? undefined : this.states.get(event.index);
88
+ if (!state || state.stopped || !event.delta)
89
+ fail("step.delta has no active step");
90
+ const delta = event.delta;
91
+ if (delta.type === "text") {
92
+ if (state.kind !== "output" || state.step.type !== "model_output")
93
+ fail("Text delta outside model output");
94
+ const content = (state.step.content ??= []), last = content.at(-1);
95
+ if (last?.type === "text")
96
+ last.text = (last.text ?? "") + (delta.text ?? "");
97
+ else
98
+ content.push({ type: "text", text: delta.text ?? "" });
99
+ events.push(this.append(state, delta.text ?? ""));
100
+ }
101
+ else if (delta.type === "thought_summary") {
102
+ if (state.kind !== "thought" || delta.content?.type !== "text")
103
+ fail("Invalid thought summary delta");
104
+ (state.step.summary ??= []).push(structuredClone(delta.content));
105
+ events.push(this.append(state, delta.content.text ?? ""));
106
+ }
107
+ else if (delta.type === "thought_signature") {
108
+ if (state.kind !== "thought" || typeof delta.signature !== "string")
109
+ fail("Invalid thought signature delta");
110
+ state.step.signature = delta.signature;
111
+ }
112
+ else if (delta.type === "arguments_delta") {
113
+ if (state.kind !== "function_call" || typeof delta.arguments !== "string")
114
+ fail("Invalid function arguments delta");
115
+ state.hasDeltas = true;
116
+ state.arguments += delta.arguments;
117
+ events.push({
118
+ type: "content_block_delta",
119
+ index: state.index,
120
+ delta: { type: "input_json_delta", partial_json: delta.arguments },
121
+ });
122
+ }
123
+ else if (delta.type === "text_annotation_delta") {
124
+ if (state.kind !== "output" || state.step.type !== "model_output")
125
+ fail("Annotation without model text");
126
+ const last = state.step.content?.filter(part => part.type === "text").at(-1);
127
+ if (!last)
128
+ fail("Annotation without model text");
129
+ this.unmapped("text annotations");
130
+ last.annotations = [
131
+ ...(last.annotations ?? []),
132
+ ...structuredClone(delta.annotations ?? []),
133
+ ];
134
+ }
135
+ else if (delta.type === "video" ||
136
+ delta.type === "image" ||
137
+ delta.type === "audio" ||
138
+ delta.type === "document") {
139
+ if (state.kind !== "output" || state.step.type !== "model_output")
140
+ fail("Media outside model output");
141
+ this.unmapped(delta.type);
142
+ (state.step.content ??= []).push(structuredClone(delta));
143
+ }
144
+ else
145
+ fail(`Unsupported Interactions delta: ${delta.type}`);
146
+ }
147
+ else if (event.event_type === "step.stop") {
148
+ const state = event.index == null ? undefined : this.states.get(event.index);
149
+ if (!state || state.stopped)
150
+ fail("step.stop has no active step");
151
+ state.stopped = true;
152
+ }
153
+ else if (event.event_type === "interaction.completed") {
154
+ if (!event.interaction)
155
+ fail("Missing completed interaction");
156
+ this.checkStatus(event.interaction);
157
+ for (const [index, step] of (event.interaction.steps ?? []).entries()) {
158
+ const state = this.states.get(index);
159
+ if (state)
160
+ events.push(...this.reconcile(state, step));
161
+ else
162
+ events.push(...this.start(index, step));
163
+ }
164
+ this.terminal = structuredClone(event.interaction);
165
+ }
166
+ else if (!["interaction.created", "interaction.status_update", "metadata"].includes(event.event_type) &&
167
+ !usage)
168
+ fail(`Unsupported Interactions event: ${event.event_type}`);
169
+ return events;
170
+ }
171
+ finishStream() {
172
+ if (this.finished)
173
+ return [];
174
+ if (!this.terminal)
175
+ fail("Interactions stream ended before interaction.completed");
176
+ if (this.terminal.status === "requires_action" &&
177
+ ![...this.states.values()].some(s => s.block.type === "tool_use"))
178
+ fail("requires_action omitted function calls");
179
+ const events = [];
180
+ for (const state of this.states.values()) {
181
+ if (state.kind === "function_call") {
182
+ const argumentsText = state.hasDeltas
183
+ ? state.arguments
184
+ : JSON.stringify(state.step.arguments ?? {});
185
+ const args = parseArguments(argumentsText);
186
+ if (state.hasDeltas && state.finalArguments && !(0, steps_1.sameJson)(args, state.step.arguments))
187
+ fail("Final arguments disagree with streamed arguments");
188
+ state.step.arguments = args;
189
+ state.block.input = args;
190
+ if (!state.hasDeltas)
191
+ events.push({
192
+ type: "content_block_delta",
193
+ index: state.index,
194
+ delta: { type: "input_json_delta", partial_json: argumentsText },
195
+ });
196
+ }
197
+ else if (state.kind === "thought") {
198
+ state.block.signature = state.step.signature ?? "";
199
+ if (state.step.signature)
200
+ events.push({
201
+ type: "content_block_delta",
202
+ index: state.index,
203
+ delta: { type: "signature_delta", signature: state.step.signature },
204
+ });
205
+ }
206
+ events.push({ type: "content_block_stop", index: state.index });
207
+ }
208
+ this.finished = true;
209
+ events.push({
210
+ type: "message_delta",
211
+ delta: {
212
+ stop_reason: this.stopReason(),
213
+ stop_sequence: null,
214
+ container: null,
215
+ stop_details: null,
216
+ },
217
+ usage: (0, usage_1.convertInteractionMessageUsage)(this.usage) ?? { output_tokens_details: null },
218
+ });
219
+ events.push({ type: "message_stop" });
220
+ return events;
221
+ }
222
+ start(index, raw) {
223
+ const step = structuredClone(raw);
224
+ const fields = { index: this.states.size, text: "", stopped: false };
225
+ let state;
226
+ if (step.type === "function_call") {
227
+ if (!step.id || !step.name)
228
+ fail("Function call omitted id or name");
229
+ if ([...this.states.values()].some(s => s.block.type === "tool_use" && s.block.id === step.id))
230
+ fail("Duplicate function call ID");
231
+ state = {
232
+ ...fields,
233
+ kind: "function_call",
234
+ step,
235
+ arguments: "",
236
+ hasDeltas: false,
237
+ finalArguments: step.arguments != null,
238
+ block: {
239
+ type: "tool_use",
240
+ id: step.id,
241
+ name: step.name,
242
+ input: {},
243
+ caller: { type: "direct" },
244
+ },
245
+ };
246
+ }
247
+ else if (step.type === "thought") {
248
+ if (step.summary?.some(part => part.type !== "text"))
249
+ this.unmapped("thought summary");
250
+ state = {
251
+ ...fields,
252
+ kind: "thought",
253
+ step,
254
+ block: { type: "thinking", thinking: "", signature: "" },
255
+ };
256
+ }
257
+ else {
258
+ if (step.type !== "model_output")
259
+ this.unmapped(step.type);
260
+ state = {
261
+ ...fields,
262
+ kind: "output",
263
+ step,
264
+ block: { type: "text", text: "", citations: null },
265
+ };
266
+ }
267
+ this.validateContent(step);
268
+ this.states.set(index, state);
269
+ const events = [
270
+ {
271
+ type: "content_block_start",
272
+ index: state.index,
273
+ content_block: structuredClone(state.block),
274
+ },
275
+ ];
276
+ const text = this.text(step);
277
+ if (text)
278
+ events.push(this.append(state, text));
279
+ return events;
280
+ }
281
+ append(state, text) {
282
+ state.text += text;
283
+ if (state.kind === "thought") {
284
+ state.block.thinking = state.text;
285
+ return {
286
+ type: "content_block_delta",
287
+ index: state.index,
288
+ delta: { type: "thinking_delta", thinking: text },
289
+ };
290
+ }
291
+ if (state.block.type !== "text")
292
+ fail("Text outside a text/thinking block");
293
+ state.block.text = state.text;
294
+ return { type: "content_block_delta", index: state.index, delta: { type: "text_delta", text } };
295
+ }
296
+ reconcile(state, step) {
297
+ (0, steps_1.validateFinalStep)(state.step, step);
298
+ if (state.kind === "function_call" && step.type === "function_call") {
299
+ state.step = { ...state.step, ...structuredClone(step) };
300
+ state.finalArguments = step.arguments != null;
301
+ return [];
302
+ }
303
+ if (state.kind === "thought" && step.type === "thought") {
304
+ state.step = { ...state.step, ...structuredClone(step) };
305
+ }
306
+ else if (state.kind === "output" &&
307
+ step.type !== "thought" &&
308
+ step.type !== "function_call") {
309
+ if (state.step.type === "model_output" && step.type === "model_output")
310
+ state.step = { ...state.step, ...structuredClone(step) };
311
+ else if (state.step.type === "user_input" && step.type === "user_input")
312
+ state.step = { ...state.step, ...structuredClone(step) };
313
+ else
314
+ Object.assign(state.step, structuredClone(step));
315
+ }
316
+ this.validateContent(state.step);
317
+ const text = this.text(state.step);
318
+ if (!text.startsWith(state.text))
319
+ fail("Final output disagrees with streamed text");
320
+ const events = text.length > state.text.length ? [this.append(state, text.slice(state.text.length))] : [];
321
+ return events;
322
+ }
323
+ message(final) {
324
+ return {
325
+ id: this.id,
326
+ type: "message",
327
+ role: "assistant",
328
+ model: this.model,
329
+ content: final ? [...this.states.values()].map(s => structuredClone(s.block)) : [],
330
+ stop_reason: final ? this.stopReason() : null,
331
+ stop_sequence: null,
332
+ container: null,
333
+ diagnostics: null,
334
+ stop_details: null,
335
+ ...(this.usage && { usage: (0, usage_1.convertInteractionMessageUsage)(this.usage) }),
336
+ };
337
+ }
338
+ stopReason() {
339
+ // The native status does not identify why results are incomplete.
340
+ if (this.terminal?.status === "incomplete")
341
+ return null;
342
+ return [...this.states.values()].some(s => s.block.type === "tool_use")
343
+ ? "tool_use"
344
+ : "end_turn";
345
+ }
346
+ identity(raw, id) {
347
+ this.id ||= raw?.id || id || `msg_${Math.random().toString(36).slice(2)}`;
348
+ if (raw?.model)
349
+ this.model = raw.model;
350
+ }
351
+ checkStatus(raw) {
352
+ // Empty strings use the target ID generated by identity(); the field remains required.
353
+ if (typeof raw.id !== "string")
354
+ fail("Missing interaction ID");
355
+ if (!["completed", "requires_action", "incomplete"].includes(raw.status))
356
+ throw new types_1.InteractionsResponseError(raw.errors?.[0]?.message ?? `Unexpected interaction status: ${raw.status}`, raw.errors?.[0]?.code);
357
+ }
358
+ text(step) {
359
+ return (0, steps_1.interactionStepContent)(step)
360
+ .filter(p => p.type === "text")
361
+ .map(p => p.text ?? "")
362
+ .join("");
363
+ }
364
+ validateContent(step) {
365
+ for (const part of (0, steps_1.interactionStepContent)(step)) {
366
+ if (part.type !== "text")
367
+ this.unmapped(part.type);
368
+ if (part.type === "text" && part.annotations?.length)
369
+ this.unmapped("text annotations");
370
+ }
371
+ }
372
+ unmapped(kind) {
373
+ fail(`Interactions ${kind} is not supported by Messages conversion`);
374
+ }
375
+ }
376
+ exports.MessagesToInteractionsConverter = MessagesToInteractionsConverter;
377
+ function parseArguments(value) {
378
+ try {
379
+ const result = JSON.parse(value);
380
+ if (!result || typeof result !== "object" || Array.isArray(result))
381
+ throw new Error();
382
+ return result;
383
+ }
384
+ catch {
385
+ return fail("Incomplete or invalid function arguments in stream");
386
+ }
387
+ }
388
+ function fail(message) {
389
+ throw new types_1.InteractionsResponseError(message);
390
+ }
@@ -1,6 +1,9 @@
1
1
  import type OpenAI from "openai";
2
- type RespResponse = OpenAI.Responses.Response;
3
- type RespStreamEvent = OpenAI.Responses.ResponseStreamEvent;
2
+ import { type ConvertedResponse as RespResponse, type ConvertedResponseStreamEvent as RespStreamEvent } from "./utils";
3
+ type WithResponseServiceTier<T> = T extends unknown ? Omit<T, "service_tier"> & {
4
+ service_tier?: OpenAI.Responses.ResponseCreateParams["service_tier"];
5
+ } : never;
6
+ type ConvertedCCParams = WithResponseServiceTier<OpenAI.Chat.Completions.ChatCompletionCreateParams>;
4
7
  export declare class ResponsesToChatCompletionConverter {
5
8
  private streamState;
6
9
  /**
@@ -11,7 +14,7 @@ export declare class ResponsesToChatCompletionConverter {
11
14
  */
12
15
  private requestParams?;
13
16
  constructor();
14
- convertRequest(params: OpenAI.Responses.ResponseCreateParams): OpenAI.Chat.Completions.ChatCompletionCreateParams;
17
+ convertRequest(params: OpenAI.Responses.ResponseCreateParams): ConvertedCCParams;
15
18
  /**
16
19
  * Convert a ChatCompletion response back to a Responses Response.
17
20
  *
@@ -177,6 +177,7 @@ class ResponsesToChatCompletionConverter {
177
177
  const respResult = {
178
178
  id: response.id,
179
179
  object: "response",
180
+ access_programs: null,
180
181
  created_at: response.created,
181
182
  model: response.model,
182
183
  output,
@@ -225,6 +226,7 @@ class ResponsesToChatCompletionConverter {
225
226
  total_tokens: response.usage.total_tokens,
226
227
  input_tokens_details: {
227
228
  cached_tokens: response.usage.prompt_tokens_details?.cached_tokens ?? 0,
229
+ cache_write_tokens: response.usage.prompt_tokens_details?.cache_write_tokens ?? null,
228
230
  },
229
231
  output_tokens_details: {
230
232
  reasoning_tokens: response.usage.completion_tokens_details?.reasoning_tokens ?? 0,
@@ -1108,6 +1110,7 @@ class ResponsesToChatCompletionConverter {
1108
1110
  return {
1109
1111
  id: this.streamState.id,
1110
1112
  object: "response",
1113
+ access_programs: null,
1111
1114
  created_at: this.streamState.created,
1112
1115
  model: this.streamState.model,
1113
1116
  output: [],
@@ -1177,6 +1180,7 @@ class ResponsesToChatCompletionConverter {
1177
1180
  total_tokens: usage.total_tokens,
1178
1181
  input_tokens_details: {
1179
1182
  cached_tokens: usage.prompt_tokens_details?.cached_tokens ?? 0,
1183
+ cache_write_tokens: usage.prompt_tokens_details?.cache_write_tokens ?? null,
1180
1184
  },
1181
1185
  output_tokens_details: {
1182
1186
  reasoning_tokens: usage.completion_tokens_details?.reasoning_tokens ?? 0,
@@ -1,7 +1,9 @@
1
1
  import type OpenAI from "openai";
2
2
  import type { GenerateContentParameters, GenerateContentResponse } from "@google/genai";
3
- type RespResponse = OpenAI.Responses.Response;
4
- type RespStreamEvent = OpenAI.Responses.ResponseStreamEvent;
3
+ import { type ConvertedResponse as RespResponse, type ConvertedResponseStreamEvent } from "./utils";
4
+ type RespStreamEvent = Exclude<ConvertedResponseStreamEvent, OpenAI.Responses.ResponseFunctionCallArgumentsDoneEvent> | (OpenAI.Responses.ResponseFunctionCallArgumentsDoneEvent & {
5
+ name: string;
6
+ });
5
7
  export declare class ResponsesToGeminiConverter {
6
8
  private streamState;
7
9
  constructor();
@@ -168,6 +168,7 @@ class ResponsesToGeminiConverter {
168
168
  const respResult = {
169
169
  id: response.responseId ?? `resp_${this.generateId()}`,
170
170
  object: "response",
171
+ access_programs: null,
171
172
  created_at: Math.floor(Date.now() / 1000),
172
173
  model: response.modelVersion ?? "",
173
174
  output,
@@ -704,7 +705,10 @@ class ResponsesToGeminiConverter {
704
705
  input_tokens: inputTokens,
705
706
  output_tokens: outputTokens,
706
707
  total_tokens: usage?.totalTokenCount ?? 0,
707
- input_tokens_details: { cached_tokens: usage?.cachedContentTokenCount ?? 0 },
708
+ input_tokens_details: {
709
+ cached_tokens: usage?.cachedContentTokenCount ?? 0,
710
+ cache_write_tokens: null,
711
+ },
708
712
  output_tokens_details: { reasoning_tokens: reasoningTokens },
709
713
  };
710
714
  }
@@ -948,6 +952,7 @@ class ResponsesToGeminiConverter {
948
952
  return {
949
953
  id: this.streamState.id,
950
954
  object: "response",
955
+ access_programs: null,
951
956
  created_at: this.streamState.createdAt,
952
957
  model: this.streamState.model,
953
958
  output: [],
@@ -0,0 +1,7 @@
1
+ import type OpenAI from "openai";
2
+ import { type InteractionCreateParams } from "../interactions/types";
3
+ type Params = OpenAI.Responses.ResponseCreateParams;
4
+ export declare function validateResponsesInteractionsParameters(params: Params): void;
5
+ /** Input ranges let a gateway restore native history/media without reimplementing conversion. */
6
+ export declare function convertResponsesInteractionRequest(params: Params): InteractionCreateParams;
7
+ export {};