@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,376 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ChatCompletionToInteractionsConverter = 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
+ class ChatCompletionToInteractionsConverter {
10
+ id = "";
11
+ model = "";
12
+ created = Math.floor(Date.now() / 1000);
13
+ started = false;
14
+ completed = false;
15
+ steps = new Map();
16
+ eventIds = new Set();
17
+ toolCount = 0;
18
+ textLength = 0;
19
+ usage;
20
+ convertRequest(params) {
21
+ this.model = params.model;
22
+ return (0, interactions_request_1.convertChatCompletionRequest)(params);
23
+ }
24
+ convertResponse(response) {
25
+ this.usage = response.usage && structuredClone(response.usage);
26
+ this.checkStatus(response);
27
+ const text = [];
28
+ const tools = [];
29
+ const annotations = [];
30
+ for (const step of response.steps ?? []) {
31
+ if (step.type === "model_output") {
32
+ for (const part of step.content ?? []) {
33
+ if (part.type !== "text") {
34
+ this.unsupportedContent(part.type);
35
+ continue;
36
+ }
37
+ const offset = Array.from(text.join("")).length;
38
+ const value = part.text ?? "";
39
+ annotations.push(...this.convertAnnotations(part.annotations ?? [], value, offset));
40
+ text.push(value);
41
+ }
42
+ }
43
+ else if (step.type === "function_call") {
44
+ this.checkFunction(step);
45
+ tools.push({
46
+ id: step.id,
47
+ type: "function",
48
+ function: { name: step.name, arguments: JSON.stringify(step.arguments ?? {}) },
49
+ });
50
+ }
51
+ else
52
+ this.validateHiddenStep(step);
53
+ }
54
+ return {
55
+ id: response.id,
56
+ object: "chat.completion",
57
+ created: this.timestamp(response.created),
58
+ model: response.model ?? this.model,
59
+ choices: [
60
+ {
61
+ index: 0,
62
+ finish_reason: this.finishReason(response, tools.length > 0),
63
+ logprobs: null,
64
+ message: {
65
+ role: "assistant",
66
+ content: text.length ? text.join("") : null,
67
+ refusal: null,
68
+ ...(tools.length > 0 && { tool_calls: tools }),
69
+ ...(annotations.length > 0 && { annotations }),
70
+ },
71
+ },
72
+ ],
73
+ ...(response.usage && { usage: (0, usage_1.convertInteractionUsage)(response.usage) }),
74
+ };
75
+ }
76
+ async *convertStream(stream) {
77
+ for await (const event of stream)
78
+ yield* this.convertStreamEvent(event);
79
+ this.finishStream();
80
+ }
81
+ convertStreamEvent(event) {
82
+ if (event.event_id && this.eventIds.has(event.event_id))
83
+ return [];
84
+ if (event.event_id)
85
+ this.eventIds.add(event.event_id);
86
+ if (this.completed)
87
+ throw new types_1.InteractionsResponseError("Received an event after interaction.completed");
88
+ // Usage metadata and step.stop.usage are cumulative snapshots, not deltas.
89
+ const usage = (0, events_1.eventUsage)(event);
90
+ const interaction = (0, events_1.eventInteraction)(event);
91
+ const status = (0, events_1.eventStatus)(event);
92
+ if (usage)
93
+ this.usage = { ...this.usage, ...structuredClone(usage) };
94
+ if (event.event_type === "error")
95
+ throw new types_1.InteractionsResponseError(event.error?.message ?? "Interactions stream failed", event.error?.code);
96
+ if (interaction) {
97
+ this.model = interaction.model ?? this.model;
98
+ this.created = this.timestamp(interaction.created);
99
+ if (["failed", "cancelled"].includes(interaction.status))
100
+ this.checkStatus(interaction, true);
101
+ }
102
+ if (status === "failed" || status === "cancelled")
103
+ throw new types_1.InteractionsResponseError(`Interaction ${status}`);
104
+ if (!this.id) {
105
+ // Vertex may leave the interaction ID empty throughout a stream. Choose the CC ID
106
+ // once; a later native ID must not change chunks already sent to clients.
107
+ this.id = interaction?.id || (0, events_1.eventInteractionId)(event) || `chatcmpl-${this.generateId()}`;
108
+ }
109
+ const chunks = [];
110
+ if (!this.started) {
111
+ this.started = true;
112
+ chunks.push(this.chunk({ role: "assistant", content: "" }));
113
+ }
114
+ if (event.event_type === "step.start") {
115
+ if (event.index == null || !event.step)
116
+ throw new types_1.InteractionsResponseError("Invalid step.start");
117
+ if (this.steps.has(event.index))
118
+ throw new types_1.InteractionsResponseError("Duplicate step.start without event_id");
119
+ chunks.push(...this.startStep(event.index, event.step));
120
+ }
121
+ else if (event.event_type === "step.delta") {
122
+ const state = event.index == null ? undefined : this.steps.get(event.index);
123
+ if (!state || state.stopped || !event.delta)
124
+ throw new types_1.InteractionsResponseError("step.delta has no active step");
125
+ const delta = event.delta;
126
+ if (delta.type === "text") {
127
+ if (state.kind !== "model_output")
128
+ throw new types_1.InteractionsResponseError("Text delta outside model output");
129
+ const text = delta.text ?? "";
130
+ state.text += text;
131
+ this.textLength += Array.from(text).length;
132
+ chunks.push(this.chunk({ content: text }));
133
+ }
134
+ else if (delta.type === "arguments_delta") {
135
+ if (state.kind !== "function_call")
136
+ throw new types_1.InteractionsResponseError("Arguments delta outside function call");
137
+ const value = delta.arguments ?? "";
138
+ state.arguments += value;
139
+ state.sentArguments = true;
140
+ chunks.push(this.chunk({ tool_calls: [{ index: state.toolIndex, function: { arguments: value } }] }));
141
+ }
142
+ else if (delta.type === "text_annotation_delta") {
143
+ if (state.kind !== "model_output")
144
+ throw new types_1.InteractionsResponseError("Text annotation outside model output");
145
+ const annotations = this.convertAnnotations(delta.annotations ?? [], state.text, state.textOffset);
146
+ if (annotations.length)
147
+ chunks.push(this.chunk({ content: "", ...{ annotations } }));
148
+ }
149
+ else if (delta.type === "thought_summary" && state.step.type === "thought") {
150
+ if (delta.content?.type !== "text")
151
+ this.unsupportedContent("thought summary");
152
+ }
153
+ else if (delta.type === "thought_signature" && state.step.type === "thought") {
154
+ state.step.signature = delta.signature;
155
+ }
156
+ else
157
+ this.unsupportedContent(delta.type);
158
+ }
159
+ else if (event.event_type === "step.stop") {
160
+ const state = event.index == null ? undefined : this.steps.get(event.index);
161
+ if (!state || state.stopped)
162
+ throw new types_1.InteractionsResponseError("step.stop has no active step");
163
+ chunks.push(...this.stopStep(state));
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, true);
169
+ // Some servers supply output only in the final snapshot. Never replay steps
170
+ // already delivered as deltas when the final event also includes a snapshot.
171
+ for (const [index, step] of (event.interaction.steps ?? []).entries()) {
172
+ const state = this.steps.get(index);
173
+ if (state)
174
+ (0, steps_1.validateFinalStep)(state.step, step);
175
+ if (!state)
176
+ chunks.push(...this.startStep(index, step));
177
+ else if (step.type === "model_output" && state.kind === "model_output") {
178
+ const text = (step.content ?? [])
179
+ .filter(part => part.type === "text")
180
+ .map(part => part.text ?? "")
181
+ .join("");
182
+ if (!text.startsWith(state.text))
183
+ throw new types_1.InteractionsResponseError("Final output disagrees with streamed text");
184
+ const remaining = text.slice(state.text.length);
185
+ if (remaining) {
186
+ state.text = text;
187
+ this.textLength += Array.from(remaining).length;
188
+ chunks.push(this.chunk({ content: remaining }));
189
+ }
190
+ for (const part of step.content ?? [])
191
+ if (part.type !== "text")
192
+ this.unsupportedContent(part.type);
193
+ }
194
+ else if (step.type === "function_call" &&
195
+ state.kind === "function_call" &&
196
+ !state.stopped) {
197
+ state.step = step;
198
+ }
199
+ }
200
+ for (const state of this.steps.values())
201
+ if (!state.stopped)
202
+ chunks.push(...this.stopStep(state));
203
+ if (event.interaction.status !== "incomplete")
204
+ this.validateToolArguments();
205
+ const final = this.chunk({});
206
+ final.choices[0].finish_reason = this.finishReason(event.interaction, this.toolCount > 0);
207
+ chunks.push(final);
208
+ if (this.usage)
209
+ chunks.push({ ...this.chunk({}), choices: [], usage: (0, usage_1.convertInteractionUsage)(this.usage) });
210
+ this.completed = true;
211
+ }
212
+ else if (!["interaction.created", "interaction.status_update", "metadata"].includes(event.event_type)) {
213
+ this.unsupportedContent(event.event_type);
214
+ }
215
+ return chunks;
216
+ }
217
+ // Adapters call this at EOF so a truncated stream is never reported as success.
218
+ finishStream() {
219
+ if (!this.completed)
220
+ throw new types_1.InteractionsResponseError("Interactions stream ended before interaction.completed");
221
+ }
222
+ getUsage() {
223
+ return this.usage;
224
+ }
225
+ startStep(index, step) {
226
+ if (step.type === "function_call") {
227
+ this.checkFunction(step);
228
+ const state = {
229
+ kind: "function_call",
230
+ step,
231
+ toolIndex: this.toolCount++,
232
+ arguments: "",
233
+ sentArguments: false,
234
+ stopped: false,
235
+ };
236
+ this.steps.set(index, state);
237
+ return [
238
+ this.chunk({
239
+ tool_calls: [
240
+ {
241
+ index: state.toolIndex,
242
+ id: step.id,
243
+ type: "function",
244
+ function: { name: step.name, arguments: "" },
245
+ },
246
+ ],
247
+ }),
248
+ ];
249
+ }
250
+ if (step.type === "model_output") {
251
+ const state = {
252
+ kind: "model_output",
253
+ step,
254
+ text: "",
255
+ textOffset: this.textLength,
256
+ stopped: false,
257
+ };
258
+ this.steps.set(index, state);
259
+ const chunks = [];
260
+ for (const part of step.content ?? []) {
261
+ if (part.type !== "text") {
262
+ this.unsupportedContent(part.type);
263
+ continue;
264
+ }
265
+ const text = part.text ?? "";
266
+ const annotations = this.convertAnnotations(part.annotations ?? [], text, this.textLength);
267
+ state.text += text;
268
+ this.textLength += Array.from(text).length;
269
+ chunks.push(this.chunk({ content: text, ...(annotations.length > 0 && { annotations }) }));
270
+ }
271
+ return chunks;
272
+ }
273
+ this.validateHiddenStep(step);
274
+ this.steps.set(index, { kind: "other", step, stopped: false });
275
+ return [];
276
+ }
277
+ stopStep(state) {
278
+ state.stopped = true;
279
+ if (state.kind !== "function_call")
280
+ return [];
281
+ if (state.sentArguments)
282
+ return [];
283
+ return [
284
+ this.chunk({
285
+ tool_calls: [
286
+ {
287
+ index: state.toolIndex,
288
+ function: { arguments: JSON.stringify(state.step.arguments ?? {}) },
289
+ },
290
+ ],
291
+ }),
292
+ ];
293
+ }
294
+ validateToolArguments() {
295
+ for (const state of this.steps.values()) {
296
+ if (state.kind !== "function_call" || !state.sentArguments)
297
+ continue;
298
+ try {
299
+ const parsed = JSON.parse(state.arguments);
300
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
301
+ throw new Error();
302
+ }
303
+ catch {
304
+ throw new types_1.InteractionsResponseError("Incomplete or invalid function arguments in stream");
305
+ }
306
+ }
307
+ }
308
+ chunk(delta) {
309
+ return {
310
+ id: this.id,
311
+ object: "chat.completion.chunk",
312
+ model: this.model,
313
+ created: this.created,
314
+ choices: [{ index: 0, delta, finish_reason: null, logprobs: null }],
315
+ };
316
+ }
317
+ timestamp(value) {
318
+ const parsed = value ? Date.parse(value) : NaN;
319
+ return Number.isFinite(parsed) ? Math.floor(parsed / 1000) : this.created;
320
+ }
321
+ generateId() {
322
+ return Math.random().toString(36).substring(2, 15);
323
+ }
324
+ checkStatus(response, allowEmptyId = false) {
325
+ if (typeof response.id !== "string" || (!allowEmptyId && !response.id))
326
+ throw new types_1.InteractionsResponseError("Missing interaction ID");
327
+ if (!["completed", "requires_action", "incomplete"].includes(response.status)) {
328
+ throw new types_1.InteractionsResponseError(response.errors?.[0]?.message ?? `Unexpected interaction status: ${response.status}`, response.errors?.[0]?.code);
329
+ }
330
+ }
331
+ finishReason(response, hasTools) {
332
+ if (response.status === "incomplete")
333
+ return "length";
334
+ return hasTools || response.status === "requires_action" ? "tool_calls" : "stop";
335
+ }
336
+ checkFunction(step) {
337
+ if (!step.id || !step.name)
338
+ throw new types_1.InteractionsResponseError("Function call omitted id or name");
339
+ }
340
+ validateHiddenStep(step) {
341
+ // CC exposes search citations in assistant text, but has no reasoning content field.
342
+ if (step.type === "thought") {
343
+ if (step.summary?.some(part => part.type !== "text"))
344
+ this.unsupportedContent("thought summary");
345
+ }
346
+ else if (!["google_search_call", "google_search_result"].includes(step.type)) {
347
+ this.unsupportedContent(step.type);
348
+ }
349
+ }
350
+ unsupportedContent(type) {
351
+ throw new types_1.InteractionsResponseError(`Interactions ${type} output is not supported by Chat Completions conversion`);
352
+ }
353
+ convertAnnotations(annotations, text, offset) {
354
+ return annotations.flatMap(annotation => {
355
+ if (annotation.type !== "url_citation" || annotation.url == null)
356
+ return [];
357
+ if (annotation.start_index == null || annotation.end_index == null)
358
+ return [];
359
+ // Google uses UTF-8 byte offsets; CC uses character offsets. Count Unicode
360
+ // code points rather than treating a Chinese character as three positions.
361
+ const index = (bytes) => Array.from(new TextDecoder().decode(new TextEncoder().encode(text).slice(0, bytes))).length;
362
+ return [
363
+ {
364
+ type: "url_citation",
365
+ url_citation: {
366
+ url: annotation.url,
367
+ title: annotation.title ?? annotation.url,
368
+ start_index: offset + index(annotation.start_index),
369
+ end_index: offset + index(annotation.end_index),
370
+ },
371
+ },
372
+ ];
373
+ });
374
+ }
375
+ }
376
+ exports.ChatCompletionToInteractionsConverter = ChatCompletionToInteractionsConverter;
@@ -2,16 +2,22 @@ import type OpenAI from "openai";
2
2
  type RespResponse = OpenAI.Responses.Response;
3
3
  type RespStreamEvent = OpenAI.Responses.ResponseStreamEvent;
4
4
  type CCParams = OpenAI.Chat.Completions.ChatCompletionCreateParams;
5
+ type ConvertedCCResponse = Omit<OpenAI.ChatCompletion, "service_tier"> & {
6
+ service_tier?: OpenAI.Responses.Response["service_tier"];
7
+ };
8
+ type ConvertedCCChunk = Omit<OpenAI.ChatCompletionChunk, "service_tier"> & {
9
+ service_tier?: OpenAI.Responses.Response["service_tier"];
10
+ };
5
11
  export declare class ChatCompletionToResponsesConverter {
6
12
  private streamState;
7
13
  private legacyFunctionMode;
8
14
  constructor();
9
15
  convertRequest(params: CCParams): OpenAI.Responses.ResponseCreateParams;
10
- convertResponse(response: RespResponse): OpenAI.ChatCompletion;
16
+ convertResponse(response: RespResponse): ConvertedCCResponse;
11
17
  private convertOutputMessages;
12
18
  private convertReasoning;
13
- convertStream(stream: AsyncIterable<RespStreamEvent>): AsyncIterable<OpenAI.ChatCompletionChunk>;
14
- convertStreamEvent(event: RespStreamEvent): OpenAI.ChatCompletionChunk | OpenAI.ChatCompletionChunk[] | null;
19
+ convertStream(stream: AsyncIterable<RespStreamEvent>): AsyncIterable<ConvertedCCChunk>;
20
+ convertStreamEvent(event: RespStreamEvent): ConvertedCCChunk | ConvertedCCChunk[] | null;
15
21
  private convertMessages;
16
22
  private convertReasoningInput;
17
23
  private generateId;
package/dist/index.d.ts CHANGED
@@ -1,4 +1,10 @@
1
1
  export { ChatCompletionToGeminiConverter } from "./chat-completions/gemini";
2
+ export { ChatCompletionToInteractionsConverter } from "./chat-completions/interactions";
3
+ export { validateChatCompletionInteractionsParameters } from "./chat-completions/interactions-request";
4
+ export type { InteractionChatCompletion, InteractionChatCompletionChunk, } from "./chat-completions/interactions";
5
+ export * from "./interactions/types";
6
+ export { convertInteractionUsage } from "./interactions/usage";
7
+ export type { InteractionCompletionUsage } from "./interactions/usage";
2
8
  export { GeminiToChatCompletionConverter } from "./gemini/chat-completions";
3
9
  export { GeminiToMessagesConverter } from "./gemini/messages";
4
10
  export { GeminiToResponsesConverter } from "./gemini/responses";
@@ -6,7 +12,17 @@ export { ChatCompletionToMessagesConverter } from "./chat-completions/messages";
6
12
  export { ChatCompletionToResponsesConverter } from "./chat-completions/responses";
7
13
  export { MessagesToChatCompletionConverter } from "./messages/chat-completions";
8
14
  export { MessagesToGeminiConverter } from "./messages/gemini";
15
+ export { MessagesToInteractionsConverter } from "./messages/interactions";
16
+ export type { InteractionMessage, InteractionMessageStreamEvent } from "./messages/interactions";
17
+ export { validateMessagesInteractionsParameters } from "./messages/interactions-request";
18
+ export { convertInteractionMessageUsage } from "./interactions/usage";
19
+ export type { InteractionMessageUsage } from "./interactions/usage";
9
20
  export { MessagesToResponsesConverter } from "./messages/responses";
10
21
  export { ResponsesToGeminiConverter } from "./responses/gemini";
22
+ export { ResponsesToInteractionsConverter } from "./responses/interactions";
23
+ export type { InteractionResponse, InteractionResponseStreamEvent } from "./responses/interactions";
24
+ export { validateResponsesInteractionsParameters } from "./responses/interactions-request";
25
+ export { convertInteractionResponseUsage } from "./interactions/usage";
26
+ export type { InteractionResponseUsage } from "./interactions/usage";
11
27
  export { ResponsesToMessagesConverter } from "./responses/messages";
12
28
  export { ResponsesToChatCompletionConverter } from "./responses/chat-completions";
package/dist/index.js CHANGED
@@ -1,9 +1,30 @@
1
1
  "use strict";
2
2
  // rosetta-ai: Universal translator between AI provider protocols
3
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
4
+ if (k2 === undefined) k2 = k;
5
+ var desc = Object.getOwnPropertyDescriptor(m, k);
6
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7
+ desc = { enumerable: true, get: function() { return m[k]; } };
8
+ }
9
+ Object.defineProperty(o, k2, desc);
10
+ }) : (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k;
12
+ o[k2] = m[k];
13
+ }));
14
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
15
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
16
+ };
3
17
  Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.ResponsesToChatCompletionConverter = exports.ResponsesToMessagesConverter = exports.ResponsesToGeminiConverter = exports.MessagesToResponsesConverter = exports.MessagesToGeminiConverter = exports.MessagesToChatCompletionConverter = exports.ChatCompletionToResponsesConverter = exports.ChatCompletionToMessagesConverter = exports.GeminiToResponsesConverter = exports.GeminiToMessagesConverter = exports.GeminiToChatCompletionConverter = exports.ChatCompletionToGeminiConverter = void 0;
18
+ exports.ResponsesToChatCompletionConverter = exports.ResponsesToMessagesConverter = exports.convertInteractionResponseUsage = exports.validateResponsesInteractionsParameters = exports.ResponsesToInteractionsConverter = exports.ResponsesToGeminiConverter = exports.MessagesToResponsesConverter = exports.convertInteractionMessageUsage = exports.validateMessagesInteractionsParameters = exports.MessagesToInteractionsConverter = exports.MessagesToGeminiConverter = exports.MessagesToChatCompletionConverter = exports.ChatCompletionToResponsesConverter = exports.ChatCompletionToMessagesConverter = exports.GeminiToResponsesConverter = exports.GeminiToMessagesConverter = exports.GeminiToChatCompletionConverter = exports.convertInteractionUsage = exports.validateChatCompletionInteractionsParameters = exports.ChatCompletionToInteractionsConverter = exports.ChatCompletionToGeminiConverter = void 0;
5
19
  var gemini_1 = require("./chat-completions/gemini");
6
20
  Object.defineProperty(exports, "ChatCompletionToGeminiConverter", { enumerable: true, get: function () { return gemini_1.ChatCompletionToGeminiConverter; } });
21
+ var interactions_1 = require("./chat-completions/interactions");
22
+ Object.defineProperty(exports, "ChatCompletionToInteractionsConverter", { enumerable: true, get: function () { return interactions_1.ChatCompletionToInteractionsConverter; } });
23
+ var interactions_request_1 = require("./chat-completions/interactions-request");
24
+ Object.defineProperty(exports, "validateChatCompletionInteractionsParameters", { enumerable: true, get: function () { return interactions_request_1.validateChatCompletionInteractionsParameters; } });
25
+ __exportStar(require("./interactions/types"), exports);
26
+ var usage_1 = require("./interactions/usage");
27
+ Object.defineProperty(exports, "convertInteractionUsage", { enumerable: true, get: function () { return usage_1.convertInteractionUsage; } });
7
28
  var chat_completions_1 = require("./gemini/chat-completions");
8
29
  Object.defineProperty(exports, "GeminiToChatCompletionConverter", { enumerable: true, get: function () { return chat_completions_1.GeminiToChatCompletionConverter; } });
9
30
  var messages_1 = require("./gemini/messages");
@@ -18,10 +39,22 @@ var chat_completions_2 = require("./messages/chat-completions");
18
39
  Object.defineProperty(exports, "MessagesToChatCompletionConverter", { enumerable: true, get: function () { return chat_completions_2.MessagesToChatCompletionConverter; } });
19
40
  var gemini_2 = require("./messages/gemini");
20
41
  Object.defineProperty(exports, "MessagesToGeminiConverter", { enumerable: true, get: function () { return gemini_2.MessagesToGeminiConverter; } });
42
+ var interactions_2 = require("./messages/interactions");
43
+ Object.defineProperty(exports, "MessagesToInteractionsConverter", { enumerable: true, get: function () { return interactions_2.MessagesToInteractionsConverter; } });
44
+ var interactions_request_2 = require("./messages/interactions-request");
45
+ Object.defineProperty(exports, "validateMessagesInteractionsParameters", { enumerable: true, get: function () { return interactions_request_2.validateMessagesInteractionsParameters; } });
46
+ var usage_2 = require("./interactions/usage");
47
+ Object.defineProperty(exports, "convertInteractionMessageUsage", { enumerable: true, get: function () { return usage_2.convertInteractionMessageUsage; } });
21
48
  var responses_3 = require("./messages/responses");
22
49
  Object.defineProperty(exports, "MessagesToResponsesConverter", { enumerable: true, get: function () { return responses_3.MessagesToResponsesConverter; } });
23
50
  var gemini_3 = require("./responses/gemini");
24
51
  Object.defineProperty(exports, "ResponsesToGeminiConverter", { enumerable: true, get: function () { return gemini_3.ResponsesToGeminiConverter; } });
52
+ var interactions_3 = require("./responses/interactions");
53
+ Object.defineProperty(exports, "ResponsesToInteractionsConverter", { enumerable: true, get: function () { return interactions_3.ResponsesToInteractionsConverter; } });
54
+ var interactions_request_3 = require("./responses/interactions-request");
55
+ Object.defineProperty(exports, "validateResponsesInteractionsParameters", { enumerable: true, get: function () { return interactions_request_3.validateResponsesInteractionsParameters; } });
56
+ var usage_3 = require("./interactions/usage");
57
+ Object.defineProperty(exports, "convertInteractionResponseUsage", { enumerable: true, get: function () { return usage_3.convertInteractionResponseUsage; } });
25
58
  var messages_3 = require("./responses/messages");
26
59
  Object.defineProperty(exports, "ResponsesToMessagesConverter", { enumerable: true, get: function () { return messages_3.ResponsesToMessagesConverter; } });
27
60
  var chat_completions_3 = require("./responses/chat-completions");
@@ -0,0 +1,6 @@
1
+ import type { InteractionEvent, InteractionSnapshot, InteractionUsage } from "./types";
2
+ export declare function eventInteraction(event: InteractionEvent): InteractionSnapshot | undefined;
3
+ export declare function eventInteractionId(event: InteractionEvent): string | undefined;
4
+ export declare function eventStatus(event: InteractionEvent): InteractionSnapshot["status"] | undefined;
5
+ /** Cumulative snapshots only: never add step_usage to the interaction total. */
6
+ export declare function eventUsage(event: InteractionEvent): InteractionUsage | undefined;
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.eventInteraction = eventInteraction;
4
+ exports.eventInteractionId = eventInteractionId;
5
+ exports.eventStatus = eventStatus;
6
+ exports.eventUsage = eventUsage;
7
+ function eventInteraction(event) {
8
+ return "interaction" in event ? event.interaction : undefined;
9
+ }
10
+ function eventInteractionId(event) {
11
+ return "interaction_id" in event ? event.interaction_id : undefined;
12
+ }
13
+ function eventStatus(event) {
14
+ return eventInteraction(event)?.status ?? ("status" in event ? event.status : undefined);
15
+ }
16
+ /** Cumulative snapshots only: never add step_usage to the interaction total. */
17
+ function eventUsage(event) {
18
+ return eventInteraction(event)?.usage ?? event.metadata?.total_usage ?? event.usage;
19
+ }
@@ -0,0 +1,84 @@
1
+ import { type InteractionStartStep, type InteractionStep } from "./types";
2
+ /** Check final-snapshot identity before mutating a protocol-specific stream state. */
3
+ export declare function validateFinalStep(previous: InteractionStartStep, final: InteractionStep): void;
4
+ export declare function interactionStepContent(step: InteractionStartStep): ({
5
+ channels?: number | undefined;
6
+ data?: string | undefined;
7
+ mime_type?: ((string & {}) | "audio/mp3" | "audio/wav" | "audio/aiff" | "audio/aac" | "audio/ogg" | "audio/flac" | "audio/mpeg" | "audio/m4a" | "audio/l16" | "audio/opus" | "audio/alaw" | "audio/mulaw" | "audio/webm") | undefined;
8
+ sample_rate?: number | undefined;
9
+ type: "audio";
10
+ uri?: string | undefined;
11
+ } | {
12
+ data?: string | undefined;
13
+ mime_type?: ((string & {}) | "application/pdf" | "text/csv") | undefined;
14
+ type: "document";
15
+ uri?: string | undefined;
16
+ } | {
17
+ data?: string | undefined;
18
+ mime_type?: ((string & {}) | "image/jpeg" | "image/png" | "image/webp" | "image/heic" | "image/heif" | "image/gif" | "image/bmp" | "image/tiff") | undefined;
19
+ resolution?: ("low" | "medium" | "high" | (string & {}) | "ultra_high") | undefined;
20
+ type: "image";
21
+ uri?: string | undefined;
22
+ } | {
23
+ annotations?: Array<{
24
+ custom_metadata?: {
25
+ [k: string]: any;
26
+ } | undefined;
27
+ document_uri?: string | undefined;
28
+ end_index?: number | undefined;
29
+ file_name?: string | undefined;
30
+ media_id?: string | undefined;
31
+ page_number?: number | undefined;
32
+ source?: string | undefined;
33
+ start_index?: number | undefined;
34
+ type: "file_citation";
35
+ } | {
36
+ end_index?: number | undefined;
37
+ name?: string | undefined;
38
+ place_id?: string | undefined;
39
+ review_snippets?: Array<{
40
+ review_id?: string | undefined;
41
+ title?: string | undefined;
42
+ url?: string | undefined;
43
+ }> | undefined;
44
+ start_index?: number | undefined;
45
+ type: "place_citation";
46
+ url?: string | undefined;
47
+ } | {
48
+ end_index?: number | undefined;
49
+ speaker?: string | undefined;
50
+ start_index?: number | undefined;
51
+ style?: string | undefined;
52
+ type: "speech_metadata";
53
+ } | {
54
+ end_index?: number | undefined;
55
+ start_index?: number | undefined;
56
+ title?: string | undefined;
57
+ type: "url_citation";
58
+ url?: string | undefined;
59
+ } | {
60
+ end_index?: number | undefined;
61
+ end_offset?: string | undefined;
62
+ speaker?: string | undefined;
63
+ start_index?: number | undefined;
64
+ start_offset?: string | undefined;
65
+ text?: string | undefined;
66
+ type: "word_info";
67
+ }> | undefined;
68
+ text: string;
69
+ type: "text";
70
+ } | {
71
+ data?: string | undefined;
72
+ mime_type?: ((string & {}) | "video/mp4" | "video/mpeg" | "video/webm" | "video/mpg" | "video/mov" | "video/avi" | "video/x-flv" | "video/wmv" | "video/3gpp") | undefined;
73
+ name?: string | undefined;
74
+ processing?: {
75
+ end_offset?: string | undefined;
76
+ fps?: number | undefined;
77
+ start_offset?: string | undefined;
78
+ type: "static";
79
+ } | ((string & {}) | "static" | "agentic") | undefined;
80
+ resolution?: ("low" | "medium" | "high" | (string & {}) | "ultra_high") | undefined;
81
+ type: "video";
82
+ uri?: string | undefined;
83
+ })[];
84
+ export declare function sameJson(a: unknown, b: unknown): boolean;
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.validateFinalStep = validateFinalStep;
4
+ exports.interactionStepContent = interactionStepContent;
5
+ exports.sameJson = sameJson;
6
+ const types_1 = require("./types");
7
+ /** Check final-snapshot identity before mutating a protocol-specific stream state. */
8
+ function validateFinalStep(previous, final) {
9
+ if (previous.type !== final.type)
10
+ throw new types_1.InteractionsResponseError("Final step type disagrees with stream");
11
+ if (previous.type === "function_call" &&
12
+ final.type === "function_call" &&
13
+ (previous.id !== final.id || previous.name !== final.name))
14
+ throw new types_1.InteractionsResponseError("Final function identity disagrees with stream");
15
+ if ("signature" in previous &&
16
+ previous.signature &&
17
+ "signature" in final &&
18
+ final.signature != null &&
19
+ previous.signature !== final.signature)
20
+ throw new types_1.InteractionsResponseError("Final signature disagrees with stream");
21
+ if ("content" in final && final.content) {
22
+ const received = interactionStepContent(previous).filter(part => part.type !== "text");
23
+ const media = final.content.filter(part => part.type !== "text");
24
+ if (received.some((part, index) => !sameJson(part, media[index])))
25
+ throw new types_1.InteractionsResponseError("Final media disagrees with stream");
26
+ }
27
+ }
28
+ function interactionStepContent(step) {
29
+ return step.type === "thought"
30
+ ? (step.summary ?? [])
31
+ : "content" in step
32
+ ? (step.content ?? [])
33
+ : [];
34
+ }
35
+ function sameJson(a, b) {
36
+ if (a === b)
37
+ return true;
38
+ if (a == null || b == null || typeof a !== "object" || typeof b !== "object")
39
+ return false;
40
+ const left = a, right = b;
41
+ return (Array.isArray(a) === Array.isArray(b) &&
42
+ Object.keys(left).length === Object.keys(right).length &&
43
+ Object.keys(left).every(key => Object.hasOwn(right, key) && sameJson(left[key], right[key])));
44
+ }