@saturn-universe/cli 0.1.2-dev.1 → 0.1.2-dev.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/attach.d.ts +3 -1
- package/dist/attach.js +4 -1
- 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/provider-discovery.d.ts +1 -0
- package/dist/provider-discovery.js +2 -1
- package/dist/provider-pricing.d.ts +1 -1
- package/dist/provider-pricing.js +3 -2
- package/dist/provider-wizard.d.ts +18 -0
- package/dist/provider-wizard.js +109 -0
- package/dist/provider.js +95 -37
- package/dist/renderer.d.ts +1 -1
- package/dist/renderer.js +5 -3
- package/dist/repl-host.d.ts +2 -0
- package/dist/repl-host.js +9 -1
- package/dist/repl-run-observer.js +1 -0
- package/dist/repl.js +118 -23
- package/dist/session-history.d.ts +4 -2
- package/dist/session-history.js +42 -10
- package/dist/slash-commands.d.ts +1 -0
- package/dist/slash-commands.js +16 -2
- package/dist/terminal-text.js +33 -7
- package/dist/tui.d.ts +2 -0
- package/dist/tui.js +87 -42
- package/package.json +4 -3
package/dist/attach.d.ts
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import type { TerminalRunStatus } from '@saturn-universe/protocol';
|
|
2
2
|
import type { RunProgressArguments } from './commands.js';
|
|
3
3
|
import type { CliOutput } from './results.js';
|
|
4
|
-
export declare function attach(root: string, args: RunProgressArguments
|
|
4
|
+
export declare function attach(root: string, args: RunProgressArguments & {
|
|
5
|
+
readonly initialPollMs?: number;
|
|
6
|
+
}, output: (frame: CliOutput) => void, signal: AbortSignal): Promise<{
|
|
5
7
|
cursor: string;
|
|
6
8
|
status?: TerminalRunStatus | 'paused';
|
|
7
9
|
pauseReason?: string;
|
package/dist/attach.js
CHANGED
|
@@ -6,6 +6,7 @@ import { integer, runProgressCommand } from './commands.js';
|
|
|
6
6
|
import { sendHostCommand } from './host-command.js';
|
|
7
7
|
export async function attach(root, args, output, signal) {
|
|
8
8
|
const pollMs = integer(args.values['poll-ms'], 250, 60000);
|
|
9
|
+
let nextPollMs = Math.min(args.initialPollMs ?? pollMs, pollMs);
|
|
9
10
|
const rawTimeout = args.values['timeout-ms'];
|
|
10
11
|
const unlimited = rawTimeout === '0';
|
|
11
12
|
const timeoutMs = unlimited ? Infinity : integer(rawTimeout, 300000, 2147483647);
|
|
@@ -55,6 +56,7 @@ export async function attach(root, args, output, signal) {
|
|
|
55
56
|
break;
|
|
56
57
|
if (!(args.values.reconnect && reconnectable(error)))
|
|
57
58
|
throw error;
|
|
59
|
+
nextPollMs = pollMs;
|
|
58
60
|
if (last !== error.code)
|
|
59
61
|
output({
|
|
60
62
|
ok: false,
|
|
@@ -67,7 +69,8 @@ export async function attach(root, args, output, signal) {
|
|
|
67
69
|
const remaining = deadline - performance.now();
|
|
68
70
|
if (remaining <= 0)
|
|
69
71
|
break;
|
|
70
|
-
await delay(Math.min(
|
|
72
|
+
await delay(Math.min(nextPollMs, remaining), undefined, { signal: observation }).catch(() => { });
|
|
73
|
+
nextPollMs = Math.min(pollMs, nextPollMs * 2);
|
|
71
74
|
}
|
|
72
75
|
if (!signal.aborted)
|
|
73
76
|
throw new CliError('HOST_TIMEOUT');
|
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()));
|
|
@@ -28,4 +28,5 @@ export declare function supportsTextModel(model: DiscoveredModel): boolean;
|
|
|
28
28
|
export declare function probeProviderEndpoint(baseUrl: string, apiKey: string, options?: {
|
|
29
29
|
readonly preferredProtocol?: ProviderProtocol;
|
|
30
30
|
readonly fetch?: typeof fetch;
|
|
31
|
+
readonly signal?: AbortSignal;
|
|
31
32
|
}): Promise<ProviderDiscovery>;
|
|
@@ -189,7 +189,8 @@ export async function probeProviderEndpoint(baseUrl, apiKey, options = {}) {
|
|
|
189
189
|
if (!endpoint || !apiKey.trim())
|
|
190
190
|
return unavailable;
|
|
191
191
|
const request = options.fetch ?? fetch;
|
|
192
|
-
const
|
|
192
|
+
const timeout = AbortSignal.timeout(8000);
|
|
193
|
+
const signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;
|
|
193
194
|
if (preset?.openCodeModelsUrl) {
|
|
194
195
|
try {
|
|
195
196
|
const response = await request(preset?.openCodeModelsUrl, {
|
|
@@ -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,7 +64,7 @@ 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);
|
|
@@ -73,8 +73,9 @@ export async function enrichPrices(baseUrl, models, request = fetch) {
|
|
|
73
73
|
return models;
|
|
74
74
|
const preset = matchedPreset?.id;
|
|
75
75
|
try {
|
|
76
|
+
const timeout = AbortSignal.timeout(4000);
|
|
76
77
|
const response = await request('https://models.dev/api.json', {
|
|
77
|
-
signal: AbortSignal.timeout
|
|
78
|
+
signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
|
|
78
79
|
redirect: 'error',
|
|
79
80
|
});
|
|
80
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, openCodeClientHeaders, 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
|
}
|
|
@@ -240,15 +262,18 @@ function parseProtocol(value) {
|
|
|
240
262
|
function selection(value) {
|
|
241
263
|
return [...new Set(value.split(',').map((part) => part.trim()))];
|
|
242
264
|
}
|
|
243
|
-
async function login(command, env, root, line, prompt, probe, prices) {
|
|
265
|
+
async function login(command, env, root, line, prompt, wizard, probe, prices) {
|
|
244
266
|
const flags = command.values;
|
|
245
267
|
let requestedId = command.id;
|
|
246
|
-
if (requestedId === undefined &&
|
|
268
|
+
if (requestedId === undefined && wizard) {
|
|
269
|
+
requestedId = await providerWizard.selectProvider(addPresets);
|
|
270
|
+
}
|
|
271
|
+
else if (requestedId === undefined && prompt) {
|
|
247
272
|
requestedId =
|
|
248
|
-
|
|
273
|
+
addPresets[await askChoice(prompt, line, 'Provider', addPresets.map((preset) => preset.label))].id;
|
|
249
274
|
}
|
|
250
275
|
const custom = requestedId === 'custom';
|
|
251
|
-
if (prompt && custom) {
|
|
276
|
+
if ((prompt || wizard) && custom) {
|
|
252
277
|
const used = new Set((await listProviderLogins(env, root)).map((p) => p.id));
|
|
253
278
|
let n = 1;
|
|
254
279
|
while (used.has('custom-' + n))
|
|
@@ -258,16 +283,19 @@ async function login(command, env, root, line, prompt, probe, prices) {
|
|
|
258
283
|
const id = providerId(requestedId);
|
|
259
284
|
const preset = providerPresets.find((item) => item.id === id);
|
|
260
285
|
const defaultUrl = preset?.defaultBaseUrl;
|
|
261
|
-
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: '));
|
|
262
296
|
const baseUrl = rawUrl && normalizeProviderBaseUrl(rawUrl);
|
|
263
297
|
if (!baseUrl)
|
|
264
298
|
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;
|
|
271
299
|
if (flags['api-key-stdin'] && (flags['api-key'] !== undefined || process.stdin.isTTY))
|
|
272
300
|
throw new AuthError('请通过管道提供密钥。', 'USAGE');
|
|
273
301
|
const openCodeModelsUrl = baseUrl === defaultUrl ? preset?.openCodeModelsUrl : undefined;
|
|
@@ -289,7 +317,7 @@ async function login(command, env, root, line, prompt, probe, prices) {
|
|
|
289
317
|
throw new AuthError('指定的环境变量没有密钥。');
|
|
290
318
|
const apiKey = configuredKey ??
|
|
291
319
|
(flags['api-key-stdin'] ? (await readText(process.stdin)).trimEnd() : flags['api-key']) ??
|
|
292
|
-
(
|
|
320
|
+
(wizard ? await providerWizard.apiKey() : await prompt?.question('API Key: ', true));
|
|
293
321
|
if (!apiKey?.trim() || apiKey !== apiKey.trim() || /[\u0000-\u001f\u007f]/.test(apiKey))
|
|
294
322
|
throw new AuthError('请输入一行有效的 API Key。', 'USAGE');
|
|
295
323
|
if (id.includes(apiKey) || baseUrl.includes(apiKey) || decodeURI(baseUrl).includes(apiKey))
|
|
@@ -299,27 +327,47 @@ async function login(command, env, root, line, prompt, probe, prices) {
|
|
|
299
327
|
inferProviderProtocol(baseUrl);
|
|
300
328
|
let protocol = preferredProtocol;
|
|
301
329
|
let discovered = [];
|
|
330
|
+
const defaultFlag = flags.default ?? flags.model;
|
|
302
331
|
if (!flags['no-probe'] &&
|
|
303
|
-
(openCodeModelsUrl || (flags.models === undefined &&
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
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
|
+
}
|
|
311
353
|
}
|
|
312
354
|
const candidates = discovered.filter(supportsTextModel);
|
|
313
355
|
const knownModel = new Map(discovered.map((model) => [model.id, model]));
|
|
314
|
-
const requestedDefault =
|
|
315
|
-
?
|
|
316
|
-
:
|
|
356
|
+
const requestedDefault = defaultFlag !== undefined && !knownModel.has(defaultFlag) && defaultFlag.startsWith(`${id}/`)
|
|
357
|
+
? defaultFlag.slice(id.length + 1)
|
|
358
|
+
: defaultFlag;
|
|
317
359
|
let models;
|
|
318
360
|
let chosen;
|
|
319
361
|
if (flags.models !== undefined)
|
|
320
362
|
models = selection(flags.models);
|
|
321
363
|
else if (requestedDefault !== undefined)
|
|
322
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
|
+
}
|
|
323
371
|
else if (prompt && candidates.length) {
|
|
324
372
|
const selected = await chooseManyFromPages(prompt, line, modelPickerTitle, candidates.map(modelChoice));
|
|
325
373
|
models = selected.map((index) => candidates[index].id);
|
|
@@ -340,7 +388,7 @@ async function login(command, env, root, line, prompt, probe, prices) {
|
|
|
340
388
|
throw new AuthError('请指定有效的模型名称。', 'USAGE');
|
|
341
389
|
const selectable = models.filter((model) => supportsTextModel(knownModel.get(model) ?? { id: model }));
|
|
342
390
|
const choicesFor = (items) => items.map((model) => modelChoice(knownModel.get(model) ?? { id: model }));
|
|
343
|
-
const defaultSelection = (flags.models !== undefined ?
|
|
391
|
+
const defaultSelection = (flags.models !== undefined ? defaultFlag : requestedDefault) ??
|
|
344
392
|
chosen ??
|
|
345
393
|
(prompt && selectable.length > 1
|
|
346
394
|
? selectable[await chooseFromPages(prompt, line, modelPickerTitle, choicesFor(selectable))]
|
|
@@ -354,7 +402,7 @@ async function login(command, env, root, line, prompt, probe, prices) {
|
|
|
354
402
|
: defaultSelection;
|
|
355
403
|
if (defaultModel !== undefined && !models.includes(defaultModel))
|
|
356
404
|
throw new AuthError('默认模型必须来自已选择的模型。', 'USAGE');
|
|
357
|
-
if (prompt && (defaultModel === undefined || !selectable.includes(defaultModel)))
|
|
405
|
+
if ((prompt || wizard) && (defaultModel === undefined || !selectable.includes(defaultModel)))
|
|
358
406
|
throw new AuthError('请选择可用于对话的默认模型。', 'USAGE');
|
|
359
407
|
await saveProviderLogin({
|
|
360
408
|
providerId: id,
|
|
@@ -366,7 +414,7 @@ async function login(command, env, root, line, prompt, probe, prices) {
|
|
|
366
414
|
discovered,
|
|
367
415
|
...(defaultModel === undefined ? {} : { defaultModel }),
|
|
368
416
|
}, env);
|
|
369
|
-
return { provider: id, models, tested: false };
|
|
417
|
+
return { provider: id, models, tested: false, defaultModel };
|
|
370
418
|
}
|
|
371
419
|
const modelPickerTitle = 'Model · 上下文 / USD/1M(入/出,≈估算)';
|
|
372
420
|
function modelChoice(model) {
|
|
@@ -377,13 +425,23 @@ function modelChoice(model) {
|
|
|
377
425
|
? `${model.id} · ${displayName}`
|
|
378
426
|
: model.id;
|
|
379
427
|
const context = model.contextWindow === undefined ? '—' : formatTokenCompact(model.contextWindow);
|
|
380
|
-
const exactPrice = model.priceSource === 'models.dev' || model.priceSource === 'opencode';
|
|
381
|
-
const cost = model.pricing
|
|
382
|
-
? `${exactPrice ? '' : '≈'}$${model.pricing.inputPerMillion}/$${model.pricing.outputPerMillion}`
|
|
383
|
-
: '—';
|
|
384
428
|
return {
|
|
385
429
|
label,
|
|
386
|
-
detail: `${context} ${
|
|
430
|
+
detail: `${context} ${modelCost(model) ?? '—'}`,
|
|
387
431
|
...(model.displayName ? { search: model.displayName } : {}),
|
|
388
432
|
};
|
|
389
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,7 +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.
|
|
7
|
+
const SATURN_CLI_VERSION = '0.1.2-dev.10';
|
|
8
8
|
const { bold, dim, cyan, brightCyan, green, yellow, red, magenta, whiteBold } = createTerminalPainter();
|
|
9
9
|
function padLogoLines(lines) {
|
|
10
10
|
const maxWidth = Math.max(0, ...lines.map(stringDisplayWidth));
|
|
@@ -1002,12 +1002,14 @@ export function renderConfigSummary(inspection, status) {
|
|
|
1002
1002
|
return [
|
|
1003
1003
|
cyan('[Config] 当前设置'),
|
|
1004
1004
|
' 工作区:' + inspection.workdir,
|
|
1005
|
-
active ? ' 使用的配置文件:' + active.path : '
|
|
1005
|
+
active ? ' 使用的配置文件:' + active.path : ' 未找到 config.toml。',
|
|
1006
1006
|
status ? ' 工作台已连接。默认模型:' + (status.defaultProfile ?? '尚未选择') : ' 工作台未连接。',
|
|
1007
1007
|
].join('\n');
|
|
1008
1008
|
}
|
|
1009
|
-
export function renderConfigCheck(inspection, status) {
|
|
1009
|
+
export function renderConfigCheck(inspection, status, availableModes = status?.availableModes) {
|
|
1010
1010
|
const lines = [renderConfigSummary(inspection, status)];
|
|
1011
|
+
if (availableModes?.length)
|
|
1012
|
+
lines.push(' 可用模式:' + availableModes.map(({ ref }) => ref).join('、'));
|
|
1011
1013
|
if (!inspection.files.workspaceConfig.exists && !inspection.files.userConfig.exists) {
|
|
1012
1014
|
lines.push(' 运行 saturn provider add 连接第一个 AI 服务。');
|
|
1013
1015
|
}
|
package/dist/repl-host.d.ts
CHANGED
|
@@ -5,8 +5,10 @@ export interface ReplHostState {
|
|
|
5
5
|
host?: ManagedHost | undefined;
|
|
6
6
|
activeMode?: ModeSummary | undefined;
|
|
7
7
|
modeRef?: string | undefined;
|
|
8
|
+
sessionModeRef?: string | undefined;
|
|
8
9
|
}
|
|
9
10
|
export declare function applyReplMode(state: ReplHostState, activeMode: ModeSummary | undefined, modeRef?: string): void;
|
|
11
|
+
export declare function applyReplSessionMode(state: ReplHostState, modeRef: string | undefined): void;
|
|
10
12
|
export declare function createReplHostConnection(state: ReplHostState, initialOptions: HostLaunchOptions): {
|
|
11
13
|
launch: () => Promise<ManagedHost>;
|
|
12
14
|
accept: (host: ManagedHost) => ManagedHost;
|
package/dist/repl-host.js
CHANGED
|
@@ -4,12 +4,20 @@ export function applyReplMode(state, activeMode, modeRef) {
|
|
|
4
4
|
state.activeMode = activeMode;
|
|
5
5
|
state.modeRef = activeMode?.ref ?? modeRef;
|
|
6
6
|
}
|
|
7
|
+
export function applyReplSessionMode(state, modeRef) {
|
|
8
|
+
state.sessionModeRef = modeRef;
|
|
9
|
+
const status = state.host?.status;
|
|
10
|
+
if (modeRef)
|
|
11
|
+
applyReplMode(state, status?.availableModes.find(({ ref }) => ref === modeRef), modeRef);
|
|
12
|
+
else
|
|
13
|
+
applyReplMode(state, status?.activeMode);
|
|
14
|
+
}
|
|
7
15
|
export function createReplHostConnection(state, initialOptions) {
|
|
8
16
|
let launchOptions = { ...initialOptions };
|
|
9
17
|
let latestStatusRequest = 0;
|
|
10
18
|
function accept(host) {
|
|
11
19
|
state.host = host;
|
|
12
|
-
|
|
20
|
+
applyReplSessionMode(state, state.sessionModeRef);
|
|
13
21
|
return host;
|
|
14
22
|
}
|
|
15
23
|
async function refreshStatus({ signal, merge = false } = {}) {
|
|
@@ -34,6 +34,7 @@ export function createReplRunObserver(workdir, runCursors) {
|
|
|
34
34
|
result = await attach(workdir, {
|
|
35
35
|
runId,
|
|
36
36
|
...(interactiveProgress ? { interactiveProgress } : {}),
|
|
37
|
+
initialPollMs: 16,
|
|
37
38
|
values: { after: cursor, 'poll-ms': '100', 'timeout-ms': '0', reconnect: true },
|
|
38
39
|
commandId: randomUUID(),
|
|
39
40
|
}, (frame) => {
|