oira666_pi-subagent 0.2.19 → 0.2.21

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/render.ts CHANGED
@@ -1,463 +1,471 @@
1
- /**
2
- * TUI rendering for subagent tool calls and results.
3
- */
4
-
5
- import * as os from "node:os";
6
- import { Container, Spacer, Text } from "@mariozechner/pi-tui";
7
- import {
8
- type LiveLogEntry,
9
- type NestedSubagentResult,
10
- type SingleResult,
11
- type SubagentDetails,
12
- type UsageStats,
13
- aggregateUsage,
14
- getDisplayItems,
15
- getFinalOutput,
16
- getNestedSubagentResults,
17
- isResultError,
18
- isSubagentDetails,
19
- } from "./types.js";
20
-
21
- const OUTPUT_PREVIEW_LINE_COUNT = 6;
22
-
23
- type ThemeFg = (color: string, text: string) => string;
24
- type NodeStatus = "running" | "success" | "error";
25
-
26
- interface TreeNode {
27
- label: string;
28
- status: NodeStatus;
29
- meta?: string;
30
- task?: string;
31
- outputPreview?: string[];
32
- liveActivity?: LiveLogEntry[];
33
- children: TreeNode[];
34
- }
35
-
36
-
37
- interface TreeCounts {
38
- total: number;
39
- running: number;
40
- success: number;
41
- error: number;
42
- finished: number;
43
- }
44
-
45
- interface PendingSubagentCall {
46
- toolCallId: string;
47
- tasks: Array<{ agent: string; task?: string; cwd?: string }>;
48
- }
49
-
50
- // ---------------------------------------------------------------------------
51
- // Formatting helpers
52
- // ---------------------------------------------------------------------------
53
-
54
- function formatTokens(count: number): string {
55
- if (count < 1000) return count.toString();
56
- if (count < 10000) return `${(count / 1000).toFixed(1)}k`;
57
- if (count < 1000000) return `${Math.round(count / 1000)}k`;
58
- return `${(count / 1000000).toFixed(1)}M`;
59
- }
60
-
61
- function formatUsage(usage: Partial<UsageStats>, model?: string): string {
62
- const parts: string[] = [];
63
- const totalTokens =
64
- (usage.input || 0) +
65
- (usage.output || 0) +
66
- (usage.cacheRead || 0) +
67
- (usage.cacheWrite || 0);
68
- if (usage.turns) parts.push(`${usage.turns} turn${usage.turns > 1 ? "s" : ""}`);
69
- if (totalTokens > 0) parts.push(`tok:${formatTokens(totalTokens)}`);
70
- if (usage.input) parts.push(`in:${formatTokens(usage.input)}`);
71
- if (usage.output) parts.push(`out:${formatTokens(usage.output)}`);
72
- if (usage.cacheRead) parts.push(`cacheR:${formatTokens(usage.cacheRead)}`);
73
- if (usage.cacheWrite) parts.push(`cacheW:${formatTokens(usage.cacheWrite)}`);
74
- if (usage.cost) parts.push(`$${usage.cost.toFixed(4)}`);
75
- if (usage.contextTokens && usage.contextTokens > 0) parts.push(`ctx:${formatTokens(usage.contextTokens)}`);
76
- if (model) parts.push(model);
77
- return parts.join(" • ");
78
- }
79
-
80
- function truncate(text: string, maxLen: number): string {
81
- return text.length > maxLen ? `${text.slice(0, maxLen)}...` : text;
82
- }
83
-
84
- function splitOutputLines(text: string): string[] {
85
- const lines = text.replace(/\r\n?/g, "\n").split("\n");
86
- if (lines.length > 1 && lines[lines.length - 1] === "") lines.pop();
87
- return lines;
88
- }
89
-
90
- function lastNonEmptyLines(text: string, limit: number): string[] {
91
- return splitOutputLines(text)
92
- .map((line) => line.trimEnd())
93
- .filter((line) => line.trim().length > 0)
94
- .slice(-limit);
95
- }
96
-
97
- function statusEmoji(status: NodeStatus, theme: { fg: ThemeFg }): string {
98
- switch (status) {
99
- case "running":
100
- return theme.fg("warning", "⏳");
101
- case "error":
102
- return theme.fg("error", "❌");
103
- default:
104
- return theme.fg("success", "✅");
105
- }
106
- }
107
-
108
- function statusFromResult(result: SingleResult): NodeStatus {
109
- if (result.exitCode === -1) return "running";
110
- return isResultError(result) ? "error" : "success";
111
- }
112
-
113
- function countNodes(nodes: TreeNode[]): TreeCounts {
114
- const counts: TreeCounts = {
115
- total: 0,
116
- running: 0,
117
- success: 0,
118
- error: 0,
119
- finished: 0,
120
- };
121
-
122
- const visit = (node: TreeNode) => {
123
- counts.total++;
124
- if (node.status === "running") counts.running++;
125
- if (node.status === "success") counts.success++;
126
- if (node.status === "error") counts.error++;
127
- if (node.status !== "running") counts.finished++;
128
- for (const child of node.children) visit(child);
129
- };
130
-
131
- for (const node of nodes) visit(node);
132
- return counts;
133
- }
134
-
135
- function hasNestedChildren(nodes: TreeNode[]): boolean {
136
- return nodes.some((node) => node.children.length > 0 || hasNestedChildren(node.children));
137
- }
138
-
139
- function extractPendingSubagentCalls(messages: SingleResult["messages"]): PendingSubagentCall[] {
140
- const calls: PendingSubagentCall[] = [];
141
- for (let messageIndex = 0; messageIndex < messages.length; messageIndex++) {
142
- const message = messages[messageIndex] as any;
143
- if (message.role !== "assistant" || !Array.isArray(message.content)) continue;
144
- for (let partIndex = 0; partIndex < message.content.length; partIndex++) {
145
- const part = message.content[partIndex] as any;
146
- if (part?.type !== "toolCall" || part?.name !== "subagent") continue;
147
- const args = part.arguments && typeof part.arguments === "object" ? part.arguments : {};
148
- const tasks = Array.isArray((args as any).tasks)
149
- ? (args as any).tasks
150
- .filter((task: any) => task && typeof task.agent === "string")
151
- .map((task: any) => ({
152
- agent: task.agent,
153
- task: typeof task.task === "string" ? task.task : undefined,
154
- cwd: typeof task.cwd === "string" ? task.cwd : undefined,
155
- }))
156
- : [];
157
- calls.push({
158
- toolCallId:
159
- typeof part.toolCallId === "string"
160
- ? part.toolCallId
161
- : typeof part.id === "string"
162
- ? part.id
163
- : `${messageIndex}:${partIndex}`,
164
- tasks,
165
- });
166
- }
167
- }
168
- return calls;
169
- }
170
-
171
- function buildPendingNodes(call: PendingSubagentCall): TreeNode[] {
172
- return call.tasks.map((task) => ({
173
- label: task.agent,
174
- status: "running",
175
- task: task.task,
176
- children: [],
177
- }));
178
- }
179
-
180
- function buildNodesFromNestedResult(nested: NestedSubagentResult): TreeNode[] {
181
- return nested.details.results.map((result) => buildResultNode(result));
182
- }
183
-
184
- function subagentCallSignature(call: PendingSubagentCall): string {
185
- return JSON.stringify(call.tasks.map((task) => ({ agent: task.agent, task: task.task ?? "", cwd: task.cwd ?? "" })));
186
- }
187
-
188
- function nestedResultIsHealthy(nested: NestedSubagentResult | undefined): boolean {
189
- if (!nested || nested.isError) return false;
190
- return nested.details.results.every((result) => !isResultError(result));
191
- }
192
-
193
- function buildNestedChildren(result: SingleResult): TreeNode[] {
194
- const parentIsRunning = result.exitCode === -1;
195
- const completedByToolCallId = new Map<string, NestedSubagentResult>();
196
- for (const nested of getNestedSubagentResults(result.messages)) {
197
- completedByToolCallId.set(nested.toolCallId, nested);
198
- }
199
-
200
- const calls = extractPendingSubagentCalls(result.messages);
201
- const laterResumeBySignature = new Map<string, number>();
202
- calls.forEach((call, index) => {
203
- const completed = completedByToolCallId.get(call.toolCallId);
204
- // A resumed call has the same task signature as the interrupted call but a
205
- // newer toolCallId. Prefer that newer running/successful tree over the old
206
- // synthetic/aborted result so resumed nested subagents render in-place.
207
- if (!completed || nestedResultIsHealthy(completed)) {
208
- laterResumeBySignature.set(subagentCallSignature(call), index);
209
- }
210
- });
211
-
212
- const nodes: TreeNode[] = [];
213
- calls.forEach((call, index) => {
214
- const completed = completedByToolCallId.get(call.toolCallId);
215
- const newerEquivalent = laterResumeBySignature.get(subagentCallSignature(call));
216
- if (
217
- newerEquivalent !== undefined &&
218
- newerEquivalent > index &&
219
- (!completed || completed.isError || !nestedResultIsHealthy(completed))
220
- ) {
221
- return;
222
- }
223
-
224
- if (completed && isSubagentDetails(completed.details)) {
225
- nodes.push(...buildNodesFromNestedResult(completed));
226
- return;
227
- }
228
- // Unmatched subagent tool calls are useful while the parent is still
229
- // running (they show live pending children). Once the parent finished,
230
- // unmatched calls are stale history from an interrupted/resumed session and
231
- // must not keep the whole tree in a perpetual "running" state.
232
- if (parentIsRunning) nodes.push(...buildPendingNodes(call));
233
- });
234
- return nodes;
235
- }
236
-
237
- function formatToolArgPreview(toolName: string, args: Record<string, unknown>): string {
238
- const shorten = (p: string) => {
239
- const home = os.homedir();
240
- return p.startsWith(home) ? `~${p.slice(home.length)}` : p;
241
- };
242
- const truncateTo = (s: string, n: number) =>
243
- s.length > n ? s.slice(0, n) + "\u2026" : s;
244
-
245
- switch (toolName) {
246
- case "bash": {
247
- const cmd = (args.command as string) || "";
248
- return truncateTo(cmd.replace(/\s+/g, " "), 52);
249
- }
250
- case "read":
251
- case "write":
252
- case "edit":
253
- return shorten(truncateTo((args.path ?? args.file_path ?? "") as string, 52));
254
- case "grep":
255
- return truncateTo(`/${args.pattern}/`, 30) +
256
- (args.path ? ` in ${shorten(args.path as string)}` : "");
257
- case "find":
258
- return truncateTo((args.pattern ?? "*") as string, 30) +
259
- (args.path ? ` in ${shorten(args.path as string)}` : "");
260
- case "subagent": {
261
- const tasks = (args.tasks as any[]) ?? [];
262
- return tasks.map((t: any) => t.agent).join(", ");
263
- }
264
- default:
265
- return "";
266
- }
267
- }
268
-
269
- function formatLiveLogEntry(
270
- entry: LiveLogEntry,
271
- theme: { fg: ThemeFg },
272
- ): string {
273
- switch (entry.kind) {
274
- case "turn_start":
275
- return theme.fg("muted", "\u27f3") + " " + theme.fg("dim", "thinking\u2026");
276
-
277
- case "turn_end": {
278
- const tokens = entry.inputTokens || entry.outputTokens
279
- ? " " + theme.fg("dim",
280
- `\u2191${formatTokens(entry.inputTokens)} \u2193${formatTokens(entry.outputTokens)}`)
281
- : "";
282
- return (
283
- theme.fg("success", "\u2713") +
284
- " " +
285
- theme.fg("muted", `turn ${entry.turn}`) +
286
- tokens
287
- );
288
- }
289
-
290
- case "tool_start": {
291
- const argPreview = formatToolArgPreview(entry.toolName, entry.args);
292
- return (
293
- theme.fg("muted", "\u2192") +
294
- " " +
295
- theme.fg("accent", entry.toolName) +
296
- (argPreview ? " " + theme.fg("dim", argPreview) : "")
297
- );
298
- }
299
-
300
- case "tool_end":
301
- return (
302
- theme.fg("success", "\u2713") +
303
- " " +
304
- theme.fg("accent", entry.toolName)
305
- );
306
- }
307
- }
308
-
309
- function buildLeafPreview(result: SingleResult): string[] | undefined {
310
- const items = getDisplayItems(result.messages);
311
- const lines: string[] = [];
312
- for (const item of items) {
313
- if (item.type === "text") {
314
- lines.push(...lastNonEmptyLines(item.text, OUTPUT_PREVIEW_LINE_COUNT));
315
- }
316
- }
317
- const finalOutput = getFinalOutput(result.messages);
318
- if (finalOutput) lines.push(...lastNonEmptyLines(finalOutput, OUTPUT_PREVIEW_LINE_COUNT));
319
- const unique = lines.filter((line, index) => line && lines.indexOf(line) === index);
320
- return unique.length > 0 ? unique.slice(-OUTPUT_PREVIEW_LINE_COUNT) : undefined;
321
- }
322
-
323
- function buildResultNode(result: SingleResult): TreeNode {
324
- const status = statusFromResult(result);
325
- const usage = formatUsage(result.usage, result.model);
326
- const metaParts: string[] = [result.agentSource];
327
- if (usage) metaParts.push(usage);
328
- if (status === "error") {
329
- const errorText = result.errorMessage || result.stderr || result.stopReason;
330
- if (errorText) metaParts.push(truncate(errorText.replace(/\s+/g, " "), 120));
331
- }
332
-
333
- const children = buildNestedChildren(result);
334
- const isRunning = status === "running";
335
- return {
336
- label: result.agent,
337
- status,
338
- meta: metaParts.join(" • "),
339
- task: result.task,
340
- liveActivity: isRunning && result.liveLog?.length > 0 ? result.liveLog : undefined,
341
- outputPreview: !isRunning && children.length === 0 ? buildLeafPreview(result) : undefined,
342
- children,
343
- };
344
- }
345
-
346
- function buildTopLevelNodes(details: SubagentDetails): TreeNode[] {
347
- return details.results.map((result) => buildResultNode(result));
348
- }
349
-
350
- function renderTreeLines(
351
- nodes: TreeNode[],
352
- theme: { fg: ThemeFg },
353
- showOutputPreview: boolean,
354
- depth = 0,
355
- ): string[] {
356
- const lines: string[] = [];
357
-
358
- for (const node of nodes) {
359
- const indent = " ".repeat(depth);
360
- let line = `${indent}${statusEmoji(node.status, theme)} ${theme.fg("accent", node.label)}`;
361
- if (node.meta) line += ` ${theme.fg("dim", node.meta)}`;
362
- lines.push(line);
363
-
364
- if (showOutputPreview && node.outputPreview && node.outputPreview.length > 0) {
365
- for (const outputLine of node.outputPreview) {
366
- lines.push(`${indent} ${theme.fg("toolOutput", outputLine)}`);
367
- }
368
- }
369
-
370
- if (showOutputPreview && node.liveActivity && node.liveActivity.length > 0) {
371
- for (const entry of node.liveActivity) {
372
- lines.push(`${indent} ${formatLiveLogEntry(entry, theme)}`);
373
- }
374
- }
375
-
376
- if (node.children.length > 0) {
377
- lines.push(...renderTreeLines(node.children, theme, false, depth + 1));
378
- }
379
- }
380
-
381
- return lines;
382
- }
383
-
384
- function topLevelSummary(details: SubagentDetails, counts: TreeCounts): string {
385
- // aggregatedUsage includes own agents + all their nested descendants;
386
- // fall back to summing only direct results for old serialised data lacking the field.
387
- const totalUsage = formatUsage(
388
- details.aggregatedUsage ?? aggregateUsage(details.results),
389
- );
390
- const parts = [
391
- `${counts.running} running`,
392
- `${counts.finished}/${counts.total} finished`,
393
- `${counts.success} ok`,
394
- `${counts.error} error`,
395
- ];
396
- if (totalUsage) parts.push(totalUsage);
397
- return parts.join(" • ");
398
- }
399
-
400
- // ---------------------------------------------------------------------------
401
- // renderCall — shown while the tool is being invoked
402
- // ---------------------------------------------------------------------------
403
-
404
- export function renderCall(
405
- args: Record<string, any>,
406
- theme: { fg: ThemeFg; bold: (s: string) => string },
407
- context?: { isPartial?: boolean; isError?: boolean },
408
- ): Text {
409
- const tasks = Array.isArray(args.tasks) ? args.tasks : [];
410
- const count = tasks.length;
411
- const icon = context?.isPartial === false
412
- ? context.isError
413
- ? theme.fg("error", "❌")
414
- : theme.fg("success", "✅")
415
- : theme.fg("warning", "⏳");
416
- let text = `${theme.fg("toolTitle", theme.bold("subagent "))}${theme.fg("accent", `${count} task${count === 1 ? "" : "s"}`)}`;
417
- for (const task of tasks.slice(0, 6)) {
418
- const agent = typeof task?.agent === "string" ? task.agent : "...";
419
- const preview = typeof task?.task === "string" ? ` ${truncate(task.task, 56)}` : "";
420
- text += `\n ${icon} ${theme.fg("accent", agent)}${theme.fg("dim", preview)}`;
421
- }
422
- if (tasks.length > 6) text += `\n ${theme.fg("muted", `... +${tasks.length - 6} more`)}`;
423
- return new Text(text, 0, 0);
424
- }
425
-
426
- // ---------------------------------------------------------------------------
427
- // renderResult — shown after the tool completes / streams updates
428
- // ---------------------------------------------------------------------------
429
-
430
- export function renderResult(
431
- result: { content: Array<{ type: string; text?: string }>; details?: unknown },
432
- _expanded: boolean,
433
- theme: { fg: ThemeFg; bold: (s: string) => string },
434
- ): Container | Text {
435
- const details = result.details as SubagentDetails | undefined;
436
- if (!details || details.results.length === 0) {
437
- const first = result.content[0];
438
- return new Text(first?.type === "text" && first.text ? first.text : "(no output)", 0, 0);
439
- }
440
-
441
- const nodes = buildTopLevelNodes(details);
442
- const counts = countNodes(nodes);
443
- const showOutputPreview = !hasNestedChildren(nodes);
444
- const icon = counts.running > 0
445
- ? theme.fg("warning", "⏳")
446
- : counts.error > 0
447
- ? theme.fg("error", "❌")
448
- : theme.fg("success", "✅");
449
-
450
- const container = new Container();
451
- container.addChild(
452
- new Text(
453
- `${icon} ${theme.fg("toolTitle", theme.bold("subagent tree "))}${theme.fg("dim", topLevelSummary(details, counts))}`,
454
- 0,
455
- 0,
456
- ),
457
- );
458
-
459
- container.addChild(new Spacer(1));
460
- container.addChild(new Text(renderTreeLines(nodes, theme, showOutputPreview).join("\n"), 0, 0));
461
-
462
- return container;
463
- }
1
+ /**
2
+ * TUI rendering for subagent tool calls and results.
3
+ */
4
+
5
+ import * as os from "node:os";
6
+ import { Container, Spacer, Text } from "@mariozechner/pi-tui";
7
+ import {
8
+ type LiveLogEntry,
9
+ type NestedSubagentResult,
10
+ type SingleResult,
11
+ type SubagentDetails,
12
+ type UsageStats,
13
+ aggregateUsage,
14
+ getDisplayItems,
15
+ getFinalOutput,
16
+ getNestedSubagentResults,
17
+ isResultError,
18
+ isSubagentDetails,
19
+ } from "./types.js";
20
+
21
+ const OUTPUT_PREVIEW_LINE_COUNT = 6;
22
+
23
+ let broadcastNumberingActive = false;
24
+
25
+ export function setBroadcastNumberingActive(active: boolean): void {
26
+ broadcastNumberingActive = active;
27
+ }
28
+
29
+ type ThemeFg = (color: string, text: string) => string;
30
+ type NodeStatus = "running" | "success" | "error";
31
+
32
+ interface TreeNode {
33
+ label: string;
34
+ status: NodeStatus;
35
+ meta?: string;
36
+ task?: string;
37
+ outputPreview?: string[];
38
+ liveActivity?: LiveLogEntry[];
39
+ children: TreeNode[];
40
+ }
41
+
42
+
43
+ interface TreeCounts {
44
+ total: number;
45
+ running: number;
46
+ success: number;
47
+ error: number;
48
+ finished: number;
49
+ }
50
+
51
+ interface PendingSubagentCall {
52
+ toolCallId: string;
53
+ tasks: Array<{ agent: string; task?: string }>;
54
+ }
55
+
56
+ // ---------------------------------------------------------------------------
57
+ // Formatting helpers
58
+ // ---------------------------------------------------------------------------
59
+
60
+ function formatTokens(count: number): string {
61
+ if (count < 1000) return count.toString();
62
+ if (count < 10000) return `${(count / 1000).toFixed(1)}k`;
63
+ if (count < 1000000) return `${Math.round(count / 1000)}k`;
64
+ return `${(count / 1000000).toFixed(1)}M`;
65
+ }
66
+
67
+ function formatUsage(usage: Partial<UsageStats>, model?: string): string {
68
+ const parts: string[] = [];
69
+ const totalTokens =
70
+ (usage.input || 0) +
71
+ (usage.output || 0) +
72
+ (usage.cacheRead || 0) +
73
+ (usage.cacheWrite || 0);
74
+ if (usage.turns) parts.push(`${usage.turns} turn${usage.turns > 1 ? "s" : ""}`);
75
+ if (totalTokens > 0) parts.push(`tok:${formatTokens(totalTokens)}`);
76
+ if (usage.input) parts.push(`in:${formatTokens(usage.input)}`);
77
+ if (usage.output) parts.push(`out:${formatTokens(usage.output)}`);
78
+ if (usage.cacheRead) parts.push(`cacheR:${formatTokens(usage.cacheRead)}`);
79
+ if (usage.cacheWrite) parts.push(`cacheW:${formatTokens(usage.cacheWrite)}`);
80
+ if (usage.cost) parts.push(`$${usage.cost.toFixed(4)}`);
81
+ if (usage.contextTokens && usage.contextTokens > 0) parts.push(`ctx:${formatTokens(usage.contextTokens)}`);
82
+ if (model) parts.push(model);
83
+ return parts.join(" • ");
84
+ }
85
+
86
+ function truncate(text: string, maxLen: number): string {
87
+ return text.length > maxLen ? `${text.slice(0, maxLen)}...` : text;
88
+ }
89
+
90
+ function splitOutputLines(text: string): string[] {
91
+ const lines = text.replace(/\r\n?/g, "\n").split("\n");
92
+ if (lines.length > 1 && lines[lines.length - 1] === "") lines.pop();
93
+ return lines;
94
+ }
95
+
96
+ function lastNonEmptyLines(text: string, limit: number): string[] {
97
+ return splitOutputLines(text)
98
+ .map((line) => line.trimEnd())
99
+ .filter((line) => line.trim().length > 0)
100
+ .slice(-limit);
101
+ }
102
+
103
+ function statusEmoji(status: NodeStatus, theme: { fg: ThemeFg }): string {
104
+ switch (status) {
105
+ case "running":
106
+ return theme.fg("warning", "⏳");
107
+ case "error":
108
+ return theme.fg("error", "❌");
109
+ default:
110
+ return theme.fg("success", "✅");
111
+ }
112
+ }
113
+
114
+ function statusFromResult(result: SingleResult): NodeStatus {
115
+ if (result.exitCode === -1) return "running";
116
+ return isResultError(result) ? "error" : "success";
117
+ }
118
+
119
+ function countNodes(nodes: TreeNode[]): TreeCounts {
120
+ const counts: TreeCounts = {
121
+ total: 0,
122
+ running: 0,
123
+ success: 0,
124
+ error: 0,
125
+ finished: 0,
126
+ };
127
+
128
+ const visit = (node: TreeNode) => {
129
+ counts.total++;
130
+ if (node.status === "running") counts.running++;
131
+ if (node.status === "success") counts.success++;
132
+ if (node.status === "error") counts.error++;
133
+ if (node.status !== "running") counts.finished++;
134
+ for (const child of node.children) visit(child);
135
+ };
136
+
137
+ for (const node of nodes) visit(node);
138
+ return counts;
139
+ }
140
+
141
+ function hasNestedChildren(nodes: TreeNode[]): boolean {
142
+ return nodes.some((node) => node.children.length > 0 || hasNestedChildren(node.children));
143
+ }
144
+
145
+ function extractPendingSubagentCalls(messages: SingleResult["messages"]): PendingSubagentCall[] {
146
+ const calls: PendingSubagentCall[] = [];
147
+ for (let messageIndex = 0; messageIndex < messages.length; messageIndex++) {
148
+ const message = messages[messageIndex] as any;
149
+ if (message.role !== "assistant" || !Array.isArray(message.content)) continue;
150
+ for (let partIndex = 0; partIndex < message.content.length; partIndex++) {
151
+ const part = message.content[partIndex] as any;
152
+ if (part?.type !== "toolCall" || part?.name !== "subagent") continue;
153
+ const args = part.arguments && typeof part.arguments === "object" ? part.arguments : {};
154
+ const tasks = Array.isArray((args as any).tasks)
155
+ ? (args as any).tasks
156
+ .filter((task: any) => task && typeof task.agent === "string")
157
+ .map((task: any) => ({
158
+ agent: task.agent,
159
+ task: typeof task.task === "string" ? task.task : undefined,
160
+ }))
161
+ : [];
162
+ calls.push({
163
+ toolCallId:
164
+ typeof part.toolCallId === "string"
165
+ ? part.toolCallId
166
+ : typeof part.id === "string"
167
+ ? part.id
168
+ : `${messageIndex}:${partIndex}`,
169
+ tasks,
170
+ });
171
+ }
172
+ }
173
+ return calls;
174
+ }
175
+
176
+ function buildPendingNodes(call: PendingSubagentCall): TreeNode[] {
177
+ return call.tasks.map((task) => ({
178
+ label: task.agent,
179
+ status: "running",
180
+ task: task.task,
181
+ children: [],
182
+ }));
183
+ }
184
+
185
+ function buildNodesFromNestedResult(nested: NestedSubagentResult): TreeNode[] {
186
+ return nested.details.results.map((result) => buildResultNode(result));
187
+ }
188
+
189
+ function subagentCallSignature(call: PendingSubagentCall): string {
190
+ return JSON.stringify(call.tasks.map((task) => ({ agent: task.agent, task: task.task ?? "" })));
191
+ }
192
+
193
+ function nestedResultIsHealthy(nested: NestedSubagentResult | undefined): boolean {
194
+ if (!nested || nested.isError) return false;
195
+ return nested.details.results.every((result) => !isResultError(result));
196
+ }
197
+
198
+ function buildNestedChildren(result: SingleResult): TreeNode[] {
199
+ const parentIsRunning = result.exitCode === -1;
200
+ const completedByToolCallId = new Map<string, NestedSubagentResult>();
201
+ for (const nested of getNestedSubagentResults(result.messages)) {
202
+ completedByToolCallId.set(nested.toolCallId, nested);
203
+ }
204
+
205
+ const calls = extractPendingSubagentCalls(result.messages);
206
+ const laterResumeBySignature = new Map<string, number>();
207
+ calls.forEach((call, index) => {
208
+ const completed = completedByToolCallId.get(call.toolCallId);
209
+ // A resumed call has the same task signature as the interrupted call but a
210
+ // newer toolCallId. Prefer that newer running/successful tree over the old
211
+ // synthetic/aborted result so resumed nested subagents render in-place.
212
+ if (!completed || nestedResultIsHealthy(completed)) {
213
+ laterResumeBySignature.set(subagentCallSignature(call), index);
214
+ }
215
+ });
216
+
217
+ const nodes: TreeNode[] = [];
218
+ calls.forEach((call, index) => {
219
+ const completed = completedByToolCallId.get(call.toolCallId);
220
+ const newerEquivalent = laterResumeBySignature.get(subagentCallSignature(call));
221
+ if (
222
+ newerEquivalent !== undefined &&
223
+ newerEquivalent > index &&
224
+ (!completed || completed.isError || !nestedResultIsHealthy(completed))
225
+ ) {
226
+ return;
227
+ }
228
+
229
+ if (completed && isSubagentDetails(completed.details)) {
230
+ nodes.push(...buildNodesFromNestedResult(completed));
231
+ return;
232
+ }
233
+ // Unmatched subagent tool calls are useful while the parent is still
234
+ // running (they show live pending children). Once the parent finished,
235
+ // unmatched calls are stale history from an interrupted/resumed session and
236
+ // must not keep the whole tree in a perpetual "running" state.
237
+ if (parentIsRunning) nodes.push(...buildPendingNodes(call));
238
+ });
239
+ return nodes;
240
+ }
241
+
242
+ function formatToolArgPreview(toolName: string, args: Record<string, unknown>): string {
243
+ const shorten = (p: string) => {
244
+ const home = os.homedir();
245
+ return p.startsWith(home) ? `~${p.slice(home.length)}` : p;
246
+ };
247
+ const truncateTo = (s: string, n: number) =>
248
+ s.length > n ? s.slice(0, n) + "\u2026" : s;
249
+
250
+ switch (toolName) {
251
+ case "bash": {
252
+ const cmd = (args.command as string) || "";
253
+ return truncateTo(cmd.replace(/\s+/g, " "), 52);
254
+ }
255
+ case "read":
256
+ case "write":
257
+ case "edit":
258
+ return shorten(truncateTo((args.path ?? args.file_path ?? "") as string, 52));
259
+ case "grep":
260
+ return truncateTo(`/${args.pattern}/`, 30) +
261
+ (args.path ? ` in ${shorten(args.path as string)}` : "");
262
+ case "find":
263
+ return truncateTo((args.pattern ?? "*") as string, 30) +
264
+ (args.path ? ` in ${shorten(args.path as string)}` : "");
265
+ case "subagent": {
266
+ const tasks = (args.tasks as any[]) ?? [];
267
+ return tasks.map((t: any) => t.agent).join(", ");
268
+ }
269
+ default:
270
+ return "";
271
+ }
272
+ }
273
+
274
+ function formatLiveLogEntry(
275
+ entry: LiveLogEntry,
276
+ theme: { fg: ThemeFg },
277
+ ): string {
278
+ switch (entry.kind) {
279
+ case "turn_start":
280
+ return theme.fg("muted", "\u27f3") + " " + theme.fg("dim", "thinking\u2026");
281
+
282
+ case "turn_end": {
283
+ const tokens = entry.inputTokens || entry.outputTokens
284
+ ? " " + theme.fg("dim",
285
+ `\u2191${formatTokens(entry.inputTokens)} \u2193${formatTokens(entry.outputTokens)}`)
286
+ : "";
287
+ return (
288
+ theme.fg("success", "\u2713") +
289
+ " " +
290
+ theme.fg("muted", `turn ${entry.turn}`) +
291
+ tokens
292
+ );
293
+ }
294
+
295
+ case "tool_start": {
296
+ const argPreview = formatToolArgPreview(entry.toolName, entry.args);
297
+ return (
298
+ theme.fg("muted", "\u2192") +
299
+ " " +
300
+ theme.fg("accent", entry.toolName) +
301
+ (argPreview ? " " + theme.fg("dim", argPreview) : "")
302
+ );
303
+ }
304
+
305
+ case "tool_end":
306
+ return (
307
+ theme.fg("success", "\u2713") +
308
+ " " +
309
+ theme.fg("accent", entry.toolName)
310
+ );
311
+ }
312
+ }
313
+
314
+ function buildLeafPreview(result: SingleResult): string[] | undefined {
315
+ const items = getDisplayItems(result.messages);
316
+ const lines: string[] = [];
317
+ for (const item of items) {
318
+ if (item.type === "text") {
319
+ lines.push(...lastNonEmptyLines(item.text, OUTPUT_PREVIEW_LINE_COUNT));
320
+ }
321
+ }
322
+ const finalOutput = getFinalOutput(result.messages);
323
+ if (finalOutput) lines.push(...lastNonEmptyLines(finalOutput, OUTPUT_PREVIEW_LINE_COUNT));
324
+ const unique = lines.filter((line, index) => line && lines.indexOf(line) === index);
325
+ return unique.length > 0 ? unique.slice(-OUTPUT_PREVIEW_LINE_COUNT) : undefined;
326
+ }
327
+
328
+ function buildResultNode(result: SingleResult): TreeNode {
329
+ const status = statusFromResult(result);
330
+ const usage = formatUsage(result.usage, result.model);
331
+ const metaParts: string[] = [result.agentSource];
332
+ if (usage) metaParts.push(usage);
333
+ if (status === "error") {
334
+ const errorText = result.errorMessage || result.stderr || result.stopReason;
335
+ if (errorText) metaParts.push(truncate(errorText.replace(/\s+/g, " "), 120));
336
+ }
337
+
338
+ const children = buildNestedChildren(result);
339
+ const isRunning = status === "running";
340
+ return {
341
+ label: result.agent,
342
+ status,
343
+ meta: metaParts.join(" • "),
344
+ task: result.task,
345
+ liveActivity: isRunning && result.liveLog?.length > 0 ? result.liveLog : undefined,
346
+ outputPreview: !isRunning && children.length === 0 ? buildLeafPreview(result) : undefined,
347
+ children,
348
+ };
349
+ }
350
+
351
+ function buildTopLevelNodes(details: SubagentDetails): TreeNode[] {
352
+ return details.results.map((result) => buildResultNode(result));
353
+ }
354
+
355
+ function renderTreeLines(
356
+ nodes: TreeNode[],
357
+ theme: { fg: ThemeFg },
358
+ showOutputPreview: boolean,
359
+ depth = 0,
360
+ prefix = "",
361
+ ): string[] {
362
+ const lines: string[] = [];
363
+
364
+ nodes.forEach((node, index) => {
365
+ const indent = " ".repeat(depth);
366
+ const number = prefix ? `${prefix}.${index + 1}` : `${index + 1}`;
367
+ const numberPrefix = broadcastNumberingActive ? `${number}. ` : "";
368
+ let line = `${indent}${numberPrefix}${statusEmoji(node.status, theme)} ${theme.fg("accent", node.label)}`;
369
+ if (node.meta) line += ` ${theme.fg("dim", node.meta)}`;
370
+ lines.push(line);
371
+
372
+ if (showOutputPreview && node.outputPreview && node.outputPreview.length > 0) {
373
+ for (const outputLine of node.outputPreview) {
374
+ lines.push(`${indent} ${theme.fg("toolOutput", outputLine)}`);
375
+ }
376
+ }
377
+
378
+ if (showOutputPreview && node.liveActivity && node.liveActivity.length > 0) {
379
+ for (const entry of node.liveActivity) {
380
+ lines.push(`${indent} ${formatLiveLogEntry(entry, theme)}`);
381
+ }
382
+ }
383
+
384
+ if (node.children.length > 0) {
385
+ lines.push(...renderTreeLines(node.children, theme, false, depth + 1, number));
386
+ }
387
+ });
388
+
389
+ return lines;
390
+ }
391
+
392
+ function topLevelSummary(details: SubagentDetails, counts: TreeCounts): string {
393
+ // aggregatedUsage includes own agents + all their nested descendants;
394
+ // fall back to summing only direct results for old serialised data lacking the field.
395
+ const totalUsage = formatUsage(
396
+ details.aggregatedUsage ?? aggregateUsage(details.results),
397
+ );
398
+ const parts = [
399
+ `${counts.running} running`,
400
+ `${counts.finished}/${counts.total} finished`,
401
+ `${counts.success} ok`,
402
+ `${counts.error} error`,
403
+ ];
404
+ if (totalUsage) parts.push(totalUsage);
405
+ return parts.join(" • ");
406
+ }
407
+
408
+ // ---------------------------------------------------------------------------
409
+ // renderCall — shown while the tool is being invoked
410
+ // ---------------------------------------------------------------------------
411
+
412
+ export function renderCall(
413
+ args: Record<string, any>,
414
+ theme: { fg: ThemeFg; bold: (s: string) => string },
415
+ context?: { isPartial?: boolean; isError?: boolean },
416
+ ): Text {
417
+ const tasks = Array.isArray(args.tasks) ? args.tasks : [];
418
+ const count = tasks.length;
419
+ const icon = context?.isPartial === false
420
+ ? context.isError
421
+ ? theme.fg("error", "❌")
422
+ : theme.fg("success", "✅")
423
+ : theme.fg("warning", "⏳");
424
+ let text = `${theme.fg("toolTitle", theme.bold("subagent "))}${theme.fg("accent", `${count} task${count === 1 ? "" : "s"}`)}`;
425
+ for (const task of tasks.slice(0, 6)) {
426
+ const agent = typeof task?.agent === "string" ? task.agent : "...";
427
+ const preview = typeof task?.task === "string" ? ` ${truncate(task.task, 56)}` : "";
428
+ text += `\n ${icon} ${theme.fg("accent", agent)}${theme.fg("dim", preview)}`;
429
+ }
430
+ if (tasks.length > 6) text += `\n ${theme.fg("muted", `... +${tasks.length - 6} more`)}`;
431
+ return new Text(text, 0, 0);
432
+ }
433
+
434
+ // ---------------------------------------------------------------------------
435
+ // renderResult — shown after the tool completes / streams updates
436
+ // ---------------------------------------------------------------------------
437
+
438
+ export function renderResult(
439
+ result: { content: Array<{ type: string; text?: string }>; details?: unknown },
440
+ _expanded: boolean,
441
+ theme: { fg: ThemeFg; bold: (s: string) => string },
442
+ ): Container | Text {
443
+ const details = result.details as SubagentDetails | undefined;
444
+ if (!details || details.results.length === 0) {
445
+ const first = result.content[0];
446
+ return new Text(first?.type === "text" && first.text ? first.text : "(no output)", 0, 0);
447
+ }
448
+
449
+ const nodes = buildTopLevelNodes(details);
450
+ const counts = countNodes(nodes);
451
+ const showOutputPreview = !hasNestedChildren(nodes);
452
+ const icon = counts.running > 0
453
+ ? theme.fg("warning", "⏳")
454
+ : counts.error > 0
455
+ ? theme.fg("error", "❌")
456
+ : theme.fg("success", "✅");
457
+
458
+ const container = new Container();
459
+ container.addChild(
460
+ new Text(
461
+ `${icon} ${theme.fg("toolTitle", theme.bold("subagent tree "))}${theme.fg("dim", topLevelSummary(details, counts))}`,
462
+ 0,
463
+ 0,
464
+ ),
465
+ );
466
+
467
+ container.addChild(new Spacer(1));
468
+ container.addChild(new Text(renderTreeLines(nodes, theme, showOutputPreview).join("\n"), 0, 0));
469
+
470
+ return container;
471
+ }