@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/tui.js ADDED
@@ -0,0 +1,2559 @@
1
+ import readline from 'node:readline';
2
+ import { PassThrough } from 'node:stream';
3
+ import { isSlashDraft, locateCursor, nextCharOffset, normalizeCursorOffset, offsetAtColumn, paletteSelection, prevCharOffset, prevWordOffset, resolvePaletteAction, resolvePaletteState, wrapBuffer, } from './composer.js';
4
+ import { createTerminalPainter, padEndDisplay, segmentGraphemes, stringDisplayWidth, stripAnsi, terminalColorEnabled, truncateDisplay, truncateDisplayPath, truncateMiddle, wrapTextByWidth, } from './terminal-text.js';
5
+ import { renderCompactSaturnLogo, renderSaturnLogo } from './renderer.js';
6
+ import { isImmediateSlashCommand, SLASH_COMMAND_HINTS } from './slash-commands.js';
7
+ import { createTerminalInput, decodeEnhancedKey } from './terminal-input.js';
8
+ import { renderMarkdown } from './markdown.js';
9
+ import { formatDuration, spinnerFrameMs } from './duration.js';
10
+ import { copySelection, selectRows } from './terminal-selection.js';
11
+ import { formatTokenCompact } from './usage.js';
12
+ const TERMINAL_SATELLITE_STATUSES = new Set(['completed', 'failed', 'interrupted', 'cancelled']);
13
+ function isTerminalSatelliteStatus(status) {
14
+ return TERMINAL_SATELLITE_STATUSES.has(status);
15
+ }
16
+ function formatSatelliteHeader(visibleCount, satellites, sidebarFocused) {
17
+ let doneWorkers = 0;
18
+ let failedWorkers = 0;
19
+ for (const sat of satellites) {
20
+ if (sat.role !== 'worker')
21
+ continue;
22
+ if (sat.status === 'completed')
23
+ doneWorkers += 1;
24
+ else if (isTerminalSatelliteStatus(sat.status))
25
+ failedWorkers += 1;
26
+ }
27
+ const suffix = doneWorkers > 0 && failedWorkers > 0
28
+ ? ` · ${doneWorkers}✓ ${failedWorkers}✕`
29
+ : doneWorkers > 0
30
+ ? ` · ${doneWorkers} done`
31
+ : failedWorkers > 0
32
+ ? ` · ${failedWorkers} failed`
33
+ : '';
34
+ const base = `SATELLITES (${visibleCount}${suffix})`;
35
+ return sidebarFocused ? `${base} [↑↓ Enter]` : base;
36
+ }
37
+ function satelliteTree(satellites) {
38
+ const roots = satellites.filter((sat) => sat.role === 'main').map((sat) => ({ sat, branch: '' }));
39
+ const allWorkers = satellites.filter((sat) => sat.role === 'worker');
40
+ const activeWorkerIds = new Set(allWorkers.filter((sat) => !isTerminalSatelliteStatus(sat.status)).map(({ id }) => id));
41
+ // Keep a parent worker visible if any of its child helpers is still active.
42
+ for (let changed = true; changed;) {
43
+ changed = false;
44
+ for (const sat of allWorkers) {
45
+ if (sat.parentMemberId &&
46
+ sat.parentMemberId !== sat.id &&
47
+ activeWorkerIds.has(sat.id) &&
48
+ allWorkers.some((parent) => parent.id === sat.parentMemberId) &&
49
+ !activeWorkerIds.has(sat.parentMemberId)) {
50
+ activeWorkerIds.add(sat.parentMemberId);
51
+ changed = true;
52
+ }
53
+ }
54
+ }
55
+ const workers = allWorkers.filter((sat) => activeWorkerIds.has(sat.id));
56
+ const parents = new Set(workers.map(({ id }) => id));
57
+ const isChild = (sat) => sat.depth !== 1 && sat.parentMemberId !== sat.id && parents.has(sat.parentMemberId ?? '');
58
+ const top = workers.filter((sat) => !isChild(sat));
59
+ const shown = new Set(top.map(({ id }) => id));
60
+ const children = new Map();
61
+ for (const sat of workers) {
62
+ const parent = sat.parentMemberId;
63
+ if (!shown.has(sat.id) && parent && shown.has(parent)) {
64
+ const siblings = children.get(parent) ?? [];
65
+ siblings.push(sat);
66
+ children.set(parent, siblings);
67
+ }
68
+ else if (!shown.has(sat.id)) {
69
+ top.push(sat);
70
+ }
71
+ }
72
+ return [
73
+ ...roots,
74
+ ...top.flatMap((sat, index) => {
75
+ const end = index === top.length - 1;
76
+ const siblings = children.get(sat.id) ?? [];
77
+ return [
78
+ { sat, branch: end ? '└─ ' : '├─ ' },
79
+ ...siblings.map((child, i) => ({
80
+ sat: child,
81
+ branch: `${end ? ' ' : '│ '}${i === siblings.length - 1 ? '└─' : '├─'} `,
82
+ })),
83
+ ];
84
+ }),
85
+ ];
86
+ }
87
+ const SPINNER_FRAMES = ['◐', '◓', '◑', '◒'];
88
+ const THINKING_SPINNER = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
89
+ function fitCell(text, width) {
90
+ return padEndDisplay(truncateDisplay(text, width), width);
91
+ }
92
+ function renderDockMetadata(model, cols, p) {
93
+ const isMain = (model.teamMember ?? 'main') === 'main';
94
+ const contextWindow = model.usage?.contextWindow ?? (isMain ? model.contextWindow : undefined);
95
+ const { lastInputTokens: lastInput, lastOutputTokens: lastOutput, lastCachedInputTokens: lastCached, outputTokensPerSec: tps, } = model.usage ?? {};
96
+ const used = lastInput === undefined ? undefined : lastInput + (lastOutput ?? 0);
97
+ const context = used !== undefined && contextWindow !== undefined && contextWindow > 0
98
+ ? {
99
+ pct: Math.min(999, Math.max(0, Math.round((used / contextWindow) * 100))),
100
+ tokens: `${formatTokenCompact(used)}/${formatTokenCompact(contextWindow)}`,
101
+ }
102
+ : undefined;
103
+ const ctxPct = context?.pct;
104
+ const tpsVal = tps !== undefined && tps > 0 ? Math.round(tps) : undefined;
105
+ const cachePct = lastInput !== undefined && lastInput > 0 && lastCached !== undefined
106
+ ? Math.min(100, Math.max(0, Math.round((lastCached / lastInput) * 100)))
107
+ : undefined;
108
+ const ctxColor = ctxPct === undefined ? p.dim : ctxPct >= 85 ? p.red : ctxPct >= 60 ? p.yellow : p.cyan;
109
+ const cacheColor = cachePct === undefined || cachePct < 40 ? p.dim : cachePct >= 75 ? p.green : p.yellow;
110
+ function bar(cells, pct, paint) {
111
+ const filled = Math.min(cells, Math.round((pct / 100) * cells));
112
+ return `${filled ? paint('▓'.repeat(filled)) : ''}${filled < cells ? p.dim('░'.repeat(cells - filled)) : ''}`;
113
+ }
114
+ function segments(ctxCells, cacheCells, showTokens) {
115
+ const ctx = ctxPct === undefined ? p.dim('--') : ctxColor(`${ctxPct}%`);
116
+ const speed = tpsVal === undefined ? p.dim('--') : p.gold(String(tpsVal));
117
+ const cache = cachePct === undefined ? p.dim('--') : cacheColor(`${cachePct}%`);
118
+ if (ctxCells === 0) {
119
+ return [
120
+ `CTX ${ctx}`,
121
+ tpsVal === undefined ? `TPS ${speed}` : `TPS ${speed}${p.dim('t/s')}`,
122
+ `CACHE ${cache}`,
123
+ ];
124
+ }
125
+ const pill = (value) => `${p.dim('[')}${value}${p.dim(']')}`;
126
+ const detail = showTokens && context ? ` ${p.dim(context.tokens)}` : '';
127
+ const tpsText = tpsVal === undefined ? speed : `${speed} ${p.dim('t/s')}`;
128
+ return [
129
+ pill(`CTX ${bar(ctxCells, ctxPct ?? 0, ctxColor)} ${ctx}${detail}`),
130
+ pill(`TPS ${tpsText}`),
131
+ pill(`CACHE ${bar(cacheCells, cachePct ?? 0, cacheColor)} ${cache}`),
132
+ ];
133
+ }
134
+ const warnPrefix = model.credReady ? '' : `${p.yellow('⚠')} `;
135
+ const budget = Math.max(4, cols - (model.credReady ? 0 : 2));
136
+ const compact = segments(0, 0, false);
137
+ let text = compact.join(' ');
138
+ for (const [ctxCells, cacheCells, showTokens] of [
139
+ [8, 6, true],
140
+ [8, 6, false],
141
+ [5, 4, false],
142
+ ]) {
143
+ const candidate = segments(ctxCells, cacheCells, showTokens).join(' ');
144
+ if (stringDisplayWidth(candidate) <= budget) {
145
+ text = candidate;
146
+ break;
147
+ }
148
+ }
149
+ while (compact.length > 1 && stringDisplayWidth(text) > budget) {
150
+ compact.pop();
151
+ text = compact.join(' ');
152
+ }
153
+ return [fitCell(`${warnPrefix}${text}`, cols)];
154
+ }
155
+ function formatCoordinatorIdleLabel(activeWorkers) {
156
+ return activeWorkers === 1
157
+ ? 'Coordinator Idle · 1 Worker Active'
158
+ : `Coordinator Idle · ${activeWorkers} Workers Active`;
159
+ }
160
+ function renderActivityLine(model, cols, p) {
161
+ const frame = Math.max(0, Math.floor(model.spinnerFrame ?? 0));
162
+ const spinner = THINKING_SPINNER[frame % THINKING_SPINNER.length];
163
+ const now = model.nowMs ?? Date.now();
164
+ const active = Object.entries(model.liveAgents ?? {})
165
+ .filter(([memberId, agent]) => agent.phase && agent.phase !== 'idle' && (!model.teamMember || model.teamMember === memberId))
166
+ .sort(([, a], [, b]) => (b.lastActivityAt ?? '').localeCompare(a.lastActivityAt ?? ''));
167
+ const [liveMemberId, live] = active[0] ?? [];
168
+ const mainSatellite = model.satellites.find((sat) => sat.role === 'main');
169
+ const activeWorkerCount = model.satellites.filter((sat) => sat.role === 'worker' &&
170
+ [
171
+ 'running',
172
+ 'running:ro',
173
+ 'queued',
174
+ 'waiting',
175
+ 'waiting_approval',
176
+ 'launching',
177
+ 'thinking',
178
+ 'tool',
179
+ ].includes(sat.status)).length;
180
+ const mainPhase = model.liveAgents?.main?.phase;
181
+ const coordinatorIdle = Boolean(model.activeRun) &&
182
+ !model.teamMember &&
183
+ activeWorkerCount > 0 &&
184
+ (!mainPhase || mainPhase === 'idle') &&
185
+ (mainSatellite?.status === 'idle' ||
186
+ mainSatellite?.status === 'waiting' ||
187
+ mainSatellite?.status === 'watching');
188
+ const tone = coordinatorIdle
189
+ ? 'team'
190
+ : live?.phase === 'tool' || live?.phase === 'waiting_approval'
191
+ ? 'tool'
192
+ : live && liveMemberId !== 'main'
193
+ ? 'team'
194
+ : (model.thinking?.tone ?? 'thinking');
195
+ const startedAt = model.runStartedAt ?? model.thinking?.startedAt;
196
+ const runElapsed = startedAt !== undefined ? formatDuration(Math.max(0, now - startedAt)) : undefined;
197
+ const baseLabel = coordinatorIdle
198
+ ? [formatCoordinatorIdleLabel(activeWorkerCount), runElapsed].filter(Boolean).join(' · ')
199
+ : live
200
+ ? `${liveMemberId} · ${agentStatus(live, now)}`
201
+ : [model.thinking?.label ?? 'Saturn Orbiting', runElapsed].filter(Boolean).join(' · ');
202
+ const queueLabel = (model.queuedCount ?? 0) > 0 ? `排队 ${model.queuedCount}` : undefined;
203
+ const label = [baseLabel, queueLabel].filter(Boolean).join(' · ');
204
+ const spinnerColor = tone === 'planner' ? p.magenta : tone === 'tool' ? p.yellow : tone === 'team' ? p.cyan : p.brightCyan;
205
+ const baseToneColor = tone === 'planner' ? p.magenta : tone === 'tool' ? p.yellow : p.cyan;
206
+ const chars = [...label];
207
+ const pos = Math.floor(frame / 2) % (chars.length + 6);
208
+ let shimmerLabel = '';
209
+ for (let i = 0; i < chars.length; i++) {
210
+ const ch = chars[i];
211
+ const dist = Math.abs(i - pos);
212
+ if (dist === 0)
213
+ shimmerLabel += p.whiteBold(ch);
214
+ else if (dist === 1)
215
+ shimmerLabel += p.brightCyan(ch);
216
+ else
217
+ shimmerLabel += baseToneColor(ch);
218
+ }
219
+ const leftRaw = ` ${spinnerColor(spinner)} ${shimmerLabel}`;
220
+ const leftW = stringDisplayWidth(leftRaw);
221
+ const elapsedPrefix = live && runElapsed ? `${runElapsed} · ` : '';
222
+ const rightCandidates = [`${elapsedPrefix}Esc 中断 · Ctrl+C 分离`, `${elapsedPrefix}Esc 中断`, 'Esc 中断'];
223
+ for (const rightPlain of rightCandidates) {
224
+ const rightW = stringDisplayWidth(rightPlain);
225
+ if (leftW + rightW + 1 <= cols) {
226
+ const gap = cols - leftW - rightW;
227
+ return fitCell(`${leftRaw}${' '.repeat(gap)}${p.dim(rightPlain)}`, cols);
228
+ }
229
+ }
230
+ return fitCell(leftRaw, cols);
231
+ }
232
+ function renderDockStatus(model, cols, p, hideBoard = false) {
233
+ const lines = [];
234
+ if (!model.activeRun && !model.thinking && (model.queuedCount ?? 0) > 0) {
235
+ lines.push(fitCell(p.dim(`排队 ${model.queuedCount} 条消息等待发送`), cols));
236
+ }
237
+ if (model.teamMember)
238
+ lines.push(fitCell(p.cyan('成员 ' + terminalText(model.teamMember) + ' · Esc 返回 main'), cols));
239
+ if (model.boardUrl && !hideBoard) {
240
+ lines.push(fitCell(p.cyan(`Board: ${terminalText(model.boardUrl)}`), cols));
241
+ }
242
+ if (model.pauseReason && !model.activeRun && !model.approvalPrompt) {
243
+ lines.push(fitCell(p.yellow(`已暂停 · ${model.pauseReason}`), cols));
244
+ const commands = model.pauseReason === 'approval' ? ['/approve', '/deny'] : ['/resume', '/reconcile'];
245
+ let actions = '';
246
+ for (const command of commands) {
247
+ const next = actions ? `${actions} ${command}` : command;
248
+ if (stringDisplayWidth(next) > cols) {
249
+ lines.push(fitCell(p.yellow(actions), cols));
250
+ actions = command;
251
+ }
252
+ else {
253
+ actions = next;
254
+ }
255
+ }
256
+ if (actions)
257
+ lines.push(fitCell(p.yellow(actions), cols));
258
+ }
259
+ if (model.hostPhase === 'connecting') {
260
+ const spinner = SPINNER_FRAMES[(model.spinnerFrame ?? 0) % SPINNER_FRAMES.length];
261
+ lines.push(fitCell(p.cyan(`${spinner} Linking Orbit`), cols));
262
+ }
263
+ else if (model.hostPhase === 'error') {
264
+ lines.push(fitCell(p.red(`✕ ${terminalText(model.hostError ?? 'Host connection error')}`), cols));
265
+ }
266
+ if (model.statusHint) {
267
+ lines.push(fitCell(p.yellow(terminalText(model.statusHint)), cols));
268
+ }
269
+ return lines;
270
+ }
271
+ function todoStatusPriority(status) {
272
+ switch (status) {
273
+ case 'in_progress':
274
+ return 0;
275
+ case 'pending':
276
+ return 1;
277
+ case 'completed':
278
+ return 2;
279
+ case 'cancelled':
280
+ return 3;
281
+ }
282
+ }
283
+ function formatTodoLine(item, width, p) {
284
+ const text = truncateDisplay(terminalText(item.content), Math.max(4, width - 4));
285
+ switch (item.status) {
286
+ case 'completed':
287
+ return ` ${p.green('✓')} ${p.dim(text)}`;
288
+ case 'in_progress':
289
+ return ` ${p.brightCyan('◐')} ${p.whiteBold(text)}`;
290
+ case 'pending':
291
+ return ` ${p.dim('○')} ${text}`;
292
+ case 'cancelled':
293
+ return ` ${p.dim('✕')} ${p.dim(text)}`;
294
+ }
295
+ }
296
+ function agentStatus(agent, now) {
297
+ const elapsed = Date.parse(agent.requestStartedAt ?? '');
298
+ const duration = Number.isFinite(elapsed) ? ` ${formatDuration(now - elapsed)}` : '';
299
+ const retry = agent.retryAttempt === undefined
300
+ ? ''
301
+ : `retry ${agent.retryAttempt}${agent.retryMaxAttempts === undefined ? '' : `/${agent.retryMaxAttempts}`}`;
302
+ switch (agent.phase) {
303
+ case 'thinking':
304
+ return [`thinking${duration}`, retry].filter(Boolean).join(' · ');
305
+ case 'streaming':
306
+ return [`streaming${duration}`, retry].filter(Boolean).join(' · ');
307
+ case 'retrying':
308
+ return retry || 'retrying';
309
+ case 'tool': {
310
+ const tool = agent.currentTool ?? 'tool';
311
+ return agent.stepCount === undefined ? tool : `${tool} · step ${agent.stepCount}`;
312
+ }
313
+ case 'waiting_approval':
314
+ return 'awaiting approval';
315
+ case 'idle':
316
+ case undefined:
317
+ return 'idle';
318
+ }
319
+ }
320
+ function satelliteStatus(sat, live, frame, p) {
321
+ const spinner = THINKING_SPINNER[frame % THINKING_SPINNER.length];
322
+ switch (sat.status) {
323
+ case 'completed':
324
+ return { glyph: p.green('✓'), label: 'done' };
325
+ case 'failed':
326
+ case 'interrupted':
327
+ return { glyph: p.red('✕'), label: 'failed' };
328
+ }
329
+ const phase = sat.status === 'waiting_approval' || sat.status === 'awaiting approval'
330
+ ? 'waiting_approval'
331
+ : live?.phase && live.phase !== 'idle'
332
+ ? live.phase
333
+ : sat.status;
334
+ switch (phase) {
335
+ case 'running':
336
+ case 'running:ro':
337
+ case 'launching':
338
+ case 'thinking':
339
+ case 'streaming':
340
+ case 'retrying':
341
+ return { glyph: p.brightCyan(spinner), label: 'thinking', running: true };
342
+ case 'tool':
343
+ return { glyph: p.yellow(spinner), label: 'tool', running: true };
344
+ case 'waiting_approval':
345
+ return { glyph: p.magenta(frame % 8 < 4 ? '◉' : '○'), label: 'approval' };
346
+ case 'waiting':
347
+ return { glyph: p.dim('·'), label: 'queued' };
348
+ default:
349
+ return { glyph: p.dim('·'), label: phase };
350
+ }
351
+ }
352
+ function renderSidebarLines(model, tree, width, height, p, colStart) {
353
+ const lines = [];
354
+ const targets = [];
355
+ const inner = Math.max(8, width - 2);
356
+ const colEnd = colStart + width - 1;
357
+ const viewedMember = model.teamMember ?? 'main';
358
+ lines.push(` ${p.brightCyan('ORBITAL TELEMETRY')}`);
359
+ lines.push(` ${p.dim('─'.repeat(inner))}`);
360
+ lines.push(` ${p.gold('SESSION')}`);
361
+ const workdir = terminalText(model.workdir).replace(/\s+/g, ' ').trim();
362
+ const workdirText = truncateDisplayPath(workdir, Math.max(4, width - 12));
363
+ lines.push(` ${p.dim('工作目录')} ${p.cyan(workdirText)}`);
364
+ const modelId = terminalText(model.modelId || model.profileLabel).replace(/\s+/g, ' ');
365
+ const effort = model.modelId && model.reasoningEffort
366
+ ? ` (${terminalText(model.reasoningEffort).replace(/\s+/g, ' ')})`
367
+ : '';
368
+ const modelBudget = Math.max(4, width - 12);
369
+ const effortWidth = stringDisplayWidth(effort);
370
+ const fittedModel = effort && modelBudget >= effortWidth + 4
371
+ ? truncateMiddle(modelId, modelBudget - effortWidth) + effort
372
+ : truncateMiddle(modelId + effort, modelBudget);
373
+ const styledModel = model.credReady ? p.whiteBold(fittedModel) : p.yellow(fittedModel);
374
+ lines.push(` ${p.dim('当前模型')} ${styledModel}`);
375
+ const turn = model.mainTurn;
376
+ const activeTurn = turn?.status === 'running' || turn?.status === 'paused';
377
+ const paused = turn?.status === 'paused' ? (model.pauseReason === 'approval' ? '(待审批)' : '(已暂停)') : '';
378
+ lines.push(` ${p.dim(turn && !activeTurn ? '最近轮次' : '当前轮次')} ${turn?.ordinal ?? '—'}${paused}`);
379
+ lines.push(` ${p.dim('累计步数')} ${model.stepCount ?? (model.sessionId ? '—' : 0)}`);
380
+ if (model.sandbox && model.sandbox.backend !== 'host') {
381
+ const sb = model.sandbox;
382
+ const stateLabel = sb.fallbackActive
383
+ ? p.yellow(`⚠ ${sb.backend}→host (unsafe fallback)`)
384
+ : sb.state === 'ready'
385
+ ? p.green(`${sb.backend} · ${sb.activeContainers} container${sb.activeContainers === 1 ? '' : 's'}`)
386
+ : p.red(`${sb.backend} (${sb.state})`);
387
+ lines.push(` ${p.dim('沙箱状态')} ${stateLabel}`);
388
+ }
389
+ if (model.boardUrl) {
390
+ lines.push(` ${p.dim('Board:')} ${p.cyan(terminalText(model.boardUrl))}`);
391
+ }
392
+ if (model.latestRunStatus && !model.activeRun) {
393
+ const labels = {
394
+ created: '待执行',
395
+ running: '执行中',
396
+ paused: '已暂停',
397
+ cancelling: '取消中',
398
+ completed: '已完成',
399
+ failed: '已失败',
400
+ cancelled: '已取消',
401
+ };
402
+ lines.push(` ${p.dim('最近运行')} ${labels[model.latestRunStatus] ?? '—'}`);
403
+ }
404
+ lines.push('');
405
+ const sats = tree.map(({ sat }) => sat);
406
+ const selectedIndex = Math.max(0, sats.findIndex(({ id }) => id === model.focusedSatelliteId));
407
+ const satReserve = Math.max(3, sats.length + 1);
408
+ const todos = model.todos;
409
+ const doneCount = todos.filter((item) => item.status === 'completed').length;
410
+ if (todos.length > 0 && lines.length < height - satReserve) {
411
+ lines.push(` ${p.gold(`TODO (${doneCount}/${todos.length})`)}`);
412
+ const itemBudget = Math.max(0, height - satReserve - 1 - lines.length);
413
+ if (itemBudget > 0) {
414
+ if (todos.length <= itemBudget) {
415
+ for (const item of todos) {
416
+ lines.push(truncateDisplay(formatTodoLine(item, width, p), width));
417
+ }
418
+ }
419
+ else {
420
+ const showCount = Math.max(0, itemBudget - 1);
421
+ const selectedIndices = todos
422
+ .map((item, index) => ({ index, priority: todoStatusPriority(item.status) }))
423
+ .sort((a, b) => a.priority - b.priority || a.index - b.index)
424
+ .slice(0, showCount)
425
+ .map((entry) => entry.index)
426
+ .sort((a, b) => a - b);
427
+ for (const idx of selectedIndices) {
428
+ lines.push(truncateDisplay(formatTodoLine(todos[idx], width, p), width));
429
+ }
430
+ const clipped = todos.length - selectedIndices.length;
431
+ if (clipped > 0) {
432
+ lines.push(` ${p.dim(`+${clipped} 项...`)}`);
433
+ }
434
+ }
435
+ }
436
+ if (lines.length < height - satReserve) {
437
+ lines.push('');
438
+ }
439
+ }
440
+ if (lines.length < height) {
441
+ const sidebarFocused = model.focusArea === 'sidebar' && sats.length > 0 && lines.length + 1 < height;
442
+ const satHeader = formatSatelliteHeader(sats.length, model.satellites, sidebarFocused);
443
+ lines.push(` ${sidebarFocused ? p.brightCyan(truncateDisplay(satHeader, inner)) : p.gold(satHeader)}`);
444
+ const now = model.nowMs ?? Date.now();
445
+ const frame = Math.max(0, Math.floor(model.spinnerFrame ?? 0));
446
+ const states = sats.map((sat) => satelliteStatus(sat, model.liveAgents?.[sat.id], frame, p));
447
+ const rootStatus = model.activeRun || sats.some((sat, index) => sat.role === 'worker' && states[index].running)
448
+ ? 'active'
449
+ : 'idle';
450
+ const rowCount = height - lines.length;
451
+ const start = sidebarFocused ? Math.max(0, selectedIndex - rowCount + 1) : 0;
452
+ for (let index = start; index < Math.min(start + rowCount, tree.length); index++) {
453
+ const { sat, branch } = tree[index];
454
+ const isFocusedItem = sidebarFocused && index === selectedIndex;
455
+ const isActiveView = sat.id === viewedMember;
456
+ const isRoot = sat.role === 'main';
457
+ const { glyph, label } = states[index];
458
+ const status = isRoot
459
+ ? rootStatus
460
+ : truncateDisplay(terminalText(label).replace(/\s+/g, ' '), inner - 8);
461
+ const statusWidth = stringDisplayWidth(status);
462
+ const indent = isFocusedItem && !p.colored ? '▸' : ' ';
463
+ const prefix = `${indent}${branch ? p.dim(branch.trimEnd()) + ' ' : ''}${isRoot ? p.gold('◎') : glyph} `;
464
+ const contentWidth = width - statusWidth - 2;
465
+ const id = truncateDisplay(terminalText(sat.id).replace(/\s+/g, ' '), contentWidth - stringDisplayWidth(prefix));
466
+ const styledId = isRoot ? p.white(id) : isFocusedItem || isActiveView ? p.whiteBold(id) : id;
467
+ const left = `${prefix}${styledId}`;
468
+ const live = model.liveAgents?.[sat.id];
469
+ const liveActivity = label === 'tool'
470
+ ? live?.currentTool
471
+ : label === 'thinking' && live?.phase && live.phase !== 'idle'
472
+ ? agentStatus(live, now).replace(/^(?:thinking|streaming)\b\s*(?:·\s*)?/, '')
473
+ : undefined;
474
+ const activity = isRoot
475
+ ? ''
476
+ : terminalText(liveActivity || sat.task || '')
477
+ .replace(/\s+/g, ' ')
478
+ .trim();
479
+ const withActivity = activity && stringDisplayWidth(left) + 1 + stringDisplayWidth(activity) <= contentWidth
480
+ ? `${left} ${p.dim(activity)}`
481
+ : left;
482
+ const satLine = `${fitCell(withActivity, contentWidth)} ${p.dim(status)}`;
483
+ targets.push({ row: lines.length + 1, colStart, colEnd, memberId: sat.id });
484
+ lines.push(isFocusedItem && p.colored ? `\x1b[7m${satLine.replaceAll('\x1b[0m', '\x1b[0;7m')}\x1b[0m` : satLine);
485
+ }
486
+ }
487
+ const out = [];
488
+ for (let i = 0; i < height; i++) {
489
+ out.push(fitCell(lines[i] ?? '', width));
490
+ }
491
+ return {
492
+ lines: out,
493
+ targets,
494
+ ...(targets.length ? { navigation: { memberIds: sats.map(({ id }) => id), selectedIndex } } : {}),
495
+ };
496
+ }
497
+ function choiceViewport(index, count, visibleCount) {
498
+ return Math.max(0, Math.min(index - Math.floor(visibleCount / 2), count - visibleCount));
499
+ }
500
+ function choiceHeader(title, width, index, count, p) {
501
+ const arrows = `${index > 0 ? '▲' : ''}${index + 1 < count ? '▼' : ''}`;
502
+ const counter = count ? ` ${index + 1}/${count}${arrows ? ' ' + arrows : ''} ` : '';
503
+ const titleText = truncateDisplay(title, Math.max(0, width - 2 - stringDisplayWidth(counter)));
504
+ const fill = Math.max(0, width - 2 - stringDisplayWidth(titleText + counter));
505
+ return p.cyan(`╭${titleText}${'─'.repeat(fill)}${counter}╮`);
506
+ }
507
+ function renderPaletteOverlay(palette, paletteIndex, leftWidth, p, maxRows) {
508
+ const boxWidth = Math.min(leftWidth, Math.max(Math.min(leftWidth, 34), Math.min(74, leftWidth - 2)));
509
+ const innerWidth = Math.max(4, boxWidth - 4);
510
+ const { index: selectedIndex, count } = paletteSelection(palette, paletteIndex);
511
+ const visibleCount = Math.min(7, Math.max(1, maxRows - 2));
512
+ const start = choiceViewport(selectedIndex, count, visibleCount);
513
+ if (palette.kind === 'args') {
514
+ const rawHeader = palette.currentLabel
515
+ ? `─ ${palette.command} · 当前: ${palette.currentLabel} `
516
+ : `─ ${palette.command} `;
517
+ const topBorder = choiceHeader(rawHeader, boxWidth, selectedIndex, count, p);
518
+ const footerText = '── ↑↓ 选择 Tab 补全 Enter 执行 Esc 收起 ';
519
+ const footerTrunc = truncateDisplay(footerText, Math.max(0, boxWidth - 2));
520
+ const botFill = Math.max(0, boxWidth - 2 - stringDisplayWidth(footerTrunc));
521
+ const botBorder = p.cyan(`╰${footerTrunc}${'─'.repeat(botFill)}╯`);
522
+ const rows = [topBorder];
523
+ const options = palette.options.slice(start, start + visibleCount);
524
+ if (!options.length) {
525
+ const emptyMsg = palette.partial ? `No matching args (${palette.partial})` : 'Type argument value...';
526
+ rows.push(`${p.cyan('│')} ${fitCell(p.dim(emptyMsg), innerWidth)} ${p.cyan('│')}`);
527
+ }
528
+ else {
529
+ const valColWidth = Math.min(20, Math.max(10, ...options.map((opt) => stringDisplayWidth(opt.value))));
530
+ for (let i = 0; i < options.length; i++) {
531
+ const opt = options[i];
532
+ const selected = i + start === selectedIndex;
533
+ const valCol = padEndDisplay(truncateDisplay(opt.value, valColWidth), valColWidth);
534
+ const currentTagPlain = opt.current ? '● 当前' : '';
535
+ const currentTagW = stringDisplayWidth(currentTagPlain);
536
+ const leftFixedW = 2 + valColWidth + 1;
537
+ const canShowTag = currentTagW > 0 && innerWidth - leftFixedW - currentTagW - 1 >= 4;
538
+ const summaryBudget = Math.max(4, innerWidth - leftFixedW - (canShowTag ? currentTagW + 1 : 0));
539
+ const summary = truncateDisplay(opt.summary, summaryBudget);
540
+ const leftPart = selected
541
+ ? `${p.brightCyan('▸ ')}${p.whiteBold(valCol)} ${summary}`
542
+ : ` ${p.cyan(valCol)} ${p.dim(summary)}`;
543
+ const leftW = stringDisplayWidth(leftPart);
544
+ const content = canShowTag
545
+ ? `${leftPart}${' '.repeat(Math.max(1, innerWidth - leftW - currentTagW))}${p.green(currentTagPlain)}`
546
+ : leftPart;
547
+ rows.push(`${p.cyan('│')} ${fitCell(content, innerWidth)} ${p.cyan('│')}`);
548
+ }
549
+ }
550
+ rows.push(botBorder);
551
+ return rows;
552
+ }
553
+ const items = palette.items.slice(start, start + visibleCount);
554
+ const topBorder = choiceHeader(`─ Commands (${palette.token}) `, boxWidth, selectedIndex, count, p);
555
+ const footerText = '── ↑↓ 选择 Tab 补全 Esc 收起 ';
556
+ const footerTrunc = truncateDisplay(footerText, Math.max(0, boxWidth - 2));
557
+ const botFill = Math.max(0, boxWidth - 2 - stringDisplayWidth(footerTrunc));
558
+ const botBorder = p.cyan(`╰${footerTrunc}${'─'.repeat(botFill)}╯`);
559
+ const rows = [topBorder];
560
+ if (!items.length) {
561
+ rows.push(`${p.cyan('│')} ${fitCell(p.dim('No matching commands'), innerWidth)} ${p.cyan('│')}`);
562
+ }
563
+ else {
564
+ for (let i = 0; i < items.length; i++) {
565
+ const item = items[i];
566
+ const selected = i + start === selectedIndex;
567
+ const cmdCol = padEndDisplay(truncateDisplay(item.command, 11), 11);
568
+ const badgeVal = item.currentBadge;
569
+ const leftFixedW = 2 + 11 + 1;
570
+ let badgePlain = '';
571
+ let canShowBadge = false;
572
+ if (badgeVal) {
573
+ const rawBadge = `[当前: ${badgeVal}]`;
574
+ const maxBadgeW = Math.max(8, Math.floor(innerWidth * 0.4));
575
+ badgePlain =
576
+ stringDisplayWidth(rawBadge) > maxBadgeW
577
+ ? `[当前: ${truncateMiddle(badgeVal, Math.max(3, maxBadgeW - 8))}]`
578
+ : rawBadge;
579
+ const badgeW = stringDisplayWidth(badgePlain);
580
+ canShowBadge = innerWidth - leftFixedW - badgeW - 1 >= 6;
581
+ }
582
+ const badgeW = canShowBadge ? stringDisplayWidth(badgePlain) : 0;
583
+ const summaryBudget = Math.max(4, innerWidth - leftFixedW - (canShowBadge ? badgeW + 1 : 0));
584
+ const summary = truncateDisplay(item.summary, summaryBudget);
585
+ const leftPart = selected
586
+ ? `${p.brightCyan('▸ ')}${p.bold(p.brightCyan(cmdCol))} ${summary}`
587
+ : ` ${p.cyan(cmdCol)} ${p.dim(summary)}`;
588
+ const leftW = stringDisplayWidth(leftPart);
589
+ const content = canShowBadge
590
+ ? `${leftPart}${' '.repeat(Math.max(1, innerWidth - leftW - badgeW))}${p.dim(badgePlain)}`
591
+ : leftPart;
592
+ rows.push(`${p.cyan('│')} ${fitCell(content, innerWidth)} ${p.cyan('│')}`);
593
+ }
594
+ }
595
+ rows.push(botBorder);
596
+ return rows;
597
+ }
598
+ function formatPickerTime(iso) {
599
+ const date = new Date(iso);
600
+ if (Number.isNaN(date.getTime()))
601
+ return iso.slice(0, 16);
602
+ const pad = (n) => String(n).padStart(2, '0');
603
+ return `${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
604
+ }
605
+ function renderChoiceOverlay(picker, leftWidth, p, maxRows) {
606
+ const boxWidth = Math.min(leftWidth, Math.max(Math.min(leftWidth, 44), Math.min(82, leftWidth - 2)));
607
+ const innerWidth = boxWidth - 4;
608
+ const { options, selectedIndex, subtitle, title } = picker;
609
+ const rows = [choiceHeader(`─ ${terminalText(title)} `, boxWidth, selectedIndex, options.length, p)];
610
+ const row = (text) => `${p.cyan('│')} ${fitCell(text, innerWidth)} ${p.cyan('│')}`;
611
+ if (subtitle && maxRows >= 4)
612
+ rows.push(row(p.dim(terminalText(subtitle))));
613
+ const visibleCount = Math.min(10, Math.max(1, maxRows - rows.length - 1));
614
+ const start = choiceViewport(selectedIndex, options.length, visibleCount);
615
+ for (const [index, option] of options.slice(start, start + visibleCount).entries()) {
616
+ const selected = index + start === selectedIndex;
617
+ const current = option.current ? '● 当前' : '';
618
+ const currentWidth = stringDisplayWidth(current);
619
+ const meta = truncateDisplay(terminalText(option.meta ?? ''), Math.floor(innerWidth / 2) - currentWidth);
620
+ const right = [meta && p.dim(meta), current && p.green(current)].filter(Boolean).join(' ');
621
+ const rightWidth = stringDisplayWidth(right);
622
+ const labelWidth = innerWidth - 2 - (rightWidth ? rightWidth + 1 : 0);
623
+ const label = truncateDisplay(terminalText(option.label), labelWidth);
624
+ const left = selected ? p.brightCyan('▸ ') + p.whiteBold(label) : ' ' + label;
625
+ rows.push(row(right ? fitCell(left, innerWidth - rightWidth) + right : left));
626
+ }
627
+ const footerText = '── ↑↓ 选择 Enter 确认 Esc 取消 ';
628
+ const footerTrunc = truncateDisplay(footerText, Math.max(0, boxWidth - 2));
629
+ const botFill = Math.max(0, boxWidth - 2 - stringDisplayWidth(footerTrunc));
630
+ const botBorder = p.cyan(`╰${footerTrunc}${'─'.repeat(botFill)}╯`);
631
+ rows.push(botBorder);
632
+ return rows;
633
+ }
634
+ function renderSecretOverlay(prompt, cols, p) {
635
+ const width = Math.min(82, cols);
636
+ const inner = width - 4;
637
+ const mask = '•'.repeat(Math.min(prompt.maskLength, inner - 2));
638
+ const footer = truncateDisplay('── Enter 提交 Esc 取消 ', width - 2);
639
+ return [
640
+ choiceHeader(`─ ${terminalText(prompt.label).trim()} `, width, 0, 0, p),
641
+ `${p.cyan('│')} ${fitCell('› ' + mask, inner)} ${p.cyan('│')}`,
642
+ p.cyan(`╰${footer}${'─'.repeat(width - 2 - stringDisplayWidth(footer))}╯`),
643
+ ];
644
+ }
645
+ function renderSideQuestionOverlay(question, cols, maxRows, frame, p) {
646
+ const width = Math.min(82, cols);
647
+ const inner = width - 4;
648
+ const border = (left, title, right) => {
649
+ const label = truncateDisplay(title, width - 2);
650
+ return p.cyan(left + label + '─'.repeat(width - 2 - stringDisplayWidth(label)) + right);
651
+ };
652
+ const visibleCount = Math.max(1, maxRows - 2);
653
+ const prompt = wrapTextByWidth(terminalText(question.question), inner).map((line) => p.dim(line));
654
+ const content = question.result === undefined
655
+ ? [
656
+ ...prompt.slice(0, Math.max(0, visibleCount - 1)),
657
+ p.cyan(`${THINKING_SPINNER[frame % THINKING_SPINNER.length]} 正在回答…`),
658
+ ]
659
+ : [...prompt, ...wrapTextByWidth(terminalText(question.result), inner)];
660
+ const maxScroll = Math.max(0, content.length - visibleCount);
661
+ const start = Math.min(question.scroll, maxScroll);
662
+ const lines = [
663
+ border('╭', '─ BTW · Side Question(不写入历史) ', '╮'),
664
+ ...content
665
+ .slice(start, start + visibleCount)
666
+ .map((line) => p.cyan('│') + ' ' + fitCell(line, inner) + ' ' + p.cyan('│')),
667
+ border('╰', maxScroll ? '─ Esc / Enter 关闭 · ↑↓ ' : '─ Esc / Enter 关闭 ', '╯'),
668
+ ];
669
+ return { lines: lines.slice(0, maxRows), maxScroll };
670
+ }
671
+ function renderApprovalOverlay(pending, leftWidth, p, showDetails = false, maxRows = 9) {
672
+ const boxWidth = Math.min(leftWidth, Math.max(Math.min(leftWidth, 40), Math.min(76, leftWidth - 2)));
673
+ const innerWidth = Math.max(6, boxWidth - 4);
674
+ const member = pending.memberId ? ` [${terminalText(pending.memberId)}]` : '';
675
+ const titleText = `─ Approval Required${truncateDisplay(member, Math.max(0, innerWidth - 20))} `;
676
+ const topFill = Math.max(0, boxWidth - 2 - stringDisplayWidth(titleText));
677
+ const rows = [p.yellow(`╭${titleText}${'─'.repeat(topFill)}╮`)];
678
+ const [program, workdir, ...args] = pending.resources;
679
+ const resources = pending.toolName === 'run_process' && program && workdir
680
+ ? [`程序 ${program}`, `目录 ${workdir}`, ...(args.length ? [`参数 ${JSON.stringify(args)}`] : [])]
681
+ : pending.resources.length
682
+ ? [`目标 ${pending.resources.join(', ')}`]
683
+ : [];
684
+ const detailLines = [
685
+ `Tool: ${pending.toolName}`,
686
+ ...resources,
687
+ ...(showDetails ? [`ID: ${pending.approvalId} Call: ${pending.toolCallId}`, pending.reason] : []),
688
+ ]
689
+ .filter(Boolean)
690
+ .slice(0, Math.max(0, maxRows - 3))
691
+ .map((line) => terminalText(line).replace(/\n/g, ' '));
692
+ detailLines.push(`${p.bold('[y]')} 批准 / ${p.bold('[n]')} 拒绝 / ${p.bold('[d]')} 暂缓`);
693
+ for (const line of detailLines)
694
+ rows.push(`${p.yellow('│')} ${fitCell(line, innerWidth)} ${p.yellow('│')}`);
695
+ rows.push(p.yellow(`╰${'─'.repeat(Math.max(0, boxWidth - 2))}╯`));
696
+ return rows;
697
+ }
698
+ const markdownLayouts = new WeakMap();
699
+ function formatToolSummaryLines(plain, maxWidth, p, soft) {
700
+ const normalized = plain.replace(/\r\n?/g, '\n').replace(/\t/g, ' ');
701
+ if (!p.colored)
702
+ return wrapTextByWidth(normalized, maxWidth, soft);
703
+ const paintRun = (style, text) => style === 'cyan' ? p.cyan(text) : style === 'light' ? p.light(text) : p.dim(text);
704
+ const tokenizeParagraph = (paragraph) => {
705
+ const runs = [];
706
+ let body = paragraph;
707
+ if (body.startsWith('›')) {
708
+ runs.push({ text: '›', style: 'cyan' });
709
+ body = body.slice(1);
710
+ }
711
+ const hintMatch = body.match(/(?:\s*·\s*Ctrl\+T\s*(?:展开|收起))$/);
712
+ const trailingHint = hintMatch?.[0] ?? '';
713
+ const mainBody = trailingHint ? body.slice(0, body.length - trailingHint.length) : body;
714
+ const tokenRegex = /·|([^)]*)|\([^)]*\)/g;
715
+ let cursor = 0;
716
+ for (const match of mainBody.matchAll(tokenRegex)) {
717
+ const idx = match.index ?? 0;
718
+ if (idx > cursor)
719
+ runs.push({ text: mainBody.slice(cursor, idx), style: 'light' });
720
+ const token = match[0];
721
+ if (token === '·') {
722
+ runs.push({ text: token, style: 'dim' });
723
+ }
724
+ else {
725
+ const open = token[0];
726
+ const close = token[token.length - 1];
727
+ const inner = token.slice(1, -1);
728
+ runs.push({ text: open, style: 'dim' });
729
+ for (const part of inner.split(/(,\s*|\s+等$)/)) {
730
+ if (!part)
731
+ continue;
732
+ runs.push({
733
+ text: part,
734
+ style: part.startsWith(',') || part.endsWith('等') ? 'dim' : 'cyan',
735
+ });
736
+ }
737
+ runs.push({ text: close, style: 'dim' });
738
+ }
739
+ cursor = idx + token.length;
740
+ }
741
+ if (cursor < mainBody.length)
742
+ runs.push({ text: mainBody.slice(cursor), style: 'light' });
743
+ if (trailingHint)
744
+ runs.push({ text: trailingHint, style: 'dim' });
745
+ return runs;
746
+ };
747
+ const out = [];
748
+ for (const paragraph of normalized.split('\n')) {
749
+ if (!paragraph.length) {
750
+ out.push('');
751
+ continue;
752
+ }
753
+ const paraSoft = new Set();
754
+ const wrapped = wrapTextByWidth(paragraph, maxWidth, paraSoft);
755
+ for (const rel of paraSoft)
756
+ soft.add(out.length + rel);
757
+ const runs = tokenizeParagraph(paragraph);
758
+ let runIndex = 0;
759
+ let runOffset = 0;
760
+ for (const line of wrapped) {
761
+ let remaining = line.length;
762
+ let styled = '';
763
+ while (remaining > 0 && runIndex < runs.length) {
764
+ const run = runs[runIndex];
765
+ const avail = run.text.length - runOffset;
766
+ const take = Math.min(remaining, avail);
767
+ if (take > 0)
768
+ styled += paintRun(run.style, run.text.slice(runOffset, runOffset + take));
769
+ remaining -= take;
770
+ runOffset += take;
771
+ if (runOffset >= run.text.length) {
772
+ runIndex++;
773
+ runOffset = 0;
774
+ }
775
+ }
776
+ out.push(styled);
777
+ }
778
+ }
779
+ return out;
780
+ }
781
+ function formatEntryLines(entry, leftWidth, p, soft, showDetails = false, spinnerFrame = 0) {
782
+ const plain = terminalText(entry.text);
783
+ const out = [];
784
+ switch (entry.kind) {
785
+ case 'user': {
786
+ const wrapped = wrapTextByWidth(plain, Math.max(4, leftWidth - 2), soft);
787
+ for (const line of wrapped) {
788
+ out.push(`${p.gold('┃ ')}${p.whiteBold(line)}`);
789
+ }
790
+ return out;
791
+ }
792
+ case 'assistant': {
793
+ const cached = markdownLayouts.get(entry);
794
+ if (cached?.width === leftWidth && cached.colored === p.colored) {
795
+ for (const index of cached.soft)
796
+ soft.add(index);
797
+ return cached.lines;
798
+ }
799
+ const markdownWraps = new Set();
800
+ const lines = [
801
+ p.green('◎ Saturn'),
802
+ ...renderMarkdown(plain, Math.max(4, leftWidth - 2), p.colored, markdownWraps).map((line) => ` ${line}`),
803
+ ];
804
+ for (const index of markdownWraps)
805
+ soft.add(index + 1);
806
+ markdownLayouts.set(entry, { width: leftWidth, colored: p.colored, lines, soft });
807
+ return lines;
808
+ }
809
+ case 'thinking': {
810
+ const frame = Math.max(0, Math.floor(spinnerFrame));
811
+ const wraps = new Set();
812
+ const lines = wrapTextByWidth(plain, Math.max(4, leftWidth - 2), wraps);
813
+ const bodyLine = (line) => `${p.dim('│ ')}${p.thinkingItalic(line)}`;
814
+ const collapseLine = (omitted) => p.dim(`│ … +${omitted} 行 · Ctrl+O 展开`);
815
+ if (entry.streaming) {
816
+ const header = p.magenta(`${THINKING_SPINNER[frame % THINKING_SPINNER.length]} Thinking…`);
817
+ if (!showDetails && lines.length > 5) {
818
+ const tailCount = 4;
819
+ const omitted = lines.length - tailCount;
820
+ const tail = lines.slice(-tailCount);
821
+ const offset = lines.length - tail.length;
822
+ for (const index of wraps)
823
+ if (index >= offset)
824
+ soft.add(index - offset + 2);
825
+ return [header, collapseLine(omitted), ...tail.map(bodyLine)];
826
+ }
827
+ for (const index of wraps)
828
+ soft.add(index + 1);
829
+ return [header, ...lines.map(bodyLine)];
830
+ }
831
+ const header = p.magenta('✦ Thinking');
832
+ const collapsed = !showDetails && lines.length > 5;
833
+ const visible = collapsed ? lines.slice(0, 4) : lines;
834
+ for (const index of wraps)
835
+ if (index < visible.length)
836
+ soft.add(index + 1);
837
+ return [
838
+ header,
839
+ ...visible.map(bodyLine),
840
+ ...(collapsed ? [collapseLine(lines.length - visible.length)] : []),
841
+ ];
842
+ }
843
+ case 'planner': {
844
+ const text = plain.startsWith('[Planner]') ? plain : `[Planner] ${plain}`;
845
+ const wrapped = wrapTextByWidth(text, Math.max(4, leftWidth - 2), soft);
846
+ for (let i = 0; i < wrapped.length; i++) {
847
+ const line = wrapped[i];
848
+ if (i === 0 && line.startsWith('[Planner]')) {
849
+ out.push(`${p.magenta('[Planner]')}${line.slice('[Planner]'.length)}`);
850
+ }
851
+ else {
852
+ out.push(line);
853
+ }
854
+ }
855
+ return out;
856
+ }
857
+ case 'team': {
858
+ const cached = markdownLayouts.get(entry);
859
+ if (cached?.width === leftWidth && cached.colored === p.colored) {
860
+ for (const index of cached.soft)
861
+ soft.add(index);
862
+ return cached.lines;
863
+ }
864
+ let header = entry.header ? terminalText(entry.header) : undefined;
865
+ let body = plain;
866
+ if (!header) {
867
+ const arrowMatch = body.match(/^(?:\[Team\]\s*)?([^\n·]+→[^\n·]+?)\s*·\s*([\s\S]*)$/);
868
+ if (arrowMatch) {
869
+ header = arrowMatch[1].trim();
870
+ body = arrowMatch[2];
871
+ }
872
+ else if (body.startsWith('[Team]')) {
873
+ const firstNl = body.indexOf('\n');
874
+ if (firstNl >= 0) {
875
+ header = body.slice('[Team]'.length, firstNl).trim();
876
+ body = body.slice(firstNl + 1);
877
+ }
878
+ else {
879
+ body = body.slice('[Team]'.length).trim();
880
+ }
881
+ }
882
+ }
883
+ const markdownWraps = new Set();
884
+ const heading = header ? p.cyan(`◎ Team · ${header}`) : p.cyan('◎ Team');
885
+ const renderedBody = body.trim()
886
+ ? renderMarkdown(body, Math.max(4, leftWidth - 2), p.colored, markdownWraps).map((line) => ` ${line}`)
887
+ : [];
888
+ const lines = [heading, ...renderedBody];
889
+ for (const index of markdownWraps)
890
+ soft.add(index + 1);
891
+ markdownLayouts.set(entry, { width: leftWidth, colored: p.colored, lines, soft });
892
+ return lines;
893
+ }
894
+ case 'ledger':
895
+ case 'skill':
896
+ case 'web': {
897
+ const status = plain.replace(/\s+/g, ' ').trim();
898
+ const width = Math.max(1, leftWidth - 2);
899
+ const line = stringDisplayWidth(status) <= width ? status : truncateDisplay(status, width - 1) + '…';
900
+ const paint = entry.kind === 'ledger'
901
+ ? p.cyan
902
+ : entry.kind === 'skill'
903
+ ? p.gold
904
+ : entry.tone === 'error'
905
+ ? p.red
906
+ : entry.tone === 'muted'
907
+ ? p.dim
908
+ : p.green;
909
+ return [paint('│ ' + line)];
910
+ }
911
+ case 'tool': {
912
+ if (!entry.tone && plain.startsWith('›')) {
913
+ return formatToolSummaryLines(plain, Math.max(4, leftWidth - 2), p, soft);
914
+ }
915
+ const wrapped = wrapTextByWidth(plain, Math.max(4, leftWidth - 2), soft);
916
+ for (let i = 0; i < wrapped.length; i++) {
917
+ const line = wrapped[i];
918
+ if (entry.tone === 'error') {
919
+ out.push(p.red(line));
920
+ }
921
+ else if (entry.tone === 'warn') {
922
+ out.push(i === 0 ? p.yellow(line) : p.dim(line));
923
+ }
924
+ else {
925
+ const tagMatch = line.match(/^(\[Tool[^\]]*\])(.*)$/);
926
+ if (i === 0 && tagMatch) {
927
+ out.push(`${p.yellow(tagMatch[1])}${tagMatch[2]}`);
928
+ }
929
+ else {
930
+ out.push(p.dim(line));
931
+ }
932
+ }
933
+ }
934
+ return out;
935
+ }
936
+ case 'approval': {
937
+ const wrapped = wrapTextByWidth(plain, Math.max(4, leftWidth - 2), soft);
938
+ for (const line of wrapped) {
939
+ out.push(p.yellow(line));
940
+ }
941
+ return out;
942
+ }
943
+ case 'error': {
944
+ const wrapped = wrapTextByWidth(plain, Math.max(4, leftWidth - 2), soft);
945
+ for (const line of wrapped) {
946
+ out.push(p.red(line));
947
+ }
948
+ return out;
949
+ }
950
+ case 'system': {
951
+ const wrapped = wrapTextByWidth(plain, Math.max(4, leftWidth - 2), soft);
952
+ for (const line of wrapped) {
953
+ const tagMatch = line.match(/^(\[[A-Za-z]+\])(.*)$/);
954
+ if (tagMatch) {
955
+ out.push(`${p.cyan(tagMatch[1])}${tagMatch[2]}`);
956
+ }
957
+ else {
958
+ out.push(p.dim(line));
959
+ }
960
+ }
961
+ return out;
962
+ }
963
+ }
964
+ }
965
+ function renderLandingPane(model, leftWidth, height, p) {
966
+ if (height <= 0)
967
+ return [];
968
+ const logo = leftWidth < 70
969
+ ? renderCompactSaturnLogo(p.colored)
970
+ : renderSaturnLogo(model.spinnerFrame ?? 0, p.colored);
971
+ const logoWidth = Math.max(0, ...logo.map(stringDisplayWidth));
972
+ const logoLeftPad = Math.max(0, Math.floor((leftWidth - Math.min(leftWidth, logoWidth)) / 2));
973
+ const centeredBlock = logo.map((line) => {
974
+ const truncated = truncateDisplay(line, Math.max(0, leftWidth - logoLeftPad));
975
+ return `${' '.repeat(logoLeftPad)}${truncated}`;
976
+ });
977
+ if (model.warning) {
978
+ const warning = truncateDisplay(p.yellow(`⚠ ${model.warning}`), leftWidth);
979
+ const warnPad = Math.max(0, Math.floor((leftWidth - stringDisplayWidth(warning)) / 2));
980
+ centeredBlock.push(`${' '.repeat(warnPad)}${warning}`);
981
+ }
982
+ const topPad = Math.max(0, Math.floor((height - centeredBlock.length) / 2));
983
+ const out = [];
984
+ for (let i = 0; i < height; i++) {
985
+ const srcIndex = i - topPad;
986
+ const raw = srcIndex >= 0 && srcIndex < centeredBlock.length ? centeredBlock[srcIndex] : '';
987
+ out.push(fitCell(raw, leftWidth));
988
+ }
989
+ return out;
990
+ }
991
+ function terminalText(text) {
992
+ return stripAnsi(text)
993
+ .replace(/\r\n?/g, '\n')
994
+ .replace(/\t/g, ' ')
995
+ .replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g, '');
996
+ }
997
+ function renderFeedPane(model, leftWidth, height, p, anchor) {
998
+ const feedLines = [];
999
+ const counts = new Map();
1000
+ const modifiedFiles = new Set();
1001
+ const teamReporters = [];
1002
+ let activityStart = 0;
1003
+ let hasActivity = false;
1004
+ function append(entry, index) {
1005
+ if (feedLines.length)
1006
+ feedLines.push({ entry: index, line: -1, text: '', indent: 0, soft: false });
1007
+ const soft = new Set();
1008
+ const frame = Math.max(0, Math.floor(model.spinnerFrame ?? 0));
1009
+ for (const [line, text] of formatEntryLines(entry, leftWidth, p, soft, model.showDetails, frame).entries()) {
1010
+ const indent = entry.kind === 'user' || (['assistant', 'team', 'thinking'].includes(entry.kind) && line > 0) ? 2 : 0;
1011
+ feedLines.push({ entry: index, line, text, indent, soft: soft.has(line) });
1012
+ }
1013
+ }
1014
+ function flushActivities() {
1015
+ if (!hasActivity)
1016
+ return;
1017
+ const parts = [];
1018
+ const listCount = counts.get('list_dir') ?? 0;
1019
+ const readCount = counts.get('read_file') ?? 0;
1020
+ const searchCount = (counts.get('search_files') ?? 0) + (counts.get('grep') ?? 0);
1021
+ const globCount = counts.get('glob') ?? 0;
1022
+ const cmdOk = counts.get('command') ?? 0;
1023
+ const cmdFailed = counts.get('command_failed') ?? 0;
1024
+ const cmdTotal = cmdOk + cmdFailed;
1025
+ const writeCount = (counts.get('write_file') ?? 0) + (counts.get('edit_file') ?? 0);
1026
+ const otherCount = counts.get('tool_other') ?? 0;
1027
+ const todoCount = counts.get('todo') ?? 0;
1028
+ const teamPlanCount = counts.get('team_plan') ?? 0;
1029
+ if (listCount > 0)
1030
+ parts.push(`已列出 ${listCount} 个目录`);
1031
+ if (readCount > 0)
1032
+ parts.push(`已读取 ${readCount} 个文件`);
1033
+ if (globCount > 0)
1034
+ parts.push(`已按路径匹配 ${globCount} 次`);
1035
+ if (searchCount > 0)
1036
+ parts.push(`已搜索 ${searchCount} 次`);
1037
+ if (cmdTotal > 0) {
1038
+ parts.push(cmdFailed > 0 ? `已执行 ${cmdTotal} 条命令(${cmdFailed} 非零)` : `已执行 ${cmdTotal} 条命令`);
1039
+ }
1040
+ if (writeCount > 0) {
1041
+ if (modifiedFiles.size > 0) {
1042
+ const names = [...modifiedFiles];
1043
+ const preview = names.length <= 3 ? names.join(', ') : `${names.slice(0, 3).join(', ')} 等`;
1044
+ parts.push(`修改 ${names.length} 个文件(${preview})`);
1045
+ }
1046
+ else {
1047
+ parts.push(`修改文件 ${writeCount} 次`);
1048
+ }
1049
+ }
1050
+ if (otherCount > 0)
1051
+ parts.push(`其他工具 ${otherCount} 次`);
1052
+ if (parts.length === 0 && todoCount > 0 && teamPlanCount === 0 && teamReporters.length === 0) {
1053
+ parts.push(`已更新待办 ${todoCount} 次`);
1054
+ }
1055
+ if (parts.length > 0) {
1056
+ append({ kind: 'tool', text: `› ${parts.join(' · ')} · Ctrl+T 展开` }, activityStart);
1057
+ }
1058
+ if (teamReporters.length > 0) {
1059
+ const uniqueMembers = [...new Set(teamReporters)];
1060
+ const names = uniqueMembers.length <= 4 ? uniqueMembers.join(' · ') : `${uniqueMembers.slice(0, 4).join(' · ')} 等`;
1061
+ append({
1062
+ kind: 'system',
1063
+ text: `[Team] 已收到 ${teamReporters.length} 份卫星汇报(${names}) · Ctrl+T 展开`,
1064
+ }, activityStart);
1065
+ }
1066
+ else if (teamPlanCount > 0) {
1067
+ append({ kind: 'system', text: '[Team] 已启动卫星团队协作 · Ctrl+T 展开' }, activityStart);
1068
+ }
1069
+ counts.clear();
1070
+ modifiedFiles.clear();
1071
+ teamReporters.length = 0;
1072
+ hasActivity = false;
1073
+ }
1074
+ for (const [index, entry] of model.entries.entries()) {
1075
+ if (!model.showDetails && entry.activity) {
1076
+ if (!hasActivity)
1077
+ activityStart = index;
1078
+ hasActivity = true;
1079
+ counts.set(entry.activity, (counts.get(entry.activity) ?? 0) + 1);
1080
+ if ((entry.activity === 'write_file' || entry.activity === 'edit_file') && entry.activityLabel) {
1081
+ modifiedFiles.add(entry.activityLabel);
1082
+ }
1083
+ if (entry.activity === 'team_report') {
1084
+ teamReporters.push(entry.activityLabel || 'satellite');
1085
+ }
1086
+ continue;
1087
+ }
1088
+ const text = model.showDetails ? (entry.detail ?? entry.text) : entry.text;
1089
+ if (!text)
1090
+ continue;
1091
+ flushActivities();
1092
+ const kind = model.showDetails &&
1093
+ entry.detail &&
1094
+ (entry.kind === 'ledger' || entry.kind === 'skill' || entry.kind === 'web')
1095
+ ? 'tool'
1096
+ : entry.kind;
1097
+ append(text === entry.text && kind === entry.kind ? entry : { ...entry, kind, text }, index);
1098
+ }
1099
+ flushActivities();
1100
+ const maxScroll = Math.max(0, feedLines.length - height);
1101
+ const anchorIndex = anchor
1102
+ ? feedLines.findIndex((line) => line.entry > anchor.entry || (line.entry === anchor.entry && line.line >= anchor.line))
1103
+ : -1;
1104
+ const offset = anchorIndex >= 0 ? maxScroll - anchorIndex : model.scrollOffset;
1105
+ const clampedScroll = Math.max(0, Math.min(offset, maxScroll));
1106
+ const endIndex = feedLines.length - clampedScroll;
1107
+ const startIndex = Math.max(0, endIndex - height);
1108
+ const visible = feedLines.slice(startIndex, endIndex);
1109
+ const out = [];
1110
+ for (let i = 0; i < height; i++) {
1111
+ out.push(fitCell(visible[i]?.text ?? '', leftWidth));
1112
+ }
1113
+ let firstColumns = leftWidth;
1114
+ if (clampedScroll > 0 && out.length > 0) {
1115
+ const badge = p.dim(` ↑ ${clampedScroll} `);
1116
+ const badgeW = stringDisplayWidth(badge);
1117
+ if (leftWidth > badgeW + 4) {
1118
+ firstColumns -= badgeW;
1119
+ const firstBase = truncateDisplay(out[0], firstColumns);
1120
+ out[0] = `${fitCell(firstBase, leftWidth - badgeW)}${badge}`;
1121
+ }
1122
+ }
1123
+ const first = visible[0];
1124
+ const allSelectionRows = feedLines.map(({ text, indent, soft }, i) => ({
1125
+ text: stripAnsi(text).slice(indent),
1126
+ indent,
1127
+ soft,
1128
+ columns: i === startIndex && clampedScroll > 0 ? firstColumns : leftWidth,
1129
+ }));
1130
+ return {
1131
+ lines: out,
1132
+ selectionRows: allSelectionRows.slice(startIndex, endIndex),
1133
+ allSelectionRows,
1134
+ feedStartIndex: startIndex,
1135
+ offset: clampedScroll,
1136
+ maxOffset: maxScroll,
1137
+ ...(first ? { anchor: { entry: first.entry, line: first.line } } : {}),
1138
+ };
1139
+ }
1140
+ function renderInputDock(model, cols, maxDockLines, p, hideBoard = false) {
1141
+ const modeBadge = model.activeMode
1142
+ ? `${model.activeMode.displayName} (${model.activeMode.ref})`
1143
+ : model.modeRef;
1144
+ const sandboxBadge = model.sandbox && model.sandbox.backend !== 'host'
1145
+ ? model.sandbox.fallbackActive
1146
+ ? `⚠ sandbox:${model.sandbox.backend}→host`
1147
+ : `sandbox:${model.sandbox.backend}${model.sandbox.activeContainers > 0 ? `(${model.sandbox.activeContainers})` : ''}`
1148
+ : undefined;
1149
+ const titleText = truncateDisplay(`─ Saturn${modeBadge ? ` · ${modeBadge}` : ''}${sandboxBadge ? ` · ${sandboxBadge}` : ''}${model.permissionMode ? ` · ${model.permissionMode}` : ''} `, cols - 2);
1150
+ const borderColor = model.activeRun ? p.cyan : p.gold;
1151
+ const topFill = Math.max(0, cols - 2 - stringDisplayWidth(titleText));
1152
+ const topBorder = borderColor(`╭${titleText}${'─'.repeat(topFill)}╮`);
1153
+ const botBorder = borderColor(`╰${'─'.repeat(Math.max(0, cols - 2))}╯`);
1154
+ const innerWidth = Math.max(4, cols - 8);
1155
+ const headerLines = (model.activeRun || Boolean(model.thinking)) && !model.approvalPrompt && maxDockLines >= 4
1156
+ ? [renderActivityLine(model, cols, p)]
1157
+ : [];
1158
+ if ((model.activeRun || model.thinking) && model.queuedPrompt) {
1159
+ const { text, count } = model.queuedPrompt;
1160
+ const prefix = `↳ Queued (${count}): "`;
1161
+ const suffix = `"${count > 1 ? ` (+${count - 1})` : ''} · Alt+Enter / /steer 插队`;
1162
+ const budget = Math.max(0, cols - stringDisplayWidth(prefix + suffix));
1163
+ const plain = terminalText(text).replace(/\s+/g, ' ').trim();
1164
+ const summary = stringDisplayWidth(plain) <= budget
1165
+ ? plain
1166
+ : budget > 0
1167
+ ? truncateDisplay(plain, budget - 1) + '…'
1168
+ : '';
1169
+ const line = budget
1170
+ ? prefix + summary + suffix
1171
+ : `↳ Queued (${count})${count > 1 ? ` (+${count - 1})` : ''}: ${plain}`;
1172
+ headerLines.push(p.dim(truncateDisplay(line, cols)));
1173
+ }
1174
+ const topBorderIndex = headerLines.length;
1175
+ const metadata = renderDockMetadata(model, cols, p);
1176
+ const status = renderDockStatus(model, cols, p, hideBoard).slice(0, Math.max(0, maxDockLines - 3 - headerLines.length - metadata.length));
1177
+ const maxInputLines = Math.max(1, Math.min(4, maxDockLines - 2 - headerLines.length - metadata.length - status.length));
1178
+ const lines = [...headerLines, topBorder];
1179
+ let cursorInputRowOffset = topBorderIndex + 1;
1180
+ let cursorCol = Math.min(cols - 1, 6);
1181
+ let cursorVisible = true;
1182
+ let composerScrollOffset = 0;
1183
+ let composerMaxScroll = 0;
1184
+ let composerRows = [];
1185
+ let visibleInputCount = 1;
1186
+ if (!model.buffer.length) {
1187
+ const placeholder = truncateDisplay('输入任务或 / 命令...', innerWidth);
1188
+ const pad = ' '.repeat(Math.max(0, innerWidth - stringDisplayWidth(placeholder)));
1189
+ lines.push(`${borderColor('│')} ${p.brightCyan('◎ >')} ${p.dim(placeholder)}${pad} ${borderColor('│')}`);
1190
+ }
1191
+ else {
1192
+ const visualLines = wrapBuffer(model.buffer, innerWidth);
1193
+ const active = locateCursor(visualLines, model.cursor);
1194
+ composerMaxScroll = Math.max(0, visualLines.length - maxInputLines);
1195
+ const defaultWindowStart = Math.max(0, Math.min(active.row - maxInputLines + 1, composerMaxScroll));
1196
+ composerScrollOffset =
1197
+ model.composerScrollOffset !== undefined
1198
+ ? Math.max(0, Math.min(model.composerScrollOffset, composerMaxScroll))
1199
+ : defaultWindowStart;
1200
+ const windowEnd = Math.min(visualLines.length, composerScrollOffset + maxInputLines);
1201
+ visibleInputCount = Math.max(1, windowEnd - composerScrollOffset);
1202
+ for (let i = composerScrollOffset; i < windowEnd; i++) {
1203
+ const vline = visualLines[i];
1204
+ const lead = i === 0 ? p.brightCyan('◎ >') : ' ';
1205
+ const content = padEndDisplay(truncateDisplay(vline.text, innerWidth), innerWidth);
1206
+ lines.push(`${borderColor('│')} ${lead} ${content} ${borderColor('│')}`);
1207
+ }
1208
+ composerRows = visualLines.map((vline, i) => ({
1209
+ text: vline.text,
1210
+ indent: 6,
1211
+ soft: i > 0 && vline.startOffset === visualLines[i - 1].endOffset,
1212
+ columns: 6 + innerWidth,
1213
+ }));
1214
+ cursorVisible = active.row >= composerScrollOffset && active.row < windowEnd;
1215
+ cursorInputRowOffset =
1216
+ topBorderIndex + 1 + Math.max(0, Math.min(visibleInputCount - 1, active.row - composerScrollOffset));
1217
+ cursorCol = Math.min(cols - 2, 6 + active.col);
1218
+ }
1219
+ lines.push(botBorder);
1220
+ lines.push(...metadata, ...status);
1221
+ return {
1222
+ lines,
1223
+ cursorInputRowOffset,
1224
+ cursorCol,
1225
+ cursorVisible,
1226
+ composerTopOffset: topBorderIndex + 1,
1227
+ composerBottomOffset: topBorderIndex + visibleInputCount,
1228
+ composerColStart: 7,
1229
+ composerColEnd: 6 + innerWidth,
1230
+ composerScrollOffset,
1231
+ composerMaxScroll,
1232
+ composerRows,
1233
+ };
1234
+ }
1235
+ export function renderOrbitalFrame(model, cols, rows, anchor) {
1236
+ const safeCols = Math.max(20, Math.floor(cols));
1237
+ const safeRows = Math.max(10, Math.floor(rows));
1238
+ const p = createTerminalPainter(terminalColorEnabled(model.color));
1239
+ const wide = safeCols >= 100 && model.showSidebar;
1240
+ const modal = model.secretPrompt || model.choicePicker;
1241
+ const maxDockLines = safeRows - (modal ? 3 : 1);
1242
+ const dock = renderInputDock(model, safeCols, maxDockLines, p, wide);
1243
+ const bodyHeight = Math.max(1, safeRows - dock.lines.length);
1244
+ const tree = wide ? satelliteTree(model.satellites) : [];
1245
+ const liveWorkers = model.activeRun && model.liveAgents && tree.length > 1;
1246
+ const rightWidth = wide ? Math.max(liveWorkers ? 36 : 28, Math.floor(safeCols * 0.28)) : 0;
1247
+ const leftWidth = wide ? Math.max(10, safeCols - rightWidth - 1) : safeCols;
1248
+ const palette = model.paletteDismissed
1249
+ ? undefined
1250
+ : (model.paletteState ?? resolvePaletteState(model.buffer, SLASH_COMMAND_HINTS, model));
1251
+ const sideQuestion = model.sideQuestion
1252
+ ? renderSideQuestionOverlay(model.sideQuestion, leftWidth, bodyHeight, model.spinnerFrame ?? 0, p)
1253
+ : undefined;
1254
+ const overlays = [];
1255
+ if (model.secretPrompt) {
1256
+ overlays.push(...renderSecretOverlay(model.secretPrompt, leftWidth, p));
1257
+ }
1258
+ else if (model.choicePicker) {
1259
+ overlays.push(...renderChoiceOverlay(model.choicePicker, leftWidth, p, bodyHeight));
1260
+ }
1261
+ else if (sideQuestion) {
1262
+ overlays.push(...sideQuestion.lines);
1263
+ }
1264
+ else if (model.approvalPrompt) {
1265
+ overlays.push(...renderApprovalOverlay(model.approvalPrompt, leftWidth, p, model.showDetails, bodyHeight));
1266
+ }
1267
+ if (!modal && !sideQuestion && palette) {
1268
+ overlays.push(...renderPaletteOverlay(palette, model.paletteIndex ?? 0, leftWidth, p, bodyHeight));
1269
+ }
1270
+ const clippedOverlays = overlays.length > bodyHeight ? overlays.slice(-bodyHeight) : overlays;
1271
+ const baseHeight = Math.max(0, bodyHeight - clippedOverlays.length);
1272
+ const feed = renderFeedPane(model, leftWidth, baseHeight, p, anchor);
1273
+ const baseLeftRows = model.entries.length ? feed.lines : renderLandingPane(model, leftWidth, baseHeight, p);
1274
+ const overlayRows = clippedOverlays.map((line) => fitCell(line, leftWidth));
1275
+ const leftRows = sideQuestion && !modal ? [...overlayRows, ...baseLeftRows] : [...baseLeftRows, ...overlayRows];
1276
+ const sidebar = wide
1277
+ ? renderSidebarLines(model, tree, rightWidth, bodyHeight, p, leftWidth + 2)
1278
+ : undefined;
1279
+ const rightRows = sidebar?.lines ?? [];
1280
+ const sidebarTargets = sidebar?.targets ?? [];
1281
+ const bodyRows = [];
1282
+ for (let i = 0; i < bodyHeight; i++) {
1283
+ const leftCell = fitCell(leftRows[i] ?? '', leftWidth);
1284
+ if (wide) {
1285
+ const rightCell = fitCell(rightRows[i] ?? '', rightWidth);
1286
+ bodyRows.push(`${leftCell}${p.dim('│')}${rightCell}`);
1287
+ }
1288
+ else {
1289
+ bodyRows.push(leftCell);
1290
+ }
1291
+ }
1292
+ const allLines = [...bodyRows, ...dock.lines].map((line) => truncateDisplay(line, safeCols));
1293
+ const cursorRow = Math.max(0, Math.min(safeRows - 1, bodyHeight + dock.cursorInputRowOffset));
1294
+ const cursorCol = Math.max(0, Math.min(safeCols - 1, dock.cursorCol));
1295
+ return {
1296
+ lines: allLines.slice(0, safeRows),
1297
+ cursorRow,
1298
+ cursorCol,
1299
+ cursorVisible: !modal && !sideQuestion && dock.cursorVisible,
1300
+ ...(sideQuestion ? { sideQuestionMaxScroll: sideQuestion.maxScroll } : {}),
1301
+ selectionRows: feed.selectionRows,
1302
+ allSelectionRows: feed.allSelectionRows,
1303
+ feedStartIndex: feed.feedStartIndex,
1304
+ composerRegion: {
1305
+ topRow: bodyHeight + dock.composerTopOffset + 1,
1306
+ bottomRow: bodyHeight + dock.composerBottomOffset + 1,
1307
+ colStart: dock.composerColStart,
1308
+ colEnd: dock.composerColEnd,
1309
+ scrollOffset: dock.composerScrollOffset,
1310
+ maxScroll: dock.composerMaxScroll,
1311
+ rows: dock.composerRows,
1312
+ },
1313
+ sidebarTargets,
1314
+ sidebarNavigation: sidebar?.navigation,
1315
+ viewport: {
1316
+ columns: leftWidth,
1317
+ rows: baseHeight,
1318
+ offset: feed.offset,
1319
+ maxOffset: feed.maxOffset,
1320
+ ...(feed.anchor ? { anchor: feed.anchor } : {}),
1321
+ },
1322
+ };
1323
+ }
1324
+ export function createOrbitalTui(options) {
1325
+ const stdin = process.stdin;
1326
+ const stdout = process.stdout;
1327
+ const hints = options.hints;
1328
+ let telemetry = { ...options.initialModel };
1329
+ const entries = [];
1330
+ let scrollOffset = 0;
1331
+ let scrollAnchor;
1332
+ let viewport;
1333
+ let lastFrame;
1334
+ let selection;
1335
+ let dragScrollTimer;
1336
+ let composerScrollOffset = 0;
1337
+ let copying = false;
1338
+ let showDetails = false;
1339
+ let focusArea = 'composer';
1340
+ let focusedSatelliteId;
1341
+ let buffer = '';
1342
+ let cursor = 0;
1343
+ let paletteDismissed = false;
1344
+ let paletteIndex = 0;
1345
+ let paletteNavigated = false;
1346
+ let spinnerFrame = 0;
1347
+ let approvalPrompt;
1348
+ let choicePicker;
1349
+ let secretPrompt;
1350
+ let sideQuestion;
1351
+ let sideRequest;
1352
+ let statusHint;
1353
+ const history = [];
1354
+ let historyIndex = 0;
1355
+ let draftBeforeHistory = '';
1356
+ let entered = false;
1357
+ let left = false;
1358
+ let wasRaw = false;
1359
+ let restoreKeyboard = '';
1360
+ const terminalSignals = ['SIGINT', 'SIGTERM', 'SIGHUP'];
1361
+ let spinTimer;
1362
+ let ctrlCTimer;
1363
+ let ctrlCArmed = false;
1364
+ let pendingRender;
1365
+ let detachHandler;
1366
+ let interruptHandler;
1367
+ let immediateHandler;
1368
+ let steerHandler;
1369
+ let navigationHandler;
1370
+ let selectSatelliteHandler;
1371
+ let olderHistoryHandler;
1372
+ let paste;
1373
+ const submissionQueue = [];
1374
+ const isPrompt = (value) => value !== null && value.trim().length > 0 && !value.trimStart().startsWith('/');
1375
+ let submissionWaiter;
1376
+ let approvalWaiter;
1377
+ let choiceWaiter;
1378
+ const isPaletteVisible = () => !paletteDismissed && isSlashDraft(buffer);
1379
+ const getPaletteState = () => paletteDismissed ? undefined : resolvePaletteState(buffer, hints, telemetry);
1380
+ const buildViewModel = () => {
1381
+ const prompts = submissionQueue.filter(isPrompt);
1382
+ return {
1383
+ ...telemetry,
1384
+ spinnerFrame,
1385
+ entries,
1386
+ scrollOffset,
1387
+ showDetails,
1388
+ focusArea,
1389
+ focusedSatelliteId,
1390
+ buffer,
1391
+ cursor,
1392
+ composerScrollOffset,
1393
+ queuedCount: telemetry.queuedCount ?? prompts.length,
1394
+ queuedPrompt: prompts.length ? { text: prompts[0], count: prompts.length } : undefined,
1395
+ paletteDismissed,
1396
+ paletteState: getPaletteState(),
1397
+ paletteIndex,
1398
+ ...(approvalPrompt ? { approvalPrompt } : {}),
1399
+ ...(choicePicker ? { choicePicker } : {}),
1400
+ ...(secretPrompt
1401
+ ? {
1402
+ secretPrompt: {
1403
+ label: secretPrompt.label,
1404
+ maskLength: Array.from(segmentGraphemes(secretPrompt.value)).length,
1405
+ },
1406
+ }
1407
+ : {}),
1408
+ ...(sideQuestion ? { sideQuestion } : {}),
1409
+ ...(statusHint ? { statusHint } : {}),
1410
+ };
1411
+ };
1412
+ const renderNow = () => {
1413
+ if (!entered || left)
1414
+ return;
1415
+ syncSpinner();
1416
+ const cols = Math.max(20, stdout.columns ?? 100);
1417
+ const rows = Math.max(10, stdout.rows ?? 30);
1418
+ const frame = renderOrbitalFrame(buildViewModel(), cols, rows, scrollOffset > 0 ? scrollAnchor : undefined);
1419
+ lastFrame = frame;
1420
+ if (focusArea === 'sidebar') {
1421
+ const navigation = frame.sidebarNavigation;
1422
+ if (navigation)
1423
+ focusedSatelliteId = navigation.memberIds[navigation.selectedIndex];
1424
+ else
1425
+ focusArea = 'composer';
1426
+ }
1427
+ viewport = frame.viewport;
1428
+ composerScrollOffset = frame.composerRegion.scrollOffset;
1429
+ if (viewport.rows > 0) {
1430
+ scrollOffset = viewport.offset;
1431
+ scrollAnchor = viewport.anchor;
1432
+ }
1433
+ const body = frame.lines.map((line, i) => `\x1b[${i + 1};1H${fitCell(line, cols)}`).join('');
1434
+ let overlay = '';
1435
+ if (selection &&
1436
+ !(selection.start.x === selection.end.x && selection.start.absRow === selection.end.absRow)) {
1437
+ if (selection.target === 'feed' && frame.allSelectionRows.length > 0 && frame.viewport.rows > 0) {
1438
+ const maxRow = frame.allSelectionRows.length;
1439
+ const highlight = selectRows(frame.allSelectionRows, { x: selection.start.x, y: Math.max(1, Math.min(selection.start.absRow, maxRow)) }, { x: selection.end.x, y: Math.max(1, Math.min(selection.end.absRow, maxRow)) });
1440
+ overlay = highlight.parts
1441
+ .map(({ from, to, text }, index) => {
1442
+ const screenIdx = highlight.firstRow + index - frame.feedStartIndex;
1443
+ if (screenIdx < 0 || screenIdx >= frame.viewport.rows || from < 0 || to <= from)
1444
+ return '';
1445
+ return `\x1b[${screenIdx + 1};${from + 1}H\x1b[7m${text}\x1b[0m`;
1446
+ })
1447
+ .join('');
1448
+ }
1449
+ else if (selection.target === 'composer' && frame.composerRegion.rows.length > 0) {
1450
+ const cr = frame.composerRegion;
1451
+ const maxRow = cr.rows.length;
1452
+ const highlight = selectRows(cr.rows, { x: selection.start.x, y: Math.max(1, Math.min(selection.start.absRow, maxRow)) }, { x: selection.end.x, y: Math.max(1, Math.min(selection.end.absRow, maxRow)) });
1453
+ const visCount = cr.bottomRow - cr.topRow + 1;
1454
+ overlay = highlight.parts
1455
+ .map(({ from, to, text }, index) => {
1456
+ const relIdx = highlight.firstRow + index - cr.scrollOffset;
1457
+ if (relIdx < 0 || relIdx >= visCount || from < 0 || to <= from)
1458
+ return '';
1459
+ return `\x1b[${cr.topRow + relIdx};${from + 1}H\x1b[7m${text}\x1b[0m`;
1460
+ })
1461
+ .join('');
1462
+ }
1463
+ }
1464
+ const showCursorSeq = focusArea === 'sidebar' || frame.cursorVisible === false
1465
+ ? '\x1b[?25l'
1466
+ : `\x1b[${frame.cursorRow + 1};${frame.cursorCol + 1}H\x1b[?25h`;
1467
+ stdout.write(`\x1b[?25l\x1b[?7l${body}${overlay}\x1b[?7h${showCursorSeq}`);
1468
+ };
1469
+ function queueRender() {
1470
+ if (pendingRender)
1471
+ return;
1472
+ pendingRender = setImmediate(() => {
1473
+ pendingRender = undefined;
1474
+ renderNow();
1475
+ });
1476
+ }
1477
+ function setEntry(entry, key, beforeKey) {
1478
+ const text = entry.text.replace(/\n+$/, '');
1479
+ if (!text && !entry.detail && !entry.activity)
1480
+ return;
1481
+ const next = { ...entry, text, ...(key ? { key } : {}) };
1482
+ const index = key ? entries.findIndex((item) => item.key === key) : -1;
1483
+ if (index >= 0)
1484
+ entries[index] = next;
1485
+ else {
1486
+ const before = beforeKey ? entries.findIndex((item) => item.key === beforeKey) : -1;
1487
+ if (before < 0)
1488
+ entries.push(next);
1489
+ else {
1490
+ entries.splice(before, 0, next);
1491
+ if (scrollAnchor && scrollAnchor.entry >= before)
1492
+ scrollAnchor = { ...scrollAnchor, entry: scrollAnchor.entry + 1 };
1493
+ }
1494
+ }
1495
+ queueRender();
1496
+ }
1497
+ function removeEntry(key) {
1498
+ const index = entries.findIndex((entry) => entry.key === key);
1499
+ if (index < 0)
1500
+ return;
1501
+ entries.splice(index, 1);
1502
+ if (scrollAnchor && scrollAnchor.entry > index)
1503
+ scrollAnchor = { ...scrollAnchor, entry: scrollAnchor.entry - 1 };
1504
+ queueRender();
1505
+ }
1506
+ function clearDragScroll() {
1507
+ if (dragScrollTimer) {
1508
+ clearInterval(dragScrollTimer);
1509
+ dragScrollTimer = undefined;
1510
+ }
1511
+ }
1512
+ function triggerCopySelection(text) {
1513
+ if (copying || !text.trim())
1514
+ return;
1515
+ copying = true;
1516
+ void copySelection(text, (sequence) => {
1517
+ if (!left)
1518
+ stdout.write(sequence);
1519
+ })
1520
+ .then((result) => {
1521
+ statusHint = result === 'copied' ? '已复制' : result === 'sent' ? '已发送到终端' : '剪贴板不可用';
1522
+ }, () => {
1523
+ statusHint = '剪贴板不可用';
1524
+ })
1525
+ .finally(() => {
1526
+ copying = false;
1527
+ renderNow();
1528
+ });
1529
+ }
1530
+ function selectedText(sel, frame) {
1531
+ const rows = sel.target === 'feed' ? frame.allSelectionRows : frame.composerRegion.rows;
1532
+ if (!rows.length)
1533
+ return '';
1534
+ return selectRows(rows, { x: sel.start.x, y: Math.max(1, Math.min(sel.start.absRow, rows.length)) }, { x: sel.end.x, y: Math.max(1, Math.min(sel.end.absRow, rows.length)) }).text;
1535
+ }
1536
+ function updateFeedDragEnd(x, y, frame) {
1537
+ if (!selection || selection.target !== 'feed')
1538
+ return;
1539
+ const maxRow = Math.max(1, frame.allSelectionRows.length);
1540
+ const visRows = Math.max(1, frame.selectionRows.length);
1541
+ const clampedX = Math.max(1, Math.min(x, frame.viewport.columns));
1542
+ const clampedY = Math.max(1, Math.min(y, visRows));
1543
+ selection.end = {
1544
+ x: clampedX,
1545
+ absRow: Math.max(1, Math.min(maxRow, frame.feedStartIndex + clampedY)),
1546
+ };
1547
+ }
1548
+ function updateComposerDragEnd(x, y, frame) {
1549
+ if (!selection || selection.target !== 'composer')
1550
+ return;
1551
+ const cr = frame.composerRegion;
1552
+ const maxRow = Math.max(1, cr.rows.length);
1553
+ const clampedX = Math.max(cr.colStart, Math.min(x, cr.colEnd));
1554
+ const clampedY = Math.max(cr.topRow, Math.min(y, cr.bottomRow));
1555
+ selection.end = {
1556
+ x: clampedX,
1557
+ absRow: Math.max(1, Math.min(maxRow, composerScrollOffset + (clampedY - cr.topRow) + 1)),
1558
+ };
1559
+ }
1560
+ function scrollBy(delta) {
1561
+ if (!viewport?.rows)
1562
+ return;
1563
+ const offset = Math.max(0, Math.min(viewport.maxOffset, scrollOffset + delta));
1564
+ if (delta > 0 && offset === viewport.maxOffset) {
1565
+ if (!scrollOffset && viewport.maxOffset === 0)
1566
+ scrollAnchor = viewport.anchor;
1567
+ olderHistoryHandler?.();
1568
+ }
1569
+ if (offset === scrollOffset)
1570
+ return;
1571
+ scrollOffset = offset;
1572
+ scrollAnchor = undefined;
1573
+ renderNow();
1574
+ }
1575
+ function syncDragEdgeScroll(y) {
1576
+ if (!selection || !selection.dragging || selection.target !== 'feed' || !viewport?.rows) {
1577
+ clearDragScroll();
1578
+ return;
1579
+ }
1580
+ const atTopEdge = y <= 1 && scrollOffset < viewport.maxOffset;
1581
+ const atBottomEdge = y >= viewport.rows && scrollOffset > 0;
1582
+ if (!atTopEdge && !atBottomEdge) {
1583
+ clearDragScroll();
1584
+ return;
1585
+ }
1586
+ if (dragScrollTimer)
1587
+ return;
1588
+ dragScrollTimer = setInterval(() => {
1589
+ if (!selection || !selection.dragging || selection.target !== 'feed' || !viewport?.rows) {
1590
+ clearDragScroll();
1591
+ return;
1592
+ }
1593
+ const px = selection.pointerX;
1594
+ const py = selection.pointerY;
1595
+ if (py <= 1 && scrollOffset < viewport.maxOffset) {
1596
+ scrollBy(1);
1597
+ if (lastFrame)
1598
+ updateFeedDragEnd(px, 1, lastFrame);
1599
+ renderNow();
1600
+ }
1601
+ else if (py >= viewport.rows && scrollOffset > 0) {
1602
+ scrollBy(-1);
1603
+ if (lastFrame)
1604
+ updateFeedDragEnd(px, lastFrame.viewport.rows, lastFrame);
1605
+ renderNow();
1606
+ }
1607
+ else {
1608
+ clearDragScroll();
1609
+ }
1610
+ }, 80);
1611
+ dragScrollTimer.unref();
1612
+ }
1613
+ const keyboardInput = new PassThrough();
1614
+ readline.emitKeypressEvents(keyboardInput);
1615
+ const terminalInput = createTerminalInput((text) => {
1616
+ const enhanced = decodeEnhancedKey(text);
1617
+ if (enhanced)
1618
+ onKeypress(enhanced.text, enhanced.key);
1619
+ else
1620
+ keyboardInput.write(text);
1621
+ }, ({ x, y, direction }) => {
1622
+ if (sideQuestion || choicePicker || secretPrompt)
1623
+ return;
1624
+ if (viewport && x >= 1 && x <= viewport.columns && y >= 1 && y <= viewport.rows) {
1625
+ scrollBy(-direction * 3);
1626
+ if (selection?.target === 'feed' && selection.dragging && lastFrame) {
1627
+ updateFeedDragEnd(selection.pointerX, selection.pointerY, lastFrame);
1628
+ renderNow();
1629
+ }
1630
+ return;
1631
+ }
1632
+ if (lastFrame &&
1633
+ lastFrame.composerRegion.maxScroll > 0 &&
1634
+ y >= lastFrame.composerRegion.topRow &&
1635
+ y <= lastFrame.composerRegion.bottomRow) {
1636
+ const next = Math.max(0, Math.min(lastFrame.composerRegion.maxScroll, composerScrollOffset + direction));
1637
+ if (next !== composerScrollOffset) {
1638
+ composerScrollOffset = next;
1639
+ if (selection?.target === 'composer' && selection.dragging) {
1640
+ updateComposerDragEnd(selection.pointerX, selection.pointerY, lastFrame);
1641
+ }
1642
+ renderNow();
1643
+ }
1644
+ }
1645
+ }, ({ kind, x, y }) => {
1646
+ if (sideQuestion || approvalPrompt || choicePicker || secretPrompt || isPaletteVisible())
1647
+ return;
1648
+ if (kind === 'down') {
1649
+ clearDragScroll();
1650
+ const hit = lastFrame?.sidebarTargets.find((target) => target.row === y && x >= target.colStart && x <= target.colEnd);
1651
+ if (hit) {
1652
+ selection = undefined;
1653
+ focusedSatelliteId = hit.memberId;
1654
+ renderNow();
1655
+ selectSatelliteHandler?.(hit.memberId);
1656
+ return;
1657
+ }
1658
+ if (lastFrame &&
1659
+ y >= 1 &&
1660
+ y <= lastFrame.selectionRows.length &&
1661
+ x >= 1 &&
1662
+ x <= lastFrame.viewport.columns &&
1663
+ lastFrame.allSelectionRows.length > 0) {
1664
+ const absRow = Math.max(1, Math.min(lastFrame.allSelectionRows.length, lastFrame.feedStartIndex + y));
1665
+ selection = {
1666
+ target: 'feed',
1667
+ start: { x, absRow },
1668
+ end: { x, absRow },
1669
+ dragging: true,
1670
+ pointerX: x,
1671
+ pointerY: y,
1672
+ };
1673
+ return;
1674
+ }
1675
+ if (lastFrame &&
1676
+ lastFrame.composerRegion.rows.length > 0 &&
1677
+ y >= lastFrame.composerRegion.topRow &&
1678
+ y <= lastFrame.composerRegion.bottomRow) {
1679
+ const cr = lastFrame.composerRegion;
1680
+ const clampedX = Math.max(cr.colStart, Math.min(x, cr.colEnd));
1681
+ const absRow = Math.max(1, Math.min(cr.rows.length, composerScrollOffset + (y - cr.topRow) + 1));
1682
+ selection = {
1683
+ target: 'composer',
1684
+ start: { x: clampedX, absRow },
1685
+ end: { x: clampedX, absRow },
1686
+ dragging: true,
1687
+ pointerX: x,
1688
+ pointerY: y,
1689
+ };
1690
+ return;
1691
+ }
1692
+ if (selection) {
1693
+ selection = undefined;
1694
+ renderNow();
1695
+ }
1696
+ return;
1697
+ }
1698
+ if (!selection || !selection.dragging || !lastFrame)
1699
+ return;
1700
+ selection.pointerX = x;
1701
+ selection.pointerY = y;
1702
+ if (selection.target === 'feed') {
1703
+ updateFeedDragEnd(x, y, lastFrame);
1704
+ }
1705
+ else {
1706
+ const cr = lastFrame.composerRegion;
1707
+ if (y < cr.topRow && composerScrollOffset > 0) {
1708
+ composerScrollOffset = Math.max(0, composerScrollOffset - 1);
1709
+ }
1710
+ else if (y > cr.bottomRow && composerScrollOffset < cr.maxScroll) {
1711
+ composerScrollOffset = Math.min(cr.maxScroll, composerScrollOffset + 1);
1712
+ }
1713
+ updateComposerDragEnd(x, y, lastFrame);
1714
+ }
1715
+ if (kind === 'drag') {
1716
+ syncDragEdgeScroll(y);
1717
+ renderNow();
1718
+ return;
1719
+ }
1720
+ clearDragScroll();
1721
+ selection.dragging = false;
1722
+ if (selection.start.x === selection.end.x && selection.start.absRow === selection.end.absRow) {
1723
+ selection = undefined;
1724
+ renderNow();
1725
+ return;
1726
+ }
1727
+ const text = selectedText(selection, lastFrame);
1728
+ renderNow();
1729
+ triggerCopySelection(text);
1730
+ }, ({ kind, y }) => {
1731
+ if (kind !== 'down' ||
1732
+ sideQuestion ||
1733
+ approvalPrompt ||
1734
+ choicePicker ||
1735
+ secretPrompt ||
1736
+ isPaletteVisible())
1737
+ return;
1738
+ clearDragScroll();
1739
+ if (selection && lastFrame) {
1740
+ const text = selectedText(selection, lastFrame);
1741
+ selection = undefined;
1742
+ if (text.trim()) {
1743
+ triggerCopySelection(text);
1744
+ }
1745
+ else {
1746
+ renderNow();
1747
+ }
1748
+ return;
1749
+ }
1750
+ if (lastFrame &&
1751
+ y >= lastFrame.composerRegion.topRow &&
1752
+ y <= lastFrame.composerRegion.bottomRow &&
1753
+ buffer.length > 0) {
1754
+ triggerCopySelection(buffer);
1755
+ }
1756
+ });
1757
+ function restoreTerminal() {
1758
+ if (restoreKeyboard)
1759
+ stdout.write(restoreKeyboard);
1760
+ restoreKeyboard = '';
1761
+ stdout.write('\x1b[?7h\x1b[?2004l\x1b[?1006l\x1b[?1002l\x1b[?25h\x1b[0m\x1b[?1049l');
1762
+ if (stdin.isTTY)
1763
+ stdin.setRawMode(wasRaw);
1764
+ }
1765
+ function restoreOnSignal(signal) {
1766
+ process.off('exit', restoreTerminal);
1767
+ restoreTerminal();
1768
+ // The one-time listener is gone. Preserve the signal's normal exit status.
1769
+ process.kill(process.pid, signal);
1770
+ }
1771
+ const syncSpinner = () => {
1772
+ const shouldAnimate = entered &&
1773
+ !left &&
1774
+ (entries.length === 0 ||
1775
+ telemetry.hostPhase === 'connecting' ||
1776
+ telemetry.activeRun ||
1777
+ Boolean(telemetry.thinking) ||
1778
+ Boolean(sideQuestion && sideQuestion.result === undefined));
1779
+ if (shouldAnimate && !spinTimer) {
1780
+ spinTimer = setInterval(() => {
1781
+ spinnerFrame = (spinnerFrame + 1) % 1000000;
1782
+ renderNow();
1783
+ }, spinnerFrameMs);
1784
+ spinTimer.unref();
1785
+ }
1786
+ else if (!shouldAnimate && spinTimer) {
1787
+ clearInterval(spinTimer);
1788
+ spinTimer = undefined;
1789
+ }
1790
+ };
1791
+ const emitSubmission = (value) => {
1792
+ if (value !== null && immediateHandler && isImmediateSlashCommand(value)) {
1793
+ immediateHandler(value);
1794
+ return;
1795
+ }
1796
+ if (value !== null) {
1797
+ const trimmed = value.trim();
1798
+ if (trimmed && history[history.length - 1] !== trimmed) {
1799
+ history.push(trimmed);
1800
+ if (history.length > 200)
1801
+ history.shift();
1802
+ }
1803
+ historyIndex = history.length;
1804
+ draftBeforeHistory = '';
1805
+ }
1806
+ if (value !== null && navigationHandler?.(value))
1807
+ return;
1808
+ if (submissionWaiter) {
1809
+ const resolve = submissionWaiter;
1810
+ submissionWaiter = undefined;
1811
+ resolve(value);
1812
+ }
1813
+ else {
1814
+ submissionQueue.push(value);
1815
+ if (isPrompt(value) && (telemetry.activeRun || telemetry.thinking)) {
1816
+ const queued = submissionQueue.filter(isPrompt).length;
1817
+ statusHint = `已加入队列(${queued})`;
1818
+ renderNow();
1819
+ }
1820
+ }
1821
+ };
1822
+ function closeSideQuestion() {
1823
+ sideRequest?.abort();
1824
+ sideRequest = undefined;
1825
+ sideQuestion = undefined;
1826
+ syncSpinner();
1827
+ renderNow();
1828
+ }
1829
+ function steerSubmission() {
1830
+ if (!steerHandler)
1831
+ return;
1832
+ const draft = buffer;
1833
+ const queueIndex = draft.trim() ? -1 : submissionQueue.findIndex(isPrompt);
1834
+ const text = draft.trim() || (queueIndex >= 0 ? submissionQueue[queueIndex].trim() : '');
1835
+ if (!text)
1836
+ return;
1837
+ if (queueIndex >= 0)
1838
+ submissionQueue.splice(queueIndex, 1);
1839
+ else
1840
+ resetBuffer();
1841
+ renderNow();
1842
+ void steerHandler(text).then((accepted) => {
1843
+ if (accepted || left)
1844
+ return;
1845
+ if (queueIndex >= 0) {
1846
+ if (submissionWaiter)
1847
+ emitSubmission(text);
1848
+ else
1849
+ submissionQueue.splice(queueIndex, 0, text);
1850
+ }
1851
+ else if (!buffer) {
1852
+ insertText(draft);
1853
+ }
1854
+ else {
1855
+ history.push(draft);
1856
+ if (history.length > 200)
1857
+ history.shift();
1858
+ historyIndex = history.length;
1859
+ }
1860
+ renderNow();
1861
+ });
1862
+ }
1863
+ const composerInnerWidth = () => Math.max(4, Math.max(20, stdout.columns ?? 100) - 8);
1864
+ const composerMaxVisibleLines = () => lastFrame ? Math.max(1, lastFrame.composerRegion.bottomRow - lastFrame.composerRegion.topRow + 1) : 4;
1865
+ const syncComposerScrollToCursor = () => {
1866
+ if (!buffer.length) {
1867
+ composerScrollOffset = 0;
1868
+ return;
1869
+ }
1870
+ cursor = normalizeCursorOffset(buffer, cursor);
1871
+ const visualLines = wrapBuffer(buffer, composerInnerWidth());
1872
+ const active = locateCursor(visualLines, cursor);
1873
+ const maxLines = composerMaxVisibleLines();
1874
+ const maxScroll = Math.max(0, visualLines.length - maxLines);
1875
+ if (active.row < composerScrollOffset)
1876
+ composerScrollOffset = active.row;
1877
+ else if (active.row >= composerScrollOffset + maxLines) {
1878
+ composerScrollOffset = active.row - maxLines + 1;
1879
+ }
1880
+ composerScrollOffset = Math.max(0, Math.min(composerScrollOffset, maxScroll));
1881
+ };
1882
+ const moveCursorVertical = (direction) => {
1883
+ if (!buffer.length)
1884
+ return false;
1885
+ const visualLines = wrapBuffer(buffer, composerInnerWidth());
1886
+ const active = locateCursor(visualLines, cursor);
1887
+ const targetRow = active.row + direction;
1888
+ if (targetRow < 0 || targetRow >= visualLines.length)
1889
+ return false;
1890
+ cursor = offsetAtColumn(visualLines[targetRow], active.col);
1891
+ syncComposerScrollToCursor();
1892
+ return true;
1893
+ };
1894
+ const resetPalette = () => {
1895
+ paletteDismissed = false;
1896
+ paletteIndex = 0;
1897
+ paletteNavigated = false;
1898
+ };
1899
+ const resetBuffer = () => {
1900
+ buffer = '';
1901
+ cursor = 0;
1902
+ composerScrollOffset = 0;
1903
+ resetPalette();
1904
+ };
1905
+ const applyPaletteEdit = (text) => {
1906
+ buffer = text;
1907
+ cursor = buffer.length;
1908
+ resetPalette();
1909
+ renderNow();
1910
+ };
1911
+ const disarmCtrlC = () => {
1912
+ ctrlCArmed = false;
1913
+ if (ctrlCTimer) {
1914
+ clearTimeout(ctrlCTimer);
1915
+ ctrlCTimer = undefined;
1916
+ }
1917
+ };
1918
+ const onResize = () => {
1919
+ clearDragScroll();
1920
+ selection = undefined;
1921
+ syncComposerScrollToCursor();
1922
+ renderNow();
1923
+ };
1924
+ const onKeypress = (str, key) => {
1925
+ if (!entered || left)
1926
+ return;
1927
+ if (key.name === 'paste-start') {
1928
+ paste = '';
1929
+ return;
1930
+ }
1931
+ if (paste !== undefined) {
1932
+ if (key.name === 'paste-end') {
1933
+ const content = paste;
1934
+ paste = undefined;
1935
+ if (secretPrompt)
1936
+ appendSecret(content);
1937
+ else if (!approvalPrompt && !sideQuestion && !choicePicker)
1938
+ insertText(terminalText(content));
1939
+ }
1940
+ else if (str)
1941
+ paste += str;
1942
+ return;
1943
+ }
1944
+ clearDragScroll();
1945
+ const hadSelection = Boolean(selection);
1946
+ selection = undefined;
1947
+ if (!(key.ctrl && key.name === 'c')) {
1948
+ disarmCtrlC();
1949
+ }
1950
+ statusHint = undefined;
1951
+ if (secretPrompt) {
1952
+ if (key.name === 'escape' || (key.ctrl && key.name === 'c')) {
1953
+ settleSecret(null);
1954
+ }
1955
+ else if (key.name === 'return' || key.name === 'enter') {
1956
+ settleSecret(secretPrompt.value);
1957
+ }
1958
+ else if (key.name === 'backspace') {
1959
+ secretPrompt.value = secretPrompt.value.slice(0, prevCharOffset(secretPrompt.value, secretPrompt.value.length));
1960
+ queueRender();
1961
+ }
1962
+ else if (str && !key.ctrl && !key.meta) {
1963
+ appendSecret(str);
1964
+ }
1965
+ return;
1966
+ }
1967
+ if (choicePicker && choiceWaiter) {
1968
+ const { options, selectedIndex } = choicePicker;
1969
+ if (key.name === 'up' || key.name === 'down') {
1970
+ const direction = key.name === 'up' ? -1 : 1;
1971
+ choicePicker = {
1972
+ ...choicePicker,
1973
+ selectedIndex: (selectedIndex + direction + options.length) % options.length,
1974
+ };
1975
+ renderNow();
1976
+ }
1977
+ else if (key.name === 'escape' ||
1978
+ (key.ctrl && key.name === 'c') ||
1979
+ key.name === 'return' ||
1980
+ key.name === 'enter') {
1981
+ const selected = key.name === 'escape' || key.ctrl ? null : (options[selectedIndex]?.id ?? null);
1982
+ const resolve = choiceWaiter;
1983
+ choiceWaiter = undefined;
1984
+ choicePicker = undefined;
1985
+ resolve(selected);
1986
+ queueRender();
1987
+ }
1988
+ return;
1989
+ }
1990
+ if (sideQuestion) {
1991
+ if (['escape', 'return', 'enter', 'space'].includes(key.name ?? '')) {
1992
+ closeSideQuestion();
1993
+ return;
1994
+ }
1995
+ if (key.name === 'up' || key.name === 'down') {
1996
+ const scroll = Math.max(0, Math.min(lastFrame?.sideQuestionMaxScroll ?? 0, sideQuestion.scroll + (key.name === 'up' ? -1 : 1)));
1997
+ sideQuestion = { ...sideQuestion, scroll };
1998
+ renderNow();
1999
+ return;
2000
+ }
2001
+ if (!(key.ctrl && ['c', 'b', 't', 'o'].includes(key.name ?? '')))
2002
+ return;
2003
+ }
2004
+ if (approvalWaiter) {
2005
+ if (key.ctrl && key.name === 'c') {
2006
+ const resolve = approvalWaiter;
2007
+ approvalWaiter = undefined;
2008
+ approvalPrompt = undefined;
2009
+ syncSpinner();
2010
+ renderNow();
2011
+ resolve(null);
2012
+ return;
2013
+ }
2014
+ const ch = (str ?? '').trim().toLowerCase();
2015
+ if (ch === 'y' || ch === 'n' || ch === 'd') {
2016
+ const resolve = approvalWaiter;
2017
+ approvalWaiter = undefined;
2018
+ approvalPrompt = undefined;
2019
+ syncSpinner();
2020
+ renderNow();
2021
+ resolve(ch);
2022
+ return;
2023
+ }
2024
+ }
2025
+ if (key.ctrl && key.name === 'b') {
2026
+ const nextShow = !telemetry.showSidebar;
2027
+ telemetry = { ...telemetry, showSidebar: nextShow };
2028
+ if (!nextShow)
2029
+ focusArea = 'composer';
2030
+ renderNow();
2031
+ return;
2032
+ }
2033
+ if (key.ctrl && (key.name === 't' || key.name === 'o')) {
2034
+ showDetails = !showDetails;
2035
+ renderNow();
2036
+ return;
2037
+ }
2038
+ if (key.name === 'pageup') {
2039
+ const step = Math.max(3, Math.floor((stdout.rows ?? 30) / 3));
2040
+ scrollBy(step);
2041
+ return;
2042
+ }
2043
+ if (key.name === 'pagedown') {
2044
+ const step = Math.max(3, Math.floor((stdout.rows ?? 30) / 3));
2045
+ scrollBy(-step);
2046
+ return;
2047
+ }
2048
+ if (key.ctrl && key.name === 'y') {
2049
+ if (buffer.length > 0) {
2050
+ triggerCopySelection(buffer);
2051
+ }
2052
+ return;
2053
+ }
2054
+ if (approvalWaiter)
2055
+ return;
2056
+ if (key.ctrl && key.name === 'c') {
2057
+ if (telemetry.activeRun) {
2058
+ disarmCtrlC();
2059
+ detachHandler?.();
2060
+ }
2061
+ else if (buffer.length > 0) {
2062
+ disarmCtrlC();
2063
+ resetBuffer();
2064
+ renderNow();
2065
+ }
2066
+ else if (ctrlCArmed) {
2067
+ disarmCtrlC();
2068
+ emitSubmission(null);
2069
+ }
2070
+ else {
2071
+ disarmCtrlC();
2072
+ ctrlCArmed = true;
2073
+ const hint = '再按一次 Ctrl+C 退出(或输入 /exit)';
2074
+ statusHint = hint;
2075
+ ctrlCTimer = setTimeout(() => {
2076
+ ctrlCTimer = undefined;
2077
+ ctrlCArmed = false;
2078
+ if (statusHint === hint) {
2079
+ statusHint = undefined;
2080
+ renderNow();
2081
+ }
2082
+ }, 2000);
2083
+ ctrlCTimer.unref();
2084
+ renderNow();
2085
+ }
2086
+ return;
2087
+ }
2088
+ const palette = getPaletteState();
2089
+ const selectionInPalette = paletteSelection(palette, paletteIndex);
2090
+ if (focusArea === 'sidebar') {
2091
+ const navigation = lastFrame?.sidebarNavigation;
2092
+ if (!navigation || key.name === 'escape' || key.name === 'left') {
2093
+ focusArea = 'composer';
2094
+ renderNow();
2095
+ return;
2096
+ }
2097
+ const { memberIds, selectedIndex } = navigation;
2098
+ if (key.name === 'up' || key.name === 'down') {
2099
+ const direction = key.name === 'up' ? -1 : 1;
2100
+ const nextIndex = (selectedIndex + direction + memberIds.length) % memberIds.length;
2101
+ focusedSatelliteId = memberIds[nextIndex];
2102
+ renderNow();
2103
+ return;
2104
+ }
2105
+ if (key.name === 'return' || key.name === 'enter') {
2106
+ const selected = memberIds[selectedIndex];
2107
+ focusArea = 'composer';
2108
+ if (selected)
2109
+ selectSatelliteHandler?.(selected);
2110
+ renderNow();
2111
+ return;
2112
+ }
2113
+ return;
2114
+ }
2115
+ if (key.name === 'escape') {
2116
+ if (palette) {
2117
+ paletteDismissed = true;
2118
+ renderNow();
2119
+ }
2120
+ else if (hadSelection) {
2121
+ renderNow();
2122
+ }
2123
+ else if (telemetry.activeRun) {
2124
+ interruptHandler?.();
2125
+ }
2126
+ else if (buffer.length === 0 && telemetry.teamMember && telemetry.teamMember !== 'main') {
2127
+ selectSatelliteHandler?.('main');
2128
+ }
2129
+ return;
2130
+ }
2131
+ if (key.name === 'tab') {
2132
+ const action = palette && resolvePaletteAction(palette, paletteIndex, 'tab', paletteNavigated);
2133
+ if (action?.kind === 'edit')
2134
+ applyPaletteEdit(action.text);
2135
+ return;
2136
+ }
2137
+ if ((key.name === 'return' || key.name === 'enter') &&
2138
+ (key.ctrl || key.meta) &&
2139
+ (telemetry.activeRun || telemetry.thinking)) {
2140
+ steerSubmission();
2141
+ return;
2142
+ }
2143
+ if (key.sequence === '\n' || (key.ctrl && key.name === 'j')) {
2144
+ insertText('\n');
2145
+ return;
2146
+ }
2147
+ if (key.name === 'return' || key.name === 'enter') {
2148
+ if (cursor === buffer.length && buffer.endsWith('\\')) {
2149
+ buffer = buffer.slice(0, -1) + '\n';
2150
+ cursor = buffer.length;
2151
+ renderNow();
2152
+ return;
2153
+ }
2154
+ const action = palette && !isImmediateSlashCommand(buffer)
2155
+ ? resolvePaletteAction(palette, paletteIndex, 'enter', paletteNavigated)
2156
+ : undefined;
2157
+ if (action?.kind === 'edit') {
2158
+ applyPaletteEdit(action.text);
2159
+ return;
2160
+ }
2161
+ const submitted = action?.text ?? buffer;
2162
+ resetBuffer();
2163
+ renderNow();
2164
+ emitSubmission(submitted);
2165
+ return;
2166
+ }
2167
+ if (key.name === 'up') {
2168
+ if (selectionInPalette.count > 0) {
2169
+ const { index, count } = selectionInPalette;
2170
+ paletteIndex = (index - 1 + count) % count;
2171
+ paletteNavigated = true;
2172
+ renderNow();
2173
+ return;
2174
+ }
2175
+ if (moveCursorVertical(-1)) {
2176
+ renderNow();
2177
+ return;
2178
+ }
2179
+ if (history.length > 0 && historyIndex > 0) {
2180
+ if (historyIndex === history.length)
2181
+ draftBeforeHistory = buffer;
2182
+ historyIndex--;
2183
+ buffer = history[historyIndex];
2184
+ cursor = buffer.length;
2185
+ syncComposerScrollToCursor();
2186
+ paletteDismissed = true;
2187
+ paletteNavigated = false;
2188
+ renderNow();
2189
+ }
2190
+ return;
2191
+ }
2192
+ if (key.name === 'down') {
2193
+ if (selectionInPalette.count > 0) {
2194
+ paletteIndex = (selectionInPalette.index + 1) % selectionInPalette.count;
2195
+ paletteNavigated = true;
2196
+ renderNow();
2197
+ return;
2198
+ }
2199
+ if (moveCursorVertical(1)) {
2200
+ renderNow();
2201
+ return;
2202
+ }
2203
+ if (historyIndex < history.length) {
2204
+ historyIndex++;
2205
+ buffer = historyIndex === history.length ? draftBeforeHistory : history[historyIndex];
2206
+ cursor = buffer.length;
2207
+ syncComposerScrollToCursor();
2208
+ paletteDismissed = true;
2209
+ paletteNavigated = false;
2210
+ renderNow();
2211
+ }
2212
+ return;
2213
+ }
2214
+ if (key.name === 'backspace') {
2215
+ if (cursor > 0) {
2216
+ const prev = prevCharOffset(buffer, cursor);
2217
+ buffer = buffer.slice(0, prev) + buffer.slice(cursor);
2218
+ cursor = prev;
2219
+ syncComposerScrollToCursor();
2220
+ resetPalette();
2221
+ renderNow();
2222
+ }
2223
+ return;
2224
+ }
2225
+ if (key.name === 'delete') {
2226
+ if (cursor < buffer.length) {
2227
+ const next = nextCharOffset(buffer, cursor);
2228
+ buffer = buffer.slice(0, cursor) + buffer.slice(next);
2229
+ syncComposerScrollToCursor();
2230
+ resetPalette();
2231
+ renderNow();
2232
+ }
2233
+ return;
2234
+ }
2235
+ if (key.ctrl && key.name === 'a') {
2236
+ cursor = 0;
2237
+ syncComposerScrollToCursor();
2238
+ renderNow();
2239
+ return;
2240
+ }
2241
+ if (key.ctrl && key.name === 'e') {
2242
+ cursor = buffer.length;
2243
+ syncComposerScrollToCursor();
2244
+ renderNow();
2245
+ return;
2246
+ }
2247
+ if (key.ctrl && key.name === 'u') {
2248
+ buffer = buffer.slice(cursor);
2249
+ cursor = 0;
2250
+ syncComposerScrollToCursor();
2251
+ resetPalette();
2252
+ renderNow();
2253
+ return;
2254
+ }
2255
+ if (key.ctrl && key.name === 'w') {
2256
+ const prev = prevWordOffset(buffer, cursor);
2257
+ buffer = buffer.slice(0, prev) + buffer.slice(cursor);
2258
+ cursor = prev;
2259
+ syncComposerScrollToCursor();
2260
+ resetPalette();
2261
+ renderNow();
2262
+ return;
2263
+ }
2264
+ if (key.name === 'left') {
2265
+ cursor = prevCharOffset(buffer, cursor);
2266
+ syncComposerScrollToCursor();
2267
+ renderNow();
2268
+ return;
2269
+ }
2270
+ if (key.name === 'right') {
2271
+ if ((key.ctrl || buffer.length === 0) && lastFrame?.sidebarNavigation) {
2272
+ focusArea = 'sidebar';
2273
+ focusedSatelliteId = telemetry.teamMember ?? 'main';
2274
+ renderNow();
2275
+ return;
2276
+ }
2277
+ cursor = nextCharOffset(buffer, cursor);
2278
+ syncComposerScrollToCursor();
2279
+ renderNow();
2280
+ return;
2281
+ }
2282
+ if (key.name === 'home') {
2283
+ cursor = 0;
2284
+ syncComposerScrollToCursor();
2285
+ renderNow();
2286
+ return;
2287
+ }
2288
+ if (key.name === 'end') {
2289
+ cursor = buffer.length;
2290
+ syncComposerScrollToCursor();
2291
+ renderNow();
2292
+ return;
2293
+ }
2294
+ if (str && !key.ctrl && !key.meta) {
2295
+ const normalized = str.replace(/\r\n?/g, '\n');
2296
+ if ([...normalized].some((ch) => (ch.codePointAt(0) ?? 0) >= 0x20 || ch === '\n')) {
2297
+ insertText(normalized);
2298
+ }
2299
+ }
2300
+ };
2301
+ function insertText(text) {
2302
+ buffer = buffer.slice(0, cursor) + text + buffer.slice(cursor);
2303
+ cursor += text.length;
2304
+ syncComposerScrollToCursor();
2305
+ resetPalette();
2306
+ renderNow();
2307
+ }
2308
+ function promptChoice(prompt) {
2309
+ if (left || choiceWaiter || secretPrompt || !prompt.options.length)
2310
+ return Promise.resolve(null);
2311
+ clearDragScroll();
2312
+ selection = undefined;
2313
+ choicePicker = {
2314
+ ...prompt,
2315
+ selectedIndex: Math.max(0, prompt.options.findIndex((option) => option.current)),
2316
+ };
2317
+ return new Promise((resolve) => {
2318
+ choiceWaiter = resolve;
2319
+ renderNow();
2320
+ });
2321
+ }
2322
+ function appendSecret(text) {
2323
+ if (!secretPrompt)
2324
+ return;
2325
+ secretPrompt.value += text.replace(/[\p{Cc}\p{Cf}]/gu, '');
2326
+ queueRender();
2327
+ }
2328
+ function settleSecret(value) {
2329
+ const prompt = secretPrompt;
2330
+ secretPrompt = undefined;
2331
+ if (prompt) {
2332
+ prompt.value = '';
2333
+ prompt.resolve(value);
2334
+ queueRender();
2335
+ }
2336
+ }
2337
+ return {
2338
+ enter() {
2339
+ if (entered && !left)
2340
+ return;
2341
+ entered = true;
2342
+ left = false;
2343
+ wasRaw = Boolean(stdin.isRaw);
2344
+ stdout.write('\x1b[?1049h\x1b[?2004h\x1b[?1002h\x1b[?1006h\x1b[?25h');
2345
+ process.once('exit', restoreTerminal);
2346
+ if (stdin.isTTY) {
2347
+ stdin.setRawMode(true);
2348
+ if (stdout.isTTY && process.env.TERM !== 'dumb') {
2349
+ const kitty = Boolean(process.env.KITTY_WINDOW_ID) ||
2350
+ /kitty|foot|ghostty|wezterm/i.test(`${process.env.TERM ?? ''} ${process.env.TERM_PROGRAM ?? ''}`);
2351
+ restoreKeyboard = kitty ? '\x1b[<u' : '\x1b[>4;0m\x1b[>4m';
2352
+ stdout.write(kitty ? '\x1b[>1u' : '\x1b[>4;2m');
2353
+ }
2354
+ if (process.platform !== 'win32') {
2355
+ for (const signal of terminalSignals) {
2356
+ if (!process.listenerCount(signal))
2357
+ process.once(signal, restoreOnSignal);
2358
+ }
2359
+ }
2360
+ }
2361
+ keyboardInput.on('keypress', onKeypress);
2362
+ stdin.on('data', terminalInput.write);
2363
+ stdin.resume();
2364
+ stdout.on('resize', onResize);
2365
+ syncSpinner();
2366
+ renderNow();
2367
+ },
2368
+ leave() {
2369
+ if (!entered || left)
2370
+ return;
2371
+ left = true;
2372
+ closeSideQuestion();
2373
+ disarmCtrlC();
2374
+ clearDragScroll();
2375
+ if (spinTimer) {
2376
+ clearInterval(spinTimer);
2377
+ spinTimer = undefined;
2378
+ }
2379
+ if (pendingRender) {
2380
+ clearImmediate(pendingRender);
2381
+ pendingRender = undefined;
2382
+ }
2383
+ stdin.off('data', terminalInput.write);
2384
+ keyboardInput.off('keypress', onKeypress);
2385
+ terminalInput.reset();
2386
+ paste = undefined;
2387
+ stdout.off('resize', onResize);
2388
+ process.off('exit', restoreTerminal);
2389
+ for (const signal of terminalSignals)
2390
+ process.off(signal, restoreOnSignal);
2391
+ restoreTerminal();
2392
+ stdin.pause();
2393
+ if (typeof stdin.unref === 'function')
2394
+ stdin.unref();
2395
+ if (submissionWaiter) {
2396
+ const resolve = submissionWaiter;
2397
+ submissionWaiter = undefined;
2398
+ resolve(null);
2399
+ }
2400
+ if (approvalWaiter) {
2401
+ const resolve = approvalWaiter;
2402
+ approvalWaiter = undefined;
2403
+ resolve(null);
2404
+ }
2405
+ if (choiceWaiter) {
2406
+ const resolve = choiceWaiter;
2407
+ choiceWaiter = undefined;
2408
+ choicePicker = undefined;
2409
+ resolve(null);
2410
+ }
2411
+ settleSecret(null);
2412
+ },
2413
+ appendEntry(kind, text) {
2414
+ setEntry({ kind, text });
2415
+ },
2416
+ setEntry,
2417
+ rekeyEntry(from, to) {
2418
+ if (from === to)
2419
+ return;
2420
+ const index = entries.findIndex((entry) => entry.key === from);
2421
+ if (index < 0)
2422
+ return;
2423
+ const existing = entries.findIndex((entry) => entry.key === to);
2424
+ if (existing >= 0) {
2425
+ if (scrollAnchor?.entry === index)
2426
+ scrollAnchor = { ...scrollAnchor, entry: existing };
2427
+ removeEntry(from);
2428
+ return;
2429
+ }
2430
+ entries[index] = { ...entries[index], key: to };
2431
+ queueRender();
2432
+ },
2433
+ prependHistory(history) {
2434
+ const existing = new Set(entries.map((entry) => entry.key));
2435
+ const older = history.filter((entry) => !existing.has(entry.key));
2436
+ if (!older.length)
2437
+ return;
2438
+ entries.unshift(...older);
2439
+ if (scrollAnchor && scrollOffset > 0) {
2440
+ scrollAnchor = { ...scrollAnchor, entry: scrollAnchor.entry + older.length };
2441
+ }
2442
+ queueRender();
2443
+ },
2444
+ onOlderHistory(fn) {
2445
+ olderHistoryHandler = fn;
2446
+ },
2447
+ removeEntry,
2448
+ clearEntries() {
2449
+ clearDragScroll();
2450
+ selection = undefined;
2451
+ entries.length = 0;
2452
+ scrollOffset = 0;
2453
+ scrollAnchor = undefined;
2454
+ renderNow();
2455
+ },
2456
+ updateTelemetry(patch) {
2457
+ telemetry = { ...telemetry, ...patch };
2458
+ syncSpinner();
2459
+ queueRender();
2460
+ },
2461
+ waitForSubmission() {
2462
+ if (left)
2463
+ return Promise.resolve(null);
2464
+ if (submissionQueue.length > 0) {
2465
+ const next = submissionQueue.shift();
2466
+ queueRender();
2467
+ return Promise.resolve(next);
2468
+ }
2469
+ return new Promise((resolve) => {
2470
+ submissionWaiter = resolve;
2471
+ });
2472
+ },
2473
+ promptApproval(pending, signal) {
2474
+ if (left || signal?.aborted)
2475
+ return Promise.resolve(null);
2476
+ clearDragScroll();
2477
+ selection = undefined;
2478
+ approvalPrompt = pending;
2479
+ syncSpinner();
2480
+ renderNow();
2481
+ return new Promise((resolve) => {
2482
+ const abort = () => {
2483
+ approvalWaiter = undefined;
2484
+ approvalPrompt = undefined;
2485
+ syncSpinner();
2486
+ renderNow();
2487
+ resolve(null);
2488
+ };
2489
+ signal?.addEventListener('abort', abort, { once: true });
2490
+ approvalWaiter = (decision) => {
2491
+ signal?.removeEventListener('abort', abort);
2492
+ resolve(decision);
2493
+ };
2494
+ });
2495
+ },
2496
+ promptChoice,
2497
+ promptSecret(label) {
2498
+ if (left || choiceWaiter || secretPrompt)
2499
+ return Promise.resolve(null);
2500
+ clearDragScroll();
2501
+ selection = undefined;
2502
+ return new Promise((resolve) => {
2503
+ secretPrompt = { label, value: '', resolve };
2504
+ renderNow();
2505
+ });
2506
+ },
2507
+ promptResumeSession(items) {
2508
+ return promptChoice({
2509
+ title: 'Resume Session',
2510
+ options: items.map((item) => {
2511
+ const mode = item.modeRef?.replace(/@\d+$/, '') ?? 'default';
2512
+ return {
2513
+ id: item.id,
2514
+ label: (item.firstUserMessage || item.title || item.id.slice(0, 8)).replace(/\s+/g, ' ').trim(),
2515
+ meta: `${formatPickerTime(item.updatedAt)} [${mode}] (${item.latestRunStatus ?? item.status})`,
2516
+ };
2517
+ }),
2518
+ });
2519
+ },
2520
+ onDetach(fn) {
2521
+ detachHandler = fn;
2522
+ },
2523
+ onInterrupt(fn) {
2524
+ interruptHandler = fn;
2525
+ },
2526
+ onImmediateSubmission(fn) {
2527
+ immediateHandler = fn;
2528
+ },
2529
+ onSteer(fn) {
2530
+ steerHandler = fn;
2531
+ },
2532
+ showSideQuestion(question, ask) {
2533
+ sideRequest?.abort();
2534
+ clearDragScroll();
2535
+ selection = undefined;
2536
+ const request = new AbortController();
2537
+ sideRequest = request;
2538
+ sideQuestion = { question, scroll: 0 };
2539
+ syncSpinner();
2540
+ renderNow();
2541
+ void ask(request.signal).then((answer) => finish(answer), (error) => finish(error instanceof Error ? error.message : String(error)));
2542
+ function finish(result) {
2543
+ if (sideRequest !== request || !sideQuestion)
2544
+ return;
2545
+ sideQuestion = { ...sideQuestion, result };
2546
+ syncSpinner();
2547
+ renderNow();
2548
+ }
2549
+ },
2550
+ closeSideQuestion,
2551
+ onNavigation(fn) {
2552
+ navigationHandler = fn;
2553
+ },
2554
+ onSelectSatellite(fn) {
2555
+ selectSatelliteHandler = fn;
2556
+ },
2557
+ renderNow,
2558
+ };
2559
+ }