@saturn-universe/model 0.1.0 → 0.1.2-dev.2

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/codec.d.ts CHANGED
@@ -1,5 +1,8 @@
1
- import type { ModelRequest, ModelToolCall, ResponsesCodec, ResponsesOutputItem } from '@saturn-universe/core';
1
+ import type { ModelRequest, ModelToolCall, ProtocolJsonObject, ResponsesCodec, ResponsesOutputItem } from '@saturn-universe/core';
2
2
  export declare const digest: (value: unknown) => string;
3
+ export declare function isResponsesOutputItem(value: ProtocolJsonObject): boolean;
4
+ export declare function reasoningSummaryParts(value: ProtocolJsonObject): string[];
5
+ export declare function hasEncryptedReasoning(value: ProtocolJsonObject): boolean;
3
6
  export declare const responsesCodec: ResponsesCodec;
4
7
  export declare const responsesCodecs: {
5
8
  get(id: string, version: number): ResponsesCodec;
package/dist/codec.js CHANGED
@@ -3,6 +3,34 @@ import { canonicalJson } from '@saturn-universe/core';
3
3
  import { z } from 'zod';
4
4
  import { GatewayError } from './errors.js';
5
5
  export const digest = (value) => createHash('sha256').update(canonicalJson(value)).digest('hex');
6
+ const reasoningItemSchema = z.object({
7
+ type: z.literal('reasoning'),
8
+ id: z.string().min(1),
9
+ summary: z.array(z.object({ type: z.literal('summary_text'), text: z.string() }).passthrough()),
10
+ });
11
+ export function isResponsesOutputItem(value) {
12
+ return value.type === 'message' || value.type === 'reasoning' || value.type === 'function_call';
13
+ }
14
+ export function reasoningSummaryParts(value) {
15
+ const texts = (source) => {
16
+ if (typeof source === 'string')
17
+ return source.trim() ? [source] : [];
18
+ if (!Array.isArray(source))
19
+ return [];
20
+ return source.flatMap((part) => {
21
+ const text = typeof part === 'string' ? part : part?.text;
22
+ return typeof text === 'string' && text.trim() ? [text] : [];
23
+ });
24
+ };
25
+ const summary = texts(value.summary);
26
+ if (summary.length || hasEncryptedReasoning(value))
27
+ return summary;
28
+ const content = texts(value.content);
29
+ return content.length ? content : texts(value.reasoning_text);
30
+ }
31
+ export function hasEncryptedReasoning(value) {
32
+ return typeof value.encrypted_content === 'string' && Boolean(value.encrypted_content.trim());
33
+ }
6
34
  const item = z.discriminatedUnion('type', [
7
35
  z
8
36
  .object({
@@ -16,14 +44,7 @@ const item = z.discriminatedUnion('type', [
16
44
  ])),
17
45
  })
18
46
  .passthrough(),
19
- z
20
- .object({
21
- type: z.literal('reasoning'),
22
- id: z.string().min(1),
23
- summary: z.array(z.object({ type: z.literal('summary_text'), text: z.string() }).passthrough()),
24
- encrypted_content: z.string().min(1),
25
- })
26
- .passthrough(),
47
+ reasoningItemSchema.extend({ encrypted_content: z.string().min(1) }).passthrough(),
27
48
  z
28
49
  .object({
29
50
  type: z.literal('function_call'),
@@ -39,12 +60,11 @@ export const responsesCodec = {
39
60
  version: 1,
40
61
  decodeOutput(items) {
41
62
  return items.map((value) => {
42
- if (!['message', 'reasoning', 'function_call'].includes(String(value.type)))
63
+ if (!isResponsesOutputItem(value))
43
64
  throw new GatewayError('unsupported_item');
44
65
  if (value.type === 'reasoning' && ('content' in value || 'reasoning_text' in value))
45
66
  throw new GatewayError('unsupported_capability');
46
- if (value.type === 'reasoning' &&
47
- (typeof value.encrypted_content !== 'string' || !value.encrypted_content.trim()))
67
+ if (value.type === 'reasoning' && !hasEncryptedReasoning(value))
48
68
  throw new GatewayError('continuation_unavailable');
49
69
  if (!item.safeParse(value).success)
50
70
  throw new GatewayError('invalid_output');
@@ -103,8 +123,7 @@ export const responsesCodecV2 = {
103
123
  ...responsesCodec,
104
124
  version: 2,
105
125
  decodeOutput(items, binding) {
106
- if (items.some((value) => value.type === 'reasoning' &&
107
- (typeof value.encrypted_content !== 'string' || !value.encrypted_content.trim())))
126
+ if (items.some((value) => value.type === 'reasoning' && !hasEncryptedReasoning(value)))
108
127
  throw new GatewayError('continuation_unavailable');
109
128
  return responsesCodec.decodeOutput(items.map((value) => normalizeReasoning(value).value), binding);
110
129
  },
package/dist/index.js CHANGED
@@ -9,24 +9,31 @@ import { sdkProviderFailure } from './provider-errors.js';
9
9
  import { createWireBridge } from './wire.js';
10
10
  export { GatewayError } from './errors.js';
11
11
  export { digest, responsesCodec, responsesCodecV2, responsesCodecs } from './codec.js';
12
+ function validProviderRoute({ baseURL, protocol }) {
13
+ try {
14
+ const endpoint = new URL(baseURL);
15
+ return (providerProtocols.includes(protocol) &&
16
+ ['https:', 'http:'].includes(endpoint.protocol) &&
17
+ !endpoint.username &&
18
+ !endpoint.password &&
19
+ !endpoint.search &&
20
+ !endpoint.hash &&
21
+ !endpoint.pathname.endsWith('/responses'));
22
+ }
23
+ catch {
24
+ return false;
25
+ }
26
+ }
12
27
  export class ProviderRegistry {
13
28
  profiles = new Map();
14
29
  register(profile) {
15
30
  const profileRef = `${profile.id}@${profile.revision}`;
16
- let endpoint;
17
- try {
18
- endpoint = new URL(profile.baseURL);
19
- }
20
- catch {
21
- throw new GatewayError('profile_mismatch');
22
- }
23
- if (!providerProtocols.includes(profile.protocol) ||
24
- !['https:', 'http:'].includes(endpoint.protocol) ||
25
- endpoint.username ||
26
- endpoint.password ||
27
- endpoint.search ||
28
- endpoint.hash ||
29
- endpoint.pathname.endsWith('/responses') ||
31
+ if (!validProviderRoute(profile) ||
32
+ Object.entries(profile.modelRoutes ?? {}).some(([model, route]) => !Object.hasOwn(profile.models, model) ||
33
+ !validProviderRoute({
34
+ protocol: route.protocol ?? profile.protocol,
35
+ baseURL: route.baseURL ?? profile.baseURL,
36
+ })) ||
30
37
  !profile.apiKeyRef ||
31
38
  !profile.credentialScopeRef ||
32
39
  this.profiles.has(profileRef))
@@ -65,10 +72,20 @@ export class ProviderRegistry {
65
72
  return this.profiles.delete(profileRef);
66
73
  }
67
74
  resolve(model) {
68
- const profile = this.profiles.get(model.profileRef)?.profile;
69
- const capabilities = profile?.models[model.modelId];
70
- if (!profile || profile.id !== model.providerId || !capabilities)
75
+ const registered = this.profiles.get(model.profileRef)?.profile;
76
+ if (!registered || registered.id !== model.providerId || !Object.hasOwn(registered.models, model.modelId))
71
77
  throw new GatewayError('profile_mismatch');
78
+ const capabilities = registered.models[model.modelId];
79
+ const route = registered.modelRoutes && Object.hasOwn(registered.modelRoutes, model.modelId)
80
+ ? registered.modelRoutes[model.modelId]
81
+ : undefined;
82
+ const profile = route
83
+ ? {
84
+ ...registered,
85
+ baseURL: route.baseURL ?? registered.baseURL,
86
+ protocol: route.protocol ?? registered.protocol,
87
+ }
88
+ : registered;
72
89
  const endpointFingerprint = digest(profile.baseURL.replace(/\/$/, ''));
73
90
  const capabilityDigest = digest(capabilities);
74
91
  const binding = {
@@ -396,7 +413,9 @@ function validateCapabilities(request, capabilities, protocol) {
396
413
  throw new GatewayError('unsupported_capability');
397
414
  if ((options.reasoning?.effort &&
398
415
  (!r.reasoningModel ||
399
- (r.reasoningEfforts.length > 0 && !r.reasoningEfforts.includes(options.reasoning.effort)))) ||
416
+ (nativeResponses &&
417
+ r.reasoningEfforts.length > 0 &&
418
+ !r.reasoningEfforts.includes(options.reasoning.effort)))) ||
400
419
  (options.reasoning?.summary && (!nativeResponses || !r.reasoningSummary)) ||
401
420
  (options.reasoning?.context &&
402
421
  (!nativeResponses || !r.reasoningContexts.includes(options.reasoning.context))) ||
@@ -424,7 +443,8 @@ function accept(request, capture, capabilities, sdk) {
424
443
  : []);
425
444
  const toolCalls = decodeToolCalls(request, outputItems);
426
445
  const nativeText = content.map((part) => part.text).join('');
427
- validateSdkResponse(raw, sdk, toolCalls, nativeText);
446
+ if (capture.source !== 'wire_sse' || capabilities.responses.encryptedReasoning === 'required')
447
+ validateSdkResponse(raw, sdk, toolCalls, nativeText);
428
448
  const usage = raw.usage;
429
449
  if (sdk.usage.inputTokens !== usage.input_tokens || sdk.usage.outputTokens !== usage.output_tokens)
430
450
  throw new GatewayError('invalid_output');
@@ -492,6 +512,7 @@ function accept(request, capture, capabilities, sdk) {
492
512
  outputDigest: digest(outputItems.map((item) => item.value)),
493
513
  providerMetadata: {
494
514
  responseId: raw.id,
515
+ ...(raw.reasoningSummary === undefined ? {} : { reasoningSummary: raw.reasoningSummary }),
495
516
  ...(raw.normalization === undefined ? {} : { normalization: raw.normalization }),
496
517
  ...(raw.reasoning?.context === undefined ? {} : { reasoningContext: raw.reasoning.context }),
497
518
  ...(raw.model === undefined ? {} : { model: raw.model }),
@@ -76,6 +76,20 @@ function sdkFetch(url, lifecycle, transport, capture, secrets, hasTools) {
76
76
  };
77
77
  }
78
78
  const reasoningEfforts = z.enum(['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max']);
79
+ function supportedReasoningEffort(effort, supported) {
80
+ if (effort === undefined || !supported.length || supported.includes(effort))
81
+ return effort;
82
+ const rank = reasoningEfforts.options.findIndex((value) => value === effort);
83
+ const levels = supported.flatMap((level) => {
84
+ const index = reasoningEfforts.options.findIndex((value) => value === level);
85
+ return index < 0 ? [] : [{ level, index }];
86
+ });
87
+ if (rank < 0 || !levels.length)
88
+ return supported[0];
89
+ // Prefer the lower effort when two supported levels are equally close.
90
+ return levels.sort((a, b) => Math.abs(a.index - rank) - Math.abs(b.index - rank) || a.index - b.index)[0]
91
+ ?.level;
92
+ }
79
93
  const thinkingBudgets = { minimal: 1024, low: 1024, medium: 4096, high: 8192, xhigh: 16384, max: 32768 };
80
94
  export function createSdkSettings(request, connection, capabilities, lifecycle, transport, capture, invocation, streaming) {
81
95
  const { protocol, baseURL, apiKey, secrets } = connection;
@@ -92,7 +106,7 @@ export function createSdkSettings(request, connection, capabilities, lifecycle,
92
106
  headers: Object.fromEntries(headers),
93
107
  fetch: sdkFetch(endpoint(connection, modelId, streaming), lifecycle, transport, capture, secrets, request.tools.length > 0),
94
108
  };
95
- const effort = request.responsesOptions.reasoning?.effort;
109
+ const effort = supportedReasoningEffort(request.responsesOptions.reasoning?.effort, capabilities.responses.reasoningEfforts);
96
110
  const parallel = request.responsesOptions.parallelToolCalls;
97
111
  const mappedEffort = reasoningEfforts.safeParse(effort);
98
112
  if (effort !== undefined && protocol !== 'openai-chat' && !mappedEffort.success)
package/dist/wire.d.ts CHANGED
@@ -33,6 +33,7 @@ declare const responseSchema: z.ZodObject<{
33
33
  type NativeResponse = Omit<z.infer<typeof responseSchema>, 'output'> & {
34
34
  output: readonly ProtocolJsonObject[];
35
35
  outputItems: readonly ResponsesOutputItem[];
36
+ reasoningSummary?: string;
36
37
  normalization?: {
37
38
  version: 2;
38
39
  removedPaths: string[];
package/dist/wire.js CHANGED
@@ -1,8 +1,8 @@
1
- import { canonicalJson } from '@saturn-universe/core';
1
+ import { canonicalJson, maxModelReasoningSummaryLength } from '@saturn-universe/core';
2
2
  import { z } from 'zod';
3
3
  import { GatewayError } from './errors.js';
4
4
  import { providerFailure, transportFailure } from './provider-errors.js';
5
- import { responsesCodecs, normalizeReasoning } from './codec.js';
5
+ import { hasEncryptedReasoning, isResponsesOutputItem, normalizeReasoning, reasoningSummaryParts, responsesCodecs, } from './codec.js';
6
6
  const tokens = z.number().int().nonnegative().safe();
7
7
  const usageSchema = z.object({
8
8
  input_tokens: tokens,
@@ -152,7 +152,7 @@ export function createWireBridge(request, profile, capabilities, signal, capture
152
152
  if (!bodyStream)
153
153
  throw new GatewayError('native_capture_incomplete');
154
154
  capture.source = 'wire_sse';
155
- return new Response(bodyStream.pipeThrough(captureSse(capture, request, secrets, lifecycle, onProgress)), {
155
+ return new Response(bodyStream.pipeThrough(captureSse(capture, request, capabilities, secrets, lifecycle, onProgress)), {
156
156
  headers: response.headers,
157
157
  status: response.status,
158
158
  });
@@ -162,7 +162,7 @@ export function createWireBridge(request, profile, capabilities, signal, capture
162
162
  let value;
163
163
  try {
164
164
  value = parseWireJson(text, secrets, (json) => captureUsage(capture, json));
165
- capture.response = decodeResponse(value, request.binding);
165
+ capture.response = decodeResponse(value, request.binding, capabilities.responses.encryptedReasoning);
166
166
  }
167
167
  catch (error) {
168
168
  if (error instanceof GatewayError)
@@ -171,6 +171,7 @@ export function createWireBridge(request, profile, capabilities, signal, capture
171
171
  }
172
172
  const sdkOutput = normalizeSdkOutput(capture.response.output);
173
173
  const sdkNeedsRewrite = request.binding.codecVersion !== 1 ||
174
+ capabilities.responses.encryptedReasoning !== 'required' ||
174
175
  sdkOutput.some((item, index) => item !== capture.response.output[index]);
175
176
  return new Response(sdkNeedsRewrite ? JSON.stringify({ ...value, output: sdkOutput }) : text, {
176
177
  headers: response.headers,
@@ -285,7 +286,7 @@ function parseWireJson(text, secrets, observe, allowErrorFrames = false) {
285
286
  throw new GatewayError('invalid_output');
286
287
  return value;
287
288
  }
288
- function decodeResponse(value, binding) {
289
+ function decodeResponse(value, binding, encryptedReasoning) {
289
290
  const decoded = responseSchema.safeParse(value);
290
291
  if (!decoded.success)
291
292
  throw new GatewayError('invalid_output');
@@ -295,25 +296,41 @@ function decodeResponse(value, binding) {
295
296
  if ((raw.usage.input_tokens_details?.cached_tokens ?? 0) > raw.usage.input_tokens ||
296
297
  (raw.usage.output_tokens_details?.reasoning_tokens ?? 0) > raw.usage.output_tokens)
297
298
  throw new GatewayError('invalid_output');
299
+ const strict = encryptedReasoning === 'required';
300
+ const retained = raw.output
301
+ .map((value, index) => ({ value, index }))
302
+ .filter(({ value }) => strict ||
303
+ (isResponsesOutputItem(value) && (value.type !== 'reasoning' || hasEncryptedReasoning(value))));
304
+ const replayable = retained.map(({ value }) => value);
305
+ const omittedReasoning = !strict && raw.output.some((value) => value.type === 'reasoning' && !hasEncryptedReasoning(value));
298
306
  const removedPaths = [];
299
307
  const outputItems = responsesCodecs
300
308
  .get(binding.codecId, binding.codecVersion)
301
- .decodeOutput(raw.output, binding);
302
- if (binding.codecVersion === 2)
303
- raw.output.forEach((value, index) => {
304
- if (value.type === 'reasoning')
305
- removedPaths.push(...['content', 'reasoning_text']
306
- .filter((key) => key in value)
307
- .map((key) => `output[${index}].${key}`));
308
- });
309
- const output = outputItems.map((item) => item.value);
309
+ .decodeOutput(replayable, binding);
310
+ const output = retained.map(({ value, index }) => {
311
+ if (binding.codecVersion !== 2)
312
+ return value;
313
+ const normalized = normalizeReasoning(value);
314
+ removedPaths.push(...normalized.removed.map((key) => `output[${index}].${key}`));
315
+ return normalized.value;
316
+ });
310
317
  if (raw.status === 'completed' &&
311
- outputItems.some((item) => 'status' in item.value && item.value.status !== 'completed'))
318
+ replayable.some((item) => (item.type === 'message' || item.type === 'function_call') &&
319
+ item.status !== null &&
320
+ item.status !== undefined &&
321
+ item.status !== 'completed'))
312
322
  throw new GatewayError('native_capture_incomplete');
323
+ const reasoningSummary = omittedReasoning
324
+ ? raw.output
325
+ .flatMap((value) => (value.type === 'reasoning' ? reasoningSummaryParts(value) : []))
326
+ .join('\n')
327
+ .slice(0, maxModelReasoningSummaryLength)
328
+ : undefined;
313
329
  return {
314
330
  ...raw,
315
331
  output,
316
332
  outputItems,
333
+ ...(reasoningSummary?.trim() ? { reasoningSummary } : {}),
317
334
  ...(binding.codecVersion === 2
318
335
  ? { normalization: { version: 2, removedPaths, reason: 'private_reasoning_excluded' } }
319
336
  : {}),
@@ -327,7 +344,7 @@ const eventSchema = z.object({
327
344
  item: z.record(z.string(), z.json()).optional(),
328
345
  response: z.unknown().optional(),
329
346
  });
330
- function captureSse(capture, request, secrets, lifecycle, onProgress) {
347
+ function captureSse(capture, request, capabilities, secrets, lifecycle, onProgress) {
331
348
  const decoder = new TextDecoder('utf-8', { fatal: true });
332
349
  let buffer = '';
333
350
  let bytes = 0;
@@ -337,6 +354,7 @@ function captureSse(capture, request, secrets, lifecycle, onProgress) {
337
354
  const added = new Map();
338
355
  const reasoningIndices = new Set();
339
356
  const binding = request.binding;
357
+ const strict = capabilities.responses.encryptedReasoning === 'required';
340
358
  const requestId = request.id;
341
359
  function activity(stage, text) {
342
360
  onProgress?.({ type: 'activity', requestId, stage, bytes: Buffer.byteLength(text) });
@@ -385,7 +403,7 @@ function captureSse(capture, request, secrets, lifecycle, onProgress) {
385
403
  activity(event.type, data);
386
404
  if (event.type === 'response.reasoning_summary_text.delta' && event.delta !== undefined)
387
405
  onProgress?.({ type: 'reasoning_summary_delta', requestId, text: event.delta });
388
- if (binding.codecVersion === 2) {
406
+ if (strict && binding.codecVersion === 2) {
389
407
  if (event.item?.type === 'reasoning' && typeof event.output_index === 'number')
390
408
  reasoningIndices.add(event.output_index);
391
409
  if (event.type.startsWith('response.reasoning_text.') ||
@@ -400,13 +418,22 @@ function captureSse(capture, request, secrets, lifecycle, onProgress) {
400
418
  }
401
419
  if (event.type === 'response.output_text.delta' || event.type === 'response.refusal.delta') {
402
420
  const index = event.output_index ?? [...added].find(([, id]) => id === event.item_id)?.[0];
403
- if (index === undefined || event.delta === undefined)
421
+ if (index !== undefined && event.delta !== undefined)
422
+ onProgress?.({ type: 'text_delta', requestId, index, text: event.delta });
423
+ else if (strict)
404
424
  throw new GatewayError('protocol');
405
- onProgress?.({ type: 'text_delta', requestId, index, text: event.delta });
406
425
  }
407
426
  if (event.type === 'response.output_item.added' || event.type === 'response.output_item.done') {
408
427
  const index = event.output_index;
409
428
  const value = event.item;
429
+ if (!strict) {
430
+ if (event.type.endsWith('.added') &&
431
+ index !== null &&
432
+ index !== undefined &&
433
+ typeof value?.id === 'string')
434
+ added.set(index, value.id);
435
+ return '';
436
+ }
410
437
  if (index === undefined || index === null || !value || typeof value.id !== 'string')
411
438
  throw new GatewayError('protocol');
412
439
  if (event.type.endsWith('.added')) {
@@ -429,18 +456,21 @@ function captureSse(capture, request, secrets, lifecycle, onProgress) {
429
456
  hasTools: request.tools.length > 0,
430
457
  });
431
458
  if (event.type === 'response.completed' || event.type === 'response.incomplete') {
432
- const response = decodeResponse(event.response, binding);
459
+ const response = decodeResponse(event.response, binding, capabilities.responses.encryptedReasoning);
433
460
  const output = [...done.entries()].sort(([a], [b]) => a - b);
434
461
  if (response.status !== (event.type === 'response.completed' ? 'completed' : 'incomplete') ||
435
- added.size !== done.size ||
436
- output.some(([index], i) => index !== i) ||
437
- canonicalJson(response.output) !== canonicalJson(output.map(([, value]) => value)))
462
+ (strict &&
463
+ (added.size !== done.size ||
464
+ output.some(([index], i) => index !== i) ||
465
+ canonicalJson(response.output) !== canonicalJson(output.map(([, value]) => value)))))
438
466
  throw new GatewayError('native_capture_incomplete');
439
467
  capture.response = response;
440
468
  original.response = { ...event.response, output: response.output };
441
469
  terminal = true;
442
470
  }
443
- return `data: ${JSON.stringify(original)}\n\n`;
471
+ // In tolerant mode, Saturn publishes progress and reads output from the terminal response.
472
+ // The SDK only needs the terminal event to finish its stream.
473
+ return strict || terminal ? `data: ${JSON.stringify(original)}\n\n` : '';
444
474
  }
445
475
  return new TransformStream({
446
476
  transform(chunk, controller) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@saturn-universe/model",
3
- "version": "0.1.0",
3
+ "version": "0.1.2-dev.2",
4
4
  "license": "AGPL-3.0-only",
5
5
  "type": "module",
6
6
  "files": [
@@ -17,7 +17,7 @@
17
17
  "@ai-sdk/google": "4.0.114",
18
18
  "@ai-sdk/openai": "4.0.111",
19
19
  "@ai-sdk/openai-compatible": "3.0.87",
20
- "@saturn-universe/core": "0.1.0",
20
+ "@saturn-universe/core": "0.1.2-dev.2",
21
21
  "ai": "7.0.165",
22
22
  "zod": "4.6.0"
23
23
  }