@saturn-universe/model 0.0.0-stage → 0.1.0

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.js ADDED
@@ -0,0 +1,540 @@
1
+ import { z } from 'zod';
2
+ import { createOpenAI } from '@ai-sdk/openai';
3
+ import { generateText, streamText, jsonSchema, stepCountIs, Output } from 'ai';
4
+ import { canonicalJson, defaultModelTotalTimeoutMs, modelConfiguration, providerProtocols, } from '@saturn-universe/core';
5
+ import { GatewayError, classify } from './errors.js';
6
+ import { decodeToolCalls, digest, responsesCodecs } from './codec.js';
7
+ import { acceptSdkResponse, createSdkSettings, sdkStreamProgress } from './sdk-adapter.js';
8
+ import { sdkProviderFailure } from './provider-errors.js';
9
+ import { createWireBridge } from './wire.js';
10
+ export { GatewayError } from './errors.js';
11
+ export { digest, responsesCodec, responsesCodecV2, responsesCodecs } from './codec.js';
12
+ export class ProviderRegistry {
13
+ profiles = new Map();
14
+ register(profile) {
15
+ 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') ||
30
+ !profile.apiKeyRef ||
31
+ !profile.credentialScopeRef ||
32
+ this.profiles.has(profileRef))
33
+ throw new GatewayError('profile_mismatch');
34
+ if (Object.entries(profile.headers).some(([key, value]) => /auth|api[-_]?key|token|secret|cookie/i.test(key) && value.kind !== 'secret_ref'))
35
+ throw new GatewayError('profile_mismatch');
36
+ responsesCodecs.get(profile.codecId, profile.codecVersion);
37
+ const registration = Symbol();
38
+ this.profiles.set(profileRef, { profile: structuredClone(profile), active: true, registration });
39
+ return () => {
40
+ const entry = this.profiles.get(profileRef);
41
+ if (entry?.registration === registration)
42
+ entry.active = false;
43
+ };
44
+ }
45
+ deactivate(profileRef) {
46
+ const entry = this.profiles.get(profileRef);
47
+ if (entry)
48
+ entry.active = false;
49
+ }
50
+ activate(profileRef) {
51
+ const entry = this.profiles.get(profileRef);
52
+ if (entry)
53
+ entry.active = true;
54
+ }
55
+ isActive(profileRef) {
56
+ return this.profiles.get(profileRef)?.active ?? false;
57
+ }
58
+ listActive() {
59
+ return [...this.profiles.values()]
60
+ .filter((entry) => entry.active)
61
+ .map((entry) => structuredClone(entry.profile));
62
+ }
63
+ /** Remove the profile after callers that need the old revision have drained. */
64
+ release(profileRef) {
65
+ return this.profiles.delete(profileRef);
66
+ }
67
+ 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)
71
+ throw new GatewayError('profile_mismatch');
72
+ const endpointFingerprint = digest(profile.baseURL.replace(/\/$/, ''));
73
+ const capabilityDigest = digest(capabilities);
74
+ const binding = {
75
+ profileId: profile.id,
76
+ profileRevision: profile.revision,
77
+ endpointFingerprint,
78
+ credentialScopeRef: profile.credentialScopeRef,
79
+ modelId: model.modelId,
80
+ codecId: profile.codecId,
81
+ codecVersion: profile.codecVersion,
82
+ capabilityDigest,
83
+ compatibilityKey: digest({
84
+ endpointFingerprint,
85
+ scope: profile.credentialScopeRef,
86
+ model: model.modelId,
87
+ codec: [profile.codecId, profile.codecVersion],
88
+ capabilityDigest,
89
+ ...(profile.protocol === 'openai-responses' ? {} : { protocol: profile.protocol }),
90
+ }),
91
+ };
92
+ return structuredClone({ profile, binding, capabilities });
93
+ }
94
+ }
95
+ export function createModelGateway(registry, credentials, transport = (input, init) => fetch(input, init)) {
96
+ async function prepare(request, options, timeouts, capture, onProgress) {
97
+ const { signal } = timeouts;
98
+ signal.throwIfAborted();
99
+ const { profile, binding, capabilities } = registry.resolve(request.model);
100
+ validateRequest(request, binding, capabilities, profile.protocol);
101
+ const { apiKey, headers, secrets } = await withAbort(signal, resolveAuthentication(profile, credentials));
102
+ if (profile.protocol !== 'openai-responses')
103
+ return {
104
+ protocol: profile.protocol,
105
+ settings: createSdkSettings(request, { protocol: profile.protocol, baseURL: profile.baseURL, apiKey, headers, secrets }, capabilities, timeouts, transport, capture, options, onProgress !== undefined),
106
+ capabilities,
107
+ secrets,
108
+ };
109
+ const provider = createOpenAI({
110
+ baseURL: profile.baseURL,
111
+ apiKey,
112
+ headers,
113
+ fetch: createWireBridge(request, profile, capabilities, signal, capture, secrets, { ...timeouts, promptCacheOnly: options.promptCacheOnly === true }, transport, onProgress),
114
+ });
115
+ const tools = Object.fromEntries(request.tools.map((tool) => [
116
+ tool.wireName,
117
+ { description: tool.description, inputSchema: jsonSchema(tool.inputSchema), strict: false },
118
+ ]));
119
+ const settings = {
120
+ model: provider.responses(request.model.modelId),
121
+ prompt: 'Saturn native input is supplied by the Responses wire bridge.',
122
+ tools,
123
+ maxRetries: 0,
124
+ stopWhen: stepCountIs(1),
125
+ maxOutputTokens: request.maxOutputTokens,
126
+ abortSignal: signal,
127
+ providerOptions: {
128
+ openai: {
129
+ store: false,
130
+ strictJsonSchema: request.output.kind === 'json',
131
+ forceReasoning: capabilities.responses.reasoningModel,
132
+ },
133
+ },
134
+ ...(request.temperature === undefined ? {} : { temperature: request.temperature }),
135
+ ...(request.output.kind === 'json'
136
+ ? { output: Output.object({ schema: jsonSchema(request.output.schema), name: request.output.name }) }
137
+ : {}),
138
+ };
139
+ return { protocol: profile.protocol, settings, capabilities, secrets };
140
+ }
141
+ async function execute(request, options) {
142
+ const timeouts = startRequestTimeouts(request, options);
143
+ const capture = { source: 'wire_json', sent: 0 };
144
+ let sdkSecrets;
145
+ try {
146
+ const prepared = await prepare(request, options, timeouts, capture);
147
+ if (prepared.protocol !== 'openai-responses')
148
+ sdkSecrets = prepared.secrets;
149
+ const result = await withAbort(timeouts.signal, generateText(prepared.settings));
150
+ timeouts.signal.throwIfAborted();
151
+ return prepared.protocol === 'openai-responses'
152
+ ? accept(request, capture, prepared.capabilities, result)
153
+ : acceptSdkResponse(request, prepared.protocol, result, prepared.secrets);
154
+ }
155
+ catch (error) {
156
+ throw classify(capture.error ??
157
+ (sdkSecrets ? sdkProviderFailure(error, sdkSecrets, request.tools.length > 0) : error), timeouts.signal).withObservation(timeouts.details(), capture.usage);
158
+ }
159
+ finally {
160
+ timeouts.close();
161
+ }
162
+ }
163
+ async function publishStream(request, options, timeouts, publish) {
164
+ const capture = { source: 'wire_json', sent: 0 };
165
+ let sdkSecrets;
166
+ try {
167
+ const prepared = await prepare(request, options, timeouts, capture, publish);
168
+ if (prepared.protocol !== 'openai-responses')
169
+ sdkSecrets = prepared.secrets;
170
+ if (!prepared.capabilities.streaming)
171
+ throw new GatewayError('unsupported_capability');
172
+ const result = streamText({
173
+ ...prepared.settings,
174
+ onError: () => {
175
+ /* SDK diagnostics stay inside the adapter. */
176
+ },
177
+ });
178
+ const reader = result.fullStream.getReader();
179
+ const progress = prepared.protocol === 'openai-responses'
180
+ ? undefined
181
+ : sdkStreamProgress(request, prepared.secrets, publish);
182
+ try {
183
+ while (true) {
184
+ const part = await withAbort(timeouts.signal, reader.read());
185
+ if (part.done)
186
+ break;
187
+ if (part.value.type === 'error')
188
+ throw part.value.error;
189
+ progress?.(part.value);
190
+ }
191
+ }
192
+ finally {
193
+ void reader.cancel().catch(() => undefined);
194
+ reader.releaseLock();
195
+ }
196
+ timeouts.signal.throwIfAborted();
197
+ const [text, content, toolCalls, usage, sdkResponse, finishReason] = await withAbort(timeouts.signal, Promise.all([
198
+ result.text,
199
+ result.content,
200
+ result.toolCalls,
201
+ result.usage,
202
+ result.response,
203
+ result.finishReason,
204
+ ]));
205
+ timeouts.signal.throwIfAborted();
206
+ const sdk = {
207
+ text,
208
+ content,
209
+ toolCalls,
210
+ usage,
211
+ response: sdkResponse,
212
+ finishReason,
213
+ };
214
+ const response = prepared.protocol === 'openai-responses'
215
+ ? accept(request, capture, prepared.capabilities, sdk)
216
+ : acceptSdkResponse(request, prepared.protocol, sdk, prepared.secrets);
217
+ for (const [callIndex, call] of response.toolCalls.entries())
218
+ publish({
219
+ type: 'tool_delta',
220
+ requestId: request.id,
221
+ callIndex,
222
+ fragment: String(response.continuation.outputItems[call.outputIndex].value.arguments),
223
+ });
224
+ publish({ type: 'usage', requestId: request.id, usage: response.usage });
225
+ publish({ type: 'finished', requestId: request.id, response });
226
+ }
227
+ catch (error) {
228
+ publish({
229
+ type: 'failed',
230
+ requestId: request.id,
231
+ error: classify(capture.error ??
232
+ (sdkSecrets ? sdkProviderFailure(error, sdkSecrets, request.tools.length > 0) : error), timeouts.signal).withObservation(timeouts.details(), capture.usage).error,
233
+ });
234
+ }
235
+ finally {
236
+ timeouts.close();
237
+ }
238
+ }
239
+ return {
240
+ async describe(model) {
241
+ const { binding, capabilities } = registry.resolve(model);
242
+ return { binding, capabilities };
243
+ },
244
+ validateRequest(request) {
245
+ const { profile, binding, capabilities } = registry.resolve(request.model);
246
+ validateRequest(request, binding, capabilities, profile.protocol);
247
+ },
248
+ execute,
249
+ generate: execute,
250
+ async *stream(request, options) {
251
+ yield { type: 'started', requestId: request.id };
252
+ const timeouts = startRequestTimeouts(request, options);
253
+ let cancelled = false;
254
+ // Wire-only frames may never produce a part in the SDK stream.
255
+ const events = new ReadableStream({
256
+ start(controller) {
257
+ void publishStream(request, options, timeouts, (event) => {
258
+ if (!cancelled)
259
+ controller.enqueue(event);
260
+ }).then(() => {
261
+ if (!cancelled)
262
+ controller.close();
263
+ }, (error) => {
264
+ if (!cancelled)
265
+ controller.error(error);
266
+ });
267
+ },
268
+ cancel() {
269
+ cancelled = true;
270
+ timeouts.close();
271
+ },
272
+ });
273
+ yield* events;
274
+ },
275
+ };
276
+ }
277
+ function startRequestTimeouts(request, options) {
278
+ const controller = new AbortController();
279
+ const signal = AbortSignal.any([options.signal, controller.signal]);
280
+ const idleMs = options.streamIdleTimeoutMs ?? options.timeoutMs;
281
+ const totalMs = options.requestTotalTimeoutMs ??
282
+ defaultModelTotalTimeoutMs(Math.max(idleMs, options.timeoutMs), request.responsesOptions.reasoning?.effort);
283
+ let idle;
284
+ let total;
285
+ let deadline;
286
+ let phase = 'awaiting_headers';
287
+ const startedAt = performance.now();
288
+ const details = () => ({
289
+ phase,
290
+ elapsedMs: Math.round(performance.now() - startedAt),
291
+ });
292
+ const expire = (timeoutKind, message) => controller.abort(new GatewayError('timeout', timeoutKind !== 'deadline', true, undefined, message, {
293
+ details: { ...details(), timeoutKind },
294
+ }));
295
+ const clear = () => {
296
+ clearTimeout(idle);
297
+ clearTimeout(total);
298
+ clearTimeout(deadline);
299
+ };
300
+ const onActivity = (nextPhase = phase) => {
301
+ if (signal.aborted)
302
+ return;
303
+ phase = nextPhase;
304
+ clearTimeout(idle);
305
+ idle = setTimeout(() => expire('idle', 'Model stream idle timeout'), idleMs);
306
+ };
307
+ if (!signal.aborted) {
308
+ signal.addEventListener('abort', clear, { once: true });
309
+ onActivity();
310
+ total = setTimeout(() => expire('total', 'Model request total timeout'), totalMs);
311
+ if (options.deadlineTimeoutMs !== undefined)
312
+ deadline = setTimeout(() => expire('deadline', 'Run or Turn deadline reached during model request'), options.deadlineTimeoutMs);
313
+ }
314
+ return { signal, onActivity, details, close: () => controller.abort() };
315
+ }
316
+ async function withAbort(signal, pending) {
317
+ let onAbort;
318
+ const aborted = new Promise((_, reject) => {
319
+ onAbort = () => reject(signal.reason);
320
+ if (signal.aborted)
321
+ onAbort();
322
+ else
323
+ signal.addEventListener('abort', onAbort, { once: true });
324
+ });
325
+ try {
326
+ return await Promise.race([pending, aborted]);
327
+ }
328
+ finally {
329
+ signal.removeEventListener('abort', onAbort);
330
+ }
331
+ }
332
+ async function resolveAuthentication(profile, credentials) {
333
+ const headers = {};
334
+ const secrets = [];
335
+ try {
336
+ for (const [key, value] of Object.entries(profile.headers)) {
337
+ const resolved = value.kind === 'secret_ref' ? await credentials.resolve(value.ref) : value.value;
338
+ headers[key] = resolved;
339
+ if (value.kind === 'secret_ref')
340
+ secrets.push(resolved);
341
+ }
342
+ const apiKey = await credentials.resolve(profile.apiKeyRef);
343
+ secrets.push(apiKey);
344
+ if (secrets.some((secret) => !secret.trim()))
345
+ throw new GatewayError('auth');
346
+ return { apiKey, headers, secrets };
347
+ }
348
+ catch {
349
+ throw new GatewayError('auth');
350
+ }
351
+ }
352
+ function validateRequest(request, binding, capabilities, protocol) {
353
+ if (canonicalJson(request.binding) !== canonicalJson(binding) ||
354
+ canonicalJson(request.responses.binding) !== canonicalJson(binding))
355
+ throw new GatewayError('profile_mismatch');
356
+ if (request.responses.fullInputDigest !== digest(request.responses.fullInput))
357
+ throw new GatewayError('continuation_mismatch');
358
+ const r = capabilities.responses;
359
+ const options = request.responsesOptions;
360
+ const instructions = request.messages
361
+ .filter((message) => message.role === 'system')
362
+ .map((message) => message.content)
363
+ .join('\n\n') ||
364
+ request.responses.instructions ||
365
+ '';
366
+ if (request.responses.configurationDigest !==
367
+ digest(modelConfiguration({
368
+ binding,
369
+ instructions,
370
+ placement: r.instructionPlacement,
371
+ tools: request.tools,
372
+ output: request.output,
373
+ reasoning: options.reasoning,
374
+ })))
375
+ throw new GatewayError('continuation_mismatch');
376
+ if (r.instructionPlacement === 'instructions' && request.responses.instructions !== instructions)
377
+ throw new GatewayError('continuation_mismatch');
378
+ validateCapabilities(request, capabilities, protocol);
379
+ if (new Set(request.tools.map((t) => t.wireName)).size !== request.tools.length)
380
+ throw new GatewayError('invalid_request');
381
+ for (const value of request.responses.fullInput)
382
+ if (value.type === 'item_reference' ||
383
+ (protocol === 'openai-responses' &&
384
+ value.type === 'reasoning' &&
385
+ (typeof value.encrypted_content !== 'string' || !value.encrypted_content)))
386
+ throw new GatewayError('continuation_unavailable');
387
+ }
388
+ function validateCapabilities(request, capabilities, protocol) {
389
+ const r = capabilities.responses, options = request.responsesOptions;
390
+ const nativeResponses = protocol === 'openai-responses';
391
+ if ((nativeResponses && (r.store === 'unsupported' || r.truncation === 'unsupported')) ||
392
+ (request.tools.length && !capabilities.tools) ||
393
+ (request.output.kind === 'json' && !capabilities.structuredOutput) ||
394
+ request.maxOutputTokens > capabilities.maxOutputTokens ||
395
+ request.maxOutputTokens < 1)
396
+ throw new GatewayError('unsupported_capability');
397
+ if ((options.reasoning?.effort &&
398
+ (!r.reasoningModel ||
399
+ (r.reasoningEfforts.length > 0 && !r.reasoningEfforts.includes(options.reasoning.effort)))) ||
400
+ (options.reasoning?.summary && (!nativeResponses || !r.reasoningSummary)) ||
401
+ (options.reasoning?.context &&
402
+ (!nativeResponses || !r.reasoningContexts.includes(options.reasoning.context))) ||
403
+ (options.parallelToolCalls !== undefined && (protocol === 'gemini' || !r.parallelToolCallsParameter)) ||
404
+ (options.metadata && (!nativeResponses || !r.metadataParameter)) ||
405
+ options.extensionOptions)
406
+ throw new GatewayError('unsupported_capability');
407
+ if ((options.parallelToolCalls === true && !capabilities.parallelToolCalls) ||
408
+ (nativeResponses && r.encryptedReasoning === 'required' && r.encryptedContentInclude === 'unsupported'))
409
+ throw new GatewayError('unsupported_capability');
410
+ }
411
+ function accept(request, capture, capabilities, sdk) {
412
+ const raw = capture.response;
413
+ if (!raw)
414
+ throw new GatewayError('native_capture_incomplete');
415
+ const outputItems = raw.outputItems;
416
+ if (capabilities.responses.assistantPhase === 'not_emitted' &&
417
+ outputItems.some((item) => item.kind === 'message' && item.value.phase !== null && item.value.phase !== undefined))
418
+ throw new GatewayError('unsupported_capability');
419
+ const content = outputItems.flatMap((item) => item.kind === 'message'
420
+ ? item.value.content.map((part) => ({
421
+ type: 'text',
422
+ text: String(part.type === 'refusal' ? part.refusal : part.text),
423
+ }))
424
+ : []);
425
+ const toolCalls = decodeToolCalls(request, outputItems);
426
+ const nativeText = content.map((part) => part.text).join('');
427
+ validateSdkResponse(raw, sdk, toolCalls, nativeText);
428
+ const usage = raw.usage;
429
+ if (sdk.usage.inputTokens !== usage.input_tokens || sdk.usage.outputTokens !== usage.output_tokens)
430
+ throw new GatewayError('invalid_output');
431
+ const incomplete = raw.incomplete_details;
432
+ const cached = usage.input_tokens_details?.cached_tokens;
433
+ const reasoning = usage.output_tokens_details?.reasoning_tokens;
434
+ if ((cached !== undefined && sdk.usage.inputTokenDetails?.cacheReadTokens !== cached) ||
435
+ (reasoning !== undefined && sdk.usage.outputTokenDetails?.reasoningTokens !== reasoning))
436
+ throw new GatewayError('continuation_mismatch');
437
+ const finishReason = raw.status === 'incomplete'
438
+ ? incomplete?.reason === 'content_filter'
439
+ ? 'content_filter'
440
+ : 'length'
441
+ : toolCalls.length
442
+ ? 'tool_calls'
443
+ : outputItems.some((item) => item.kind === 'message' && item.value.content.some((part) => part.type === 'refusal'))
444
+ ? 'content_filter'
445
+ : 'stop';
446
+ const messageItems = outputItems.filter((item) => item.kind === 'message');
447
+ const hasCommentary = messageItems.some((item) => item.value.phase === 'commentary');
448
+ const hasFinalAnswer = messageItems.some((item) => item.value.phase === 'final_answer');
449
+ const hasFinal = messageItems.length > 0 &&
450
+ (capabilities.responses.assistantPhase === 'not_emitted' || hasFinalAnswer || !hasCommentary);
451
+ const turnDisposition = toolCalls.length
452
+ ? 'tool_calls'
453
+ : finishReason === 'stop' && hasFinal && nativeText.trim()
454
+ ? 'final'
455
+ : 'continue';
456
+ let structuredOutput;
457
+ if (request.output.kind === 'json' && turnDisposition === 'final') {
458
+ try {
459
+ structuredOutput = JSON.parse(nativeText);
460
+ if (!z.fromJSONSchema(request.output.schema).safeParse(structuredOutput).success)
461
+ throw new GatewayError('invalid_output');
462
+ }
463
+ catch {
464
+ throw new GatewayError('invalid_output');
465
+ }
466
+ }
467
+ return {
468
+ requestId: request.id,
469
+ providerResponseId: raw.id,
470
+ content,
471
+ toolCalls,
472
+ ...(structuredOutput === undefined ? {} : { structuredOutput }),
473
+ turnDisposition,
474
+ finishReason,
475
+ usage: {
476
+ inputTokens: usage.input_tokens,
477
+ outputTokens: usage.output_tokens,
478
+ accuracy: 'reported',
479
+ ...(cached === undefined ? {} : { cachedInputTokens: cached }),
480
+ ...(reasoning === undefined ? {} : { reasoningTokens: reasoning }),
481
+ },
482
+ continuation: {
483
+ version: 1,
484
+ protocol: 'openai-responses',
485
+ binding: request.binding,
486
+ epochId: request.responses.epochId,
487
+ responseId: raw.id,
488
+ sourceRequestId: request.id,
489
+ requestInputDigest: request.responses.fullInputDigest,
490
+ configurationDigest: request.responses.configurationDigest,
491
+ outputItems,
492
+ outputDigest: digest(outputItems.map((item) => item.value)),
493
+ providerMetadata: {
494
+ responseId: raw.id,
495
+ ...(raw.normalization === undefined ? {} : { normalization: raw.normalization }),
496
+ ...(raw.reasoning?.context === undefined ? {} : { reasoningContext: raw.reasoning.context }),
497
+ ...(raw.model === undefined ? {} : { model: raw.model }),
498
+ ...(raw.service_tier === null || raw.service_tier === undefined
499
+ ? {}
500
+ : { serviceTier: raw.service_tier }),
501
+ },
502
+ capture: { source: capture.source, complete: true },
503
+ },
504
+ };
505
+ }
506
+ function validateSdkResponse(raw, sdk, toolCalls, nativeText) {
507
+ const outputItems = raw.outputItems;
508
+ const sdkCalls = new Map(sdk.toolCalls.map((call) => [call.toolCallId, call]));
509
+ const texts = sdk.content?.filter((part) => part.type === 'text') ?? [];
510
+ const textById = new Map();
511
+ for (const part of texts) {
512
+ const metadata = part.providerMetadata?.openai;
513
+ if (!metadata?.itemId)
514
+ throw new GatewayError('continuation_mismatch');
515
+ textById.set(metadata.itemId, (textById.get(metadata.itemId) ?? '') + (part.text ?? ''));
516
+ const native = outputItems.find((item) => item.kind === 'message' && item.value.id === metadata.itemId);
517
+ if (!native ||
518
+ (metadata.phase !== undefined && metadata.phase !== null && metadata.phase !== native.value.phase))
519
+ throw new GatewayError('continuation_mismatch');
520
+ }
521
+ const textMatches = texts.length
522
+ ? outputItems
523
+ .filter((item) => item.kind === 'message')
524
+ .every((item) => item.kind === 'message' &&
525
+ (textById.get(item.value.id) ?? '') ===
526
+ item.value.content.map((part) => (part.type === 'refusal' ? part.refusal : part.text)).join(''))
527
+ : sdk.text === nativeText;
528
+ if (sdk.response.id !== raw.id ||
529
+ !textMatches ||
530
+ sdk.toolCalls.length !== toolCalls.length ||
531
+ sdkCalls.size !== toolCalls.length ||
532
+ toolCalls.some((call) => {
533
+ const normalized = sdkCalls.get(call.providerCallId);
534
+ return (!normalized ||
535
+ normalized.toolName !== outputItems[call.outputIndex].value.name ||
536
+ (call.arguments.kind === 'json' &&
537
+ canonicalJson(normalized.input) !== canonicalJson(call.arguments.value)));
538
+ }))
539
+ throw new GatewayError('continuation_mismatch');
540
+ }
@@ -0,0 +1,13 @@
1
+ import type { ModelFailureDetails } from '@saturn-universe/core';
2
+ import { GatewayError } from './errors.js';
3
+ export declare function transportFailure(error: unknown, details: ModelFailureDetails, secrets: readonly string[]): GatewayError;
4
+ interface FailureOptions {
5
+ status?: number | undefined;
6
+ retry?: string | null | undefined;
7
+ secrets?: readonly string[];
8
+ hasTools?: boolean;
9
+ }
10
+ export declare function providerFailure(value: unknown, { status, retry, secrets, hasTools }?: FailureOptions): GatewayError;
11
+ /** Provider errors embedded in an otherwise successful SDK stream. */
12
+ export declare function sdkProviderFailure(error: unknown, secrets: readonly string[], hasTools: boolean): unknown;
13
+ export {};