@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,1449 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { parseArgs } from 'node:util';
4
+ import { contextExtensionRefPattern, DEFAULT_MODE_REF, DEFAULT_SESSION_LIST_LIMIT, discoverAgentSkills, modeSelectorPattern, parseTeamConfig, resolveModeSelector, } from '@saturn-universe/protocol';
5
+ import { CliError, UsageError } from './cli-diagnostics.js';
6
+ import { compactionArguments, compactionOptions, compactionOptionUsage } from './compaction-command.js';
7
+ import { ensureHostWorkspace, reconcileRunTool, resolveRunApproval, sendHostCommand, } from './host-command.js';
8
+ import { stopHost } from './host-launcher.js';
9
+ import { reconciliationCommand, reconciliationOptions } from './reconcile-command.js';
10
+ import { applyReplMode } from './repl-host.js';
11
+ import { renderConfigCheck, renderConfigInit, renderConfigSummary, renderReplHelp, renderShortcutHelp, renderTeamBoard, renderUsageCard, } from './renderer.js';
12
+ import { initUserConfig, inspectUserConfig, syncUserConfigDefaults, } from './user-config.js';
13
+ import { authenticateMcpServer, formatMcpServerStatus, listMcpServersInfo, setWorkspaceMcpTrust, } from './mcp-cli.js';
14
+ import { exportSessionToJsonl, formatByteSize } from './export.js';
15
+ import { formatTokenCompact } from './usage.js';
16
+ const profileHint = {
17
+ command: '/profile',
18
+ summary: 'Alias for /model',
19
+ takesArgs: true,
20
+ currentValue: (ctx) => ctx.profileName,
21
+ argOptions: (_args, ctx) => [
22
+ ...(ctx.availableProfiles ?? []).map((profile) => ({
23
+ value: profile.name,
24
+ summary: profileSummary(profile),
25
+ current: profile.name === ctx.profileName,
26
+ })),
27
+ { value: 'default', summary: '恢复使用 Host 默认 profile' },
28
+ ],
29
+ };
30
+ export const SLASH_COMMAND_HINTS = [
31
+ { command: '/btw', summary: '旁白问答(不写入历史)', takesArgs: true },
32
+ { command: '/steer', summary: '转向当前运行(Ctrl+Enter / Alt+Enter)', takesArgs: true },
33
+ {
34
+ command: '/team',
35
+ summary: 'Launch an Agent Team (or inspect team board)',
36
+ takesArgs: true,
37
+ argOptions: (args, ctx) => {
38
+ const last = args[args.length - 1];
39
+ if (last === '--preset') {
40
+ return (ctx.availableTeamPresets ?? []).map((preset) => ({
41
+ value: preset,
42
+ summary: '使用该团队预设',
43
+ appendSpace: true,
44
+ }));
45
+ }
46
+ if (last === '--concurrency' || last === '--max-members' || last === '--file') {
47
+ return [];
48
+ }
49
+ return [
50
+ { value: '--concurrency', summary: '最大并发卫星数 (1-16)', appendSpace: true },
51
+ { value: '--max-members', summary: '最大团队成员数 (1-15)', appendSpace: true },
52
+ { value: '--preset', summary: '使用预置团队模板', appendSpace: true },
53
+ { value: '--file', summary: '从 JSON 配置文件加载团队', appendSpace: true },
54
+ ];
55
+ },
56
+ },
57
+ {
58
+ command: '/permission',
59
+ summary: 'Set tool approval mode (strict|default|full)',
60
+ takesArgs: true,
61
+ currentValue: (ctx) => ctx.permissionMode ?? 'default',
62
+ argOptions: (_args, ctx) => [
63
+ {
64
+ value: 'strict',
65
+ summary: '工作区内仅只读与只读插件自动放行,写入/命令/越界路径与插件写工具需审批',
66
+ current: ctx.permissionMode === 'strict',
67
+ },
68
+ {
69
+ value: 'default',
70
+ summary: '工作区内读写/命令及白名单插件自动放行,越界路径与外部写工具需审批',
71
+ current: (ctx.permissionMode ?? 'default') === 'default',
72
+ },
73
+ {
74
+ value: 'full',
75
+ summary: '全自动放行工作区内外普通操作与已授权 MCP/插件(保留安全硬防线)',
76
+ current: ctx.permissionMode === 'full',
77
+ },
78
+ ],
79
+ },
80
+ {
81
+ command: '/effort',
82
+ summary: 'Show or switch reasoning effort (or /effort worker <level>)',
83
+ takesArgs: true,
84
+ currentValue: (ctx) => ctx.reasoningEffort ?? '(default)',
85
+ argOptions: (args, ctx) => {
86
+ const supported = ctx.availableReasoningEfforts && ctx.availableReasoningEfforts.length > 0
87
+ ? ctx.availableReasoningEfforts
88
+ : ['low', 'medium', 'high', 'max'];
89
+ if (args.length === 1 && args[0]?.toLowerCase() === 'worker') {
90
+ return [
91
+ ...supported.map((level) => ({
92
+ value: level,
93
+ summary: '设置子代理思考强度',
94
+ current: ctx.workerReasoningEffort === level,
95
+ })),
96
+ { value: 'off', summary: '关闭子代理思考强度', current: ctx.workerReasoningEffort === 'off' },
97
+ { value: 'default', summary: '恢复子代理默认思考强度' },
98
+ ];
99
+ }
100
+ if (args.length === 0) {
101
+ return [
102
+ ...supported.map((level) => ({
103
+ value: level,
104
+ summary: '切换当前模型思考强度',
105
+ current: ctx.reasoningEffort === level,
106
+ })),
107
+ { value: 'off', summary: '关闭思考强度', current: ctx.reasoningEffort === 'off' },
108
+ { value: 'default', summary: '恢复模型默认思考强度' },
109
+ { value: 'worker', summary: '覆盖子代理思考强度 (/effort worker <level>)', appendSpace: true },
110
+ ];
111
+ }
112
+ return [];
113
+ },
114
+ },
115
+ { command: '/usage', summary: 'Show session context, tokens, speed, and estimated cost', takesArgs: false },
116
+ { command: '/sandbox', summary: '查看隔离环境' },
117
+ { command: '/run', summary: '查看当前任务状态' },
118
+ { command: '/new', summary: 'Create and switch to a new session', takesArgs: true },
119
+ { command: '/session', summary: 'Show or switch current session', takesArgs: true },
120
+ { command: '/attach', summary: 'Follow Run progress (Ctrl+C detaches)', takesArgs: true },
121
+ {
122
+ command: '/resume',
123
+ summary: 'Pick a recent session to resume, or resume a sessionId/runId',
124
+ takesArgs: true,
125
+ },
126
+ {
127
+ command: '/export',
128
+ summary: 'Export full session (main + workers) to JSONL',
129
+ takesArgs: true,
130
+ },
131
+ { command: '/cancel', summary: 'Cancel an active Run', takesArgs: true },
132
+ { command: '/approve', summary: 'Approve pending tool call and resume', takesArgs: true },
133
+ { command: '/deny', summary: 'Deny pending tool call', takesArgs: true },
134
+ { command: '/reconcile', summary: 'Reconcile an unknown tool outcome', takesArgs: true },
135
+ { command: '/compact', summary: 'Auto-compact context, or compact through a turn', takesArgs: true },
136
+ {
137
+ ...profileHint,
138
+ command: '/model',
139
+ summary: '选择模型和思考强度',
140
+ takesArgs: false,
141
+ submitWithoutArgs: true,
142
+ },
143
+ profileHint,
144
+ {
145
+ command: '/mode',
146
+ summary: 'Show or switch Host Mode (restarts Host)',
147
+ takesArgs: true,
148
+ currentValue: (ctx) => ctx.activeMode
149
+ ? `${ctx.activeMode.displayName} (${ctx.activeMode.ref})`
150
+ : (ctx.modeRef ?? DEFAULT_MODE_REF),
151
+ argOptions: (_args, ctx) => (ctx.availableModes ?? []).map((m) => ({
152
+ value: m.ref,
153
+ summary: `${m.displayName} — ${m.description}`,
154
+ current: m.ref === (ctx.activeMode?.ref ?? ctx.modeRef),
155
+ })),
156
+ },
157
+ {
158
+ command: '/skill',
159
+ summary: 'Inspect or toggle auto-discovered and versioned Skills',
160
+ takesArgs: true,
161
+ currentValue: (ctx) => {
162
+ const discovered = ctx.discoveredSkills ?? [];
163
+ if (discovered.length) {
164
+ const disabled = new Set(ctx.disabledSkills ?? []);
165
+ const enabled = discovered.filter((item) => !disabled.has(item.name)).length;
166
+ return `${enabled}/${discovered.length} active`;
167
+ }
168
+ return ctx.skillRefs.length ? ctx.skillRefs.join(', ') : '(none)';
169
+ },
170
+ argOptions: (args, ctx) => {
171
+ const discovered = ctx.discoveredSkills ?? [];
172
+ const disabled = new Set(ctx.disabledSkills ?? []);
173
+ if (args.length === 0) {
174
+ return [
175
+ { value: 'list', summary: '列出自动发现及已启用的 Skills' },
176
+ { value: 'show', summary: '查看某个 Skill 的详细说明与资源', appendSpace: true },
177
+ { value: 'toggle', summary: '启用或停用自动发现的 Skill', appendSpace: true },
178
+ { value: 'enable', summary: '启用自动发现的 Skill', appendSpace: true },
179
+ { value: 'disable', summary: '在当前会话停用自动发现的 Skill', appendSpace: true },
180
+ { value: 'add', summary: '启用 Skill 或添加版本化 Skill', appendSpace: true },
181
+ { value: 'remove', summary: '移除版本化 Skill 或停用 Skill', appendSpace: true },
182
+ { value: 'clear', summary: '重置 Skill 选择(全部启用/清空手动项)' },
183
+ ];
184
+ }
185
+ if (args.length === 1) {
186
+ const sub = args[0]?.toLowerCase();
187
+ if (sub === 'show' || sub === 'info' || sub === 'toggle') {
188
+ return discovered.map((s) => ({
189
+ value: s.name,
190
+ summary: `[${s.scope}] ${s.description}`,
191
+ current: !disabled.has(s.name),
192
+ }));
193
+ }
194
+ if (sub === 'enable') {
195
+ return discovered
196
+ .filter((s) => disabled.has(s.name))
197
+ .map((s) => ({
198
+ value: s.name,
199
+ summary: `[${s.scope}] ${s.description}`,
200
+ current: false,
201
+ }));
202
+ }
203
+ if (sub === 'disable') {
204
+ return discovered
205
+ .filter((s) => !disabled.has(s.name))
206
+ .map((s) => ({
207
+ value: s.name,
208
+ summary: `[${s.scope}] ${s.description}`,
209
+ current: true,
210
+ }));
211
+ }
212
+ if (sub === 'add') {
213
+ return [
214
+ ...discovered.map((s) => ({
215
+ value: s.name,
216
+ summary: `[${s.scope}] ${s.description}`,
217
+ current: !disabled.has(s.name),
218
+ })),
219
+ ...(ctx.availableSkills ?? []).map((s) => ({
220
+ value: s,
221
+ summary: '启用版本化 Skill',
222
+ current: ctx.skillRefs.includes(s),
223
+ })),
224
+ ];
225
+ }
226
+ if (sub === 'remove') {
227
+ return [
228
+ ...ctx.skillRefs.map((s) => ({
229
+ value: s,
230
+ summary: '移除该版本化 Skill',
231
+ current: true,
232
+ })),
233
+ ...discovered
234
+ .filter((s) => !disabled.has(s.name))
235
+ .map((s) => ({
236
+ value: s.name,
237
+ summary: `[${s.scope}] 停用该 Skill`,
238
+ current: true,
239
+ })),
240
+ ];
241
+ }
242
+ }
243
+ return [];
244
+ },
245
+ },
246
+ {
247
+ command: '/mcp',
248
+ summary: 'Inspect MCP servers and manage credentials or project trust',
249
+ takesArgs: true,
250
+ currentValue: (ctx) => {
251
+ const servers = ctx.mcpServers ?? [];
252
+ if (!servers.length)
253
+ return '(none)';
254
+ const ready = servers.filter((s) => s.discovery === 'ready').length;
255
+ return `${ready}/${servers.length} ready`;
256
+ },
257
+ argOptions: (args, ctx) => {
258
+ const servers = ctx.mcpServers ?? [];
259
+ if (args.length === 0) {
260
+ return [
261
+ { value: 'list', summary: '列出已配置的 MCP 服务器、状态与工具数' },
262
+ { value: 'status', summary: '查看 MCP 连接与信任状态' },
263
+ { value: 'trust', summary: '信任当前工作区的 .mcp.json 并连接服务' },
264
+ { value: 'untrust', summary: '撤销当前工作区 .mcp.json 信任' },
265
+ { value: 'show', summary: '查看指定 MCP 服务器详情', appendSpace: true },
266
+ { value: 'auth', summary: '隐藏输入 HTTP MCP 凭据并重新连接', appendSpace: true },
267
+ ];
268
+ }
269
+ const action = args[0]?.toLowerCase();
270
+ if (args.length === 1 && (action === 'show' || action === 'get' || action === 'auth')) {
271
+ return servers
272
+ .filter((s) => action !== 'auth' || s.transport === 'http')
273
+ .map((s) => ({
274
+ value: s.id,
275
+ summary: s.discovery === 'ready' ? `${s.discovery} · ${s.toolCount} tools` : s.discovery,
276
+ current: s.discovery === 'ready',
277
+ }));
278
+ }
279
+ return [];
280
+ },
281
+ },
282
+ {
283
+ command: '/config',
284
+ summary: 'Inspect or initialize ~/.saturn/ config',
285
+ takesArgs: true,
286
+ currentValue: (ctx) => ctx.configSource ?? 'none',
287
+ argOptions: () => [
288
+ { value: 'show', summary: '查看当前配置摘要' },
289
+ { value: 'check', summary: '检查配置文件与凭证就绪状态' },
290
+ { value: 'init', summary: '初始化 ~/.saturn/ 配置目录' },
291
+ ],
292
+ },
293
+ {
294
+ command: '/board',
295
+ summary: 'Show the active CTF WebUI board URL',
296
+ takesArgs: false,
297
+ currentValue: (ctx) => ctx.boardUrl,
298
+ },
299
+ { command: '/pwd', summary: 'Print current workspace path', takesArgs: false },
300
+ { command: '/help', summary: 'Show slash command reference', takesArgs: false },
301
+ { command: '/shortcuts', summary: '查看全屏终端快捷键', takesArgs: false },
302
+ { command: '/clear', summary: 'Clear terminal screen and redraw banner', takesArgs: false },
303
+ { command: '/shutdown', summary: 'Shut down local Host', takesArgs: false },
304
+ { command: '/exit', summary: 'Exit Saturn CLI', takesArgs: false },
305
+ { command: '/quit', summary: 'Alias for /exit', takesArgs: false },
306
+ ];
307
+ export const SLASH_COMMAND_NAMES = SLASH_COMMAND_HINTS.map((item) => item.command);
308
+ export function tokenizeCommandLine(line) {
309
+ const tokens = [];
310
+ let current = '';
311
+ let quote;
312
+ let escaping = false;
313
+ let hasToken = false;
314
+ for (let i = 0; i < line.length; i++) {
315
+ const ch = line[i];
316
+ if (escaping) {
317
+ current += ch;
318
+ escaping = false;
319
+ hasToken = true;
320
+ continue;
321
+ }
322
+ if (ch === '\\' && quote !== "'") {
323
+ escaping = true;
324
+ hasToken = true;
325
+ continue;
326
+ }
327
+ if (quote) {
328
+ if (ch === quote)
329
+ quote = undefined;
330
+ else
331
+ current += ch;
332
+ hasToken = true;
333
+ continue;
334
+ }
335
+ if (ch === '"' || ch === "'") {
336
+ quote = ch;
337
+ hasToken = true;
338
+ continue;
339
+ }
340
+ if (/\s/.test(ch)) {
341
+ if (hasToken) {
342
+ tokens.push(current);
343
+ current = '';
344
+ hasToken = false;
345
+ }
346
+ continue;
347
+ }
348
+ current += ch;
349
+ hasToken = true;
350
+ }
351
+ if (escaping)
352
+ current += '\\';
353
+ if (quote)
354
+ throw new Error('Unterminated quote in command');
355
+ if (hasToken)
356
+ tokens.push(current);
357
+ return tokens;
358
+ }
359
+ export async function ensureWorkspaceId(state) {
360
+ if (!state.workspaceId)
361
+ state.workspaceId = (await ensureHostWorkspace(state.workdir)).workspaceId;
362
+ return state.workspaceId;
363
+ }
364
+ function selectSession(state, hooks, sessionId, summary) {
365
+ state.sessionId = sessionId;
366
+ state.member = summary.member;
367
+ state.lastRunId = summary.latestRun?.id;
368
+ state.hasRunHistory = (summary.runCount ?? 0) > 0 || state.lastRunId !== undefined;
369
+ hooks.onSessionChanged?.({ ...summary, id: sessionId });
370
+ }
371
+ async function switchSession(state, hooks, sessionId, signal) {
372
+ if (signal?.aborted)
373
+ return;
374
+ const session = await sendHostCommand(state.workdir, { type: 'session.query', sessionId }, { signal });
375
+ if (signal?.aborted)
376
+ return;
377
+ hooks.checkSessionSwitch?.(session);
378
+ selectSession(state, hooks, sessionId, session);
379
+ }
380
+ export async function ensureSessionId(state, title = 'CLI session') {
381
+ if (state.sessionId)
382
+ return state.sessionId;
383
+ const workspaceId = await ensureWorkspaceId(state);
384
+ const created = await sendHostCommand(state.workdir, {
385
+ type: 'session.create',
386
+ workspaceId,
387
+ title,
388
+ });
389
+ state.sessionId = created.sessionId;
390
+ return state.sessionId;
391
+ }
392
+ function parsePositiveInt(value, max, label) {
393
+ if (value === undefined)
394
+ return undefined;
395
+ const parsed = Number(value);
396
+ if (!Number.isSafeInteger(parsed) || parsed < 1 || parsed > max) {
397
+ throw new Error(`${label} must be an integer between 1 and ${max}`);
398
+ }
399
+ return parsed;
400
+ }
401
+ function looksLikeRunId(value, lastRunId) {
402
+ if (lastRunId && value === lastRunId)
403
+ return true;
404
+ return (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value) || /^run[-_]/i.test(value));
405
+ }
406
+ function resolveActiveProfileStatus(state, status) {
407
+ const profiles = status?.profiles ?? [];
408
+ const activeName = state.profile ??
409
+ (state.taskProfile ? status?.taskProfiles?.[state.taskProfile] : undefined) ??
410
+ status?.selectedProfile ??
411
+ status?.defaultProfile;
412
+ return profiles.find((item) => item.name === activeName);
413
+ }
414
+ function supportsReasoning(profile) {
415
+ return Boolean(profile.reasoningModel || profile.reasoningEfforts?.length);
416
+ }
417
+ function profileSummary(profile) {
418
+ return [
419
+ profile.modelId !== profile.name ? profile.modelId : undefined,
420
+ profile.contextWindow ? `${formatTokenCompact(profile.contextWindow)} 上下文` : undefined,
421
+ profile.ready === false ? '缺少凭证' : undefined,
422
+ supportsReasoning(profile) ? '支持思考' : '无思考',
423
+ ]
424
+ .filter(Boolean)
425
+ .join(' · ');
426
+ }
427
+ function profileDefaultEffort(profile) {
428
+ if (profile.defaultReasoningEffort !== undefined)
429
+ return profile.defaultReasoningEffort;
430
+ const effort = profile.reasoningEffort;
431
+ return effort && !['auto', 'off', 'none'].includes(effort) ? effort : null;
432
+ }
433
+ function requireRunId(explicit, state) {
434
+ const runId = explicit ?? state.lastRunId;
435
+ if (!runId)
436
+ throw new Error('No runId provided and no recent run in this session.');
437
+ return runId;
438
+ }
439
+ function markUserMutated(state, field) {
440
+ state.userMutatedDefaults ??= new Set();
441
+ state.userMutatedDefaults.add(field);
442
+ }
443
+ async function persistGlobalDefaults(state, hooks, patch) {
444
+ try {
445
+ const persist = hooks.persistDefaults ??
446
+ ((nextPatch) => syncUserConfigDefaults(nextPatch, { workdir: state.workdir }));
447
+ const result = await persist(patch);
448
+ const base = '已同步至全局默认配置 (~/.saturn/config.toml)';
449
+ return result.workspaceConfigOverrides
450
+ ? `${base}(注意:当前工作区存在 .saturn/config.toml,将覆盖全局默认配置)`
451
+ : base;
452
+ }
453
+ catch (error) {
454
+ const message = error instanceof Error ? error.message : String(error);
455
+ return `(警告:未能写入全局默认配置:${message})`;
456
+ }
457
+ }
458
+ const immediateSlash = /^\/(btw|steer)(?:\s+([\s\S]*))?$/i;
459
+ export function isImmediateSlashCommand(line) {
460
+ return immediateSlash.test(line.trim());
461
+ }
462
+ export async function handleSlashCommand(line, state, hooks) {
463
+ const immediate = immediateSlash.exec(line.trim());
464
+ if (immediate) {
465
+ const command = immediate[1].toLowerCase();
466
+ const text = immediate[2]?.trim();
467
+ if (!text) {
468
+ hooks.writeLine(command === 'btw' ? 'Usage: /btw <question>' : 'Usage: /steer <message>');
469
+ }
470
+ else if (command === 'steer') {
471
+ if (!hooks.steer)
472
+ throw new Error('/steer requires an active run in the TUI');
473
+ await hooks.steer(text);
474
+ }
475
+ else {
476
+ const member = state.member;
477
+ const sessionId = member?.parentSessionId ?? state.sessionId;
478
+ const ask = async (signal) => {
479
+ if (!sessionId)
480
+ throw new Error('/btw requires an existing session');
481
+ await hooks.ensureConnected();
482
+ const { answer } = await sendHostCommand(state.workdir, {
483
+ type: 'session.btw',
484
+ sessionId,
485
+ question: text,
486
+ ...(member ? { agentSessionId: member.agentSessionId } : {}),
487
+ }, { signal });
488
+ return answer;
489
+ };
490
+ if (hooks.showSideQuestion)
491
+ hooks.showSideQuestion(text, ask);
492
+ else
493
+ hooks.writeLine(await ask());
494
+ }
495
+ return 'continue';
496
+ }
497
+ const tokens = tokenizeCommandLine(line.trim());
498
+ if (!tokens.length)
499
+ return 'continue';
500
+ const [command, ...args] = tokens;
501
+ const cmd = command.toLowerCase();
502
+ switch (cmd) {
503
+ case '/sandbox': {
504
+ const host = state.host ?? (await Promise.resolve(hooks.ensureConnected()).catch(() => undefined));
505
+ const status = (await Promise.resolve(hooks.refreshHostStatus()).catch(() => undefined)) ?? host?.status;
506
+ const sandbox = status?.sandbox;
507
+ hooks.writeLine(sandbox
508
+ ? [
509
+ `Sandbox: ${sandbox.backend} (${sandbox.state})`,
510
+ `范围 ${sandbox.scope}`,
511
+ `运行中容器 ${sandbox.activeContainers}`,
512
+ ...(sandbox.image ? [`镜像 ${sandbox.image}`] : []),
513
+ ...(sandbox.reason ? [sandbox.reason] : []),
514
+ ].join(' · ')
515
+ : status
516
+ ? 'Sandbox: 未配置沙箱'
517
+ : 'Sandbox: 无法获取 Host 状态');
518
+ return 'continue';
519
+ }
520
+ case '/run': {
521
+ const id = args[0] ?? state.lastRunId;
522
+ if (!id)
523
+ hooks.writeLine('本次对话还没有任务。');
524
+ else {
525
+ await hooks.ensureConnected();
526
+ const task = await sendHostCommand(state.workdir, { type: 'run.query', runId: id });
527
+ hooks.writeLine('任务 ' + id + ' · ' + task.status);
528
+ }
529
+ return 'continue';
530
+ }
531
+ case '/exit':
532
+ case '/quit':
533
+ return 'exit';
534
+ case '/help':
535
+ hooks.writeLine(renderReplHelp());
536
+ return 'continue';
537
+ case '/shortcuts':
538
+ hooks.writeLine(renderShortcutHelp());
539
+ return 'continue';
540
+ case '/clear':
541
+ if (hooks.clearScreen) {
542
+ hooks.clearScreen();
543
+ }
544
+ else {
545
+ hooks.write('\x1b[2J\x1b[H');
546
+ if (hooks.renderBanner)
547
+ hooks.write(hooks.renderBanner());
548
+ }
549
+ return 'continue';
550
+ case '/pwd':
551
+ hooks.writeLine(state.workdir);
552
+ return 'continue';
553
+ case '/board': {
554
+ const host = await hooks.ensureConnected();
555
+ let status = host?.status ?? state.host?.status;
556
+ if (!status?.boardUrl) {
557
+ try {
558
+ status = (await hooks.refreshHostStatus()) ?? status;
559
+ }
560
+ catch {
561
+ // Keep previously known status if host.status refresh fails.
562
+ }
563
+ }
564
+ if (status?.boardUrl) {
565
+ hooks.writeLine(`Board: ${status.boardUrl}`);
566
+ return 'continue';
567
+ }
568
+ const modeRef = status?.activeMode?.ref ?? state.activeMode?.ref ?? state.modeRef;
569
+ if (modeRef !== 'ctf@1') {
570
+ hooks.writeLine(`当前模式 (${modeRef ?? DEFAULT_MODE_REF}) 未启用 CTF 看板 WebUI;可使用 \`/mode ctf@1\` 切换开启。`);
571
+ return 'continue';
572
+ }
573
+ hooks.writeLine('CTF 看板 WebUI 暂未就绪或启动失败,请检查 Host 日志或稍后重试 `/board`。');
574
+ return 'continue';
575
+ }
576
+ case '/permission': {
577
+ const mode = args[0]?.toLowerCase();
578
+ if (!args.length) {
579
+ hooks.writeLine(`Permission mode: ${state.permissionMode}`);
580
+ }
581
+ else if (args.length === 1 && (mode === 'strict' || mode === 'default' || mode === 'full')) {
582
+ state.permissionMode = mode;
583
+ markUserMutated(state, 'permission');
584
+ const syncNotice = await persistGlobalDefaults(state, hooks, { permissionMode: mode });
585
+ hooks.writeLine(`Permission mode: ${mode} (new runs) · ${syncNotice}`);
586
+ }
587
+ else {
588
+ hooks.writeLine('Usage: /permission [strict|default|full]');
589
+ }
590
+ return 'continue';
591
+ }
592
+ case '/team': {
593
+ if (args.some((arg) => arg === '--member' || arg.startsWith('--member='))) {
594
+ const parsed = parseArgs({
595
+ args,
596
+ allowPositionals: true,
597
+ options: { member: { type: 'string' } },
598
+ });
599
+ if (parsed.positionals.length > 1 || !parsed.values.member)
600
+ throw new Error('Usage: /team [runId] --member <memberId>');
601
+ const navSignal = hooks.getNavigationSignal?.();
602
+ const runId = requireRunId(parsed.positionals[0], state);
603
+ await hooks.ensureConnected();
604
+ if (navSignal?.aborted)
605
+ return 'continue';
606
+ const team = await sendHostCommand(state.workdir, {
607
+ type: 'team.query',
608
+ runId,
609
+ }, { signal: navSignal });
610
+ if (navSignal?.aborted)
611
+ return 'continue';
612
+ const member = team.members.find(({ id }) => id === parsed.values.member);
613
+ if (!member?.agentSessionId)
614
+ throw new Error('找不到团队成员会话');
615
+ const target = member.id === 'main'
616
+ ? (team.sessionId ?? state.member?.parentSessionId ?? state.sessionId)
617
+ : member.agentSessionId;
618
+ if (!target)
619
+ throw new Error('找不到主会话');
620
+ await switchSession(state, hooks, target, navSignal);
621
+ return 'continue';
622
+ }
623
+ if (args.length === 0 ||
624
+ (args.length === 1 && !args[0].startsWith('-') && looksLikeRunId(args[0], state.lastRunId))) {
625
+ const runId = requireRunId(args[0], state);
626
+ await hooks.ensureConnected();
627
+ const team = await sendHostCommand(state.workdir, { type: 'team.query', runId });
628
+ hooks.writeLine(renderTeamBoard(team));
629
+ return 'continue';
630
+ }
631
+ const parsed = parseArgs({
632
+ args,
633
+ allowPositionals: true,
634
+ strict: true,
635
+ options: {
636
+ concurrency: { type: 'string' },
637
+ 'max-members': { type: 'string' },
638
+ preset: { type: 'string' },
639
+ file: { type: 'string' },
640
+ text: { type: 'string' },
641
+ },
642
+ });
643
+ const concurrency = parsePositiveInt(parsed.values.concurrency, 16, 'concurrency');
644
+ const maxMembers = parsePositiveInt(parsed.values['max-members'], 15, 'max-members');
645
+ const preset = parsed.values.preset;
646
+ const file = parsed.values.file;
647
+ const prompt = (typeof parsed.values.text === 'string' ? parsed.values.text : parsed.positionals.join(' ')).trim();
648
+ if (file && (preset || concurrency !== undefined || maxMembers !== undefined)) {
649
+ throw new Error('--file cannot be combined with --preset, --concurrency, or --max-members');
650
+ }
651
+ if (preset && (concurrency !== undefined || maxMembers !== undefined)) {
652
+ throw new Error('--preset cannot be combined with --concurrency or --max-members');
653
+ }
654
+ if (!prompt) {
655
+ throw new Error('Usage: /team [--concurrency N] [--max-members N] [--preset NAME] [--file FILE] <prompt>');
656
+ }
657
+ if (file) {
658
+ let team;
659
+ try {
660
+ const resolved = path.resolve(state.workdir, file);
661
+ team = parseTeamConfig(JSON.parse(await readFile(resolved, 'utf8')));
662
+ }
663
+ catch {
664
+ throw new CliError('INVALID_TEAM_CONFIG');
665
+ }
666
+ await hooks.submitAndFollow({ text: prompt, team });
667
+ return 'continue';
668
+ }
669
+ if (preset) {
670
+ await hooks.submitAndFollow({ text: prompt, teamPreset: preset });
671
+ return 'continue';
672
+ }
673
+ await hooks.submitAndFollow({
674
+ text: prompt,
675
+ teamHint: {
676
+ force: true,
677
+ ...(concurrency !== undefined ? { concurrency } : {}),
678
+ ...(maxMembers !== undefined ? { maxMembers } : {}),
679
+ },
680
+ });
681
+ return 'continue';
682
+ }
683
+ case '/effort': {
684
+ const host = state.host ?? (await Promise.resolve(hooks.ensureConnected()).catch(() => undefined));
685
+ const status = host?.status;
686
+ const activeProfile = resolveActiveProfileStatus(state, status);
687
+ const reasoningModel = activeProfile?.reasoningModel ?? status?.reasoningModel;
688
+ const supportedEfforts = activeProfile?.reasoningEfforts ?? status?.reasoningEfforts ?? [];
689
+ const currentMain = state.reasoningEffort ??
690
+ (state.profileDefaultReasoningEffort === undefined
691
+ ? (activeProfile?.reasoningEffort ?? status?.reasoningEffort ?? 'default')
692
+ : (state.profileDefaultReasoningEffort ?? 'default'));
693
+ if (!args.length) {
694
+ const lines = [
695
+ `当前思考强度: ${currentMain}${state.workerReasoningEffort ? ` · 子代理: ${state.workerReasoningEffort}` : ''}`,
696
+ supportedEfforts.length
697
+ ? `当前模型支持: ${supportedEfforts.join(', ')}, off`
698
+ : reasoningModel === false
699
+ ? '当前模型不支持可调思考强度'
700
+ : '当前模型支持: low, medium, high, max, off (以模型实际能力为准)',
701
+ ];
702
+ hooks.writeLine(lines.join('\n'));
703
+ return 'continue';
704
+ }
705
+ const isWorker = args[0]?.toLowerCase() === 'worker';
706
+ if (isWorker) {
707
+ const level = args[1]?.toLowerCase();
708
+ if (!level) {
709
+ hooks.writeLine(`当前子代理思考强度: ${state.workerReasoningEffort ?? '(follow default)'}`);
710
+ return 'continue';
711
+ }
712
+ if (args.length > 2) {
713
+ throw new Error('Usage: /effort worker <level|off|default>');
714
+ }
715
+ if (level === 'default' || level === 'clear') {
716
+ state.workerReasoningEffort = undefined;
717
+ markUserMutated(state, 'workerEffort');
718
+ const syncNotice = await persistGlobalDefaults(state, hooks, { workerReasoningEffort: null });
719
+ hooks.writeLine(`已恢复子代理默认思考强度 · ${syncNotice}`);
720
+ return 'continue';
721
+ }
722
+ if (level === 'off' || level === 'none') {
723
+ state.workerReasoningEffort = 'off';
724
+ markUserMutated(state, 'workerEffort');
725
+ const syncNotice = await persistGlobalDefaults(state, hooks, { workerReasoningEffort: 'off' });
726
+ hooks.writeLine(`已切换子代理思考强度为 off · ${syncNotice}`);
727
+ return 'continue';
728
+ }
729
+ if (reasoningModel === false) {
730
+ throw new Error('当前模型不支持调节思考强度');
731
+ }
732
+ if (supportedEfforts.length > 0 && !supportedEfforts.includes(level)) {
733
+ throw new Error(`当前模型不支持思考强度 "${level}",可选值:${supportedEfforts.join(', ')}, off`);
734
+ }
735
+ state.workerReasoningEffort = level;
736
+ markUserMutated(state, 'workerEffort');
737
+ const syncNotice = await persistGlobalDefaults(state, hooks, { workerReasoningEffort: level });
738
+ hooks.writeLine(`已切换子代理思考强度为 ${level} · ${syncNotice}`);
739
+ return 'continue';
740
+ }
741
+ if (args.length > 1) {
742
+ throw new Error('Usage: /effort [level|off|default] | /effort worker <level|off|default>');
743
+ }
744
+ const level = args[0].toLowerCase();
745
+ const hasHistory = Boolean(state.lastRunId || state.hasRunHistory);
746
+ const cacheHint = hasHistory ? '(提示:中途更改思考强度可能使下一次请求的提示词缓存失效)' : '';
747
+ if (level === 'default' || level === 'clear') {
748
+ state.reasoningEffort = undefined;
749
+ markUserMutated(state, 'effort');
750
+ const syncNotice = await persistGlobalDefaults(state, hooks, { reasoningEffort: null });
751
+ hooks.writeLine(`已恢复思考强度为默认${cacheHint} · ${syncNotice}`);
752
+ return 'continue';
753
+ }
754
+ if (level === 'off' || level === 'none') {
755
+ state.reasoningEffort = 'off';
756
+ markUserMutated(state, 'effort');
757
+ const syncNotice = await persistGlobalDefaults(state, hooks, { reasoningEffort: 'off' });
758
+ hooks.writeLine(`已切换思考强度为 off${cacheHint} · ${syncNotice}`);
759
+ return 'continue';
760
+ }
761
+ if (reasoningModel === false) {
762
+ throw new Error('当前模型不支持调节思考强度');
763
+ }
764
+ if (supportedEfforts.length > 0 && !supportedEfforts.includes(level)) {
765
+ throw new Error(`当前模型不支持思考强度 "${level}",可选值:${supportedEfforts.join(', ')}, off`);
766
+ }
767
+ state.reasoningEffort = level;
768
+ markUserMutated(state, 'effort');
769
+ const syncNotice = await persistGlobalDefaults(state, hooks, { reasoningEffort: level });
770
+ hooks.writeLine(`已切换思考强度为 ${level}${cacheHint} · ${syncNotice}`);
771
+ return 'continue';
772
+ }
773
+ case '/usage': {
774
+ const host = await hooks.ensureConnected();
775
+ const status = host?.status ?? state.host?.status;
776
+ const activeProfile = resolveActiveProfileStatus(state, status);
777
+ if (!state.sessionId) {
778
+ const emptyBucket = { inputTokens: 0, cachedInputTokens: 0, outputTokens: 0, reasoningTokens: 0 };
779
+ hooks.writeLine(renderUsageCard({
780
+ ...((activeProfile?.modelId ?? status?.modelId)
781
+ ? { modelId: activeProfile?.modelId ?? status?.modelId }
782
+ : {}),
783
+ ...((activeProfile?.contextWindow ?? status?.contextWindow)
784
+ ? { contextWindow: activeProfile?.contextWindow ?? status?.contextWindow }
785
+ : {}),
786
+ ...(activeProfile?.pricing ? { pricing: activeProfile.pricing } : {}),
787
+ ...(activeProfile?.pricingSource ? { pricingSource: activeProfile.pricingSource } : {}),
788
+ main: emptyBucket,
789
+ subagent: emptyBucket,
790
+ total: emptyBucket,
791
+ }));
792
+ return 'continue';
793
+ }
794
+ const usage = await sendHostCommand(state.workdir, {
795
+ type: 'session.usage',
796
+ sessionId: state.sessionId,
797
+ });
798
+ const resolvedModelId = usage.modelId ?? usage.model?.modelId ?? activeProfile?.modelId ?? status?.modelId;
799
+ hooks.writeLine(renderUsageCard({
800
+ ...usage,
801
+ ...(resolvedModelId ? { modelId: resolvedModelId } : {}),
802
+ ...(usage.contextWindow !== undefined
803
+ ? {}
804
+ : (activeProfile?.contextWindow ?? status?.contextWindow)
805
+ ? { contextWindow: activeProfile?.contextWindow ?? status?.contextWindow }
806
+ : {}),
807
+ ...(usage.pricing ? {} : activeProfile?.pricing ? { pricing: activeProfile.pricing } : {}),
808
+ ...(!usage.pricing && activeProfile?.pricingSource
809
+ ? { pricingSource: activeProfile.pricingSource }
810
+ : {}),
811
+ }));
812
+ return 'continue';
813
+ }
814
+ case '/new': {
815
+ await hooks.ensureConnected();
816
+ const workspaceId = await ensureWorkspaceId(state);
817
+ const title = args.join(' ').trim() || 'CLI session';
818
+ const created = await sendHostCommand(state.workdir, {
819
+ type: 'session.create',
820
+ workspaceId,
821
+ title,
822
+ });
823
+ selectSession(state, hooks, created.sessionId, {
824
+ id: created.sessionId,
825
+ runCount: 0,
826
+ turnCount: 0,
827
+ stepCount: 0,
828
+ todos: [],
829
+ });
830
+ hooks.writeLine(`Session ${created.sessionId}`);
831
+ return 'continue';
832
+ }
833
+ case '/session': {
834
+ const targetId = args[0];
835
+ if (!targetId) {
836
+ if (!state.sessionId) {
837
+ hooks.writeLine('Session: (none — created on first prompt)');
838
+ return 'continue';
839
+ }
840
+ await hooks.ensureConnected();
841
+ const info = await sendHostCommand(state.workdir, {
842
+ type: 'session.query',
843
+ sessionId: state.sessionId,
844
+ });
845
+ hooks.writeLine(`Session: ${state.sessionId}\nRuns: ${info.runCount ?? 0} · Main turns: ${info.turnCount ?? 0} · Steps: ${info.stepCount ?? 0}`);
846
+ return 'continue';
847
+ }
848
+ const navSignal = hooks.getNavigationSignal?.();
849
+ await hooks.ensureConnected();
850
+ await switchSession(state, hooks, targetId, navSignal);
851
+ return 'continue';
852
+ }
853
+ case '/attach': {
854
+ const parsed = parseArgs({
855
+ args,
856
+ allowPositionals: true,
857
+ strict: true,
858
+ options: {
859
+ after: { type: 'string' },
860
+ },
861
+ });
862
+ const runId = requireRunId(parsed.positionals[0], state);
863
+ const after = parsed.values.after ?? state.runCursors.get(runId) ?? '0';
864
+ await hooks.ensureConnected();
865
+ await hooks.followRun(runId, after);
866
+ return 'continue';
867
+ }
868
+ case '/resume': {
869
+ const target = args[0]?.trim();
870
+ if (!target && hooks.pickSession && !hooks.isPausedOrCheckpointedRun?.()) {
871
+ await hooks.ensureConnected();
872
+ const workspaceId = await ensureWorkspaceId(state);
873
+ const sessions = await sendHostCommand(state.workdir, {
874
+ type: 'session.list',
875
+ workspaceId,
876
+ limit: DEFAULT_SESSION_LIST_LIMIT,
877
+ });
878
+ if (!sessions.length) {
879
+ hooks.writeLine('当前工作区没有可恢复的历史会话。');
880
+ return 'continue';
881
+ }
882
+ const picked = await hooks.pickSession(sessions);
883
+ if (!picked)
884
+ return 'continue';
885
+ return handleSlashCommand('/session ' + picked, state, hooks);
886
+ }
887
+ const runId = target || requireRunId(undefined, state);
888
+ await hooks.ensureConnected();
889
+ if (target && target !== state.lastRunId) {
890
+ const session = await sendHostCommand(state.workdir, {
891
+ type: 'session.query',
892
+ sessionId: target,
893
+ }).catch((error) => {
894
+ if (error instanceof CliError && error.code === 'NOT_FOUND')
895
+ return undefined;
896
+ throw error;
897
+ });
898
+ if (session) {
899
+ hooks.checkSessionSwitch?.(session);
900
+ selectSession(state, hooks, target, session);
901
+ return 'continue';
902
+ }
903
+ }
904
+ const result = await sendHostCommand(state.workdir, { type: 'run.resume', runId });
905
+ state.lastRunId = result.runId;
906
+ await hooks.followRun(result.runId, state.runCursors.get(result.runId) ?? '0');
907
+ return 'continue';
908
+ }
909
+ case '/export': {
910
+ if (args.length > 1) {
911
+ throw new Error('Usage: /export [path]');
912
+ }
913
+ const targetSessionId = state.member?.parentSessionId ?? state.sessionId;
914
+ if (!targetSessionId) {
915
+ throw new Error('当前没有可导出的会话(请先发送一条消息或切换到已有会话)。');
916
+ }
917
+ await hooks.ensureConnected();
918
+ const exported = await exportSessionToJsonl({
919
+ workdir: state.workdir,
920
+ sessionId: targetSessionId,
921
+ outputPath: args[0],
922
+ sendCommand: (command) => sendHostCommand(state.workdir, command),
923
+ });
924
+ hooks.writeLine(`已导出会话 ${exported.sessionId} 至 ${exported.path}(${exported.count} 条记录,${formatByteSize(exported.bytes)})`);
925
+ return 'continue';
926
+ }
927
+ case '/cancel': {
928
+ const first = args[0];
929
+ let runId;
930
+ let reason;
931
+ if (first && looksLikeRunId(first, state.lastRunId)) {
932
+ runId = first;
933
+ reason = args.slice(1).join(' ').trim() || 'Cancelled from CLI';
934
+ }
935
+ else {
936
+ runId = requireRunId(undefined, state);
937
+ reason = args.join(' ').trim() || 'Cancelled from CLI';
938
+ }
939
+ await hooks.ensureConnected();
940
+ const result = await sendHostCommand(state.workdir, {
941
+ type: 'run.cancel',
942
+ runId,
943
+ reason,
944
+ });
945
+ hooks.writeLine(`Run ${result.runId} ${result.status ?? 'cancel_requested'}`);
946
+ return 'continue';
947
+ }
948
+ case '/approve':
949
+ case '/deny': {
950
+ const approved = cmd === '/approve';
951
+ const { positionals, values } = parseArgs({
952
+ args,
953
+ allowPositionals: true,
954
+ strict: true,
955
+ options: {
956
+ approval: { type: 'string' },
957
+ 'tool-call': { type: 'string' },
958
+ reason: { type: 'string' },
959
+ 'defer-resume': { type: 'boolean' },
960
+ },
961
+ });
962
+ if (positionals.length > 1)
963
+ throw new CliError('USAGE');
964
+ const runId = requireRunId(positionals[0], state);
965
+ await hooks.ensureConnected();
966
+ const deferResume = values['defer-resume'];
967
+ const resolved = await resolveRunApproval(state.workdir, runId, {
968
+ approvalId: values.approval,
969
+ toolCallId: values['tool-call'],
970
+ approved,
971
+ reason: values.reason,
972
+ deferResume,
973
+ });
974
+ if (!resolved) {
975
+ hooks.writeLine(`No pending approval found on run ${runId}.`);
976
+ return 'continue';
977
+ }
978
+ const { receipt: { approvalId }, toolCallId, } = resolved;
979
+ hooks.writeLine(`${approved ? 'Approved' : 'Denied'} ${approvalId} (${toolCallId}).`);
980
+ if (!deferResume) {
981
+ await hooks.followRun(runId, state.runCursors.get(runId) ?? '0');
982
+ }
983
+ return 'continue';
984
+ }
985
+ case '/reconcile': {
986
+ const { positionals, values } = parseArgs({
987
+ args,
988
+ allowPositionals: true,
989
+ strict: true,
990
+ options: reconciliationOptions,
991
+ });
992
+ if (positionals.length > 1)
993
+ throw new Error('/reconcile accepts at most one run ID');
994
+ const runId = requireRunId(positionals[0], state);
995
+ const command = reconciliationCommand(values);
996
+ if ('error' in command)
997
+ throw new Error(command.error);
998
+ await hooks.ensureConnected();
999
+ const { toolCallId } = await reconcileRunTool(state.workdir, runId, command);
1000
+ hooks.writeLine(`Reconciled tool call ${toolCallId}.`);
1001
+ return 'continue';
1002
+ }
1003
+ case '/compact': {
1004
+ let runId;
1005
+ let throughTurnId;
1006
+ let summary;
1007
+ if (args.some((arg) => arg.startsWith('--'))) {
1008
+ const { positionals, values } = parseArgs({
1009
+ args,
1010
+ allowPositionals: true,
1011
+ strict: true,
1012
+ options: compactionOptions,
1013
+ });
1014
+ if (positionals.length > 1)
1015
+ throw new Error(`Usage: /compact [RUN] ${compactionOptionUsage}`);
1016
+ [runId] = positionals;
1017
+ ({ 'through-turn': throughTurnId, summary } = values);
1018
+ }
1019
+ else if (args.length === 1 && looksLikeRunId(args[0], state.lastRunId)) {
1020
+ [runId] = args;
1021
+ }
1022
+ else {
1023
+ [throughTurnId] = args;
1024
+ summary = args.length > 1 ? args.slice(1).join(' ').trim() : undefined;
1025
+ }
1026
+ const parameters = compactionArguments({ 'through-turn': throughTurnId, summary });
1027
+ const target = requireRunId(runId, state);
1028
+ await hooks.ensureConnected();
1029
+ const result = await sendHostCommand(state.workdir, {
1030
+ type: 'surface.compact',
1031
+ runId: target,
1032
+ ...parameters,
1033
+ });
1034
+ hooks.writeLine(`Compaction ${result.compactionId} replaced=${result.replacedCount}`);
1035
+ return 'continue';
1036
+ }
1037
+ case '/model':
1038
+ case '/profile': {
1039
+ if (args.length > 1)
1040
+ throw new UsageError(`Usage: ${cmd} [profile]`);
1041
+ let target = args[0];
1042
+ let effort;
1043
+ let profileDefault;
1044
+ if (!target) {
1045
+ const host = state.host ?? (await hooks.ensureConnected().catch(() => undefined));
1046
+ const status = host?.status;
1047
+ const active = resolveActiveProfileStatus(state, status);
1048
+ const profiles = status?.profiles ?? [];
1049
+ if (!hooks.promptChoice || cmd === '/profile') {
1050
+ hooks.writeLine(`Active profile: ${active?.name ?? state.profile ?? '(host default)'}`);
1051
+ if (profiles.length)
1052
+ hooks.writeLine(`Available: ${profiles.map((p) => `${p.name} (${profileSummary(p)})`).join(', ')}`);
1053
+ return 'continue';
1054
+ }
1055
+ const available = profiles.filter((profile) => profile.ready !== false);
1056
+ if (!available.length) {
1057
+ hooks.writeLine('没有可用模型。使用 saturn provider add 添加模型,或用 /config check 查看配置。');
1058
+ return 'continue';
1059
+ }
1060
+ const selected = await hooks.promptChoice({
1061
+ title: '选择模型',
1062
+ options: available.map((profile) => ({
1063
+ id: profile.name,
1064
+ label: profile.name,
1065
+ meta: profileSummary(profile),
1066
+ current: profile.name === active?.name,
1067
+ })),
1068
+ });
1069
+ const profile = available.find((item) => item.name === selected);
1070
+ if (!profile)
1071
+ return 'continue';
1072
+ target = profile.name;
1073
+ effort = null;
1074
+ profileDefault = profileDefaultEffort(profile);
1075
+ if (supportsReasoning(profile)) {
1076
+ const levels = [
1077
+ ...new Set(profile.reasoningEfforts?.filter((level) => level !== 'off' && level !== 'none')),
1078
+ ];
1079
+ const current = (profile.name === active?.name
1080
+ ? (state.reasoningEffort ?? state.profileDefaultReasoningEffort ?? profile.reasoningEffort)
1081
+ : profileDefault) ?? undefined;
1082
+ effort = await hooks.promptChoice({
1083
+ title: '选择思考强度',
1084
+ subtitle: `${profile.name} · Esc 使用模型默认值`,
1085
+ options: [...levels, 'off'].map((level) => ({
1086
+ id: level,
1087
+ label: level,
1088
+ ...(level === 'off' ? { meta: '关闭思考' } : {}),
1089
+ current: (current === 'none' ? 'off' : current) === level,
1090
+ })),
1091
+ });
1092
+ }
1093
+ }
1094
+ if (effort === undefined && (target === 'clear' || target === 'default')) {
1095
+ state.profile = undefined;
1096
+ state.profileDefaultReasoningEffort = undefined;
1097
+ markUserMutated(state, 'profile');
1098
+ const syncNotice = await persistGlobalDefaults(state, hooks, { defaultProfile: null });
1099
+ hooks.writeLine(`Profile reset to host default. · ${syncNotice}`);
1100
+ return 'continue';
1101
+ }
1102
+ if (effort === undefined) {
1103
+ const profile = state.host?.status.profiles?.find((item) => item.name === target);
1104
+ if (profile) {
1105
+ const current = state.reasoningEffort;
1106
+ if (current &&
1107
+ current !== 'off' &&
1108
+ (profile.reasoningModel === false ||
1109
+ (profile.reasoningEfforts?.length && !profile.reasoningEfforts.includes(current))))
1110
+ effort = null;
1111
+ if (effort === null || state.profileDefaultReasoningEffort !== undefined)
1112
+ profileDefault = profileDefaultEffort(profile);
1113
+ }
1114
+ }
1115
+ state.profile = target;
1116
+ markUserMutated(state, 'profile');
1117
+ state.profileDefaultReasoningEffort = profileDefault;
1118
+ if (effort !== undefined) {
1119
+ state.reasoningEffort = effort ?? undefined;
1120
+ markUserMutated(state, 'effort');
1121
+ }
1122
+ const syncNotice = await persistGlobalDefaults(state, hooks, {
1123
+ defaultProfile: target,
1124
+ ...(effort === undefined ? {} : { reasoningEffort: effort }),
1125
+ });
1126
+ hooks.writeLine(`Profile set to ${target}.${effort !== undefined ? ` · 思考强度 ${effort ?? '默认'}` : ''} · ${syncNotice}`);
1127
+ return 'continue';
1128
+ }
1129
+ case '/mode': {
1130
+ const target = args[0];
1131
+ if (!target) {
1132
+ const host = await Promise.resolve(hooks.ensureConnected()).catch(() => state.host);
1133
+ const status = host?.status ?? state.host?.status;
1134
+ const active = status?.activeMode ?? state.activeMode;
1135
+ const activeLabel = active
1136
+ ? `${active.displayName} (${active.ref})`
1137
+ : (state.modeRef ?? DEFAULT_MODE_REF);
1138
+ hooks.writeLine(`Active mode: ${activeLabel}`);
1139
+ if (active?.description)
1140
+ hooks.writeLine(` ${active.description}`);
1141
+ const available = status?.availableModes ?? [];
1142
+ if (available.length) {
1143
+ hooks.writeLine('Available modes:');
1144
+ for (const item of available) {
1145
+ const mark = item.ref === active?.ref ? '* ' : ' ';
1146
+ hooks.writeLine(`${mark}${item.ref} — ${item.displayName}: ${item.description}`);
1147
+ }
1148
+ }
1149
+ return 'continue';
1150
+ }
1151
+ if (args.length > 1) {
1152
+ throw new Error('Usage: /mode [name|name@version]');
1153
+ }
1154
+ const normalizedInput = target === 'clear' || target === 'none' ? DEFAULT_MODE_REF : target;
1155
+ if (!modeSelectorPattern.test(normalizedInput)) {
1156
+ throw new Error('Mode 格式无效,请使用短名或版本化名称(如 ctf 或 ctf@1)');
1157
+ }
1158
+ if (hooks.isRunActive?.()) {
1159
+ throw new Error('当前有正在执行的任务,请等待完成或先 /cancel 后再切换 Mode');
1160
+ }
1161
+ if (state.lastRunId) {
1162
+ try {
1163
+ const run = await sendHostCommand(state.workdir, {
1164
+ type: 'run.query',
1165
+ runId: state.lastRunId,
1166
+ });
1167
+ if (run?.status && ['created', 'running', 'paused', 'cancelling'].includes(run.status)) {
1168
+ throw new Error('当前有正在执行的任务,请等待完成或先 /cancel 后再切换 Mode');
1169
+ }
1170
+ }
1171
+ catch (error) {
1172
+ if (error instanceof CliError && ['HOST_UNAVAILABLE', 'NOT_FOUND'].includes(error.code)) {
1173
+ // Host stopped or run absent; safe to switch mode.
1174
+ }
1175
+ else if (error instanceof Error && error.message.includes('正在执行的任务')) {
1176
+ throw error;
1177
+ }
1178
+ else if (!(error instanceof CliError)) {
1179
+ throw error;
1180
+ }
1181
+ }
1182
+ }
1183
+ const host = state.host ?? (await Promise.resolve(hooks.ensureConnected()).catch(() => undefined));
1184
+ const available = host?.status?.availableModes;
1185
+ const matched = resolveModeSelector(normalizedInput, available);
1186
+ if (available?.length && !matched) {
1187
+ throw new Error(`未知 Mode "${target}",可选:${available.map((item) => item.ref).join(', ')}`);
1188
+ }
1189
+ const resolvedRef = matched?.ref ?? normalizedInput;
1190
+ const currentRef = state.activeMode?.ref ?? host?.status?.activeMode?.ref;
1191
+ const persistedModeRef = target === 'clear' || target === 'none' ? null : resolvedRef;
1192
+ if (currentRef && resolvedRef === currentRef) {
1193
+ const currentSummary = state.activeMode ?? host?.status?.activeMode;
1194
+ const label = currentSummary ? `${currentSummary.displayName} (${currentSummary.ref})` : currentRef;
1195
+ markUserMutated(state, 'mode');
1196
+ const syncNotice = await persistGlobalDefaults(state, hooks, { modeRef: persistedModeRef });
1197
+ hooks.writeLine(`当前已处于模式: ${label} · ${syncNotice}`);
1198
+ return 'continue';
1199
+ }
1200
+ const nextStatus = hooks.switchMode ? await hooks.switchMode(resolvedRef) : undefined;
1201
+ applyReplMode(state, nextStatus?.activeMode ?? matched, resolvedRef);
1202
+ markUserMutated(state, 'mode');
1203
+ const syncNotice = await persistGlobalDefaults(state, hooks, {
1204
+ modeRef: target === 'clear' || target === 'none' ? null : (state.activeMode?.ref ?? resolvedRef),
1205
+ });
1206
+ const label = state.activeMode
1207
+ ? `${state.activeMode.displayName} (${state.activeMode.ref})`
1208
+ : state.modeRef;
1209
+ hooks.writeLine(`已切换至模式: ${label} · ${syncNotice}`);
1210
+ if (nextStatus?.boardUrl) {
1211
+ hooks.writeLine(`Board: ${nextStatus.boardUrl}`);
1212
+ }
1213
+ return 'continue';
1214
+ }
1215
+ case '/skill': {
1216
+ const action = (args[0] ?? 'list').toLowerCase();
1217
+ const ref = args[1];
1218
+ const host = state.host ?? (await Promise.resolve(hooks.ensureConnected()).catch(() => undefined));
1219
+ const discovered = host?.status?.discoveredSkills ?? (await discoverAgentSkills(state.workdir));
1220
+ const disabled = (state.disabledSkills ??= []);
1221
+ if (action === 'list') {
1222
+ const lines = [];
1223
+ if (discovered.length) {
1224
+ lines.push('Discovered skills:');
1225
+ for (const item of discovered) {
1226
+ const active = !disabled.includes(item.name);
1227
+ const marker = active ? '✓' : '○';
1228
+ const res = item.resources.length ? ` (${item.resources.length} resources)` : '';
1229
+ lines.push(` ${marker} [${item.scope}] ${item.name} — ${item.description}${res}${active ? '' : ' [disabled]'}`);
1230
+ }
1231
+ }
1232
+ else {
1233
+ lines.push('Discovered skills: (none)');
1234
+ }
1235
+ if (state.skillRefs.length) {
1236
+ lines.push(`Pinned versioned skills: ${state.skillRefs.join(', ')}`);
1237
+ }
1238
+ hooks.writeLine(lines.join('\n'));
1239
+ return 'continue';
1240
+ }
1241
+ if (action === 'show' || action === 'info') {
1242
+ if (!ref)
1243
+ throw new Error('Usage: /skill show <name>');
1244
+ const found = discovered.find((item) => item.name === ref);
1245
+ if (!found)
1246
+ throw new Error(`Skill "${ref}" not found.`);
1247
+ const active = !disabled.includes(found.name);
1248
+ const lines = [
1249
+ `Skill: ${found.name} [${found.scope}] (${active ? 'enabled' : 'disabled'})`,
1250
+ `Source: ${found.source}`,
1251
+ `Description: ${found.description}`,
1252
+ ...(found.license ? [`License: ${found.license}`] : []),
1253
+ ...(found.compatibility ? [`Compatibility: ${found.compatibility}`] : []),
1254
+ `Resources (${found.resources.length}): ${found.resources.length ? found.resources.join(', ') : '(none)'}`,
1255
+ ];
1256
+ hooks.writeLine(lines.join('\n'));
1257
+ return 'continue';
1258
+ }
1259
+ if (action === 'toggle' || action === 'enable' || action === 'disable') {
1260
+ if (!ref)
1261
+ throw new Error(`Usage: /skill ${action} <name>`);
1262
+ const found = discovered.find((item) => item.name === ref);
1263
+ if (!found)
1264
+ throw new Error(`Skill "${ref}" not found.`);
1265
+ const idx = disabled.indexOf(found.name);
1266
+ const currentlyDisabled = idx >= 0;
1267
+ const shouldEnable = action === 'enable' ? true : action === 'disable' ? false : currentlyDisabled;
1268
+ if (shouldEnable && idx >= 0)
1269
+ disabled.splice(idx, 1);
1270
+ if (!shouldEnable && idx < 0)
1271
+ disabled.push(found.name);
1272
+ hooks.writeLine(`Skill "${found.name}" [${found.scope}] ${shouldEnable ? 'enabled' : 'disabled'} for this session.`);
1273
+ return 'continue';
1274
+ }
1275
+ if (action === 'clear') {
1276
+ state.skillRefs.length = 0;
1277
+ disabled.length = 0;
1278
+ hooks.writeLine('Reset skill selection (all discovered skills enabled; pinned refs cleared).');
1279
+ return 'continue';
1280
+ }
1281
+ if (action === 'add') {
1282
+ if (!ref)
1283
+ throw new Error('Usage: /skill add <name | name@version>');
1284
+ const discoveredMatch = discovered.find((item) => item.name === ref);
1285
+ if (discoveredMatch && !contextExtensionRefPattern.test(ref)) {
1286
+ const idx = disabled.indexOf(discoveredMatch.name);
1287
+ if (idx >= 0)
1288
+ disabled.splice(idx, 1);
1289
+ hooks.writeLine(`Skill "${discoveredMatch.name}" [${discoveredMatch.scope}] enabled.`);
1290
+ return 'continue';
1291
+ }
1292
+ if (!contextExtensionRefPattern.test(ref)) {
1293
+ throw new Error('Usage: /skill add <name | name@version>');
1294
+ }
1295
+ if (!state.skillRefs.includes(ref))
1296
+ state.skillRefs.push(ref);
1297
+ hooks.writeLine(`Active skills: ${state.skillRefs.join(', ')}`);
1298
+ return 'continue';
1299
+ }
1300
+ if (action === 'remove') {
1301
+ if (!ref)
1302
+ throw new Error('Usage: /skill remove <name | name@version>');
1303
+ const index = state.skillRefs.indexOf(ref);
1304
+ if (index >= 0) {
1305
+ state.skillRefs.splice(index, 1);
1306
+ hooks.writeLine(`Active skills: ${state.skillRefs.length ? state.skillRefs.join(', ') : '(none)'}`);
1307
+ return 'continue';
1308
+ }
1309
+ const discoveredMatch = discovered.find((item) => item.name === ref);
1310
+ if (discoveredMatch) {
1311
+ if (!disabled.includes(discoveredMatch.name))
1312
+ disabled.push(discoveredMatch.name);
1313
+ hooks.writeLine(`Skill "${discoveredMatch.name}" disabled for this session.`);
1314
+ return 'continue';
1315
+ }
1316
+ hooks.writeLine(`Active skills: ${state.skillRefs.length ? state.skillRefs.join(', ') : '(none)'}`);
1317
+ return 'continue';
1318
+ }
1319
+ throw new Error('Usage: /skill [list|show|toggle|enable|disable|add|remove|clear] [name|ref]');
1320
+ }
1321
+ case '/mcp': {
1322
+ const action = (args[0] ?? 'list').toLowerCase();
1323
+ const target = args[1];
1324
+ const trust = action === 'trust' || action === 'enable';
1325
+ const untrust = action === 'untrust' || action === 'disable';
1326
+ if (trust || untrust || action === 'auth') {
1327
+ if (hooks.isRunActive?.()) {
1328
+ throw new Error('当前有正在执行的任务,请等待完成或先 /cancel 后再变更 MCP 设置');
1329
+ }
1330
+ if (state.lastRunId) {
1331
+ try {
1332
+ const run = await sendHostCommand(state.workdir, {
1333
+ type: 'run.query',
1334
+ runId: state.lastRunId,
1335
+ });
1336
+ if (run?.status && ['created', 'running', 'paused', 'cancelling'].includes(run.status)) {
1337
+ throw new Error('当前有正在执行的任务,请等待完成或先 /cancel 后再变更 MCP 设置');
1338
+ }
1339
+ }
1340
+ catch (error) {
1341
+ if (error instanceof CliError && ['HOST_UNAVAILABLE', 'NOT_FOUND'].includes(error.code)) {
1342
+ // Safe to proceed when Host is stopped or run is absent.
1343
+ }
1344
+ else if (error instanceof Error && error.message.includes('正在执行的任务')) {
1345
+ throw error;
1346
+ }
1347
+ else if (!(error instanceof CliError)) {
1348
+ throw error;
1349
+ }
1350
+ }
1351
+ }
1352
+ if (action === 'auth') {
1353
+ if (!hooks.promptMcpSecret || !hooks.restartHost)
1354
+ throw new UsageError('MCP 授权需要交互式终端,请运行 saturn mcp auth <name>。');
1355
+ const before = state.host?.status;
1356
+ const result = await authenticateMcpServer(state.workdir, args.slice(1), {
1357
+ prompt: hooks.promptMcpSecret,
1358
+ ...(before ? { before } : {}),
1359
+ restart: hooks.restartHost,
1360
+ });
1361
+ hooks.writeLine(result ? formatMcpServerStatus(result.server) : '已取消 MCP 授权。');
1362
+ return 'continue';
1363
+ }
1364
+ await setWorkspaceMcpTrust(state.workdir, trust);
1365
+ const nextStatus = hooks.restartHost ? await hooks.restartHost() : undefined;
1366
+ const info = await listMcpServersInfo(state.workdir, nextStatus ?? state.host?.status);
1367
+ const lines = [
1368
+ trust
1369
+ ? `已信任当前工作区 (${state.workdir}) 的 .mcp.json${hooks.restartHost ? ',Host 已重新加载。' : '(下次启动 Host 时生效)。'}`
1370
+ : `已撤销当前工作区 (${state.workdir}) 的 .mcp.json 信任${hooks.restartHost ? ',Host 已重新加载。' : '。'}`,
1371
+ ];
1372
+ for (const srv of info.servers)
1373
+ lines.push(' - ' + formatMcpServerStatus(srv));
1374
+ hooks.writeLine(lines.join('\n'));
1375
+ return 'continue';
1376
+ }
1377
+ const host = state.host ?? (await Promise.resolve(hooks.ensureConnected()).catch(() => undefined));
1378
+ const info = await listMcpServersInfo(state.workdir, host?.status);
1379
+ if (action === 'show' || action === 'get') {
1380
+ if (!target)
1381
+ throw new Error('Usage: /mcp show <name>');
1382
+ const srv = info.servers.find((item) => item.id === target);
1383
+ if (!srv)
1384
+ throw new Error(`MCP server "${target}" not found.`);
1385
+ hooks.writeLine([
1386
+ `MCP ${srv.id} [${srv.scope}] (${srv.config.transport})`,
1387
+ ` status: ${srv.status}${srv.status === 'ready' && srv.toolCount !== undefined ? ` (${srv.toolCount} tools)` : ''}`,
1388
+ ` source: ${srv.source}`,
1389
+ ` config: ${JSON.stringify(srv.config)}`,
1390
+ ...(srv.error ? [` error: ${srv.error}`] : []),
1391
+ ].join('\n'));
1392
+ return 'continue';
1393
+ }
1394
+ if (action === 'list' || action === 'status') {
1395
+ if (!info.servers.length && !info.mcpJsonError) {
1396
+ hooks.writeLine('MCP servers: (none configured). Use `saturn mcp add` or add `.mcp.json`.');
1397
+ return 'continue';
1398
+ }
1399
+ const lines = ['MCP servers:'];
1400
+ let hasPendingTrust = false;
1401
+ for (const srv of info.servers) {
1402
+ if (srv.status === 'pending_trust')
1403
+ hasPendingTrust = true;
1404
+ lines.push(' - ' + formatMcpServerStatus(srv));
1405
+ }
1406
+ if (info.mcpJsonError) {
1407
+ lines.push(` - [project] .mcp.json · error: ${info.mcpJsonError}`);
1408
+ }
1409
+ if (hasPendingTrust) {
1410
+ lines.push('提示: 检测到未信任工作区的 .mcp.json 服务,输入 `/mcp trust` 可信任并启用它们。');
1411
+ }
1412
+ hooks.writeLine(lines.join('\n'));
1413
+ return 'continue';
1414
+ }
1415
+ throw new Error('Usage: /mcp [list|status|trust|untrust|show <name>|auth <name> [--header NAME]]');
1416
+ }
1417
+ case '/config': {
1418
+ const sub = (args[0] ?? 'show').toLowerCase();
1419
+ if (sub === 'init') {
1420
+ const force = args.includes('--force');
1421
+ const result = await initUserConfig(force);
1422
+ hooks.writeLine(renderConfigInit(result));
1423
+ return 'continue';
1424
+ }
1425
+ if (sub === 'show' || sub === 'check') {
1426
+ const inspection = await inspectUserConfig(state.workdir);
1427
+ let status;
1428
+ try {
1429
+ status = await sendHostCommand(state.workdir, { type: 'host.status' });
1430
+ }
1431
+ catch {
1432
+ // Host may be stopped; still show file existence inspection.
1433
+ }
1434
+ hooks.writeLine(sub === 'check' ? renderConfigCheck(inspection, status) : renderConfigSummary(inspection, status));
1435
+ return 'continue';
1436
+ }
1437
+ throw new Error('Usage: /config [show|check|init] [--force]');
1438
+ }
1439
+ case '/shutdown': {
1440
+ await stopHost(state.workdir, state.host);
1441
+ state.host = undefined;
1442
+ hooks.writeLine('Host stopped.');
1443
+ return 'continue';
1444
+ }
1445
+ default:
1446
+ hooks.writeLine(`Unknown command: ${command}. Type /help for available commands.`);
1447
+ return 'continue';
1448
+ }
1449
+ }