@saturn-universe/cli 0.1.1 → 0.1.2-dev.3
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/cli-help.js +1 -1
- package/dist/config-cli.js +16 -4
- package/dist/host-launcher.d.ts +2 -1
- package/dist/host-launcher.js +16 -1
- package/dist/menu.d.ts +1 -1
- package/dist/menu.js +2 -2
- package/dist/provider-discovery.d.ts +7 -1
- package/dist/provider-discovery.js +120 -12
- package/dist/provider-pricing.d.ts +1 -1
- package/dist/provider-pricing.js +7 -3
- package/dist/provider-wizard.d.ts +18 -0
- package/dist/provider-wizard.js +109 -0
- package/dist/provider.js +114 -37
- package/dist/renderer.d.ts +1 -1
- package/dist/renderer.js +6 -3
- package/package.json +4 -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/cli-help.js
CHANGED
|
@@ -6,7 +6,7 @@ const topics = {
|
|
|
6
6
|
summary: '配置 AI 服务和默认模型',
|
|
7
7
|
actions: {
|
|
8
8
|
add: [
|
|
9
|
-
'[<provider>] [--base-url URL] [--protocol openai-responses|openai-chat|anthropic|gemini] [--models ID[,ID...]] [--default ID] [--api-key-stdin | --credential-ref env:NAME] [--no-probe] [--json]',
|
|
9
|
+
'[<provider>] [--base-url URL] [--protocol openai-responses|openai-chat|anthropic|gemini] [--models ID[,ID...]] [--default ID | --model ID] [--api-key-stdin | --credential-ref env:NAME] [--no-probe] [--json]',
|
|
10
10
|
'连接服务商并选择默认模型。交互模式下可直接运行。',
|
|
11
11
|
'saturn provider add',
|
|
12
12
|
],
|
package/dist/config-cli.js
CHANGED
|
@@ -2,6 +2,7 @@ import { parseArgs } from 'node:util';
|
|
|
2
2
|
import { CliError } from './cli-diagnostics.js';
|
|
3
3
|
import { workspaceRoot } from './client.js';
|
|
4
4
|
import { sendHostCommand } from './host-command.js';
|
|
5
|
+
import { inspectHostModes } from './host-launcher.js';
|
|
5
6
|
import { renderConfigCheck, renderConfigInit, renderConfigSummary } from './renderer.js';
|
|
6
7
|
import { initUserConfig, inspectUserConfig } from './user-config.js';
|
|
7
8
|
export async function runConfigCommand(configArgs) {
|
|
@@ -37,11 +38,22 @@ export async function runConfigCommand(configArgs) {
|
|
|
37
38
|
}
|
|
38
39
|
const workdir = await workspaceRoot(typeof parsed.values.workspace === 'string' ? parsed.values.workspace : process.cwd());
|
|
39
40
|
const inspection = await inspectUserConfig(workdir);
|
|
40
|
-
const status = await
|
|
41
|
+
const [status, availableModes] = await Promise.all([
|
|
42
|
+
sendHostCommand(workdir, { type: 'host.status' }, { timeoutMs: 2000 }).catch(() => undefined),
|
|
43
|
+
sub === 'check' ? inspectHostModes(workdir) : undefined,
|
|
44
|
+
]);
|
|
41
45
|
if (json) {
|
|
42
|
-
process.stdout.write(JSON.stringify({
|
|
46
|
+
process.stdout.write(JSON.stringify({
|
|
47
|
+
ok: true,
|
|
48
|
+
result: {
|
|
49
|
+
...inspection,
|
|
50
|
+
...(status ? { host: status } : {}),
|
|
51
|
+
...(availableModes ? { availableModes } : {}),
|
|
52
|
+
},
|
|
53
|
+
}) + '\n');
|
|
43
54
|
return;
|
|
44
55
|
}
|
|
45
|
-
process.stdout.write((sub === 'check'
|
|
46
|
-
|
|
56
|
+
process.stdout.write((sub === 'check'
|
|
57
|
+
? renderConfigCheck(inspection, status, availableModes)
|
|
58
|
+
: renderConfigSummary(inspection, status)) + '\n');
|
|
47
59
|
}
|
package/dist/host-launcher.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { HostStatusSnapshot } from '@saturn-universe/protocol';
|
|
1
|
+
import type { HostStatusSnapshot, ModeSummary } from '@saturn-universe/protocol';
|
|
2
2
|
export interface HostLaunchOptions {
|
|
3
3
|
readonly config?: string;
|
|
4
4
|
readonly profile?: string;
|
|
@@ -15,6 +15,7 @@ export interface ManagedHost {
|
|
|
15
15
|
export declare const DEFAULT_HOST_READY_TIMEOUT_MS = 60000;
|
|
16
16
|
export declare function resolveHostReadyTimeoutMs(env?: NodeJS.ProcessEnv): number;
|
|
17
17
|
export declare function resolveHostEntry(): Promise<string>;
|
|
18
|
+
export declare function inspectHostModes(root: string): Promise<readonly ModeSummary[]>;
|
|
18
19
|
export declare function shouldEnableEnvProxy(env: NodeJS.ProcessEnv): boolean;
|
|
19
20
|
export declare function buildHostSpawnEnv(baseEnv?: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
|
|
20
21
|
export declare function ensureHost(root: string, options?: HostLaunchOptions): Promise<ManagedHost>;
|
package/dist/host-launcher.js
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import { spawn } from 'node:child_process';
|
|
1
|
+
import { execFile, spawn } from 'node:child_process';
|
|
2
2
|
import { randomUUID } from 'node:crypto';
|
|
3
3
|
import { access, realpath } from 'node:fs/promises';
|
|
4
4
|
import path from 'node:path';
|
|
5
5
|
import { createRequire } from 'node:module';
|
|
6
6
|
import { setTimeout as delay } from 'node:timers/promises';
|
|
7
7
|
import { fileURLToPath } from 'node:url';
|
|
8
|
+
import { promisify } from 'node:util';
|
|
8
9
|
import { matchesModeSelector, parseHostStatusResult } from '@saturn-universe/protocol';
|
|
9
10
|
import { request } from './client.js';
|
|
10
11
|
import { CliError, isHostConnectionError, safeCode } from './cli-diagnostics.js';
|
|
@@ -71,6 +72,20 @@ function parseHostStartupError(stderrText) {
|
|
|
71
72
|
}
|
|
72
73
|
return undefined;
|
|
73
74
|
}
|
|
75
|
+
export async function inspectHostModes(root) {
|
|
76
|
+
const hostEntry = await resolveHostEntry();
|
|
77
|
+
try {
|
|
78
|
+
const { stdout } = await promisify(execFile)(process.execPath, [hostEntry, root, '--inspect-modes'], {
|
|
79
|
+
timeout: resolveHostReadyTimeoutMs(),
|
|
80
|
+
windowsHide: true,
|
|
81
|
+
});
|
|
82
|
+
return JSON.parse(stdout);
|
|
83
|
+
}
|
|
84
|
+
catch (error) {
|
|
85
|
+
const { stderr } = error;
|
|
86
|
+
throw (stderr && parseHostStartupError(stderr)) || new CliError('HOST_UNAVAILABLE');
|
|
87
|
+
}
|
|
88
|
+
}
|
|
74
89
|
export function shouldEnableEnvProxy(env) {
|
|
75
90
|
return (env.NODE_USE_ENV_PROXY === undefined &&
|
|
76
91
|
Boolean(env.HTTPS_PROXY?.trim() || env.https_proxy?.trim() || env.HTTP_PROXY?.trim() || env.http_proxy?.trim()));
|
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 {
|
|
@@ -23,4 +28,5 @@ export declare function supportsTextModel(model: DiscoveredModel): boolean;
|
|
|
23
28
|
export declare function probeProviderEndpoint(baseUrl: string, apiKey: string, options?: {
|
|
24
29
|
readonly preferredProtocol?: ProviderProtocol;
|
|
25
30
|
readonly fetch?: typeof fetch;
|
|
31
|
+
readonly signal?: AbortSignal;
|
|
26
32
|
}): Promise<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',
|
|
@@ -100,7 +189,26 @@ export async function probeProviderEndpoint(baseUrl, apiKey, options = {}) {
|
|
|
100
189
|
if (!endpoint || !apiKey.trim())
|
|
101
190
|
return unavailable;
|
|
102
191
|
const request = options.fetch ?? fetch;
|
|
103
|
-
const
|
|
192
|
+
const timeout = AbortSignal.timeout(8000);
|
|
193
|
+
const signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;
|
|
194
|
+
if (preset?.openCodeModelsUrl) {
|
|
195
|
+
try {
|
|
196
|
+
const response = await request(preset?.openCodeModelsUrl, {
|
|
197
|
+
headers: { Authorization: 'Bearer ' + apiKey, ...openCodeClientHeaders },
|
|
198
|
+
signal,
|
|
199
|
+
redirect: 'error',
|
|
200
|
+
});
|
|
201
|
+
if (!response.ok) {
|
|
202
|
+
await response.body?.cancel();
|
|
203
|
+
return unavailable;
|
|
204
|
+
}
|
|
205
|
+
const models = openCodeModels(await response.json(), preset?.openCodeModelsUrl, apiKey);
|
|
206
|
+
return models ? { protocol: fallback, confidence: 'detected', models } : unavailable;
|
|
207
|
+
}
|
|
208
|
+
catch {
|
|
209
|
+
return unavailable;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
104
212
|
const headersFor = {
|
|
105
213
|
openai: { Authorization: `Bearer ${apiKey}` },
|
|
106
214
|
anthropic: { 'x-api-key': apiKey, 'anthropic-version': '2023-06-01' },
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { type DiscoveredModel } from './provider-discovery.js';
|
|
2
2
|
export declare function modelAlias(id: string): string;
|
|
3
|
-
export declare function enrichPrices(baseUrl: string, models: readonly DiscoveredModel[], request?: typeof fetch): Promise<readonly DiscoveredModel[]>;
|
|
3
|
+
export declare function enrichPrices(baseUrl: string, models: readonly DiscoveredModel[], request?: typeof fetch, signal?: AbortSignal): Promise<readonly DiscoveredModel[]>;
|
package/dist/provider-pricing.js
CHANGED
|
@@ -64,14 +64,18 @@ function priceIndex(entries) {
|
|
|
64
64
|
};
|
|
65
65
|
}
|
|
66
66
|
// Only the public catalog URL is sent. Endpoint, credentials and model IDs stay local.
|
|
67
|
-
export async function enrichPrices(baseUrl, models, request = fetch) {
|
|
67
|
+
export async function enrichPrices(baseUrl, models, request = fetch, signal) {
|
|
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 {
|
|
76
|
+
const timeout = AbortSignal.timeout(4000);
|
|
73
77
|
const response = await request('https://models.dev/api.json', {
|
|
74
|
-
signal: AbortSignal.timeout
|
|
78
|
+
signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
|
|
75
79
|
redirect: 'error',
|
|
76
80
|
});
|
|
77
81
|
if (!response.ok) {
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { type ProviderPreset, type ProviderProtocol } from '@saturn-universe/protocol';
|
|
2
|
+
export declare const customProtocols: readonly ["openai-chat", "openai-responses", "anthropic", "gemini"];
|
|
3
|
+
export declare const providerWizard: {
|
|
4
|
+
start(): void;
|
|
5
|
+
finish(profile: string, configPath: string): void;
|
|
6
|
+
cancel(error: unknown): void;
|
|
7
|
+
selectProvider(presets: readonly ProviderPreset[]): Promise<string>;
|
|
8
|
+
selectProtocol(): Promise<"openai-responses" | "openai-chat" | "anthropic" | "gemini">;
|
|
9
|
+
endpoint(protocol: ProviderProtocol | undefined): Promise<string>;
|
|
10
|
+
apiKey(): Promise<string>;
|
|
11
|
+
selectModel(options: {
|
|
12
|
+
value: string;
|
|
13
|
+
label: string;
|
|
14
|
+
hint: string;
|
|
15
|
+
}[]): Promise<string>;
|
|
16
|
+
manualModel(): Promise<string>;
|
|
17
|
+
fetchModels<T>(load: (signal: AbortSignal) => Promise<T>): Promise<T | undefined>;
|
|
18
|
+
};
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { autocomplete, CANCEL_SYMBOL, cancel, intro, isCancel, outro, password, select, settings, spinner, text, } from '@clack/prompts';
|
|
2
|
+
import { emitKeypressEvents } from 'node:readline';
|
|
3
|
+
import { styleText } from 'node:util';
|
|
4
|
+
import { normalizeProviderBaseUrl, } from '@saturn-universe/protocol';
|
|
5
|
+
export const customProtocols = ['openai-chat', 'openai-responses', 'anthropic', 'gemini'];
|
|
6
|
+
async function answer(prompt) {
|
|
7
|
+
const value = await prompt;
|
|
8
|
+
if (isCancel(value))
|
|
9
|
+
throw value;
|
|
10
|
+
return value;
|
|
11
|
+
}
|
|
12
|
+
export const providerWizard = {
|
|
13
|
+
start() {
|
|
14
|
+
const brand = styleText(['bgYellow', 'black', 'bold'], ' SATURN ');
|
|
15
|
+
intro(`${brand} ${styleText('bold', 'Provider Setup')}`);
|
|
16
|
+
},
|
|
17
|
+
finish(profile, configPath) {
|
|
18
|
+
outro(`Saved ${styleText('bold', profile)} to ${configPath}`);
|
|
19
|
+
},
|
|
20
|
+
cancel(error) {
|
|
21
|
+
if (!isCancel(error))
|
|
22
|
+
throw error;
|
|
23
|
+
cancel('Provider setup cancelled.');
|
|
24
|
+
},
|
|
25
|
+
selectProvider(presets) {
|
|
26
|
+
return answer(select({
|
|
27
|
+
message: 'Select provider',
|
|
28
|
+
options: presets.map((preset) => ({
|
|
29
|
+
value: preset.id,
|
|
30
|
+
label: preset.label,
|
|
31
|
+
...(preset.defaultBaseUrl ? { hint: preset.defaultProtocol } : {}),
|
|
32
|
+
})),
|
|
33
|
+
}));
|
|
34
|
+
},
|
|
35
|
+
selectProtocol() {
|
|
36
|
+
return answer(select({
|
|
37
|
+
message: 'Select protocol',
|
|
38
|
+
initialValue: 'openai-chat',
|
|
39
|
+
options: customProtocols.map((value) => ({
|
|
40
|
+
value,
|
|
41
|
+
label: value,
|
|
42
|
+
...(value === 'openai-chat' ? { hint: 'recommended' } : {}),
|
|
43
|
+
})),
|
|
44
|
+
}));
|
|
45
|
+
},
|
|
46
|
+
endpoint(protocol) {
|
|
47
|
+
return answer(text({
|
|
48
|
+
message: 'Enter endpoint URL',
|
|
49
|
+
placeholder: protocol === 'gemini' ? 'https://api.example.com/v1beta' : 'https://api.example.com/v1',
|
|
50
|
+
validate: (value) => normalizeProviderBaseUrl(value ?? '') ? undefined : 'Enter a complete HTTP or HTTPS URL.',
|
|
51
|
+
}));
|
|
52
|
+
},
|
|
53
|
+
apiKey() {
|
|
54
|
+
return answer(password({
|
|
55
|
+
message: 'Enter API key',
|
|
56
|
+
validate: (value) => (value?.trim() ? undefined : 'Enter an API key.'),
|
|
57
|
+
}));
|
|
58
|
+
},
|
|
59
|
+
selectModel(options) {
|
|
60
|
+
return answer(autocomplete({ message: 'Select default model', options, placeholder: 'Search models' }));
|
|
61
|
+
},
|
|
62
|
+
manualModel() {
|
|
63
|
+
return answer(text({
|
|
64
|
+
message: 'Enter model ID',
|
|
65
|
+
validate: (value) => (value?.trim() ? undefined : 'Enter a model ID.'),
|
|
66
|
+
}));
|
|
67
|
+
},
|
|
68
|
+
async fetchModels(load) {
|
|
69
|
+
const input = process.stdin;
|
|
70
|
+
const wasRaw = Boolean(input.isRaw);
|
|
71
|
+
const wasFlowing = input.readableFlowing === true;
|
|
72
|
+
const controller = new AbortController();
|
|
73
|
+
// The animated spinner otherwise handles these keys with process.exit(0).
|
|
74
|
+
// Let the wizard abort discovery and render its cancellation footer instead.
|
|
75
|
+
const cancelAliases = ['escape', '\x03'].filter((key) => settings.aliases.get(key) === 'cancel');
|
|
76
|
+
const progress = spinner({
|
|
77
|
+
onCancel: () => controller.abort(),
|
|
78
|
+
signal: controller.signal,
|
|
79
|
+
cancelMessage: 'Model discovery cancelled.',
|
|
80
|
+
});
|
|
81
|
+
const onKey = (_, key) => {
|
|
82
|
+
if (key?.name === 'escape' || (key?.ctrl && key.name === 'c'))
|
|
83
|
+
controller.abort();
|
|
84
|
+
};
|
|
85
|
+
for (const key of cancelAliases)
|
|
86
|
+
settings.aliases.delete(key);
|
|
87
|
+
try {
|
|
88
|
+
emitKeypressEvents(input);
|
|
89
|
+
input.setRawMode(true);
|
|
90
|
+
input.on('keypress', onKey);
|
|
91
|
+
input.resume();
|
|
92
|
+
progress.start('Fetching models...');
|
|
93
|
+
const result = await load(controller.signal).catch(() => undefined);
|
|
94
|
+
if (controller.signal.aborted)
|
|
95
|
+
throw CANCEL_SYMBOL;
|
|
96
|
+
progress.stop(result ? 'Model discovery finished' : 'Model list unavailable');
|
|
97
|
+
return result;
|
|
98
|
+
}
|
|
99
|
+
finally {
|
|
100
|
+
progress.clear();
|
|
101
|
+
input.off('keypress', onKey);
|
|
102
|
+
input.setRawMode(wasRaw);
|
|
103
|
+
if (!wasFlowing)
|
|
104
|
+
input.pause();
|
|
105
|
+
for (const key of cancelAliases)
|
|
106
|
+
settings.aliases.set(key, 'cancel');
|
|
107
|
+
}
|
|
108
|
+
},
|
|
109
|
+
};
|
package/dist/provider.js
CHANGED
|
@@ -4,11 +4,13 @@ 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, userConfigPath, } 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';
|
|
11
11
|
import { inferProviderProtocol, probeProviderEndpoint, supportsTextModel, } from './provider-discovery.js';
|
|
12
|
+
import { customProtocols, providerWizard } from './provider-wizard.js';
|
|
13
|
+
const addPresets = providerPresets.filter(({ id }) => id !== 'anthropic' && id !== 'google');
|
|
12
14
|
function providerId(value) {
|
|
13
15
|
const parsed = providerIdSchema.safeParse(value);
|
|
14
16
|
if (!parsed.success)
|
|
@@ -44,13 +46,15 @@ function parseProviderArgs(args) {
|
|
|
44
46
|
'api-key-stdin': { type: 'boolean' },
|
|
45
47
|
'api-key': { type: 'string' },
|
|
46
48
|
protocol: { type: 'string' },
|
|
49
|
+
model: { type: 'string' },
|
|
47
50
|
models: { type: 'string' },
|
|
48
51
|
default: { type: 'string' },
|
|
49
52
|
'no-probe': { type: 'boolean' },
|
|
50
53
|
},
|
|
51
54
|
});
|
|
52
55
|
if (positionals.length <= 1 &&
|
|
53
|
-
(!positionals[0] || !values.provider || positionals[0] === values.provider)
|
|
56
|
+
(!positionals[0] || !values.provider || positionals[0] === values.provider) &&
|
|
57
|
+
!(values.default !== undefined && values.model !== undefined))
|
|
54
58
|
return { action, id: values.provider ?? positionals[0], values };
|
|
55
59
|
}
|
|
56
60
|
}
|
|
@@ -69,8 +73,10 @@ export async function runProviderCommand(args, options = {}) {
|
|
|
69
73
|
const print = options.writeLine ?? ((value) => process.stdout.write(value + '\n'));
|
|
70
74
|
const result = (value, message) => print(json ? JSON.stringify({ ok: true, result: value }) : message);
|
|
71
75
|
const progress = json ? () => { } : print;
|
|
72
|
-
const
|
|
73
|
-
const prompt =
|
|
76
|
+
const tty = !json && process.stdin.isTTY && process.stdout.isTTY;
|
|
77
|
+
const prompt = !json
|
|
78
|
+
? (options.prompt ?? (tty ? terminalPrompt(process.stdin, process.stdout) : undefined))
|
|
79
|
+
: undefined;
|
|
74
80
|
try {
|
|
75
81
|
const profiles = () => listProviderLogins(env, root);
|
|
76
82
|
const describe = (p) => [p.profile, p.selected ? '当前默认' : '', p.configured ? '已配置' : '缺少密钥']
|
|
@@ -133,8 +139,24 @@ export async function runProviderCommand(args, options = {}) {
|
|
|
133
139
|
await removeProviderLogin(providerId(command.id), command.keep, env);
|
|
134
140
|
return result({ provider: command.id }, command.keep ? '已移除密钥。' : '已删除服务。');
|
|
135
141
|
case 'add': {
|
|
136
|
-
const
|
|
137
|
-
|
|
142
|
+
const wizard = tty && !options.prompt && Object.keys(command.values).length === 0;
|
|
143
|
+
if (wizard) {
|
|
144
|
+
prompt?.close();
|
|
145
|
+
providerWizard.start();
|
|
146
|
+
}
|
|
147
|
+
try {
|
|
148
|
+
const { defaultModel, ...added } = await login(command, env, root, progress, options.prompt && !json ? prompt : undefined, wizard, options.probe ?? probeProviderEndpoint, options.prices ?? enrichPrices);
|
|
149
|
+
if (wizard && defaultModel) {
|
|
150
|
+
providerWizard.finish(`${added.provider}/${defaultModel}`, userConfigPath(env));
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
return result(added, '已保存 AI 服务。');
|
|
154
|
+
}
|
|
155
|
+
catch (error) {
|
|
156
|
+
if (!wizard)
|
|
157
|
+
throw error;
|
|
158
|
+
providerWizard.cancel(error);
|
|
159
|
+
}
|
|
138
160
|
}
|
|
139
161
|
}
|
|
140
162
|
}
|
|
@@ -209,7 +231,11 @@ export async function testModel(baseUrl, key, model, protocol = 'openai-response
|
|
|
209
231
|
method: 'POST',
|
|
210
232
|
redirect: 'error',
|
|
211
233
|
signal: AbortSignal.timeout(15000),
|
|
212
|
-
headers: {
|
|
234
|
+
headers: {
|
|
235
|
+
'Content-Type': 'application/json',
|
|
236
|
+
...headers,
|
|
237
|
+
...(new URL(endpoint).origin === 'https://opencode.ai' ? openCodeClientHeaders : {}),
|
|
238
|
+
},
|
|
213
239
|
body: JSON.stringify(body),
|
|
214
240
|
});
|
|
215
241
|
}
|
|
@@ -236,14 +262,18 @@ function parseProtocol(value) {
|
|
|
236
262
|
function selection(value) {
|
|
237
263
|
return [...new Set(value.split(',').map((part) => part.trim()))];
|
|
238
264
|
}
|
|
239
|
-
async function login(command, env, root, line, prompt, probe, prices) {
|
|
265
|
+
async function login(command, env, root, line, prompt, wizard, probe, prices) {
|
|
240
266
|
const flags = command.values;
|
|
241
267
|
let requestedId = command.id;
|
|
242
|
-
if (requestedId === undefined &&
|
|
268
|
+
if (requestedId === undefined && wizard) {
|
|
269
|
+
requestedId = await providerWizard.selectProvider(addPresets);
|
|
270
|
+
}
|
|
271
|
+
else if (requestedId === undefined && prompt) {
|
|
243
272
|
requestedId =
|
|
244
|
-
|
|
273
|
+
addPresets[await askChoice(prompt, line, 'Provider', addPresets.map((preset) => preset.label))].id;
|
|
245
274
|
}
|
|
246
|
-
|
|
275
|
+
const custom = requestedId === 'custom';
|
|
276
|
+
if ((prompt || wizard) && custom) {
|
|
247
277
|
const used = new Set((await listProviderLogins(env, root)).map((p) => p.id));
|
|
248
278
|
let n = 1;
|
|
249
279
|
while (used.has('custom-' + n))
|
|
@@ -253,55 +283,91 @@ async function login(command, env, root, line, prompt, probe, prices) {
|
|
|
253
283
|
const id = providerId(requestedId);
|
|
254
284
|
const preset = providerPresets.find((item) => item.id === id);
|
|
255
285
|
const defaultUrl = preset?.defaultBaseUrl;
|
|
256
|
-
const
|
|
286
|
+
const explicitProtocol = flags.protocol !== undefined
|
|
287
|
+
? parseProtocol(flags.protocol)
|
|
288
|
+
: custom && wizard
|
|
289
|
+
? await providerWizard.selectProtocol()
|
|
290
|
+
: custom && prompt
|
|
291
|
+
? customProtocols[await askChoice(prompt, line, 'Protocol', ['openai-chat (推荐)', ...customProtocols.slice(1)], 0)]
|
|
292
|
+
: undefined;
|
|
293
|
+
const rawUrl = flags['base-url'] ??
|
|
294
|
+
defaultUrl ??
|
|
295
|
+
(wizard ? await providerWizard.endpoint(explicitProtocol) : await prompt?.question('EndPoint: '));
|
|
257
296
|
const baseUrl = rawUrl && normalizeProviderBaseUrl(rawUrl);
|
|
258
297
|
if (!baseUrl)
|
|
259
298
|
throw new AuthError('EndPoint 需要完整的 HTTP 或 HTTPS URL。', 'USAGE');
|
|
260
299
|
if (flags['api-key-stdin'] && (flags['api-key'] !== undefined || process.stdin.isTTY))
|
|
261
300
|
throw new AuthError('请通过管道提供密钥。', 'USAGE');
|
|
262
|
-
const
|
|
301
|
+
const openCodeModelsUrl = baseUrl === defaultUrl ? preset?.openCodeModelsUrl : undefined;
|
|
302
|
+
const defaultReference = openCodeModelsUrl && preset && !flags['api-key-stdin'] && flags['api-key'] === undefined
|
|
303
|
+
? preset.defaultEnvKey
|
|
304
|
+
: undefined;
|
|
305
|
+
const presetKey = !flags['credential-ref'] && defaultReference
|
|
306
|
+
? (await resolveCredentialMap(root, env)).values.get(defaultReference)
|
|
307
|
+
: undefined;
|
|
308
|
+
const reference = flags['credential-ref'] ?? (presetKey ? 'env:' + defaultReference : undefined);
|
|
263
309
|
if (reference &&
|
|
264
310
|
(!credentialRefSchema.safeParse(reference).success ||
|
|
265
311
|
flags['api-key-stdin'] ||
|
|
266
312
|
flags['api-key'] !== undefined))
|
|
267
313
|
throw new AuthError('请使用一个 env:变量名 引用密钥。', 'USAGE');
|
|
268
|
-
const configuredKey =
|
|
269
|
-
? (await resolveCredentialMap(root, env)).values.get(reference.slice(4))
|
|
270
|
-
: undefined;
|
|
314
|
+
const configuredKey = presetKey ??
|
|
315
|
+
(reference ? (await resolveCredentialMap(root, env)).values.get(reference.slice(4)) : undefined);
|
|
271
316
|
if (reference && !configuredKey)
|
|
272
317
|
throw new AuthError('指定的环境变量没有密钥。');
|
|
273
318
|
const apiKey = configuredKey ??
|
|
274
319
|
(flags['api-key-stdin'] ? (await readText(process.stdin)).trimEnd() : flags['api-key']) ??
|
|
275
|
-
(
|
|
320
|
+
(wizard ? await providerWizard.apiKey() : await prompt?.question('API Key: ', true));
|
|
276
321
|
if (!apiKey?.trim() || apiKey !== apiKey.trim() || /[\u0000-\u001f\u007f]/.test(apiKey))
|
|
277
322
|
throw new AuthError('请输入一行有效的 API Key。', 'USAGE');
|
|
278
323
|
if (id.includes(apiKey) || baseUrl.includes(apiKey) || decodeURI(baseUrl).includes(apiKey))
|
|
279
324
|
throw new AuthError('请只在密钥输入框中填写 API Key。', 'USAGE');
|
|
280
|
-
const explicitProtocol = flags.protocol === undefined ? undefined : parseProtocol(flags.protocol);
|
|
281
325
|
const preferredProtocol = explicitProtocol ??
|
|
282
|
-
(baseUrl === defaultUrl ? preset?.defaultProtocol : undefined) ??
|
|
326
|
+
(custom ? 'openai-chat' : baseUrl === defaultUrl ? preset?.defaultProtocol : undefined) ??
|
|
283
327
|
inferProviderProtocol(baseUrl);
|
|
284
328
|
let protocol = preferredProtocol;
|
|
285
329
|
let discovered = [];
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
330
|
+
const defaultFlag = flags.default ?? flags.model;
|
|
331
|
+
if (!flags['no-probe'] &&
|
|
332
|
+
(openCodeModelsUrl || (flags.models === undefined && defaultFlag === undefined))) {
|
|
333
|
+
const discover = async (signal) => {
|
|
334
|
+
const result = await probe(baseUrl, apiKey, { preferredProtocol, ...(signal ? { signal } : {}) });
|
|
335
|
+
signal?.throwIfAborted();
|
|
336
|
+
const candidates = result.models.filter((model) => (id + '/' + model.id).length <= 200);
|
|
337
|
+
const models = openCodeModelsUrl
|
|
338
|
+
? candidates
|
|
339
|
+
: signal
|
|
340
|
+
? await prices(baseUrl, candidates, undefined, signal)
|
|
341
|
+
: await prices(baseUrl, candidates);
|
|
342
|
+
return { ...result, models };
|
|
343
|
+
};
|
|
344
|
+
if (!wizard)
|
|
345
|
+
line('读取模型…');
|
|
346
|
+
const result = wizard ? await providerWizard.fetchModels(discover) : await discover();
|
|
347
|
+
if (result) {
|
|
348
|
+
discovered = result.models;
|
|
349
|
+
protocol = explicitProtocol ?? result.protocol;
|
|
350
|
+
if (!wizard && result.warning)
|
|
351
|
+
line('无法完全确认服务能力,请确认服务地址和模型权限。');
|
|
352
|
+
}
|
|
293
353
|
}
|
|
294
354
|
const candidates = discovered.filter(supportsTextModel);
|
|
295
355
|
const knownModel = new Map(discovered.map((model) => [model.id, model]));
|
|
296
|
-
const requestedDefault =
|
|
297
|
-
?
|
|
298
|
-
:
|
|
356
|
+
const requestedDefault = defaultFlag !== undefined && !knownModel.has(defaultFlag) && defaultFlag.startsWith(`${id}/`)
|
|
357
|
+
? defaultFlag.slice(id.length + 1)
|
|
358
|
+
: defaultFlag;
|
|
299
359
|
let models;
|
|
300
360
|
let chosen;
|
|
301
361
|
if (flags.models !== undefined)
|
|
302
362
|
models = selection(flags.models);
|
|
303
363
|
else if (requestedDefault !== undefined)
|
|
304
364
|
models = [requestedDefault];
|
|
365
|
+
else if (wizard) {
|
|
366
|
+
chosen = candidates.length
|
|
367
|
+
? await providerWizard.selectModel(candidates.map((model) => wizardModelChoice(model, protocol)))
|
|
368
|
+
: (await providerWizard.manualModel()).trim();
|
|
369
|
+
models = [chosen];
|
|
370
|
+
}
|
|
305
371
|
else if (prompt && candidates.length) {
|
|
306
372
|
const selected = await chooseManyFromPages(prompt, line, modelPickerTitle, candidates.map(modelChoice));
|
|
307
373
|
models = selected.map((index) => candidates[index].id);
|
|
@@ -316,13 +382,13 @@ async function login(command, env, root, line, prompt, probe, prices) {
|
|
|
316
382
|
if (!models.length ||
|
|
317
383
|
models.some((model) => !model ||
|
|
318
384
|
`${id}/${model}`.length > 200 ||
|
|
319
|
-
(protocol === 'gemini' && !geminiModelPath(model)) ||
|
|
385
|
+
((knownModel.get(model)?.protocol ?? protocol) === 'gemini' && !geminiModelPath(model)) ||
|
|
320
386
|
/[\u0000-\u001f\u007f-\u009f]/.test(model) ||
|
|
321
387
|
model.includes(apiKey)))
|
|
322
388
|
throw new AuthError('请指定有效的模型名称。', 'USAGE');
|
|
323
389
|
const selectable = models.filter((model) => supportsTextModel(knownModel.get(model) ?? { id: model }));
|
|
324
390
|
const choicesFor = (items) => items.map((model) => modelChoice(knownModel.get(model) ?? { id: model }));
|
|
325
|
-
const defaultSelection = (flags.models !== undefined ?
|
|
391
|
+
const defaultSelection = (flags.models !== undefined ? defaultFlag : requestedDefault) ??
|
|
326
392
|
chosen ??
|
|
327
393
|
(prompt && selectable.length > 1
|
|
328
394
|
? selectable[await chooseFromPages(prompt, line, modelPickerTitle, choicesFor(selectable))]
|
|
@@ -336,7 +402,7 @@ async function login(command, env, root, line, prompt, probe, prices) {
|
|
|
336
402
|
: defaultSelection;
|
|
337
403
|
if (defaultModel !== undefined && !models.includes(defaultModel))
|
|
338
404
|
throw new AuthError('默认模型必须来自已选择的模型。', 'USAGE');
|
|
339
|
-
if (prompt && (defaultModel === undefined || !selectable.includes(defaultModel)))
|
|
405
|
+
if ((prompt || wizard) && (defaultModel === undefined || !selectable.includes(defaultModel)))
|
|
340
406
|
throw new AuthError('请选择可用于对话的默认模型。', 'USAGE');
|
|
341
407
|
await saveProviderLogin({
|
|
342
408
|
providerId: id,
|
|
@@ -348,7 +414,7 @@ async function login(command, env, root, line, prompt, probe, prices) {
|
|
|
348
414
|
discovered,
|
|
349
415
|
...(defaultModel === undefined ? {} : { defaultModel }),
|
|
350
416
|
}, env);
|
|
351
|
-
return { provider: id, models, tested: false };
|
|
417
|
+
return { provider: id, models, tested: false, defaultModel };
|
|
352
418
|
}
|
|
353
419
|
const modelPickerTitle = 'Model · 上下文 / USD/1M(入/出,≈估算)';
|
|
354
420
|
function modelChoice(model) {
|
|
@@ -359,12 +425,23 @@ function modelChoice(model) {
|
|
|
359
425
|
? `${model.id} · ${displayName}`
|
|
360
426
|
: model.id;
|
|
361
427
|
const context = model.contextWindow === undefined ? '—' : formatTokenCompact(model.contextWindow);
|
|
362
|
-
const cost = model.pricing
|
|
363
|
-
? `${model.priceSource === 'models.dev' ? '' : '≈'}$${model.pricing.inputPerMillion}/$${model.pricing.outputPerMillion}`
|
|
364
|
-
: '—';
|
|
365
428
|
return {
|
|
366
429
|
label,
|
|
367
|
-
detail: `${context} ${
|
|
430
|
+
detail: `${context} ${modelCost(model) ?? '—'}`,
|
|
368
431
|
...(model.displayName ? { search: model.displayName } : {}),
|
|
369
432
|
};
|
|
370
433
|
}
|
|
434
|
+
function modelCost(model) {
|
|
435
|
+
const exactPrice = model.priceSource === 'models.dev' || model.priceSource === 'opencode';
|
|
436
|
+
if (model.pricing)
|
|
437
|
+
return `${exactPrice ? '' : '≈'}$${model.pricing.inputPerMillion}/$${model.pricing.outputPerMillion}`;
|
|
438
|
+
}
|
|
439
|
+
function wizardModelChoice(model, protocol) {
|
|
440
|
+
const metadata = [
|
|
441
|
+
model.protocol ?? protocol,
|
|
442
|
+
model.contextWindow && formatTokenCompact(model.contextWindow).toUpperCase(),
|
|
443
|
+
(model.reasoningModel ?? !!model.reasoningEfforts?.length) && 'reasoning',
|
|
444
|
+
modelCost(model),
|
|
445
|
+
];
|
|
446
|
+
return { value: model.id, label: modelChoice(model).label, hint: metadata.filter(Boolean).join(' · ') };
|
|
447
|
+
}
|
package/dist/renderer.d.ts
CHANGED
|
@@ -197,7 +197,7 @@ export declare function renderTeamBoard(team: TeamQueryResult): string;
|
|
|
197
197
|
export declare function renderHostStatus(status: HostStatusSnapshot): string;
|
|
198
198
|
export declare function renderRunDetails(details: Partial<RunQueryResult>): string;
|
|
199
199
|
export declare function renderConfigSummary(inspection: UserConfigInspection, status?: HostStatusSnapshot): string;
|
|
200
|
-
export declare function renderConfigCheck(inspection: UserConfigInspection, status?: HostStatusSnapshot): string;
|
|
200
|
+
export declare function renderConfigCheck(inspection: UserConfigInspection, status?: HostStatusSnapshot, availableModes?: readonly import("@saturn-universe/protocol").ModeSummary[] | undefined): string;
|
|
201
201
|
export declare function renderConfigInit(result: InitUserConfigResult): string;
|
|
202
202
|
export declare function renderUsageCard(usage: SessionUsageView): string;
|
|
203
203
|
export declare function renderReplHelp(): string;
|
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.3';
|
|
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}`,
|
|
@@ -1001,12 +1002,14 @@ export function renderConfigSummary(inspection, status) {
|
|
|
1001
1002
|
return [
|
|
1002
1003
|
cyan('[Config] 当前设置'),
|
|
1003
1004
|
' 工作区:' + inspection.workdir,
|
|
1004
|
-
active ? ' 使用的配置文件:' + active.path : '
|
|
1005
|
+
active ? ' 使用的配置文件:' + active.path : ' 未找到 config.toml。',
|
|
1005
1006
|
status ? ' 工作台已连接。默认模型:' + (status.defaultProfile ?? '尚未选择') : ' 工作台未连接。',
|
|
1006
1007
|
].join('\n');
|
|
1007
1008
|
}
|
|
1008
|
-
export function renderConfigCheck(inspection, status) {
|
|
1009
|
+
export function renderConfigCheck(inspection, status, availableModes = status?.availableModes) {
|
|
1009
1010
|
const lines = [renderConfigSummary(inspection, status)];
|
|
1011
|
+
if (availableModes?.length)
|
|
1012
|
+
lines.push(' 可用模式:' + availableModes.map(({ ref }) => ref).join('、'));
|
|
1010
1013
|
if (!inspection.files.workspaceConfig.exists && !inspection.files.userConfig.exists) {
|
|
1011
1014
|
lines.push(' 运行 saturn provider add 连接第一个 AI 服务。');
|
|
1012
1015
|
}
|
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.3",
|
|
4
4
|
"description": "Saturn local multi-agent runtime CLI",
|
|
5
5
|
"license": "AGPL-3.0-only",
|
|
6
6
|
"type": "module",
|
|
@@ -8,8 +8,9 @@
|
|
|
8
8
|
"dist"
|
|
9
9
|
],
|
|
10
10
|
"dependencies": {
|
|
11
|
-
"@
|
|
12
|
-
"@saturn-universe/
|
|
11
|
+
"@clack/prompts": "1.9.0",
|
|
12
|
+
"@saturn-universe/protocol": "0.1.2-dev.3",
|
|
13
|
+
"@saturn-universe/runtime-host": "0.1.2-dev.3",
|
|
13
14
|
"mdast-util-from-markdown": "^2.1.0",
|
|
14
15
|
"mdast-util-gfm": "^3.1.0",
|
|
15
16
|
"micromark-extension-gfm": "^3.0.0",
|