@saturn-universe/model 0.0.0-stage → 0.1.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/wire.js ADDED
@@ -0,0 +1,498 @@
1
+ import { canonicalJson, maxModelReasoningSummaryLength } from '@saturn-universe/core';
2
+ import { z } from 'zod';
3
+ import { GatewayError } from './errors.js';
4
+ import { providerFailure, transportFailure } from './provider-errors.js';
5
+ import { hasEncryptedReasoning, normalizeReasoning, reasoningItemSchema, responsesCodecs } from './codec.js';
6
+ const tokens = z.number().int().nonnegative().safe();
7
+ const usageSchema = z.object({
8
+ input_tokens: tokens,
9
+ output_tokens: tokens,
10
+ input_tokens_details: z.object({ cached_tokens: tokens.optional() }).nullish(),
11
+ output_tokens_details: z.object({ reasoning_tokens: tokens.optional() }).nullish(),
12
+ });
13
+ const responseSchema = z.object({
14
+ id: z.string().min(1),
15
+ status: z.enum(['completed', 'incomplete']),
16
+ output: z.array(z.record(z.string(), z.json())),
17
+ usage: usageSchema,
18
+ incomplete_details: z.object({ reason: z.enum(['max_output_tokens', 'content_filter']) }).nullish(),
19
+ model: z.string().optional(),
20
+ service_tier: z.string().nullish(),
21
+ reasoning: z.object({ context: z.string().optional() }).nullish(),
22
+ });
23
+ export const maxCaptureBytes = 32 * 1024 * 1024;
24
+ const maxTrackedTurnStates = 256;
25
+ const sessionTurnStates = new Map();
26
+ function rememberTurnState(key, value) {
27
+ sessionTurnStates.delete(key);
28
+ sessionTurnStates.set(key, value);
29
+ if (sessionTurnStates.size > maxTrackedTurnStates) {
30
+ const oldest = sessionTurnStates.keys().next().value;
31
+ if (oldest !== undefined)
32
+ sessionTurnStates.delete(oldest);
33
+ }
34
+ }
35
+ export function createWireBridge(request, profile, capabilities, signal, capture, secrets, lifecycle, transport, onProgress) {
36
+ return async (url, init) => {
37
+ if (String(url) !== profile.baseURL.replace(/\/$/, '') + '/responses' ||
38
+ init?.method !== 'POST' ||
39
+ capture.sent)
40
+ throw new GatewayError('protocol');
41
+ const body = JSON.parse(String(init.body));
42
+ const plan = request.responses;
43
+ if (body.model !== request.model.modelId)
44
+ throw new GatewayError('profile_mismatch');
45
+ body.input = plan.fullInput;
46
+ delete body.instructions;
47
+ if (plan.instructions !== undefined)
48
+ body.instructions = plan.instructions;
49
+ delete body.store;
50
+ if (capabilities.responses.store === 'supported')
51
+ body.store = false;
52
+ delete body.truncation;
53
+ if (capabilities.responses.truncation === 'explicit_disabled')
54
+ body.truncation = 'disabled';
55
+ delete body.reasoning;
56
+ if (request.responsesOptions.reasoning)
57
+ body.reasoning = request.responsesOptions.reasoning;
58
+ delete body.include;
59
+ if (capabilities.responses.encryptedContentInclude === 'supported' &&
60
+ capabilities.responses.encryptedReasoning === 'required')
61
+ body.include = ['reasoning.encrypted_content'];
62
+ delete body.parallel_tool_calls;
63
+ if (request.responsesOptions.parallelToolCalls !== undefined)
64
+ body.parallel_tool_calls = request.responsesOptions.parallelToolCalls;
65
+ delete body.metadata;
66
+ if (request.responsesOptions.metadata)
67
+ body.metadata = request.responsesOptions.metadata;
68
+ body.max_output_tokens = request.maxOutputTokens;
69
+ const cacheKey = request.agentSessionId;
70
+ if (cacheKey)
71
+ body.prompt_cache_key = cacheKey;
72
+ if (request.temperature !== undefined && body.temperature !== request.temperature)
73
+ throw new GatewayError('unsupported_capability');
74
+ if (canonicalJson(body.tools ?? []) !==
75
+ canonicalJson(request.tools.map((tool) => ({
76
+ type: 'function',
77
+ name: tool.wireName,
78
+ description: tool.description,
79
+ parameters: tool.inputSchema,
80
+ strict: false,
81
+ }))))
82
+ throw new GatewayError('protocol');
83
+ const headers = new Headers(init.headers);
84
+ const turnStateKey = `${profile.id}:${cacheKey}`;
85
+ if (lifecycle.promptCacheOnly) {
86
+ headers.delete('session_id');
87
+ headers.delete('conversation_id');
88
+ headers.delete('x-codex-turn-state');
89
+ }
90
+ else if (cacheKey) {
91
+ if (!headers.has('session_id'))
92
+ headers.set('session_id', cacheKey);
93
+ if (!headers.has('conversation_id'))
94
+ headers.set('conversation_id', cacheKey);
95
+ const turnState = sessionTurnStates.get(turnStateKey);
96
+ if (turnState && !headers.has('x-codex-turn-state'))
97
+ headers.set('x-codex-turn-state', turnState);
98
+ }
99
+ capture.sent++;
100
+ const failTransport = (error) => {
101
+ if (signal.aborted)
102
+ return signal.reason;
103
+ capture.error = transportFailure(error, lifecycle.details(), secrets);
104
+ return capture.error;
105
+ };
106
+ let response;
107
+ try {
108
+ response = await transport(url, {
109
+ ...init,
110
+ headers,
111
+ body: JSON.stringify(body),
112
+ signal,
113
+ redirect: 'error',
114
+ });
115
+ }
116
+ catch (error) {
117
+ throw failTransport(error);
118
+ }
119
+ signal.throwIfAborted();
120
+ lifecycle.onActivity('awaiting_first_frame');
121
+ const responseTurnState = response.headers.get('x-codex-turn-state');
122
+ if (!lifecycle.promptCacheOnly && cacheKey && responseTurnState?.trim()) {
123
+ rememberTurnState(turnStateKey, responseTurnState.trim());
124
+ }
125
+ const bodyStream = response.body ? observeBody(response.body, failTransport) : null;
126
+ if (!response.ok) {
127
+ const status = response.status;
128
+ const data = await readBounded(bodyStream)
129
+ .then((text) => {
130
+ try {
131
+ return JSON.parse(text);
132
+ }
133
+ catch {
134
+ return text;
135
+ }
136
+ })
137
+ .catch((error) => {
138
+ if (signal.aborted || capture.error)
139
+ throw error;
140
+ return undefined;
141
+ });
142
+ captureUsage(capture, data);
143
+ capture.error = providerFailure(data, {
144
+ status,
145
+ retry: response.headers.get('retry-after'),
146
+ secrets,
147
+ hasTools: Array.isArray(body.tools) && body.tools.length > 0,
148
+ });
149
+ throw capture.error;
150
+ }
151
+ if (response.headers.get('content-type')?.includes('text/event-stream')) {
152
+ if (!bodyStream)
153
+ throw new GatewayError('native_capture_incomplete');
154
+ capture.source = 'wire_sse';
155
+ return new Response(bodyStream.pipeThrough(captureSse(capture, request, capabilities, secrets, lifecycle, onProgress)), {
156
+ headers: response.headers,
157
+ status: response.status,
158
+ });
159
+ }
160
+ capture.source = 'wire_json';
161
+ const text = await readBounded(bodyStream);
162
+ let value;
163
+ try {
164
+ value = parseWireJson(text, secrets, (json) => captureUsage(capture, json));
165
+ capture.response = decodeResponse(value, request.binding, capabilities.responses.encryptedReasoning);
166
+ }
167
+ catch (error) {
168
+ if (error instanceof GatewayError)
169
+ capture.error = error;
170
+ throw error;
171
+ }
172
+ const sdkOutput = normalizeSdkOutput(capture.response.output);
173
+ const sdkNeedsRewrite = request.binding.codecVersion !== 1 ||
174
+ sdkOutput.some((item, index) => item !== capture.response.output[index]);
175
+ return new Response(sdkNeedsRewrite ? JSON.stringify({ ...value, output: sdkOutput }) : text, {
176
+ headers: response.headers,
177
+ status: response.status,
178
+ });
179
+ };
180
+ }
181
+ export function observeBody(body, failTransport) {
182
+ const reader = body.getReader();
183
+ return new ReadableStream({
184
+ async pull(controller) {
185
+ try {
186
+ const part = await reader.read();
187
+ if (part.done) {
188
+ reader.releaseLock();
189
+ controller.close();
190
+ }
191
+ else
192
+ controller.enqueue(part.value);
193
+ }
194
+ catch (error) {
195
+ reader.releaseLock();
196
+ controller.error(failTransport(error));
197
+ }
198
+ },
199
+ async cancel(reason) {
200
+ try {
201
+ await reader.cancel(reason);
202
+ }
203
+ finally {
204
+ reader.releaseLock();
205
+ }
206
+ },
207
+ }, { highWaterMark: 0 });
208
+ }
209
+ function captureUsage(capture, value) {
210
+ if (!value || typeof value !== 'object' || !('usage' in value))
211
+ return;
212
+ const decoded = usageSchema.safeParse(value.usage);
213
+ if (!decoded.success)
214
+ return;
215
+ const raw = decoded.data;
216
+ const cached = raw.input_tokens_details?.cached_tokens;
217
+ const reasoning = raw.output_tokens_details?.reasoning_tokens;
218
+ capture.usage = {
219
+ inputTokens: raw.input_tokens,
220
+ outputTokens: raw.output_tokens,
221
+ accuracy: 'reported',
222
+ ...(cached !== undefined && cached <= raw.input_tokens ? { cachedInputTokens: cached } : {}),
223
+ ...(reasoning !== undefined && reasoning <= raw.output_tokens ? { reasoningTokens: reasoning } : {}),
224
+ };
225
+ }
226
+ function normalizeSdkOutput(output) {
227
+ return output.map((item) => {
228
+ if (item.type !== 'message' || !Array.isArray(item.content))
229
+ return item;
230
+ let changed = false;
231
+ const content = item.content.map((part) => {
232
+ if (part &&
233
+ typeof part === 'object' &&
234
+ !Array.isArray(part) &&
235
+ part.type === 'output_text' &&
236
+ (part.annotations === undefined || part.annotations === null)) {
237
+ changed = true;
238
+ return { ...part, annotations: [] };
239
+ }
240
+ return part;
241
+ });
242
+ return changed ? { ...item, content } : item;
243
+ });
244
+ }
245
+ export async function readBounded(body) {
246
+ if (!body)
247
+ throw new GatewayError('native_capture_incomplete');
248
+ const reader = body.getReader();
249
+ const chunks = [];
250
+ let bytes = 0;
251
+ try {
252
+ while (true) {
253
+ const { value, done } = await reader.read();
254
+ if (done)
255
+ break;
256
+ bytes += value.byteLength;
257
+ if (bytes > maxCaptureBytes)
258
+ throw new GatewayError('native_capture_incomplete');
259
+ chunks.push(value);
260
+ }
261
+ return new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks));
262
+ }
263
+ finally {
264
+ await reader.cancel().catch(() => undefined);
265
+ reader.releaseLock();
266
+ }
267
+ }
268
+ function parseWireJson(text, secrets, observe, allowErrorFrames = false) {
269
+ let value;
270
+ try {
271
+ value = JSON.parse(text);
272
+ }
273
+ catch {
274
+ throw new GatewayError('protocol');
275
+ }
276
+ observe?.(value);
277
+ if (allowErrorFrames &&
278
+ value &&
279
+ typeof value === 'object' &&
280
+ 'type' in value &&
281
+ (value.type === 'response.failed' || value.type === 'error'))
282
+ return value;
283
+ // Reflected authentication must never become a persisted model response.
284
+ if (secrets.some((secret) => secret && JSON.stringify(value).includes(secret)))
285
+ throw new GatewayError('invalid_output');
286
+ return value;
287
+ }
288
+ function decodeResponse(value, binding, encryptedReasoning) {
289
+ const decoded = responseSchema.safeParse(value);
290
+ if (!decoded.success)
291
+ throw new GatewayError('invalid_output');
292
+ const raw = decoded.data;
293
+ if (raw.status === 'incomplete' && !raw.incomplete_details)
294
+ throw new GatewayError('invalid_output');
295
+ if ((raw.usage.input_tokens_details?.cached_tokens ?? 0) > raw.usage.input_tokens ||
296
+ (raw.usage.output_tokens_details?.reasoning_tokens ?? 0) > raw.usage.output_tokens)
297
+ throw new GatewayError('invalid_output');
298
+ const replayable = encryptedReasoning === 'required'
299
+ ? raw.output
300
+ : raw.output.filter((value) => value.type !== 'reasoning' || hasEncryptedReasoning(value));
301
+ const omittedReasoning = replayable.length !== raw.output.length;
302
+ const removedPaths = [];
303
+ const outputItems = responsesCodecs
304
+ .get(binding.codecId, binding.codecVersion)
305
+ .decodeOutput(replayable, binding);
306
+ // SSE completeness and the SDK both use the full provider output.
307
+ const output = binding.codecVersion === 2
308
+ ? raw.output.map((value, index) => {
309
+ const normalized = normalizeReasoning(value);
310
+ removedPaths.push(...normalized.removed.map((key) => `output[${index}].${key}`));
311
+ return normalized.value;
312
+ })
313
+ : raw.output;
314
+ if (raw.status === 'completed' && output.some((item) => 'status' in item && item.status !== 'completed'))
315
+ throw new GatewayError('native_capture_incomplete');
316
+ const reasoningSummary = omittedReasoning
317
+ ? output
318
+ .flatMap((value) => {
319
+ if (value.type !== 'reasoning')
320
+ return [];
321
+ const item = reasoningItemSchema.safeParse(value);
322
+ if (!item.success)
323
+ throw new GatewayError('invalid_output');
324
+ return item.data.summary.map((part) => part.text);
325
+ })
326
+ .join('\n')
327
+ .slice(0, maxModelReasoningSummaryLength)
328
+ : undefined;
329
+ return {
330
+ ...raw,
331
+ output,
332
+ outputItems,
333
+ ...(reasoningSummary?.trim() ? { reasoningSummary } : {}),
334
+ ...(binding.codecVersion === 2
335
+ ? { normalization: { version: 2, removedPaths, reason: 'private_reasoning_excluded' } }
336
+ : {}),
337
+ };
338
+ }
339
+ const eventSchema = z.object({
340
+ type: z.string(),
341
+ output_index: z.number().int().nonnegative().safe().nullish(),
342
+ item_id: z.string().optional(),
343
+ delta: z.string().optional(),
344
+ item: z.record(z.string(), z.json()).optional(),
345
+ response: z.unknown().optional(),
346
+ });
347
+ function captureSse(capture, request, capabilities, secrets, lifecycle, onProgress) {
348
+ const decoder = new TextDecoder('utf-8', { fatal: true });
349
+ let buffer = '';
350
+ let bytes = 0;
351
+ let terminal = false;
352
+ let receivedFrame = false;
353
+ const done = new Map();
354
+ const added = new Map();
355
+ const reasoningIndices = new Set();
356
+ const binding = request.binding;
357
+ const requestId = request.id;
358
+ function activity(stage, text) {
359
+ onProgress?.({ type: 'activity', requestId, stage, bytes: Buffer.byteLength(text) });
360
+ }
361
+ function frame(text) {
362
+ const lines = text.split('\n');
363
+ const heartbeat = lines.some((line) => /^event:\s*(?:ping|heartbeat)\s*$/.test(line));
364
+ if (heartbeat) {
365
+ if (!terminal) {
366
+ if (receivedFrame)
367
+ lifecycle.onActivity();
368
+ activity('heartbeat', text);
369
+ }
370
+ return '';
371
+ }
372
+ const data = lines
373
+ .filter((line) => line.startsWith('data:'))
374
+ .map((line) => line.slice(5).trimStart())
375
+ .join('\n');
376
+ if (!data || data === '[DONE]') {
377
+ if (!terminal && lines.some((line) => line.startsWith(':'))) {
378
+ if (receivedFrame)
379
+ lifecycle.onActivity();
380
+ activity('heartbeat', text);
381
+ }
382
+ return text + '\n\n';
383
+ }
384
+ const original = parseWireJson(data, secrets, (json) => {
385
+ if (json && typeof json === 'object' && 'response' in json)
386
+ captureUsage(capture, json.response);
387
+ captureUsage(capture, json);
388
+ }, true);
389
+ const decoded = eventSchema.safeParse(original);
390
+ if (!decoded.success)
391
+ throw new GatewayError('protocol');
392
+ const event = decoded.data;
393
+ if (terminal)
394
+ throw new GatewayError('protocol');
395
+ receivedFrame = true;
396
+ lifecycle.onActivity('stream_idle');
397
+ if (event.type === 'response.output_item.added' ||
398
+ event.type === 'response.function_call_arguments.delta' ||
399
+ event.type === 'response.reasoning_text.delta' ||
400
+ event.type === 'response.in_progress' ||
401
+ event.type === 'response.created')
402
+ activity(event.type, data);
403
+ if (event.type === 'response.reasoning_summary_text.delta' && event.delta !== undefined)
404
+ onProgress?.({ type: 'reasoning_summary_delta', requestId, text: event.delta });
405
+ if (binding.codecVersion === 2) {
406
+ if (event.item?.type === 'reasoning' && typeof event.output_index === 'number')
407
+ reasoningIndices.add(event.output_index);
408
+ if (event.type.startsWith('response.reasoning_text.') ||
409
+ (event.type.startsWith('response.content_part.') &&
410
+ typeof event.output_index === 'number' &&
411
+ reasoningIndices.has(event.output_index)))
412
+ return '';
413
+ if (event.item) {
414
+ event.item = normalizeReasoning(event.item).value;
415
+ original.item = event.item;
416
+ }
417
+ }
418
+ if (event.type === 'response.output_text.delta' || event.type === 'response.refusal.delta') {
419
+ const index = event.output_index ?? [...added].find(([, id]) => id === event.item_id)?.[0];
420
+ if (index === undefined || event.delta === undefined)
421
+ throw new GatewayError('protocol');
422
+ onProgress?.({ type: 'text_delta', requestId, index, text: event.delta });
423
+ }
424
+ if (event.type === 'response.output_item.added' || event.type === 'response.output_item.done') {
425
+ const index = event.output_index;
426
+ const value = event.item;
427
+ if (index === undefined || index === null || !value || typeof value.id !== 'string')
428
+ throw new GatewayError('protocol');
429
+ if (event.type.endsWith('.added')) {
430
+ if (added.has(index))
431
+ throw new GatewayError('protocol');
432
+ added.set(index, value.id);
433
+ if (value.type === 'function_call' && (value.arguments === undefined || value.arguments === null)) {
434
+ original.item = { ...value, arguments: '' };
435
+ }
436
+ }
437
+ else {
438
+ if (done.has(index) || added.get(index) !== value.id)
439
+ throw new GatewayError('protocol');
440
+ done.set(index, value);
441
+ }
442
+ }
443
+ if (event.type === 'response.failed' || event.type === 'error')
444
+ throw providerFailure(event.type === 'response.failed' ? event.response : original, {
445
+ secrets,
446
+ hasTools: request.tools.length > 0,
447
+ });
448
+ if (event.type === 'response.completed' || event.type === 'response.incomplete') {
449
+ const response = decodeResponse(event.response, binding, capabilities.responses.encryptedReasoning);
450
+ const output = [...done.entries()].sort(([a], [b]) => a - b);
451
+ if (response.status !== (event.type === 'response.completed' ? 'completed' : 'incomplete') ||
452
+ added.size !== done.size ||
453
+ output.some(([index], i) => index !== i) ||
454
+ canonicalJson(response.output) !== canonicalJson(output.map(([, value]) => value)))
455
+ throw new GatewayError('native_capture_incomplete');
456
+ capture.response = response;
457
+ original.response = { ...event.response, output: response.output };
458
+ terminal = true;
459
+ }
460
+ return `data: ${JSON.stringify(original)}\n\n`;
461
+ }
462
+ return new TransformStream({
463
+ transform(chunk, controller) {
464
+ try {
465
+ bytes += chunk.byteLength;
466
+ if (bytes > maxCaptureBytes)
467
+ throw new GatewayError('native_capture_incomplete');
468
+ buffer += decoder.decode(chunk, { stream: true });
469
+ buffer = buffer.replace(/\r\n/g, '\n');
470
+ let end;
471
+ while ((end = buffer.indexOf('\n\n')) >= 0) {
472
+ const output = frame(buffer.slice(0, end));
473
+ if (output)
474
+ controller.enqueue(new TextEncoder().encode(output));
475
+ buffer = buffer.slice(end + 2);
476
+ }
477
+ }
478
+ catch (error) {
479
+ capture.error = error instanceof GatewayError ? error : new GatewayError('protocol');
480
+ controller.error(capture.error);
481
+ }
482
+ },
483
+ flush(controller) {
484
+ try {
485
+ buffer += decoder.decode();
486
+ const output = buffer.trim() && frame(buffer);
487
+ if (output)
488
+ controller.enqueue(new TextEncoder().encode(output));
489
+ if (!terminal)
490
+ throw new GatewayError('native_capture_incomplete');
491
+ }
492
+ catch (error) {
493
+ capture.error = error instanceof GatewayError ? error : new GatewayError('protocol');
494
+ controller.error(capture.error);
495
+ }
496
+ },
497
+ });
498
+ }
package/package.json CHANGED
@@ -1,6 +1,24 @@
1
1
  {
2
2
  "name": "@saturn-universe/model",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "license": "AGPL-3.0-only",
5
+ "type": "module",
6
+ "files": [
7
+ "dist"
8
+ ],
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js"
13
+ }
14
+ },
15
+ "dependencies": {
16
+ "@ai-sdk/anthropic": "4.0.99",
17
+ "@ai-sdk/google": "4.0.114",
18
+ "@ai-sdk/openai": "4.0.111",
19
+ "@ai-sdk/openai-compatible": "3.0.87",
20
+ "@saturn-universe/core": "0.1.1",
21
+ "ai": "7.0.165",
22
+ "zod": "4.6.0"
23
+ }
6
24
  }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.