@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/LICENSE +661 -0
- package/dist/codec.d.ts +12 -0
- package/dist/codec.js +129 -0
- package/dist/errors.d.ts +7 -0
- package/dist/errors.js +36 -0
- package/dist/index.d.ts +24 -0
- package/dist/index.js +540 -0
- package/dist/provider-errors.d.ts +13 -0
- package/dist/provider-errors.js +170 -0
- package/dist/sdk-adapter.d.ts +33 -0
- package/dist/sdk-adapter.js +315 -0
- package/dist/sdk-messages.d.ts +23 -0
- package/dist/sdk-messages.js +154 -0
- package/dist/wire.d.ts +61 -0
- package/dist/wire.js +481 -0
- package/package.json +21 -3
- package/README.md +0 -3
package/dist/codec.js
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { canonicalJson } from '@saturn-universe/core';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import { GatewayError } from './errors.js';
|
|
5
|
+
export const digest = (value) => createHash('sha256').update(canonicalJson(value)).digest('hex');
|
|
6
|
+
const item = z.discriminatedUnion('type', [
|
|
7
|
+
z
|
|
8
|
+
.object({
|
|
9
|
+
type: z.literal('message'),
|
|
10
|
+
id: z.string().min(1),
|
|
11
|
+
role: z.literal('assistant'),
|
|
12
|
+
phase: z.enum(['commentary', 'final_answer']).nullish(),
|
|
13
|
+
content: z.array(z.discriminatedUnion('type', [
|
|
14
|
+
z.object({ type: z.literal('output_text'), text: z.string() }).passthrough(),
|
|
15
|
+
z.object({ type: z.literal('refusal'), refusal: z.string() }).passthrough(),
|
|
16
|
+
])),
|
|
17
|
+
})
|
|
18
|
+
.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(),
|
|
27
|
+
z
|
|
28
|
+
.object({
|
|
29
|
+
type: z.literal('function_call'),
|
|
30
|
+
id: z.string().min(1),
|
|
31
|
+
call_id: z.string().min(1),
|
|
32
|
+
name: z.string().min(1),
|
|
33
|
+
arguments: z.string(),
|
|
34
|
+
})
|
|
35
|
+
.passthrough(),
|
|
36
|
+
]);
|
|
37
|
+
export const responsesCodec = {
|
|
38
|
+
id: 'saturn-responses',
|
|
39
|
+
version: 1,
|
|
40
|
+
decodeOutput(items) {
|
|
41
|
+
return items.map((value) => {
|
|
42
|
+
if (!['message', 'reasoning', 'function_call'].includes(String(value.type)))
|
|
43
|
+
throw new GatewayError('unsupported_item');
|
|
44
|
+
if (value.type === 'reasoning' && ('content' in value || 'reasoning_text' in value))
|
|
45
|
+
throw new GatewayError('unsupported_capability');
|
|
46
|
+
if (value.type === 'reasoning' &&
|
|
47
|
+
(typeof value.encrypted_content !== 'string' || !value.encrypted_content.trim()))
|
|
48
|
+
throw new GatewayError('continuation_unavailable');
|
|
49
|
+
if (!item.safeParse(value).success)
|
|
50
|
+
throw new GatewayError('invalid_output');
|
|
51
|
+
return { kind: value.type, value: structuredClone(value) };
|
|
52
|
+
});
|
|
53
|
+
},
|
|
54
|
+
encodePart(part, bytes, capabilities) {
|
|
55
|
+
if (part.type === 'image') {
|
|
56
|
+
if (!capabilities.images)
|
|
57
|
+
throw new GatewayError('unsupported_capability');
|
|
58
|
+
return {
|
|
59
|
+
type: 'input_image',
|
|
60
|
+
image_url: `data:${part.artifact.mediaType};base64,${Buffer.from(bytes).toString('base64')}`,
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
if (part.type !== 'file' || !capabilities.files)
|
|
64
|
+
throw new GatewayError('unsupported_capability');
|
|
65
|
+
return {
|
|
66
|
+
type: 'input_file',
|
|
67
|
+
file_data: `data:${part.artifact.mediaType};base64,${Buffer.from(bytes).toString('base64')}`,
|
|
68
|
+
filename: part.name,
|
|
69
|
+
};
|
|
70
|
+
},
|
|
71
|
+
replayItem(output) {
|
|
72
|
+
const input = { ...output.value };
|
|
73
|
+
const removedOutputOnlyPaths = [];
|
|
74
|
+
for (const key of ['status', 'created_by', 'parsed'])
|
|
75
|
+
if (key in input) {
|
|
76
|
+
delete input[key];
|
|
77
|
+
removedOutputOnlyPaths.push(key);
|
|
78
|
+
}
|
|
79
|
+
return { input: input, removedOutputOnlyPaths };
|
|
80
|
+
},
|
|
81
|
+
};
|
|
82
|
+
export const responsesCodecs = {
|
|
83
|
+
get(id, version) {
|
|
84
|
+
if (id !== responsesCodec.id || ![1, 2].includes(version))
|
|
85
|
+
throw new GatewayError('unsupported_capability');
|
|
86
|
+
return version === 1 ? responsesCodec : responsesCodecV2;
|
|
87
|
+
},
|
|
88
|
+
};
|
|
89
|
+
const privateContent = z.array(z.object({ type: z.literal('reasoning_text'), text: z.string() }).strict());
|
|
90
|
+
export function normalizeReasoning(value) {
|
|
91
|
+
if (value.type !== 'reasoning')
|
|
92
|
+
return { value, removed: [] };
|
|
93
|
+
if (('content' in value && value.content !== null && !privateContent.safeParse(value.content).success) ||
|
|
94
|
+
('reasoning_text' in value && value.reasoning_text !== null && typeof value.reasoning_text !== 'string'))
|
|
95
|
+
throw new GatewayError('invalid_output');
|
|
96
|
+
const normalized = { ...value };
|
|
97
|
+
const removed = ['content', 'reasoning_text'].filter((key) => key in normalized);
|
|
98
|
+
for (const key of removed)
|
|
99
|
+
delete normalized[key];
|
|
100
|
+
return { value: normalized, removed };
|
|
101
|
+
}
|
|
102
|
+
export const responsesCodecV2 = {
|
|
103
|
+
...responsesCodec,
|
|
104
|
+
version: 2,
|
|
105
|
+
decodeOutput(items, binding) {
|
|
106
|
+
if (items.some((value) => value.type === 'reasoning' &&
|
|
107
|
+
(typeof value.encrypted_content !== 'string' || !value.encrypted_content.trim())))
|
|
108
|
+
throw new GatewayError('continuation_unavailable');
|
|
109
|
+
return responsesCodec.decodeOutput(items.map((value) => normalizeReasoning(value).value), binding);
|
|
110
|
+
},
|
|
111
|
+
};
|
|
112
|
+
export function decodeToolCalls(request, outputItems) {
|
|
113
|
+
const toolCalls = outputItems.flatMap((item, outputIndex) => {
|
|
114
|
+
if (item.kind !== 'function_call')
|
|
115
|
+
return [];
|
|
116
|
+
const name = request.tools.find((tool) => tool.wireName === item.value.name)?.canonicalName ?? item.value.name;
|
|
117
|
+
let args;
|
|
118
|
+
try {
|
|
119
|
+
args = { kind: 'json', value: JSON.parse(item.value.arguments) };
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
args = { kind: 'invalid', raw: item.value.arguments, reason: 'Invalid JSON arguments' };
|
|
123
|
+
}
|
|
124
|
+
return [{ outputIndex, providerCallId: item.value.call_id, toolName: name, arguments: args }];
|
|
125
|
+
});
|
|
126
|
+
if (new Set(toolCalls.map((call) => call.providerCallId)).size !== toolCalls.length)
|
|
127
|
+
throw new GatewayError('invalid_output');
|
|
128
|
+
return toolCalls;
|
|
129
|
+
}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { ModelError, ModelErrorCode } from '@saturn-universe/core';
|
|
2
|
+
export declare class GatewayError extends Error {
|
|
3
|
+
readonly error: ModelError;
|
|
4
|
+
constructor(code: ModelErrorCode, retryable?: boolean, outcomeUnknown?: boolean, retryAfterMs?: number, message?: string, extra?: Pick<ModelError, 'details' | 'usage'> & ErrorOptions);
|
|
5
|
+
withObservation(details: ModelError['details'], usage: ModelError['usage']): GatewayError;
|
|
6
|
+
}
|
|
7
|
+
export declare function classify(error: unknown, signal: AbortSignal): GatewayError;
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
export class GatewayError extends Error {
|
|
2
|
+
error;
|
|
3
|
+
constructor(code, retryable = false, outcomeUnknown = false, retryAfterMs, message = `Model request failed: ${code}`, extra) {
|
|
4
|
+
super(message, extra?.cause === undefined ? undefined : { cause: extra.cause });
|
|
5
|
+
this.name = 'ModelGatewayError';
|
|
6
|
+
this.error = {
|
|
7
|
+
code,
|
|
8
|
+
message: this.message,
|
|
9
|
+
retryable,
|
|
10
|
+
outcomeUnknown,
|
|
11
|
+
...(retryAfterMs === undefined ? {} : { retryAfterMs }),
|
|
12
|
+
...(extra?.details ? { details: extra.details } : {}),
|
|
13
|
+
...(extra?.usage ? { usage: extra.usage } : {}),
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
withObservation(details, usage) {
|
|
17
|
+
const error = this.error;
|
|
18
|
+
const observedDetails = error.details ?? details;
|
|
19
|
+
const observedUsage = error.usage ?? usage;
|
|
20
|
+
return new GatewayError(error.code, error.retryable, error.outcomeUnknown, error.retryAfterMs, error.message, {
|
|
21
|
+
...(observedDetails ? { details: observedDetails } : {}),
|
|
22
|
+
...(observedUsage ? { usage: observedUsage } : {}),
|
|
23
|
+
cause: this.cause,
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
export function classify(error, signal) {
|
|
28
|
+
if (signal.aborted) {
|
|
29
|
+
if (signal.reason instanceof GatewayError)
|
|
30
|
+
return signal.reason;
|
|
31
|
+
return new GatewayError(signal.reason?.name === 'TimeoutError' ? 'timeout' : 'cancelled', signal.reason?.name === 'TimeoutError', true);
|
|
32
|
+
}
|
|
33
|
+
if (error instanceof GatewayError)
|
|
34
|
+
return error;
|
|
35
|
+
return new GatewayError('protocol');
|
|
36
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { ModelCapabilities, ProviderBinding, ProviderProfile, ModelRef, ModelRequest, ModelResponse, ModelInvocationOptions, ModelGateway } from '@saturn-universe/core';
|
|
2
|
+
export { GatewayError } from './errors.js';
|
|
3
|
+
export { digest, responsesCodec, responsesCodecV2, responsesCodecs } from './codec.js';
|
|
4
|
+
export interface CredentialVault {
|
|
5
|
+
resolve(ref: string): Promise<string>;
|
|
6
|
+
}
|
|
7
|
+
export declare class ProviderRegistry {
|
|
8
|
+
private readonly profiles;
|
|
9
|
+
register(profile: ProviderProfile): () => void;
|
|
10
|
+
deactivate(profileRef: string): void;
|
|
11
|
+
activate(profileRef: string): void;
|
|
12
|
+
isActive(profileRef: string): boolean;
|
|
13
|
+
listActive(): readonly ProviderProfile[];
|
|
14
|
+
/** Remove the profile after callers that need the old revision have drained. */
|
|
15
|
+
release(profileRef: string): boolean;
|
|
16
|
+
resolve(model: ModelRef): {
|
|
17
|
+
profile: ProviderProfile;
|
|
18
|
+
binding: ProviderBinding;
|
|
19
|
+
capabilities: ModelCapabilities;
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
export declare function createModelGateway(registry: ProviderRegistry, credentials: CredentialVault, transport?: typeof fetch): ModelGateway & {
|
|
23
|
+
execute(request: ModelRequest, options: ModelInvocationOptions): Promise<ModelResponse>;
|
|
24
|
+
};
|