@zenmux/rosetta-ai 1.0.42 → 1.0.43-beta.45317478271.1

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.
package/dist/index.d.ts CHANGED
@@ -26,3 +26,5 @@ export { convertInteractionResponseUsage } from "./interactions/usage";
26
26
  export type { InteractionResponseUsage } from "./interactions/usage";
27
27
  export { ResponsesToMessagesConverter } from "./responses/messages";
28
28
  export { ResponsesToChatCompletionConverter } from "./responses/chat-completions";
29
+ export { SystemOneToGeminiDecisionsConverter } from "./systemone/gemini-decisions";
30
+ export { SystemOneDecisionRequestError } from "./systemone/gemini-decisions-request";
package/dist/index.js CHANGED
@@ -15,7 +15,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
15
15
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
16
16
  };
17
17
  Object.defineProperty(exports, "__esModule", { value: true });
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;
18
+ exports.SystemOneDecisionRequestError = exports.SystemOneToGeminiDecisionsConverter = 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;
19
19
  var gemini_1 = require("./chat-completions/gemini");
20
20
  Object.defineProperty(exports, "ChatCompletionToGeminiConverter", { enumerable: true, get: function () { return gemini_1.ChatCompletionToGeminiConverter; } });
21
21
  var interactions_1 = require("./chat-completions/interactions");
@@ -59,3 +59,7 @@ var messages_3 = require("./responses/messages");
59
59
  Object.defineProperty(exports, "ResponsesToMessagesConverter", { enumerable: true, get: function () { return messages_3.ResponsesToMessagesConverter; } });
60
60
  var chat_completions_3 = require("./responses/chat-completions");
61
61
  Object.defineProperty(exports, "ResponsesToChatCompletionConverter", { enumerable: true, get: function () { return chat_completions_3.ResponsesToChatCompletionConverter; } });
62
+ var gemini_decisions_1 = require("./systemone/gemini-decisions");
63
+ Object.defineProperty(exports, "SystemOneToGeminiDecisionsConverter", { enumerable: true, get: function () { return gemini_decisions_1.SystemOneToGeminiDecisionsConverter; } });
64
+ var gemini_decisions_request_1 = require("./systemone/gemini-decisions-request");
65
+ Object.defineProperty(exports, "SystemOneDecisionRequestError", { enumerable: true, get: function () { return gemini_decisions_request_1.SystemOneDecisionRequestError; } });
@@ -0,0 +1,22 @@
1
+ import type { Decisions } from "@google/genai";
2
+ export interface SystemOneDecisionRequest {
3
+ model: string;
4
+ state: unknown;
5
+ questions: unknown;
6
+ }
7
+ export type DecisionImage = Extract<Decisions.DecisionInputContent, {
8
+ type: "image";
9
+ }>;
10
+ export interface DecisionQuestionMapping {
11
+ id: string;
12
+ originalId: string;
13
+ question: Decisions.Question;
14
+ originalLevels?: string[];
15
+ }
16
+ export declare class SystemOneDecisionRequestError extends Error {
17
+ }
18
+ export interface ConvertedDecisionRequest {
19
+ body: Decisions.CreateDecisionRequest;
20
+ mapping: DecisionQuestionMapping[];
21
+ }
22
+ export declare function convertSystemOneDecisionRequest(request: SystemOneDecisionRequest, images: ReadonlyMap<string, DecisionImage>): ConvertedDecisionRequest;
@@ -0,0 +1,193 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SystemOneDecisionRequestError = void 0;
4
+ exports.convertSystemOneDecisionRequest = convertSystemOneDecisionRequest;
5
+ class SystemOneDecisionRequestError extends Error {
6
+ }
7
+ exports.SystemOneDecisionRequestError = SystemOneDecisionRequestError;
8
+ function invalid(path, message) {
9
+ throw new SystemOneDecisionRequestError(`${path}: ${message}`);
10
+ }
11
+ function record(value) {
12
+ return value !== null && typeof value === "object" && !Array.isArray(value);
13
+ }
14
+ function text(value, path) {
15
+ if (typeof value !== "string" || !value.trim())
16
+ invalid(path, "expected non-empty text");
17
+ return value;
18
+ }
19
+ function count(n, path, min, max) {
20
+ if (n < min || n > max)
21
+ invalid(path, `expected ${min} to ${max} entries`);
22
+ }
23
+ // Only string values carry references. Object keys (including option IDs) are business data.
24
+ function render(value, path, replace) {
25
+ if (typeof value === "string")
26
+ return text(replace(value), path);
27
+ if (!record(value) && !Array.isArray(value))
28
+ invalid(path, "expected text, an object or an array");
29
+ return JSON.stringify(value, (_key, v) => (typeof v === "string" ? replace(v) : v));
30
+ }
31
+ function convertQuestion(value, path, replace) {
32
+ if (!record(value))
33
+ invalid(path, "expected a question object");
34
+ for (const field of Object.keys(value)) {
35
+ if (!["type", "instructions", "criteria"].includes(field))
36
+ invalid(`${path}.${field}`, "unsupported question field");
37
+ }
38
+ const { type, criteria } = value;
39
+ if (type !== "noul" && type !== "choice" && type !== "score")
40
+ invalid(`${path}.type`, "Gemini Decisions supports noul, choice and score");
41
+ const instructions = render(value.instructions, `${path}.instructions`, replace);
42
+ const p = `${path}.criteria`;
43
+ if (type === "score") {
44
+ if (!Array.isArray(criteria))
45
+ invalid(p, "expected an ordered array of levels");
46
+ count(criteria.length, p, 2, 255);
47
+ return { type, instructions, criteria: criteria.map((v, i) => replace(text(v, `${p}[${i}]`))) };
48
+ }
49
+ if (type === "noul" && criteria === undefined)
50
+ return { type, instructions };
51
+ if (!record(criteria))
52
+ invalid(p, "expected an object");
53
+ if (type === "noul") {
54
+ return {
55
+ type,
56
+ instructions,
57
+ criteria: Object.fromEntries(Object.entries(criteria).map(([k, v]) => {
58
+ if (k !== "true" && k !== "false")
59
+ invalid(`${p}.${k}`, "expected true or false");
60
+ if (typeof v !== "string")
61
+ invalid(`${p}.${k}`, "expected text");
62
+ return [`${k}_description`, replace(v)];
63
+ })),
64
+ };
65
+ }
66
+ const entries = Object.entries(criteria);
67
+ count(entries.length, p, 2, 255);
68
+ return {
69
+ type,
70
+ instructions,
71
+ criteria: Object.fromEntries(entries.map(([k, v]) => {
72
+ if (!k ||
73
+ k.trim() !== k ||
74
+ [...k].length > 128 ||
75
+ /[\p{Cc}\s]/u.test(k.replaceAll(" ", "")))
76
+ invalid(`${p}.${k}`, "invalid Google choice option ID");
77
+ if (v !== null && typeof v !== "string")
78
+ invalid(`${p}.${k}`, "expected text or null");
79
+ return [k, v === null ? "" : replace(v)];
80
+ })),
81
+ };
82
+ }
83
+ function convertSystemOneDecisionRequest(request, images) {
84
+ if (!record(request.questions))
85
+ invalid("questions", "expected an object");
86
+ const entries = Object.entries(request.questions);
87
+ count(entries.length, "questions", 1, 1000);
88
+ const labels = new Map();
89
+ if (images.size) {
90
+ // Avoid duplicating the whole JSON body just to reserve existing labels.
91
+ const occupied = new Set();
92
+ function reserve(value) {
93
+ if (typeof value === "string") {
94
+ for (const match of value.matchAll(/\[Image \d+\]/g))
95
+ occupied.add(match[0]);
96
+ }
97
+ else if (Array.isArray(value)) {
98
+ value.forEach(reserve);
99
+ }
100
+ else if (record(value)) {
101
+ for (const key of Object.keys(value)) {
102
+ reserve(key);
103
+ reserve(value[key]);
104
+ }
105
+ }
106
+ }
107
+ reserve(request.state);
108
+ reserve(request.questions);
109
+ let i = 0;
110
+ for (const ref of images.keys()) {
111
+ if (!ref.trim())
112
+ invalid("assets", "empty image reference");
113
+ let label;
114
+ do {
115
+ label = `[Image ${++i}]`;
116
+ } while (occupied.has(label));
117
+ labels.set(ref, label);
118
+ }
119
+ }
120
+ function replacer(used, path) {
121
+ return (s) => {
122
+ // Track one occurrence per distinct image, not an array of every reference in a large state.
123
+ const pending = [];
124
+ for (const [ref, label] of labels) {
125
+ const start = s.indexOf(ref);
126
+ if (start !== -1)
127
+ pending.push({ ref, label, start });
128
+ }
129
+ if (!pending.length)
130
+ return s;
131
+ let output = "", end = 0;
132
+ while (pending.length) {
133
+ let next = 0;
134
+ for (let i = 1; i < pending.length; i++)
135
+ if (pending[i].start < pending[next].start)
136
+ next = i;
137
+ const hit = pending[next];
138
+ if (hit.start < end)
139
+ invalid(path, "overlapping image references");
140
+ output += s.slice(end, hit.start) + hit.label;
141
+ end = hit.start + hit.ref.length;
142
+ used.add(hit.ref);
143
+ hit.start = s.indexOf(hit.ref, hit.start + 1);
144
+ if (hit.start === -1)
145
+ pending.splice(next, 1);
146
+ }
147
+ return output + s.slice(end);
148
+ };
149
+ }
150
+ const shared = new Set();
151
+ const state = render(request.state, "state", replacer(shared, "state"));
152
+ const reservedIds = new Set(Object.keys(request.questions));
153
+ let sequence = 0;
154
+ let firstExtra;
155
+ const mapping = entries.map(([originalId, raw]) => {
156
+ const path = `questions.${originalId}`;
157
+ const used = new Set();
158
+ const question = convertQuestion(raw, path, replacer(used, path));
159
+ for (const ref of used)
160
+ if (shared.has(ref))
161
+ used.delete(ref);
162
+ const previous = firstExtra;
163
+ if (previous && (previous.size !== used.size || [...used].some(r => !previous.has(r))))
164
+ invalid(path, "Google Decisions requires the same images to be visible to every question");
165
+ firstExtra ??= used;
166
+ let id = originalId;
167
+ if (!/^[A-Za-z0-9_-]{1,64}$/.test(id)) {
168
+ do {
169
+ id = `q_${++sequence}`;
170
+ } while (reservedIds.has(id));
171
+ }
172
+ return {
173
+ id,
174
+ originalId,
175
+ question,
176
+ ...(question.type === "score"
177
+ ? { originalLevels: raw.criteria }
178
+ : {}),
179
+ };
180
+ });
181
+ const blocks = [{ type: "text", text: state }];
182
+ for (const [ref, image] of images) {
183
+ if (!shared.has(ref) && !firstExtra?.has(ref))
184
+ invalid(`assets.${ref}`, "image is not referenced by any string value");
185
+ blocks.push({ type: "text", text: `\n${labels.get(ref)}:\n` }, image);
186
+ }
187
+ const body = {
188
+ model: request.model,
189
+ input: images.size ? blocks : state,
190
+ questions: Object.fromEntries(mapping.map(m => [m.id, m.question])),
191
+ };
192
+ return { body, mapping };
193
+ }
@@ -0,0 +1,22 @@
1
+ import type { Decisions } from "@google/genai";
2
+ import { type ConvertedDecisionRequest, type DecisionImage, type SystemOneDecisionRequest } from "./gemini-decisions-request";
3
+ type SystemOneAnswer = Exclude<Decisions.Answer, {
4
+ type: "noul";
5
+ }> | {
6
+ type: "noul";
7
+ noul: number;
8
+ confidence?: number;
9
+ };
10
+ interface SystemOneDecisionResponse {
11
+ model: string;
12
+ answers: Record<string, SystemOneAnswer>;
13
+ usage: {
14
+ input_tokens: number;
15
+ output_tokens: number;
16
+ };
17
+ }
18
+ export declare class SystemOneToGeminiDecisionsConverter {
19
+ convertRequest(request: SystemOneDecisionRequest, images?: ReadonlyMap<string, DecisionImage>): ConvertedDecisionRequest;
20
+ convertResponse(response: Decisions.CreateDecisionResponse, request: ConvertedDecisionRequest): SystemOneDecisionResponse;
21
+ }
22
+ export {};
@@ -0,0 +1,96 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SystemOneToGeminiDecisionsConverter = void 0;
4
+ const gemini_decisions_request_1 = require("./gemini-decisions-request");
5
+ function within(n, min, max) {
6
+ return typeof n === "number" && Number.isFinite(n) && n >= min && n <= max;
7
+ }
8
+ function sameKeys(value, expected) {
9
+ return (value !== null &&
10
+ typeof value === "object" &&
11
+ !Array.isArray(value) &&
12
+ Object.keys(value).length === expected.length &&
13
+ expected.every(k => Object.hasOwn(value, k)));
14
+ }
15
+ function invalid(path) {
16
+ throw new Error(`Invalid Gemini Decisions response: ${path}`);
17
+ }
18
+ class SystemOneToGeminiDecisionsConverter {
19
+ convertRequest(request, images = new Map()) {
20
+ return (0, gemini_decisions_request_1.convertSystemOneDecisionRequest)(request, images);
21
+ }
22
+ convertResponse(response, request) {
23
+ const { answers, usage } = response;
24
+ if (response.prompt_feedback?.block_reason &&
25
+ response.prompt_feedback.block_reason !== "unspecified")
26
+ invalid("prompt_feedback.block_reason");
27
+ if (!answers ||
28
+ !sameKeys(answers, request.mapping.map(m => m.id)))
29
+ invalid("answers must match the requested question IDs");
30
+ const input = usage?.total_input_tokens;
31
+ if (typeof input !== "number" || !Number.isSafeInteger(input) || input < 0)
32
+ invalid("usage.total_input_tokens");
33
+ if (usage?.total_output_tokens !== undefined && usage.total_output_tokens !== 0)
34
+ invalid("usage.total_output_tokens");
35
+ const result = request.mapping.map(({ id, originalId, question, originalLevels }) => {
36
+ const a = answers[id];
37
+ const p = `answers.${id}`;
38
+ if (!a || a.type !== question.type)
39
+ invalid(`${p}.type`);
40
+ if (a.type === "noul") {
41
+ if (!within(a.noul, 0.01, 0.99))
42
+ invalid(`${p}.noul`);
43
+ if (a.confidence !== undefined && !within(a.confidence, 0, 1))
44
+ invalid(`${p}.confidence`);
45
+ return [
46
+ originalId,
47
+ {
48
+ type: a.type,
49
+ noul: a.noul,
50
+ ...(a.confidence !== undefined && { confidence: a.confidence }),
51
+ },
52
+ ];
53
+ }
54
+ if (!within(a.confidence, 0, 1))
55
+ invalid(`${p}.confidence`);
56
+ const keys = Object.keys(question.criteria);
57
+ if (!sameKeys(a.probabilities, keys) ||
58
+ !Object.values(a.probabilities).every(v => within(v, 0, 1)))
59
+ invalid(`${p}.probabilities`);
60
+ if (a.type === "choice") {
61
+ if (!keys.includes(a.choice))
62
+ invalid(`${p}.choice`);
63
+ return [
64
+ originalId,
65
+ {
66
+ type: a.type,
67
+ choice: a.choice,
68
+ probabilities: a.probabilities,
69
+ confidence: a.confidence,
70
+ },
71
+ ];
72
+ }
73
+ if (question.type !== "score" || !originalLevels || !within(a.score, 0, keys.length - 1))
74
+ invalid(`${p}.score`);
75
+ if (!sameKeys(a.legend, keys) ||
76
+ !question.criteria.every((level, i) => a.legend[i] === level))
77
+ invalid(`${p}.legend`);
78
+ return [
79
+ originalId,
80
+ {
81
+ type: a.type,
82
+ score: a.score,
83
+ legend: Object.fromEntries(originalLevels.entries()),
84
+ probabilities: a.probabilities,
85
+ confidence: a.confidence,
86
+ },
87
+ ];
88
+ });
89
+ return {
90
+ model: request.body.model,
91
+ answers: Object.fromEntries(result),
92
+ usage: { input_tokens: input, output_tokens: 0 },
93
+ };
94
+ }
95
+ }
96
+ exports.SystemOneToGeminiDecisionsConverter = SystemOneToGeminiDecisionsConverter;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zenmux/rosetta-ai",
3
- "version": "1.0.42",
3
+ "version": "1.0.43-beta.45317478271.1",
4
4
  "description": "Universal translator between AI provider protocols",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",