@saturn-universe/model 0.1.1 → 0.1.2-dev.10

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,15 +1,8 @@
1
- import { z } from 'zod';
2
- import type { ModelRequest, ModelToolCall, ResponsesCodec, ResponsesOutputItem } from '@saturn-universe/core';
1
+ import type { ModelRequest, ModelToolCall, ProtocolJsonObject, ResponsesCodec, ResponsesOutputItem } from '@saturn-universe/core';
3
2
  export declare const digest: (value: unknown) => string;
4
- export declare const reasoningItemSchema: z.ZodObject<{
5
- type: z.ZodLiteral<"reasoning">;
6
- id: z.ZodString;
7
- summary: z.ZodArray<z.ZodObject<{
8
- type: z.ZodLiteral<"summary_text">;
9
- text: z.ZodString;
10
- }, z.core.$loose>>;
11
- }, z.core.$strip>;
12
- export declare function hasEncryptedReasoning(value: import('@saturn-universe/core').ProtocolJsonObject): boolean;
3
+ export declare function isResponsesOutputItem(value: ProtocolJsonObject): boolean;
4
+ export declare function reasoningSummaryParts(value: ProtocolJsonObject): string[];
5
+ export declare function hasEncryptedReasoning(value: ProtocolJsonObject): boolean;
13
6
  export declare const responsesCodec: ResponsesCodec;
14
7
  export declare const responsesCodecs: {
15
8
  get(id: string, version: number): ResponsesCodec;
package/dist/codec.js CHANGED
@@ -3,11 +3,31 @@ 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
- export const reasoningItemSchema = z.object({
6
+ const reasoningItemSchema = z.object({
7
7
  type: z.literal('reasoning'),
8
8
  id: z.string().min(1),
9
9
  summary: z.array(z.object({ type: z.literal('summary_text'), text: z.string() }).passthrough()),
10
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
+ }
11
31
  export function hasEncryptedReasoning(value) {
12
32
  return typeof value.encrypted_content === 'string' && Boolean(value.encrypted_content.trim());
13
33
  }
@@ -40,7 +60,7 @@ export const responsesCodec = {
40
60
  version: 1,
41
61
  decodeOutput(items) {
42
62
  return items.map((value) => {
43
- if (!['message', 'reasoning', 'function_call'].includes(String(value.type)))
63
+ if (!isResponsesOutputItem(value))
44
64
  throw new GatewayError('unsupported_item');
45
65
  if (value.type === 'reasoning' && ('content' in value || 'reasoning_text' in value))
46
66
  throw new GatewayError('unsupported_capability');
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');
@@ -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.js CHANGED
@@ -2,7 +2,7 @@ import { canonicalJson, maxModelReasoningSummaryLength } from '@saturn-universe/
2
2
  import { z } from 'zod';
3
3
  import { GatewayError } from './errors.js';
4
4
  import { providerFailure, transportFailure } from './provider-errors.js';
5
- import { hasEncryptedReasoning, normalizeReasoning, reasoningItemSchema, responsesCodecs } 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,
@@ -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,
@@ -295,34 +296,33 @@ function decodeResponse(value, binding, encryptedReasoning) {
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');
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;
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));
302
306
  const removedPaths = [];
303
307
  const outputItems = responsesCodecs
304
308
  .get(binding.codecId, binding.codecVersion)
305
309
  .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'))
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
+ });
317
+ if (raw.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'))
315
322
  throw new GatewayError('native_capture_incomplete');
316
323
  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
- })
324
+ ? raw.output
325
+ .flatMap((value) => (value.type === 'reasoning' ? reasoningSummaryParts(value) : []))
326
326
  .join('\n')
327
327
  .slice(0, maxModelReasoningSummaryLength)
328
328
  : undefined;
@@ -354,6 +354,7 @@ function captureSse(capture, request, capabilities, secrets, lifecycle, onProgre
354
354
  const added = new Map();
355
355
  const reasoningIndices = new Set();
356
356
  const binding = request.binding;
357
+ const strict = capabilities.responses.encryptedReasoning === 'required';
357
358
  const requestId = request.id;
358
359
  function activity(stage, text) {
359
360
  onProgress?.({ type: 'activity', requestId, stage, bytes: Buffer.byteLength(text) });
@@ -402,7 +403,7 @@ function captureSse(capture, request, capabilities, secrets, lifecycle, onProgre
402
403
  activity(event.type, data);
403
404
  if (event.type === 'response.reasoning_summary_text.delta' && event.delta !== undefined)
404
405
  onProgress?.({ type: 'reasoning_summary_delta', requestId, text: event.delta });
405
- if (binding.codecVersion === 2) {
406
+ if (strict && binding.codecVersion === 2) {
406
407
  if (event.item?.type === 'reasoning' && typeof event.output_index === 'number')
407
408
  reasoningIndices.add(event.output_index);
408
409
  if (event.type.startsWith('response.reasoning_text.') ||
@@ -417,13 +418,22 @@ function captureSse(capture, request, capabilities, secrets, lifecycle, onProgre
417
418
  }
418
419
  if (event.type === 'response.output_text.delta' || event.type === 'response.refusal.delta') {
419
420
  const index = event.output_index ?? [...added].find(([, id]) => id === event.item_id)?.[0];
420
- 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)
421
424
  throw new GatewayError('protocol');
422
- onProgress?.({ type: 'text_delta', requestId, index, text: event.delta });
423
425
  }
424
426
  if (event.type === 'response.output_item.added' || event.type === 'response.output_item.done') {
425
427
  const index = event.output_index;
426
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
+ }
427
437
  if (index === undefined || index === null || !value || typeof value.id !== 'string')
428
438
  throw new GatewayError('protocol');
429
439
  if (event.type.endsWith('.added')) {
@@ -449,15 +459,18 @@ function captureSse(capture, request, capabilities, secrets, lifecycle, onProgre
449
459
  const response = decodeResponse(event.response, binding, capabilities.responses.encryptedReasoning);
450
460
  const output = [...done.entries()].sort(([a], [b]) => a - b);
451
461
  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)))
462
+ (strict &&
463
+ (added.size !== done.size ||
464
+ output.some(([index], i) => index !== i) ||
465
+ canonicalJson(response.output) !== canonicalJson(output.map(([, value]) => value)))))
455
466
  throw new GatewayError('native_capture_incomplete');
456
467
  capture.response = response;
457
468
  original.response = { ...event.response, output: response.output };
458
469
  terminal = true;
459
470
  }
460
- 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` : '';
461
474
  }
462
475
  return new TransformStream({
463
476
  transform(chunk, controller) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@saturn-universe/model",
3
- "version": "0.1.1",
3
+ "version": "0.1.2-dev.10",
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.1",
20
+ "@saturn-universe/core": "0.1.2-dev.10",
21
21
  "ai": "7.0.165",
22
22
  "zod": "4.6.0"
23
23
  }