@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.
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
package/dist/repl.js ADDED
@@ -0,0 +1,1834 @@
1
+ import path from 'node:path';
2
+ import { createInterface } from 'node:readline/promises';
3
+ import { isTerminalRunEventType, MAX_SESSION_HISTORY_PAGE_SIZE, mergeAgentContextMetrics, } from '@saturn-universe/protocol';
4
+ import { formatDuration } from './duration.js';
5
+ import { CliError, formatDiagnosticReference } from './cli-diagnostics.js';
6
+ import { approvalCommand, sendHostCommand } from './host-command.js';
7
+ import { createReplHostConnection } from './repl-host.js';
8
+ import { createReplRunObserver } from './repl-run-observer.js';
9
+ import { renderApprovalPrompt, renderAssistantText, renderBanner, renderConversationEvent, renderProgressEvent, renderUnifiedToolBlock, } from './renderer.js';
10
+ import { createSessionHistoryLoader, historyEntryKey, messageEntryKey } from './session-history.js';
11
+ import { SLASH_COMMAND_HINTS, SLASH_COMMAND_NAMES, ensureSessionId, ensureWorkspaceId, handleSlashCommand, } from './slash-commands.js';
12
+ import { createOrbitalTui } from './tui.js';
13
+ function replSubmission(state, runOptions, target) {
14
+ const config = {};
15
+ if (target.streamText)
16
+ config.streamText = target.streamText;
17
+ if (target.modeRef)
18
+ config.modeRef = target.modeRef;
19
+ if (runOptions.team)
20
+ config.team = { ...runOptions.team, members: [...runOptions.team.members] };
21
+ const reasoningEffort = state.reasoningEffort ?? state.profileDefaultReasoningEffort;
22
+ if (reasoningEffort !== undefined) {
23
+ config.responses = {
24
+ storage: 'local_stateless',
25
+ ...(reasoningEffort && reasoningEffort !== 'off' ? { reasoning: { effort: reasoningEffort } } : {}),
26
+ };
27
+ }
28
+ if (state.workerReasoningEffort !== undefined)
29
+ config.workerReasoningEffort = state.workerReasoningEffort;
30
+ if (state.disabledSkills?.length)
31
+ config.disabledSkills = [...state.disabledSkills];
32
+ return {
33
+ workspaceId: target.workspaceId,
34
+ sessionId: target.sessionId,
35
+ permissionMode: state.permissionMode,
36
+ content: [{ type: 'text', text: runOptions.text }],
37
+ ...(state.profile ? { profile: state.profile } : {}),
38
+ ...(state.taskProfile ? { taskProfile: state.taskProfile } : {}),
39
+ ...(Object.keys(config).length ? { config } : {}),
40
+ ...(state.skillRefs.length ? { skillRefs: [...state.skillRefs] } : {}),
41
+ ...(runOptions.teamHint ? { teamHint: runOptions.teamHint } : {}),
42
+ ...(runOptions.teamPreset ? { teamPreset: runOptions.teamPreset } : {}),
43
+ };
44
+ }
45
+ function quoteShellArg(value) {
46
+ return /[\s"'$&|<>()^;!*?~]/.test(value) ? `"${value.replace(/"/g, '\\"')}"` : value;
47
+ }
48
+ export function formatResumeCommand(workdir, sessionId, cwd = process.cwd()) {
49
+ const resolvedWorkdir = path.resolve(workdir);
50
+ const resolvedCwd = path.resolve(cwd);
51
+ const isSameDir = process.platform === 'win32'
52
+ ? resolvedWorkdir.toLowerCase() === resolvedCwd.toLowerCase()
53
+ : resolvedWorkdir === resolvedCwd;
54
+ const sid = quoteShellArg(sessionId);
55
+ if (isSameDir) {
56
+ return `saturn --session ${sid}`;
57
+ }
58
+ return `saturn -C ${quoteShellArg(workdir)} --session ${sid}`;
59
+ }
60
+ function writeOut(text) {
61
+ process.stdout.write(text);
62
+ }
63
+ function writeLine(text) {
64
+ process.stdout.write(text + '\n');
65
+ }
66
+ function formatCliError(error) {
67
+ if (error instanceof CliError) {
68
+ if (error.code === 'CREDENTIAL_UNAVAILABLE') {
69
+ return `Error: ${error.code} (diagnosticId=${error.diagnosticId}). Configure credentials in ~/.saturn/credentials.toml or run \`/config check\`.`;
70
+ }
71
+ if (error.code === 'MODE_MISMATCH') {
72
+ return `Error: MODE_MISMATCH (diagnosticId=${error.diagnosticId}). 当前工作区 Host 运行在其他 Mode 下;请使用 \`/mode <target>\` 切换或重启 Host。`;
73
+ }
74
+ if (error.code === 'SANDBOX_UNAVAILABLE' || error.code === 'SANDBOX_IMAGE_MISSING') {
75
+ return `Error: ${error.code} (diagnosticId=${error.diagnosticId}). Sandbox runtime or image is unavailable; build images via docker/sandboxes/build.sh or pass --allow-unsafe-sandbox-fallback for local debugging.`;
76
+ }
77
+ return `Error: ${formatDiagnosticReference(error)}`;
78
+ }
79
+ if (error instanceof Error)
80
+ return `Error: ${error.message}`;
81
+ return 'Error: Command failed';
82
+ }
83
+ function activeRestartMessage(targetMode) {
84
+ const operation = targetMode === undefined ? '重启 Host' : '切换 Mode';
85
+ return `当前有正在执行的任务,请等待完成或先 /cancel 后再${operation}`;
86
+ }
87
+ function createApprovalQueue(root, prompt, report) {
88
+ let pending = [];
89
+ let active;
90
+ let work;
91
+ let resolved = 0;
92
+ let receivedSnapshot = false;
93
+ const shown = new Set();
94
+ async function drain() {
95
+ for (;;) {
96
+ const approval = pending.find(({ approvalId }) => !shown.has(approvalId));
97
+ if (!approval)
98
+ return;
99
+ const { approvalId, toolCallId, toolName } = approval;
100
+ const controller = new AbortController();
101
+ active = { approvalId, controller };
102
+ shown.add(approvalId);
103
+ try {
104
+ const decision = await prompt(approval, controller.signal);
105
+ if (controller.signal.aborted)
106
+ continue;
107
+ if (decision === null || decision === 'd') {
108
+ report(`[Deferred] ${toolName}. Use /approve or /deny later.`);
109
+ continue;
110
+ }
111
+ const approved = decision === 'y';
112
+ await sendHostCommand(root, approvalCommand({ approvalId, toolCallId }, { approved, reason: approved ? 'Approved in CLI' : 'Denied in CLI' }));
113
+ resolved++;
114
+ report(` ${approved ? 'Approved' : 'Denied'} ${toolName}.`);
115
+ }
116
+ catch (error) {
117
+ if (!controller.signal.aborted)
118
+ report(formatCliError(error));
119
+ }
120
+ finally {
121
+ active = undefined;
122
+ }
123
+ }
124
+ }
125
+ function update(snapshot) {
126
+ pending = snapshot;
127
+ if (active && !pending.some(({ approvalId }) => approvalId === active.approvalId))
128
+ active.controller.abort();
129
+ if (!work && pending.some(({ approvalId }) => !shown.has(approvalId))) {
130
+ work = drain().finally(() => {
131
+ work = undefined;
132
+ update(pending);
133
+ });
134
+ }
135
+ }
136
+ return {
137
+ observe(snapshot) {
138
+ if (!snapshot)
139
+ return;
140
+ receivedSnapshot = true;
141
+ update(snapshot);
142
+ },
143
+ async finishPause(runId, reason, signal) {
144
+ if (!receivedSnapshot && reason === 'approval') {
145
+ const details = await sendHostCommand(root, { type: 'run.query', runId }, { signal });
146
+ if (signal.aborted)
147
+ return;
148
+ update((details.tools ?? []).flatMap(({ call, memberId, approval }) => {
149
+ if (approval?.status !== 'pending')
150
+ return [];
151
+ return [
152
+ {
153
+ toolCallId: call.id,
154
+ toolName: call.toolName,
155
+ approvalId: approval.request.approvalId,
156
+ resources: approval.request.resources ?? [],
157
+ reason: approval.request.reason ?? '',
158
+ ...(memberId ? { memberId } : {}),
159
+ },
160
+ ];
161
+ }));
162
+ }
163
+ await work;
164
+ },
165
+ get resolved() {
166
+ return resolved;
167
+ },
168
+ async close() {
169
+ update([]);
170
+ await work;
171
+ },
172
+ };
173
+ }
174
+ function isSessionScopedEvent(type) {
175
+ return type.startsWith('model.') || type.startsWith('message.') || type.startsWith('tool.call.');
176
+ }
177
+ export function showTeamEvent(event, member) {
178
+ if (event.type.startsWith('tool.approval.'))
179
+ return true;
180
+ if (event.type === 'run.team.message.sent')
181
+ return member ? event.to === member.id || event.from === member.id : event.to === 'main';
182
+ if (member) {
183
+ if (event.agentSessionId)
184
+ return event.agentSessionId === member.agentSessionId;
185
+ if (event.memberId)
186
+ return event.memberId === member.id;
187
+ return !isSessionScopedEvent(event.type);
188
+ }
189
+ return !event.memberId || event.memberId === 'main' || event.memberId === 'planner';
190
+ }
191
+ function activeModeRef(state, status) {
192
+ return status?.activeMode?.ref ?? state.activeMode?.ref ?? state.modeRef;
193
+ }
194
+ function hydrateDefaultsFromStatus(state, status) {
195
+ const defaults = status?.runDefaults;
196
+ if (!defaults)
197
+ return;
198
+ const mutated = state.userMutatedDefaults;
199
+ if (!mutated?.has('permission') && defaults.permissionMode) {
200
+ state.permissionMode = defaults.permissionMode;
201
+ }
202
+ if (!mutated?.has('effort') &&
203
+ state.reasoningEffort === undefined &&
204
+ defaults.reasoningEffort !== undefined) {
205
+ state.reasoningEffort = defaults.reasoningEffort;
206
+ }
207
+ if (!mutated?.has('workerEffort') &&
208
+ state.workerReasoningEffort === undefined &&
209
+ defaults.workerReasoningEffort !== undefined) {
210
+ state.workerReasoningEffort = defaults.workerReasoningEffort;
211
+ }
212
+ }
213
+ function resolveProfileTelemetry(state, status, running) {
214
+ const profiles = status?.profiles ?? [];
215
+ const activeName = state.profile ??
216
+ (state.taskProfile ? status?.taskProfiles?.[state.taskProfile] : undefined) ??
217
+ status?.selectedProfile ??
218
+ status?.defaultProfile;
219
+ const active = profiles.find((item) => item.name === activeName);
220
+ const profileName = active?.name ?? state.profile ?? 'no profile';
221
+ const modelId = running?.modelId ?? active?.modelId ?? status?.modelId;
222
+ const effort = running
223
+ ? running.reasoningEffort
224
+ : (state.reasoningEffort ??
225
+ (state.profileDefaultReasoningEffort === undefined
226
+ ? (active?.reasoningEffort ?? status?.reasoningEffort)
227
+ : (state.profileDefaultReasoningEffort ?? (active?.reasoningModel ? 'auto' : undefined))));
228
+ const availableReasoningEfforts = active?.reasoningEfforts ?? status?.reasoningEfforts;
229
+ const contextWindow = active?.contextWindow ?? status?.contextWindow;
230
+ const profileLabel = modelId ? [modelId, effort].filter(Boolean).join(' · ').toUpperCase() : '—';
231
+ const credReady = Boolean(running || (active ? active.ready !== false : status?.modelId));
232
+ let warning;
233
+ if (status) {
234
+ if (status.sandbox?.fallbackActive) {
235
+ warning = `UNSAFE SANDBOX FALLBACK (${status.sandbox.backend} → host)`;
236
+ }
237
+ else if (!profiles.length && !status.modelId) {
238
+ warning = 'No profile configured · run /config init';
239
+ }
240
+ else if (active && active.ready === false) {
241
+ warning = `Missing credential for ${active.name} · /config check`;
242
+ }
243
+ }
244
+ return {
245
+ profileLabel,
246
+ profileName,
247
+ modelId,
248
+ reasoningEffort: effort,
249
+ workerReasoningEffort: state.workerReasoningEffort,
250
+ availableReasoningEfforts,
251
+ contextWindow,
252
+ credReady,
253
+ workspaceTools: Boolean(status?.workspaceTools),
254
+ warning,
255
+ };
256
+ }
257
+ function eventEntryKind(event) {
258
+ switch (event.type) {
259
+ case 'run.search.started':
260
+ case 'run.search.branch.created':
261
+ case 'run.search.branch.evaluated':
262
+ case 'run.search.converged':
263
+ return 'planner';
264
+ case 'run.team.planned':
265
+ case 'run.team.message.sent':
266
+ return 'team';
267
+ case 'message.assistant.added':
268
+ return event.memberId && event.memberId !== 'main' ? 'team' : 'assistant';
269
+ case 'model.responded':
270
+ return event.text?.trim() ? 'thinking' : 'system';
271
+ case 'tool.call.requested':
272
+ case 'tool.call.started':
273
+ return 'tool';
274
+ case 'tool.call.denied':
275
+ case 'tool.call.rejected':
276
+ case 'tool.call.failed':
277
+ return 'error';
278
+ case 'tool.call.settled': {
279
+ const isCommand = event.toolName === 'run_process' || event.toolName === 'run_readonly_command';
280
+ const nonZeroCommand = isCommand && Boolean(event.exitSignal || (event.exitCode !== undefined && event.exitCode !== 0));
281
+ if (nonZeroCommand || event.toolStatus === 'success' || event.toolStatus === 'cancelled')
282
+ return 'tool';
283
+ return 'error';
284
+ }
285
+ case 'tool.call.outcome_unknown':
286
+ return 'error';
287
+ case 'tool.approval.requested':
288
+ case 'tool.approval.resolved':
289
+ return 'approval';
290
+ case 'run.failed':
291
+ case 'turn.failed':
292
+ case 'step.failed':
293
+ case 'model.failed':
294
+ return 'error';
295
+ default:
296
+ return 'system';
297
+ }
298
+ }
299
+ function initialReplState(options) {
300
+ return {
301
+ workdir: options.workdir,
302
+ ...(options.sessionId ? { sessionId: options.sessionId } : {}),
303
+ ...(options.profile ? { profile: options.profile } : {}),
304
+ ...(options.taskProfile ? { taskProfile: options.taskProfile } : {}),
305
+ ...(options.modeRef ? { modeRef: options.modeRef } : {}),
306
+ skillRefs: [...(options.skillRefs ?? [])],
307
+ permissionMode: 'default',
308
+ runCursors: new Map(),
309
+ };
310
+ }
311
+ async function runPipedRepl(options, hostOptions) {
312
+ const state = initialReplState(options);
313
+ const connection = createReplHostConnection(state, hostOptions);
314
+ let initialHost;
315
+ try {
316
+ initialHost = connection.accept(await connection.launch());
317
+ }
318
+ catch (error) {
319
+ process.stderr.write(formatCliError(error) + '\n');
320
+ process.exitCode = error instanceof CliError && error.code.startsWith('HOST_') ? 3 : 1;
321
+ return;
322
+ }
323
+ hydrateDefaultsFromStatus(state, initialHost.status);
324
+ async function printMemberHistory() {
325
+ if (!state.member)
326
+ return;
327
+ const { parentSessionId, agentSessionId, id } = state.member;
328
+ const page = await sendHostCommand(state.workdir, {
329
+ type: 'session.history',
330
+ sessionId: parentSessionId,
331
+ agentSessionId,
332
+ limit: MAX_SESSION_HISTORY_PAGE_SIZE,
333
+ });
334
+ writeLine('团队成员 ' + id);
335
+ for (const { role, text } of page.messages)
336
+ writeLine('[' + role + '] ' + text);
337
+ }
338
+ if (state.sessionId) {
339
+ try {
340
+ const session = await sendHostCommand(state.workdir, {
341
+ type: 'session.query',
342
+ sessionId: state.sessionId,
343
+ });
344
+ state.member = session.member;
345
+ if (session.member)
346
+ state.lastRunId = session.latestRun?.id;
347
+ await printMemberHistory();
348
+ }
349
+ catch (error) {
350
+ writeLine(formatCliError(error));
351
+ }
352
+ }
353
+ const buildBanner = () => renderBanner({
354
+ workdir: state.workdir,
355
+ sessionId: state.sessionId,
356
+ profile: state.profile,
357
+ skillRefs: state.skillRefs,
358
+ status: state.host?.status ?? initialHost.status,
359
+ ownedHost: state.host?.owned ?? initialHost.owned,
360
+ });
361
+ writeOut(buildBanner());
362
+ let inputClosed = false;
363
+ let exitRequested = false;
364
+ const runObserver = createReplRunObserver(state.workdir, state.runCursors);
365
+ let sigintArmed = false;
366
+ let sigintTimer;
367
+ const lineQueue = [];
368
+ let lineWaiter;
369
+ const disarmSigint = () => {
370
+ sigintArmed = false;
371
+ if (sigintTimer) {
372
+ clearTimeout(sigintTimer);
373
+ sigintTimer = undefined;
374
+ }
375
+ };
376
+ const rl = createInterface({
377
+ input: process.stdin,
378
+ output: process.stdout,
379
+ terminal: false,
380
+ historySize: 200,
381
+ completer: (line) => {
382
+ if (!line.startsWith('/'))
383
+ return [[], line];
384
+ const matches = SLASH_COMMAND_NAMES.filter((name) => name.startsWith(line));
385
+ return [matches.length ? matches : [...SLASH_COMMAND_NAMES], line];
386
+ },
387
+ });
388
+ rl.on('line', (line) => {
389
+ disarmSigint();
390
+ if (lineWaiter) {
391
+ const resolve = lineWaiter;
392
+ lineWaiter = undefined;
393
+ resolve(line);
394
+ }
395
+ else {
396
+ lineQueue.push(line);
397
+ }
398
+ });
399
+ rl.once('close', () => {
400
+ disarmSigint();
401
+ inputClosed = true;
402
+ runObserver.close();
403
+ if (lineWaiter) {
404
+ const resolve = lineWaiter;
405
+ lineWaiter = undefined;
406
+ resolve(null);
407
+ }
408
+ });
409
+ const onSigint = () => {
410
+ if (runObserver.detach()) {
411
+ disarmSigint();
412
+ return;
413
+ }
414
+ if (sigintArmed) {
415
+ disarmSigint();
416
+ exitRequested = true;
417
+ rl.close();
418
+ return;
419
+ }
420
+ sigintArmed = true;
421
+ writeLine('\n再按一次 Ctrl+C 退出(或输入 /exit)');
422
+ sigintTimer = setTimeout(() => {
423
+ sigintArmed = false;
424
+ sigintTimer = undefined;
425
+ }, 2000);
426
+ sigintTimer.unref();
427
+ };
428
+ rl.on('SIGINT', onSigint);
429
+ process.on('SIGINT', onSigint);
430
+ async function promptLine(prompt, signal) {
431
+ if (exitRequested || signal?.aborted)
432
+ return null;
433
+ if (!inputClosed) {
434
+ rl.setPrompt(prompt);
435
+ rl.prompt();
436
+ }
437
+ if (lineQueue.length > 0)
438
+ return lineQueue.shift();
439
+ if (inputClosed)
440
+ return null;
441
+ return new Promise((resolve) => {
442
+ const abort = () => {
443
+ lineWaiter = undefined;
444
+ resolve(null);
445
+ };
446
+ signal?.addEventListener('abort', abort, { once: true });
447
+ lineWaiter = (line) => {
448
+ signal?.removeEventListener('abort', abort);
449
+ resolve(line);
450
+ };
451
+ });
452
+ }
453
+ async function ensureConnected() {
454
+ if (state.host) {
455
+ try {
456
+ await connection.refreshStatus();
457
+ if (state.host)
458
+ return state.host;
459
+ }
460
+ catch (error) {
461
+ if (!(error instanceof CliError) || error.code !== 'HOST_UNAVAILABLE')
462
+ throw error;
463
+ state.host = undefined;
464
+ }
465
+ }
466
+ const launched = connection.accept(await connection.launch());
467
+ hydrateDefaultsFromStatus(state, launched.status);
468
+ return launched;
469
+ }
470
+ async function restartConnection(targetMode) {
471
+ if (runObserver.active) {
472
+ throw new Error(activeRestartMessage(targetMode));
473
+ }
474
+ return (await connection.restart(targetMode)).status;
475
+ }
476
+ async function followRun(runId, initialAfter = '0') {
477
+ let startedAt;
478
+ let endedAt;
479
+ if (initialAfter !== '0') {
480
+ const details = await sendHostCommand(state.workdir, { type: 'run.query', runId });
481
+ if (details.startedAt)
482
+ startedAt = Date.parse(details.startedAt);
483
+ }
484
+ const approvals = createApprovalQueue(state.workdir, async (pending, signal) => {
485
+ writeLine(renderApprovalPrompt(pending));
486
+ for (;;) {
487
+ const answer = (await promptLine(' Choice [y/n/d]: ', signal))?.trim().toLowerCase();
488
+ if (answer === undefined)
489
+ return null;
490
+ if (answer === 'y' || answer === 'yes')
491
+ return 'y';
492
+ if (answer === 'n' || answer === 'no')
493
+ return 'n';
494
+ if (answer === 'd' || answer === 'defer')
495
+ return 'd';
496
+ writeLine(' Please enter y, n, or d.');
497
+ }
498
+ }, writeLine);
499
+ try {
500
+ const result = await runObserver.follow({
501
+ runId,
502
+ after: initialAfter,
503
+ approvals,
504
+ onReconnect: writeLine,
505
+ onPage(_page, events) {
506
+ let reportedError = false;
507
+ for (const event of events) {
508
+ if (event.occurredAt) {
509
+ if (event.type === 'run.started')
510
+ startedAt = Date.parse(event.occurredAt);
511
+ if (isTerminalRunEventType(event.type))
512
+ endedAt = Date.parse(event.occurredAt);
513
+ }
514
+ if (!showTeamEvent(event, state.member))
515
+ continue;
516
+ if (event.error)
517
+ reportedError = true;
518
+ const rendered = renderProgressEvent(event);
519
+ if (rendered)
520
+ writeLine(rendered);
521
+ }
522
+ return reportedError;
523
+ },
524
+ });
525
+ if (!result)
526
+ return;
527
+ if (result.detached) {
528
+ writeLine(`[Detached] Run ${runId} (cursor=${result.cursor}). Use /attach ${runId} to resume watching.`);
529
+ return;
530
+ }
531
+ if (result.status === 'paused') {
532
+ writeLine(`[Paused] Run ${runId} reason=${result.pauseReason ?? 'unknown'}. Use /resume or /reconcile.`);
533
+ return;
534
+ }
535
+ if (startedAt !== undefined && endedAt !== undefined)
536
+ writeLine('任务用时 ' + formatDuration(endedAt - startedAt));
537
+ if (result.status === 'failed' && !result.reportedError) {
538
+ const details = await sendHostCommand(state.workdir, {
539
+ type: 'run.query',
540
+ runId,
541
+ });
542
+ if (details.error) {
543
+ writeLine(`Error: ${formatDiagnosticReference(details.error)}`);
544
+ }
545
+ }
546
+ }
547
+ finally {
548
+ await approvals.close();
549
+ }
550
+ }
551
+ async function submitAndFollow(runOptions) {
552
+ if (state.member)
553
+ throw new Error('请返回主会话提交任务(/team --member main)');
554
+ await ensureConnected();
555
+ const workspaceId = await ensureWorkspaceId(state);
556
+ const sessionId = await ensureSessionId(state);
557
+ const input = replSubmission(state, runOptions, {
558
+ workspaceId,
559
+ sessionId,
560
+ modeRef: state.activeMode?.ref ?? state.modeRef,
561
+ });
562
+ const result = await sendHostCommand(state.workdir, {
563
+ type: 'run.submit',
564
+ input,
565
+ });
566
+ state.lastRunId = result.runId;
567
+ state.hasRunHistory = true;
568
+ state.runCursors.set(result.runId, '0');
569
+ await followRun(result.runId, '0');
570
+ }
571
+ const hooks = {
572
+ write: writeOut,
573
+ writeLine,
574
+ submitAndFollow,
575
+ followRun,
576
+ ensureConnected,
577
+ refreshHostStatus: connection.refreshSnapshot,
578
+ isRunActive: () => runObserver.active,
579
+ switchMode: restartConnection,
580
+ restartHost: restartConnection,
581
+ renderBanner: buildBanner,
582
+ onSessionChanged() {
583
+ void printMemberHistory().catch((error) => writeLine(formatCliError(error)));
584
+ },
585
+ };
586
+ try {
587
+ for (;;) {
588
+ const rawLine = await promptLine('saturn> ');
589
+ if (rawLine === null || exitRequested)
590
+ break;
591
+ const trimmed = rawLine.trim();
592
+ if (!trimmed)
593
+ continue;
594
+ try {
595
+ if (trimmed.startsWith('/')) {
596
+ const action = await handleSlashCommand(trimmed, state, hooks);
597
+ if (action === 'exit')
598
+ break;
599
+ }
600
+ else {
601
+ await submitAndFollow({ text: trimmed });
602
+ }
603
+ }
604
+ catch (error) {
605
+ writeLine(formatCliError(error));
606
+ }
607
+ }
608
+ }
609
+ finally {
610
+ disarmSigint();
611
+ rl.off('SIGINT', onSigint);
612
+ process.off('SIGINT', onSigint);
613
+ if (!inputClosed)
614
+ rl.close();
615
+ process.stdin.pause();
616
+ if (state.host?.owned && state.host.stop) {
617
+ await state.host.stop();
618
+ }
619
+ if (state.sessionId) {
620
+ process.stdout.write(`\n会话已保存,使用以下命令恢复会话:\n ${formatResumeCommand(state.workdir, state.sessionId)}\n`);
621
+ }
622
+ }
623
+ }
624
+ async function runTtyRepl(options, hostOptions) {
625
+ const state = initialReplState(options);
626
+ const connection = createReplHostConnection(state, hostOptions);
627
+ let sessionSummary;
628
+ let runningModel;
629
+ let retainedContextTelemetry;
630
+ let todos = [];
631
+ let exiting = false;
632
+ const runObserver = createReplRunObserver(state.workdir, state.runCursors);
633
+ let followingRun;
634
+ let pendingRun;
635
+ const runStarts = new Map();
636
+ let openingMember = false;
637
+ let navigationSeq = 0;
638
+ let navigationAbort;
639
+ let lastHostConnectedAt = 0;
640
+ const liveMemberSessions = new Map();
641
+ let interruptingRun;
642
+ let latestRunPausedOrCheckpoint = false;
643
+ const tui = createOrbitalTui({
644
+ hints: SLASH_COMMAND_HINTS,
645
+ initialModel: {
646
+ workdir: state.workdir,
647
+ hostPhase: 'connecting',
648
+ ...resolveProfileTelemetry(state, undefined),
649
+ permissionMode: state.permissionMode,
650
+ workspaceTools: false,
651
+ ...(state.modeRef ? { modeRef: state.modeRef } : {}),
652
+ skillRefs: [...state.skillRefs],
653
+ ...(state.sessionId ? { sessionId: state.sessionId } : {}),
654
+ runCount: 0,
655
+ turnCount: 0,
656
+ todos: [],
657
+ inboxCount: 0,
658
+ activeRun: false,
659
+ satellites: [{ id: 'main', role: 'main', status: 'idle' }],
660
+ showSidebar: true,
661
+ },
662
+ });
663
+ const syncTuiTelemetry = (phaseOverride) => {
664
+ const status = state.host?.status;
665
+ const hostPhase = phaseOverride ?? (state.host ? (state.host.owned ? 'ready' : 'attached') : 'connecting');
666
+ const resolvedProfile = resolveProfileTelemetry(state, status, runningModel);
667
+ tui.updateTelemetry({
668
+ hostPhase,
669
+ ...resolvedProfile,
670
+ usage: retainedContextTelemetry,
671
+ permissionMode: state.permissionMode,
672
+ ...(activeModeRef(state, status) ? { modeRef: activeModeRef(state, status) } : { modeRef: undefined }),
673
+ activeMode: status?.activeMode ?? state.activeMode,
674
+ sandbox: status?.sandbox,
675
+ skillRefs: [...state.skillRefs],
676
+ ...(state.disabledSkills?.length ? { disabledSkills: [...state.disabledSkills] } : {}),
677
+ ...(state.sessionId ? { sessionId: state.sessionId } : { sessionId: undefined }),
678
+ teamMember: state.member?.id,
679
+ runCount: sessionSummary?.runCount ?? 0,
680
+ turnCount: sessionSummary?.turnCount ?? 0,
681
+ stepCount: sessionSummary?.stepCount,
682
+ mainTurn: sessionSummary?.mainTurn,
683
+ latestRunStatus: sessionSummary?.latestRun?.status,
684
+ todos: [...todos],
685
+ availableProfiles: status?.profiles,
686
+ availableModes: status?.availableModes,
687
+ availableSkills: status?.skills,
688
+ discoveredSkills: status?.discoveredSkills,
689
+ mcpServers: status?.mcpServers,
690
+ availableTeamPresets: status?.teamPresets,
691
+ boardUrl: formatBoardUrlForSession(status?.boardUrl),
692
+ configSource: status?.configSource,
693
+ });
694
+ };
695
+ function formatBoardUrlForSession(boardUrl) {
696
+ if (!boardUrl)
697
+ return undefined;
698
+ if (!state.sessionId)
699
+ return boardUrl;
700
+ try {
701
+ const parsed = new URL(boardUrl);
702
+ if (!parsed.searchParams.has('session') && !parsed.searchParams.has('sessionId')) {
703
+ parsed.searchParams.set('session', state.sessionId);
704
+ }
705
+ return parsed.toString();
706
+ }
707
+ catch {
708
+ return boardUrl;
709
+ }
710
+ }
711
+ let lastAnnouncedBoardUrl;
712
+ const announceBoardUrl = (boardUrl) => {
713
+ const sessionBoardUrl = formatBoardUrlForSession(boardUrl);
714
+ if (!sessionBoardUrl) {
715
+ lastAnnouncedBoardUrl = undefined;
716
+ return;
717
+ }
718
+ if (sessionBoardUrl === lastAnnouncedBoardUrl)
719
+ return;
720
+ lastAnnouncedBoardUrl = sessionBoardUrl;
721
+ tui.appendEntry('system', `Board: ${sessionBoardUrl}`);
722
+ };
723
+ let sessionToken = new AbortController();
724
+ let viewGeneration = 0;
725
+ let restoredSessionId;
726
+ let history;
727
+ let lastSummaryRefresh = 0;
728
+ let lastHostStatusRefresh = 0;
729
+ let hostStatusRefreshInFlight;
730
+ let hostStatusRefreshQueued = false;
731
+ async function refreshHostStatus(signal, force = false) {
732
+ if (exiting || !state.host)
733
+ return;
734
+ if (hostStatusRefreshInFlight && !force) {
735
+ hostStatusRefreshQueued = true;
736
+ return;
737
+ }
738
+ if (force)
739
+ hostStatusRefreshQueued = false;
740
+ const request = connection.refreshStatus({ signal, merge: true });
741
+ hostStatusRefreshInFlight = request;
742
+ lastHostStatusRefresh = Date.now();
743
+ try {
744
+ const refreshed = await request;
745
+ if (exiting || signal.aborted || !refreshed || state.host !== refreshed.current)
746
+ return;
747
+ lastHostConnectedAt = Date.now();
748
+ const { sandbox: prevSandbox, boardUrl: prevBoardUrl } = refreshed.previous.status;
749
+ const nextStatus = refreshed.current.status;
750
+ const nextSandbox = nextStatus.sandbox;
751
+ const sandboxChanged = prevSandbox?.backend !== nextSandbox?.backend ||
752
+ prevSandbox?.state !== nextSandbox?.state ||
753
+ prevSandbox?.activeContainers !== nextSandbox?.activeContainers ||
754
+ prevSandbox?.fallbackActive !== nextSandbox?.fallbackActive ||
755
+ prevSandbox?.image !== nextSandbox?.image ||
756
+ prevSandbox?.reason !== nextSandbox?.reason;
757
+ const boardUrlChanged = prevBoardUrl !== nextStatus.boardUrl;
758
+ if (sandboxChanged || boardUrlChanged)
759
+ syncTuiTelemetry();
760
+ if (boardUrlChanged)
761
+ announceBoardUrl(nextStatus.boardUrl);
762
+ }
763
+ catch {
764
+ // A later poll can recover sandbox telemetry after a transient disconnect.
765
+ }
766
+ finally {
767
+ if (hostStatusRefreshInFlight === request) {
768
+ hostStatusRefreshInFlight = undefined;
769
+ if (hostStatusRefreshQueued && !exiting && !signal.aborted) {
770
+ hostStatusRefreshQueued = false;
771
+ void refreshHostStatus(signal);
772
+ }
773
+ }
774
+ }
775
+ }
776
+ function applySummary(info, targetId, initial = false) {
777
+ if (exiting || state.sessionId !== targetId)
778
+ return;
779
+ if (sessionSummary?.id === targetId &&
780
+ sessionSummary.cursor &&
781
+ (!info.cursor || BigInt(info.cursor) < BigInt(sessionSummary.cursor)))
782
+ return;
783
+ if (info.member)
784
+ state.member = info.member;
785
+ if (history)
786
+ bindHistory(targetId);
787
+ if ((info.runCount ?? 0) > 0 || info.latestRun?.id)
788
+ state.hasRunHistory = true;
789
+ sessionSummary = { ...info, id: targetId };
790
+ todos = [...(info.todos ?? [])];
791
+ if (initial) {
792
+ state.lastRunId ??= info.latestRun?.id;
793
+ tui.updateTelemetry({ pauseReason: info.latestRun?.pauseReason });
794
+ }
795
+ syncTuiTelemetry();
796
+ }
797
+ async function refreshSummary(initial = false) {
798
+ if (!state.sessionId)
799
+ return;
800
+ const targetId = state.sessionId;
801
+ const signal = sessionToken.signal;
802
+ lastSummaryRefresh = Date.now();
803
+ try {
804
+ const session = await sendHostCommand(state.workdir, {
805
+ type: 'session.query',
806
+ sessionId: targetId,
807
+ }, { signal });
808
+ if (session && !signal.aborted)
809
+ applySummary(session, targetId, initial);
810
+ return session;
811
+ }
812
+ catch {
813
+ // A later refresh can recover telemetry after a transient disconnect.
814
+ }
815
+ }
816
+ function formatHistoryEntry(message, memberId, fullText) {
817
+ if (message.role === 'tool') {
818
+ const toolOutput = fullText ?? message.toolOutput;
819
+ const detail = [
820
+ `[Tool${memberId ? `:${memberId}` : ''}] ${message.toolName ?? 'tool'} ${message.toolStatus ?? ''} (${message.toolCallId ?? ''})`,
821
+ message.toolArguments ? `Args: ${message.toolArguments}` : '',
822
+ message.error ? `${message.error.code} ${message.error.message ?? ''}` : '',
823
+ toolOutput ?? message.text,
824
+ ]
825
+ .filter(Boolean)
826
+ .join('\n');
827
+ const unified = renderUnifiedToolBlock({
828
+ toolName: message.toolName,
829
+ toolArguments: message.toolArguments,
830
+ toolData: message.toolData,
831
+ toolOutput,
832
+ toolStatus: message.toolStatus,
833
+ error: message.error,
834
+ detail,
835
+ });
836
+ if (unified) {
837
+ return { kind: unified.block ?? 'tool', ...unified };
838
+ }
839
+ return {
840
+ kind: 'tool',
841
+ text: fullText ?? message.text,
842
+ activity: 'tool_other',
843
+ detail: detail || (fullText ?? message.text),
844
+ };
845
+ }
846
+ const content = fullText ?? message.text;
847
+ return {
848
+ kind: message.role,
849
+ text: message.role === 'assistant' ? renderAssistantText(content) : content,
850
+ };
851
+ }
852
+ function bindHistory(targetId) {
853
+ const { member } = state;
854
+ const sessionId = member?.parentSessionId ?? targetId;
855
+ const agentSessionId = member?.agentSessionId;
856
+ if (history?.sessionId === sessionId && history.agentSessionId === agentSessionId)
857
+ return history.loader;
858
+ history?.loader.close();
859
+ const route = agentSessionId === undefined ? { sessionId } : { sessionId, agentSessionId };
860
+ const loader = createSessionHistoryLoader(state.workdir, route, {
861
+ onPage: (messages) => tui.prependHistory(messages.map((message) => ({
862
+ ...formatHistoryEntry(message, member?.id),
863
+ key: historyEntryKey(message),
864
+ }))),
865
+ onMessage: (message, text) => tui.setEntry(formatHistoryEntry(message, member?.id, text), historyEntryKey(message)),
866
+ onError: (error) => tui.appendEntry('error', `历史加载失败 · ${formatCliError(error)}`),
867
+ });
868
+ history = { sessionId, agentSessionId, loader };
869
+ return loader;
870
+ }
871
+ function restoreSession() {
872
+ const targetId = state.sessionId;
873
+ if (!targetId || restoredSessionId === targetId)
874
+ return;
875
+ restoredSessionId = targetId;
876
+ const signal = sessionToken.signal;
877
+ void (async () => {
878
+ const info = sessionSummary?.id === targetId ? sessionSummary : await refreshSummary(true);
879
+ if (signal.aborted || exiting || state.sessionId !== targetId)
880
+ return;
881
+ await bindHistory(targetId).load();
882
+ if (signal.aborted || exiting || followingRun || openingMember)
883
+ return;
884
+ const followStatuses = state.member
885
+ ? ['created', 'running', 'paused', 'cancelling']
886
+ : ['created', 'running', 'cancelling'];
887
+ if (!info?.latestRun || !followStatuses.includes(info.latestRun.status))
888
+ return;
889
+ openingMember = true;
890
+ try {
891
+ await followRun(info.latestRun.id);
892
+ }
893
+ catch (error) {
894
+ if (!exiting)
895
+ tui.appendEntry('error', formatCliError(error));
896
+ }
897
+ finally {
898
+ openingMember = false;
899
+ }
900
+ })();
901
+ }
902
+ tui.enter();
903
+ tui.onOlderHistory(() => void history?.loader.load());
904
+ tui.onDetach(runObserver.detach);
905
+ tui.onInterrupt?.(() => {
906
+ const runId = followingRun;
907
+ if (!runId || interruptingRun === runId)
908
+ return;
909
+ interruptingRun = runId;
910
+ tui.updateTelemetry({ statusHint: '正在中断当前运行...' });
911
+ void sendHostCommand(state.workdir, {
912
+ type: 'run.cancel',
913
+ runId,
914
+ reason: 'Interrupted from CLI (Esc)',
915
+ }).catch((error) => {
916
+ if (interruptingRun === runId)
917
+ interruptingRun = undefined;
918
+ if (!exiting)
919
+ tui.appendEntry('error', formatCliError(error));
920
+ });
921
+ });
922
+ function showConnectedHost(host) {
923
+ lastHostConnectedAt = Date.now();
924
+ syncTuiTelemetry(host.owned ? 'ready' : 'attached');
925
+ announceBoardUrl(host.status.boardUrl);
926
+ restoreSession();
927
+ return host;
928
+ }
929
+ function adoptLaunchedHost(host) {
930
+ connection.accept(host);
931
+ hydrateDefaultsFromStatus(state, host.status);
932
+ return showConnectedHost(host);
933
+ }
934
+ let hostBootPromise = connection.launch().then((host) => {
935
+ hostBootPromise = undefined;
936
+ return exiting ? host : adoptLaunchedHost(host);
937
+ }, (error) => {
938
+ hostBootPromise = undefined;
939
+ if (exiting)
940
+ return undefined;
941
+ const message = formatCliError(error);
942
+ tui.updateTelemetry({ hostPhase: 'error', hostError: message, warning: message });
943
+ tui.appendEntry('error', message);
944
+ return undefined;
945
+ });
946
+ async function ensureConnected() {
947
+ const booted = hostBootPromise && (await hostBootPromise);
948
+ if (booted)
949
+ return booted;
950
+ if (state.host) {
951
+ if (followingRun || Date.now() - lastHostConnectedAt < 2000)
952
+ return state.host;
953
+ try {
954
+ const refreshed = await connection.refreshStatus();
955
+ if (refreshed && state.host === refreshed.current)
956
+ return showConnectedHost(refreshed.current);
957
+ if (state.host)
958
+ return state.host;
959
+ }
960
+ catch (error) {
961
+ if (!(error instanceof CliError) || error.code !== 'HOST_UNAVAILABLE')
962
+ throw error;
963
+ state.host = undefined;
964
+ }
965
+ }
966
+ tui.updateTelemetry({ hostPhase: 'connecting' });
967
+ return adoptLaunchedHost(await connection.launch());
968
+ }
969
+ async function restartConnection(targetMode) {
970
+ if (followingRun) {
971
+ throw new Error(activeRestartMessage(targetMode));
972
+ }
973
+ if (hostBootPromise)
974
+ await hostBootPromise;
975
+ tui.updateTelemetry({
976
+ hostPhase: 'connecting',
977
+ hostError: undefined,
978
+ statusHint: targetMode === undefined ? '正在重新加载 Host 与 MCP 配置...' : `正在切换至模式 ${targetMode}...`,
979
+ });
980
+ hostStatusRefreshInFlight = undefined;
981
+ hostStatusRefreshQueued = false;
982
+ try {
983
+ const nextHost = await connection.restart(targetMode);
984
+ lastHostConnectedAt = Date.now();
985
+ tui.updateTelemetry({ statusHint: undefined });
986
+ syncTuiTelemetry();
987
+ announceBoardUrl(nextHost.status.boardUrl);
988
+ return nextHost.status;
989
+ }
990
+ catch (error) {
991
+ state.host = undefined;
992
+ tui.updateTelemetry({
993
+ hostPhase: 'error',
994
+ statusHint: undefined,
995
+ hostError: formatCliError(error),
996
+ });
997
+ throw error;
998
+ }
999
+ }
1000
+ async function followRun(runId, initialAfter = '0', initialInputKey) {
1001
+ if (followingRun)
1002
+ throw new Error('当前正在跟随一个任务');
1003
+ followingRun = runId;
1004
+ let pendingInputKey = initialInputKey;
1005
+ let terminalAt;
1006
+ const satellites = [{ id: 'main', role: 'main', status: 'running' }];
1007
+ let inboxCount = 0;
1008
+ let searchActive = false;
1009
+ let searchRollouts = 0;
1010
+ let searchMaxRollouts = 0;
1011
+ const currentViewKey = () => state.member?.agentSessionId ?? 'main';
1012
+ let activeViewKey = currentViewKey();
1013
+ let activeDraft;
1014
+ let liveThinking;
1015
+ let renderedViewGeneration = viewGeneration;
1016
+ let pauseReason;
1017
+ let terminalStatus;
1018
+ const toolEntries = new Map();
1019
+ const approvals = createApprovalQueue(state.workdir, (pending, signal) => tui.promptApproval(pending, signal), (text) => {
1020
+ if (!exiting)
1021
+ tui.appendEntry('approval', text);
1022
+ });
1023
+ const modelRead = new AbortController();
1024
+ void sendHostCommand(state.workdir, { type: 'run.model', runId }, { signal: modelRead.signal })
1025
+ .then((model) => {
1026
+ if (!exiting && !modelRead.signal.aborted && model?.modelId) {
1027
+ runningModel = model;
1028
+ syncTuiTelemetry();
1029
+ }
1030
+ })
1031
+ .catch(() => { });
1032
+ void refreshSummary();
1033
+ void refreshHostStatus(modelRead.signal);
1034
+ const sandboxTimer = state.host?.status.sandbox && state.host.status.sandbox.backend !== 'host'
1035
+ ? setInterval(() => {
1036
+ if (Date.now() - lastHostStatusRefresh >= 2000)
1037
+ void refreshHostStatus(modelRead.signal);
1038
+ }, 2000)
1039
+ : undefined;
1040
+ sandboxTimer?.unref();
1041
+ if (initialAfter !== '0' && !runStarts.has(runId)) {
1042
+ void sendHostCommand(state.workdir, { type: 'run.query', runId }, { signal: modelRead.signal })
1043
+ .then((details) => {
1044
+ if (!exiting && !modelRead.signal.aborted && details?.startedAt) {
1045
+ const startedAt = Date.parse(details.startedAt);
1046
+ runStarts.set(runId, startedAt);
1047
+ tui.updateTelemetry({ runStartedAt: startedAt });
1048
+ }
1049
+ })
1050
+ .catch(() => { });
1051
+ }
1052
+ function clearDraft() {
1053
+ if (activeDraft && activeDraft.memberKey === currentViewKey()) {
1054
+ tui.removeEntry(`assistant:${activeDraft.requestId}`);
1055
+ }
1056
+ activeDraft = undefined;
1057
+ }
1058
+ function finalizeThinking(requestId) {
1059
+ if (!liveThinking)
1060
+ return;
1061
+ if (liveThinking.memberKey !== currentViewKey()) {
1062
+ liveThinking = undefined;
1063
+ return;
1064
+ }
1065
+ if (!liveThinking.streaming)
1066
+ return;
1067
+ if (requestId && liveThinking.requestId !== requestId)
1068
+ return;
1069
+ liveThinking = { ...liveThinking, streaming: false };
1070
+ tui.setEntry({ kind: 'thinking', text: liveThinking.text, streaming: false }, `thinking:${liveThinking.requestId}`, `assistant:${liveThinking.requestId}`);
1071
+ }
1072
+ const upsertSatellite = (next) => {
1073
+ const idx = satellites.findIndex((s) => s.id === next.id);
1074
+ if (idx >= 0) {
1075
+ const prev = satellites[idx];
1076
+ satellites[idx] = {
1077
+ ...prev,
1078
+ ...next,
1079
+ ...(next.task === undefined && prev.task !== undefined ? { task: prev.task } : {}),
1080
+ };
1081
+ }
1082
+ else {
1083
+ satellites.push(next);
1084
+ }
1085
+ };
1086
+ const thinkingStartedAt = Date.now();
1087
+ let currentThinking = {
1088
+ label: 'Saturn Orbiting',
1089
+ startedAt: thinkingStartedAt,
1090
+ tone: 'thinking',
1091
+ };
1092
+ const countRunningWorkers = () => satellites.filter((s) => s.role === 'worker' &&
1093
+ ['running', 'running:ro', 'queued', 'waiting', 'waiting_approval'].includes(s.status)).length;
1094
+ const formatTeamOrbitLabel = (count) => count === 1 ? 'Coordinator Idle · 1 Worker Active' : `Coordinator Idle · ${count} Workers Active`;
1095
+ tui.updateTelemetry({
1096
+ activeRun: true,
1097
+ pauseReason: undefined,
1098
+ thinking: currentThinking,
1099
+ runStartedAt: runStarts.get(runId),
1100
+ satellites: [...satellites],
1101
+ inboxCount,
1102
+ });
1103
+ try {
1104
+ const result = await runObserver.follow({
1105
+ runId,
1106
+ after: initialAfter,
1107
+ interactiveProgress: true,
1108
+ approvals,
1109
+ onReconnect(message) {
1110
+ clearDraft();
1111
+ tui.appendEntry('system', message);
1112
+ },
1113
+ onPage(page, newEvents) {
1114
+ const viewKey = currentViewKey();
1115
+ const viewChanged = renderedViewGeneration !== viewGeneration || activeViewKey !== viewKey;
1116
+ if (viewChanged) {
1117
+ renderedViewGeneration = viewGeneration;
1118
+ activeViewKey = viewKey;
1119
+ activeDraft = undefined;
1120
+ liveThinking = undefined;
1121
+ toolEntries.clear();
1122
+ searchActive = false;
1123
+ searchRollouts = 0;
1124
+ searchMaxRollouts = 0;
1125
+ currentThinking = {
1126
+ label: 'Saturn Orbiting',
1127
+ startedAt: Date.now(),
1128
+ tone: 'thinking',
1129
+ };
1130
+ }
1131
+ const events = page.events ?? [];
1132
+ let telemetryDirty = viewChanged;
1133
+ let reportedError = false;
1134
+ for (const event of newEvents) {
1135
+ if (event.type === 'run.failed' && event.error)
1136
+ reportedError = true;
1137
+ if (event.type === 'run.failed' && event.checkpoint)
1138
+ latestRunPausedOrCheckpoint = true;
1139
+ if (event.occurredAt) {
1140
+ if (event.type === 'run.started') {
1141
+ const startedAt = Date.parse(event.occurredAt);
1142
+ runStarts.set(runId, startedAt);
1143
+ tui.updateTelemetry({ runStartedAt: startedAt });
1144
+ }
1145
+ if (isTerminalRunEventType(event.type))
1146
+ terminalAt = Date.parse(event.occurredAt);
1147
+ }
1148
+ if (event.type === 'tool.call.settled' &&
1149
+ (event.toolName === 'todo_write' || event.toolName === 'review_numeric_data') &&
1150
+ (!event.memberId || event.memberId === 'main') &&
1151
+ event.toolStatus === 'success' &&
1152
+ Array.isArray(event.todos)) {
1153
+ todos = [...event.todos];
1154
+ telemetryDirty = true;
1155
+ }
1156
+ if (event.type === 'run.team.planned') {
1157
+ if (event.decision === 'team' && event.team?.members?.length) {
1158
+ for (const member of event.team.members) {
1159
+ upsertSatellite({
1160
+ id: member.id,
1161
+ role: 'worker',
1162
+ status: 'queued',
1163
+ task: member.task,
1164
+ parentMemberId: member.parent,
1165
+ });
1166
+ }
1167
+ telemetryDirty = true;
1168
+ }
1169
+ }
1170
+ else if (event.type === 'run.search.started') {
1171
+ searchActive = true;
1172
+ searchRollouts = 0;
1173
+ searchMaxRollouts = event.maxRollouts ?? 0;
1174
+ currentThinking = {
1175
+ label: searchMaxRollouts
1176
+ ? `Trajectory Search [0/${searchMaxRollouts}] · ${event.trigger ?? 'search'}`
1177
+ : `Trajectory Search · ${event.trigger ?? 'search'}`,
1178
+ startedAt: thinkingStartedAt,
1179
+ tone: 'planner',
1180
+ };
1181
+ telemetryDirty = true;
1182
+ }
1183
+ else if (event.type === 'run.search.branch.created') {
1184
+ searchRollouts += 1;
1185
+ const branchId = event.branchId ?? `b${searchRollouts}`;
1186
+ upsertSatellite({
1187
+ id: branchId,
1188
+ role: 'worker',
1189
+ status: event.degradedToReadonly ? 'running:ro' : 'running',
1190
+ ...(event.hypothesis ? { task: event.hypothesis } : {}),
1191
+ });
1192
+ if (searchActive) {
1193
+ currentThinking = {
1194
+ label: searchMaxRollouts
1195
+ ? `Trajectory Search [${searchRollouts}/${searchMaxRollouts}] · ${branchId}`
1196
+ : `Trajectory Search [${searchRollouts}] · ${branchId}`,
1197
+ startedAt: thinkingStartedAt,
1198
+ tone: 'planner',
1199
+ };
1200
+ }
1201
+ telemetryDirty = true;
1202
+ }
1203
+ else if (event.type === 'run.search.branch.evaluated') {
1204
+ if (event.branchId) {
1205
+ upsertSatellite({
1206
+ id: event.branchId,
1207
+ role: 'worker',
1208
+ status: event.verdict ?? 'evaluated',
1209
+ });
1210
+ telemetryDirty = true;
1211
+ }
1212
+ }
1213
+ else if (event.type === 'run.search.converged') {
1214
+ searchActive = false;
1215
+ if (event.winnerBranchId) {
1216
+ upsertSatellite({
1217
+ id: event.winnerBranchId,
1218
+ role: 'worker',
1219
+ status: 'winner',
1220
+ });
1221
+ }
1222
+ currentThinking = {
1223
+ label: 'Saturn Orbiting',
1224
+ startedAt: thinkingStartedAt,
1225
+ tone: 'thinking',
1226
+ };
1227
+ telemetryDirty = true;
1228
+ }
1229
+ else if (event.memberId && event.memberId !== 'planner') {
1230
+ const existing = satellites.find((s) => s.id === event.memberId);
1231
+ const role = existing?.role ?? (event.memberId === 'main' ? 'main' : 'worker');
1232
+ if (event.type === 'turn.started' ||
1233
+ event.type === 'turn.resumed' ||
1234
+ event.type === 'tool.call.requested') {
1235
+ upsertSatellite({ id: event.memberId, role, status: 'running' });
1236
+ telemetryDirty = true;
1237
+ }
1238
+ else if (event.type === 'turn.paused') {
1239
+ upsertSatellite({
1240
+ id: event.memberId,
1241
+ role,
1242
+ status: event.reason === 'approval' ? 'waiting_approval' : 'paused',
1243
+ });
1244
+ telemetryDirty = true;
1245
+ }
1246
+ else if (event.type === 'turn.interrupted') {
1247
+ upsertSatellite({ id: event.memberId, role, status: 'interrupted' });
1248
+ telemetryDirty = true;
1249
+ }
1250
+ else if (event.type === 'turn.failed') {
1251
+ upsertSatellite({ id: event.memberId, role, status: 'failed' });
1252
+ telemetryDirty = true;
1253
+ }
1254
+ else if (event.type === 'turn.completed' &&
1255
+ role === 'worker' &&
1256
+ !['solved', 'promising', 'pruned', 'winner'].includes(existing?.status ?? '')) {
1257
+ upsertSatellite({ id: event.memberId, role, status: 'completed' });
1258
+ telemetryDirty = true;
1259
+ }
1260
+ else if (event.type === 'turn.completed' && role === 'main') {
1261
+ clearDraft();
1262
+ const activeWorkers = countRunningWorkers();
1263
+ upsertSatellite({ id: 'main', role: 'main', status: 'idle' });
1264
+ if (activeWorkers > 0) {
1265
+ currentThinking = {
1266
+ label: formatTeamOrbitLabel(activeWorkers),
1267
+ startedAt: thinkingStartedAt,
1268
+ tone: 'team',
1269
+ };
1270
+ }
1271
+ telemetryDirty = true;
1272
+ }
1273
+ }
1274
+ if (event.type === 'run.team.message.sent') {
1275
+ inboxCount += 1;
1276
+ telemetryDirty = true;
1277
+ }
1278
+ if (event.type === 'tool.call.started') {
1279
+ currentThinking = {
1280
+ label: `Running ${event.toolName ?? 'tool'}`,
1281
+ startedAt: Date.now(),
1282
+ tone: 'tool',
1283
+ };
1284
+ telemetryDirty = true;
1285
+ }
1286
+ else if (event.type === 'model.requested' && (!event.memberId || event.memberId === 'main')) {
1287
+ currentThinking = {
1288
+ label: 'Saturn Orbiting',
1289
+ startedAt: thinkingStartedAt,
1290
+ tone: 'thinking',
1291
+ };
1292
+ telemetryDirty = true;
1293
+ }
1294
+ else if (event.type === 'tool.call.settled') {
1295
+ const runningWorkers = countRunningWorkers();
1296
+ currentThinking = searchActive
1297
+ ? {
1298
+ label: searchMaxRollouts
1299
+ ? `Trajectory Search [${searchRollouts}/${searchMaxRollouts}]`
1300
+ : `Trajectory Search [${searchRollouts}]`,
1301
+ startedAt: thinkingStartedAt,
1302
+ tone: 'planner',
1303
+ }
1304
+ : !page.liveAgents && runningWorkers > 0
1305
+ ? {
1306
+ label: formatTeamOrbitLabel(runningWorkers),
1307
+ startedAt: thinkingStartedAt,
1308
+ tone: 'team',
1309
+ }
1310
+ : {
1311
+ label: 'Saturn Orbiting',
1312
+ startedAt: thinkingStartedAt,
1313
+ tone: 'thinking',
1314
+ };
1315
+ telemetryDirty = true;
1316
+ }
1317
+ const memberView = state.member;
1318
+ if (!showTeamEvent(event, memberView))
1319
+ continue;
1320
+ if (event.type === 'message.assistant.added' || event.type === 'tool.call.requested') {
1321
+ finalizeThinking(event.type === 'message.assistant.added' ? event.requestId : undefined);
1322
+ }
1323
+ if (event.requestId && (event.type === 'model.responded' || event.type === 'model.failed')) {
1324
+ const summary = event.type === 'model.responded' ? event.text : event.reasoningSummary;
1325
+ if (summary?.trim()) {
1326
+ tui.setEntry({ kind: 'thinking', text: summary, streaming: false }, `thinking:${event.requestId}`, `assistant:${event.requestId}`);
1327
+ }
1328
+ else if (event.error?.code === 'steered') {
1329
+ tui.removeEntry(`thinking:${event.requestId}`);
1330
+ }
1331
+ else {
1332
+ finalizeThinking(event.requestId);
1333
+ }
1334
+ if (liveThinking?.requestId === event.requestId)
1335
+ liveThinking = undefined;
1336
+ if (event.type === 'model.responded' && summary?.trim())
1337
+ continue;
1338
+ }
1339
+ if (event.type === 'message.user.added') {
1340
+ if (!event.messageId)
1341
+ continue;
1342
+ const key = messageEntryKey(event.messageId);
1343
+ if (memberView || event.steering) {
1344
+ if (event.text)
1345
+ tui.setEntry({ kind: 'user', text: event.text }, key);
1346
+ }
1347
+ else if (pendingInputKey && (!event.memberId || event.memberId === 'main')) {
1348
+ tui.rekeyEntry(pendingInputKey, key);
1349
+ pendingInputKey = undefined;
1350
+ }
1351
+ continue;
1352
+ }
1353
+ const isMemberReply = memberView && event.type === 'message.assistant.added';
1354
+ const entry = isMemberReply
1355
+ ? event.text
1356
+ ? { text: renderAssistantText(event.text) }
1357
+ : undefined
1358
+ : renderConversationEvent(event);
1359
+ const messageKey = event.messageId
1360
+ ? messageEntryKey(event.messageId)
1361
+ : event.type === 'message.assistant.added' && event.requestId
1362
+ ? `assistant:${event.requestId}`
1363
+ : undefined;
1364
+ if (activeDraft && event.requestId === activeDraft.requestId) {
1365
+ if (event.type === 'model.failed' || (messageKey && (!entry || event.messageId)))
1366
+ clearDraft();
1367
+ else if (messageKey)
1368
+ activeDraft = undefined;
1369
+ }
1370
+ if (entry) {
1371
+ const next = {
1372
+ kind: entry.block ?? (isMemberReply ? 'assistant' : eventEntryKind(event)),
1373
+ ...entry,
1374
+ };
1375
+ if (event.toolCallId && event.type.startsWith('tool.call.')) {
1376
+ const previous = toolEntries.get(event.toolCallId);
1377
+ const detailParts = [previous?.detail, next.detail].filter((part, idx, arr) => Boolean(part) && arr.indexOf(part) === idx);
1378
+ const grouped = {
1379
+ ...next,
1380
+ text: event.type === 'tool.call.settled' ? next.text : next.text || previous?.text || '',
1381
+ ...(detailParts.length ? { detail: detailParts.join('\n') } : {}),
1382
+ };
1383
+ toolEntries.set(event.toolCallId, grouped);
1384
+ tui.setEntry(grouped, `tool:${runId}:${event.toolCallId}`);
1385
+ }
1386
+ else {
1387
+ tui.setEntry(next, messageKey ?? `event:${runId}:${event.position}`);
1388
+ }
1389
+ }
1390
+ }
1391
+ for (const { memberId } of page.pendingApprovals ?? []) {
1392
+ if (!memberId || memberId === 'planner')
1393
+ continue;
1394
+ const existing = satellites.find(({ id }) => id === memberId);
1395
+ if (existing?.status === 'waiting_approval')
1396
+ continue;
1397
+ upsertSatellite({
1398
+ id: memberId,
1399
+ role: memberId === 'main' ? 'main' : 'worker',
1400
+ status: 'waiting_approval',
1401
+ });
1402
+ telemetryDirty = true;
1403
+ }
1404
+ for (const [memberId, agent] of Object.entries(page.liveAgents ?? {})) {
1405
+ if (memberId === 'planner')
1406
+ continue;
1407
+ if (agent.agentSessionId)
1408
+ liveMemberSessions.set(memberId, agent.agentSessionId);
1409
+ if (!agent.phase && !agent.memberId && !agent.agentSessionId)
1410
+ continue;
1411
+ if (satellites.some(({ id }) => id === memberId))
1412
+ continue;
1413
+ upsertSatellite({ id: memberId, role: 'worker', status: 'running' });
1414
+ telemetryDirty = true;
1415
+ }
1416
+ if (events.length && Date.now() - lastSummaryRefresh >= 750)
1417
+ void refreshSummary();
1418
+ const sandboxLifecycleEvent = events.some((event) => event.type === 'run.started' ||
1419
+ event.type === 'turn.started' ||
1420
+ event.type === 'turn.completed' ||
1421
+ event.type === 'turn.failed' ||
1422
+ event.type === 'turn.interrupted' ||
1423
+ (event.type === 'tool.call.settled' && event.toolName === 'spawn_team'));
1424
+ if (sandboxLifecycleEvent || Date.now() - lastHostStatusRefresh >= 2000) {
1425
+ void refreshHostStatus(modelRead.signal);
1426
+ }
1427
+ const draft = state.member ? undefined : page.draft;
1428
+ const rawLiveAgent = page.liveAgents?.[state.member?.id ?? 'main'];
1429
+ const liveAgent = state.member &&
1430
+ rawLiveAgent?.agentSessionId &&
1431
+ rawLiveAgent.agentSessionId !== state.member.agentSessionId
1432
+ ? undefined
1433
+ : rawLiveAgent;
1434
+ const assistantStarted = Boolean(draft && liveAgent?.requestId && draft.requestId === liveAgent.requestId && draft.text.length > 0);
1435
+ if (!page.hasMore &&
1436
+ liveAgent?.requestId &&
1437
+ liveAgent.reasoningSummary?.trim() &&
1438
+ (liveAgent.phase === 'thinking' || liveAgent.phase === 'streaming')) {
1439
+ if (liveThinking && liveThinking.requestId !== liveAgent.requestId) {
1440
+ finalizeThinking();
1441
+ }
1442
+ const { requestId, reasoningSummary } = liveAgent;
1443
+ const isStreaming = liveAgent.phase === 'thinking' && !assistantStarted;
1444
+ if (liveThinking?.memberKey !== viewKey ||
1445
+ liveThinking?.requestId !== requestId ||
1446
+ liveThinking.text !== reasoningSummary ||
1447
+ liveThinking.streaming !== isStreaming) {
1448
+ liveThinking = {
1449
+ requestId,
1450
+ text: reasoningSummary,
1451
+ streaming: isStreaming,
1452
+ memberKey: viewKey,
1453
+ };
1454
+ tui.setEntry({ kind: 'thinking', text: reasoningSummary, streaming: isStreaming }, `thinking:${requestId}`, `assistant:${requestId}`);
1455
+ }
1456
+ }
1457
+ else if (liveThinking?.streaming &&
1458
+ (!liveAgent || liveAgent.phase !== 'thinking' || assistantStarted)) {
1459
+ finalizeThinking();
1460
+ }
1461
+ const draftStreaming = Boolean(draft &&
1462
+ !page.hasMore &&
1463
+ (draft.requestId !== activeDraft?.requestId || draft.revision !== activeDraft.revision));
1464
+ if (draft && draftStreaming) {
1465
+ finalizeThinking(draft.requestId);
1466
+ if (draft.requestId !== activeDraft?.requestId)
1467
+ clearDraft();
1468
+ tui.setEntry({ kind: 'assistant', text: renderAssistantText(draft.text) }, `assistant:${draft.requestId}`);
1469
+ activeDraft = { requestId: draft.requestId, revision: draft.revision, memberKey: viewKey };
1470
+ if (currentThinking?.label !== 'Saturn Transmitting') {
1471
+ currentThinking = {
1472
+ label: 'Saturn Transmitting',
1473
+ startedAt: thinkingStartedAt,
1474
+ tone: 'thinking',
1475
+ };
1476
+ telemetryDirty = true;
1477
+ }
1478
+ }
1479
+ else if (!page.liveAgents) {
1480
+ const runningWorkers = countRunningWorkers();
1481
+ if (runningWorkers > 0 && currentThinking?.tone !== 'tool' && !activeDraft) {
1482
+ const teamLabel = formatTeamOrbitLabel(runningWorkers);
1483
+ if (currentThinking?.tone !== 'team' || currentThinking.label !== teamLabel) {
1484
+ currentThinking = {
1485
+ label: teamLabel,
1486
+ startedAt: thinkingStartedAt,
1487
+ tone: 'team',
1488
+ };
1489
+ telemetryDirty = true;
1490
+ }
1491
+ }
1492
+ else if (runningWorkers === 0 && currentThinking?.tone === 'team') {
1493
+ currentThinking = {
1494
+ label: 'Saturn Orbiting',
1495
+ startedAt: thinkingStartedAt,
1496
+ tone: 'thinking',
1497
+ };
1498
+ telemetryDirty = true;
1499
+ }
1500
+ }
1501
+ const activeMemberKey = state.member?.id ?? 'main';
1502
+ if (telemetryDirty || page.liveAgents || page.telemetry) {
1503
+ retainedContextTelemetry = mergeAgentContextMetrics(retainedContextTelemetry, page.telemetry?.[activeMemberKey], page.liveAgents?.[activeMemberKey]);
1504
+ tui.updateTelemetry({
1505
+ satellites: [...satellites],
1506
+ inboxCount,
1507
+ todos: [...todos],
1508
+ thinking: currentThinking,
1509
+ liveAgents: page.liveAgents,
1510
+ usage: retainedContextTelemetry,
1511
+ });
1512
+ }
1513
+ return reportedError;
1514
+ },
1515
+ });
1516
+ if (exiting || !result)
1517
+ return;
1518
+ if (result.detached) {
1519
+ tui.setEntry({
1520
+ kind: 'system',
1521
+ text: '[已分离] 已暂停跟随当前任务,输入 /attach 可继续查看',
1522
+ detail: `[Detached] Run ${runId} (cursor=${result.cursor}). Use /attach ${runId} to resume watching.`,
1523
+ });
1524
+ return;
1525
+ }
1526
+ if (result.status === 'paused') {
1527
+ pauseReason = result.pauseReason ?? 'unknown';
1528
+ latestRunPausedOrCheckpoint = true;
1529
+ tui.setEntry({
1530
+ kind: 'system',
1531
+ text: `[已暂停] 原因:${pauseReason},核对后使用 /reconcile 或 /resume 继续`,
1532
+ detail: `[Paused] Run ${runId} reason=${pauseReason}. Use /reconcile or /resume after verification.`,
1533
+ });
1534
+ return;
1535
+ }
1536
+ const { status } = result;
1537
+ terminalStatus = status;
1538
+ if (status === 'failed' && !result.reportedError) {
1539
+ const details = await sendHostCommand(state.workdir, {
1540
+ type: 'run.query',
1541
+ runId,
1542
+ });
1543
+ if (!exiting && details.error)
1544
+ tui.appendEntry('error', `Error: ${formatDiagnosticReference(details.error)}`);
1545
+ }
1546
+ }
1547
+ finally {
1548
+ if (sandboxTimer)
1549
+ clearInterval(sandboxTimer);
1550
+ modelRead.abort();
1551
+ await approvals.close();
1552
+ if (interruptingRun === runId)
1553
+ interruptingRun = undefined;
1554
+ followingRun = undefined;
1555
+ liveMemberSessions.clear();
1556
+ runningModel = undefined;
1557
+ if (!exiting) {
1558
+ const startedAt = runStarts.get(runId);
1559
+ if (terminalAt !== undefined && startedAt !== undefined) {
1560
+ tui.setEntry({ kind: 'system', text: '任务用时 ' + formatDuration(terminalAt - startedAt) }, 'duration:' + runId);
1561
+ }
1562
+ syncTuiTelemetry();
1563
+ finalizeThinking();
1564
+ clearDraft();
1565
+ for (let i = 0; i < satellites.length; i++) {
1566
+ const sat = satellites[i];
1567
+ if (sat.id === 'main') {
1568
+ satellites[i] = {
1569
+ ...sat,
1570
+ status: pauseReason ? 'paused' : terminalStatus === 'failed' ? 'failed' : 'idle',
1571
+ };
1572
+ }
1573
+ else if (sat.status === 'running' || sat.status === 'running:ro' || sat.status === 'queued') {
1574
+ satellites[i] = {
1575
+ ...sat,
1576
+ status: pauseReason
1577
+ ? 'paused'
1578
+ : terminalStatus === 'completed'
1579
+ ? 'completed'
1580
+ : terminalStatus === 'failed'
1581
+ ? 'failed'
1582
+ : terminalStatus === 'cancelled'
1583
+ ? 'cancelled'
1584
+ : 'idle',
1585
+ };
1586
+ }
1587
+ }
1588
+ tui.updateTelemetry({
1589
+ activeRun: false,
1590
+ pauseReason,
1591
+ statusHint: undefined,
1592
+ thinking: undefined,
1593
+ liveAgents: undefined,
1594
+ runStartedAt: undefined,
1595
+ satellites: [...satellites],
1596
+ inboxCount,
1597
+ todos: [...todos],
1598
+ });
1599
+ await Promise.all([refreshSummary(), refreshHostStatus(sessionToken.signal, true)]);
1600
+ }
1601
+ }
1602
+ }
1603
+ async function submitAndFollow(runOptions) {
1604
+ if (state.member)
1605
+ throw new Error('请返回主会话提交任务(/team --member main)');
1606
+ await ensureConnected();
1607
+ const workspaceId = await ensureWorkspaceId(state);
1608
+ const createsSession = !state.sessionId;
1609
+ const sessionId = await ensureSessionId(state);
1610
+ if (createsSession)
1611
+ bindHistory(sessionId);
1612
+ const input = replSubmission(state, runOptions, {
1613
+ workspaceId,
1614
+ sessionId,
1615
+ modeRef: activeModeRef(state, state.host?.status),
1616
+ streamText: true,
1617
+ });
1618
+ tui.updateTelemetry({
1619
+ activeRun: true,
1620
+ pauseReason: undefined,
1621
+ thinking: { label: 'Saturn Orbiting', startedAt: Date.now(), tone: 'thinking' },
1622
+ });
1623
+ latestRunPausedOrCheckpoint = false;
1624
+ let result;
1625
+ pendingRun = sendHostCommand(state.workdir, { type: 'run.submit', input });
1626
+ try {
1627
+ result = await pendingRun;
1628
+ }
1629
+ catch (error) {
1630
+ tui.updateTelemetry({ activeRun: false, thinking: undefined });
1631
+ throw error;
1632
+ }
1633
+ finally {
1634
+ pendingRun = undefined;
1635
+ }
1636
+ state.lastRunId = result.runId;
1637
+ state.hasRunHistory = true;
1638
+ state.runCursors.set(result.runId, '0');
1639
+ const inputKey = `input:${result.runId}`;
1640
+ tui.setEntry({ kind: 'user', text: runOptions.text }, inputKey);
1641
+ tui.setEntry({ kind: 'system', text: '', detail: `Run ${result.runId} submitted.` });
1642
+ await followRun(result.runId, '0', inputKey);
1643
+ }
1644
+ const hooks = {
1645
+ promptMcpSecret: (label) => tui.promptSecret(label),
1646
+ write: (text) => tui.appendEntry('system', text),
1647
+ writeLine: (text) => tui.appendEntry('system', text),
1648
+ clearScreen: () => tui.clearEntries(),
1649
+ submitAndFollow,
1650
+ followRun,
1651
+ ensureConnected,
1652
+ refreshHostStatus: connection.refreshSnapshot,
1653
+ isRunActive: () => Boolean(followingRun),
1654
+ async steer(content) {
1655
+ const agentSessionId = state.member?.agentSessionId;
1656
+ const runId = followingRun ?? (await pendingRun)?.runId;
1657
+ if (!runId)
1658
+ throw new Error('No active run to steer');
1659
+ await sendHostCommand(state.workdir, {
1660
+ type: 'run.steer',
1661
+ runId,
1662
+ content,
1663
+ ...(agentSessionId ? { agentSessionId } : {}),
1664
+ });
1665
+ },
1666
+ showSideQuestion: (question, ask) => tui.showSideQuestion(question, async (signal) => {
1667
+ try {
1668
+ return await ask(signal);
1669
+ }
1670
+ catch (error) {
1671
+ return formatCliError(error);
1672
+ }
1673
+ }),
1674
+ isPausedOrCheckpointedRun: () => Boolean(state.lastRunId && (latestRunPausedOrCheckpoint || sessionSummary?.latestRun?.status === 'paused')),
1675
+ pickSession: (sessions) => tui.promptResumeSession?.(sessions) ?? Promise.resolve(null),
1676
+ promptChoice: (prompt) => tui.promptChoice(prompt),
1677
+ switchMode: restartConnection,
1678
+ restartHost: restartConnection,
1679
+ getNavigationSignal: () => navigationAbort?.signal,
1680
+ checkSessionSwitch(info) {
1681
+ if (followingRun && info.latestRun?.id !== followingRun)
1682
+ throw new Error('请先按 Ctrl+C 分离当前任务,再切换到其他任务的会话');
1683
+ },
1684
+ onSessionChanged(info) {
1685
+ latestRunPausedOrCheckpoint = info.latestRun?.status === 'paused';
1686
+ if (restoredSessionId !== info.id) {
1687
+ viewGeneration += 1;
1688
+ tui.closeSideQuestion();
1689
+ sessionToken.abort();
1690
+ sessionToken = new AbortController();
1691
+ sessionSummary = undefined;
1692
+ retainedContextTelemetry = undefined;
1693
+ history?.loader.close();
1694
+ history = undefined;
1695
+ tui.clearEntries();
1696
+ tui.updateTelemetry({ thinking: undefined, liveAgents: undefined });
1697
+ }
1698
+ applySummary(info, info.id, true);
1699
+ syncTuiTelemetry();
1700
+ announceBoardUrl(state.host?.status.boardUrl);
1701
+ restoreSession();
1702
+ },
1703
+ };
1704
+ function runNavigation(command, label) {
1705
+ const seq = ++navigationSeq;
1706
+ navigationAbort?.abort();
1707
+ const navAbort = new AbortController();
1708
+ navigationAbort = navAbort;
1709
+ tui.updateTelemetry({ statusHint: label ? `正在切换到 ${label}...` : '正在切换会话...' });
1710
+ void handleSlashCommand(command, state, hooks)
1711
+ .catch((error) => {
1712
+ if (!exiting &&
1713
+ !navAbort.signal.aborted &&
1714
+ seq === navigationSeq &&
1715
+ !(error instanceof Error && error.name === 'AbortError')) {
1716
+ tui.appendEntry('error', formatCliError(error));
1717
+ }
1718
+ })
1719
+ .finally(() => {
1720
+ if (navigationAbort === navAbort)
1721
+ navigationAbort = undefined;
1722
+ if (!exiting && seq === navigationSeq)
1723
+ tui.updateTelemetry({ statusHint: undefined });
1724
+ });
1725
+ }
1726
+ tui.onSelectSatellite?.((memberId) => {
1727
+ if (exiting)
1728
+ return;
1729
+ const currentMember = state.member?.id ?? 'main';
1730
+ if (memberId === currentMember && !navigationAbort)
1731
+ return;
1732
+ if (memberId === 'main') {
1733
+ const parentSessionId = state.member?.parentSessionId ?? state.sessionId;
1734
+ if (!parentSessionId)
1735
+ return;
1736
+ runNavigation('/session ' + parentSessionId, 'main');
1737
+ return;
1738
+ }
1739
+ const directAgentSessionId = followingRun ? liveMemberSessions.get(memberId) : undefined;
1740
+ if (directAgentSessionId) {
1741
+ runNavigation('/session ' + directAgentSessionId, memberId);
1742
+ return;
1743
+ }
1744
+ const runId = followingRun ?? state.lastRunId;
1745
+ if (!runId)
1746
+ return;
1747
+ runNavigation(`/team ${runId} --member ${memberId}`, memberId);
1748
+ });
1749
+ tui.onNavigation?.((value) => {
1750
+ const command = value.trim();
1751
+ if (!followingRun || !/^\/(?:team(?:\s|$)|session\s)/.test(command))
1752
+ return false;
1753
+ runNavigation(command);
1754
+ return true;
1755
+ });
1756
+ tui.onImmediateSubmission((value) => {
1757
+ void handleSlashCommand(value, state, hooks).catch((error) => {
1758
+ if (!exiting)
1759
+ tui.appendEntry('error', formatCliError(error));
1760
+ });
1761
+ });
1762
+ tui.onSteer(async (text) => {
1763
+ try {
1764
+ await hooks.steer(text);
1765
+ return true;
1766
+ }
1767
+ catch (error) {
1768
+ if (!exiting)
1769
+ tui.appendEntry('error', formatCliError(error));
1770
+ return false;
1771
+ }
1772
+ });
1773
+ try {
1774
+ while (!exiting) {
1775
+ const rawLine = await tui.waitForSubmission();
1776
+ if (rawLine === null)
1777
+ break;
1778
+ const trimmed = rawLine.trim();
1779
+ if (!trimmed)
1780
+ continue;
1781
+ try {
1782
+ if (trimmed.startsWith('/')) {
1783
+ tui.appendEntry('user', trimmed);
1784
+ const action = await handleSlashCommand(trimmed, state, hooks);
1785
+ if (action === 'exit')
1786
+ break;
1787
+ syncTuiTelemetry(state.host ? (state.host.owned ? 'ready' : 'attached') : 'connecting');
1788
+ }
1789
+ else {
1790
+ await submitAndFollow({ text: trimmed });
1791
+ }
1792
+ }
1793
+ catch (error) {
1794
+ if (!trimmed.startsWith('/'))
1795
+ tui.appendEntry('user', trimmed);
1796
+ tui.appendEntry('error', formatCliError(error));
1797
+ }
1798
+ }
1799
+ }
1800
+ finally {
1801
+ exiting = true;
1802
+ runObserver.close();
1803
+ navigationAbort?.abort();
1804
+ sessionToken.abort();
1805
+ history?.loader.close();
1806
+ tui.leave();
1807
+ let hostToStop = state.host;
1808
+ if (!hostToStop && hostBootPromise) {
1809
+ hostToStop = await hostBootPromise;
1810
+ }
1811
+ if (hostToStop?.owned && hostToStop.stop) {
1812
+ await hostToStop.stop();
1813
+ }
1814
+ if (state.sessionId) {
1815
+ process.stdout.write(`\n会话已保存,使用以下命令恢复会话:\n ${formatResumeCommand(state.workdir, state.sessionId)}\n`);
1816
+ }
1817
+ }
1818
+ }
1819
+ export async function startRepl(options) {
1820
+ const hostOptions = {
1821
+ ...(options.config ? { config: options.config } : {}),
1822
+ ...(options.profile ? { profile: options.profile } : {}),
1823
+ ...(options.taskProfile ? { taskProfile: options.taskProfile } : {}),
1824
+ ...(options.modeRef ? { mode: options.modeRef } : {}),
1825
+ ...(options.allowUnsafeSandboxFallback ? { allowUnsafeSandboxFallback: true } : {}),
1826
+ };
1827
+ const isTty = Boolean(process.stdin.isTTY && process.stdout.isTTY);
1828
+ if (isTty) {
1829
+ await runTtyRepl(options, hostOptions);
1830
+ }
1831
+ else {
1832
+ await runPipedRepl(options, hostOptions);
1833
+ }
1834
+ }