@zenmux/rosetta-ai 1.0.32 → 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,19 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.InteractionsResponseError = exports.InteractionsRequestError = void 0;
4
+ class InteractionsRequestError extends Error {
5
+ constructor(message) {
6
+ super(message);
7
+ this.name = "InteractionsRequestError";
8
+ }
9
+ }
10
+ exports.InteractionsRequestError = InteractionsRequestError;
11
+ class InteractionsResponseError extends Error {
12
+ code;
13
+ constructor(message, code) {
14
+ super(message);
15
+ this.code = code;
16
+ this.name = "InteractionsResponseError";
17
+ }
18
+ }
19
+ exports.InteractionsResponseError = InteractionsResponseError;
@@ -0,0 +1,11 @@
1
+ import type OpenAI from "openai";
2
+ import type Anthropic from "@anthropic-ai/sdk";
3
+ import type { ConvertedResponse } from "../responses/utils";
4
+ import type { InteractionUsage } from "./types";
5
+ export type InteractionCompletionUsage = Partial<OpenAI.CompletionUsage>;
6
+ export type InteractionResponseUsage = Partial<NonNullable<ConvertedResponse["usage"]>>;
7
+ export type InteractionMessageUsage = Partial<Anthropic.Usage>;
8
+ /** Messages separates uncached input from cache reads; native fee aliases keep the total. */
9
+ export declare function convertInteractionMessageUsage(usage: InteractionUsage | undefined): InteractionMessageUsage | undefined;
10
+ export declare function convertInteractionResponseUsage(usage: InteractionUsage | undefined): InteractionResponseUsage | null;
11
+ export declare function convertInteractionUsage(usage: InteractionUsage | undefined): InteractionCompletionUsage | undefined;
@@ -0,0 +1,74 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.convertInteractionMessageUsage = convertInteractionMessageUsage;
4
+ exports.convertInteractionResponseUsage = convertInteractionResponseUsage;
5
+ exports.convertInteractionUsage = convertInteractionUsage;
6
+ /** Messages separates uncached input from cache reads; native fee aliases keep the total. */
7
+ function convertInteractionMessageUsage(usage) {
8
+ if (!usage)
9
+ return undefined;
10
+ const result = {
11
+ output_tokens_details: null,
12
+ };
13
+ if (usage.total_input_tokens != null)
14
+ result.input_tokens = usage.total_input_tokens - (usage.total_cached_tokens ?? 0);
15
+ if (usage.total_cached_tokens != null)
16
+ result.cache_read_input_tokens = usage.total_cached_tokens;
17
+ if (usage.total_output_tokens != null && usage.total_thought_tokens != null)
18
+ result.output_tokens = usage.total_output_tokens + usage.total_thought_tokens;
19
+ return result;
20
+ }
21
+ function convertInteractionResponseUsage(usage) {
22
+ if (!usage)
23
+ return null;
24
+ const result = {};
25
+ if (usage.total_input_tokens != null)
26
+ result.input_tokens = usage.total_input_tokens;
27
+ if (usage.total_output_tokens != null && usage.total_thought_tokens != null)
28
+ result.output_tokens = usage.total_output_tokens + usage.total_thought_tokens;
29
+ if (usage.total_tokens != null)
30
+ result.total_tokens = usage.total_tokens;
31
+ if (usage.total_cached_tokens != null)
32
+ result.input_tokens_details = {
33
+ cached_tokens: usage.total_cached_tokens,
34
+ cache_write_tokens: null,
35
+ };
36
+ if (usage.total_thought_tokens != null)
37
+ result.output_tokens_details = { reasoning_tokens: usage.total_thought_tokens };
38
+ return result;
39
+ }
40
+ function modalityTokens(items, modality) {
41
+ const matches = items?.filter(item => item.modality?.toLowerCase() === modality);
42
+ if (!matches?.length || matches.some(item => item.tokens == null))
43
+ return undefined;
44
+ return matches.reduce((sum, item) => sum + item.tokens, 0);
45
+ }
46
+ function convertInteractionUsage(usage) {
47
+ if (!usage)
48
+ return undefined;
49
+ const result = {};
50
+ if (usage.total_input_tokens != null)
51
+ result.prompt_tokens = usage.total_input_tokens;
52
+ if (usage.total_output_tokens != null && usage.total_thought_tokens != null) {
53
+ result.completion_tokens = usage.total_output_tokens + usage.total_thought_tokens;
54
+ }
55
+ if (usage.total_tokens != null)
56
+ result.total_tokens = usage.total_tokens;
57
+ // V1's function-call example reports input=100, output=25, tool-use=50,
58
+ // total=125. Tool-use is preserved separately, never blindly added to input.
59
+ const audioInput = modalityTokens(usage.input_tokens_by_modality, "audio");
60
+ if (usage.total_cached_tokens != null || audioInput != null) {
61
+ result.prompt_tokens_details = {
62
+ ...(usage.total_cached_tokens != null && { cached_tokens: usage.total_cached_tokens }),
63
+ ...(audioInput != null && { audio_tokens: audioInput }),
64
+ };
65
+ }
66
+ const audioOutput = modalityTokens(usage.output_tokens_by_modality, "audio");
67
+ if (usage.total_thought_tokens != null || audioOutput != null) {
68
+ result.completion_tokens_details = {
69
+ ...(usage.total_thought_tokens != null && { reasoning_tokens: usage.total_thought_tokens }),
70
+ ...(audioOutput != null && { audio_tokens: audioOutput }),
71
+ };
72
+ }
73
+ return result;
74
+ }
@@ -0,0 +1,4 @@
1
+ import type Anthropic from "@anthropic-ai/sdk";
2
+ import { type InteractionCreateParams } from "../interactions/types";
3
+ export declare function validateMessagesInteractionsParameters(params: Anthropic.MessageCreateParams): void;
4
+ export declare function convertMessagesInteractionRequest(params: Anthropic.MessageCreateParams): InteractionCreateParams;
@@ -0,0 +1,278 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.validateMessagesInteractionsParameters = validateMessagesInteractionsParameters;
4
+ exports.convertMessagesInteractionRequest = convertMessagesInteractionRequest;
5
+ const types_1 = require("../interactions/types");
6
+ function validateMessagesInteractionsParameters(params) {
7
+ const p = params;
8
+ const known = new Set([
9
+ "model",
10
+ "messages",
11
+ "max_tokens",
12
+ "system",
13
+ "stream",
14
+ "tools",
15
+ "tool_choice",
16
+ "stop_sequences",
17
+ "thinking",
18
+ "output_config",
19
+ ]);
20
+ for (const [key, value] of Object.entries(p))
21
+ if (value != null && !known.has(key))
22
+ fail(`${key} is not supported by the Messages to Interactions converter`);
23
+ if (p.max_tokens != null && (!Number.isSafeInteger(p.max_tokens) || p.max_tokens <= 0))
24
+ fail("max_tokens must be a positive integer");
25
+ if (p.stream != null && typeof p.stream !== "boolean")
26
+ fail("stream must be a boolean");
27
+ if (p.thinking != null) {
28
+ const thinking = object(p.thinking, "thinking");
29
+ if (thinking.type !== "adaptive")
30
+ fail("Interactions V1 supports adaptive thinking; disabling thinking or setting a token budget has no equivalent");
31
+ if (Object.entries(thinking).some(([key, value]) => value != null && !["type", "display"].includes(key)))
32
+ fail("Unsupported thinking option for Interactions V1");
33
+ if (thinking.display != null &&
34
+ (typeof thinking.display !== "string" ||
35
+ !["summarized", "omitted"].includes(thinking.display)))
36
+ fail("Unsupported thinking.display");
37
+ }
38
+ if (p.output_config != null) {
39
+ const config = object(p.output_config, "output_config");
40
+ if (Object.entries(config).some(([key, value]) => value != null && !["effort", "format"].includes(key)))
41
+ fail("Unsupported output_config option");
42
+ if (config.effort != null &&
43
+ (typeof config.effort !== "string" || !["low", "medium", "high"].includes(config.effort)))
44
+ fail("Unsupported output_config.effort for Interactions V1");
45
+ if (config.format != null) {
46
+ const format = object(config.format, "output_config.format");
47
+ if (format.type !== "json_schema" || format.strict === true)
48
+ fail("Unsupported output_config.format or strict guarantee");
49
+ object(format.schema, "output_config.format.schema");
50
+ }
51
+ }
52
+ if (p.stop_sequences != null &&
53
+ (!Array.isArray(p.stop_sequences) ||
54
+ p.stop_sequences.some((s) => typeof s !== "string")))
55
+ fail("stop_sequences must be an array of strings");
56
+ if (p.tools != null && !Array.isArray(p.tools))
57
+ fail("tools must be an array");
58
+ for (const raw of p.tools ?? []) {
59
+ const tool = object(raw, "tool");
60
+ if (tool.type != null && tool.type !== "custom")
61
+ fail("Only custom function tools are supported by this converter");
62
+ if (tool.strict === true)
63
+ fail("Interactions V1 cannot guarantee tool strict=true");
64
+ for (const key of [
65
+ "cache_control",
66
+ "defer_loading",
67
+ "allowed_callers",
68
+ "input_examples",
69
+ "eager_input_streaming",
70
+ ])
71
+ if (tool[key] != null)
72
+ fail(`tool.${key} has no equivalent in Interactions V1`);
73
+ }
74
+ if (p.tool_choice != null) {
75
+ const choice = object(p.tool_choice, "tool_choice");
76
+ if (typeof choice.type !== "string" || !["auto", "any", "none", "tool"].includes(choice.type))
77
+ fail("Unsupported tool_choice.type");
78
+ if (choice.disable_parallel_tool_use === true)
79
+ fail("Interactions V1 cannot enforce disable_parallel_tool_use=true");
80
+ }
81
+ }
82
+ function convertMessagesInteractionRequest(params) {
83
+ validateMessagesInteractionsParameters(params);
84
+ const p = params;
85
+ const model = nonempty(p.model, "model");
86
+ if (!Array.isArray(p.messages) || !p.messages.length)
87
+ fail("messages must be a nonempty array");
88
+ const input = [];
89
+ const calls = new Map();
90
+ const results = new Set();
91
+ for (const raw of p.messages) {
92
+ const message = object(raw, "message");
93
+ if (message.role !== "user" && message.role !== "assistant")
94
+ fail("Messages role must be user or assistant");
95
+ if (message.interactions != null)
96
+ fail("Native history is not supported by Messages conversion");
97
+ const blocks = typeof message.content === "string"
98
+ ? [{ type: "text", text: message.content }]
99
+ : array(message.content, "content");
100
+ let content = [];
101
+ const flush = () => {
102
+ if (content.length)
103
+ input.push({ type: message.role === "user" ? "user_input" : "model_output", content });
104
+ content = [];
105
+ };
106
+ for (const rawBlock of blocks) {
107
+ const block = object(rawBlock, "content block");
108
+ if (block.interactions != null)
109
+ fail("Native history is not supported by Messages conversion");
110
+ if (block.cache_control != null)
111
+ fail("cache_control has no equivalent in Interactions V1");
112
+ if (block.type === "tool_use") {
113
+ flush();
114
+ if (message.role !== "assistant")
115
+ fail("tool_use requires assistant role");
116
+ const id = nonempty(block.id, "tool_use.id"), name = nonempty(block.name, "tool_use.name");
117
+ if (calls.has(id))
118
+ fail("Duplicate tool_use.id");
119
+ if (block.caller != null && object(block.caller, "tool caller").type !== "direct")
120
+ fail("Unsupported tool caller");
121
+ calls.set(id, name);
122
+ input.push({
123
+ type: "function_call",
124
+ id,
125
+ name,
126
+ arguments: structuredClone(object(block.input, "tool_use.input")),
127
+ });
128
+ }
129
+ else if (block.type === "tool_result") {
130
+ flush();
131
+ if (message.role !== "user")
132
+ fail("tool_result requires user role");
133
+ const id = nonempty(block.tool_use_id, "tool_result.tool_use_id");
134
+ if (!calls.has(id) || results.has(id))
135
+ fail("tool_result must match one preceding tool_use");
136
+ if (block.is_error != null && typeof block.is_error !== "boolean")
137
+ fail("tool_result.is_error must be a boolean");
138
+ results.add(id);
139
+ input.push({
140
+ type: "function_result",
141
+ call_id: id,
142
+ name: calls.get(id),
143
+ ...(block.is_error != null && { is_error: block.is_error }),
144
+ result: typeof block.content === "string"
145
+ ? block.content
146
+ : array(block.content ?? [], "tool_result.content").map(convertContent),
147
+ });
148
+ }
149
+ else if (block.type === "thinking") {
150
+ flush();
151
+ if (message.role !== "assistant")
152
+ fail("thinking requires assistant role");
153
+ input.push({
154
+ type: "thought",
155
+ summary: [{ type: "text", text: string(block.thinking, "thinking") }],
156
+ ...(block.signature != null && {
157
+ signature: string(block.signature, "thinking.signature"),
158
+ }),
159
+ });
160
+ }
161
+ else {
162
+ content.push(convertContent(block));
163
+ }
164
+ }
165
+ flush();
166
+ }
167
+ const config = {};
168
+ if (p.max_tokens != null)
169
+ config.max_output_tokens = p.max_tokens;
170
+ if (p.stop_sequences != null)
171
+ config.stop_sequences = [...p.stop_sequences];
172
+ if (p.output_config?.effort != null)
173
+ config.thinking_level = p.output_config.effort;
174
+ if (p.thinking != null)
175
+ config.thinking_summaries =
176
+ object(p.thinking, "thinking").display === "omitted" ? "none" : "auto";
177
+ const tools = [];
178
+ const names = new Set();
179
+ for (const raw of p.tools ?? []) {
180
+ const tool = object(raw, "tool");
181
+ const name = nonempty(tool.name, "tool.name");
182
+ if (names.has(name))
183
+ fail("Duplicate tool name");
184
+ names.add(name);
185
+ tools.push({
186
+ type: "function",
187
+ name,
188
+ parameters: structuredClone(object(tool.input_schema, "tool.input_schema")),
189
+ ...(tool.description != null && {
190
+ description: string(tool.description, "tool.description"),
191
+ }),
192
+ });
193
+ }
194
+ if (p.tool_choice != null) {
195
+ const choice = p.tool_choice;
196
+ if (choice.type === "tool") {
197
+ if (!names.has(choice.name))
198
+ fail("tool_choice must refer to a declared function");
199
+ config.tool_choice = { allowed_tools: { mode: "any", tools: [choice.name] } };
200
+ }
201
+ else
202
+ config.tool_choice = choice.type;
203
+ if (choice.type === "any" && !tools.length)
204
+ fail("tool_choice=any requires tools");
205
+ }
206
+ const result = { model, input, store: false, stream: p.stream ?? false };
207
+ if (p.system != null)
208
+ result.system_instruction =
209
+ typeof p.system === "string"
210
+ ? p.system
211
+ : array(p.system, "system")
212
+ .map(block => {
213
+ if (block.type !== "text" || block.cache_control != null)
214
+ fail("system supports plain text only");
215
+ return string(block.text, "system.text");
216
+ })
217
+ .join("\n");
218
+ if (Object.keys(config).length)
219
+ result.generation_config = config;
220
+ if (tools.length)
221
+ result.tools = tools;
222
+ if (p.output_config?.format)
223
+ result.response_format = {
224
+ type: "text",
225
+ mime_type: "application/json",
226
+ schema: structuredClone(p.output_config.format.schema),
227
+ };
228
+ return result;
229
+ }
230
+ function convertContent(raw) {
231
+ const block = object(raw, "content block");
232
+ if (block.cache_control != null)
233
+ fail("cache_control has no equivalent in Interactions V1");
234
+ if (block.type === "text") {
235
+ if (block.citations != null && (!Array.isArray(block.citations) || block.citations.length))
236
+ fail("Citation history has no equivalent in Interactions conversion");
237
+ return { type: "text", text: string(block.text, "text") };
238
+ }
239
+ if (block.type === "image" || block.type === "document") {
240
+ if (block.title != null || block.context != null || block.citations != null)
241
+ fail("Document metadata/citations have no equivalent in Interactions V1");
242
+ const source = object(block.source, "source");
243
+ if (source.type === "base64")
244
+ return {
245
+ type: block.type,
246
+ mime_type: nonempty(source.media_type, "source.media_type"),
247
+ data: nonempty(source.data, "source.data"),
248
+ };
249
+ if (source.type === "url")
250
+ return { type: block.type, uri: nonempty(source.url, "source.url") };
251
+ fail("Only base64 or URL media sources are supported");
252
+ }
253
+ return fail(`Unsupported Messages content block: ${block.type}`);
254
+ }
255
+ function array(value, name) {
256
+ if (!Array.isArray(value))
257
+ fail(`${name} must be an array`);
258
+ return value.map(item => object(item, name));
259
+ }
260
+ function object(value, name) {
261
+ if (!value || typeof value !== "object" || Array.isArray(value))
262
+ fail(`${name} must be an object`);
263
+ return value;
264
+ }
265
+ function string(value, name) {
266
+ if (typeof value !== "string")
267
+ fail(`${name} must be a string`);
268
+ return value;
269
+ }
270
+ function nonempty(value, name) {
271
+ const text = string(value, name);
272
+ if (!text.trim())
273
+ fail(`${name} must not be empty`);
274
+ return text;
275
+ }
276
+ function fail(message) {
277
+ throw new types_1.InteractionsRequestError(message);
278
+ }
@@ -0,0 +1,42 @@
1
+ import type Anthropic from "@anthropic-ai/sdk";
2
+ import { type Interaction, type InteractionCreateParams, type InteractionEvent, type InteractionUsage } from "../interactions/types";
3
+ import { type InteractionMessageUsage } from "../interactions/usage";
4
+ export type InteractionMessage = Omit<Anthropic.Message, "usage"> & {
5
+ usage?: Partial<InteractionMessageUsage>;
6
+ };
7
+ export type InteractionMessageStreamEvent = Exclude<Anthropic.RawMessageStreamEvent, Anthropic.RawMessageStartEvent | Anthropic.RawMessageDeltaEvent> | {
8
+ type: "message_start";
9
+ message: InteractionMessage;
10
+ } | {
11
+ type: "message_delta";
12
+ delta: Anthropic.RawMessageDeltaEvent["delta"];
13
+ usage?: Partial<InteractionMessageUsage>;
14
+ };
15
+ /** Direct Messages ↔ Interactions V1; only target-protocol content is returned. */
16
+ export declare class MessagesToInteractionsConverter {
17
+ private model;
18
+ private id;
19
+ private started;
20
+ private finished;
21
+ private terminal?;
22
+ private usage?;
23
+ private states;
24
+ private seen;
25
+ convertRequest(params: Anthropic.MessageCreateParams): InteractionCreateParams;
26
+ getUsage(): InteractionUsage | undefined;
27
+ getStatus(): Interaction["status"] | undefined;
28
+ convertResponse(raw: Interaction): InteractionMessage;
29
+ convertStream(stream: AsyncIterable<InteractionEvent>): AsyncIterable<InteractionMessageStreamEvent>;
30
+ convertStreamEvent(event: InteractionEvent): InteractionMessageStreamEvent[];
31
+ finishStream(): InteractionMessageStreamEvent[];
32
+ private start;
33
+ private append;
34
+ private reconcile;
35
+ private message;
36
+ private stopReason;
37
+ private identity;
38
+ private checkStatus;
39
+ private text;
40
+ private validateContent;
41
+ private unmapped;
42
+ }