@saturn-universe/cli 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/LICENSE +661 -0
  2. package/dist/attach.d.ts +9 -0
  3. package/dist/attach.js +80 -0
  4. package/dist/auth-config.d.ts +31 -0
  5. package/dist/auth-config.js +285 -0
  6. package/dist/choice-menu.d.ts +13 -0
  7. package/dist/choice-menu.js +238 -0
  8. package/dist/cli-diagnostics.d.ts +23 -0
  9. package/dist/cli-diagnostics.js +42 -0
  10. package/dist/cli-help.d.ts +6 -0
  11. package/dist/cli-help.js +163 -0
  12. package/dist/client.d.ts +13 -0
  13. package/dist/client.js +90 -0
  14. package/dist/commands.d.ts +64 -0
  15. package/dist/commands.js +299 -0
  16. package/dist/compaction-command.d.ts +16 -0
  17. package/dist/compaction-command.js +16 -0
  18. package/dist/composer.d.ts +88 -0
  19. package/dist/composer.js +124 -0
  20. package/dist/config-cli.d.ts +1 -0
  21. package/dist/config-cli.js +47 -0
  22. package/dist/config-file.d.ts +1 -0
  23. package/dist/config-file.js +43 -0
  24. package/dist/config-lock.d.ts +5 -0
  25. package/dist/config-lock.js +45 -0
  26. package/dist/duration.d.ts +2 -0
  27. package/dist/duration.js +11 -0
  28. package/dist/export.d.ts +19 -0
  29. package/dist/export.js +66 -0
  30. package/dist/host-command.d.ts +40 -0
  31. package/dist/host-command.js +48 -0
  32. package/dist/host-launcher.d.ts +22 -0
  33. package/dist/host-launcher.js +300 -0
  34. package/dist/index.d.ts +2 -0
  35. package/dist/index.js +400 -0
  36. package/dist/markdown.d.ts +1 -0
  37. package/dist/markdown.js +118 -0
  38. package/dist/mcp-cli.d.ts +44 -0
  39. package/dist/mcp-cli.js +647 -0
  40. package/dist/menu.d.ts +7 -0
  41. package/dist/menu.js +91 -0
  42. package/dist/project-mcp-config.d.ts +9 -0
  43. package/dist/project-mcp-config.js +98 -0
  44. package/dist/provider-discovery.d.ts +26 -0
  45. package/dist/provider-discovery.js +138 -0
  46. package/dist/provider-pricing.d.ts +3 -0
  47. package/dist/provider-pricing.js +130 -0
  48. package/dist/provider.d.ts +16 -0
  49. package/dist/provider.js +370 -0
  50. package/dist/reconcile-command.d.ts +36 -0
  51. package/dist/reconcile-command.js +64 -0
  52. package/dist/renderer.d.ts +204 -0
  53. package/dist/renderer.js +1134 -0
  54. package/dist/repl-host.d.ts +22 -0
  55. package/dist/repl-host.js +51 -0
  56. package/dist/repl-run-observer.d.ts +27 -0
  57. package/dist/repl-run-observer.js +86 -0
  58. package/dist/repl.d.ts +12 -0
  59. package/dist/repl.js +1834 -0
  60. package/dist/results.d.ts +23 -0
  61. package/dist/results.js +1 -0
  62. package/dist/sandbox-cli.d.ts +39 -0
  63. package/dist/sandbox-cli.js +324 -0
  64. package/dist/session-history.d.ts +17 -0
  65. package/dist/session-history.js +76 -0
  66. package/dist/settings-menu.d.ts +2 -0
  67. package/dist/settings-menu.js +111 -0
  68. package/dist/skill-cli.d.ts +25 -0
  69. package/dist/skill-cli.js +355 -0
  70. package/dist/slash-commands.d.ts +66 -0
  71. package/dist/slash-commands.js +1449 -0
  72. package/dist/terminal-input.d.ts +24 -0
  73. package/dist/terminal-input.js +111 -0
  74. package/dist/terminal-selection.d.ts +21 -0
  75. package/dist/terminal-selection.js +72 -0
  76. package/dist/terminal-text.d.ts +38 -0
  77. package/dist/terminal-text.js +238 -0
  78. package/dist/tui.d.ts +170 -0
  79. package/dist/tui.js +2559 -0
  80. package/dist/usage.d.ts +13 -0
  81. package/dist/usage.js +46 -0
  82. package/dist/user-config.d.ts +48 -0
  83. package/dist/user-config.js +188 -0
  84. package/package.json +18 -3
  85. package/README.md +0 -3
@@ -0,0 +1,23 @@
1
+ import type { HostCommandResults, RunProgressPage, RunQueryResult, TeamQueryResult } from '@saturn-universe/protocol';
2
+ import type { CliDiagnostic } from './cli-diagnostics.js';
3
+ import type { RenderProgressEvent } from './renderer.js';
4
+ export interface CliResult extends Partial<RunQueryResult>, Pick<RunProgressPage, 'draft' | 'liveAgents' | 'telemetry' | 'pendingApprovals'>, Partial<Pick<TeamQueryResult, 'sessionId' | 'concurrency' | 'members' | 'tasks' | 'inbox' | 'plan'>>, Partial<Pick<HostCommandResults['surface.compact'], 'compactionId' | 'replacedCount'>> {
5
+ help?: string;
6
+ workspaceId?: string;
7
+ cursor?: string;
8
+ events?: readonly RenderProgressEvent[];
9
+ epoch?: HostCommandResults['host.status']['epoch'];
10
+ stopping?: HostCommandResults['host.shutdown']['stopping'];
11
+ [key: string]: unknown;
12
+ }
13
+ export type CliOutput = {
14
+ ok: true;
15
+ commandId?: string;
16
+ type?: string;
17
+ result: CliResult;
18
+ } | {
19
+ ok: false;
20
+ type?: string;
21
+ cursor?: string;
22
+ error: CliDiagnostic;
23
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,39 @@
1
+ export interface SandboxListEntry {
2
+ readonly sessionId?: string;
3
+ readonly runId: string;
4
+ readonly role: 'main' | 'worker';
5
+ readonly memberId: string;
6
+ readonly sandboxProfile: string;
7
+ readonly backend: string;
8
+ readonly image: string;
9
+ readonly containerId: string;
10
+ readonly containerRunning: boolean;
11
+ readonly workDir: string;
12
+ readonly sizeBytes: number;
13
+ readonly status: string;
14
+ readonly createdAt: string;
15
+ readonly updatedAt: string;
16
+ readonly expiresAt?: string;
17
+ }
18
+ export interface SandboxListResult {
19
+ readonly workspaceRoot: string;
20
+ readonly workspaceHash: string;
21
+ readonly sandboxes: readonly SandboxListEntry[];
22
+ readonly totalSizeBytes: number;
23
+ readonly activeContainers: number;
24
+ }
25
+ export interface SandboxCleanResult {
26
+ readonly workspaceRoot: string;
27
+ readonly removedSandboxes: number;
28
+ readonly removedContainers: number;
29
+ readonly freedBytes: number;
30
+ }
31
+ export declare function listSandboxes(root: string, options?: {
32
+ readonly sessionId?: string;
33
+ }): Promise<SandboxListResult>;
34
+ export declare function cleanSandboxes(root: string, options?: {
35
+ readonly all?: boolean;
36
+ readonly olderThanHours?: number;
37
+ readonly sessionId?: string;
38
+ }): Promise<SandboxCleanResult>;
39
+ export declare function runSandboxCommand(args: string[], root: string): Promise<void>;
@@ -0,0 +1,324 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { lstat, opendir, readdir, readFile, rm } from 'node:fs/promises';
4
+ import path from 'node:path';
5
+ import { parseArgs, promisify } from 'node:util';
6
+ import { CliError } from './cli-diagnostics.js';
7
+ import { topicHelp } from './cli-help.js';
8
+ const execFileAsync = promisify(execFile);
9
+ const sandboxHelp = topicHelp('sandbox');
10
+ function workspaceHashFor(root) {
11
+ const normalized = process.platform === 'win32' ? root.toLowerCase() : root;
12
+ return createHash('sha256').update(normalized).digest('hex').slice(0, 16);
13
+ }
14
+ async function computeDirBytes(directory) {
15
+ let total = 0;
16
+ const pending = [directory];
17
+ while (pending.length) {
18
+ const current = pending.pop();
19
+ let dir;
20
+ try {
21
+ dir = await opendir(current);
22
+ }
23
+ catch {
24
+ continue;
25
+ }
26
+ for await (const entry of dir) {
27
+ const fullPath = path.join(current, entry.name);
28
+ const info = await lstat(fullPath).catch(() => undefined);
29
+ if (!info || info.isSymbolicLink())
30
+ continue;
31
+ if (info.isDirectory())
32
+ pending.push(fullPath);
33
+ else if (info.isFile())
34
+ total += info.size;
35
+ }
36
+ }
37
+ return total;
38
+ }
39
+ async function listLiveContainers(workspaceHash) {
40
+ const map = new Map();
41
+ try {
42
+ const { stdout } = await execFileAsync('docker', [
43
+ 'ps',
44
+ '-a',
45
+ '--filter',
46
+ 'label=saturn.managed=true',
47
+ '--filter',
48
+ `label=saturn.workspace=${workspaceHash}`,
49
+ '--format',
50
+ '{{json .}}',
51
+ ], { timeout: 8000, windowsHide: true });
52
+ for (const line of stdout.split(/\r?\n/)) {
53
+ const trimmed = line.trim();
54
+ if (!trimmed)
55
+ continue;
56
+ try {
57
+ const parsed = JSON.parse(trimmed);
58
+ if (parsed.ID) {
59
+ map.set(parsed.ID, { id: parsed.ID, state: parsed.State ?? 'unknown' });
60
+ }
61
+ }
62
+ catch {
63
+ // Ignore malformed docker line
64
+ }
65
+ }
66
+ }
67
+ catch {
68
+ // Docker unavailable; report disk metadata only.
69
+ }
70
+ return map;
71
+ }
72
+ async function removeDockerContainer(containerId) {
73
+ if (!containerId)
74
+ return false;
75
+ try {
76
+ await execFileAsync('docker', ['rm', '-f', containerId], { timeout: 10000, windowsHide: true });
77
+ return true;
78
+ }
79
+ catch {
80
+ return false;
81
+ }
82
+ }
83
+ async function listSandboxesRoots(root) {
84
+ const roots = [{ dir: path.join(root, '.saturn', 'sandboxes') }];
85
+ const sessionsDir = path.join(root, '.saturn', 'sessions');
86
+ try {
87
+ for (const entry of (await readdir(sessionsDir, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
88
+ if (entry.isDirectory()) {
89
+ roots.push({
90
+ sessionId: entry.name,
91
+ dir: path.join(sessionsDir, entry.name, 'sandboxes'),
92
+ });
93
+ }
94
+ }
95
+ }
96
+ catch {
97
+ // No session sandbox directories
98
+ }
99
+ return roots;
100
+ }
101
+ async function collectSandboxes(root, sessionIdFilter) {
102
+ const workspaceHash = workspaceHashFor(root);
103
+ const candidateRoots = await listSandboxesRoots(root);
104
+ const liveContainers = await listLiveContainers(workspaceHash);
105
+ const results = [];
106
+ for (const { sessionId: dirSessionId, dir: sandboxesRoot } of candidateRoots) {
107
+ let runDirs;
108
+ try {
109
+ runDirs = await readdir(sandboxesRoot);
110
+ }
111
+ catch {
112
+ continue;
113
+ }
114
+ for (const runEntry of runDirs.sort()) {
115
+ const runDir = path.join(sandboxesRoot, runEntry);
116
+ const memberDirs = [path.join(runDir, 'main')];
117
+ try {
118
+ const workersDir = path.join(runDir, 'workers');
119
+ for (const worker of (await readdir(workersDir)).sort()) {
120
+ memberDirs.push(path.join(workersDir, worker));
121
+ }
122
+ }
123
+ catch {
124
+ // No workers directory
125
+ }
126
+ for (const memberDir of memberDirs) {
127
+ const metaPath = path.join(memberDir, 'meta.json');
128
+ let raw;
129
+ try {
130
+ raw = JSON.parse(await readFile(metaPath, 'utf8'));
131
+ }
132
+ catch {
133
+ continue;
134
+ }
135
+ const effectiveSessionId = raw.sessionId ?? dirSessionId;
136
+ if (sessionIdFilter && effectiveSessionId !== sessionIdFilter)
137
+ continue;
138
+ const workDir = raw.workDir ?? path.join(memberDir, 'work');
139
+ const sizeBytes = await computeDirBytes(memberDir);
140
+ const containerId = raw.containerId ?? '';
141
+ const live = containerId
142
+ ? [...liveContainers.values()].find((c) => containerId.startsWith(c.id) || c.id.startsWith(containerId))
143
+ : undefined;
144
+ results.push({
145
+ ...(effectiveSessionId ? { sessionId: effectiveSessionId } : {}),
146
+ runId: raw.runId ?? runEntry,
147
+ role: raw.role ?? 'main',
148
+ memberId: raw.memberId ?? path.basename(memberDir),
149
+ sandboxProfile: raw.sandboxProfile ?? 'default',
150
+ backend: raw.backend ?? 'unknown',
151
+ image: raw.image ?? '',
152
+ containerId,
153
+ containerRunning: live?.state === 'running',
154
+ workDir,
155
+ sizeBytes,
156
+ status: raw.status ?? 'unknown',
157
+ createdAt: raw.createdAt ?? '',
158
+ updatedAt: raw.updatedAt ?? '',
159
+ ...(raw.expiresAt ? { expiresAt: raw.expiresAt } : {}),
160
+ memberDir,
161
+ runDir,
162
+ });
163
+ }
164
+ }
165
+ }
166
+ return { workspaceHash, entries: results };
167
+ }
168
+ export async function listSandboxes(root, options = {}) {
169
+ const { workspaceHash, entries } = await collectSandboxes(root, options.sessionId);
170
+ const sandboxes = entries.map(({ memberDir: _m, runDir: _r, ...rest }) => rest);
171
+ return {
172
+ workspaceRoot: root,
173
+ workspaceHash,
174
+ sandboxes,
175
+ totalSizeBytes: sandboxes.reduce((sum, item) => sum + item.sizeBytes, 0),
176
+ activeContainers: sandboxes.filter((item) => item.containerRunning).length,
177
+ };
178
+ }
179
+ export async function cleanSandboxes(root, options = {}) {
180
+ const { workspaceHash, entries } = await collectSandboxes(root, options.sessionId);
181
+ const now = Date.now();
182
+ const cutoffMs = options.olderThanHours !== undefined ? now - options.olderThanHours * 3600 * 1000 : undefined;
183
+ let removedSandboxes = 0;
184
+ let removedContainers = 0;
185
+ let freedBytes = 0;
186
+ const touchedRunDirs = new Set();
187
+ const removedIds = new Set();
188
+ for (const entry of entries) {
189
+ const ts = Date.parse(entry.updatedAt || entry.createdAt);
190
+ const expired = entry.expiresAt !== undefined && Date.parse(entry.expiresAt) <= now;
191
+ const matches = options.all
192
+ ? true
193
+ : cutoffMs !== undefined
194
+ ? Number.isFinite(ts) && ts <= cutoffMs
195
+ : entry.status !== 'running' || expired;
196
+ if (!matches)
197
+ continue;
198
+ if (entry.containerId) {
199
+ removedIds.add(entry.containerId);
200
+ if (await removeDockerContainer(entry.containerId)) {
201
+ removedContainers++;
202
+ }
203
+ }
204
+ await rm(entry.memberDir, { recursive: true, force: true });
205
+ removedSandboxes++;
206
+ freedBytes += entry.sizeBytes;
207
+ touchedRunDirs.add(entry.runDir);
208
+ }
209
+ if (options.all && !options.sessionId) {
210
+ const live = await listLiveContainers(workspaceHash);
211
+ for (const container of live.values()) {
212
+ const alreadyRemoved = [...removedIds].some((id) => id.startsWith(container.id) || container.id.startsWith(id));
213
+ if (!alreadyRemoved && (await removeDockerContainer(container.id))) {
214
+ removedContainers++;
215
+ }
216
+ }
217
+ }
218
+ for (const runDir of touchedRunDirs) {
219
+ try {
220
+ const workersDir = path.join(runDir, 'workers');
221
+ const workers = await readdir(workersDir).catch(() => []);
222
+ if (workers.length === 0)
223
+ await rm(workersDir, { recursive: true, force: true }).catch(() => { });
224
+ const remaining = await readdir(runDir).catch(() => []);
225
+ if (remaining.length === 0)
226
+ await rm(runDir, { recursive: true, force: true }).catch(() => { });
227
+ }
228
+ catch {
229
+ // Ignore cleanup errors
230
+ }
231
+ }
232
+ return {
233
+ workspaceRoot: root,
234
+ removedSandboxes,
235
+ removedContainers,
236
+ freedBytes,
237
+ };
238
+ }
239
+ function formatBytes(bytes) {
240
+ if (bytes < 1024)
241
+ return `${bytes} B`;
242
+ if (bytes < 1024 * 1024)
243
+ return `${(bytes / 1024).toFixed(1)} KiB`;
244
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MiB`;
245
+ }
246
+ export async function runSandboxCommand(args, root) {
247
+ let parsed;
248
+ try {
249
+ parsed = parseArgs({
250
+ args,
251
+ allowPositionals: true,
252
+ strict: true,
253
+ options: {
254
+ json: { type: 'boolean' },
255
+ all: { type: 'boolean' },
256
+ 'older-than': { type: 'string' },
257
+ session: { type: 'string' },
258
+ help: { type: 'boolean', short: 'h' },
259
+ },
260
+ });
261
+ }
262
+ catch {
263
+ throw new CliError('USAGE');
264
+ }
265
+ const [sub = 'list', ...extra] = parsed.positionals;
266
+ const json = Boolean(parsed.values.json);
267
+ const sessionRaw = typeof parsed.values.session === 'string' ? parsed.values.session.trim() : undefined;
268
+ const sessionId = sessionRaw || undefined;
269
+ if (parsed.values.help || sub === 'help') {
270
+ if (json)
271
+ process.stdout.write(JSON.stringify({ ok: true, result: { help: sandboxHelp } }) + '\n');
272
+ else
273
+ process.stdout.write(sandboxHelp + '\n');
274
+ return;
275
+ }
276
+ if (extra.length || !['list', 'clean'].includes(sub)) {
277
+ throw new CliError('USAGE');
278
+ }
279
+ if (sub === 'list') {
280
+ if (parsed.values.all || parsed.values['older-than'] !== undefined) {
281
+ throw new CliError('USAGE');
282
+ }
283
+ const result = await listSandboxes(root, sessionId ? { sessionId } : {});
284
+ if (json) {
285
+ process.stdout.write(JSON.stringify({ ok: true, result }) + '\n');
286
+ return;
287
+ }
288
+ if (!result.sandboxes.length) {
289
+ process.stdout.write(`No sandboxes found for ${result.workspaceRoot}.\n`);
290
+ return;
291
+ }
292
+ process.stdout.write(`Sandboxes for ${result.workspaceRoot} (active=${result.activeContainers}, total=${formatBytes(result.totalSizeBytes)}):\n`);
293
+ for (const item of result.sandboxes) {
294
+ const containerTag = item.containerId
295
+ ? `${item.containerId.slice(0, 12)}(${item.containerRunning ? 'up' : 'gone'})`
296
+ : 'none';
297
+ const sessionTag = item.sessionId ? `${item.sessionId.slice(0, 8)}/` : '';
298
+ process.stdout.write(` - ${sessionTag}${item.runId} [${item.role}:${item.memberId}/${item.sandboxProfile}] ${item.backend} status=${item.status} container=${containerTag} size=${formatBytes(item.sizeBytes)}\n`);
299
+ }
300
+ return;
301
+ }
302
+ const all = Boolean(parsed.values.all);
303
+ const olderThanRaw = parsed.values['older-than'];
304
+ if (all && olderThanRaw !== undefined) {
305
+ throw new CliError('USAGE');
306
+ }
307
+ let olderThanHours;
308
+ if (olderThanRaw !== undefined) {
309
+ olderThanHours = Number(olderThanRaw);
310
+ if (!Number.isFinite(olderThanHours) || olderThanHours <= 0) {
311
+ throw new CliError('USAGE');
312
+ }
313
+ }
314
+ const result = await cleanSandboxes(root, {
315
+ all,
316
+ ...(olderThanHours !== undefined ? { olderThanHours } : {}),
317
+ ...(sessionId !== undefined ? { sessionId } : {}),
318
+ });
319
+ if (json) {
320
+ process.stdout.write(JSON.stringify({ ok: true, result }) + '\n');
321
+ return;
322
+ }
323
+ process.stdout.write(`Cleaned ${result.removedSandboxes} sandbox(es), removed ${result.removedContainers} container(s), freed ${formatBytes(result.freedBytes)}.\n`);
324
+ }
@@ -0,0 +1,17 @@
1
+ import type { SessionHistoryMessage } from '@saturn-universe/protocol';
2
+ interface HistoryRoute {
3
+ readonly sessionId: string;
4
+ readonly agentSessionId?: string;
5
+ }
6
+ interface HistoryOutput {
7
+ onPage(messages: readonly SessionHistoryMessage[]): void;
8
+ onMessage(message: SessionHistoryMessage, text: string): void;
9
+ onError(error: unknown): void;
10
+ }
11
+ export declare function messageEntryKey(messageId: string): string;
12
+ export declare function historyEntryKey(message: SessionHistoryMessage): string;
13
+ export declare function createSessionHistoryLoader(workdir: string, route: HistoryRoute, output: HistoryOutput): {
14
+ load(): Promise<void>;
15
+ close: () => void;
16
+ };
17
+ export {};
@@ -0,0 +1,76 @@
1
+ import { MAX_SESSION_HISTORY_PAGE_SIZE } from '@saturn-universe/protocol';
2
+ import { CliError } from './cli-diagnostics.js';
3
+ import { sendHostCommand } from './host-command.js';
4
+ export function messageEntryKey(messageId) {
5
+ return `message:${messageId}`;
6
+ }
7
+ export function historyEntryKey(message) {
8
+ if (message.role === 'thinking')
9
+ return `thinking:${message.id}`;
10
+ if (message.toolCallId)
11
+ return `tool:${message.runId}:${message.toolCallId}`;
12
+ return messageEntryKey(message.id);
13
+ }
14
+ export function createSessionHistoryLoader(workdir, route, output) {
15
+ const controller = new AbortController();
16
+ const { signal } = controller;
17
+ // An undefined boundary starts at the snapshot head. A null boundary marks a completed history.
18
+ let cursor;
19
+ let pending;
20
+ async function completeMessage(message) {
21
+ let text = message.text;
22
+ let offset = message.nextOffset;
23
+ while (offset !== undefined) {
24
+ signal.throwIfAborted();
25
+ const chunk = await sendHostCommand(workdir, { type: 'session.history.message', ...route, position: message.position, offset }, { signal });
26
+ if (chunk.id !== message.id ||
27
+ chunk.runId !== message.runId ||
28
+ chunk.role !== message.role ||
29
+ !chunk.text.length)
30
+ throw new CliError('INVALID_REPLY');
31
+ text += chunk.text;
32
+ offset = chunk.nextOffset;
33
+ }
34
+ return text;
35
+ }
36
+ async function readPage() {
37
+ try {
38
+ const page = await sendHostCommand(workdir, {
39
+ type: 'session.history',
40
+ ...route,
41
+ limit: MAX_SESSION_HISTORY_PAGE_SIZE,
42
+ ...(cursor ? { through: cursor.through } : {}),
43
+ ...(cursor?.before ? { before: cursor.before } : {}),
44
+ }, { signal });
45
+ if (signal.aborted)
46
+ return;
47
+ cursor ??= { through: page.through, before: undefined };
48
+ output.onPage(page.messages);
49
+ for (const message of page.messages) {
50
+ if (message.nextOffset === undefined)
51
+ continue;
52
+ const text = await completeMessage(message);
53
+ if (signal.aborted)
54
+ return;
55
+ output.onMessage(message, text);
56
+ }
57
+ if (!signal.aborted)
58
+ cursor = { through: cursor.through, before: page.nextBefore ?? null };
59
+ }
60
+ catch (error) {
61
+ if (!signal.aborted)
62
+ output.onError(error);
63
+ }
64
+ }
65
+ return {
66
+ load() {
67
+ if (signal.aborted || cursor?.before === null)
68
+ return Promise.resolve();
69
+ pending ??= readPage().finally(() => {
70
+ pending = undefined;
71
+ });
72
+ return pending;
73
+ },
74
+ close: () => controller.abort(),
75
+ };
76
+ }
@@ -0,0 +1,2 @@
1
+ export declare function readMcpJsonInput(input: NodeJS.ReadableStream, output: NodeJS.WritableStream): Promise<string>;
2
+ export declare function manageSettings(group: string, root: string): Promise<void>;
@@ -0,0 +1,111 @@
1
+ import { createInterface } from 'node:readline';
2
+ import { UsageError } from './cli-diagnostics.js';
3
+ import { terminalPrompt, pickAction } from './menu.js';
4
+ import { runMcpCommand } from './mcp-cli.js';
5
+ import { runProviderCommand } from './provider.js';
6
+ import { runConfigCommand } from './config-cli.js';
7
+ import { runSkillCommand } from './skill-cli.js';
8
+ import { runSandboxCommand } from './sandbox-cli.js';
9
+ import { syncUserConfigDefaults } from './user-config.js';
10
+ async function field(label) {
11
+ const prompt = terminalPrompt(process.stdin, process.stdout);
12
+ try {
13
+ return await prompt.question(label);
14
+ }
15
+ finally {
16
+ prompt.close();
17
+ }
18
+ }
19
+ export async function readMcpJsonInput(input, output) {
20
+ const reader = createInterface({ input, output, historySize: 0 });
21
+ reader.on('SIGINT', () => reader.close());
22
+ output.write('JSON(可粘贴多行,完整后按 Enter 提交。单独输入 . 检查未完成的输入)\n');
23
+ let json = '';
24
+ try {
25
+ for await (const line of reader) {
26
+ if (line.trim() === '.')
27
+ return json;
28
+ json += line + '\n';
29
+ try {
30
+ JSON.parse(json);
31
+ return json;
32
+ }
33
+ catch {
34
+ // Continue collecting lines until the JSON is complete or submitted.
35
+ }
36
+ }
37
+ throw new UsageError('已取消 MCP 导入。');
38
+ }
39
+ finally {
40
+ reader.close();
41
+ }
42
+ }
43
+ export async function manageSettings(group, root) {
44
+ switch (group) {
45
+ case 'provider':
46
+ return runProviderCommand([], { root });
47
+ case 'config': {
48
+ const choice = await pickAction('Saturn 设置', [
49
+ '查看当前设置',
50
+ '检查设置',
51
+ '管理 AI 服务',
52
+ '修改默认审批设置',
53
+ '返回',
54
+ ]);
55
+ if (choice === 2)
56
+ return runProviderCommand([], { root });
57
+ if (choice === 3) {
58
+ const mode = await pickAction('工具审批', ['严格审批', '默认审批', '返回']);
59
+ if (mode < 2) {
60
+ const saved = await syncUserConfigDefaults({ permissionMode: mode === 0 ? 'strict' : 'default' }, { workdir: root });
61
+ process.stdout.write(saved.workspaceConfigOverrides
62
+ ? '已保存用户设置,此工作区有单独的配置。\n'
63
+ : '已保存默认审批设置。\n');
64
+ }
65
+ }
66
+ else if (choice < 2)
67
+ return runConfigCommand([choice === 0 ? 'show' : 'check', '-C', root]);
68
+ return;
69
+ }
70
+ case 'mcp': {
71
+ const choice = await pickAction('外部工具服务', [
72
+ '查看连接状态',
73
+ '添加服务地址',
74
+ '从 JSON 导入服务',
75
+ '移除服务',
76
+ '返回',
77
+ ]);
78
+ if (choice === 0)
79
+ return runMcpCommand(['list'], root);
80
+ if (choice === 4)
81
+ return;
82
+ const name = await field('服务名称:');
83
+ if (choice === 3) {
84
+ if ((await field('确认移除?输入 y 确认:')).toLowerCase() === 'y')
85
+ await runMcpCommand(['remove', name], root);
86
+ return;
87
+ }
88
+ if (choice === 1) {
89
+ const address = await field('EndPoint: ');
90
+ return runMcpCommand(['add', name, '--transport', 'http', address], root);
91
+ }
92
+ const json = await readMcpJsonInput(process.stdin, process.stdout);
93
+ return runMcpCommand(['add-json', name, json], root);
94
+ }
95
+ case 'skill': {
96
+ const choice = await pickAction('技能', ['已安装的技能', '添加本地技能', '移除技能', '返回']);
97
+ if (choice === 0)
98
+ return runSkillCommand(['list'], root);
99
+ if (choice === 1)
100
+ return runSkillCommand(['add', await field('技能目录:')], root);
101
+ if (choice === 2) {
102
+ const name = await field('技能名称:');
103
+ if ((await field('确认移除?输入 y 确认:')).toLowerCase() === 'y')
104
+ await runSkillCommand(['remove', name], root);
105
+ }
106
+ return;
107
+ }
108
+ case 'sandbox':
109
+ return runSandboxCommand(['list'], root);
110
+ }
111
+ }
@@ -0,0 +1,25 @@
1
+ import type { DiscoveredSkill } from '@saturn-universe/protocol';
2
+ export interface SkillAddResult {
3
+ readonly name: string;
4
+ readonly description: string;
5
+ readonly scope: 'user' | 'project';
6
+ readonly path: string;
7
+ readonly resources: readonly string[];
8
+ }
9
+ export interface SkillRemoveResult {
10
+ readonly name: string;
11
+ readonly scope: 'user' | 'project';
12
+ readonly path: string;
13
+ }
14
+ export declare function listDiscoveredSkillsCli(workdir: string, env?: NodeJS.ProcessEnv): Promise<readonly DiscoveredSkill[]>;
15
+ export declare function addSkillCli(workdir: string, source: string, options?: {
16
+ readonly scope?: 'user' | 'project';
17
+ readonly name?: string;
18
+ readonly force?: boolean;
19
+ readonly env?: NodeJS.ProcessEnv;
20
+ }): Promise<SkillAddResult>;
21
+ export declare function removeSkillCli(workdir: string, name: string, options?: {
22
+ readonly scope?: 'user' | 'project';
23
+ readonly env?: NodeJS.ProcessEnv;
24
+ }): Promise<SkillRemoveResult>;
25
+ export declare function runSkillCommand(args: readonly string[], workdir: string, env?: NodeJS.ProcessEnv): Promise<void>;