@saturn-universe/cli 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/LICENSE +661 -0
  2. package/dist/attach.d.ts +9 -0
  3. package/dist/attach.js +80 -0
  4. package/dist/auth-config.d.ts +31 -0
  5. package/dist/auth-config.js +285 -0
  6. package/dist/choice-menu.d.ts +13 -0
  7. package/dist/choice-menu.js +238 -0
  8. package/dist/cli-diagnostics.d.ts +23 -0
  9. package/dist/cli-diagnostics.js +42 -0
  10. package/dist/cli-help.d.ts +6 -0
  11. package/dist/cli-help.js +163 -0
  12. package/dist/client.d.ts +13 -0
  13. package/dist/client.js +90 -0
  14. package/dist/commands.d.ts +64 -0
  15. package/dist/commands.js +299 -0
  16. package/dist/compaction-command.d.ts +16 -0
  17. package/dist/compaction-command.js +16 -0
  18. package/dist/composer.d.ts +88 -0
  19. package/dist/composer.js +124 -0
  20. package/dist/config-cli.d.ts +1 -0
  21. package/dist/config-cli.js +47 -0
  22. package/dist/config-file.d.ts +1 -0
  23. package/dist/config-file.js +43 -0
  24. package/dist/config-lock.d.ts +5 -0
  25. package/dist/config-lock.js +45 -0
  26. package/dist/duration.d.ts +2 -0
  27. package/dist/duration.js +11 -0
  28. package/dist/export.d.ts +19 -0
  29. package/dist/export.js +66 -0
  30. package/dist/host-command.d.ts +40 -0
  31. package/dist/host-command.js +48 -0
  32. package/dist/host-launcher.d.ts +22 -0
  33. package/dist/host-launcher.js +300 -0
  34. package/dist/index.d.ts +2 -0
  35. package/dist/index.js +400 -0
  36. package/dist/markdown.d.ts +1 -0
  37. package/dist/markdown.js +118 -0
  38. package/dist/mcp-cli.d.ts +44 -0
  39. package/dist/mcp-cli.js +647 -0
  40. package/dist/menu.d.ts +7 -0
  41. package/dist/menu.js +91 -0
  42. package/dist/project-mcp-config.d.ts +9 -0
  43. package/dist/project-mcp-config.js +98 -0
  44. package/dist/provider-discovery.d.ts +26 -0
  45. package/dist/provider-discovery.js +138 -0
  46. package/dist/provider-pricing.d.ts +3 -0
  47. package/dist/provider-pricing.js +130 -0
  48. package/dist/provider.d.ts +16 -0
  49. package/dist/provider.js +370 -0
  50. package/dist/reconcile-command.d.ts +36 -0
  51. package/dist/reconcile-command.js +64 -0
  52. package/dist/renderer.d.ts +204 -0
  53. package/dist/renderer.js +1134 -0
  54. package/dist/repl-host.d.ts +22 -0
  55. package/dist/repl-host.js +51 -0
  56. package/dist/repl-run-observer.d.ts +27 -0
  57. package/dist/repl-run-observer.js +86 -0
  58. package/dist/repl.d.ts +12 -0
  59. package/dist/repl.js +1834 -0
  60. package/dist/results.d.ts +23 -0
  61. package/dist/results.js +1 -0
  62. package/dist/sandbox-cli.d.ts +39 -0
  63. package/dist/sandbox-cli.js +324 -0
  64. package/dist/session-history.d.ts +17 -0
  65. package/dist/session-history.js +76 -0
  66. package/dist/settings-menu.d.ts +2 -0
  67. package/dist/settings-menu.js +111 -0
  68. package/dist/skill-cli.d.ts +25 -0
  69. package/dist/skill-cli.js +355 -0
  70. package/dist/slash-commands.d.ts +66 -0
  71. package/dist/slash-commands.js +1449 -0
  72. package/dist/terminal-input.d.ts +24 -0
  73. package/dist/terminal-input.js +111 -0
  74. package/dist/terminal-selection.d.ts +21 -0
  75. package/dist/terminal-selection.js +72 -0
  76. package/dist/terminal-text.d.ts +38 -0
  77. package/dist/terminal-text.js +238 -0
  78. package/dist/tui.d.ts +170 -0
  79. package/dist/tui.js +2559 -0
  80. package/dist/usage.d.ts +13 -0
  81. package/dist/usage.js +46 -0
  82. package/dist/user-config.d.ts +48 -0
  83. package/dist/user-config.js +188 -0
  84. package/package.json +18 -3
  85. package/README.md +0 -3
@@ -0,0 +1,1134 @@
1
+ import { formatDiagnosticReference, safeCode } from './cli-diagnostics.js';
2
+ import { compactionOptionUsage } from './compaction-command.js';
3
+ import { reconciliationUsage } from './reconcile-command.js';
4
+ import { createTerminalPainter, padEndDisplay, paintSgr, stringDisplayWidth, stripAnsi, terminalColorEnabled, } from './terminal-text.js';
5
+ import { formatDuration } from './duration.js';
6
+ import { estimateUsageCostUsd, formatCacheRate, formatTokenCompact, formatTokenExact, formatUsd, resolveModelPricing, } from './usage.js';
7
+ const { bold, dim, cyan, brightCyan, green, yellow, red, magenta, whiteBold } = createTerminalPainter();
8
+ function padLogoLines(lines) {
9
+ const maxWidth = Math.max(0, ...lines.map(stringDisplayWidth));
10
+ return lines.map((line) => {
11
+ const pad = Math.max(0, maxWidth - stringDisplayWidth(line));
12
+ return pad > 0 ? `${line}${' '.repeat(pad)}` : line;
13
+ });
14
+ }
15
+ const SATURN_WORDMARK = [
16
+ ' ____ _ _____ _ _ ____ _ _',
17
+ '/ ___| / \\|_ _| | | | _ \\| \\ | |',
18
+ '\\___ \\ / _ \\ | | | | | | |_) | \\| |',
19
+ ' ___) / ___ \\| | | |_| | _ <| |\\ |',
20
+ '|____/_/ \\_\\_| \\___/|_| \\_\\_| \\_|',
21
+ ];
22
+ const SATURN_COLORS = {
23
+ dim: '2',
24
+ goldBright: '38;2;255;230;163',
25
+ goldDark: '38;2;184;138;59',
26
+ gold: '38;2;240;198;116',
27
+ cyan: '36',
28
+ brightCyan: '96',
29
+ white: '97',
30
+ };
31
+ const BRAILLE_DOT_BIT = [
32
+ [0x01, 0x08],
33
+ [0x02, 0x10],
34
+ [0x04, 0x20],
35
+ [0x40, 0x80],
36
+ ];
37
+ export function renderSaturnLogo(frame = 0, colored = true) {
38
+ const cols = 30;
39
+ const rows = 10;
40
+ const cx = 30;
41
+ const cy = 20;
42
+ const radius = 12.2;
43
+ const spin = frame * 0.08;
44
+ const sinP = Math.sin(0.25);
45
+ const cosP = Math.cos(0.25);
46
+ const sinR = Math.sin(-0.28);
47
+ const cosR = Math.cos(-0.28);
48
+ const zbuf = Array.from({ length: rows * 4 }, () => Array(cols * 2).fill(-999));
49
+ const bits = Array.from({ length: rows }, () => Array(cols).fill(0));
50
+ const zCell = Array.from({ length: rows }, () => Array(cols).fill(-999));
51
+ const colors = Array.from({ length: rows }, () => Array(cols).fill(undefined));
52
+ const style = (code, text) => paintSgr(code, text, colored);
53
+ function plot(px, py, z, token) {
54
+ const ix = Math.round(px);
55
+ const iy = Math.round(py);
56
+ if (ix < 0 || iy < 0 || ix >= cols * 2 || iy >= rows * 4 || z < zbuf[iy][ix])
57
+ return;
58
+ zbuf[iy][ix] = z;
59
+ const col = ix >> 1;
60
+ const row = iy >> 2;
61
+ bits[row][col] = bits[row][col] | BRAILLE_DOT_BIT[iy & 3][ix & 1];
62
+ if (z >= zCell[row][col]) {
63
+ zCell[row][col] = z;
64
+ colors[row][col] = token;
65
+ }
66
+ }
67
+ const stars = [
68
+ [4, 4],
69
+ [55, 6],
70
+ [6, 34],
71
+ [54, 35],
72
+ ];
73
+ for (const [index, [x, y]] of stars.entries()) {
74
+ if ((frame + index * 7) % 24 < 12)
75
+ plot(x, y, -50, 'dim');
76
+ }
77
+ const radiusSquared = radius * radius;
78
+ const bandPhase = Math.sin(spin) * 0.4;
79
+ for (let py = Math.ceil(cy - radius); py <= cy + radius; py++) {
80
+ for (let px = Math.ceil(cx - radius); px <= cx + radius; px++) {
81
+ const dx = px - cx;
82
+ const dy = py - cy;
83
+ const d2 = dx * dx + dy * dy;
84
+ if (d2 > radiusSquared)
85
+ continue;
86
+ const dz = Math.sqrt(radiusSquared - d2);
87
+ const nx = dx / radius;
88
+ const ny = dy / radius;
89
+ const nz = dz / radius;
90
+ const diffuse = nx * -0.52 + ny * -0.45 + nz * 0.72;
91
+ if (diffuse < -0.35 && ((px + py) & 1) !== 0)
92
+ continue;
93
+ const lat = ny * cosR - nx * sinR;
94
+ const band = Math.sin(lat * 9 + bandPhase);
95
+ const token = diffuse > 0.42 ? 'goldBright' : diffuse < 0.0 || band < -0.6 ? 'goldDark' : 'gold';
96
+ plot(px, py, dz, token);
97
+ }
98
+ }
99
+ const occlusionRadius = (radius + 0.5) * (radius + 0.5);
100
+ function orbitPoint(r, a) {
101
+ const x0 = r * Math.cos(a);
102
+ const z0 = r * Math.sin(a);
103
+ const y1 = -z0 * sinP;
104
+ const z = z0 * cosP;
105
+ const x = x0 * cosR - y1 * sinR;
106
+ const y = x0 * sinR + y1 * cosR;
107
+ if (z < 0 && x * x + y * y < occlusionRadius)
108
+ return undefined;
109
+ return { x: cx + x * 1.18, y: cy + y * 0.92, z };
110
+ }
111
+ function ring(inner, outer, step, back, front) {
112
+ for (let r = inner; r <= outer; r += step) {
113
+ const steps = Math.round(r * 6.5);
114
+ for (let i = 0; i < steps; i++) {
115
+ const a = (i / steps) * 2 * Math.PI + spin * 0.9;
116
+ const point = orbitPoint(r, a);
117
+ if (!point)
118
+ continue;
119
+ const { x, y, z } = point;
120
+ const token = z > 0 ? (Math.sin(a * 2 - spin * 2.2) > 0.84 ? 'white' : front) : back;
121
+ plot(x, y, z > 0 ? z + 5 : z, token);
122
+ }
123
+ }
124
+ }
125
+ ring(15.6, 18.0, 1.1, 'cyan', 'brightCyan');
126
+ ring(19.6, 21.6, 1.1, 'dim', 'cyan');
127
+ const moon = orbitPoint(24.0, frame * 0.11);
128
+ if (moon) {
129
+ plot(moon.x, moon.y, moon.z + 6, 'white');
130
+ plot(moon.x + 1, moon.y, moon.z + 6, 'brightCyan');
131
+ }
132
+ const titleTop = 3;
133
+ const titleGap = 4;
134
+ const wordmarkWidth = Math.max(...SATURN_WORDMARK.map(stringDisplayWidth));
135
+ const width = cols + titleGap + wordmarkWidth;
136
+ const subtitle = 'o Orbiting Multi-Agent Kernel *';
137
+ const subtitleGap = titleGap + Math.floor((wordmarkWidth - stringDisplayWidth(subtitle)) / 2);
138
+ return bits.map((row, y) => {
139
+ const planet = row
140
+ .map((cell, x) => {
141
+ const glyph = String.fromCharCode(0x2800 + cell);
142
+ const token = colors[y][x];
143
+ return token ? style(SATURN_COLORS[token], glyph) : glyph;
144
+ })
145
+ .join('');
146
+ if (y === 9) {
147
+ return padEndDisplay(`${planet}${' '.repeat(subtitleGap)}${style(SATURN_COLORS.brightCyan, subtitle)}`, width);
148
+ }
149
+ const title = SATURN_WORDMARK[y - titleTop];
150
+ return padEndDisplay(title ? `${planet}${' '.repeat(titleGap)}${style('1;33', title)}` : planet, width);
151
+ });
152
+ }
153
+ export function renderCompactSaturnLogo(colored = terminalColorEnabled()) {
154
+ const { brightCyan: moon, yellow: planet, gold: ring } = createTerminalPainter(colored);
155
+ return padLogoLines([
156
+ ` ${moon('.')} ${moon('*')} `,
157
+ ` ${planet('.---.')} ${moon('o')}`,
158
+ ` ${moon('o')} ${planet(".' ::: '.")} `,
159
+ ` ${ring(".--'")} ${planet(':::::')} ${ring("'--.")}`,
160
+ ` ${ring('(=================)')} `,
161
+ ` ${ring("'--..")} ${planet(':::::')} ${ring("..--'")}`,
162
+ ` ${moon('*')} ${planet("'---'")} ${moon('.')} `,
163
+ ]);
164
+ }
165
+ export function renderUserTurn(text) {
166
+ const lines = text.split('\n');
167
+ if (terminalColorEnabled()) {
168
+ return lines
169
+ .map((line, index) => paintSgr('48;5;235;97', `${index === 0 ? ' › ' : ' '}${line}\x1b[K`, true))
170
+ .join('\n');
171
+ }
172
+ return lines.map((line, index) => `${index === 0 ? '› ' : ' '}${line}`).join('\n');
173
+ }
174
+ export function renderBanner(info) {
175
+ const activeProfileName = info.profile ?? info.status.defaultProfile;
176
+ const profiles = info.status.profiles ?? [];
177
+ const activeProfile = profiles.find((item) => item.name === activeProfileName) ?? profiles[0];
178
+ const readiness = !activeProfile
179
+ ? ''
180
+ : activeProfile.ready === false
181
+ ? ` ${yellow('[missing credential]')}`
182
+ : ` ${green('[ready]')}`;
183
+ const profileLabel = activeProfile
184
+ ? `${activeProfile.name}${activeProfile.modelId ? ` (${activeProfile.modelId})` : ''}${readiness}`
185
+ : yellow('none configured');
186
+ const hostLabel = info.ownedHost ? 'local host started' : 'attached to running host';
187
+ const activeMode = info.status.activeMode;
188
+ const extensions = [
189
+ `Mode: ${activeMode.displayName} (${activeMode.ref})`,
190
+ info.skillRefs.length ? `Skills: ${info.skillRefs.join(', ')}` : '',
191
+ ]
192
+ .filter(Boolean)
193
+ .join(' · ');
194
+ const sandboxLine = info.status.sandbox && info.status.sandbox.backend !== 'host'
195
+ ? info.status.sandbox.fallbackActive
196
+ ? `Sandbox: ${yellow(`UNSAFE HOST FALLBACK (${info.status.sandbox.backend} → host)`)}`
197
+ : `Sandbox: ${green(`${info.status.sandbox.backend}`)}${info.status.sandbox.image ? ` (${info.status.sandbox.image})` : ''}`
198
+ : undefined;
199
+ const metaLines = [
200
+ `${brightCyan('>_')} ${whiteBold('Saturn')} ${dim('(v0.1.1)')}`,
201
+ dim('Ringed Agent Kernel · Orbiting Agent Teams'),
202
+ `Workspace: ${info.workdir}`,
203
+ `Config: ${info.status.configSource ?? 'none'} · Profile: ${profileLabel}`,
204
+ `Host: ${dim(hostLabel)}${extensions ? ` · ${extensions}` : ''}`,
205
+ ...(sandboxLine ? [sandboxLine] : []),
206
+ ...(info.status.boardUrl ? [`Board: ${info.status.boardUrl}`] : []),
207
+ `Session: ${info.sessionId ?? dim('new (created on first prompt)')}`,
208
+ ];
209
+ const cols = process.stdout.columns ?? 100;
210
+ const logo = cols < 70 ? renderCompactSaturnLogo() : renderSaturnLogo(0, terminalColorEnabled());
211
+ const output = ['', ...logo, '', ...metaLines];
212
+ if (!profiles.length) {
213
+ output.push('', yellow(' Notice: No provider profile configured. Run `/config init` or check `/config check`.'));
214
+ }
215
+ else if (activeProfile && !activeProfile.protocol && activeProfile.ready === false) {
216
+ output.push('', yellow(` Notice: Active profile "${activeProfile.name}" is missing credentials. Run \`/config check\` for paths.`));
217
+ }
218
+ output.push('', dim('Type a message to run, or enter / for commands.'), '');
219
+ return output.join('\n');
220
+ }
221
+ export function renderTeamTree(members) {
222
+ const byParent = new Map();
223
+ for (const member of members) {
224
+ const key = member.parent ?? null;
225
+ const list = byParent.get(key) ?? [];
226
+ list.push(member);
227
+ byParent.set(key, list);
228
+ }
229
+ const lines = [];
230
+ const walk = (parentId, prefix) => {
231
+ const children = byParent.get(parentId) ?? [];
232
+ children.forEach((child, index) => {
233
+ const last = index === children.length - 1;
234
+ const connector = parentId === null ? '' : last ? '└─ ' : '├─ ';
235
+ const status = child.status ? ` [${child.status}]` : '';
236
+ const task = child.task ? `: ${child.task}` : '';
237
+ lines.push(`${prefix}${connector}${bold(child.id)}${status}${task}`);
238
+ const nextPrefix = parentId === null ? ' ' : prefix + (last ? ' ' : '│ ');
239
+ walk(child.id, nextPrefix);
240
+ });
241
+ };
242
+ walk(null, ' ');
243
+ if (!lines.length) {
244
+ for (const member of members) {
245
+ lines.push(` - ${member.id} (parent=${member.parent ?? 'root'})${member.task ? `: ${member.task}` : ''}`);
246
+ }
247
+ }
248
+ return lines.join('\n');
249
+ }
250
+ const readonlyCommandRejection = /^(?:Command "[^"]+" is not in the read-only diagnostic allowlist|Flag "[^\r\n]+" is not allowed in read-only mode)$/;
251
+ const executableNotFound = /^(?:Executable|Allowlisted read-only command) "[^\r\n]+" was not found(?:[. ]|$)/;
252
+ function isHiddenToolError(error) {
253
+ if (error?.code === 'PROGRAM_NOT_FOUND')
254
+ return true;
255
+ return error?.code === 'READONLY_COMMAND_DENIED' && readonlyCommandRejection.test(error.message ?? '');
256
+ }
257
+ function isHiddenToolEvent(event) {
258
+ if (!event.type.startsWith('tool.call.'))
259
+ return false;
260
+ if (event.type === 'tool.call.denied' && event.reason) {
261
+ // Resource validation can emit a denial with only the reason before the structured result.
262
+ return readonlyCommandRejection.test(event.reason) || executableNotFound.test(event.reason);
263
+ }
264
+ return isHiddenToolError(event.error);
265
+ }
266
+ export function renderAssistantText(text) {
267
+ return text
268
+ .replace(/(工具返回(?:了)?\s*)`?PROGRAM_NOT_FOUND\b`?/g, '$1“所需程序不可用”')
269
+ .replace(/(\btool returned\s+)`?PROGRAM_NOT_FOUND\b`?/gi, '$1“the required executable is unavailable”');
270
+ }
271
+ function modelFailureMessage(error) {
272
+ const message = error?.message;
273
+ return message &&
274
+ (/^HTTP 4\d\d · /.test(message) ||
275
+ (error.code === 'unsupported_capability' &&
276
+ message.startsWith('The configured model or endpoint does not support tool calling.')))
277
+ ? message
278
+ : '';
279
+ }
280
+ export function renderModelFailure(event) {
281
+ const error = event.error;
282
+ if (!error)
283
+ return 'Model request failed';
284
+ const qualifier = error.code === 'transport' ? (error.underlyingCode ?? error.phase) : error.phase;
285
+ const message = modelFailureMessage(error);
286
+ return [
287
+ `${safeCode(error.code)}${qualifier ? ` (${qualifier})` : ''}`,
288
+ ...(message ? [message] : []),
289
+ ...(error.phase && error.phase !== qualifier ? [error.phase] : []),
290
+ ...(error.timeoutKind ? [error.timeoutKind] : []),
291
+ ...(error.elapsedMs === undefined ? [] : [`${error.elapsedMs}ms`]),
292
+ ...(event.requestId ? [`requestId=${event.requestId}`] : []),
293
+ `diagnosticId=${error.diagnosticId}`,
294
+ ...(event.retryAfterMs === undefined ? [] : [`Retry-After ${event.retryAfterMs}ms`]),
295
+ ...(event.retryAt ? [`retryAt=${event.retryAt}`] : []),
296
+ ...(error.causes?.length
297
+ ? [error.causes.map(({ code, message }) => `${code ? `${code} ` : ''}${message}`).join(' → ')]
298
+ : []),
299
+ ].join(' · ');
300
+ }
301
+ export function renderProgressEvent(event) {
302
+ if (isHiddenToolEvent(event))
303
+ return;
304
+ const actor = event.memberId ? `:${event.memberId}` : '';
305
+ switch (event.type) {
306
+ case 'run.team.planned': {
307
+ const fallbackBadge = event.fallback ? ` ${yellow('[fallback:single]')}` : '';
308
+ const lines = [
309
+ `${magenta('[Planner]')} decision=${bold(event.decision ?? 'unknown')}${fallbackBadge}`,
310
+ ...(event.reason ? [` reason: ${event.reason}`] : []),
311
+ ...(event.summary ? [` summary: ${event.summary}`] : []),
312
+ ...(event.evidence?.length ? [` evidence: ${event.evidence.join(' | ')}`] : []),
313
+ ...(event.executionSteps?.length ? [` steps: ${event.executionSteps.join(' -> ')}`] : []),
314
+ ...(event.verificationCriteria?.length
315
+ ? [` verify: ${event.verificationCriteria.join(' | ')}`]
316
+ : []),
317
+ ];
318
+ const members = event.team?.members ?? [];
319
+ if (members.length) {
320
+ if (event.team?.concurrency !== undefined) {
321
+ lines.push(` team concurrency: ${event.team.concurrency}`);
322
+ }
323
+ lines.push(renderTeamTree([
324
+ { id: 'main', parent: null },
325
+ ...members.map((member) => ({ id: member.id, parent: member.parent, task: member.task })),
326
+ ]));
327
+ }
328
+ return lines.join('\n');
329
+ }
330
+ case 'run.team.message.sent':
331
+ return `${cyan('[Team]')} ${bold(event.from ?? '?')} -> ${bold(event.to ?? '?')}: ${event.text ?? ''}`;
332
+ case 'run.search.started':
333
+ return [
334
+ `${magenta('[ToT]')} search started trigger=${bold(event.trigger ?? 'unknown')} isolation=${event.isolation ?? 'readonly'}${event.maxRollouts !== undefined ? ` maxRollouts=${event.maxRollouts}` : ''}`,
335
+ ...(event.goal ? [` goal: ${event.goal}`] : []),
336
+ ].join('\n');
337
+ case 'run.search.branch.created':
338
+ return [
339
+ `${magenta(`[ToT:${event.branchId ?? '?'}]`)} ${event.mode ?? 'wider'} depth=${event.depth ?? 0} workspace=${event.workspaceKind ?? 'shared_readonly'}`,
340
+ ...(event.hypothesis ? [` hypothesis: ${event.hypothesis}`] : []),
341
+ ...(event.degradedToReadonly ? [` ${yellow(searchDegradedNotice)}`] : []),
342
+ ].join('\n');
343
+ case 'run.search.branch.evaluated': {
344
+ const badge = verdictBadge(event.verdict);
345
+ return [
346
+ `${magenta(`[ToT:${event.branchId ?? '?'}]`)} ${badge}${event.combinedScore !== undefined ? ` score=${event.combinedScore.toFixed(2)}` : ''}`,
347
+ ...(event.summary ? [` summary: ${event.summary}`] : []),
348
+ ...(event.reflection ? [` reflection: ${event.reflection}`] : []),
349
+ ].join('\n');
350
+ }
351
+ case 'run.search.converged':
352
+ return [
353
+ `${magenta('[ToT]')} converged outcome=${bold(event.outcome ?? 'unknown')}${event.winnerBranchId ? ` winner=${event.winnerBranchId}` : ''}`,
354
+ ...(event.winnerSummary ? [` winner: ${event.winnerSummary}`] : []),
355
+ ...(event.mergedFiles?.length ? [` merged: ${event.mergedFiles.join(', ')}`] : []),
356
+ ...(event.mergedReflections ?? []).map((reflection) => ` reflection: ${reflection}`),
357
+ ].join('\n');
358
+ case 'tool.call.requested':
359
+ return `${yellow(`[Tool${actor}]`)} ${event.toolName ?? 'tool'} ${dim(`(${event.toolCallId ?? ''})`)}`;
360
+ case 'tool.call.denied':
361
+ return `${red(`[Tool${actor}]`)} denied ${dim(event.toolCallId ?? '')}${event.reason ? `: ${event.reason}` : ''}`;
362
+ case 'tool.call.rejected':
363
+ return `${red(`[Tool${actor}]`)} rejected ${dim(event.toolCallId ?? '')}${event.error ? `: ${event.error.code}` : ''}`;
364
+ case 'tool.approval.requested': {
365
+ const approvalId = event.approval?.approvalId ?? '';
366
+ return `${yellow(`[Approval${actor}]`)} pending (${approvalId})`;
367
+ }
368
+ case 'tool.approval.resolved':
369
+ return `${event.approved ? green('[Approval]') : red('[Approval]')} ${event.approved ? 'approved' : 'denied'}`;
370
+ case 'message.assistant.added': {
371
+ const text = renderAssistantText(event.text ?? '');
372
+ if (!text.trim())
373
+ return undefined;
374
+ const label = event.memberId === 'planner' ? magenta('[Planner]') : green(`[Assistant${actor}]`);
375
+ return `${label}\n${text}`;
376
+ }
377
+ case 'run.paused':
378
+ return `${yellow('[Paused]')} reason=${event.reason ?? 'unknown'}`;
379
+ case 'turn.paused':
380
+ return event.reason === 'approval' && event.memberId
381
+ ? `${yellow(`[${event.memberId}]`)} awaiting approval`
382
+ : undefined;
383
+ case 'turn.resumed':
384
+ return event.memberId ? `${green(`[${event.memberId}]`)} running` : undefined;
385
+ case 'run.completed':
386
+ return `${green('[Run]')} completed`;
387
+ case 'run.cancelled':
388
+ return `${yellow('[Run]')} cancelled${event.reason ? `: ${event.reason}` : ''}`;
389
+ case 'run.failed':
390
+ case 'turn.failed':
391
+ case 'step.failed':
392
+ if (event.type === 'step.failed' && event.error?.code === 'steered')
393
+ return;
394
+ return event.error
395
+ ? `${red(`[Error${actor}]`)} ${formatDiagnosticReference(event.error)}`
396
+ : `${red(`[Error${actor}]`)} failed`;
397
+ case 'model.failed':
398
+ if (event.error?.code === 'steered')
399
+ return;
400
+ return `${red(`[Error${actor}]`)} ${renderModelFailure(event)}`;
401
+ default:
402
+ return undefined;
403
+ }
404
+ }
405
+ export const searchDegradedNotice = '非 Git 工作区超过复制上限,已降级为只读分支';
406
+ function verdictBadge(verdict) {
407
+ if (verdict === 'solved')
408
+ return green('[solved]');
409
+ if (verdict === 'pruned')
410
+ return red('[pruned]');
411
+ if (verdict === 'promising')
412
+ return cyan('[promising]');
413
+ return '[evaluated]';
414
+ }
415
+ function sanitizeToolErrorText(raw) {
416
+ const cleaned = stripAnsi(raw)
417
+ .replace(/\bdiagnosticId=\S+/gi, '')
418
+ .replace(/\btoolCallId=\S+/gi, '')
419
+ .replace(/\{[\s\S]*\}/g, '')
420
+ .replace(/\[[\s\S]*\]/g, '')
421
+ .split(/\r?\n/)[0]
422
+ ?.replace(/\s+/g, ' ')
423
+ .trim();
424
+ if (!cleaned)
425
+ return '工具调用失败';
426
+ return cleaned.length > 96 ? `${cleaned.slice(0, 95)}…` : cleaned;
427
+ }
428
+ function firstMeaningfulOutputLine(output) {
429
+ if (!output)
430
+ return undefined;
431
+ const lines = stripAnsi(output).split(/\r?\n/);
432
+ const stderrIndex = lines.findIndex((line) => line.trim().toLowerCase() === 'stderr:');
433
+ const searchOrder = stderrIndex >= 0 ? [...lines.slice(stderrIndex + 1), ...lines.slice(0, stderrIndex)] : lines;
434
+ for (const raw of searchOrder) {
435
+ const trimmed = raw.trim();
436
+ if (!trimmed)
437
+ continue;
438
+ const lower = trimmed.toLowerCase();
439
+ if (lower === 'stdout:' ||
440
+ lower === 'stderr:' ||
441
+ lower.startsWith('process exit:') ||
442
+ lower.startsWith('output truncated (') ||
443
+ trimmed === '… (truncated)')
444
+ continue;
445
+ return trimmed.length > 100 ? `${trimmed.slice(0, 99)}…` : trimmed;
446
+ }
447
+ return undefined;
448
+ }
449
+ function toolErrorSummary(error) {
450
+ if (!error)
451
+ return '工具调用失败';
452
+ if (error.code === 'APPROVAL_DENIED')
453
+ return '用户拒绝了审批';
454
+ if (error.code === 'APPROVAL_EXPIRED')
455
+ return '审批已过期';
456
+ if (error.code === 'PERMISSION_DENIED' || error.code === 'POLICY_DENIED')
457
+ return '权限策略拒绝了这项操作';
458
+ if (error.code === 'TOOL_TIMEOUT' || error.code === 'TIMEOUT')
459
+ return '工具执行超时';
460
+ if (error.code === 'PROGRAM_INVALID')
461
+ return '不支持直接运行该程序格式';
462
+ if (error.code === 'TOOL_NOT_FOUND' || error.code === 'UNKNOWN_TOOL' || error.code === 'UNRESOLVED_TOOL')
463
+ return '未找到该工具';
464
+ if (error.code === 'INVALID_TEAM_CONFIG') {
465
+ const parent = /^unknown parent (.+) for team member ([A-Za-z0-9][A-Za-z0-9._-]{0,63})$/.exec(error.message ?? '');
466
+ if (parent)
467
+ return '团队配置无效 · 成员 ' + parent[2] + ' 引用了未定义的父级 ' + parent[1];
468
+ }
469
+ if (error.code === 'WORKSPACE_PATH_INVALID') {
470
+ if (error.message?.startsWith('Target is a directory.'))
471
+ return '目标是目录,请指定文件路径';
472
+ if (error.message?.startsWith('Target is a file.'))
473
+ return '目标是文件,请指定目录路径';
474
+ if (error.message?.endsWith('must stay inside the workspace') ||
475
+ error.message?.endsWith('cannot traverse outside workspace'))
476
+ return '参数路径超出工作区';
477
+ if (error.message?.endsWith('references a protected path'))
478
+ return '参数指向受保护路径';
479
+ return '路径不可用或超出工作区';
480
+ }
481
+ const empty = error.message?.match(/^([\w.]+) must not be empty$/);
482
+ if (error.code === 'INVALID_ARGUMENTS' && empty)
483
+ return `${empty[1]} 不能为空`;
484
+ if (error.code === 'INVALID_ARGUMENTS' || error.code === 'VALIDATION_ERROR') {
485
+ const clean = error.message ? sanitizeToolErrorText(error.message) : '';
486
+ return clean && clean !== '工具调用失败' ? `参数校验失败 · ${clean}` : '参数校验失败';
487
+ }
488
+ return error.message ? sanitizeToolErrorText(error.message) : error.code;
489
+ }
490
+ function asRecord(value) {
491
+ return value && typeof value === 'object' && !Array.isArray(value)
492
+ ? value
493
+ : {};
494
+ }
495
+ function parseJsonSafe(raw) {
496
+ if (!raw?.trim())
497
+ return undefined;
498
+ try {
499
+ return JSON.parse(raw);
500
+ }
501
+ catch {
502
+ return undefined;
503
+ }
504
+ }
505
+ function resolveToolBlock(input) {
506
+ if (input.toolBlock)
507
+ return input.toolBlock;
508
+ const name = input.toolName;
509
+ if (!name)
510
+ return undefined;
511
+ const parsedArgs = asRecord(parseJsonSafe(input.toolArguments));
512
+ // toolArguments on tool.call.requested may be wrapped in { kind: 'json', value: ... }
513
+ const args = parsedArgs.kind === 'json' ? asRecord(parsedArgs.value) : parsedArgs;
514
+ const data = input.toolData !== undefined ? input.toolData : parseJsonSafe(input.toolOutput);
515
+ const dataObj = asRecord(data);
516
+ const str = (value, limit) => typeof value === 'string' ? value.trim().slice(0, limit) : '';
517
+ if (name === 'security_record_fact' || name === 'ctf_record_fact') {
518
+ const id = str(dataObj.id, 80);
519
+ const category = str(dataObj.category, 80);
520
+ return {
521
+ kind: 'fact',
522
+ ...(id ? { id } : {}),
523
+ ...(category ? { category } : {}),
524
+ };
525
+ }
526
+ if (name === 'security_record_hypothesis' || name === 'ctf_record_hypothesis') {
527
+ const id = str(dataObj.id, 80);
528
+ const status = str(dataObj.status, 80);
529
+ return {
530
+ kind: 'hypothesis',
531
+ ...(id ? { id } : {}),
532
+ ...(status ? { status } : {}),
533
+ };
534
+ }
535
+ if (name === 'security_skill' || name === 'skill') {
536
+ const skill = str(dataObj.skill ?? args.skill, 512);
537
+ switch (args.action) {
538
+ case 'list':
539
+ return {
540
+ kind: 'skill',
541
+ action: 'list',
542
+ count: Array.isArray(dataObj.skills) ? dataObj.skills.length : 0,
543
+ };
544
+ case 'load':
545
+ return { kind: 'skill', action: 'load', skill };
546
+ case 'read_ref':
547
+ case 'read_resource':
548
+ return { kind: 'skill', action: 'read', skill, path: str(dataObj.path ?? args.path, 1024) };
549
+ }
550
+ return undefined;
551
+ }
552
+ if (name === 'web_search') {
553
+ const query = str(args.query, 512);
554
+ const count = Array.isArray(data)
555
+ ? data.length
556
+ : typeof dataObj.count === 'number'
557
+ ? dataObj.count
558
+ : undefined;
559
+ return { kind: 'web_search', query, ...(count !== undefined ? { count } : {}) };
560
+ }
561
+ if (name === 'web_fetch') {
562
+ return { kind: 'web_fetch', url: str(args.url, 2048) };
563
+ }
564
+ return undefined;
565
+ }
566
+ function formatFetchTarget(rawUrl) {
567
+ const parsed = URL.parse(rawUrl);
568
+ if (!parsed) {
569
+ const cleaned = rawUrl.replace(/^https?:\/\//i, '').trim() || 'page';
570
+ const slash = cleaned.indexOf('/');
571
+ return { host: slash >= 0 ? cleaned.slice(0, slash) : cleaned, hostPath: cleaned };
572
+ }
573
+ const pathPart = parsed.pathname === '/' && !parsed.search ? '' : `${parsed.pathname}${parsed.search}`;
574
+ return { host: parsed.host, hostPath: `${parsed.host}${pathPart}` };
575
+ }
576
+ export function renderUnifiedToolBlock(input) {
577
+ const block = resolveToolBlock(input);
578
+ if (!block)
579
+ return undefined;
580
+ const status = input.toolStatus;
581
+ const normalizedError = input.error
582
+ ? {
583
+ code: input.error.code,
584
+ diagnosticId: input.error.diagnosticId ?? '',
585
+ ...(input.error.message ? { message: input.error.message } : {}),
586
+ }
587
+ : undefined;
588
+ if (block.kind === 'web_search') {
589
+ const query = block.query || 'web_search';
590
+ if (status === 'cancelled') {
591
+ return { block: 'web', tone: 'muted', text: `⊕ SEARCH · ${query} · 已取消`, detail: input.detail };
592
+ }
593
+ if (status && status !== 'success') {
594
+ return {
595
+ block: 'web',
596
+ tone: 'error',
597
+ text: `✕ SEARCH · ${query} · ${toolErrorSummary(normalizedError)}`,
598
+ detail: input.detail,
599
+ };
600
+ }
601
+ const countSuffix = block.count !== undefined ? ` (${block.count} 条结果)` : '';
602
+ return { block: 'web', text: `⊕ SEARCH · ${query}${countSuffix}`, detail: input.detail };
603
+ }
604
+ if (block.kind === 'web_fetch') {
605
+ const { host, hostPath } = formatFetchTarget(block.url);
606
+ if (status === 'cancelled') {
607
+ return { block: 'web', tone: 'muted', text: `⊕ FETCH · ${hostPath} · 已取消`, detail: input.detail };
608
+ }
609
+ if (status && status !== 'success') {
610
+ return {
611
+ block: 'web',
612
+ tone: 'error',
613
+ text: `✕ FETCH · ${host || 'page'} · ${toolErrorSummary(normalizedError)}`,
614
+ detail: input.detail,
615
+ };
616
+ }
617
+ return { block: 'web', text: `⊕ FETCH · ${hostPath}`, detail: input.detail };
618
+ }
619
+ if (status && status !== 'success')
620
+ return undefined;
621
+ if (block.kind === 'fact' || block.kind === 'hypothesis') {
622
+ const metadata = [block.id, block.kind === 'fact' ? block.category : block.status]
623
+ .filter(Boolean)
624
+ .join(' · ');
625
+ const label = block.kind === 'fact' ? '◆ LEDGER · 事实已写入' : '◇ LEDGER · 假设已写入';
626
+ return {
627
+ block: 'ledger',
628
+ text: metadata ? label + ' (' + metadata + ')' : label,
629
+ detail: input.detail,
630
+ };
631
+ }
632
+ switch (block.action) {
633
+ case 'load':
634
+ return { block: 'skill', text: '◈ SKILL · 已加载 ' + block.skill, detail: input.detail };
635
+ case 'read':
636
+ return {
637
+ block: 'skill',
638
+ text: '◈ SKILL · 已读取 ' + block.skill + ' / ' + block.path,
639
+ detail: input.detail,
640
+ };
641
+ case 'list':
642
+ return { block: 'skill', text: '◈ SKILL · 已列出技能 (' + block.count + ')', detail: input.detail };
643
+ }
644
+ }
645
+ export function renderConversationEvent(event) {
646
+ if (isHiddenToolEvent(event))
647
+ return;
648
+ const rendered = renderProgressEvent(event);
649
+ const actor = event.memberId ? `:${event.memberId}` : '';
650
+ switch (event.type) {
651
+ case 'run.team.message.sent': {
652
+ const from = event.from ?? '?';
653
+ const to = event.to ?? '?';
654
+ const body = renderAssistantText(event.text ?? '').trim();
655
+ return {
656
+ text: body,
657
+ header: `${from} → ${to}`,
658
+ activity: 'team_report',
659
+ activityLabel: from,
660
+ detail: body,
661
+ };
662
+ }
663
+ case 'message.assistant.added': {
664
+ const text = renderAssistantText(event.text ?? '');
665
+ if (!text.trim())
666
+ return;
667
+ return !event.memberId || event.memberId === 'main'
668
+ ? { text }
669
+ : {
670
+ text: '',
671
+ detail: `${event.memberId === 'planner' ? '[Planner]' : `[Team] ${event.memberId}`}\n${text}`,
672
+ };
673
+ }
674
+ case 'model.requested':
675
+ return { text: '', detail: `[Model${actor}] request ${event.requestId ?? ''}` };
676
+ case 'model.responded':
677
+ return event.text?.trim()
678
+ ? { text: event.text }
679
+ : { text: '', detail: `[Model${actor}] response ${event.requestId ?? ''}` };
680
+ case 'run.team.planned':
681
+ return {
682
+ text: event.fallback
683
+ ? `[fallback:single] 规划回退至主助手直接处理${event.reason ? `(${event.reason})` : ''}`
684
+ : event.summary || (event.decision === 'team' ? '已分配团队任务' : '由主助手处理'),
685
+ ...(event.fallback ? {} : { activity: 'team_plan' }),
686
+ ...(rendered ? { detail: rendered } : {}),
687
+ };
688
+ case 'run.search.started':
689
+ return {
690
+ text: `› 启动选择性树搜索 · ${event.trigger ?? 'unknown'}${event.goal ? ` · ${event.goal}` : ''}`,
691
+ ...(rendered ? { detail: rendered } : {}),
692
+ };
693
+ case 'run.search.branch.created':
694
+ return {
695
+ text: event.degradedToReadonly ? `› 分支 ${event.branchId ?? '?'} · ${searchDegradedNotice}` : '',
696
+ ...(rendered ? { detail: rendered } : {}),
697
+ };
698
+ case 'run.search.branch.evaluated':
699
+ return {
700
+ text: event.verdict === 'pruned'
701
+ ? `› 分支 ${event.branchId ?? '?'} 已剪枝${event.reflection ? ` · ${event.reflection}` : ''}`
702
+ : event.verdict === 'solved'
703
+ ? `› 分支 ${event.branchId ?? '?'} 已解决`
704
+ : '',
705
+ ...(rendered ? { detail: rendered } : {}),
706
+ };
707
+ case 'run.search.converged':
708
+ return {
709
+ text: `› 树搜索收敛 · ${event.outcome ?? 'unknown'}${event.winnerBranchId ? ` · 胜出分支 ${event.winnerBranchId}` : ''}${event.mergedFiles?.length ? ` · 合并 ${event.mergedFiles.length} 个文件` : ''}`,
710
+ ...(rendered ? { detail: rendered } : {}),
711
+ };
712
+ case 'tool.call.requested':
713
+ return { text: '', detail: [rendered, event.toolArguments].filter(Boolean).join('\n') };
714
+ case 'tool.call.started':
715
+ return {
716
+ text: '',
717
+ detail: `[Tool${actor}] ${event.toolName ?? 'tool'} started (${event.toolCallId ?? ''})`,
718
+ };
719
+ case 'tool.call.settled': {
720
+ const name = event.toolName ?? 'tool';
721
+ const error = event.error;
722
+ const detail = [
723
+ `[Tool${actor}] ${name} ${event.toolStatus ?? ''} (${event.toolCallId ?? ''})`,
724
+ event.effect ? `Effect: ${event.effect}` : '',
725
+ error ? `${error.code} ${error.message ?? ''} (diagnosticId=${error.diagnosticId})` : '',
726
+ event.toolOutput,
727
+ ]
728
+ .filter(Boolean)
729
+ .join('\n');
730
+ const isCommand = name === 'shell' || name === 'run_process' || name === 'run_readonly_command';
731
+ const nonZeroCommand = isCommand &&
732
+ (name !== 'shell' || event.toolStatus === 'success') &&
733
+ Boolean(event.exitSignal || (event.exitCode !== undefined && event.exitCode !== 0));
734
+ if (nonZeroCommand) {
735
+ const status = event.exitSignal ? `signal ${event.exitSignal}` : `exit ${event.exitCode}`;
736
+ const summary = `› ${event.toolTarget ?? name} · ${status}`;
737
+ const preview = firstMeaningfulOutputLine(event.toolOutput ?? event.error?.message);
738
+ return {
739
+ text: preview ? `${summary}\n ${preview}` : summary,
740
+ tone: 'warn',
741
+ detail: [summary, detail].join('\n'),
742
+ };
743
+ }
744
+ const unified = renderUnifiedToolBlock({
745
+ toolName: name,
746
+ toolBlock: event.toolBlock,
747
+ toolArguments: event.toolArguments,
748
+ toolOutput: event.toolOutput,
749
+ toolStatus: event.toolStatus,
750
+ error,
751
+ detail,
752
+ });
753
+ if (unified)
754
+ return unified;
755
+ if (event.toolStatus === 'cancelled')
756
+ return { text: `› ${name} · 已取消`, tone: 'muted', detail };
757
+ if (event.toolStatus !== 'success') {
758
+ return { text: `✕ ${name} · ${toolErrorSummary(error)}`, tone: 'error', detail };
759
+ }
760
+ if (name === 'list_dir' ||
761
+ name === 'read_file' ||
762
+ name === 'search_files' ||
763
+ name === 'glob' ||
764
+ name === 'grep')
765
+ return { text: '', activity: name, detail };
766
+ if (name === 'read_tool_result')
767
+ return { text: '', activity: 'read_file', detail };
768
+ if (name === 'edit_file' || name === 'apply_patch')
769
+ return {
770
+ text: event.effect === 'none'
771
+ ? `› 文件已符合要求 · ${event.toolTarget ?? name}`
772
+ : `› 已修改 ${event.toolTarget ?? '文件'}`,
773
+ activity: 'edit_file',
774
+ ...(event.toolTarget ? { activityLabel: event.toolTarget } : {}),
775
+ detail,
776
+ };
777
+ if (name === 'write_file')
778
+ return {
779
+ text: `› 已写入 ${event.toolTarget ?? '文件'}`,
780
+ activity: 'write_file',
781
+ ...(event.toolTarget ? { activityLabel: event.toolTarget } : {}),
782
+ detail,
783
+ };
784
+ if (isCommand) {
785
+ const summary = `› ${event.toolTarget ?? name} · exit 0`;
786
+ return {
787
+ text: '',
788
+ activity: 'command',
789
+ detail: [summary, detail].join('\n'),
790
+ };
791
+ }
792
+ if (name === 'start_process' ||
793
+ name === 'read_process' ||
794
+ name === 'write_process' ||
795
+ name === 'stop_process') {
796
+ return { text: '', activity: 'command', detail };
797
+ }
798
+ if (name === 'todo_write') {
799
+ const todos = Array.isArray(event.todos) ? event.todos : [];
800
+ const done = todos.filter((item) => item.status === 'completed').length;
801
+ return { text: `› 已更新待办 (${done}/${todos.length})`, activity: 'todo', detail };
802
+ }
803
+ if (name === 'spawn_team') {
804
+ return { text: '', activity: 'team_plan', detail };
805
+ }
806
+ return { text: `› 已完成 ${name}`, activity: 'tool_other', activityLabel: name, detail };
807
+ }
808
+ case 'tool.call.failed':
809
+ return {
810
+ text: `✕ ${event.toolName ?? 'tool'} · ${toolErrorSummary(event.error)}`,
811
+ tone: 'error',
812
+ detail: `[Tool${actor}] ${event.toolName ?? 'tool'} (${event.toolCallId ?? ''}) · ${event.error?.code ?? 'failed'} ${event.error?.message ?? ''}${event.error?.diagnosticId ? ` (diagnosticId=${event.error.diagnosticId})` : ''}`,
813
+ };
814
+ case 'tool.call.denied':
815
+ return {
816
+ text: `✕ ${event.toolName ?? 'tool'} · 权限或审批被拒绝`,
817
+ tone: 'error',
818
+ detail: `[Tool${actor}] ${event.toolName ?? 'tool'} (${event.toolCallId ?? ''}) · ${event.reason ?? event.type}`,
819
+ };
820
+ case 'tool.call.rejected':
821
+ return {
822
+ text: `✕ ${event.toolName ?? 'tool'} · ${event.error ? toolErrorSummary(event.error) : '参数校验失败'}`,
823
+ tone: 'error',
824
+ detail: `[Tool${actor}] ${event.toolName ?? 'tool'} (${event.toolCallId ?? ''}) · ${event.error?.code ?? 'rejected'} ${event.error?.message ?? ''}${event.error?.diagnosticId ? ` (diagnosticId=${event.error.diagnosticId})` : ''}`,
825
+ };
826
+ case 'tool.call.outcome_unknown':
827
+ return {
828
+ text: `✕ ${event.toolName ?? 'tool'} · 执行结果待核对`,
829
+ tone: 'error',
830
+ detail: `[Tool${actor}] ${event.toolCallId ?? ''} · ${event.reason ?? 'outcome unknown'}`,
831
+ };
832
+ case 'tool.approval.requested':
833
+ return {
834
+ text: '',
835
+ detail: [rendered, event.approval?.reason, ...(event.approval?.resources ?? [])]
836
+ .filter(Boolean)
837
+ .join('\n'),
838
+ };
839
+ case 'tool.approval.resolved':
840
+ return {
841
+ text: '',
842
+ detail: `${rendered ?? '[Approval]'} ${event.toolName ?? ''} (${event.toolCallId ?? ''})`,
843
+ };
844
+ case 'run.failed': {
845
+ const label = event.limit
846
+ ? {
847
+ modelAttempts: '模型请求',
848
+ toolCalls: '工具调用',
849
+ steps: '运行步骤',
850
+ tokens: '累计 token',
851
+ context: '上下文 token',
852
+ timeMs: '运行时间',
853
+ modelOutput: '模型输出 token',
854
+ }[event.limit.resource]
855
+ : undefined;
856
+ const limit = event.limit;
857
+ const reason = limit?.resource === 'context'
858
+ ? `${event.error?.code === 'CONTEXT_CHECKPOINT' ? '上下文接近上限' : '上下文超出上限'} · 预计 ${limit.required ?? limit.used}/${limit.max} token`
859
+ : limit?.resource === 'timeMs'
860
+ ? [
861
+ '达到运行时间上限',
862
+ formatDuration(limit.used) + '/' + formatDuration(limit.max),
863
+ ...(limit.required === undefined ? [] : ['预计需要 ' + formatDuration(limit.required)]),
864
+ ].join(' · ')
865
+ : label && limit
866
+ ? `达到${label}上限 · ${limit.used}/${limit.max}${limit.required === undefined ? '' : ` · 预计需要 ${limit.required}`}`
867
+ : event.error?.code === 'LIMIT'
868
+ ? '已耗尽运行额度'
869
+ : `运行失败 · ${event.error?.code ?? 'UNKNOWN'}`;
870
+ const unknown = limit?.triggeredByUnknownUsage && limit.unknownUsageTokens !== undefined
871
+ ? ` · 未知用量预估占用 ${formatTokenExact(limit.unknownUsageTokens)} token,触发本次上限`
872
+ : '';
873
+ const text = `${reason}${unknown}${event.checkpoint ? ' · 已保存进度,输入 /resume 继续' : ''}`;
874
+ return { text, detail: [text, rendered].filter(Boolean).join('\n') };
875
+ }
876
+ case 'run.cancelled':
877
+ return { text: '运行已取消', ...(rendered ? { detail: rendered } : {}) };
878
+ case 'step.started':
879
+ return { text: '', detail: `[Step${actor}] ${event.step?.kind ?? ''} started (${event.stepId ?? ''})` };
880
+ case 'model.failed':
881
+ return rendered ? { text: modelFailureMessage(event.error), detail: rendered } : undefined;
882
+ default:
883
+ return rendered ? { text: '', detail: rendered } : undefined;
884
+ }
885
+ }
886
+ export function renderApprovalPrompt(pending) {
887
+ const inner = [
888
+ `${yellow('[Approval Required]')}${pending.memberId ? ` [${pending.memberId}]` : ''} Tool: ${bold(pending.toolName)} ${dim(`(${pending.toolCallId})`)}`,
889
+ ` Approval ID: ${pending.approvalId}`,
890
+ ...(pending.reason ? [` Reason: ${pending.reason}`] : []),
891
+ ...(pending.resources.length ? [` Resources: ${pending.resources.join(', ')}`] : []),
892
+ ` ${bold('[y]')} 批准 / ${bold('[n]')} 拒绝 / ${bold('[d]')} 暂缓`,
893
+ ];
894
+ if (!process.stdout.isTTY)
895
+ return inner.join('\n');
896
+ const cols = process.stdout.columns ?? 88;
897
+ const maxLine = Math.max(...inner.map((line) => stringDisplayWidth(line)));
898
+ if (maxLine > cols - 4) {
899
+ const rule = yellow('─'.repeat(Math.max(20, Math.min(84, cols - 2))));
900
+ return [rule, ...inner, rule].join('\n');
901
+ }
902
+ const contentWidth = Math.max(Math.min(60, cols - 4), maxLine);
903
+ const bar = '─'.repeat(contentWidth + 2);
904
+ const boxed = [
905
+ yellow(`╭${bar}╮`),
906
+ ...inner.map((line) => {
907
+ const pad = ' '.repeat(Math.max(0, contentWidth - stringDisplayWidth(line)));
908
+ return `${yellow('│')} ${line}${pad} ${yellow('│')}`;
909
+ }),
910
+ yellow(`╰${bar}╯`),
911
+ ];
912
+ return boxed.join('\n');
913
+ }
914
+ export function renderTeamBoard(team) {
915
+ const taskByMember = new Map(team.tasks.map((task) => [task.memberId, task]));
916
+ const lines = [`${cyan('[Team]')} Run ${team.runId} | concurrency=${team.concurrency}`];
917
+ if (team.plan) {
918
+ const fallbackBadge = team.plan.fallback ? ` ${yellow('[fallback:single]')}` : '';
919
+ lines.push(`${magenta('[Planner]')} decision=${team.plan.decision}${fallbackBadge} | reason: ${team.plan.reason}`);
920
+ if (team.plan.summary)
921
+ lines.push(` summary: ${team.plan.summary}`);
922
+ }
923
+ lines.push(renderTeamTree(team.members.map((member) => ({
924
+ id: member.id,
925
+ parent: member.parent,
926
+ status: member.status,
927
+ task: taskByMember.get(member.id)?.task,
928
+ }))));
929
+ for (const member of team.members) {
930
+ if (member.id !== 'main')
931
+ lines.push(' ' + member.id + ' · ' + member.agentSessionId);
932
+ }
933
+ if (team.inbox?.length) {
934
+ lines.push(`${cyan('[Inbox]')} (${team.inbox.length})`);
935
+ for (const msg of team.inbox) {
936
+ lines.push(` ${msg.from} -> ${msg.to} [${msg.readAt ? 'read' : 'unread'}] ${msg.sentAt}`);
937
+ lines.push(` ${msg.text}`);
938
+ }
939
+ }
940
+ return lines.join('\n');
941
+ }
942
+ export function renderHostStatus(status) {
943
+ const lines = [
944
+ `${cyan('[Host]')} epoch=${status.epoch} cursor=${status.cursor}`,
945
+ ` configSource: ${status.configSource ?? 'none'}`,
946
+ ` workspaceTools: ${String(status.workspaceTools ?? false)}`,
947
+ ];
948
+ if (status.defaultProfile)
949
+ lines.push(` defaultProfile: ${status.defaultProfile}`);
950
+ if (status.profiles?.length) {
951
+ lines.push(' Profiles:');
952
+ for (const profile of status.profiles) {
953
+ const readiness = profile.ready ? green('ready') : yellow('missing-credential');
954
+ lines.push(` - ${profile.name} [${readiness}]${profile.modelId ? ` model=${profile.modelId}` : ''}${profile.protocol ? ` protocol=${profile.protocol}` : ''}${profile.baseURL ? ` url=${profile.baseURL}` : ''}`);
955
+ }
956
+ }
957
+ if (status.modes?.length)
958
+ lines.push(` Modes: ${status.modes.join(', ')}`);
959
+ if (status.sandbox) {
960
+ lines.push(` Sandbox: ${status.sandbox.backend} (${status.sandbox.state}${status.sandbox.fallbackActive ? ', unsafe-fallback' : ''})${status.sandbox.image ? ` image=${status.sandbox.image}` : ''}`);
961
+ }
962
+ if (status.skills?.length)
963
+ lines.push(` Skills: ${status.skills.join(', ')}`);
964
+ if (status.teamPresets?.length)
965
+ lines.push(` TeamPresets: ${status.teamPresets.join(', ')}`);
966
+ return lines.join('\n');
967
+ }
968
+ export function renderRunDetails(details) {
969
+ const lines = [
970
+ `${cyan('[Run]')} ${details.runId ?? '(unknown)'} status=${bold(details.status ?? 'unknown')}${details.pauseReason ? ` pauseReason=${details.pauseReason}` : ''}`,
971
+ ];
972
+ if (details.pluginBlock)
973
+ lines.push(red(` Blocked: ${details.pluginBlock.code} ${details.pluginBlock.message}`));
974
+ if (details.error) {
975
+ lines.push(red(` Error: ${formatDiagnosticReference(details.error)}`));
976
+ }
977
+ for (const turn of details.turns ?? []) {
978
+ lines.push(` Turn ${turn.id}: ${turn.status}`);
979
+ }
980
+ for (const step of details.steps ?? []) {
981
+ lines.push(` Step ${step.id}: ${step.kind} (${step.status})`);
982
+ }
983
+ for (const tool of details.tools ?? []) {
984
+ const approvalText = tool.approval?.status === 'pending' ? ` [pending approval ${tool.approval.request.approvalId}]` : '';
985
+ lines.push(` Tool ${tool.call.id}: ${tool.call.toolName} (${tool.status})${approvalText}`);
986
+ if (tool.result) {
987
+ lines.push(` outcome=${tool.result.outcome.status}${tool.result.effect ? ` effect=${tool.result.effect}` : ''}`);
988
+ }
989
+ const error = tool.result?.outcome.error ?? tool.lastFailure?.error;
990
+ if (error && !isHiddenToolError(error))
991
+ lines.push(` Error: ${error.code} ${error.message}`);
992
+ if (tool.call.arguments !== undefined) {
993
+ lines.push(` arguments=${JSON.stringify(tool.call.arguments)}`);
994
+ }
995
+ }
996
+ return lines.join('\n');
997
+ }
998
+ export function renderConfigSummary(inspection, status) {
999
+ const { workspaceConfig, userConfig } = inspection.files;
1000
+ const active = workspaceConfig.exists ? workspaceConfig : userConfig.exists ? userConfig : undefined;
1001
+ return [
1002
+ cyan('[Config] 当前设置'),
1003
+ ' 工作区:' + inspection.workdir,
1004
+ active ? ' 使用的配置文件:' + active.path : ' 目前使用内置设置。',
1005
+ status ? ' 工作台已连接。默认模型:' + (status.defaultProfile ?? '尚未选择') : ' 工作台未连接。',
1006
+ ].join('\n');
1007
+ }
1008
+ export function renderConfigCheck(inspection, status) {
1009
+ const lines = [renderConfigSummary(inspection, status)];
1010
+ if (!inspection.files.workspaceConfig.exists && !inspection.files.userConfig.exists) {
1011
+ lines.push(' 运行 saturn provider add 连接第一个 AI 服务。');
1012
+ }
1013
+ else if (!status) {
1014
+ lines.push(' 运行 saturn provider test 检查模型连接。');
1015
+ }
1016
+ else {
1017
+ const model = status.profiles?.find((profile) => profile.name === status.defaultProfile);
1018
+ lines.push(model?.ready
1019
+ ? green(' 默认模型已配置。')
1020
+ : yellow(' 默认模型尚未就绪。运行 saturn provider 管理服务与密钥。'));
1021
+ }
1022
+ return lines.join('\n');
1023
+ }
1024
+ export function renderConfigInit(result) {
1025
+ return [
1026
+ cyan('[Config] 用户设置'),
1027
+ ' 配置文件:' + result.configPath + (result.configCreated ? '(已创建)' : '(已存在)'),
1028
+ ' 密钥文件:' + result.credentialsPath + (result.credentialsCreated ? '(已创建)' : '(已存在)'),
1029
+ ].join('\n');
1030
+ }
1031
+ export function renderUsageCard(usage) {
1032
+ const ctxUsed = usage.latest ? usage.latest.inputTokens + usage.latest.outputTokens : undefined;
1033
+ const ctxLine = ctxUsed !== undefined && usage.contextWindow && usage.contextWindow > 0
1034
+ ? `${formatTokenCompact(ctxUsed)} / ${formatTokenCompact(usage.contextWindow)} (${((ctxUsed / usage.contextWindow) * 100).toFixed(1)}%)`
1035
+ : usage.contextWindow && usage.contextWindow > 0
1036
+ ? `— / ${formatTokenCompact(usage.contextWindow)}`
1037
+ : ctxUsed !== undefined
1038
+ ? `${formatTokenCompact(ctxUsed)} / —`
1039
+ : '—';
1040
+ const formatBucket = (label, bucket) => {
1041
+ const cacheRate = formatCacheRate(bucket.inputTokens, bucket.cachedInputTokens);
1042
+ return ` ${label.padEnd(6)} Input ${formatTokenExact(bucket.inputTokens)} · Cache ${formatTokenCompact(bucket.cachedInputTokens)} (${cacheRate}) · Output ${formatTokenExact(bucket.outputTokens)} · Reasoning ${formatTokenCompact(bucket.reasoningTokens)}${bucket.unknownUsageRequests ? ` · 用量未知 ${formatTokenExact(bucket.unknownUsageRequests)} 次请求` : ''}`;
1043
+ };
1044
+ const latestTps = usage.latest?.outputTokensPerSec;
1045
+ const avgTps = usage.avgOutputTokensPerSec;
1046
+ const speedParts = [
1047
+ latestTps !== undefined ? `最近 ${latestTps.toFixed(1)} tok/s` : undefined,
1048
+ avgTps !== undefined ? `平均 ${avgTps.toFixed(1)} tok/s` : undefined,
1049
+ ].filter(Boolean);
1050
+ const speedLine = speedParts.length ? speedParts.join(' · ') : '—';
1051
+ const resolvedPricing = resolveModelPricing(usage.modelId, usage.pricing, usage.pricingSource);
1052
+ const costLine = resolvedPricing
1053
+ ? `${formatUsd(estimateUsageCostUsd(usage.total, resolvedPricing.pricing))} USD (${resolvedPricing.source === 'config' ? 'config.toml 单价' : '参考单价'})`
1054
+ : '未配置单价(可在 config.toml 添加 pricing)';
1055
+ const lines = [
1056
+ `${cyan('[Usage]')}${usage.modelId ? ` ${bold(usage.modelId)}` : ''}`,
1057
+ ` 当前上下文: ${ctxLine}`,
1058
+ formatBucket('主代理:', usage.main),
1059
+ ...(usage.subagent.inputTokens > 0 ||
1060
+ usage.subagent.outputTokens > 0 ||
1061
+ usage.subagent.unknownUsageRequests
1062
+ ? [formatBucket('子代理:', usage.subagent)]
1063
+ : []),
1064
+ formatBucket('合计: ', usage.total),
1065
+ ` 输出速度: ${speedLine}`,
1066
+ ` 估算花费: ${costLine}`,
1067
+ ];
1068
+ return lines.join('\n');
1069
+ }
1070
+ export function renderReplHelp() {
1071
+ return [
1072
+ bold('工作台命令'),
1073
+ ' /model 选择模型和思考强度',
1074
+ ' /sandbox 查看隔离环境',
1075
+ ' /run 查看当前任务状态',
1076
+ ' <prompt> Run prompt',
1077
+ ' /steer <message> 转向当前运行(Ctrl+Enter / Alt+Enter)',
1078
+ ' /btw <question> 即时旁白问答,不写入历史',
1079
+ ' /team [--concurrency N] [--max-members N] [--preset NAME] [--file FILE] <prompt>',
1080
+ ' Launch an agent team, or bare `/team [runId]` to view board',
1081
+ ' /permission [strict|default|full] 审批模式:strict(写/命令需审批)、default(工作区内免确认)、full(全自动)',
1082
+ ' /effort [level] | /effort worker <lv> 查看或切换当前模型 / 子代理思考强度',
1083
+ ' /usage 查看当前会话上下文占用、Token 拆解、速率与估算花费',
1084
+ ' /new [title] Create and switch to a new session',
1085
+ ' /session [id] Show or switch current session',
1086
+ ' /attach [runId] Follow Run progress (Ctrl+C detaches)',
1087
+ ' /resume [sessionId|runId] 选择最近 10 个历史会话恢复,或恢复指定会话 / 暂停 Run',
1088
+ ' /export [path] 导出当前会话(主代理 + 全部子代理)为 JSONL',
1089
+ ' /cancel [runId] [reason] Cancel a Run',
1090
+ ' /approve [runId] [options] Approve pending tool call and resume',
1091
+ ' /deny [runId] [options] Deny pending tool call',
1092
+ reconciliationUsage('/reconcile [RUN]'),
1093
+ ` /compact [RUN] ${compactionOptionUsage} 压缩上下文`,
1094
+ ' /compact throughTurnId summary 压缩当前运行至指定 Turn',
1095
+ ' /model [profile] Pick model and effort, or switch directly',
1096
+ ' /profile [name] Show active profile or switch directly',
1097
+ ' /mode [name|ref] Show or switch Host Mode (restarts Host)',
1098
+ ' /skill [list|show|toggle|clear] [name] Inspect or toggle discovered/versioned skills',
1099
+ ' /mcp [list|trust|untrust|show] [name] Inspect MCP servers and manage workspace .mcp.json trust',
1100
+ ' /config [show|check|init] [--force] Inspect or initialize ~/.saturn/ config',
1101
+ ' /board 查看当前 CTF 看板 WebUI 地址',
1102
+ ' /pwd Print current workspace path',
1103
+ ' /shortcuts 查看全屏终端快捷键',
1104
+ ' /clear Clear terminal screen',
1105
+ ' /help Show this help',
1106
+ ' /shutdown Shut down local Host',
1107
+ ' /exit | /quit Exit REPL (stops auto-started Host)',
1108
+ ].join('\n');
1109
+ }
1110
+ export function renderShortcutHelp() {
1111
+ return [
1112
+ bold('全屏终端快捷键:'),
1113
+ ' Enter 提交输入;命令面板或侧边栏中确认选择',
1114
+ ' Ctrl+Enter / Alt+Enter 运行中转向,优先使用草稿,其次使用队首消息',
1115
+ ' Ctrl+J 在光标处插入换行',
1116
+ ' 行末 \\ + Enter 插入换行',
1117
+ ' ↑ / ↓ 选择命令/参数/侧边栏代理;多行输入内移动光标,首行/末行或空输入时浏览历史',
1118
+ ' Tab 补全命令或参数',
1119
+ ' Esc 收起命令面板;清除选区;运行中按一次软中断;退出侧栏;空输入查看子代理时返回 main',
1120
+ ' ← / → 按字符移动光标;空输入按 → 或 Ctrl+→ 切到右侧栏',
1121
+ ' Home / Ctrl+A 移到输入开头',
1122
+ ' End / Ctrl+E 移到输入末尾',
1123
+ ' Backspace / Delete 删除光标前/后的字符',
1124
+ ' Ctrl+U 删除光标之前的输入',
1125
+ ' Ctrl+W 删除光标前一个词',
1126
+ ' Ctrl+Y 复制当前输入框全部内容',
1127
+ ' 滚轮 / PgUp / PgDn 滚动对话历史或输入框;拖选期间支持边缘自动滚屏与滚轮延伸选区;右键复制选区',
1128
+ ' Ctrl+O / Ctrl+T 切换摘要/详情',
1129
+ ' Ctrl+B 开关侧栏(宽屏显示)',
1130
+ ' Ctrl+C 运行时分离;空闲时清空输入;空输入时连按两次退出',
1131
+ ' y / n / d 审批时批准 / 拒绝 / 暂缓',
1132
+ ' Ctrl+C 审批时暂缓并关闭审批框',
1133
+ ].join('\n');
1134
+ }