@saturn-universe/cli 0.1.0 → 0.1.2-dev.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/auth-config.js +56 -18
- package/dist/menu.d.ts +1 -1
- package/dist/menu.js +2 -2
- package/dist/provider-discovery.d.ts +6 -1
- package/dist/provider-discovery.js +118 -11
- package/dist/provider-pricing.js +4 -1
- package/dist/provider.js +32 -13
- package/dist/renderer.js +2 -1
- package/package.json +3 -3
package/dist/auth-config.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { readFile, rm } from 'node:fs/promises';
|
|
2
2
|
import { parse, stringify } from 'smol-toml';
|
|
3
|
-
import { credentialRefSchema, lookupModelMetadata, normalizeProviderBaseUrl, normalizeProviderProtocol, parseDotenvText, providerCredentialKey, resolveCredentialMap, userAuthCredentialsPath, userConfigPath, } from '@saturn-universe/protocol';
|
|
3
|
+
import { credentialRefSchema, lookupModelMetadata, normalizeProviderBaseUrl, normalizeProviderProtocol, parseDotenvText, providerCredentialKey, providerModelRouteSchema, providerPresets, resolveCredentialMap, userAuthCredentialsPath, userConfigPath, } from '@saturn-universe/protocol';
|
|
4
4
|
import { AuthError } from './cli-diagnostics.js';
|
|
5
5
|
import { atomicWriteText } from './config-file.js';
|
|
6
6
|
import { withUserConfigLock } from './config-lock.js';
|
|
@@ -46,12 +46,25 @@ function configuredProfiles(config) {
|
|
|
46
46
|
});
|
|
47
47
|
for (const [providerId, value] of Object.entries(table(config.providers))) {
|
|
48
48
|
const entry = table(value);
|
|
49
|
-
|
|
49
|
+
const modelTable = Array.isArray(entry.models) ? undefined : table(entry.models);
|
|
50
|
+
const models = modelTable ? Object.keys(modelTable) : entry.models;
|
|
51
|
+
if (!Array.isArray(models) || !models.length)
|
|
50
52
|
throw new AuthError('Could not read provider models in config.toml.');
|
|
51
|
-
|
|
53
|
+
const overrides = table(entry.model_overrides);
|
|
54
|
+
for (const model of models) {
|
|
52
55
|
if (typeof model !== 'string')
|
|
53
56
|
throw new AuthError('Could not read provider models in config.toml.');
|
|
54
|
-
|
|
57
|
+
const modelId = model.trim();
|
|
58
|
+
const modelRoute = providerModelRouteSchema.safeParse({
|
|
59
|
+
...table(own(overrides, modelId)),
|
|
60
|
+
...(modelTable ? table(own(modelTable, model)) : {}),
|
|
61
|
+
});
|
|
62
|
+
if (!modelRoute.success)
|
|
63
|
+
throw new AuthError('Could not read provider models in config.toml.');
|
|
64
|
+
profiles.push({
|
|
65
|
+
...read(providerId + '/' + modelId, providerId, modelId, entry, true),
|
|
66
|
+
modelRoute: modelRoute.data,
|
|
67
|
+
});
|
|
55
68
|
}
|
|
56
69
|
}
|
|
57
70
|
return profiles;
|
|
@@ -145,43 +158,63 @@ export async function saveProviderLogin(input, env) {
|
|
|
145
158
|
const providers = table(config.providers);
|
|
146
159
|
const previous = table(own(providers, input.providerId));
|
|
147
160
|
const priorOverrides = table(previous.model_overrides);
|
|
161
|
+
const priorModels = previous.models !== undefined && !Array.isArray(previous.models) ? table(previous.models) : undefined;
|
|
148
162
|
const credentialKey = providerCredentialKey(input.providerId);
|
|
149
163
|
const credentialRef = input.credentialRef ?? `env:${credentialKey}`;
|
|
164
|
+
const sharesOpenCodeKey = (id) => providerPresets.some((preset) => preset.id === id && preset.openCodeModelsUrl && credentialRef === 'env:' + preset.defaultEnvKey);
|
|
150
165
|
if (configuredProfiles(config).some((p) => p.providerId !== input.providerId &&
|
|
151
|
-
(p.credentialRef === credentialRef
|
|
166
|
+
((p.credentialRef === credentialRef &&
|
|
167
|
+
!(sharesOpenCodeKey(input.providerId) && sharesOpenCodeKey(p.providerId))) ||
|
|
152
168
|
(p.layered && providerCredentialKey(p.providerId) === credentialKey))))
|
|
153
169
|
throw new AuthError('The credential name is already used by another provider.');
|
|
154
170
|
const discovered = new Map(input.discovered.map((model) => [model.id, model]));
|
|
171
|
+
const useModelTable = priorModels || input.models.some((id) => discovered.get(id)?.protocol !== undefined);
|
|
155
172
|
const overrides = Object.fromEntries(input.models.flatMap((id) => {
|
|
156
173
|
const model = discovered.get(id);
|
|
157
174
|
const metadata = lookupModelMetadata(id);
|
|
158
|
-
const previous =
|
|
175
|
+
const previous = {
|
|
176
|
+
...table(own(priorOverrides, id)),
|
|
177
|
+
...(priorModels ? table(own(priorModels, id)) : {}),
|
|
178
|
+
};
|
|
179
|
+
const pricing = model?.priceSource === 'models.dev' || model?.priceSource === 'opencode'
|
|
180
|
+
? model.pricing
|
|
181
|
+
: undefined;
|
|
159
182
|
const values = {
|
|
160
|
-
...(model?.
|
|
183
|
+
...(model?.protocol === undefined ? {} : { protocol: model.protocol }),
|
|
184
|
+
...(model?.baseUrl === undefined ? {} : { base_url: model.baseUrl }),
|
|
185
|
+
...(model?.tools === undefined ? {} : { tools: model.tools }),
|
|
186
|
+
...(model?.structuredOutput === undefined ? {} : { structured_output: model.structuredOutput }),
|
|
187
|
+
...(model?.images === undefined ? {} : { images: model.images }),
|
|
188
|
+
...(model?.contextWindow !== undefined &&
|
|
189
|
+
(model.protocol || metadata?.contextWindow !== model.contextWindow)
|
|
161
190
|
? { context_window: model.contextWindow }
|
|
162
191
|
: {}),
|
|
163
|
-
...(model?.maxOutputTokens !== undefined &&
|
|
192
|
+
...(model?.maxOutputTokens !== undefined &&
|
|
193
|
+
(model.protocol || metadata?.maxOutputTokens !== model.maxOutputTokens)
|
|
164
194
|
? { max_output_tokens: model.maxOutputTokens }
|
|
165
195
|
: {}),
|
|
166
196
|
...(model?.reasoningModel !== undefined ? { reasoning_model: model.reasoningModel } : {}),
|
|
167
|
-
...(model?.reasoningModel !== false &&
|
|
197
|
+
...(model?.reasoningModel !== false &&
|
|
198
|
+
model?.reasoningEfforts &&
|
|
199
|
+
(model.protocol || model.reasoningEfforts.length)
|
|
168
200
|
? { reasoning_efforts: [...model.reasoningEfforts] }
|
|
169
201
|
: {}),
|
|
170
202
|
...(model?.defaultReasoningEffort
|
|
171
203
|
? { default_reasoning_effort: model.defaultReasoningEffort }
|
|
172
204
|
: {}),
|
|
173
|
-
...
|
|
205
|
+
...previous,
|
|
206
|
+
...(pricing
|
|
174
207
|
? {
|
|
175
208
|
pricing: {
|
|
176
|
-
input_per_million:
|
|
177
|
-
output_per_million:
|
|
178
|
-
...(
|
|
209
|
+
input_per_million: pricing.inputPerMillion,
|
|
210
|
+
output_per_million: pricing.outputPerMillion,
|
|
211
|
+
...(pricing.cachedInputPerMillion === undefined
|
|
179
212
|
? {}
|
|
180
|
-
: { cached_input_per_million:
|
|
213
|
+
: { cached_input_per_million: pricing.cachedInputPerMillion }),
|
|
214
|
+
...table(previous.pricing),
|
|
181
215
|
},
|
|
182
216
|
}
|
|
183
217
|
: {}),
|
|
184
|
-
...previous,
|
|
185
218
|
};
|
|
186
219
|
return Object.keys(values).length ? [[id, values]] : [];
|
|
187
220
|
}));
|
|
@@ -192,8 +225,8 @@ export async function saveProviderLogin(input, env) {
|
|
|
192
225
|
base_url: input.baseUrl,
|
|
193
226
|
protocol: input.protocol,
|
|
194
227
|
credential_ref: credentialRef,
|
|
195
|
-
models,
|
|
196
|
-
...(Object.keys(overrides).length ? { model_overrides: overrides } : {}),
|
|
228
|
+
models: useModelTable ? Object.fromEntries(models.map((id) => [id, own(overrides, id) ?? {}])) : models,
|
|
229
|
+
...(!useModelTable && Object.keys(overrides).length ? { model_overrides: overrides } : {}),
|
|
197
230
|
};
|
|
198
231
|
config.providers = { ...providers, [input.providerId]: entry };
|
|
199
232
|
const profiles = configuredProfiles(config);
|
|
@@ -281,5 +314,10 @@ export async function configuredEndpoint(profile, root, env) {
|
|
|
281
314
|
const key = (await resolveCredentialMap(root, env)).values.get(item.credentialRef.slice(4));
|
|
282
315
|
if (!key?.trim())
|
|
283
316
|
throw new AuthError('尚未填写这个服务的密钥。');
|
|
284
|
-
return {
|
|
317
|
+
return {
|
|
318
|
+
baseUrl: item.modelRoute?.base_url ?? item.baseUrl,
|
|
319
|
+
model: item.modelId,
|
|
320
|
+
key,
|
|
321
|
+
protocol: item.modelRoute?.protocol ?? item.protocol,
|
|
322
|
+
};
|
|
285
323
|
}
|
package/dist/menu.d.ts
CHANGED
|
@@ -3,5 +3,5 @@ export interface AuthPrompt extends ChoicePrompt {
|
|
|
3
3
|
close(): void;
|
|
4
4
|
}
|
|
5
5
|
export declare function terminalPrompt(input: NodeJS.ReadStream, output: NodeJS.WriteStream): AuthPrompt;
|
|
6
|
-
export declare function askChoice(prompt: AuthPrompt, print: (s: string) => void, title: string, labels: readonly string[]): Promise<number>;
|
|
6
|
+
export declare function askChoice(prompt: AuthPrompt, print: (s: string) => void, title: string, labels: readonly string[], defaultIndex?: number): Promise<number>;
|
|
7
7
|
export declare function pickAction(title: string, labels: readonly string[]): Promise<number>;
|
package/dist/menu.js
CHANGED
|
@@ -67,14 +67,14 @@ export function terminalPrompt(input, output) {
|
|
|
67
67
|
close,
|
|
68
68
|
};
|
|
69
69
|
}
|
|
70
|
-
export async function askChoice(prompt, print, title, labels) {
|
|
70
|
+
export async function askChoice(prompt, print, title, labels, defaultIndex) {
|
|
71
71
|
if (!labels.length)
|
|
72
72
|
throw new AuthError('当前没有可选择的项目。');
|
|
73
73
|
print(title);
|
|
74
74
|
labels.forEach((label, i) => print(' ' + (i + 1) + '. ' + label));
|
|
75
75
|
for (;;) {
|
|
76
76
|
const answer = await prompt.question('编号: ');
|
|
77
|
-
const index = Number(answer) - 1;
|
|
77
|
+
const index = answer.trim() === '' && defaultIndex !== undefined ? defaultIndex : Number(answer) - 1;
|
|
78
78
|
if (Number.isInteger(index) && index >= 0 && index < labels.length)
|
|
79
79
|
return index;
|
|
80
80
|
print('请选择列表中的编号。');
|
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
import { type ModelPricing, type ProviderProtocol } from '@saturn-universe/protocol';
|
|
2
2
|
export interface DiscoveredModel {
|
|
3
3
|
readonly id: string;
|
|
4
|
+
readonly protocol?: ProviderProtocol;
|
|
5
|
+
readonly baseUrl?: string;
|
|
6
|
+
readonly tools?: boolean;
|
|
7
|
+
readonly structuredOutput?: boolean;
|
|
8
|
+
readonly images?: boolean;
|
|
4
9
|
readonly displayName?: string;
|
|
5
10
|
readonly contextWindow?: number;
|
|
6
11
|
readonly maxOutputTokens?: number;
|
|
@@ -8,7 +13,7 @@ export interface DiscoveredModel {
|
|
|
8
13
|
readonly reasoningEfforts?: readonly string[];
|
|
9
14
|
readonly defaultReasoningEffort?: string;
|
|
10
15
|
readonly pricing?: ModelPricing;
|
|
11
|
-
readonly priceSource?: 'models.dev' | 'models.dev-estimate';
|
|
16
|
+
readonly priceSource?: 'models.dev' | 'models.dev-estimate' | 'opencode';
|
|
12
17
|
readonly textOutput?: boolean;
|
|
13
18
|
}
|
|
14
19
|
export interface ProviderDiscovery {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { lookupModelMetadata, normalizeProviderBaseUrl, } from '@saturn-universe/protocol';
|
|
1
|
+
import { lookupModelMetadata, normalizeProviderBaseUrl, openCodeClientHeaders, providerPresets, } from '@saturn-universe/protocol';
|
|
2
2
|
function modelListProtocol(protocol) {
|
|
3
3
|
return protocol === 'openai-responses' || protocol === 'openai-chat' ? 'openai' : protocol;
|
|
4
4
|
}
|
|
@@ -35,6 +35,14 @@ export function supportsTextModel(model) {
|
|
|
35
35
|
function tokenLimit(...values) {
|
|
36
36
|
return values.find((value) => typeof value === 'number' && Number.isSafeInteger(value) && value > 0);
|
|
37
37
|
}
|
|
38
|
+
function safeModelId(id, apiKey) {
|
|
39
|
+
return Boolean(id) && id.length <= 200 && !/[\u0000-\u001f\u007f-\u009f]/.test(id) && !id.includes(apiKey);
|
|
40
|
+
}
|
|
41
|
+
function safeDisplayName(value, apiKey) {
|
|
42
|
+
return typeof value === 'string' && !value.includes(apiKey)
|
|
43
|
+
? value.replace(/[\u0000-\u001f\u007f-\u009f]/g, '').slice(0, 200) || undefined
|
|
44
|
+
: undefined;
|
|
45
|
+
}
|
|
38
46
|
function modelList(value, protocol, apiKey) {
|
|
39
47
|
const body = record(value);
|
|
40
48
|
const items = protocol === 'gemini'
|
|
@@ -58,11 +66,7 @@ function modelList(value, protocol, apiKey) {
|
|
|
58
66
|
row.supportedGenerationMethods.includes('generateContent')))
|
|
59
67
|
continue;
|
|
60
68
|
const id = (gemini ? rawId.replace(/^models\//, '') : rawId).trim();
|
|
61
|
-
if (!id ||
|
|
62
|
-
id.length > 200 ||
|
|
63
|
-
/[\u0000-\u001f\u007f-\u009f]/.test(id) ||
|
|
64
|
-
id.includes(apiKey) ||
|
|
65
|
-
models.has(id))
|
|
69
|
+
if (!safeModelId(id, apiKey) || models.has(id))
|
|
66
70
|
continue;
|
|
67
71
|
const metadata = lookupModelMetadata(id);
|
|
68
72
|
const topProvider = record(row.top_provider);
|
|
@@ -70,10 +74,7 @@ function modelList(value, protocol, apiKey) {
|
|
|
70
74
|
const maxOutputTokens = tokenLimit(row.max_output_tokens, row.max_tokens, row.outputTokenLimit, row.max_completion_tokens, topProvider?.max_completion_tokens) ?? metadata?.maxOutputTokens;
|
|
71
75
|
const architecture = record(row.architecture);
|
|
72
76
|
const textOutput = textOutputFromModalities(row.output_modalities ?? architecture?.output_modalities ?? record(row.modalities)?.output);
|
|
73
|
-
const
|
|
74
|
-
const displayName = typeof name === 'string' && !name.includes(apiKey)
|
|
75
|
-
? name.replace(/[\u0000-\u001f\u007f-\u009f]/g, '').slice(0, 200)
|
|
76
|
-
: undefined;
|
|
77
|
+
const displayName = safeDisplayName(row.display_name ?? row.displayName ?? row.name, apiKey);
|
|
77
78
|
models.set(id, {
|
|
78
79
|
id,
|
|
79
80
|
...(displayName ? { displayName } : {}),
|
|
@@ -88,9 +89,97 @@ function modelList(value, protocol, apiKey) {
|
|
|
88
89
|
return undefined;
|
|
89
90
|
return [...models.values()];
|
|
90
91
|
}
|
|
92
|
+
const openCodeProtocols = {
|
|
93
|
+
'chat-completions': 'openai-chat',
|
|
94
|
+
responses: 'openai-responses',
|
|
95
|
+
messages: 'anthropic',
|
|
96
|
+
'generate-content': 'gemini',
|
|
97
|
+
};
|
|
98
|
+
function openCodePricing(value) {
|
|
99
|
+
const text = record(record(value)?.text);
|
|
100
|
+
const input = record(text?.input);
|
|
101
|
+
const inputPerMillion = input?.price;
|
|
102
|
+
const outputPerMillion = record(text?.output)?.price;
|
|
103
|
+
const cachedInputPerMillion = record(input?.cache)?.read;
|
|
104
|
+
const rate = (value) => typeof value === 'number' && Number.isFinite(value) && value >= 0;
|
|
105
|
+
if (!rate(inputPerMillion) || !rate(outputPerMillion))
|
|
106
|
+
return undefined;
|
|
107
|
+
return {
|
|
108
|
+
inputPerMillion,
|
|
109
|
+
outputPerMillion,
|
|
110
|
+
...(rate(cachedInputPerMillion) ? { cachedInputPerMillion } : {}),
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
function openCodeModels(value, catalogUrl, apiKey) {
|
|
114
|
+
const rows = record(value)?.data;
|
|
115
|
+
if (!Array.isArray(rows))
|
|
116
|
+
return undefined;
|
|
117
|
+
const origin = new URL(catalogUrl).origin;
|
|
118
|
+
const models = new Map();
|
|
119
|
+
for (const item of rows) {
|
|
120
|
+
const row = record(item);
|
|
121
|
+
if (!row || typeof row.id !== 'string')
|
|
122
|
+
continue;
|
|
123
|
+
const id = row.id.trim();
|
|
124
|
+
if (!safeModelId(id, apiKey) || models.has(id))
|
|
125
|
+
continue;
|
|
126
|
+
const api = record(row.api);
|
|
127
|
+
if (!api)
|
|
128
|
+
continue;
|
|
129
|
+
const routes = Object.entries(openCodeProtocols).flatMap(([name, protocol]) => {
|
|
130
|
+
const rawUrl = record(api[name])?.base_url;
|
|
131
|
+
const baseUrl = typeof rawUrl === 'string' ? normalizeProviderBaseUrl(rawUrl) : undefined;
|
|
132
|
+
if (!baseUrl || new URL(baseUrl).origin !== origin || decodeURI(baseUrl).includes(apiKey))
|
|
133
|
+
return [];
|
|
134
|
+
return [{ name, protocol, baseUrl }];
|
|
135
|
+
});
|
|
136
|
+
const route = routes.find(({ name }) => name === row.recommended_api) ?? routes[0];
|
|
137
|
+
if (!route)
|
|
138
|
+
continue;
|
|
139
|
+
const capabilities = record(row.capabilities);
|
|
140
|
+
const limit = record(row.limit);
|
|
141
|
+
const reasoning = record(capabilities?.reasoning);
|
|
142
|
+
const effort = reasoning?.effort;
|
|
143
|
+
const reasoningEfforts = Array.isArray(effort)
|
|
144
|
+
? [
|
|
145
|
+
...new Set(effort.filter((value) => typeof value === 'string' && value.trim() === value && safeModelId(value, apiKey))),
|
|
146
|
+
]
|
|
147
|
+
: [];
|
|
148
|
+
const tools = record(capabilities?.tools)?.supported;
|
|
149
|
+
const reasoningModel = reasoning?.supported;
|
|
150
|
+
const structuredOutput = capabilities?.structured_output;
|
|
151
|
+
const input = record(row.modalities)?.input;
|
|
152
|
+
const contextWindow = tokenLimit(limit?.context);
|
|
153
|
+
const maxOutputTokens = tokenLimit(limit?.output);
|
|
154
|
+
const pricing = openCodePricing(row.cost);
|
|
155
|
+
const displayName = safeDisplayName(row.name, apiKey);
|
|
156
|
+
models.set(id, {
|
|
157
|
+
id,
|
|
158
|
+
protocol: route.protocol,
|
|
159
|
+
baseUrl: route.baseUrl,
|
|
160
|
+
textOutput: true,
|
|
161
|
+
...(displayName ? { displayName } : {}),
|
|
162
|
+
...(contextWindow === undefined ? {} : { contextWindow }),
|
|
163
|
+
...(maxOutputTokens === undefined ? {} : { maxOutputTokens }),
|
|
164
|
+
...(typeof tools === 'boolean' ? { tools } : {}),
|
|
165
|
+
...(typeof reasoningModel === 'boolean' ? { reasoningModel, reasoningEfforts } : {}),
|
|
166
|
+
...(typeof structuredOutput === 'boolean' ? { structuredOutput } : {}),
|
|
167
|
+
...(Array.isArray(input)
|
|
168
|
+
? {
|
|
169
|
+
images: input.some((type) => typeof type === 'string' && (type === 'image' || type.startsWith('image/'))),
|
|
170
|
+
}
|
|
171
|
+
: {}),
|
|
172
|
+
...(pricing ? { pricing, priceSource: 'opencode' } : {}),
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
return [...models.values()];
|
|
176
|
+
}
|
|
91
177
|
export async function probeProviderEndpoint(baseUrl, apiKey, options = {}) {
|
|
92
178
|
const endpoint = normalizeProviderBaseUrl(baseUrl);
|
|
93
|
-
const
|
|
179
|
+
const preset = providerPresets.find((preset) => preset.openCodeModelsUrl && preset.defaultBaseUrl === endpoint);
|
|
180
|
+
const fallback = options.preferredProtocol ??
|
|
181
|
+
preset?.defaultProtocol ??
|
|
182
|
+
(endpoint ? inferProviderProtocol(endpoint) : 'openai-responses');
|
|
94
183
|
const unavailable = {
|
|
95
184
|
protocol: fallback,
|
|
96
185
|
confidence: 'unknown',
|
|
@@ -101,6 +190,24 @@ export async function probeProviderEndpoint(baseUrl, apiKey, options = {}) {
|
|
|
101
190
|
return unavailable;
|
|
102
191
|
const request = options.fetch ?? fetch;
|
|
103
192
|
const signal = AbortSignal.timeout(8000);
|
|
193
|
+
if (preset?.openCodeModelsUrl) {
|
|
194
|
+
try {
|
|
195
|
+
const response = await request(preset?.openCodeModelsUrl, {
|
|
196
|
+
headers: { Authorization: 'Bearer ' + apiKey, ...openCodeClientHeaders },
|
|
197
|
+
signal,
|
|
198
|
+
redirect: 'error',
|
|
199
|
+
});
|
|
200
|
+
if (!response.ok) {
|
|
201
|
+
await response.body?.cancel();
|
|
202
|
+
return unavailable;
|
|
203
|
+
}
|
|
204
|
+
const models = openCodeModels(await response.json(), preset?.openCodeModelsUrl, apiKey);
|
|
205
|
+
return models ? { protocol: fallback, confidence: 'detected', models } : unavailable;
|
|
206
|
+
}
|
|
207
|
+
catch {
|
|
208
|
+
return unavailable;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
104
211
|
const headersFor = {
|
|
105
212
|
openai: { Authorization: `Bearer ${apiKey}` },
|
|
106
213
|
anthropic: { 'x-api-key': apiKey, 'anthropic-version': '2023-06-01' },
|
package/dist/provider-pricing.js
CHANGED
|
@@ -68,7 +68,10 @@ export async function enrichPrices(baseUrl, models, request = fetch) {
|
|
|
68
68
|
if (!models.length)
|
|
69
69
|
return models;
|
|
70
70
|
const endpoint = normalizeProviderBaseUrl(baseUrl);
|
|
71
|
-
const
|
|
71
|
+
const matchedPreset = providerPresets.find((p) => p.defaultBaseUrl && p.defaultBaseUrl === endpoint);
|
|
72
|
+
if (matchedPreset?.openCodeModelsUrl)
|
|
73
|
+
return models;
|
|
74
|
+
const preset = matchedPreset?.id;
|
|
72
75
|
try {
|
|
73
76
|
const response = await request('https://models.dev/api.json', {
|
|
74
77
|
signal: AbortSignal.timeout(4000),
|
package/dist/provider.js
CHANGED
|
@@ -4,7 +4,7 @@ import { enrichPrices, modelAlias } from './provider-pricing.js';
|
|
|
4
4
|
import { chooseFromPages, chooseManyFromPages } from './choice-menu.js';
|
|
5
5
|
import { formatTokenCompact } from './usage.js';
|
|
6
6
|
import { parseArgs } from 'node:util';
|
|
7
|
-
import { geminiModelPath, normalizeProviderBaseUrl, normalizeProviderProtocol, providerIdSchema, credentialRefSchema, resolveCredentialMap, providerPresets, } from '@saturn-universe/protocol';
|
|
7
|
+
import { geminiModelPath, normalizeProviderBaseUrl, normalizeProviderProtocol, openCodeClientHeaders, providerIdSchema, credentialRefSchema, resolveCredentialMap, providerPresets, } from '@saturn-universe/protocol';
|
|
8
8
|
import { chooseDefault, configuredEndpoint, listProviderLogins, removeProviderLogin, saveProviderLogin, } from './auth-config.js';
|
|
9
9
|
import { AuthError } from './cli-diagnostics.js';
|
|
10
10
|
import { topicHelp } from './cli-help.js';
|
|
@@ -209,7 +209,11 @@ export async function testModel(baseUrl, key, model, protocol = 'openai-response
|
|
|
209
209
|
method: 'POST',
|
|
210
210
|
redirect: 'error',
|
|
211
211
|
signal: AbortSignal.timeout(15000),
|
|
212
|
-
headers: {
|
|
212
|
+
headers: {
|
|
213
|
+
'Content-Type': 'application/json',
|
|
214
|
+
...headers,
|
|
215
|
+
...(new URL(endpoint).origin === 'https://opencode.ai' ? openCodeClientHeaders : {}),
|
|
216
|
+
},
|
|
213
217
|
body: JSON.stringify(body),
|
|
214
218
|
});
|
|
215
219
|
}
|
|
@@ -243,7 +247,8 @@ async function login(command, env, root, line, prompt, probe, prices) {
|
|
|
243
247
|
requestedId =
|
|
244
248
|
providerPresets[await askChoice(prompt, line, 'Provider', providerPresets.map((preset) => preset.label))].id;
|
|
245
249
|
}
|
|
246
|
-
|
|
250
|
+
const custom = requestedId === 'custom';
|
|
251
|
+
if (prompt && custom) {
|
|
247
252
|
const used = new Set((await listProviderLogins(env, root)).map((p) => p.id));
|
|
248
253
|
let n = 1;
|
|
249
254
|
while (used.has('custom-' + n))
|
|
@@ -257,17 +262,29 @@ async function login(command, env, root, line, prompt, probe, prices) {
|
|
|
257
262
|
const baseUrl = rawUrl && normalizeProviderBaseUrl(rawUrl);
|
|
258
263
|
if (!baseUrl)
|
|
259
264
|
throw new AuthError('EndPoint 需要完整的 HTTP 或 HTTPS URL。', 'USAGE');
|
|
265
|
+
const protocols = ['openai-chat', 'openai-responses', 'anthropic', 'gemini'];
|
|
266
|
+
const explicitProtocol = flags.protocol !== undefined
|
|
267
|
+
? parseProtocol(flags.protocol)
|
|
268
|
+
: custom && prompt
|
|
269
|
+
? protocols[await askChoice(prompt, line, 'Protocol', ['openai-chat (推荐)', ...protocols.slice(1)], 0)]
|
|
270
|
+
: undefined;
|
|
260
271
|
if (flags['api-key-stdin'] && (flags['api-key'] !== undefined || process.stdin.isTTY))
|
|
261
272
|
throw new AuthError('请通过管道提供密钥。', 'USAGE');
|
|
262
|
-
const
|
|
273
|
+
const openCodeModelsUrl = baseUrl === defaultUrl ? preset?.openCodeModelsUrl : undefined;
|
|
274
|
+
const defaultReference = openCodeModelsUrl && preset && !flags['api-key-stdin'] && flags['api-key'] === undefined
|
|
275
|
+
? preset.defaultEnvKey
|
|
276
|
+
: undefined;
|
|
277
|
+
const presetKey = !flags['credential-ref'] && defaultReference
|
|
278
|
+
? (await resolveCredentialMap(root, env)).values.get(defaultReference)
|
|
279
|
+
: undefined;
|
|
280
|
+
const reference = flags['credential-ref'] ?? (presetKey ? 'env:' + defaultReference : undefined);
|
|
263
281
|
if (reference &&
|
|
264
282
|
(!credentialRefSchema.safeParse(reference).success ||
|
|
265
283
|
flags['api-key-stdin'] ||
|
|
266
284
|
flags['api-key'] !== undefined))
|
|
267
285
|
throw new AuthError('请使用一个 env:变量名 引用密钥。', 'USAGE');
|
|
268
|
-
const configuredKey =
|
|
269
|
-
? (await resolveCredentialMap(root, env)).values.get(reference.slice(4))
|
|
270
|
-
: undefined;
|
|
286
|
+
const configuredKey = presetKey ??
|
|
287
|
+
(reference ? (await resolveCredentialMap(root, env)).values.get(reference.slice(4)) : undefined);
|
|
271
288
|
if (reference && !configuredKey)
|
|
272
289
|
throw new AuthError('指定的环境变量没有密钥。');
|
|
273
290
|
const apiKey = configuredKey ??
|
|
@@ -277,16 +294,17 @@ async function login(command, env, root, line, prompt, probe, prices) {
|
|
|
277
294
|
throw new AuthError('请输入一行有效的 API Key。', 'USAGE');
|
|
278
295
|
if (id.includes(apiKey) || baseUrl.includes(apiKey) || decodeURI(baseUrl).includes(apiKey))
|
|
279
296
|
throw new AuthError('请只在密钥输入框中填写 API Key。', 'USAGE');
|
|
280
|
-
const explicitProtocol = flags.protocol === undefined ? undefined : parseProtocol(flags.protocol);
|
|
281
297
|
const preferredProtocol = explicitProtocol ??
|
|
282
|
-
(baseUrl === defaultUrl ? preset?.defaultProtocol : undefined) ??
|
|
298
|
+
(custom ? 'openai-chat' : baseUrl === defaultUrl ? preset?.defaultProtocol : undefined) ??
|
|
283
299
|
inferProviderProtocol(baseUrl);
|
|
284
300
|
let protocol = preferredProtocol;
|
|
285
301
|
let discovered = [];
|
|
286
|
-
if (!flags['no-probe'] &&
|
|
302
|
+
if (!flags['no-probe'] &&
|
|
303
|
+
(openCodeModelsUrl || (flags.models === undefined && flags.default === undefined))) {
|
|
287
304
|
line('读取模型…');
|
|
288
305
|
const result = await probe(baseUrl, apiKey, { preferredProtocol });
|
|
289
|
-
|
|
306
|
+
const candidates = result.models.filter((model) => (id + '/' + model.id).length <= 200);
|
|
307
|
+
discovered = openCodeModelsUrl ? candidates : await prices(baseUrl, candidates);
|
|
290
308
|
protocol = explicitProtocol ?? result.protocol;
|
|
291
309
|
if (result.warning)
|
|
292
310
|
line('无法完全确认服务能力,请确认服务地址和模型权限。');
|
|
@@ -316,7 +334,7 @@ async function login(command, env, root, line, prompt, probe, prices) {
|
|
|
316
334
|
if (!models.length ||
|
|
317
335
|
models.some((model) => !model ||
|
|
318
336
|
`${id}/${model}`.length > 200 ||
|
|
319
|
-
(protocol === 'gemini' && !geminiModelPath(model)) ||
|
|
337
|
+
((knownModel.get(model)?.protocol ?? protocol) === 'gemini' && !geminiModelPath(model)) ||
|
|
320
338
|
/[\u0000-\u001f\u007f-\u009f]/.test(model) ||
|
|
321
339
|
model.includes(apiKey)))
|
|
322
340
|
throw new AuthError('请指定有效的模型名称。', 'USAGE');
|
|
@@ -359,8 +377,9 @@ function modelChoice(model) {
|
|
|
359
377
|
? `${model.id} · ${displayName}`
|
|
360
378
|
: model.id;
|
|
361
379
|
const context = model.contextWindow === undefined ? '—' : formatTokenCompact(model.contextWindow);
|
|
380
|
+
const exactPrice = model.priceSource === 'models.dev' || model.priceSource === 'opencode';
|
|
362
381
|
const cost = model.pricing
|
|
363
|
-
? `${
|
|
382
|
+
? `${exactPrice ? '' : '≈'}$${model.pricing.inputPerMillion}/$${model.pricing.outputPerMillion}`
|
|
364
383
|
: '—';
|
|
365
384
|
return {
|
|
366
385
|
label,
|
package/dist/renderer.js
CHANGED
|
@@ -4,6 +4,7 @@ import { reconciliationUsage } from './reconcile-command.js';
|
|
|
4
4
|
import { createTerminalPainter, padEndDisplay, paintSgr, stringDisplayWidth, stripAnsi, terminalColorEnabled, } from './terminal-text.js';
|
|
5
5
|
import { formatDuration } from './duration.js';
|
|
6
6
|
import { estimateUsageCostUsd, formatCacheRate, formatTokenCompact, formatTokenExact, formatUsd, resolveModelPricing, } from './usage.js';
|
|
7
|
+
const SATURN_CLI_VERSION = '0.1.2-dev.1';
|
|
7
8
|
const { bold, dim, cyan, brightCyan, green, yellow, red, magenta, whiteBold } = createTerminalPainter();
|
|
8
9
|
function padLogoLines(lines) {
|
|
9
10
|
const maxWidth = Math.max(0, ...lines.map(stringDisplayWidth));
|
|
@@ -197,7 +198,7 @@ export function renderBanner(info) {
|
|
|
197
198
|
: `Sandbox: ${green(`${info.status.sandbox.backend}`)}${info.status.sandbox.image ? ` (${info.status.sandbox.image})` : ''}`
|
|
198
199
|
: undefined;
|
|
199
200
|
const metaLines = [
|
|
200
|
-
`${brightCyan('>_')} ${whiteBold('Saturn')} ${dim(
|
|
201
|
+
`${brightCyan('>_')} ${whiteBold('Saturn')} ${dim(`(v${SATURN_CLI_VERSION})`)}`,
|
|
201
202
|
dim('Ringed Agent Kernel · Orbiting Agent Teams'),
|
|
202
203
|
`Workspace: ${info.workdir}`,
|
|
203
204
|
`Config: ${info.status.configSource ?? 'none'} · Profile: ${profileLabel}`,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@saturn-universe/cli",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.2-dev.1",
|
|
4
4
|
"description": "Saturn local multi-agent runtime CLI",
|
|
5
5
|
"license": "AGPL-3.0-only",
|
|
6
6
|
"type": "module",
|
|
@@ -8,8 +8,8 @@
|
|
|
8
8
|
"dist"
|
|
9
9
|
],
|
|
10
10
|
"dependencies": {
|
|
11
|
-
"@saturn-universe/protocol": "0.1.
|
|
12
|
-
"@saturn-universe/runtime-host": "0.1.
|
|
11
|
+
"@saturn-universe/protocol": "0.1.2-dev.1",
|
|
12
|
+
"@saturn-universe/runtime-host": "0.1.2-dev.1",
|
|
13
13
|
"mdast-util-from-markdown": "^2.1.0",
|
|
14
14
|
"mdast-util-gfm": "^3.1.0",
|
|
15
15
|
"micromark-extension-gfm": "^3.0.0",
|