@saturn-universe/cli 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +661 -0
- package/dist/attach.d.ts +9 -0
- package/dist/attach.js +80 -0
- package/dist/auth-config.d.ts +31 -0
- package/dist/auth-config.js +285 -0
- package/dist/choice-menu.d.ts +13 -0
- package/dist/choice-menu.js +238 -0
- package/dist/cli-diagnostics.d.ts +23 -0
- package/dist/cli-diagnostics.js +42 -0
- package/dist/cli-help.d.ts +6 -0
- package/dist/cli-help.js +163 -0
- package/dist/client.d.ts +13 -0
- package/dist/client.js +90 -0
- package/dist/commands.d.ts +64 -0
- package/dist/commands.js +299 -0
- package/dist/compaction-command.d.ts +16 -0
- package/dist/compaction-command.js +16 -0
- package/dist/composer.d.ts +88 -0
- package/dist/composer.js +124 -0
- package/dist/config-cli.d.ts +1 -0
- package/dist/config-cli.js +47 -0
- package/dist/config-file.d.ts +1 -0
- package/dist/config-file.js +43 -0
- package/dist/config-lock.d.ts +5 -0
- package/dist/config-lock.js +45 -0
- package/dist/duration.d.ts +2 -0
- package/dist/duration.js +11 -0
- package/dist/export.d.ts +19 -0
- package/dist/export.js +66 -0
- package/dist/host-command.d.ts +40 -0
- package/dist/host-command.js +48 -0
- package/dist/host-launcher.d.ts +22 -0
- package/dist/host-launcher.js +300 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +400 -0
- package/dist/markdown.d.ts +1 -0
- package/dist/markdown.js +118 -0
- package/dist/mcp-cli.d.ts +44 -0
- package/dist/mcp-cli.js +647 -0
- package/dist/menu.d.ts +7 -0
- package/dist/menu.js +91 -0
- package/dist/project-mcp-config.d.ts +9 -0
- package/dist/project-mcp-config.js +98 -0
- package/dist/provider-discovery.d.ts +26 -0
- package/dist/provider-discovery.js +138 -0
- package/dist/provider-pricing.d.ts +3 -0
- package/dist/provider-pricing.js +130 -0
- package/dist/provider.d.ts +16 -0
- package/dist/provider.js +370 -0
- package/dist/reconcile-command.d.ts +36 -0
- package/dist/reconcile-command.js +64 -0
- package/dist/renderer.d.ts +204 -0
- package/dist/renderer.js +1134 -0
- package/dist/repl-host.d.ts +22 -0
- package/dist/repl-host.js +51 -0
- package/dist/repl-run-observer.d.ts +27 -0
- package/dist/repl-run-observer.js +86 -0
- package/dist/repl.d.ts +12 -0
- package/dist/repl.js +1834 -0
- package/dist/results.d.ts +23 -0
- package/dist/results.js +1 -0
- package/dist/sandbox-cli.d.ts +39 -0
- package/dist/sandbox-cli.js +324 -0
- package/dist/session-history.d.ts +17 -0
- package/dist/session-history.js +76 -0
- package/dist/settings-menu.d.ts +2 -0
- package/dist/settings-menu.js +111 -0
- package/dist/skill-cli.d.ts +25 -0
- package/dist/skill-cli.js +355 -0
- package/dist/slash-commands.d.ts +66 -0
- package/dist/slash-commands.js +1449 -0
- package/dist/terminal-input.d.ts +24 -0
- package/dist/terminal-input.js +111 -0
- package/dist/terminal-selection.d.ts +21 -0
- package/dist/terminal-selection.js +72 -0
- package/dist/terminal-text.d.ts +38 -0
- package/dist/terminal-text.js +238 -0
- package/dist/tui.d.ts +170 -0
- package/dist/tui.js +2559 -0
- package/dist/usage.d.ts +13 -0
- package/dist/usage.js +46 -0
- package/dist/user-config.d.ts +48 -0
- package/dist/user-config.js +188 -0
- package/package.json +18 -3
- package/README.md +0 -3
package/dist/attach.js
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
2
|
+
import { isTerminalRunStatus } from '@saturn-universe/protocol';
|
|
3
|
+
import { MAX_HOST_REQUEST_TIMEOUT_MS } from './client.js';
|
|
4
|
+
import { CliError, isHostConnectionError } from './cli-diagnostics.js';
|
|
5
|
+
import { integer, runProgressCommand } from './commands.js';
|
|
6
|
+
import { sendHostCommand } from './host-command.js';
|
|
7
|
+
export async function attach(root, args, output, signal) {
|
|
8
|
+
const pollMs = integer(args.values['poll-ms'], 250, 60000);
|
|
9
|
+
const rawTimeout = args.values['timeout-ms'];
|
|
10
|
+
const unlimited = rawTimeout === '0';
|
|
11
|
+
const timeoutMs = unlimited ? Infinity : integer(rawTimeout, 300000, 2147483647);
|
|
12
|
+
const deadline = unlimited ? Infinity : performance.now() + timeoutMs;
|
|
13
|
+
const observation = unlimited ? signal : AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]);
|
|
14
|
+
const finished = () => observation.aborted || performance.now() >= deadline;
|
|
15
|
+
let cursor = String(args.values.after ?? '0');
|
|
16
|
+
let last = '';
|
|
17
|
+
while (!finished()) {
|
|
18
|
+
const requestTimeout = Math.min(MAX_HOST_REQUEST_TIMEOUT_MS, Math.max(1, Math.ceil(deadline - performance.now())));
|
|
19
|
+
try {
|
|
20
|
+
const page = await sendHostCommand(root, runProgressCommand(args, cursor), {
|
|
21
|
+
commandId: args.commandId,
|
|
22
|
+
timeoutMs: requestTimeout,
|
|
23
|
+
signal: observation,
|
|
24
|
+
});
|
|
25
|
+
if (finished())
|
|
26
|
+
break;
|
|
27
|
+
cursor = page.cursor;
|
|
28
|
+
const marker = JSON.stringify([
|
|
29
|
+
cursor,
|
|
30
|
+
page.status,
|
|
31
|
+
page.pauseReason,
|
|
32
|
+
page.pluginBlock?.code,
|
|
33
|
+
page.pluginBlock?.message,
|
|
34
|
+
page.draft?.requestId,
|
|
35
|
+
page.draft?.revision,
|
|
36
|
+
page.pendingApprovals?.map(({ approvalId }) => approvalId),
|
|
37
|
+
...(args.interactiveProgress ? [page.liveAgents ?? {}, page.telemetry ?? {}] : []),
|
|
38
|
+
]);
|
|
39
|
+
if (page.events.length || marker !== last)
|
|
40
|
+
output({ ok: true, type: 'progress', result: page });
|
|
41
|
+
last = marker;
|
|
42
|
+
if (!page.hasMore && page.pluginBlock)
|
|
43
|
+
return { cursor, status: 'paused', pauseReason: page.pluginBlock.code };
|
|
44
|
+
if (!page.hasMore && (page.status === 'paused' || isTerminalRunStatus(page.status)))
|
|
45
|
+
return {
|
|
46
|
+
cursor,
|
|
47
|
+
status: page.status,
|
|
48
|
+
...(page.pauseReason ? { pauseReason: page.pauseReason } : {}),
|
|
49
|
+
};
|
|
50
|
+
if (page.hasMore)
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
catch (error) {
|
|
54
|
+
if (finished())
|
|
55
|
+
break;
|
|
56
|
+
if (!(args.values.reconnect && reconnectable(error)))
|
|
57
|
+
throw error;
|
|
58
|
+
if (last !== error.code)
|
|
59
|
+
output({
|
|
60
|
+
ok: false,
|
|
61
|
+
type: 'reconnecting',
|
|
62
|
+
cursor,
|
|
63
|
+
error: { code: error.code, diagnosticId: error.diagnosticId, retryable: error.retryable },
|
|
64
|
+
});
|
|
65
|
+
last = error.code;
|
|
66
|
+
}
|
|
67
|
+
const remaining = deadline - performance.now();
|
|
68
|
+
if (remaining <= 0)
|
|
69
|
+
break;
|
|
70
|
+
await delay(Math.min(pollMs, remaining), undefined, { signal: observation }).catch(() => { });
|
|
71
|
+
}
|
|
72
|
+
if (!signal.aborted)
|
|
73
|
+
throw new CliError('HOST_TIMEOUT');
|
|
74
|
+
return { cursor, detached: true };
|
|
75
|
+
}
|
|
76
|
+
function reconnectable(error) {
|
|
77
|
+
return (error instanceof CliError &&
|
|
78
|
+
(isHostConnectionError(error.code) ||
|
|
79
|
+
(error.retryable && ['HOST_BUSY', 'STORAGE_BUSY'].includes(error.code))));
|
|
80
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { type ProviderProtocol } from '@saturn-universe/protocol';
|
|
2
|
+
import type { DiscoveredModel } from './provider-discovery.js';
|
|
3
|
+
interface LoginConfig {
|
|
4
|
+
readonly providerId: string;
|
|
5
|
+
readonly baseUrl: string;
|
|
6
|
+
readonly protocol: ProviderProtocol;
|
|
7
|
+
readonly apiKey: string;
|
|
8
|
+
readonly credentialRef?: string;
|
|
9
|
+
readonly models: readonly string[];
|
|
10
|
+
readonly defaultModel?: string;
|
|
11
|
+
readonly discovered: readonly DiscoveredModel[];
|
|
12
|
+
}
|
|
13
|
+
export declare function saveProviderLogin(input: LoginConfig, env: NodeJS.ProcessEnv): Promise<void>;
|
|
14
|
+
export declare function removeProviderLogin(providerId: string, keepConfig: boolean, env: NodeJS.ProcessEnv): Promise<void>;
|
|
15
|
+
export declare function listProviderLogins(env: NodeJS.ProcessEnv, root: string): Promise<{
|
|
16
|
+
id: string;
|
|
17
|
+
profile: string;
|
|
18
|
+
model: string;
|
|
19
|
+
configured: boolean;
|
|
20
|
+
supported: boolean;
|
|
21
|
+
selected: boolean;
|
|
22
|
+
removable: boolean;
|
|
23
|
+
}[]>;
|
|
24
|
+
export declare function chooseDefault(profile: string, root: string, env: NodeJS.ProcessEnv): Promise<void>;
|
|
25
|
+
export declare function configuredEndpoint(profile: string, root: string, env: NodeJS.ProcessEnv): Promise<{
|
|
26
|
+
baseUrl: string;
|
|
27
|
+
model: string;
|
|
28
|
+
key: string;
|
|
29
|
+
protocol: "openai-responses" | "openai-chat" | "anthropic" | "gemini";
|
|
30
|
+
}>;
|
|
31
|
+
export {};
|
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
import { readFile, rm } from 'node:fs/promises';
|
|
2
|
+
import { parse, stringify } from 'smol-toml';
|
|
3
|
+
import { credentialRefSchema, lookupModelMetadata, normalizeProviderBaseUrl, normalizeProviderProtocol, parseDotenvText, providerCredentialKey, resolveCredentialMap, userAuthCredentialsPath, userConfigPath, } from '@saturn-universe/protocol';
|
|
4
|
+
import { AuthError } from './cli-diagnostics.js';
|
|
5
|
+
import { atomicWriteText } from './config-file.js';
|
|
6
|
+
import { withUserConfigLock } from './config-lock.js';
|
|
7
|
+
function table(value) {
|
|
8
|
+
if (value === undefined)
|
|
9
|
+
return {};
|
|
10
|
+
if (value && typeof value === 'object' && [null, Object.prototype].includes(Object.getPrototypeOf(value)))
|
|
11
|
+
return value;
|
|
12
|
+
throw new AuthError('Could not read provider tables in config.toml.');
|
|
13
|
+
}
|
|
14
|
+
function own(table, key) {
|
|
15
|
+
return Object.hasOwn(table, key) ? table[key] : undefined;
|
|
16
|
+
}
|
|
17
|
+
function configuredProfiles(config) {
|
|
18
|
+
const read = (name, providerId, modelId, entry, layered) => {
|
|
19
|
+
const { base_url: url, protocol = 'openai-responses', credential_ref: credentialRef, revision = '1', codec_version: codecVersion = 1, } = entry;
|
|
20
|
+
const baseUrl = typeof url === 'string' ? normalizeProviderBaseUrl(url) : undefined;
|
|
21
|
+
const normalizedProtocol = typeof protocol === 'string' ? normalizeProviderProtocol(protocol) : undefined;
|
|
22
|
+
const credential = credentialRefSchema.safeParse(credentialRef);
|
|
23
|
+
if (typeof providerId !== 'string' ||
|
|
24
|
+
typeof modelId !== 'string' ||
|
|
25
|
+
!baseUrl ||
|
|
26
|
+
!credential.success ||
|
|
27
|
+
typeof revision !== 'string' ||
|
|
28
|
+
(codecVersion !== 1 && codecVersion !== 2) ||
|
|
29
|
+
!normalizedProtocol)
|
|
30
|
+
throw new AuthError('Could not read provider tables in config.toml.');
|
|
31
|
+
return {
|
|
32
|
+
name,
|
|
33
|
+
providerId: providerId.trim(),
|
|
34
|
+
modelId: modelId.trim(),
|
|
35
|
+
baseUrl,
|
|
36
|
+
credentialRef: credential.data,
|
|
37
|
+
revision: revision.trim(),
|
|
38
|
+
codecVersion,
|
|
39
|
+
protocol: normalizedProtocol,
|
|
40
|
+
layered,
|
|
41
|
+
};
|
|
42
|
+
};
|
|
43
|
+
const profiles = Object.entries(table(config.profiles)).map(([name, value]) => {
|
|
44
|
+
const entry = table(value);
|
|
45
|
+
return read(name, entry.provider_id, entry.model_id, entry, false);
|
|
46
|
+
});
|
|
47
|
+
for (const [providerId, value] of Object.entries(table(config.providers))) {
|
|
48
|
+
const entry = table(value);
|
|
49
|
+
if (!Array.isArray(entry.models) || !entry.models.length)
|
|
50
|
+
throw new AuthError('Could not read provider models in config.toml.');
|
|
51
|
+
for (const model of entry.models) {
|
|
52
|
+
if (typeof model !== 'string')
|
|
53
|
+
throw new AuthError('Could not read provider models in config.toml.');
|
|
54
|
+
profiles.push(read(`${providerId}/${model.trim()}`, providerId, model, entry, true));
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return profiles;
|
|
58
|
+
}
|
|
59
|
+
function validateProfileBindings(config, profiles) {
|
|
60
|
+
const names = new Set();
|
|
61
|
+
const identities = new Set();
|
|
62
|
+
const revisions = new Map();
|
|
63
|
+
for (const p of profiles) {
|
|
64
|
+
if (names.has(p.name))
|
|
65
|
+
throw new AuthError('A generated profile name already exists in config.toml.');
|
|
66
|
+
names.add(p.name);
|
|
67
|
+
const identity = JSON.stringify([p.providerId, p.revision, p.modelId]);
|
|
68
|
+
const ref = `${p.providerId}@${p.revision}`;
|
|
69
|
+
const binding = JSON.stringify([p.baseUrl, p.credentialRef, p.codecVersion, p.protocol]);
|
|
70
|
+
if (identities.has(identity) || (revisions.has(ref) && revisions.get(ref) !== binding))
|
|
71
|
+
throw new AuthError('A provider revision conflicts with an existing profile in config.toml.');
|
|
72
|
+
identities.add(identity);
|
|
73
|
+
revisions.set(ref, binding);
|
|
74
|
+
}
|
|
75
|
+
if (Object.values(table(config.task_profiles)).some((ref) => typeof ref !== 'string' || !names.has(ref.trim())))
|
|
76
|
+
throw new AuthError('A task profile references a model that would be removed.');
|
|
77
|
+
}
|
|
78
|
+
async function readOptional(file) {
|
|
79
|
+
try {
|
|
80
|
+
return await readFile(file, 'utf8');
|
|
81
|
+
}
|
|
82
|
+
catch (error) {
|
|
83
|
+
if (error.code === 'ENOENT')
|
|
84
|
+
return undefined;
|
|
85
|
+
throw error;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
async function readConfig(env) {
|
|
89
|
+
try {
|
|
90
|
+
const text = await readOptional(userConfigPath(env));
|
|
91
|
+
if (text === undefined)
|
|
92
|
+
return { version: 1 };
|
|
93
|
+
const config = parse(text);
|
|
94
|
+
if (config.version === 1)
|
|
95
|
+
return config;
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
// TOML errors may include snippets of the source file.
|
|
99
|
+
}
|
|
100
|
+
throw new AuthError('Could not read config.toml.');
|
|
101
|
+
}
|
|
102
|
+
function updateCredential(text, key, value) {
|
|
103
|
+
const lines = text.replace(/^\uFEFF/, '').split(/\r?\n/);
|
|
104
|
+
const assignment = new RegExp(`^\\s*(?:export \\s*)?${key}\\s*=`);
|
|
105
|
+
const kept = lines.filter((line) => !assignment.test(line));
|
|
106
|
+
while (kept.at(-1) === '')
|
|
107
|
+
kept.pop();
|
|
108
|
+
if (value !== undefined) {
|
|
109
|
+
// The Host's dotenv parser preserves characters inside matching outer quotes.
|
|
110
|
+
kept.push(`${key}=${/^["']/.test(value) ? `"${value}"` : value}`);
|
|
111
|
+
}
|
|
112
|
+
return kept.length
|
|
113
|
+
? kept.join(text.includes('\r\n') ? '\r\n' : '\n') + (text.includes('\r\n') ? '\r\n' : '\n')
|
|
114
|
+
: '';
|
|
115
|
+
}
|
|
116
|
+
const authConfigBusy = () => new AuthError('Another auth update is in progress in SATURN_HOME.');
|
|
117
|
+
async function commitAuthUpdate(env, key, value, config) {
|
|
118
|
+
const nextConfig = config && stringify(config);
|
|
119
|
+
// Check serialization before changing the credential layer.
|
|
120
|
+
if (nextConfig !== undefined)
|
|
121
|
+
parse(nextConfig);
|
|
122
|
+
const credentialPath = userAuthCredentialsPath(env);
|
|
123
|
+
const previous = await readOptional(credentialPath);
|
|
124
|
+
const entries = parseDotenvText(previous ?? '');
|
|
125
|
+
const changed = value !== undefined || entries.has(key);
|
|
126
|
+
if (changed)
|
|
127
|
+
await atomicWriteText(credentialPath, updateCredential(previous ?? '', key, value), 0o600);
|
|
128
|
+
try {
|
|
129
|
+
if (nextConfig !== undefined)
|
|
130
|
+
await atomicWriteText(userConfigPath(env), nextConfig, 0o600);
|
|
131
|
+
}
|
|
132
|
+
catch (error) {
|
|
133
|
+
if (changed) {
|
|
134
|
+
if (previous === undefined)
|
|
135
|
+
await rm(credentialPath, { force: true });
|
|
136
|
+
else
|
|
137
|
+
await atomicWriteText(credentialPath, previous, 0o600);
|
|
138
|
+
}
|
|
139
|
+
throw error;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
export async function saveProviderLogin(input, env) {
|
|
143
|
+
await withUserConfigLock({ env, timeoutError: authConfigBusy }, async () => {
|
|
144
|
+
const config = await readConfig(env);
|
|
145
|
+
const providers = table(config.providers);
|
|
146
|
+
const previous = table(own(providers, input.providerId));
|
|
147
|
+
const priorOverrides = table(previous.model_overrides);
|
|
148
|
+
const credentialKey = providerCredentialKey(input.providerId);
|
|
149
|
+
const credentialRef = input.credentialRef ?? `env:${credentialKey}`;
|
|
150
|
+
if (configuredProfiles(config).some((p) => p.providerId !== input.providerId &&
|
|
151
|
+
(p.credentialRef === credentialRef ||
|
|
152
|
+
(p.layered && providerCredentialKey(p.providerId) === credentialKey))))
|
|
153
|
+
throw new AuthError('The credential name is already used by another provider.');
|
|
154
|
+
const discovered = new Map(input.discovered.map((model) => [model.id, model]));
|
|
155
|
+
const overrides = Object.fromEntries(input.models.flatMap((id) => {
|
|
156
|
+
const model = discovered.get(id);
|
|
157
|
+
const metadata = lookupModelMetadata(id);
|
|
158
|
+
const previous = table(own(priorOverrides, id));
|
|
159
|
+
const values = {
|
|
160
|
+
...(model?.contextWindow !== undefined && metadata?.contextWindow !== model.contextWindow
|
|
161
|
+
? { context_window: model.contextWindow }
|
|
162
|
+
: {}),
|
|
163
|
+
...(model?.maxOutputTokens !== undefined && metadata?.maxOutputTokens !== model.maxOutputTokens
|
|
164
|
+
? { max_output_tokens: model.maxOutputTokens }
|
|
165
|
+
: {}),
|
|
166
|
+
...(model?.reasoningModel !== undefined ? { reasoning_model: model.reasoningModel } : {}),
|
|
167
|
+
...(model?.reasoningModel !== false && model?.reasoningEfforts?.length
|
|
168
|
+
? { reasoning_efforts: [...model.reasoningEfforts] }
|
|
169
|
+
: {}),
|
|
170
|
+
...(model?.defaultReasoningEffort
|
|
171
|
+
? { default_reasoning_effort: model.defaultReasoningEffort }
|
|
172
|
+
: {}),
|
|
173
|
+
...(model?.priceSource === 'models.dev' && model.pricing
|
|
174
|
+
? {
|
|
175
|
+
pricing: {
|
|
176
|
+
input_per_million: model.pricing.inputPerMillion,
|
|
177
|
+
output_per_million: model.pricing.outputPerMillion,
|
|
178
|
+
...(model.pricing.cachedInputPerMillion === undefined
|
|
179
|
+
? {}
|
|
180
|
+
: { cached_input_per_million: model.pricing.cachedInputPerMillion }),
|
|
181
|
+
},
|
|
182
|
+
}
|
|
183
|
+
: {}),
|
|
184
|
+
...previous,
|
|
185
|
+
};
|
|
186
|
+
return Object.keys(values).length ? [[id, values]] : [];
|
|
187
|
+
}));
|
|
188
|
+
delete previous.model_overrides;
|
|
189
|
+
const models = [...input.models];
|
|
190
|
+
const entry = {
|
|
191
|
+
...previous,
|
|
192
|
+
base_url: input.baseUrl,
|
|
193
|
+
protocol: input.protocol,
|
|
194
|
+
credential_ref: credentialRef,
|
|
195
|
+
models,
|
|
196
|
+
...(Object.keys(overrides).length ? { model_overrides: overrides } : {}),
|
|
197
|
+
};
|
|
198
|
+
config.providers = { ...providers, [input.providerId]: entry };
|
|
199
|
+
const profiles = configuredProfiles(config);
|
|
200
|
+
validateProfileBindings(config, profiles);
|
|
201
|
+
if (input.defaultModel || !profiles.some((p) => p.name === config.default_profile)) {
|
|
202
|
+
config.default_profile = `${input.providerId}/${input.defaultModel ?? models[0]}`;
|
|
203
|
+
}
|
|
204
|
+
if (input.credentialRef)
|
|
205
|
+
await atomicWriteText(userConfigPath(env), stringify(config), 0o600);
|
|
206
|
+
else
|
|
207
|
+
await commitAuthUpdate(env, credentialKey, input.apiKey, config);
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
export async function removeProviderLogin(providerId, keepConfig, env) {
|
|
211
|
+
await withUserConfigLock({ env, timeoutError: authConfigBusy }, async () => {
|
|
212
|
+
const config = await readConfig(env);
|
|
213
|
+
const providers = table(config.providers);
|
|
214
|
+
const exists = Object.hasOwn(providers, providerId);
|
|
215
|
+
const key = providerCredentialKey(providerId);
|
|
216
|
+
const profiles = configuredProfiles(config);
|
|
217
|
+
if (profiles.some((p) => p.providerId !== providerId &&
|
|
218
|
+
(p.credentialRef === `env:${key}` || (p.layered && providerCredentialKey(p.providerId) === key))))
|
|
219
|
+
throw new AuthError('The credential name is used by another provider.');
|
|
220
|
+
if (keepConfig || !exists) {
|
|
221
|
+
await commitAuthUpdate(env, key, undefined);
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
const removed = new Set(profiles.filter((p) => p.layered && p.providerId === providerId).map((p) => p.name));
|
|
225
|
+
delete providers[providerId];
|
|
226
|
+
const remaining = profiles.filter((p) => !removed.has(p.name));
|
|
227
|
+
const current = typeof config.default_profile === 'string' ? config.default_profile.trim() : '';
|
|
228
|
+
if (removed.has(current)) {
|
|
229
|
+
const replacement = remaining[0];
|
|
230
|
+
if (replacement)
|
|
231
|
+
config.default_profile = replacement.name;
|
|
232
|
+
else
|
|
233
|
+
delete config.default_profile;
|
|
234
|
+
}
|
|
235
|
+
const tasks = table(config.task_profiles);
|
|
236
|
+
for (const [name, profile] of Object.entries(tasks)) {
|
|
237
|
+
if (typeof profile === 'string' && removed.has(profile.trim()))
|
|
238
|
+
delete tasks[name];
|
|
239
|
+
}
|
|
240
|
+
await commitAuthUpdate(env, key, undefined, config);
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
export async function listProviderLogins(env, root) {
|
|
244
|
+
const config = await readConfig(env);
|
|
245
|
+
const profiles = configuredProfiles(config);
|
|
246
|
+
if (!profiles.length)
|
|
247
|
+
return [];
|
|
248
|
+
const { values } = await resolveCredentialMap(root, env);
|
|
249
|
+
const secrets = profiles
|
|
250
|
+
.map((p) => values.get(p.credentialRef.slice(4)))
|
|
251
|
+
.filter((key) => !!key);
|
|
252
|
+
const clean = (value) => {
|
|
253
|
+
for (const secret of secrets)
|
|
254
|
+
value = value.replaceAll(secret, '[redacted]');
|
|
255
|
+
return value.replace(/[\u0000-\u001f\u007f-\u009f]/g, '');
|
|
256
|
+
};
|
|
257
|
+
return profiles.map((p) => ({
|
|
258
|
+
id: clean(p.providerId),
|
|
259
|
+
profile: clean(p.name),
|
|
260
|
+
model: clean(p.modelId),
|
|
261
|
+
configured: Boolean(values.get(p.credentialRef.slice(4))?.trim()),
|
|
262
|
+
supported: true,
|
|
263
|
+
selected: p.name === config.default_profile,
|
|
264
|
+
removable: p.layered,
|
|
265
|
+
}));
|
|
266
|
+
}
|
|
267
|
+
export async function chooseDefault(profile, root, env) {
|
|
268
|
+
await withUserConfigLock({ env, timeoutError: authConfigBusy }, async () => {
|
|
269
|
+
const config = await readConfig(env);
|
|
270
|
+
const item = configuredProfiles(config).find((p) => p.name === profile);
|
|
271
|
+
if (!item || !(await resolveCredentialMap(root, env)).values.get(item.credentialRef.slice(4))?.trim())
|
|
272
|
+
throw new AuthError('这个模型尚未就绪,请先检查服务和密钥。');
|
|
273
|
+
config.default_profile = profile;
|
|
274
|
+
await atomicWriteText(userConfigPath(env), stringify(config), 0o600);
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
export async function configuredEndpoint(profile, root, env) {
|
|
278
|
+
const item = configuredProfiles(await readConfig(env)).find((p) => p.name === profile);
|
|
279
|
+
if (!item)
|
|
280
|
+
throw new AuthError('请选择支持对话的模型。');
|
|
281
|
+
const key = (await resolveCredentialMap(root, env)).values.get(item.credentialRef.slice(4));
|
|
282
|
+
if (!key?.trim())
|
|
283
|
+
throw new AuthError('尚未填写这个服务的密钥。');
|
|
284
|
+
return { baseUrl: item.baseUrl, model: item.modelId, key, protocol: item.protocol };
|
|
285
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export interface ChoiceItem {
|
|
2
|
+
readonly label: string;
|
|
3
|
+
readonly detail?: string;
|
|
4
|
+
readonly search?: string;
|
|
5
|
+
}
|
|
6
|
+
export interface ChoicePrompt {
|
|
7
|
+
question(label: string, secret?: boolean): Promise<string>;
|
|
8
|
+
choose?(title: string, items: readonly ChoiceItem[]): Promise<number>;
|
|
9
|
+
chooseMany?(title: string, items: readonly ChoiceItem[]): Promise<readonly number[]>;
|
|
10
|
+
}
|
|
11
|
+
export declare function chooseFromPages(prompt: ChoicePrompt, print: (line: string) => void, title: string, items: readonly ChoiceItem[]): Promise<number>;
|
|
12
|
+
export declare function chooseManyFromPages(prompt: ChoicePrompt, print: (line: string) => void, title: string, items: readonly ChoiceItem[]): Promise<readonly number[]>;
|
|
13
|
+
export declare function chooseInTerminal(input: NodeJS.ReadStream, output: NodeJS.WriteStream, title: string, items: readonly ChoiceItem[], multiple?: boolean): Promise<readonly number[]>;
|
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
import { clearScreenDown, cursorTo, emitKeypressEvents, moveCursor } from 'node:readline';
|
|
2
|
+
import { AuthError } from './cli-diagnostics.js';
|
|
3
|
+
import { createTerminalPainter, stringDisplayWidth, truncateDisplay, truncateMiddle, } from './terminal-text.js';
|
|
4
|
+
const empty = '没有匹配的模型。';
|
|
5
|
+
function rowsFor(items, query) {
|
|
6
|
+
const needle = query.trim().toLowerCase();
|
|
7
|
+
return items.flatMap((item, index) => !needle || `${item.label} ${item.search ?? ''}`.toLowerCase().includes(needle)
|
|
8
|
+
? [{ ...item, index }]
|
|
9
|
+
: []);
|
|
10
|
+
}
|
|
11
|
+
function titleFor(title, page, pages, width) {
|
|
12
|
+
const counter = pages > 1 ? ` · ${page + 1}/${pages} 页` : '';
|
|
13
|
+
const available = width - stringDisplayWidth(counter);
|
|
14
|
+
return available > 0 ? truncateDisplay(title, available) + counter : truncateDisplay(counter.trim(), width);
|
|
15
|
+
}
|
|
16
|
+
function paintMatch(value, query, painter) {
|
|
17
|
+
const needle = query.trim().toLowerCase();
|
|
18
|
+
const at = needle ? value.toLowerCase().indexOf(needle) : -1;
|
|
19
|
+
return at < 0
|
|
20
|
+
? value
|
|
21
|
+
: value.slice(0, at) +
|
|
22
|
+
painter.gold(value.slice(at, at + needle.length)) +
|
|
23
|
+
value.slice(at + needle.length);
|
|
24
|
+
}
|
|
25
|
+
function renderRow(row, active, query, width, painter, checked) {
|
|
26
|
+
const mark = checked === undefined ? '' : checked ? '[x] ' : '[ ] ';
|
|
27
|
+
const prefix = `${active ? '>' : ' '} ${mark}${row.index + 1}. `;
|
|
28
|
+
const available = width - stringDisplayWidth(prefix);
|
|
29
|
+
const detail = row.detail && stringDisplayWidth(row.detail) + 12 < available ? ` ${row.detail}` : '';
|
|
30
|
+
const label = truncateMiddle(row.label, Math.max(0, available - stringDisplayWidth(detail)));
|
|
31
|
+
const text = paintMatch(label, query, painter);
|
|
32
|
+
return (active ? painter.cyan(prefix) + painter.bold(text) : prefix + text) + painter.dim(detail);
|
|
33
|
+
}
|
|
34
|
+
function cancelled() {
|
|
35
|
+
return new AuthError('已取消设置。', 'USAGE');
|
|
36
|
+
}
|
|
37
|
+
export async function chooseFromPages(prompt, print, title, items) {
|
|
38
|
+
if (!items.length)
|
|
39
|
+
throw new AuthError('当前没有可选择的模型。');
|
|
40
|
+
if (prompt.choose)
|
|
41
|
+
return prompt.choose(title, items);
|
|
42
|
+
return (await chooseNumbered(prompt, print, title, items, false))[0];
|
|
43
|
+
}
|
|
44
|
+
export async function chooseManyFromPages(prompt, print, title, items) {
|
|
45
|
+
if (!items.length)
|
|
46
|
+
throw new AuthError('当前没有可选择的模型。');
|
|
47
|
+
if (prompt.chooseMany)
|
|
48
|
+
return prompt.chooseMany(title, items);
|
|
49
|
+
return chooseNumbered(prompt, print, title, items, true);
|
|
50
|
+
}
|
|
51
|
+
async function chooseNumbered(prompt, print, title, items, multiple) {
|
|
52
|
+
const pageSize = 8;
|
|
53
|
+
const width = process.stdout.columns ? Math.max(8, process.stdout.columns - 1) : 100;
|
|
54
|
+
const painter = createTerminalPainter(false);
|
|
55
|
+
let page = 0;
|
|
56
|
+
let query = '';
|
|
57
|
+
let rows = rowsFor(items, query);
|
|
58
|
+
for (;;) {
|
|
59
|
+
const pages = Math.max(1, Math.ceil(rows.length / pageSize));
|
|
60
|
+
print(titleFor(title, page, pages, width));
|
|
61
|
+
for (const row of rows.slice(page * pageSize, (page + 1) * pageSize))
|
|
62
|
+
print(renderRow(row, false, query, width, painter));
|
|
63
|
+
if (!rows.length)
|
|
64
|
+
print(empty);
|
|
65
|
+
const answer = (await prompt.question(multiple ? '编号(逗号分隔)、n/p 翻页、/搜索、q 取消: ' : '编号、n/p 翻页、/搜索、q 取消: ')).trim();
|
|
66
|
+
if (answer === 'q')
|
|
67
|
+
throw cancelled();
|
|
68
|
+
if (answer.startsWith('/')) {
|
|
69
|
+
query = answer.slice(1);
|
|
70
|
+
rows = rowsFor(items, query);
|
|
71
|
+
page = 0;
|
|
72
|
+
}
|
|
73
|
+
else if (answer === 'n')
|
|
74
|
+
page = Math.min(page + 1, pages - 1);
|
|
75
|
+
else if (answer === 'p')
|
|
76
|
+
page = Math.max(page - 1, 0);
|
|
77
|
+
else {
|
|
78
|
+
const parts = multiple ? answer.split(',').map((part) => part.trim()) : [answer];
|
|
79
|
+
const indexes = parts.map((part) => (/^\d+$/.test(part) ? Number(part) - 1 : -1));
|
|
80
|
+
if (indexes.every((index) => multiple ? index >= 0 && index < items.length : rows.some((row) => row.index === index)))
|
|
81
|
+
return [...new Set(indexes)];
|
|
82
|
+
print('请选择列表中的编号。');
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
export function chooseInTerminal(input, output, title, items, multiple = false) {
|
|
87
|
+
const checked = new Set();
|
|
88
|
+
const painter = createTerminalPainter(Boolean(output.isTTY) && !process.env.NO_COLOR);
|
|
89
|
+
const wasRaw = Boolean(input.isRaw);
|
|
90
|
+
const wasFlowing = input.readableFlowing === true;
|
|
91
|
+
let query = '';
|
|
92
|
+
let search = false;
|
|
93
|
+
let digits = '';
|
|
94
|
+
let feedback = '';
|
|
95
|
+
let active = 0;
|
|
96
|
+
let drawn = 0;
|
|
97
|
+
let rows = rowsFor(items, query);
|
|
98
|
+
const pageSize = () => Math.max(1, Math.min(12, (output.rows || 24) - 5));
|
|
99
|
+
const render = () => {
|
|
100
|
+
if (drawn)
|
|
101
|
+
moveCursor(output, 0, -(drawn - 1));
|
|
102
|
+
cursorTo(output, 0);
|
|
103
|
+
clearScreenDown(output);
|
|
104
|
+
const size = pageSize();
|
|
105
|
+
const page = Math.floor(active / size);
|
|
106
|
+
const width = Math.max(1, (output.columns || 80) - 1);
|
|
107
|
+
const heading = titleFor(title, page, Math.ceil(rows.length / size), width);
|
|
108
|
+
const visible = rows.slice(page * size, (page + 1) * size);
|
|
109
|
+
const multiHint = `空格 勾选 Enter 添加(${checked.size}) ↑↓ 移动 PgUp/PgDn 翻页 / 搜索 Esc 取消`;
|
|
110
|
+
const hint = feedback ||
|
|
111
|
+
(search
|
|
112
|
+
? `搜索 / ${query}${multiple ? ' · Enter 应用' : ''}`
|
|
113
|
+
: digits
|
|
114
|
+
? `编号 ${digits}${multiple ? ' · 空格 勾选' : ''}`
|
|
115
|
+
: multiple
|
|
116
|
+
? multiHint
|
|
117
|
+
: query
|
|
118
|
+
? `筛选 / ${query} · Esc 清除`
|
|
119
|
+
: '↑↓ 移动 PgUp/PgDn 翻页 / 搜索 Enter 确认 Esc 取消');
|
|
120
|
+
const lines = [
|
|
121
|
+
painter.bold(heading),
|
|
122
|
+
...visible.map((row, index) => renderRow(row, page * size + index === active, query, width, painter, multiple ? checked.has(row.index) : undefined)),
|
|
123
|
+
...(!visible.length ? [truncateDisplay(empty, width)] : []),
|
|
124
|
+
painter.dim(truncateDisplay(hint, width)),
|
|
125
|
+
];
|
|
126
|
+
output.write(lines.join('\r\n'));
|
|
127
|
+
drawn = lines.length;
|
|
128
|
+
};
|
|
129
|
+
return new Promise((resolve, reject) => {
|
|
130
|
+
const filter = () => {
|
|
131
|
+
rows = rowsFor(items, query);
|
|
132
|
+
active = 0;
|
|
133
|
+
};
|
|
134
|
+
const finish = (indexes) => {
|
|
135
|
+
input.off('keypress', onKey);
|
|
136
|
+
input.off('end', onEnd);
|
|
137
|
+
output.off('resize', render);
|
|
138
|
+
input.setRawMode(wasRaw);
|
|
139
|
+
if (!wasFlowing)
|
|
140
|
+
input.pause();
|
|
141
|
+
if (drawn)
|
|
142
|
+
moveCursor(output, 0, -(drawn - 1));
|
|
143
|
+
cursorTo(output, 0);
|
|
144
|
+
clearScreenDown(output);
|
|
145
|
+
if (indexes) {
|
|
146
|
+
const width = Math.max(1, (output.columns || 80) - 1);
|
|
147
|
+
const selection = indexes.length === 1 ? items[indexes[0]].label : `已选择 ${indexes.length} 个模型`;
|
|
148
|
+
output.write(truncateMiddle(`> ${selection}`, width) + '\n');
|
|
149
|
+
resolve(indexes);
|
|
150
|
+
}
|
|
151
|
+
else
|
|
152
|
+
reject(cancelled());
|
|
153
|
+
};
|
|
154
|
+
const onEnd = () => finish();
|
|
155
|
+
const currentRow = () => (digits ? rows.find((item) => item.index + 1 === Number(digits)) : rows[active]);
|
|
156
|
+
const onKey = (text, key = {}) => {
|
|
157
|
+
if (key.ctrl && (key.name === 'c' || key.name === 'd'))
|
|
158
|
+
return finish();
|
|
159
|
+
feedback = '';
|
|
160
|
+
if (key.name === 'escape') {
|
|
161
|
+
if (!search && !query && !digits)
|
|
162
|
+
return finish();
|
|
163
|
+
search = false;
|
|
164
|
+
query = '';
|
|
165
|
+
digits = '';
|
|
166
|
+
filter();
|
|
167
|
+
}
|
|
168
|
+
else if (key.name === 'return' || key.name === 'enter') {
|
|
169
|
+
if (multiple) {
|
|
170
|
+
if (search)
|
|
171
|
+
search = false;
|
|
172
|
+
else if (checked.size)
|
|
173
|
+
return finish([...checked]);
|
|
174
|
+
else
|
|
175
|
+
feedback = '先按空格勾选要添加的模型。';
|
|
176
|
+
}
|
|
177
|
+
else {
|
|
178
|
+
const row = currentRow();
|
|
179
|
+
digits = '';
|
|
180
|
+
if (row)
|
|
181
|
+
return finish([row.index]);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
else if (key.name === 'up' ||
|
|
185
|
+
key.name === 'down' ||
|
|
186
|
+
key.name === 'pageup' ||
|
|
187
|
+
key.name === 'pagedown') {
|
|
188
|
+
const step = key.name === 'up' || key.name === 'down' ? 1 : pageSize();
|
|
189
|
+
const direction = key.name === 'up' || key.name === 'pageup' ? -1 : 1;
|
|
190
|
+
active = Math.max(0, Math.min(rows.length - 1, active + direction * step));
|
|
191
|
+
if (multiple)
|
|
192
|
+
search = false;
|
|
193
|
+
digits = '';
|
|
194
|
+
}
|
|
195
|
+
else if (key.name === 'backspace') {
|
|
196
|
+
if (search) {
|
|
197
|
+
query = Array.from(query).slice(0, -1).join('');
|
|
198
|
+
filter();
|
|
199
|
+
}
|
|
200
|
+
else
|
|
201
|
+
digits = digits.slice(0, -1);
|
|
202
|
+
}
|
|
203
|
+
else if (text && !key.ctrl && !key.meta && !/[\x00-\x1f\x7f-\x9f]/.test(text)) {
|
|
204
|
+
if (search) {
|
|
205
|
+
query = (query + text).slice(0, 200);
|
|
206
|
+
filter();
|
|
207
|
+
}
|
|
208
|
+
else if (multiple && text === ' ') {
|
|
209
|
+
const row = currentRow();
|
|
210
|
+
digits = '';
|
|
211
|
+
if (row) {
|
|
212
|
+
active = rows.indexOf(row);
|
|
213
|
+
if (checked.has(row.index))
|
|
214
|
+
checked.delete(row.index);
|
|
215
|
+
else
|
|
216
|
+
checked.add(row.index);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
else if (text === '/') {
|
|
220
|
+
search = true;
|
|
221
|
+
digits = '';
|
|
222
|
+
}
|
|
223
|
+
else if (/^\d$/.test(text))
|
|
224
|
+
digits = (digits + text).slice(0, 9);
|
|
225
|
+
}
|
|
226
|
+
else
|
|
227
|
+
return;
|
|
228
|
+
render();
|
|
229
|
+
};
|
|
230
|
+
emitKeypressEvents(input);
|
|
231
|
+
input.setRawMode(true);
|
|
232
|
+
input.on('keypress', onKey);
|
|
233
|
+
input.once('end', onEnd);
|
|
234
|
+
output.on('resize', render);
|
|
235
|
+
input.resume();
|
|
236
|
+
render();
|
|
237
|
+
});
|
|
238
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
export interface CliDiagnostic {
|
|
2
|
+
readonly code: string;
|
|
3
|
+
readonly diagnosticId: string;
|
|
4
|
+
readonly retryable?: boolean;
|
|
5
|
+
}
|
|
6
|
+
export declare class CliError extends Error implements CliDiagnostic {
|
|
7
|
+
readonly code: string;
|
|
8
|
+
readonly diagnosticId: string;
|
|
9
|
+
readonly retryable: boolean;
|
|
10
|
+
constructor(code: string, diagnosticId?: string, retryable?: boolean);
|
|
11
|
+
}
|
|
12
|
+
export declare class UsageError extends CliError {
|
|
13
|
+
readonly detail: string;
|
|
14
|
+
constructor(detail: string);
|
|
15
|
+
}
|
|
16
|
+
export declare class AuthError extends CliError {
|
|
17
|
+
readonly detail: string;
|
|
18
|
+
constructor(detail: string, code?: string);
|
|
19
|
+
}
|
|
20
|
+
export declare function safeCode(value: string): string;
|
|
21
|
+
export declare function formatDiagnosticReference(error: CliDiagnostic): string;
|
|
22
|
+
export declare function isHostConnectionError(code: string): boolean;
|
|
23
|
+
export declare function exitCode(code: string): number;
|