@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/index.js
ADDED
|
@@ -0,0 +1,400 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { spawn } from 'node:child_process';
|
|
3
|
+
import http from 'node:http';
|
|
4
|
+
import { parseArgs } from 'node:util';
|
|
5
|
+
import { contextExtensionRefPattern, modeSelectorPattern } from '@saturn-universe/protocol';
|
|
6
|
+
import { workspaceRoot } from './client.js';
|
|
7
|
+
import { AuthError, CliError, UsageError, exitCode, formatDiagnosticReference } from './cli-diagnostics.js';
|
|
8
|
+
import { argumentsFor, execute, knownSubcommands } from './commands.js';
|
|
9
|
+
import { helpTarget, requestedHelp } from './cli-help.js';
|
|
10
|
+
import { attach } from './attach.js';
|
|
11
|
+
import { sendHostCommand } from './host-command.js';
|
|
12
|
+
import { buildHostSpawnEnv, ensureHost, resolveHostEntry, shouldEnableEnvProxy } from './host-launcher.js';
|
|
13
|
+
import { renderModelFailure } from './renderer.js';
|
|
14
|
+
import { runConfigCommand } from './config-cli.js';
|
|
15
|
+
import { startRepl } from './repl.js';
|
|
16
|
+
import { inspectUserConfig } from './user-config.js';
|
|
17
|
+
const argv = process.argv.slice(2);
|
|
18
|
+
if (argv[0] === '--json' && argv.length > 1)
|
|
19
|
+
argv.push(argv.shift());
|
|
20
|
+
const json = argv.includes('--json');
|
|
21
|
+
async function executeProvider(args, root) {
|
|
22
|
+
const { runProviderCommand } = await import('./provider.js');
|
|
23
|
+
await runProviderCommand(args, root === undefined ? {} : { root });
|
|
24
|
+
}
|
|
25
|
+
async function main() {
|
|
26
|
+
if (shouldEnableEnvProxy(process.env) &&
|
|
27
|
+
'setGlobalProxyFromEnv' in http &&
|
|
28
|
+
typeof http.setGlobalProxyFromEnv === 'function') {
|
|
29
|
+
http.setGlobalProxyFromEnv();
|
|
30
|
+
}
|
|
31
|
+
const head = argv[0];
|
|
32
|
+
const help = requestedHelp(stripWorkspaceFlag(argv).rest);
|
|
33
|
+
if (help !== undefined) {
|
|
34
|
+
output({ ok: true, result: { help } });
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
if (head === 'auth')
|
|
38
|
+
throw new AuthError('设置 AI 服务请运行 saturn provider add。', 'USAGE');
|
|
39
|
+
if (head === 'run' || head === 'session')
|
|
40
|
+
return runFlagFirst(argv);
|
|
41
|
+
if (argv[0] === 'host') {
|
|
42
|
+
await runHostProcess(argv.slice(1));
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
if (argv[0] === 'provider') {
|
|
46
|
+
await executeProvider(argv.slice(1));
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
if (argv[0] === 'config') {
|
|
50
|
+
await runFlagFirst(argv);
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
if (argv[0] === 'skill' || argv[0] === 'mcp' || argv[0] === 'sandbox') {
|
|
54
|
+
await runFlagFirst(argv);
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
if (argv.length === 0 || argv[0].startsWith('-')) {
|
|
58
|
+
await runFlagFirst(argv);
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
if (knownSubcommands.has(argv[0])) {
|
|
62
|
+
const root = await workspaceRoot(process.cwd());
|
|
63
|
+
await runSubcommand(root, argv);
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
await runSubcommand(await workspaceRoot(argv[0]), argv.slice(1));
|
|
67
|
+
}
|
|
68
|
+
function hasPositionalHostRoot(args) {
|
|
69
|
+
for (let i = 0; i < args.length; i++) {
|
|
70
|
+
const arg = args[i];
|
|
71
|
+
if (arg === '--allow-unsafe-sandbox-fallback')
|
|
72
|
+
continue;
|
|
73
|
+
if (['--config', '--profile', '--task-profile', '--mode'].includes(arg))
|
|
74
|
+
i++;
|
|
75
|
+
else if (!arg.startsWith('-'))
|
|
76
|
+
return true;
|
|
77
|
+
}
|
|
78
|
+
return false;
|
|
79
|
+
}
|
|
80
|
+
async function runHostProcess(hostArgs) {
|
|
81
|
+
const hostEntry = await resolveHostEntry();
|
|
82
|
+
const resolvedArgs = hasPositionalHostRoot(hostArgs)
|
|
83
|
+
? hostArgs
|
|
84
|
+
: [await workspaceRoot(process.cwd()), ...hostArgs];
|
|
85
|
+
const child = spawn(process.execPath, [hostEntry, ...resolvedArgs], {
|
|
86
|
+
stdio: 'inherit',
|
|
87
|
+
windowsHide: true,
|
|
88
|
+
env: buildHostSpawnEnv(process.env),
|
|
89
|
+
});
|
|
90
|
+
await new Promise((resolve, reject) => {
|
|
91
|
+
child.once('error', () => reject(new CliError('HOST_UNAVAILABLE')));
|
|
92
|
+
child.once('close', (code) => {
|
|
93
|
+
if (code !== null && code !== 0)
|
|
94
|
+
process.exitCode = code;
|
|
95
|
+
resolve();
|
|
96
|
+
});
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
function stripWorkspaceFlag(args) {
|
|
100
|
+
const rest = [];
|
|
101
|
+
let workspace;
|
|
102
|
+
for (let i = 0; i < args.length; i++) {
|
|
103
|
+
const arg = args[i];
|
|
104
|
+
if (arg === '--') {
|
|
105
|
+
rest.push(...args.slice(i));
|
|
106
|
+
break;
|
|
107
|
+
}
|
|
108
|
+
if (arg === '--workspace' || arg === '-C') {
|
|
109
|
+
const value = args[++i];
|
|
110
|
+
if (!value || value.startsWith('-'))
|
|
111
|
+
throw new CliError('USAGE');
|
|
112
|
+
workspace = value;
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
if (arg.startsWith('--workspace=')) {
|
|
116
|
+
workspace = arg.slice('--workspace='.length);
|
|
117
|
+
if (!workspace)
|
|
118
|
+
throw new CliError('USAGE');
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
rest.push(arg);
|
|
122
|
+
}
|
|
123
|
+
return { ...(workspace !== undefined ? { workspace } : {}), rest };
|
|
124
|
+
}
|
|
125
|
+
async function runFlagFirst(args) {
|
|
126
|
+
const stripped = stripWorkspaceFlag(args);
|
|
127
|
+
const [group, action, ...tail] = stripped.rest;
|
|
128
|
+
const rootForGroup = () => workspaceRoot(stripped.workspace ?? process.cwd());
|
|
129
|
+
const tty = process.stdin.isTTY && process.stdout.isTTY && !json;
|
|
130
|
+
if ((group === 'run' || group === 'session') && (!action || action === 'list' || action === '--json')) {
|
|
131
|
+
if (tail.some((arg) => arg !== '--json'))
|
|
132
|
+
throw new CliError('USAGE');
|
|
133
|
+
const root = await rootForGroup();
|
|
134
|
+
const workspaces = await sendHostCommand(root, { type: 'workspace.query' });
|
|
135
|
+
const sessions = workspaces[0]
|
|
136
|
+
? await sendHostCommand(root, { type: 'session.list', workspaceId: workspaces[0].id, limit: 50 })
|
|
137
|
+
: [];
|
|
138
|
+
const items = group === 'session'
|
|
139
|
+
? sessions
|
|
140
|
+
: sessions
|
|
141
|
+
.filter((s) => s.latestRunId)
|
|
142
|
+
.map((s) => ({ id: s.latestRunId, title: s.title, status: s.latestRunStatus }));
|
|
143
|
+
if (json)
|
|
144
|
+
process.stdout.write(JSON.stringify({ ok: true, result: items }) + '\n');
|
|
145
|
+
else {
|
|
146
|
+
for (const item of items)
|
|
147
|
+
process.stdout.write(item.title.replace(/[\x00-\x1f\x7f-\x9f]/g, ' ') + ' · ' + item.status + ' · ' + item.id + '\n');
|
|
148
|
+
if (!items.length)
|
|
149
|
+
process.stdout.write('当前工作区还没有记录。\n');
|
|
150
|
+
if (group === 'session' && tty && !action) {
|
|
151
|
+
const { pickAction } = await import('./menu.js');
|
|
152
|
+
const selected = await pickAction('打开对话', ['新建对话', ...sessions.map((s) => s.title), '返回']);
|
|
153
|
+
if (selected === 0)
|
|
154
|
+
return startRepl({ workdir: root });
|
|
155
|
+
const session = sessions[selected - 1];
|
|
156
|
+
if (session)
|
|
157
|
+
return startRepl({ workdir: root, sessionId: session.id });
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
if (group === 'session' && action === 'new')
|
|
163
|
+
return runSubcommand(await rootForGroup(), ['session', ...tail]);
|
|
164
|
+
if (group === 'run' && action && ['show', 'attach', 'cancel', 'wait'].includes(action))
|
|
165
|
+
return runSubcommand(await rootForGroup(), [action === 'show' ? 'query' : action, ...tail]);
|
|
166
|
+
if (group && ['config', 'mcp', 'skill', 'sandbox'].includes(group) && !action && tty) {
|
|
167
|
+
const { manageSettings } = await import('./settings-menu.js');
|
|
168
|
+
await manageSettings(group, await rootForGroup());
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
if (stripped.rest.length > 0 && knownSubcommands.has(stripped.rest[0])) {
|
|
172
|
+
const root = await workspaceRoot(stripped.workspace ?? process.cwd());
|
|
173
|
+
await runSubcommand(root, stripped.rest);
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
if (stripped.rest[0] === 'provider') {
|
|
177
|
+
await executeProvider(stripped.rest.slice(1), stripped.workspace);
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
if (stripped.rest.length > 0 && stripped.rest[0] === 'config') {
|
|
181
|
+
await runConfigCommand([
|
|
182
|
+
...stripped.rest.slice(1),
|
|
183
|
+
...(stripped.workspace ? ['--workspace', stripped.workspace] : []),
|
|
184
|
+
]);
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
if (stripped.rest[0] === 'skill') {
|
|
188
|
+
const root = await workspaceRoot(stripped.workspace ?? process.cwd());
|
|
189
|
+
const { runSkillCommand } = await import('./skill-cli.js');
|
|
190
|
+
await runSkillCommand(action === '--json' ? ['list', ...stripped.rest.slice(1)] : stripped.rest.slice(1), root);
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
if (stripped.rest[0] === 'mcp') {
|
|
194
|
+
const root = await workspaceRoot(stripped.workspace ?? process.cwd());
|
|
195
|
+
const { runMcpCommand } = await import('./mcp-cli.js');
|
|
196
|
+
await runMcpCommand(action === '--json' ? ['list', ...stripped.rest.slice(1)] : stripped.rest.slice(1), root);
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
if (stripped.rest[0] === 'sandbox') {
|
|
200
|
+
const root = await workspaceRoot(stripped.workspace ?? process.cwd());
|
|
201
|
+
const { runSandboxCommand } = await import('./sandbox-cli.js');
|
|
202
|
+
await runSandboxCommand(stripped.rest.slice(1), root);
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
let parsed;
|
|
206
|
+
try {
|
|
207
|
+
parsed = parseArgs({
|
|
208
|
+
args,
|
|
209
|
+
allowPositionals: true,
|
|
210
|
+
strict: true,
|
|
211
|
+
options: {
|
|
212
|
+
workspace: { type: 'string', short: 'C' },
|
|
213
|
+
profile: { type: 'string' },
|
|
214
|
+
'task-profile': { type: 'string' },
|
|
215
|
+
mode: { type: 'string' },
|
|
216
|
+
skill: { type: 'string', multiple: true },
|
|
217
|
+
config: { type: 'string' },
|
|
218
|
+
session: { type: 'string' },
|
|
219
|
+
'allow-unsafe-sandbox-fallback': { type: 'boolean' },
|
|
220
|
+
},
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
catch {
|
|
224
|
+
throw new CliError('USAGE');
|
|
225
|
+
}
|
|
226
|
+
if (parsed.positionals.length)
|
|
227
|
+
throw new CliError('USAGE');
|
|
228
|
+
const values = parsed.values;
|
|
229
|
+
const modeRef = typeof values.mode === 'string' ? values.mode : undefined;
|
|
230
|
+
const skillRefs = Array.isArray(values.skill) ? values.skill : undefined;
|
|
231
|
+
if ((modeRef !== undefined && !modeSelectorPattern.test(modeRef)) ||
|
|
232
|
+
skillRefs?.some((ref) => !contextExtensionRefPattern.test(ref)))
|
|
233
|
+
throw new CliError('USAGE');
|
|
234
|
+
const workdir = await workspaceRoot(typeof values.workspace === 'string' ? values.workspace : process.cwd());
|
|
235
|
+
if (tty && stripped.rest.length === 0) {
|
|
236
|
+
const inspection = await inspectUserConfig(workdir);
|
|
237
|
+
if (!inspection.files.workspaceConfig.exists) {
|
|
238
|
+
const { listProviderLogins } = await import('./auth-config.js');
|
|
239
|
+
const models = await listProviderLogins(process.env, workdir);
|
|
240
|
+
if (!models.some((m) => m.selected && m.supported && m.configured)) {
|
|
241
|
+
const { pickAction } = await import('./menu.js');
|
|
242
|
+
if ((await pickAction('尚未设置可用的 AI 服务。', ['现在设置', '暂时跳过'])) === 0)
|
|
243
|
+
await executeProvider(['add'], workdir);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
await startRepl({
|
|
248
|
+
workdir,
|
|
249
|
+
...(typeof values.config === 'string' ? { config: values.config } : {}),
|
|
250
|
+
...(typeof values.profile === 'string' ? { profile: values.profile } : {}),
|
|
251
|
+
...(typeof values['task-profile'] === 'string' ? { taskProfile: values['task-profile'] } : {}),
|
|
252
|
+
...(modeRef ? { modeRef } : {}),
|
|
253
|
+
...(skillRefs ? { skillRefs } : {}),
|
|
254
|
+
...(typeof values.session === 'string' ? { sessionId: values.session } : {}),
|
|
255
|
+
...(values['allow-unsafe-sandbox-fallback'] ? { allowUnsafeSandboxFallback: true } : {}),
|
|
256
|
+
});
|
|
257
|
+
}
|
|
258
|
+
async function runSubcommand(root, subArgv) {
|
|
259
|
+
const args = argumentsFor(subArgv);
|
|
260
|
+
if (args.values['start-host'] && args.name !== 'help' && args.name !== 'shutdown') {
|
|
261
|
+
await ensureHost(root, {
|
|
262
|
+
detach: true,
|
|
263
|
+
...(args.values.mode ? { mode: String(args.values.mode) } : {}),
|
|
264
|
+
...(args.values['allow-unsafe-sandbox-fallback'] ? { allowUnsafeSandboxFallback: true } : {}),
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
if (args.name !== 'attach' && args.name !== 'wait') {
|
|
268
|
+
const result = await execute(root, args);
|
|
269
|
+
output({ ok: true, commandId: args.commandId, result });
|
|
270
|
+
if (['query', 'refresh', 'progress'].includes(args.name))
|
|
271
|
+
runExit(result);
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
const stop = new AbortController();
|
|
275
|
+
const detach = () => stop.abort();
|
|
276
|
+
process.once('SIGINT', detach);
|
|
277
|
+
process.once('SIGTERM', detach);
|
|
278
|
+
try {
|
|
279
|
+
const result = await attach(root, args, (frame) => {
|
|
280
|
+
if (args.name === 'attach' || !frame.ok)
|
|
281
|
+
output(frame);
|
|
282
|
+
}, stop.signal);
|
|
283
|
+
if (result.detached) {
|
|
284
|
+
output({ ok: true, type: 'detached', result: { runId: args.runId, cursor: result.cursor } });
|
|
285
|
+
process.exitCode = 130;
|
|
286
|
+
}
|
|
287
|
+
else {
|
|
288
|
+
if (args.name === 'wait')
|
|
289
|
+
output({ ok: true, result: { runId: args.runId, ...result } });
|
|
290
|
+
runExit(result);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
finally {
|
|
294
|
+
process.off('SIGINT', detach);
|
|
295
|
+
process.off('SIGTERM', detach);
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
function output(value) {
|
|
299
|
+
if (json) {
|
|
300
|
+
process.stdout.write(JSON.stringify(value) + '\n');
|
|
301
|
+
return;
|
|
302
|
+
}
|
|
303
|
+
if (!value.ok) {
|
|
304
|
+
process.stderr.write(formatDiagnosticReference(value.error) + '\n');
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
const result = value.result;
|
|
308
|
+
if (result.help) {
|
|
309
|
+
process.stdout.write(result.help + '\n');
|
|
310
|
+
return;
|
|
311
|
+
}
|
|
312
|
+
if (value.commandId)
|
|
313
|
+
process.stdout.write('commandId=' + value.commandId + '\n');
|
|
314
|
+
if (result.runId)
|
|
315
|
+
process.stdout.write('Run ' + result.runId + (result.status ? ' ' + result.status : '') + '\n');
|
|
316
|
+
if (result.sessionId)
|
|
317
|
+
process.stdout.write('Session ' + result.sessionId + '\n');
|
|
318
|
+
if (result.workspaceId)
|
|
319
|
+
process.stdout.write('Workspace ' + result.workspaceId + '\n');
|
|
320
|
+
if (result.cursor !== undefined)
|
|
321
|
+
process.stdout.write('cursor=' + result.cursor + '\n');
|
|
322
|
+
if (result.compactionId)
|
|
323
|
+
process.stdout.write('Compaction ' + result.compactionId + ' replaced=' + result.replacedCount + '\n');
|
|
324
|
+
if (result.pauseReason)
|
|
325
|
+
process.stdout.write('Paused: ' + result.pauseReason + '\n');
|
|
326
|
+
if (result.error)
|
|
327
|
+
process.stderr.write(formatDiagnosticReference(result.error) + '\n');
|
|
328
|
+
for (const turn of result.turns ?? [])
|
|
329
|
+
process.stdout.write('Turn ' + turn.id + ' ' + turn.status + '\n');
|
|
330
|
+
for (const step of result.steps ?? [])
|
|
331
|
+
process.stdout.write('Step ' + step.id + ' ' + step.kind + ' ' + step.status + '\n');
|
|
332
|
+
if (result.plan) {
|
|
333
|
+
process.stdout.write(`Plan ${result.plan.decision} reason=${result.plan.reason}\n`);
|
|
334
|
+
if (result.plan.summary)
|
|
335
|
+
process.stdout.write(`Summary: ${result.plan.summary}\n`);
|
|
336
|
+
}
|
|
337
|
+
if (result.concurrency !== undefined)
|
|
338
|
+
process.stdout.write('Team concurrency=' + result.concurrency + '\n');
|
|
339
|
+
for (const member of result.members ?? [])
|
|
340
|
+
process.stdout.write(`Agent ${member.id} ${member.status} session=${member.agentSessionId}${member.parent ? ` parent=${member.parent}` : ''}\n`);
|
|
341
|
+
for (const task of result.tasks ?? [])
|
|
342
|
+
process.stdout.write(`Task ${task.memberId} ${task.status}\n${task.task}\n`);
|
|
343
|
+
for (const message of result.inbox ?? [])
|
|
344
|
+
process.stdout.write(`Report ${message.from} -> ${message.to} ${message.readAt ? 'read' : 'unread'} ${message.sentAt}\n${message.text}\n`);
|
|
345
|
+
for (const tool of result.tools ?? []) {
|
|
346
|
+
process.stdout.write('Tool ' + tool.call.id + ' ' + tool.call.toolName + ' ' + tool.status + '\n');
|
|
347
|
+
if (tool.approval?.status === 'pending')
|
|
348
|
+
process.stdout.write('Approval ' + tool.approval.request.approvalId + ' toolCallId=' + tool.call.id + ' pending\n');
|
|
349
|
+
}
|
|
350
|
+
for (const event of result.events ?? []) {
|
|
351
|
+
if (event.type === 'model.failed' && event.error) {
|
|
352
|
+
process.stdout.write(`${event.position} ${event.type} ${renderModelFailure(event)}\n`);
|
|
353
|
+
continue;
|
|
354
|
+
}
|
|
355
|
+
process.stdout.write(event.position + ' ' + event.type + (event.text ? '\n' + event.text : '') + '\n');
|
|
356
|
+
if (event.type === 'run.team.planned' && event.decision)
|
|
357
|
+
process.stdout.write(`Plan ${event.decision} reason=${event.reason ?? ''}\n`);
|
|
358
|
+
if (event.type === 'run.team.message.sent' && event.from && event.to)
|
|
359
|
+
process.stdout.write(`Report ${event.from} -> ${event.to}\n${event.text ?? ''}\n`);
|
|
360
|
+
if (event.approval)
|
|
361
|
+
process.stdout.write('Approval ' + event.approval.approvalId + ' toolCallId=' + event.approval.toolCallId + ' pending\n');
|
|
362
|
+
if (event.error)
|
|
363
|
+
process.stderr.write(formatDiagnosticReference(event.error) + '\n');
|
|
364
|
+
}
|
|
365
|
+
if (result.epoch)
|
|
366
|
+
process.stdout.write('Host epoch=' + result.epoch + '\n');
|
|
367
|
+
if (result.stopping)
|
|
368
|
+
process.stdout.write('Host stopping\n');
|
|
369
|
+
}
|
|
370
|
+
function runExit(result) {
|
|
371
|
+
if (result.status === 'failed')
|
|
372
|
+
process.exitCode = 4;
|
|
373
|
+
if (result.status === 'cancelled')
|
|
374
|
+
process.exitCode = 5;
|
|
375
|
+
}
|
|
376
|
+
function errorValue(error) {
|
|
377
|
+
return { code: error.code, diagnosticId: error.diagnosticId, retryable: error.retryable };
|
|
378
|
+
}
|
|
379
|
+
main().catch((error) => {
|
|
380
|
+
const safe = error instanceof CliError ? error : new CliError('INVALID_COMMAND');
|
|
381
|
+
if (json)
|
|
382
|
+
output({ ok: false, error: errorValue(safe) });
|
|
383
|
+
else if (error instanceof AuthError || error instanceof UsageError)
|
|
384
|
+
process.stderr.write(error.detail + '\n');
|
|
385
|
+
else if (safe.code === 'USAGE') {
|
|
386
|
+
let target = [];
|
|
387
|
+
try {
|
|
388
|
+
target = helpTarget(stripWorkspaceFlag(argv).rest);
|
|
389
|
+
}
|
|
390
|
+
catch {
|
|
391
|
+
// An invalid workspace argument can prevent command lookup.
|
|
392
|
+
}
|
|
393
|
+
process.stderr.write(`参数无法识别。运行 saturn ${[...target, '--help'].join(' ')} 查看用法。\n`);
|
|
394
|
+
}
|
|
395
|
+
else if (safe.code === 'HOST_UNAVAILABLE')
|
|
396
|
+
process.stderr.write('当前工作区尚未连接。运行 saturn 打开工作台后重试。\n');
|
|
397
|
+
else
|
|
398
|
+
output({ ok: false, error: errorValue(safe) });
|
|
399
|
+
process.exitCode = exitCode(safe.code);
|
|
400
|
+
});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function renderMarkdown(text: string, width: number, color: boolean, softWraps?: Set<number>): string[];
|
package/dist/markdown.js
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { fromMarkdown } from 'mdast-util-from-markdown';
|
|
2
|
+
import { gfmFromMarkdown } from 'mdast-util-gfm';
|
|
3
|
+
import { gfm } from 'micromark-extension-gfm';
|
|
4
|
+
import { paintSgr, stringDisplayWidth, stripAnsi, wrapDisplayRanges, wrapTextByWidth, } from './terminal-text.js';
|
|
5
|
+
const syntax = { extensions: [gfm()], mdastExtensions: [gfmFromMarkdown()] };
|
|
6
|
+
const clean = (text) => stripAnsi(text).replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g, '');
|
|
7
|
+
function inline(node, style = '') {
|
|
8
|
+
switch (node.type) {
|
|
9
|
+
case 'strong':
|
|
10
|
+
case 'emphasis':
|
|
11
|
+
case 'delete':
|
|
12
|
+
case 'link':
|
|
13
|
+
case 'linkReference': {
|
|
14
|
+
const code = { strong: '1', emphasis: '3', delete: '9', link: '4;36', linkReference: '4;36' }[node.type];
|
|
15
|
+
return node.children?.flatMap((child) => inline(child, style ? style + ';' + code : code)) ?? [];
|
|
16
|
+
}
|
|
17
|
+
case 'inlineCode':
|
|
18
|
+
return [{ text: node.value ?? '', style: '33' }];
|
|
19
|
+
case 'break':
|
|
20
|
+
return [{ text: '\n', style }];
|
|
21
|
+
case 'image':
|
|
22
|
+
case 'imageReference':
|
|
23
|
+
return [{ text: node.alt ?? '', style: '2' }];
|
|
24
|
+
default:
|
|
25
|
+
return node.children?.flatMap((child) => inline(child, style)) ?? [{ text: node.value ?? '', style }];
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
const span = (text, style = '') => ({ text, style });
|
|
29
|
+
function blocks(node, width) {
|
|
30
|
+
switch (node.type) {
|
|
31
|
+
case 'heading':
|
|
32
|
+
return [inline(node, '1;36')];
|
|
33
|
+
case 'paragraph':
|
|
34
|
+
return [inline(node)];
|
|
35
|
+
case 'code':
|
|
36
|
+
return [
|
|
37
|
+
...(node.lang ? [[span(node.lang, '2;33')]] : []),
|
|
38
|
+
...(node.value ?? '').split('\n').map((line) => [span(line, '33')]),
|
|
39
|
+
];
|
|
40
|
+
case 'blockquote':
|
|
41
|
+
return (node.children ?? []).flatMap((child) => blocks(child, width).map((line) => [span('│ ', '36'), ...line]));
|
|
42
|
+
case 'list':
|
|
43
|
+
return (node.children ?? []).flatMap((item, index) => {
|
|
44
|
+
const prefix = typeof item.checked === 'boolean'
|
|
45
|
+
? item.checked
|
|
46
|
+
? '☑ '
|
|
47
|
+
: '☐ '
|
|
48
|
+
: node.ordered
|
|
49
|
+
? String((node.start ?? 1) + index) + '. '
|
|
50
|
+
: '• ';
|
|
51
|
+
return (item.children ?? [])
|
|
52
|
+
.flatMap((child) => blocks(child, width))
|
|
53
|
+
.map((line, row) => [span(row === 0 ? prefix : ' '.repeat(prefix.length), '36'), ...line]);
|
|
54
|
+
});
|
|
55
|
+
case 'table': {
|
|
56
|
+
const rows = (node.children ?? []).map((row) => (row.children ?? []).map((cell) => inline(cell)
|
|
57
|
+
.map(({ text }) => clean(text))
|
|
58
|
+
.join('')
|
|
59
|
+
.replace(/\n/g, ' ')));
|
|
60
|
+
const count = Math.max(1, ...rows.map((row) => row.length));
|
|
61
|
+
if (width < count * 5)
|
|
62
|
+
return rows.map((row, i) => [span(row.join(' │ '), i === 0 ? '1;36' : '')]);
|
|
63
|
+
const available = Math.floor((width - (count - 1) * 3) / count);
|
|
64
|
+
const widths = Array.from({ length: count }, (_, col) => Math.min(available, Math.max(2, ...rows.map((row) => stringDisplayWidth(row[col] ?? '')))));
|
|
65
|
+
return rows.flatMap((row, i) => {
|
|
66
|
+
const cells = widths.map((cellWidth, col) => wrapTextByWidth(row[col] ?? '', cellWidth));
|
|
67
|
+
return Array.from({ length: Math.max(...cells.map((cell) => cell.length)) }, (_, y) => [
|
|
68
|
+
span(cells
|
|
69
|
+
.map((cell, col) => {
|
|
70
|
+
const value = cell[y] ?? '';
|
|
71
|
+
return value + ' '.repeat(Math.max(0, widths[col] - stringDisplayWidth(value)));
|
|
72
|
+
})
|
|
73
|
+
.join(' │ '), i === 0 ? '1;36' : ''),
|
|
74
|
+
]);
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
case 'definition':
|
|
78
|
+
return [];
|
|
79
|
+
case 'thematicBreak':
|
|
80
|
+
return [[span('─'.repeat(Math.min(12, width)), '2')]];
|
|
81
|
+
default:
|
|
82
|
+
return [inline(node)];
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
function appendStyledRows(line, width, color, rows, softWraps) {
|
|
86
|
+
const spans = line.map(({ text, style }) => ({ text: clean(text), style }));
|
|
87
|
+
const visible = spans.map(({ text }) => text).join('');
|
|
88
|
+
let spanIndex = 0;
|
|
89
|
+
let spanStart = 0;
|
|
90
|
+
for (const { start, end, soft } of wrapDisplayRanges(visible, width)) {
|
|
91
|
+
let row = '';
|
|
92
|
+
for (; spanIndex < spans.length && spanStart < end; spanIndex++) {
|
|
93
|
+
const { text, style } = spans[spanIndex];
|
|
94
|
+
const fragment = text.slice(Math.max(0, start - spanStart), end - spanStart);
|
|
95
|
+
if (fragment)
|
|
96
|
+
row += style ? paintSgr(style, fragment, color) : fragment;
|
|
97
|
+
const spanEnd = spanStart + text.length;
|
|
98
|
+
if (spanEnd > end)
|
|
99
|
+
break;
|
|
100
|
+
spanStart = spanEnd;
|
|
101
|
+
}
|
|
102
|
+
if (soft)
|
|
103
|
+
softWraps?.add(rows.length);
|
|
104
|
+
rows.push(row);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
export function renderMarkdown(text, width, color, softWraps) {
|
|
108
|
+
const root = fromMarkdown(text, syntax);
|
|
109
|
+
const result = [];
|
|
110
|
+
for (const child of root.children) {
|
|
111
|
+
const lines = blocks(child, width);
|
|
112
|
+
if (lines.length && result.length)
|
|
113
|
+
result.push('');
|
|
114
|
+
for (const line of lines)
|
|
115
|
+
appendStyledRows(line, width, color, result, softWraps);
|
|
116
|
+
}
|
|
117
|
+
return result;
|
|
118
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { HostStatusSnapshot, NormalizedMcpServerConfig } from '@saturn-universe/protocol';
|
|
2
|
+
export type McpScope = 'user' | 'project';
|
|
3
|
+
export interface ConfiguredMcpServerRecord {
|
|
4
|
+
readonly id: string;
|
|
5
|
+
readonly scope: McpScope | 'workspace';
|
|
6
|
+
readonly source: string;
|
|
7
|
+
readonly config: NormalizedMcpServerConfig;
|
|
8
|
+
readonly trusted: boolean;
|
|
9
|
+
readonly status: string;
|
|
10
|
+
readonly toolCount?: number;
|
|
11
|
+
readonly error?: string;
|
|
12
|
+
}
|
|
13
|
+
export declare function addMcpServerConfig(workdir: string, name: string, entry: NormalizedMcpServerConfig, scope?: McpScope, env?: NodeJS.ProcessEnv): Promise<{
|
|
14
|
+
readonly name: string;
|
|
15
|
+
readonly scope: McpScope;
|
|
16
|
+
readonly path: string;
|
|
17
|
+
}>;
|
|
18
|
+
export declare function removeMcpServerConfig(workdir: string, name: string, scope?: McpScope, env?: NodeJS.ProcessEnv): Promise<{
|
|
19
|
+
readonly name: string;
|
|
20
|
+
readonly scope: McpScope;
|
|
21
|
+
readonly path: string;
|
|
22
|
+
}>;
|
|
23
|
+
export declare function setWorkspaceMcpTrust(workdir: string, trusted: boolean, env?: NodeJS.ProcessEnv): Promise<{
|
|
24
|
+
readonly workspace: string;
|
|
25
|
+
readonly trusted: boolean;
|
|
26
|
+
readonly configPath: string;
|
|
27
|
+
}>;
|
|
28
|
+
export declare function listMcpServersInfo(workdir: string, liveStatus?: HostStatusSnapshot, env?: NodeJS.ProcessEnv): Promise<{
|
|
29
|
+
readonly servers: readonly ConfiguredMcpServerRecord[];
|
|
30
|
+
readonly workspaceTrusted: boolean;
|
|
31
|
+
readonly mcpJsonError?: string;
|
|
32
|
+
}>;
|
|
33
|
+
export declare function formatMcpServerStatus(srv: ConfiguredMcpServerRecord): string;
|
|
34
|
+
export declare function promptMcpSecret(label: string): Promise<string>;
|
|
35
|
+
export declare function authenticateMcpServer(workdir: string, args: readonly string[], options: {
|
|
36
|
+
readonly prompt: (label: string) => Promise<string | null>;
|
|
37
|
+
readonly before?: HostStatusSnapshot;
|
|
38
|
+
readonly restart: () => Promise<HostStatusSnapshot>;
|
|
39
|
+
readonly env?: NodeJS.ProcessEnv;
|
|
40
|
+
}): Promise<{
|
|
41
|
+
readonly server: ConfiguredMcpServerRecord;
|
|
42
|
+
readonly json: boolean;
|
|
43
|
+
} | null>;
|
|
44
|
+
export declare function runMcpCommand(args: readonly string[], workdir: string, env?: NodeJS.ProcessEnv): Promise<void>;
|