@restranger/repi-subagents 0.0.0-stage → 0.0.1-ca9b82c
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.
- package/README.md +277 -2
- package/package.json +40 -5
- package/src/agent-file.ts +297 -0
- package/src/agent-schema.ts +90 -0
- package/src/child-guard.ts +151 -0
- package/src/command.ts +256 -0
- package/src/default-agents.ts +409 -0
- package/src/discovery.ts +354 -0
- package/src/extensions.ts +119 -0
- package/src/fleet-ui.ts +472 -0
- package/src/format.ts +974 -0
- package/src/frontmatter.ts +302 -0
- package/src/index.ts +112 -0
- package/src/manager.ts +1192 -0
- package/src/model-resolver.ts +58 -0
- package/src/overrides.ts +693 -0
- package/src/plugin.ts +568 -0
- package/src/prompt.ts +184 -0
- package/src/registry.ts +71 -0
- package/src/session.ts +304 -0
- package/src/status-widget.ts +65 -0
- package/src/tool-policy.ts +77 -0
- package/src/tools.ts +554 -0
- package/src/types.ts +163 -0
package/src/format.ts
ADDED
|
@@ -0,0 +1,974 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type PiUiCustomComponent,
|
|
3
|
+
type PiUiCustomTheme,
|
|
4
|
+
SHIMMER_INTERVAL_MS,
|
|
5
|
+
alignRight,
|
|
6
|
+
boldText,
|
|
7
|
+
displayWidth,
|
|
8
|
+
fitWidth,
|
|
9
|
+
renderShimmerLabel,
|
|
10
|
+
sanitize,
|
|
11
|
+
truncate,
|
|
12
|
+
wrapDisplay,
|
|
13
|
+
} from "@restranger/repi-lib";
|
|
14
|
+
import { describeToolSpec } from "./tool-policy.js";
|
|
15
|
+
import type { AgentDefinition, AgentDiagnostic, SubagentActivity, SubagentRunSnapshot } from "./types.js";
|
|
16
|
+
|
|
17
|
+
const MAX_RESULT_CHARS = 30_000;
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Wrap plain lines in the component shape Pi mounts.
|
|
21
|
+
*
|
|
22
|
+
* Pi adds the result as a child of its own `Container`, whose `invalidate()` calls
|
|
23
|
+
* `child.invalidate()` unconditionally — a component without the method crashes the UI on the first
|
|
24
|
+
* invalidate (session switch, `/reload`, shutdown). Every component this plugin hands Pi must
|
|
25
|
+
* therefore implement it, even when it has nothing to cache.
|
|
26
|
+
*/
|
|
27
|
+
export function linesComponent(render: (width: number) => string[]): PiUiCustomComponent {
|
|
28
|
+
return {
|
|
29
|
+
render,
|
|
30
|
+
invalidate: () => undefined,
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Spinner frames shared by the widget, the fleet inspector and the non-TUI dashboard. */
|
|
35
|
+
export const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"] as const;
|
|
36
|
+
|
|
37
|
+
export function spinnerFrame(ms = Date.now()): string {
|
|
38
|
+
const index = Math.floor(ms / SHIMMER_INTERVAL_MS) % SPINNER_FRAMES.length;
|
|
39
|
+
return SPINNER_FRAMES[index] ?? "⠋";
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Palette for agents without an explicit frontmatter colour.
|
|
44
|
+
*
|
|
45
|
+
* Every entry must be a real Pi theme token: `Theme.fg` throws `Unknown theme color` for anything
|
|
46
|
+
* else. The built-in dark/light themes resolve `vars` (`blue`, `green`, `yellow`, `violet`, …) to
|
|
47
|
+
* values only, so `fg("blue")` throws just like `fg("cyan")` does — only keys of `colors` work.
|
|
48
|
+
* Hex colours never reach the theme; `paintAgent` emits them directly.
|
|
49
|
+
*/
|
|
50
|
+
export const AGENT_PALETTE = ["accent", "mdLink", "mdHeading", "syntaxFunction", "toolTitle", "syntaxType"] as const;
|
|
51
|
+
|
|
52
|
+
export const DEFAULT_AGENT_COLORS: Record<string, string> = {
|
|
53
|
+
Plan: "green",
|
|
54
|
+
Explore: "thinkingLow",
|
|
55
|
+
verification: "red",
|
|
56
|
+
"statusline-setup": "orange",
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
export const COLOR_ALIASES: Record<string, string> = {
|
|
60
|
+
green: "success",
|
|
61
|
+
blue: "mdLink",
|
|
62
|
+
cyan: "thinkingLow",
|
|
63
|
+
red: "error",
|
|
64
|
+
orange: "warning",
|
|
65
|
+
yellow: "warning",
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
export function resolveAgentColor(agent?: string, configuredColor?: string): string {
|
|
69
|
+
if (configuredColor?.trim()) {
|
|
70
|
+
return configuredColor.trim();
|
|
71
|
+
}
|
|
72
|
+
const name = typeof agent === "string" ? agent : "";
|
|
73
|
+
if (DEFAULT_AGENT_COLORS[name]) {
|
|
74
|
+
return DEFAULT_AGENT_COLORS[name];
|
|
75
|
+
}
|
|
76
|
+
let hash = 0;
|
|
77
|
+
for (let i = 0; i < name.length; i++) {
|
|
78
|
+
hash = (hash << 5) - hash + name.charCodeAt(i);
|
|
79
|
+
hash |= 0;
|
|
80
|
+
}
|
|
81
|
+
const index = Math.abs(hash) % AGENT_PALETTE.length;
|
|
82
|
+
return AGENT_PALETTE[index] ?? "accent";
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** `theme.fg` for a token that may be missing from a host theme; never throws. */
|
|
86
|
+
export function paintToken(theme: PiUiCustomTheme | undefined, color: string, text: string): string {
|
|
87
|
+
if (!theme) {
|
|
88
|
+
return text;
|
|
89
|
+
}
|
|
90
|
+
try {
|
|
91
|
+
return theme.fg(color, text);
|
|
92
|
+
} catch {
|
|
93
|
+
return text;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export function paintAgent(agent?: string, theme?: PiUiCustomTheme, color?: string): string {
|
|
98
|
+
const name = typeof agent === "string" ? agent : "agent";
|
|
99
|
+
const rawColor = resolveAgentColor(name, color);
|
|
100
|
+
const resolved = COLOR_ALIASES[rawColor.toLowerCase()] ?? rawColor;
|
|
101
|
+
const label = sanitize(name);
|
|
102
|
+
if (!theme) {
|
|
103
|
+
return label;
|
|
104
|
+
}
|
|
105
|
+
if (resolved.startsWith("#") && resolved.length === 7) {
|
|
106
|
+
const r = Number.parseInt(resolved.slice(1, 3), 16);
|
|
107
|
+
const g = Number.parseInt(resolved.slice(3, 5), 16);
|
|
108
|
+
const b = Number.parseInt(resolved.slice(5, 7), 16);
|
|
109
|
+
if (!Number.isNaN(r) && !Number.isNaN(g) && !Number.isNaN(b)) {
|
|
110
|
+
return `\x1b[38;2;${r};${g};${b}m${label}\x1b[39m`;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
try {
|
|
114
|
+
return theme.fg(resolved, label);
|
|
115
|
+
} catch {
|
|
116
|
+
return label;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export function statusColor(status?: string): string {
|
|
121
|
+
switch (status) {
|
|
122
|
+
case "completed":
|
|
123
|
+
return "success";
|
|
124
|
+
case "running":
|
|
125
|
+
case "compacting":
|
|
126
|
+
case "auto-compacting":
|
|
127
|
+
return "accent";
|
|
128
|
+
case "failed":
|
|
129
|
+
return "error";
|
|
130
|
+
case "aborted":
|
|
131
|
+
return "warning";
|
|
132
|
+
default:
|
|
133
|
+
return "muted";
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Identity colors used by the reference fleet widget; stable for a given agent name. */
|
|
138
|
+
export const FLEET_AGENT_IDENTITY_COLORS = [
|
|
139
|
+
"mdLink",
|
|
140
|
+
"mdHeading",
|
|
141
|
+
"syntaxFunction",
|
|
142
|
+
"syntaxKeyword",
|
|
143
|
+
"syntaxNumber",
|
|
144
|
+
"syntaxType",
|
|
145
|
+
"syntaxVariable",
|
|
146
|
+
"customMessageLabel",
|
|
147
|
+
"toolTitle",
|
|
148
|
+
"thinkingMedium",
|
|
149
|
+
"thinkingHigh",
|
|
150
|
+
"mdQuote",
|
|
151
|
+
"bashMode",
|
|
152
|
+
"userMessageText",
|
|
153
|
+
"mdCode",
|
|
154
|
+
"syntaxOperator",
|
|
155
|
+
] as const;
|
|
156
|
+
|
|
157
|
+
export function fleetAgentIdentityColor(identity?: string): string {
|
|
158
|
+
const str = typeof identity === "string" ? identity : "";
|
|
159
|
+
let hash = 2166136261;
|
|
160
|
+
for (let index = 0; index < str.length; index++) {
|
|
161
|
+
hash ^= str.charCodeAt(index);
|
|
162
|
+
hash = Math.imul(hash, 16777619);
|
|
163
|
+
}
|
|
164
|
+
return FLEET_AGENT_IDENTITY_COLORS[(hash >>> 0) % FLEET_AGENT_IDENTITY_COLORS.length] ?? "accent";
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Whole-second elapsed label used by the fleet widget (`1m12s` is intentionally not used).
|
|
169
|
+
* Sub-second work reads `1s`, not the misleading `0s` the previous rounding produced.
|
|
170
|
+
*/
|
|
171
|
+
export function formatFleetElapsed(ms: number): string {
|
|
172
|
+
if (!Number.isFinite(ms) || ms <= 0) {
|
|
173
|
+
return "0s";
|
|
174
|
+
}
|
|
175
|
+
return `${Math.max(1, Math.round(ms / 1000))}s`;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Token label used by the fleet widget and the status summary (`↓ 1.2k tokens`). */
|
|
179
|
+
export function formatFleetTokens(count: number): string {
|
|
180
|
+
const value = Math.max(0, count);
|
|
181
|
+
const compact =
|
|
182
|
+
value >= 1_000_000
|
|
183
|
+
? `${(value / 1_000_000).toFixed(1)}M`
|
|
184
|
+
: value >= 1_000
|
|
185
|
+
? `${(value / 1_000).toFixed(1)}k`
|
|
186
|
+
: `${Math.round(value)}`;
|
|
187
|
+
return `↓ ${compact} tokens`;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// Re-exported so the plugin's own modules keep importing display primitives from `./format.js`.
|
|
191
|
+
export { alignRight, boldText, displayWidth, fitWidth, sanitize, truncate, wrapDisplay };
|
|
192
|
+
|
|
193
|
+
export function paintIdentity(identity?: string, theme?: PiUiCustomTheme): string {
|
|
194
|
+
const str = typeof identity === "string" ? identity : "";
|
|
195
|
+
const label = sanitize(str);
|
|
196
|
+
if (!theme) {
|
|
197
|
+
return label;
|
|
198
|
+
}
|
|
199
|
+
try {
|
|
200
|
+
return theme.fg(fleetAgentIdentityColor(str), label);
|
|
201
|
+
} catch {
|
|
202
|
+
return label;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export function formatAgentCatalog(agents: readonly AgentDefinition[], limit = 20): string {
|
|
207
|
+
if (agents.length === 0) {
|
|
208
|
+
return "No declarative agents found. Create `.pi/agents/<name>.md` or `~/.config/repi/agents/<name>.md`.";
|
|
209
|
+
}
|
|
210
|
+
const visible = agents.slice(0, limit);
|
|
211
|
+
const lines = visible.map(
|
|
212
|
+
(agent) => `- ${sanitize(agent.name)} — ${truncate(agent.description, 160)} (${describeToolSpec(agent)})`,
|
|
213
|
+
);
|
|
214
|
+
if (agents.length > visible.length) {
|
|
215
|
+
lines.push(`- … and ${agents.length - visible.length} more; use subagent_list.`);
|
|
216
|
+
}
|
|
217
|
+
return lines.join("\n");
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
export function formatRun(run: SubagentRunSnapshot): string {
|
|
221
|
+
const duration = formatDuration(runDuration(run));
|
|
222
|
+
const head =
|
|
223
|
+
run.status === "completed"
|
|
224
|
+
? run.turnLimitReached
|
|
225
|
+
? `Subagent "${run.agent}" hit its turn limit after ${duration} (${run.turns} turns, ${run.toolCalls} tool calls).`
|
|
226
|
+
: `Subagent "${run.agent}" completed in ${duration} (${run.turns} turns, ${run.toolCalls} tool calls).`
|
|
227
|
+
: run.status === "failed"
|
|
228
|
+
? `Subagent "${run.agent}" failed after ${duration}.`
|
|
229
|
+
: run.status === "aborted"
|
|
230
|
+
? `Subagent "${run.agent}" was aborted after ${duration}.`
|
|
231
|
+
: `Subagent "${run.agent}" is ${run.status} (${duration}).`;
|
|
232
|
+
|
|
233
|
+
const parts = [head];
|
|
234
|
+
if (run.turnLimitReached) {
|
|
235
|
+
parts.push(`Turn limit: ${run.maxTurns ?? "?"} (the harness stopped the child).`);
|
|
236
|
+
}
|
|
237
|
+
const tokens = formatUsage(run);
|
|
238
|
+
if (tokens) {
|
|
239
|
+
parts.push(`Tokens: ${tokens}.`);
|
|
240
|
+
}
|
|
241
|
+
if (run.diagnostics && run.diagnostics.length > 0) {
|
|
242
|
+
parts.push(`Diagnostics:\n${run.diagnostics.map((entry) => `- ${sanitize(entry)}`).join("\n")}`);
|
|
243
|
+
}
|
|
244
|
+
if (run.error) {
|
|
245
|
+
parts.push(`Error: ${sanitize(run.error)}`);
|
|
246
|
+
}
|
|
247
|
+
if (run.result) {
|
|
248
|
+
parts.push(`Result:\n${truncate(run.result, MAX_RESULT_CHARS)}`);
|
|
249
|
+
}
|
|
250
|
+
return parts.join("\n\n");
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
export function formatRuns(runs: readonly SubagentRunSnapshot[]): string {
|
|
254
|
+
if (runs.length === 0) {
|
|
255
|
+
return "No subagent runs in this session.";
|
|
256
|
+
}
|
|
257
|
+
return runs.map(formatRun).join("\n\n---\n\n");
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
export function formatRunList(runs: readonly SubagentRunSnapshot[]): string {
|
|
261
|
+
if (runs.length === 0) {
|
|
262
|
+
return "No subagent runs in this session.";
|
|
263
|
+
}
|
|
264
|
+
return runs
|
|
265
|
+
.map((run) => {
|
|
266
|
+
const duration = formatDuration(runDuration(run));
|
|
267
|
+
const detail =
|
|
268
|
+
run.status === "running" || run.status === "queued" ? run.description : (run.error ?? run.description);
|
|
269
|
+
return `${statusGlyph(run)} ${run.id} ${run.agent} ${run.status} ${duration} ${truncate(detail, 80)}`;
|
|
270
|
+
})
|
|
271
|
+
.join("\n");
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** One-line description of the tool/phase a child is currently executing. */
|
|
275
|
+
export function formatActivity(
|
|
276
|
+
activity: SubagentActivity | undefined,
|
|
277
|
+
now: number,
|
|
278
|
+
theme?: PiUiCustomTheme,
|
|
279
|
+
shimmerStep?: number,
|
|
280
|
+
): string | undefined {
|
|
281
|
+
if (!activity) {
|
|
282
|
+
return undefined;
|
|
283
|
+
}
|
|
284
|
+
const isSpecialPhase =
|
|
285
|
+
activity.tool === "compacting" || activity.tool === "auto-compacting" || activity.tool === "thinking";
|
|
286
|
+
const detail = activity.detail ? ` ${truncate(sanitize(activity.detail), 64)}` : "";
|
|
287
|
+
const age = Math.max(0, now - activity.at);
|
|
288
|
+
let baseText = `${sanitize(activity.tool)}${detail}`;
|
|
289
|
+
if (age >= 1_000) {
|
|
290
|
+
baseText += isSpecialPhase ? ` (${formatDuration(age)})` : ` · ${formatDuration(age)}`;
|
|
291
|
+
}
|
|
292
|
+
const content =
|
|
293
|
+
isSpecialPhase && shimmerStep !== undefined ? renderShimmerLabel(theme, baseText, shimmerStep) : baseText;
|
|
294
|
+
const icon = paintToken(theme, activity.error ? "error" : "accent", activity.error ? "✗" : "↳");
|
|
295
|
+
const coloredContent = isSpecialPhase
|
|
296
|
+
? paintToken(theme, "accent", content)
|
|
297
|
+
: `${paintToken(theme, "accent", sanitize(activity.tool))}${detail}${age >= 1_000 ? paintToken(theme, "dim", ` · ${formatDuration(age)}`) : ""}`;
|
|
298
|
+
return `${icon} ${coloredContent}`;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/** Line ceiling for the above-editor widget, however tall the terminal is. */
|
|
302
|
+
const MAX_WIDGET_LINES = 12;
|
|
303
|
+
/** Below this the widget stops reading as a widget. */
|
|
304
|
+
const MIN_WIDGET_LINES = 3;
|
|
305
|
+
/** Rows reserved below the widget for Pi's editor and footer (measured against pi-tui 1.4.0). */
|
|
306
|
+
const DOCK_LINES_BELOW_WIDGET = 6;
|
|
307
|
+
/** Indent the host adds before widget lines; the tree adds five more for its first level. */
|
|
308
|
+
const STATUS_INDENT = 2;
|
|
309
|
+
|
|
310
|
+
/** Lines the status widget may render at a terminal height, heading included. */
|
|
311
|
+
export function widgetLineBudget(terminalRows: number | undefined): number {
|
|
312
|
+
if (!terminalRows || terminalRows <= 0) {
|
|
313
|
+
return MAX_WIDGET_LINES;
|
|
314
|
+
}
|
|
315
|
+
return Math.max(MIN_WIDGET_LINES, Math.min(MAX_WIDGET_LINES, terminalRows - DOCK_LINES_BELOW_WIDGET));
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
export interface StatusWidgetOptions {
|
|
319
|
+
readonly width?: number;
|
|
320
|
+
/** Hard line budget; the plugin feeds `widgetLineBudget(terminal.rows)` here. */
|
|
321
|
+
readonly maxLines?: number;
|
|
322
|
+
readonly theme?: PiUiCustomTheme;
|
|
323
|
+
readonly now?: number;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* Status widget above the editor: one header with the fleet totals, then one tree block per active
|
|
328
|
+
* child with elapsed time, turn budget, spend, the last finished steps and the tool it is running
|
|
329
|
+
* right now. Queued children get a single row; finished ones are not rendered at all (their result
|
|
330
|
+
* is already in the tool call, `/fleet` owns history), so the widget disappears the moment the last
|
|
331
|
+
* child settles.
|
|
332
|
+
*
|
|
333
|
+
* The shape follows `pi-subagents`' fleet status widget: `● scout · running · 3s · turn 2/8 · 1.2k tok`
|
|
334
|
+
* with `├─/└─` step rows underneath.
|
|
335
|
+
*
|
|
336
|
+
* Every line is truncated to `width` and the result never exceeds `maxLines`, so the widget can
|
|
337
|
+
* neither hand the differential renderer a too-wide line nor push Pi's editor off the screen.
|
|
338
|
+
*/
|
|
339
|
+
export function formatStatusWidget(runs: readonly SubagentRunSnapshot[], options: StatusWidgetOptions = {}): string[] {
|
|
340
|
+
const width = Math.max(1, Math.floor(options.width ?? 100));
|
|
341
|
+
const maxLines = Math.max(1, Math.floor(options.maxLines ?? MAX_WIDGET_LINES));
|
|
342
|
+
const now = options.now ?? Date.now();
|
|
343
|
+
const theme = options.theme;
|
|
344
|
+
const activeRuns = runs.filter(isActiveRun);
|
|
345
|
+
if (activeRuns.length === 0) {
|
|
346
|
+
return [];
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
// A child that has not reported usage yet must not make the widget claim "0 tokens".
|
|
350
|
+
const spent = activeRuns
|
|
351
|
+
.map(usageTotal)
|
|
352
|
+
.filter((total): total is number => total !== undefined)
|
|
353
|
+
.reduce((sum, total) => sum + total, 0);
|
|
354
|
+
|
|
355
|
+
const hasFailed = runs.some((r) => r.status === "failed" || r.status === "aborted");
|
|
356
|
+
const allCompleted = activeRuns.length === 0 && runs.length > 0 && !hasFailed;
|
|
357
|
+
const anyRunning = activeRuns.some((r) => r.status === "running");
|
|
358
|
+
|
|
359
|
+
let glyph: string;
|
|
360
|
+
if (hasFailed) {
|
|
361
|
+
glyph = paintToken(theme, "error", "✗");
|
|
362
|
+
} else if (allCompleted) {
|
|
363
|
+
glyph = paintToken(theme, "success", "✓");
|
|
364
|
+
} else if (anyRunning) {
|
|
365
|
+
glyph = paintToken(theme, "accent", "●");
|
|
366
|
+
} else {
|
|
367
|
+
glyph = paintToken(theme, "dim", "○");
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
const label = `Active agents: ${activeRuns.length}`;
|
|
371
|
+
const detail = [spent > 0 ? formatFleetTokens(spent) : undefined, "/subagents fleet"]
|
|
372
|
+
.filter((part): part is string => part !== undefined)
|
|
373
|
+
.join(" · ");
|
|
374
|
+
const header = truncate(
|
|
375
|
+
` ${glyph} ${paintToken(theme, "muted", label)} · ${paintToken(theme, "dim", detail)}`,
|
|
376
|
+
width,
|
|
377
|
+
);
|
|
378
|
+
if (maxLines === 1) {
|
|
379
|
+
return [header];
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
const shimmerStep = Math.floor(now / SHIMMER_INTERVAL_MS);
|
|
383
|
+
const blocks = activeRuns.map((run) => statusRunBlock(run, now, theme, shimmerStep));
|
|
384
|
+
const lines = [header];
|
|
385
|
+
let rendered = 0;
|
|
386
|
+
const append = (index: number, withDetails: boolean): boolean => {
|
|
387
|
+
const block = blocks[index] ?? [];
|
|
388
|
+
const remaining = blocks.length - index - 1;
|
|
389
|
+
const chosen = withDetails ? block : block.slice(0, 1);
|
|
390
|
+
if (lines.length + chosen.length > maxLines) {
|
|
391
|
+
return false;
|
|
392
|
+
}
|
|
393
|
+
const branch = remaining > 0 ? "├─" : "└─";
|
|
394
|
+
const gutter = remaining > 0 ? "│ " : " ";
|
|
395
|
+
lines.push(
|
|
396
|
+
...chosen.map((line, lineIndex) =>
|
|
397
|
+
truncate(`${" ".repeat(STATUS_INDENT)}${lineIndex === 0 ? `${branch} ` : gutter}${line}`, width),
|
|
398
|
+
),
|
|
399
|
+
);
|
|
400
|
+
return true;
|
|
401
|
+
};
|
|
402
|
+
while (rendered < blocks.length) {
|
|
403
|
+
const index = rendered;
|
|
404
|
+
if (append(index, true)) {
|
|
405
|
+
rendered++;
|
|
406
|
+
continue;
|
|
407
|
+
}
|
|
408
|
+
// The details do not fit, but the run row itself may: keep the fleet visible as a roster.
|
|
409
|
+
if (!append(index, false)) {
|
|
410
|
+
break;
|
|
411
|
+
}
|
|
412
|
+
rendered++;
|
|
413
|
+
}
|
|
414
|
+
// The header already states the total, so the note is a nicety: never trade a run row for it.
|
|
415
|
+
const hidden = blocks.length - rendered;
|
|
416
|
+
if (hidden > 0 && lines.length < maxLines) {
|
|
417
|
+
lines.push(truncate(` └─ ${paintToken(theme, "dim", `… +${hidden} more active`)}`, width));
|
|
418
|
+
}
|
|
419
|
+
return lines;
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/** One run as an unindented tree block: the run row, then two steps and the live tool. */
|
|
423
|
+
function statusRunBlock(
|
|
424
|
+
run: SubagentRunSnapshot,
|
|
425
|
+
now: number,
|
|
426
|
+
theme: PiUiCustomTheme | undefined,
|
|
427
|
+
shimmerStep?: number,
|
|
428
|
+
): string[] {
|
|
429
|
+
const effectiveStatus = run.status === "running" ? (run.phase ?? run.status) : run.status;
|
|
430
|
+
const status = statusColor(effectiveStatus);
|
|
431
|
+
const glyphChar = run.status === "running" ? spinnerFrame(now) : statusGlyph(run);
|
|
432
|
+
const glyph = paintToken(theme, status, glyphChar);
|
|
433
|
+
const elapsed = formatFleetElapsed(runDuration(run, now));
|
|
434
|
+
const tokens = usageTotal(run);
|
|
435
|
+
const tokenStr = tokens !== undefined && tokens > 0 ? ` ${formatTokens(tokens)} tok` : "";
|
|
436
|
+
|
|
437
|
+
let statusWithTime: string;
|
|
438
|
+
if (run.status === "running") {
|
|
439
|
+
const rawStatus = `${effectiveStatus} (${elapsed})`;
|
|
440
|
+
const animatedStatus = shimmerStep !== undefined ? renderShimmerLabel(theme, rawStatus, shimmerStep) : rawStatus;
|
|
441
|
+
statusWithTime = paintToken(theme, status, animatedStatus);
|
|
442
|
+
} else {
|
|
443
|
+
statusWithTime = paintToken(theme, status, `${effectiveStatus} · ${elapsed}`);
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
const parts = [
|
|
447
|
+
`${glyph} ${paintAgent(run.agent, theme, run.color)}`,
|
|
448
|
+
`${statusWithTime}${tokenStr ? paintToken(theme, "dim", tokenStr) : ""}`,
|
|
449
|
+
];
|
|
450
|
+
if (run.maxTurns !== undefined) {
|
|
451
|
+
parts.push(`turn ${run.turns}/${run.maxTurns}`);
|
|
452
|
+
}
|
|
453
|
+
const lines = [parts.join(" · ")];
|
|
454
|
+
if (run.status !== "running") {
|
|
455
|
+
return lines;
|
|
456
|
+
}
|
|
457
|
+
const steps = (run.steps ?? []).filter((step) => step.finishedAt !== undefined).slice(-2);
|
|
458
|
+
for (const step of steps) {
|
|
459
|
+
const detail = step.detail ? ` ${sanitize(step.detail)}` : "";
|
|
460
|
+
const duration = step.durationMs !== undefined ? ` (${formatDuration(step.durationMs)})` : "";
|
|
461
|
+
const icon = paintToken(theme, step.isError ? "error" : "success", step.isError ? "✗" : "✓");
|
|
462
|
+
lines.push(`${icon} ${sanitize(step.tool)}${detail}${paintToken(theme, "dim", duration)}`);
|
|
463
|
+
}
|
|
464
|
+
const activity = formatActivity(run.activity, now, theme, shimmerStep);
|
|
465
|
+
if (activity) {
|
|
466
|
+
lines.push(activity);
|
|
467
|
+
}
|
|
468
|
+
return lines;
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
/**
|
|
472
|
+
* Inline progress for a foreground run: the host renders these lines under the tool call while the
|
|
473
|
+
* parent waits. The shape mirrors the widget — a status header plus the two most recent finished
|
|
474
|
+
* steps and the live tool — so foreground and background runs read the same way.
|
|
475
|
+
*/
|
|
476
|
+
export function formatRunProgress(
|
|
477
|
+
run: SubagentRunSnapshot,
|
|
478
|
+
now: number,
|
|
479
|
+
spinner = "⠋",
|
|
480
|
+
width = 100,
|
|
481
|
+
theme?: PiUiCustomTheme,
|
|
482
|
+
shimmerStep?: number,
|
|
483
|
+
): string {
|
|
484
|
+
const effectiveStatus = run.status === "running" ? (run.phase ?? run.status) : run.status;
|
|
485
|
+
const status = statusColor(effectiveStatus);
|
|
486
|
+
const glyphChar = run.status === "running" ? spinner : statusGlyph(run);
|
|
487
|
+
const glyph = paintToken(theme, status, glyphChar);
|
|
488
|
+
const elapsed = formatDuration(runDuration(run, now));
|
|
489
|
+
const tokens = usageTotal(run);
|
|
490
|
+
const tokenStr = tokens !== undefined && tokens > 0 ? ` ${formatTokens(tokens)} tok` : "";
|
|
491
|
+
|
|
492
|
+
let statusWithTime: string;
|
|
493
|
+
if (run.status === "running") {
|
|
494
|
+
const rawStatus = `${effectiveStatus} (${elapsed})`;
|
|
495
|
+
const animatedStatus = shimmerStep !== undefined ? renderShimmerLabel(theme, rawStatus, shimmerStep) : rawStatus;
|
|
496
|
+
statusWithTime = paintToken(theme, status, animatedStatus);
|
|
497
|
+
} else {
|
|
498
|
+
statusWithTime = paintToken(theme, status, `${effectiveStatus} · ${elapsed}`);
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
const parts = [
|
|
502
|
+
`${glyph} ${paintAgent(run.agent, theme, run.color)}`,
|
|
503
|
+
`${statusWithTime}${tokenStr ? paintToken(theme, "dim", tokenStr) : ""}`,
|
|
504
|
+
];
|
|
505
|
+
if (run.maxTurns !== undefined) {
|
|
506
|
+
parts.push(`turn ${run.turns}/${run.maxTurns}${run.turnLimitReached ? " limit" : ""}`);
|
|
507
|
+
}
|
|
508
|
+
const lines = [parts.join(" · ")];
|
|
509
|
+
if (run.status === "running") {
|
|
510
|
+
const steps = (run.steps ?? []).filter((step) => step.finishedAt !== undefined).slice(-2);
|
|
511
|
+
for (const step of steps) {
|
|
512
|
+
const detail = step.detail ? ` ${sanitize(step.detail)}` : "";
|
|
513
|
+
const duration = step.durationMs !== undefined ? ` (${formatDuration(step.durationMs)})` : "";
|
|
514
|
+
lines.push(` ${step.isError ? "✗" : "✓"} ${sanitize(step.tool)}${detail}${duration}`);
|
|
515
|
+
}
|
|
516
|
+
const activity = formatActivity(run.activity, now, theme, shimmerStep);
|
|
517
|
+
if (activity) {
|
|
518
|
+
lines.push(` ${activity}`);
|
|
519
|
+
}
|
|
520
|
+
} else if (run.error) {
|
|
521
|
+
lines.push(` ✗ ${firstLine(run.error)}`);
|
|
522
|
+
} else if (run.result) {
|
|
523
|
+
lines.push(` ↳ ${firstLine(run.result)}`);
|
|
524
|
+
}
|
|
525
|
+
return lines.map((line) => truncate(line, width)).join("\n");
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
/** Fleet dashboard: every run in this session as a tree, with each child's latest tool. */
|
|
529
|
+
export function formatFleetDashboard(
|
|
530
|
+
runs: readonly SubagentRunSnapshot[],
|
|
531
|
+
now: number,
|
|
532
|
+
spinner: string,
|
|
533
|
+
options: { readonly selected?: number; readonly width?: number } = {},
|
|
534
|
+
): string[] {
|
|
535
|
+
const active = runs.filter(isActiveRun).length;
|
|
536
|
+
const lines = [`Fleet · ${active} active · ${runs.length} ${runs.length === 1 ? "run" : "runs"}`];
|
|
537
|
+
const width = Math.max(40, Math.min(options.width ?? 120, 200));
|
|
538
|
+
for (const [index, run] of runs.entries()) {
|
|
539
|
+
const marker = options.selected === index ? "→ " : " ";
|
|
540
|
+
const duration = formatDuration(runDuration(run, now));
|
|
541
|
+
const head = `${marker}${statusGlyph(run, spinner)} ${sanitize(run.agent)} · ${run.status} · ${duration} — ${truncate(sanitize(run.description), Math.max(30, width - 36))}`;
|
|
542
|
+
lines.push(truncate(head, width));
|
|
543
|
+
const activity = run.status === "running" ? formatActivity(run.activity, now) : undefined;
|
|
544
|
+
if (activity) {
|
|
545
|
+
lines.push(truncate(` ${activity}`, width));
|
|
546
|
+
}
|
|
547
|
+
if (run.status === "completed" && run.result) {
|
|
548
|
+
lines.push(truncate(` ${firstLine(run.result)}`, width));
|
|
549
|
+
} else if (run.status === "failed" && run.error) {
|
|
550
|
+
lines.push(truncate(` ✗ ${firstLine(run.error)}`, width));
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
if (runs.length === 0) {
|
|
554
|
+
lines.push(" No runs in this session.");
|
|
555
|
+
}
|
|
556
|
+
return lines;
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
/** Full detail for one run as lines, so the inspector can clip it to the terminal budget. */
|
|
560
|
+
export function formatFleetInspectorLines(run: SubagentRunSnapshot, now: number, theme?: PiUiCustomTheme): string[] {
|
|
561
|
+
const agentName = theme ? paintAgent(run.agent, theme, run.color) : sanitize(run.agent);
|
|
562
|
+
const stColor = statusColor(run.status);
|
|
563
|
+
const stText = theme ? theme.fg(stColor, run.status) : run.status;
|
|
564
|
+
const tokens = formatUsage(run);
|
|
565
|
+
const lines: string[] = [
|
|
566
|
+
`${agentName} · ${stText}${run.background ? " · background" : ""}`,
|
|
567
|
+
`id ${sanitize(run.id)}${run.model ? ` · model ${sanitize(run.model)}` : ""}`,
|
|
568
|
+
];
|
|
569
|
+
const stats = [
|
|
570
|
+
formatDuration(runDuration(run, now)),
|
|
571
|
+
`${run.turns} turn${run.turns === 1 ? "" : "s"}`,
|
|
572
|
+
`${run.toolCalls} tool call${run.toolCalls === 1 ? "" : "s"}`,
|
|
573
|
+
];
|
|
574
|
+
if (tokens) {
|
|
575
|
+
stats.push(`${tokens} tokens`);
|
|
576
|
+
}
|
|
577
|
+
lines.push(stats.join(" · "));
|
|
578
|
+
if (run.maxTurns !== undefined) {
|
|
579
|
+
lines.push(`turn budget ${run.turns}/${run.maxTurns}${run.turnLimitReached ? " (limit reached)" : ""}`);
|
|
580
|
+
}
|
|
581
|
+
if (run.activity) {
|
|
582
|
+
lines.push(formatActivity(run.activity, now) ?? "");
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
if (run.steps && run.steps.length > 0) {
|
|
586
|
+
lines.push(`${theme ? theme.fg("accent", `Steps (${run.steps.length}):`) : `Steps (${run.steps.length}):`}`);
|
|
587
|
+
const shown = run.steps.slice(-12);
|
|
588
|
+
const hidden = run.steps.length - shown.length;
|
|
589
|
+
if (hidden > 0) {
|
|
590
|
+
lines.push(` … ${hidden} earlier step${hidden === 1 ? "" : "s"}`);
|
|
591
|
+
}
|
|
592
|
+
shown.forEach((step, index) => {
|
|
593
|
+
const branch = index === shown.length - 1 ? "└─ " : "├─ ";
|
|
594
|
+
const icon = step.isError ? "✗" : step.finishedAt !== undefined ? "✓" : "↳";
|
|
595
|
+
const duration = step.durationMs !== undefined ? ` (${formatDuration(step.durationMs)})` : "";
|
|
596
|
+
const detail = step.detail ? ` ${sanitize(step.detail)}` : "";
|
|
597
|
+
lines.push(` ${branch}${icon} ${sanitize(step.tool)}${detail}${duration}`);
|
|
598
|
+
});
|
|
599
|
+
} else if (run.recentActivity && run.recentActivity.length > 0) {
|
|
600
|
+
lines.push(theme ? theme.fg("accent", "Recent activity:") : "Recent activity:");
|
|
601
|
+
for (const activity of run.recentActivity.slice(-5)) {
|
|
602
|
+
lines.push(` ${formatActivity(activity, now) ?? sanitize(activity.tool)}`);
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
if (run.extensions && run.extensions.length > 0) {
|
|
607
|
+
lines.push(`Extensions: ${run.extensions.map(sanitize).join(", ")}`);
|
|
608
|
+
}
|
|
609
|
+
if (run.diagnostics && run.diagnostics.length > 0) {
|
|
610
|
+
lines.push(
|
|
611
|
+
theme
|
|
612
|
+
? theme.fg("warning", `Diagnostics (${run.diagnostics.length}):`)
|
|
613
|
+
: `Diagnostics (${run.diagnostics.length}):`,
|
|
614
|
+
);
|
|
615
|
+
for (const entry of run.diagnostics) {
|
|
616
|
+
lines.push(` ! ${sanitize(entry)}`);
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
const taskLines = run.task.trim().split("\n");
|
|
621
|
+
if (taskLines.length === 1) {
|
|
622
|
+
lines.push(`${theme ? theme.fg("accent", "Task:") : "Task:"} ${sanitize(taskLines[0] ?? "")}`);
|
|
623
|
+
} else {
|
|
624
|
+
lines.push(theme ? theme.fg("accent", "Task:") : "Task:");
|
|
625
|
+
for (const line of taskLines) {
|
|
626
|
+
lines.push(` ${sanitize(line)}`);
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
if (run.error) {
|
|
631
|
+
lines.push(theme ? theme.fg("error", "Error:") : "Error:");
|
|
632
|
+
for (const line of sanitize(run.error).trim().split("\n").slice(0, 40)) {
|
|
633
|
+
lines.push(` ${line}`);
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
if (run.result) {
|
|
637
|
+
lines.push(theme ? theme.fg("accent", "Output:") : "Output:");
|
|
638
|
+
const resultLines = run.result.split("\n");
|
|
639
|
+
for (const line of resultLines.slice(0, 400)) {
|
|
640
|
+
lines.push(` ${truncate(sanitize(line), 8_000)}`);
|
|
641
|
+
}
|
|
642
|
+
if (resultLines.length > 400) {
|
|
643
|
+
lines.push(` … ${resultLines.length - 400} more lines`);
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
return lines.filter((line) => line.length > 0);
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
/** Full detail for one run, used by text hosts and `subagent_status`. */
|
|
650
|
+
export function formatFleetInspector(run: SubagentRunSnapshot, now: number, theme?: PiUiCustomTheme): string {
|
|
651
|
+
return formatFleetInspectorLines(run, now, theme).join("\n");
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
/**
|
|
655
|
+
* Render lines for a subagent tool invocation call (renderCall).
|
|
656
|
+
*/
|
|
657
|
+
export function formatSubagentCall(args: Record<string, unknown>, theme: PiUiCustomTheme, width = 100): string[] {
|
|
658
|
+
const agent = typeof args.agent === "string" ? args.agent : "agent";
|
|
659
|
+
const isBg = args.background === true || args.async === true;
|
|
660
|
+
const scope = isBg ? "background" : "foreground";
|
|
661
|
+
const task = typeof args.task === "string" ? args.task : typeof args.prompt === "string" ? args.prompt : "...";
|
|
662
|
+
const singleLineTask = task.replace(/\s+/g, " ").trim();
|
|
663
|
+
const title = `${theme.fg("toolTitle", "subagent ")}${paintAgent(agent, theme)} ${theme.fg("muted", `[${scope}]`)}`;
|
|
664
|
+
const taskLine = truncate(`${theme.fg("dim", "task:")} ${singleLineTask}`, width);
|
|
665
|
+
return [truncate(title, width), taskLine];
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
/**
|
|
669
|
+
* Compact 1-2 line status for completed/background tool result (when not expanded).
|
|
670
|
+
*/
|
|
671
|
+
export function formatSubagentResultCompact(
|
|
672
|
+
run: SubagentRunSnapshot,
|
|
673
|
+
theme: PiUiCustomTheme,
|
|
674
|
+
now: number,
|
|
675
|
+
width = 100,
|
|
676
|
+
): string[] {
|
|
677
|
+
const glyph =
|
|
678
|
+
run.status === "completed"
|
|
679
|
+
? run.turnLimitReached
|
|
680
|
+
? theme.fg("warning", "✓")
|
|
681
|
+
: theme.fg("success", "✓")
|
|
682
|
+
: run.status === "failed"
|
|
683
|
+
? theme.fg("error", "✗")
|
|
684
|
+
: run.status === "aborted"
|
|
685
|
+
? theme.fg("warning", "⊘")
|
|
686
|
+
: theme.fg("accent", "▶");
|
|
687
|
+
const agentName = paintAgent(run.agent || "subagent", theme, run.color);
|
|
688
|
+
const st = run.status || "unknown";
|
|
689
|
+
const stColor = statusColor(st);
|
|
690
|
+
const stText = theme.fg(stColor, st);
|
|
691
|
+
const duration = theme.fg("muted", formatDuration(runDuration(run, now)));
|
|
692
|
+
const stats: string[] = [];
|
|
693
|
+
if (run.model) {
|
|
694
|
+
stats.push(theme.fg("dim", sanitize(run.model)));
|
|
695
|
+
}
|
|
696
|
+
if (run.toolCalls > 0) {
|
|
697
|
+
stats.push(theme.fg("dim", `${run.toolCalls} tool${run.toolCalls === 1 ? "" : "s"}`));
|
|
698
|
+
}
|
|
699
|
+
const tok = formatUsage(run);
|
|
700
|
+
if (tok) {
|
|
701
|
+
stats.push(theme.fg("dim", `${tok} tok`));
|
|
702
|
+
}
|
|
703
|
+
if (run.maxTurns !== undefined) {
|
|
704
|
+
const budget = `turn ${run.turns}/${run.maxTurns}`;
|
|
705
|
+
stats.push(theme.fg(run.turnLimitReached ? "warning" : "dim", budget));
|
|
706
|
+
}
|
|
707
|
+
const statsSuffix = stats.length > 0 ? ` · ${stats.join(" · ")}` : "";
|
|
708
|
+
const line1 = `${glyph} ${agentName} ${stText} · ${duration}${statsSuffix}`;
|
|
709
|
+
|
|
710
|
+
const lines = [truncate(line1, width)];
|
|
711
|
+
if (run.background && (run.status === "running" || run.status === "queued")) {
|
|
712
|
+
lines.push(
|
|
713
|
+
truncate(
|
|
714
|
+
` ↳ ${theme.fg("muted", `Running in background (${run.id}) · use /subagents fleet or subagent_status`)}`,
|
|
715
|
+
width,
|
|
716
|
+
),
|
|
717
|
+
);
|
|
718
|
+
} else if (run.status === "failed" && run.error) {
|
|
719
|
+
lines.push(truncate(` ↳ ${theme.fg("error", firstLine(run.error))}`, width));
|
|
720
|
+
} else if (run.result) {
|
|
721
|
+
const summary = firstLine(run.result);
|
|
722
|
+
const expandHint = theme.fg("accent", "(enter to expand)");
|
|
723
|
+
lines.push(
|
|
724
|
+
truncate(
|
|
725
|
+
` ↳ ${theme.fg("muted", summary ? `${truncate(summary, Math.max(20, width - 26))} ` : "")}${expandHint}`,
|
|
726
|
+
width,
|
|
727
|
+
),
|
|
728
|
+
);
|
|
729
|
+
}
|
|
730
|
+
return lines;
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
/**
|
|
734
|
+
* Rich streaming progress for active runs (isPartial).
|
|
735
|
+
*/
|
|
736
|
+
export function formatSubagentResultPartial(
|
|
737
|
+
run: SubagentRunSnapshot,
|
|
738
|
+
theme: PiUiCustomTheme,
|
|
739
|
+
now: number,
|
|
740
|
+
spinner = "⠋",
|
|
741
|
+
width = 100,
|
|
742
|
+
): string[] {
|
|
743
|
+
const agentName = paintAgent(run.agent || "subagent", theme, run.color);
|
|
744
|
+
const duration = theme.fg("muted", formatDuration(runDuration(run, now)));
|
|
745
|
+
const stats: string[] = [];
|
|
746
|
+
if (run.toolCalls > 0) {
|
|
747
|
+
stats.push(theme.fg("dim", `${run.toolCalls} tool${run.toolCalls === 1 ? "" : "s"}`));
|
|
748
|
+
}
|
|
749
|
+
const tok = formatUsage(run);
|
|
750
|
+
if (tok) {
|
|
751
|
+
stats.push(theme.fg("dim", `${tok} tok`));
|
|
752
|
+
}
|
|
753
|
+
if (run.maxTurns !== undefined) {
|
|
754
|
+
stats.push(theme.fg("dim", `turn ${run.turns}/${run.maxTurns}`));
|
|
755
|
+
}
|
|
756
|
+
const statsSuffix = stats.length > 0 ? ` · ${stats.join(" · ")}` : "";
|
|
757
|
+
const head = `${theme.fg("accent", spinner)} ${agentName} ${theme.fg("accent", "running")} · ${duration}${statsSuffix}`;
|
|
758
|
+
const lines = [truncate(head, width)];
|
|
759
|
+
|
|
760
|
+
// Show completed steps (up to 2 recent), like Claude Code
|
|
761
|
+
if (run.steps && run.steps.length > 0) {
|
|
762
|
+
const completedSteps = run.steps.filter((s) => s.finishedAt !== undefined).slice(-2);
|
|
763
|
+
for (const step of completedSteps) {
|
|
764
|
+
const icon = step.isError
|
|
765
|
+
? theme.fg("error", "✗")
|
|
766
|
+
: step.finishedAt !== undefined
|
|
767
|
+
? theme.fg("success", "✓")
|
|
768
|
+
: theme.fg("accent", "↳");
|
|
769
|
+
const detail = step.detail ? ` ${sanitize(step.detail)}` : "";
|
|
770
|
+
lines.push(truncate(` ${icon} ${theme.fg("dim", `${sanitize(step.tool)}${detail}`)}`, width));
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
// Current live activity
|
|
775
|
+
const activity = formatActivity(run.activity, now);
|
|
776
|
+
if (activity) {
|
|
777
|
+
lines.push(truncate(` ↳ ${theme.fg("accent", activity.replace(/^[↳✗]\s*/, ""))}`, width));
|
|
778
|
+
}
|
|
779
|
+
return lines;
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
/**
|
|
783
|
+
* Full expanded view for tool result (when user presses Enter / ctrl+o).
|
|
784
|
+
*/
|
|
785
|
+
export function formatSubagentResultExpanded(
|
|
786
|
+
run: SubagentRunSnapshot,
|
|
787
|
+
theme: PiUiCustomTheme,
|
|
788
|
+
now: number,
|
|
789
|
+
width = 100,
|
|
790
|
+
): string[] {
|
|
791
|
+
const glyph =
|
|
792
|
+
run.status === "completed"
|
|
793
|
+
? run.turnLimitReached
|
|
794
|
+
? theme.fg("warning", "✓")
|
|
795
|
+
: theme.fg("success", "✓")
|
|
796
|
+
: run.status === "failed"
|
|
797
|
+
? theme.fg("error", "✗")
|
|
798
|
+
: run.status === "aborted"
|
|
799
|
+
? theme.fg("warning", "⊘")
|
|
800
|
+
: theme.fg("accent", "▶");
|
|
801
|
+
const agentName = paintAgent(run.agent || "subagent", theme, run.color);
|
|
802
|
+
const st = run.status || "unknown";
|
|
803
|
+
const stColor = statusColor(st);
|
|
804
|
+
const duration = formatDuration(runDuration(run, now));
|
|
805
|
+
|
|
806
|
+
const lines: string[] = [truncate(`${glyph} ${agentName} ${theme.fg(stColor, st)} · ${duration}`, width)];
|
|
807
|
+
|
|
808
|
+
// Meta info
|
|
809
|
+
const metaParts: string[] = [`id ${sanitize(run.id)}`];
|
|
810
|
+
if (run.model) {
|
|
811
|
+
metaParts.push(`model ${sanitize(run.model)}`);
|
|
812
|
+
}
|
|
813
|
+
metaParts.push(`${run.turns ?? 0} turns · ${run.toolCalls ?? 0} tool calls`);
|
|
814
|
+
const tok = formatUsage(run);
|
|
815
|
+
if (tok) {
|
|
816
|
+
metaParts.push(`${tok} tokens`);
|
|
817
|
+
}
|
|
818
|
+
if (run.maxTurns !== undefined) {
|
|
819
|
+
metaParts.push(`turn budget ${run.turns}/${run.maxTurns}${run.turnLimitReached ? " (limit reached)" : ""}`);
|
|
820
|
+
}
|
|
821
|
+
lines.push(truncate(theme.fg("muted", metaParts.join(" · ")), width));
|
|
822
|
+
if (run.status === "running") {
|
|
823
|
+
const activity = formatActivity(run.activity, now);
|
|
824
|
+
if (activity) {
|
|
825
|
+
lines.push(truncate(` ${theme.fg("accent", activity)}`, width));
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
// Task section
|
|
830
|
+
lines.push(truncate(theme.fg("muted", "─── Task ───"), width));
|
|
831
|
+
const taskLines = (run.task ?? "").trim().split("\n");
|
|
832
|
+
for (const line of taskLines.slice(0, 10)) {
|
|
833
|
+
lines.push(truncate(` ${theme.fg("dim", sanitize(line))}`, width));
|
|
834
|
+
}
|
|
835
|
+
if (taskLines.length > 10) {
|
|
836
|
+
lines.push(truncate(` ${theme.fg("muted", `... (+${taskLines.length - 10} more lines)`)}`, width));
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
// Execution steps (tree view)
|
|
840
|
+
if (run.steps && run.steps.length > 0) {
|
|
841
|
+
lines.push(truncate(theme.fg("muted", `─── Execution Steps (${run.steps.length}) ───`), width));
|
|
842
|
+
const stepsToShow = run.steps.slice(-15);
|
|
843
|
+
const skipped = run.steps.length - stepsToShow.length;
|
|
844
|
+
if (skipped > 0) {
|
|
845
|
+
lines.push(truncate(` ${theme.fg("muted", `... ${skipped} earlier steps`)}`, width));
|
|
846
|
+
}
|
|
847
|
+
for (let i = 0; i < stepsToShow.length; i++) {
|
|
848
|
+
const step = stepsToShow[i];
|
|
849
|
+
if (!step) {
|
|
850
|
+
continue;
|
|
851
|
+
}
|
|
852
|
+
const isLast = i === stepsToShow.length - 1;
|
|
853
|
+
const branch = isLast ? "└─ " : "├─ ";
|
|
854
|
+
const icon = step.isError ? theme.fg("error", "✗") : theme.fg("success", "✓");
|
|
855
|
+
const dur = step.durationMs !== undefined ? ` (${formatDuration(step.durationMs)})` : "";
|
|
856
|
+
const detail = step.detail ? ` ${sanitize(step.detail)}` : "";
|
|
857
|
+
lines.push(
|
|
858
|
+
truncate(
|
|
859
|
+
` ${theme.fg("muted", branch)}${icon} ${theme.fg("accent", sanitize(step.tool))}${theme.fg("dim", detail)}${theme.fg("muted", dur)}`,
|
|
860
|
+
width,
|
|
861
|
+
),
|
|
862
|
+
);
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
// Output / Result section
|
|
867
|
+
lines.push(truncate(theme.fg("muted", "─── Output ───"), width));
|
|
868
|
+
if (run.error) {
|
|
869
|
+
lines.push(truncate(` ${theme.fg("error", `Error: ${sanitize(run.error)}`)}`, width));
|
|
870
|
+
}
|
|
871
|
+
if (run.result) {
|
|
872
|
+
const resultLines = run.result.trim().split("\n");
|
|
873
|
+
const maxOutputLines = 60;
|
|
874
|
+
for (const line of resultLines.slice(0, maxOutputLines)) {
|
|
875
|
+
lines.push(truncate(` ${theme.fg("dim", sanitize(line))}`, width));
|
|
876
|
+
}
|
|
877
|
+
if (resultLines.length > maxOutputLines) {
|
|
878
|
+
lines.push(truncate(` ${theme.fg("muted", `... (+${resultLines.length - maxOutputLines} more lines)`)}`, width));
|
|
879
|
+
}
|
|
880
|
+
} else if (!run.error) {
|
|
881
|
+
lines.push(truncate(` ${theme.fg("muted", run.status === "running" ? "(running…)" : "(no output)")}`, width));
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
// Diagnostics
|
|
885
|
+
if (run.diagnostics && run.diagnostics.length > 0) {
|
|
886
|
+
lines.push(truncate(theme.fg("warning", `─── Diagnostics (${run.diagnostics.length}) ───`), width));
|
|
887
|
+
for (const diag of run.diagnostics) {
|
|
888
|
+
lines.push(truncate(` ! ${theme.fg("warning", sanitize(diag))}`, width));
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
return lines;
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
export function formatDiagnostics(diagnostics: readonly AgentDiagnostic[]): string {
|
|
896
|
+
if (diagnostics.length === 0) {
|
|
897
|
+
return "No agent diagnostics.";
|
|
898
|
+
}
|
|
899
|
+
return diagnostics
|
|
900
|
+
.map(
|
|
901
|
+
(diagnostic) => `${diagnostic.level.toUpperCase()} ${sanitize(diagnostic.path)}: ${sanitize(diagnostic.message)}`,
|
|
902
|
+
)
|
|
903
|
+
.join("\n");
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
export function formatDuration(ms: number): string {
|
|
907
|
+
const seconds = Math.max(0, ms) / 1000;
|
|
908
|
+
if (seconds < 10) {
|
|
909
|
+
return `${seconds.toFixed(1)}s`;
|
|
910
|
+
}
|
|
911
|
+
// Round once, before splitting, or 59.6s renders as `60s` and 59m59.6s as `59m60s`.
|
|
912
|
+
const rounded = Math.round(seconds);
|
|
913
|
+
if (rounded < 60) {
|
|
914
|
+
return `${rounded}s`;
|
|
915
|
+
}
|
|
916
|
+
const minutes = Math.floor(rounded / 60);
|
|
917
|
+
const rest = rounded % 60;
|
|
918
|
+
return `${minutes}m${rest.toString().padStart(2, "0")}s`;
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
/** `1.2k` style token count, or nothing when the host reported no usage. */
|
|
922
|
+
export function formatTokens(total: number): string {
|
|
923
|
+
if (total < 1_000) {
|
|
924
|
+
return `${total}`;
|
|
925
|
+
}
|
|
926
|
+
if (total < 1_000_000) {
|
|
927
|
+
return `${(total / 1_000).toFixed(total < 10_000 ? 1 : 0)}k`;
|
|
928
|
+
}
|
|
929
|
+
return `${(total / 1_000_000).toFixed(1)}M`;
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
export function runDuration(run?: Partial<SubagentRunSnapshot>, now = Date.now()): number {
|
|
933
|
+
if (!run) {
|
|
934
|
+
return 0;
|
|
935
|
+
}
|
|
936
|
+
const end = run.finishedAt ?? now;
|
|
937
|
+
const start = run.startedAt ?? run.createdAt ?? now;
|
|
938
|
+
return Math.max(0, end - start);
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
export function statusGlyph(run?: Partial<SubagentRunSnapshot>, spinner?: string): string {
|
|
942
|
+
switch (run?.status) {
|
|
943
|
+
case "running":
|
|
944
|
+
return spinner ?? "▶";
|
|
945
|
+
case "queued":
|
|
946
|
+
return "◌";
|
|
947
|
+
case "completed":
|
|
948
|
+
return "✓";
|
|
949
|
+
case "aborted":
|
|
950
|
+
return "⊘";
|
|
951
|
+
default:
|
|
952
|
+
return "✗";
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
function isActiveRun(run: SubagentRunSnapshot): boolean {
|
|
957
|
+
return run.status === "running" || run.status === "queued";
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
function usageTotal(run: SubagentRunSnapshot): number | undefined {
|
|
961
|
+
if (!run.usage) {
|
|
962
|
+
return undefined;
|
|
963
|
+
}
|
|
964
|
+
return run.usage.total ?? ((run.usage.input ?? 0) + (run.usage.output ?? 0) || undefined);
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
function formatUsage(run: SubagentRunSnapshot): string | undefined {
|
|
968
|
+
const total = usageTotal(run);
|
|
969
|
+
return total === undefined ? undefined : formatTokens(total);
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
function firstLine(value: string): string {
|
|
973
|
+
return sanitize(value).trim().split("\n")[0]?.trim() ?? "";
|
|
974
|
+
}
|