@narumitw/pi-subagents 0.1.10

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.
@@ -0,0 +1,1197 @@
1
+ /**
2
+ * Subagent Tool - Delegate tasks to specialized agents
3
+ *
4
+ * Spawns a separate `pi` process for each subagent invocation,
5
+ * giving it an isolated context window.
6
+ *
7
+ * Supports three modes:
8
+ * - Single: { agent: "name", task: "..." }
9
+ * - Parallel: { tasks: [{ agent: "name", task: "..." }, ...] }
10
+ * - Chain: { chain: [{ agent: "name", task: "... {previous} ..." }, ...] }
11
+ *
12
+ * Uses JSON mode to capture structured output from subagents.
13
+ */
14
+
15
+ import { spawn } from "node:child_process";
16
+ import * as fs from "node:fs";
17
+ import * as os from "node:os";
18
+ import * as path from "node:path";
19
+ import type { AgentToolResult } from "@mariozechner/pi-agent-core";
20
+ import type { Message } from "@mariozechner/pi-ai";
21
+ import { StringEnum } from "@mariozechner/pi-ai";
22
+ import { type ExtensionAPI, getMarkdownTheme, withFileMutationQueue } from "@mariozechner/pi-coding-agent";
23
+ import { Container, Markdown, Spacer, Text } from "@mariozechner/pi-tui";
24
+ import { Type } from "typebox";
25
+ import { type AgentConfig, type AgentScope, type AgentSource, discoverAgents } from "./agents.js";
26
+
27
+ const MAX_PARALLEL_TASKS = 8;
28
+ const MAX_CONCURRENCY = 4;
29
+ const COLLAPSED_ITEM_COUNT = 10;
30
+ const DEFAULT_TIMEOUT_MS = parsePositiveInteger(process.env.PI_SUBAGENT_TIMEOUT_MS) ?? 10 * 60 * 1000;
31
+ const KILL_GRACE_MS = 5000;
32
+
33
+ function parsePositiveInteger(value: string | undefined): number | undefined {
34
+ if (!value) return undefined;
35
+ const parsed = Number.parseInt(value, 10);
36
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;
37
+ }
38
+
39
+ function formatTokens(count: number): string {
40
+ if (count < 1000) return count.toString();
41
+ if (count < 10000) return `${(count / 1000).toFixed(1)}k`;
42
+ if (count < 1000000) return `${Math.round(count / 1000)}k`;
43
+ return `${(count / 1000000).toFixed(1)}M`;
44
+ }
45
+
46
+ function formatUsageStats(
47
+ usage: {
48
+ input: number;
49
+ output: number;
50
+ cacheRead: number;
51
+ cacheWrite: number;
52
+ cost: number;
53
+ contextTokens?: number;
54
+ turns?: number;
55
+ },
56
+ model?: string,
57
+ ): string {
58
+ const parts: string[] = [];
59
+ if (usage.turns) parts.push(`${usage.turns} turn${usage.turns > 1 ? "s" : ""}`);
60
+ if (usage.input) parts.push(`↑${formatTokens(usage.input)}`);
61
+ if (usage.output) parts.push(`↓${formatTokens(usage.output)}`);
62
+ if (usage.cacheRead) parts.push(`R${formatTokens(usage.cacheRead)}`);
63
+ if (usage.cacheWrite) parts.push(`W${formatTokens(usage.cacheWrite)}`);
64
+ if (usage.cost) parts.push(`$${usage.cost.toFixed(4)}`);
65
+ if (usage.contextTokens && usage.contextTokens > 0) {
66
+ parts.push(`ctx:${formatTokens(usage.contextTokens)}`);
67
+ }
68
+ if (model) parts.push(model);
69
+ return parts.join(" ");
70
+ }
71
+
72
+ function formatToolCall(
73
+ toolName: string,
74
+ args: Record<string, unknown>,
75
+ themeFg: (color: any, text: string) => string,
76
+ ): string {
77
+ const shortenPath = (p: string) => {
78
+ const home = os.homedir();
79
+ return p.startsWith(home) ? `~${p.slice(home.length)}` : p;
80
+ };
81
+
82
+ switch (toolName) {
83
+ case "bash": {
84
+ const command = (args.command as string) || "...";
85
+ const preview = command.length > 60 ? `${command.slice(0, 60)}...` : command;
86
+ return themeFg("muted", "$ ") + themeFg("toolOutput", preview);
87
+ }
88
+ case "read": {
89
+ const rawPath = (args.file_path || args.path || "...") as string;
90
+ const filePath = shortenPath(rawPath);
91
+ const offset = args.offset as number | undefined;
92
+ const limit = args.limit as number | undefined;
93
+ let text = themeFg("accent", filePath);
94
+ if (offset !== undefined || limit !== undefined) {
95
+ const startLine = offset ?? 1;
96
+ const endLine = limit !== undefined ? startLine + limit - 1 : "";
97
+ text += themeFg("warning", `:${startLine}${endLine ? `-${endLine}` : ""}`);
98
+ }
99
+ return themeFg("muted", "read ") + text;
100
+ }
101
+ case "write": {
102
+ const rawPath = (args.file_path || args.path || "...") as string;
103
+ const filePath = shortenPath(rawPath);
104
+ const content = (args.content || "") as string;
105
+ const lines = content.split("\n").length;
106
+ let text = themeFg("muted", "write ") + themeFg("accent", filePath);
107
+ if (lines > 1) text += themeFg("dim", ` (${lines} lines)`);
108
+ return text;
109
+ }
110
+ case "edit": {
111
+ const rawPath = (args.file_path || args.path || "...") as string;
112
+ return themeFg("muted", "edit ") + themeFg("accent", shortenPath(rawPath));
113
+ }
114
+ case "ls": {
115
+ const rawPath = (args.path || ".") as string;
116
+ return themeFg("muted", "ls ") + themeFg("accent", shortenPath(rawPath));
117
+ }
118
+ case "find": {
119
+ const pattern = (args.pattern || "*") as string;
120
+ const rawPath = (args.path || ".") as string;
121
+ return themeFg("muted", "find ") + themeFg("accent", pattern) + themeFg("dim", ` in ${shortenPath(rawPath)}`);
122
+ }
123
+ case "grep": {
124
+ const pattern = (args.pattern || "") as string;
125
+ const rawPath = (args.path || ".") as string;
126
+ return (
127
+ themeFg("muted", "grep ") +
128
+ themeFg("accent", `/${pattern}/`) +
129
+ themeFg("dim", ` in ${shortenPath(rawPath)}`)
130
+ );
131
+ }
132
+ default: {
133
+ const argsStr = JSON.stringify(args);
134
+ const preview = argsStr.length > 50 ? `${argsStr.slice(0, 50)}...` : argsStr;
135
+ return themeFg("accent", toolName) + themeFg("dim", ` ${preview}`);
136
+ }
137
+ }
138
+ }
139
+
140
+ interface UsageStats {
141
+ input: number;
142
+ output: number;
143
+ cacheRead: number;
144
+ cacheWrite: number;
145
+ cost: number;
146
+ contextTokens: number;
147
+ turns: number;
148
+ }
149
+
150
+ interface SingleResult {
151
+ agent: string;
152
+ agentSource: AgentSource | "unknown";
153
+ task: string;
154
+ exitCode: number;
155
+ messages: Message[];
156
+ stderr: string;
157
+ usage: UsageStats;
158
+ model?: string;
159
+ stopReason?: string;
160
+ errorMessage?: string;
161
+ step?: number;
162
+ finalOutput?: string;
163
+ timedOut?: boolean;
164
+ timeoutMs?: number;
165
+ }
166
+
167
+ interface SubagentDetails {
168
+ mode: "single" | "parallel" | "chain";
169
+ agentScope: AgentScope;
170
+ projectAgentsDir: string | null;
171
+ results: SingleResult[];
172
+ aggregator?: SingleResult;
173
+ }
174
+
175
+ function getFinalOutput(messages: Message[]): string {
176
+ for (let i = messages.length - 1; i >= 0; i--) {
177
+ const msg = messages[i];
178
+ if (msg.role === "assistant") {
179
+ for (const part of msg.content) {
180
+ if (part.type === "text") return part.text;
181
+ }
182
+ }
183
+ }
184
+ return "";
185
+ }
186
+
187
+ function getResultFinalOutput(result: SingleResult): string {
188
+ return result.finalOutput ?? getFinalOutput(result.messages);
189
+ }
190
+
191
+ function buildFanInContext(results: SingleResult[]): string {
192
+ return results
193
+ .map((result, index) => {
194
+ const status = result.exitCode === 0 ? "completed" : result.exitCode === -1 ? "running" : "failed";
195
+ const output = getResultFinalOutput(result);
196
+ const error = result.errorMessage || result.stderr.trim();
197
+ return [
198
+ `## Result ${index + 1}: ${result.agent} (${status})`,
199
+ `Task: ${result.task}`,
200
+ output ? `Output:\n${output}` : error ? `Error:\n${error}` : "Output: (no output)",
201
+ ].join("\n\n");
202
+ })
203
+ .join("\n\n---\n\n");
204
+ }
205
+
206
+ type DisplayItem = { type: "text"; text: string } | { type: "toolCall"; name: string; args: Record<string, any> };
207
+
208
+ function getDisplayItems(messages: Message[]): DisplayItem[] {
209
+ const items: DisplayItem[] = [];
210
+ for (const msg of messages) {
211
+ if (msg.role === "assistant") {
212
+ for (const part of msg.content) {
213
+ if (part.type === "text") items.push({ type: "text", text: part.text });
214
+ else if (part.type === "toolCall") items.push({ type: "toolCall", name: part.name, args: part.arguments });
215
+ }
216
+ }
217
+ }
218
+ return items;
219
+ }
220
+
221
+ async function mapWithConcurrencyLimit<TIn, TOut>(
222
+ items: TIn[],
223
+ concurrency: number,
224
+ fn: (item: TIn, index: number) => Promise<TOut>,
225
+ ): Promise<TOut[]> {
226
+ if (items.length === 0) return [];
227
+ const limit = Math.max(1, Math.min(concurrency, items.length));
228
+ const results: TOut[] = new Array(items.length);
229
+ let nextIndex = 0;
230
+ const workers = new Array(limit).fill(null).map(async () => {
231
+ while (true) {
232
+ const current = nextIndex++;
233
+ if (current >= items.length) return;
234
+ results[current] = await fn(items[current], current);
235
+ }
236
+ });
237
+ await Promise.all(workers);
238
+ return results;
239
+ }
240
+
241
+ async function writePromptToTempFile(agentName: string, prompt: string): Promise<{ dir: string; filePath: string }> {
242
+ const tmpDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "pi-subagent-"));
243
+ const safeName = agentName.replace(/[^\w.-]+/g, "_");
244
+ const filePath = path.join(tmpDir, `prompt-${safeName}.md`);
245
+ await withFileMutationQueue(filePath, async () => {
246
+ await fs.promises.writeFile(filePath, prompt, { encoding: "utf-8", mode: 0o600 });
247
+ });
248
+ return { dir: tmpDir, filePath };
249
+ }
250
+
251
+ function getPiInvocation(args: string[]): { command: string; args: string[] } {
252
+ const currentScript = process.argv[1];
253
+ const isBunVirtualScript = currentScript?.startsWith("/$bunfs/root/");
254
+ if (currentScript && !isBunVirtualScript && fs.existsSync(currentScript)) {
255
+ return { command: process.execPath, args: [currentScript, ...args] };
256
+ }
257
+
258
+ const execName = path.basename(process.execPath).toLowerCase();
259
+ const isGenericRuntime = /^(node|bun)(\.exe)?$/.test(execName);
260
+ if (!isGenericRuntime) {
261
+ return { command: process.execPath, args };
262
+ }
263
+
264
+ return { command: "pi", args };
265
+ }
266
+
267
+ function terminateProcess(proc: ReturnType<typeof spawn>) {
268
+ if (proc.killed) return;
269
+ if (process.platform !== "win32" && proc.pid) {
270
+ try {
271
+ process.kill(-proc.pid, "SIGTERM");
272
+ } catch {
273
+ proc.kill("SIGTERM");
274
+ }
275
+ } else {
276
+ proc.kill("SIGTERM");
277
+ }
278
+
279
+ setTimeout(() => {
280
+ if (proc.killed) return;
281
+ if (process.platform !== "win32" && proc.pid) {
282
+ try {
283
+ process.kill(-proc.pid, "SIGKILL");
284
+ } catch {
285
+ proc.kill("SIGKILL");
286
+ }
287
+ } else {
288
+ proc.kill("SIGKILL");
289
+ }
290
+ }, KILL_GRACE_MS).unref();
291
+ }
292
+
293
+ type OnUpdateCallback = (partial: AgentToolResult<SubagentDetails>) => void;
294
+
295
+ async function runSingleAgent(
296
+ defaultCwd: string,
297
+ agents: AgentConfig[],
298
+ agentName: string,
299
+ task: string,
300
+ cwd: string | undefined,
301
+ step: number | undefined,
302
+ signal: AbortSignal | undefined,
303
+ timeoutMs: number,
304
+ onUpdate: OnUpdateCallback | undefined,
305
+ makeDetails: (results: SingleResult[]) => SubagentDetails,
306
+ ): Promise<SingleResult> {
307
+ const agent = agents.find((a) => a.name === agentName);
308
+
309
+ if (!agent) {
310
+ const available = agents.map((a) => `"${a.name}"`).join(", ") || "none";
311
+ return {
312
+ agent: agentName,
313
+ agentSource: "unknown",
314
+ task,
315
+ exitCode: 1,
316
+ messages: [],
317
+ stderr: `Unknown agent: "${agentName}". Available agents: ${available}.`,
318
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 },
319
+ step,
320
+ finalOutput: "",
321
+ };
322
+ }
323
+
324
+ const args: string[] = ["--mode", "json", "-p", "--no-session"];
325
+ if (agent.model) args.push("--model", agent.model);
326
+ if (agent.tools && agent.tools.length > 0) args.push("--tools", agent.tools.join(","));
327
+
328
+ let tmpPromptDir: string | null = null;
329
+ let tmpPromptPath: string | null = null;
330
+
331
+ const currentResult: SingleResult = {
332
+ agent: agentName,
333
+ agentSource: agent.source,
334
+ task,
335
+ exitCode: 0,
336
+ messages: [],
337
+ stderr: "",
338
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 },
339
+ model: agent.model,
340
+ step,
341
+ timeoutMs,
342
+ };
343
+
344
+ const emitUpdate = () => {
345
+ currentResult.finalOutput = getFinalOutput(currentResult.messages);
346
+ if (onUpdate) {
347
+ onUpdate({
348
+ content: [{ type: "text", text: currentResult.finalOutput || "(running...)" }],
349
+ details: makeDetails([currentResult]),
350
+ });
351
+ }
352
+ };
353
+
354
+ try {
355
+ if (agent.systemPrompt.trim()) {
356
+ const tmp = await writePromptToTempFile(agent.name, agent.systemPrompt);
357
+ tmpPromptDir = tmp.dir;
358
+ tmpPromptPath = tmp.filePath;
359
+ args.push("--append-system-prompt", tmpPromptPath);
360
+ }
361
+
362
+ args.push(`Task: ${task}`);
363
+ let wasAborted = false;
364
+ let timedOut = false;
365
+
366
+ const exitCode = await new Promise<number>((resolve) => {
367
+ const invocation = getPiInvocation(args);
368
+ let settled = false;
369
+ const finish = (code: number) => {
370
+ if (settled) return;
371
+ settled = true;
372
+ clearTimeout(timeout);
373
+ resolve(code);
374
+ };
375
+ const proc = spawn(invocation.command, invocation.args, {
376
+ cwd: cwd ?? defaultCwd,
377
+ detached: process.platform !== "win32",
378
+ shell: false,
379
+ stdio: ["ignore", "pipe", "pipe"],
380
+ });
381
+ let buffer = "";
382
+ const timeout = setTimeout(() => {
383
+ timedOut = true;
384
+ currentResult.timedOut = true;
385
+ currentResult.stopReason = "timeout";
386
+ currentResult.errorMessage = `Subagent timed out after ${timeoutMs}ms`;
387
+ currentResult.stderr += `${currentResult.stderr ? "\n" : ""}Subagent timed out after ${timeoutMs}ms.`;
388
+ emitUpdate();
389
+ terminateProcess(proc);
390
+ }, timeoutMs);
391
+ timeout.unref();
392
+
393
+ const processLine = (line: string) => {
394
+ if (!line.trim()) return;
395
+ let event: any;
396
+ try {
397
+ event = JSON.parse(line);
398
+ } catch {
399
+ return;
400
+ }
401
+
402
+ if (event.type === "message_end" && event.message) {
403
+ const msg = event.message as Message;
404
+ currentResult.messages.push(msg);
405
+
406
+ if (msg.role === "assistant") {
407
+ currentResult.usage.turns++;
408
+ const usage = msg.usage;
409
+ if (usage) {
410
+ currentResult.usage.input += usage.input || 0;
411
+ currentResult.usage.output += usage.output || 0;
412
+ currentResult.usage.cacheRead += usage.cacheRead || 0;
413
+ currentResult.usage.cacheWrite += usage.cacheWrite || 0;
414
+ currentResult.usage.cost += usage.cost?.total || 0;
415
+ currentResult.usage.contextTokens = usage.totalTokens || 0;
416
+ }
417
+ if (!currentResult.model && msg.model) currentResult.model = msg.model;
418
+ if (msg.stopReason) currentResult.stopReason = msg.stopReason;
419
+ if (msg.errorMessage) currentResult.errorMessage = msg.errorMessage;
420
+ }
421
+ emitUpdate();
422
+ }
423
+
424
+ if (event.type === "tool_result_end" && event.message) {
425
+ currentResult.messages.push(event.message as Message);
426
+ emitUpdate();
427
+ }
428
+ };
429
+
430
+ proc.stdout.on("data", (data) => {
431
+ buffer += data.toString();
432
+ const lines = buffer.split("\n");
433
+ buffer = lines.pop() || "";
434
+ for (const line of lines) processLine(line);
435
+ });
436
+
437
+ proc.stderr.on("data", (data) => {
438
+ currentResult.stderr += data.toString();
439
+ });
440
+
441
+ proc.on("close", (code) => {
442
+ if (buffer.trim()) processLine(buffer);
443
+ finish(timedOut ? 124 : (code ?? 0));
444
+ });
445
+
446
+ proc.on("error", (error) => {
447
+ currentResult.errorMessage = error.message;
448
+ currentResult.stderr += `${currentResult.stderr ? "\n" : ""}${error.message}`;
449
+ finish(1);
450
+ });
451
+
452
+ if (signal) {
453
+ const killProc = () => {
454
+ wasAborted = true;
455
+ currentResult.stopReason = "aborted";
456
+ currentResult.errorMessage = "Subagent was aborted";
457
+ terminateProcess(proc);
458
+ };
459
+ if (signal.aborted) killProc();
460
+ else signal.addEventListener("abort", killProc, { once: true });
461
+ }
462
+ });
463
+
464
+ currentResult.exitCode = exitCode;
465
+ currentResult.finalOutput = getFinalOutput(currentResult.messages);
466
+ if (wasAborted && !timedOut) throw new Error("Subagent was aborted");
467
+ return currentResult;
468
+ } finally {
469
+ if (tmpPromptPath)
470
+ try {
471
+ fs.unlinkSync(tmpPromptPath);
472
+ } catch {
473
+ /* ignore */
474
+ }
475
+ if (tmpPromptDir)
476
+ try {
477
+ fs.rmdirSync(tmpPromptDir);
478
+ } catch {
479
+ /* ignore */
480
+ }
481
+ }
482
+ }
483
+
484
+ const TimeoutMs = Type.Number({
485
+ description:
486
+ "Hard timeout in milliseconds for each subagent subprocess. Defaults to PI_SUBAGENT_TIMEOUT_MS or 600000.",
487
+ minimum: 1,
488
+ });
489
+
490
+ const TaskItem = Type.Object({
491
+ agent: Type.String({ description: "Name of the agent to invoke" }),
492
+ task: Type.String({ description: "Task to delegate to the agent" }),
493
+ cwd: Type.Optional(Type.String({ description: "Working directory for the agent process" })),
494
+ timeoutMs: Type.Optional(TimeoutMs),
495
+ });
496
+
497
+ const ChainItem = Type.Object({
498
+ agent: Type.String({ description: "Name of the agent to invoke" }),
499
+ task: Type.String({ description: "Task with optional {previous} placeholder for prior output" }),
500
+ cwd: Type.Optional(Type.String({ description: "Working directory for the agent process" })),
501
+ timeoutMs: Type.Optional(TimeoutMs),
502
+ });
503
+
504
+ const AggregatorItem = Type.Object({
505
+ agent: Type.String({ description: "Name of the fan-in agent to invoke after parallel tasks complete" }),
506
+ task: Type.String({ description: "Fan-in task. Use {previous} to include all parallel outputs." }),
507
+ cwd: Type.Optional(Type.String({ description: "Working directory for the aggregator process" })),
508
+ timeoutMs: Type.Optional(TimeoutMs),
509
+ });
510
+
511
+ const AgentScopeSchema = StringEnum(["user", "project", "both"] as const, {
512
+ description: 'Which agent directories to use. Default: "user". Use "both" to include project-local agents.',
513
+ default: "user",
514
+ });
515
+
516
+ const SubagentParams = Type.Object({
517
+ agent: Type.Optional(Type.String({ description: "Name of the agent to invoke (for single mode)" })),
518
+ task: Type.Optional(Type.String({ description: "Task to delegate (for single mode)" })),
519
+ tasks: Type.Optional(Type.Array(TaskItem, { description: "Array of {agent, task} for parallel execution" })),
520
+ chain: Type.Optional(Type.Array(ChainItem, { description: "Array of {agent, task} for sequential execution" })),
521
+ aggregator: Type.Optional(AggregatorItem),
522
+ agentScope: Type.Optional(AgentScopeSchema),
523
+ confirmProjectAgents: Type.Optional(
524
+ Type.Boolean({ description: "Prompt before running project-local agents. Default: true.", default: true }),
525
+ ),
526
+ cwd: Type.Optional(Type.String({ description: "Working directory for the agent process (single mode)" })),
527
+ timeoutMs: Type.Optional(TimeoutMs),
528
+ });
529
+
530
+ export default function (pi: ExtensionAPI) {
531
+ pi.registerTool({
532
+ name: "subagent",
533
+ label: "Subagent",
534
+ description: [
535
+ "Delegate tasks to specialized subagents with isolated context.",
536
+ "Modes: single (agent + task), parallel (tasks array), chain (sequential with {previous} placeholder).",
537
+ "Parallel mode may include an aggregator fan-in step that receives all task outputs.",
538
+ 'Default agent scope is "user" (from ~/.pi/agent/agents).',
539
+ 'To enable project-local agents in .pi/agents, set agentScope: "both" (or "project").',
540
+ ].join(" "),
541
+ parameters: SubagentParams,
542
+
543
+ async execute(_toolCallId, params, signal, onUpdate, ctx) {
544
+ const agentScope: AgentScope = params.agentScope ?? "user";
545
+ const discovery = discoverAgents(ctx.cwd, agentScope);
546
+ const agents = discovery.agents;
547
+ const confirmProjectAgents = params.confirmProjectAgents ?? true;
548
+ const defaultTimeoutMs = params.timeoutMs ?? DEFAULT_TIMEOUT_MS;
549
+
550
+ const hasChain = (params.chain?.length ?? 0) > 0;
551
+ const hasTasks = (params.tasks?.length ?? 0) > 0;
552
+ const hasSingle = Boolean(params.agent && params.task);
553
+ const modeCount = Number(hasChain) + Number(hasTasks) + Number(hasSingle);
554
+
555
+ const makeDetails =
556
+ (mode: "single" | "parallel" | "chain") =>
557
+ (results: SingleResult[], aggregator?: SingleResult): SubagentDetails => ({
558
+ mode,
559
+ agentScope,
560
+ projectAgentsDir: discovery.projectAgentsDir,
561
+ results,
562
+ aggregator,
563
+ });
564
+
565
+ if (modeCount !== 1 || (params.aggregator && !hasTasks)) {
566
+ const available = agents.map((a) => `${a.name} (${a.source})`).join(", ") || "none";
567
+ const reason =
568
+ modeCount !== 1
569
+ ? "Provide exactly one mode."
570
+ : "Aggregator is only valid with parallel tasks.";
571
+ return {
572
+ content: [
573
+ {
574
+ type: "text",
575
+ text: `Invalid parameters. ${reason}\nAvailable agents: ${available}`,
576
+ },
577
+ ],
578
+ details: makeDetails("single")([]),
579
+ };
580
+ }
581
+
582
+ if ((agentScope === "project" || agentScope === "both") && confirmProjectAgents && ctx.hasUI) {
583
+ const requestedAgentNames = new Set<string>();
584
+ if (params.chain) for (const step of params.chain) requestedAgentNames.add(step.agent);
585
+ if (params.tasks) for (const t of params.tasks) requestedAgentNames.add(t.agent);
586
+ if (params.aggregator) requestedAgentNames.add(params.aggregator.agent);
587
+ if (params.agent) requestedAgentNames.add(params.agent);
588
+
589
+ const projectAgentsRequested = Array.from(requestedAgentNames)
590
+ .map((name) => agents.find((a) => a.name === name))
591
+ .filter((a): a is AgentConfig => a?.source === "project");
592
+
593
+ if (projectAgentsRequested.length > 0) {
594
+ const names = projectAgentsRequested.map((a) => a.name).join(", ");
595
+ const dir = discovery.projectAgentsDir ?? "(unknown)";
596
+ const ok = await ctx.ui.confirm(
597
+ "Run project-local agents?",
598
+ `Agents: ${names}\nSource: ${dir}\n\nProject agents are repo-controlled. Only continue for trusted repositories.`,
599
+ );
600
+ if (!ok)
601
+ return {
602
+ content: [{ type: "text", text: "Canceled: project-local agents not approved." }],
603
+ details: makeDetails(hasChain ? "chain" : hasTasks ? "parallel" : "single")([]),
604
+ };
605
+ }
606
+ }
607
+
608
+ if (params.chain && params.chain.length > 0) {
609
+ const results: SingleResult[] = [];
610
+ let previousOutput = "";
611
+
612
+ for (let i = 0; i < params.chain.length; i++) {
613
+ const step = params.chain[i];
614
+ const taskWithContext = step.task.replace(/\{previous\}/g, previousOutput);
615
+
616
+ // Create update callback that includes all previous results
617
+ const chainUpdate: OnUpdateCallback | undefined = onUpdate
618
+ ? (partial) => {
619
+ // Combine completed results with current streaming result
620
+ const currentResult = partial.details?.results[0];
621
+ if (currentResult) {
622
+ const allResults = [...results, currentResult];
623
+ onUpdate({
624
+ content: partial.content,
625
+ details: makeDetails("chain")(allResults),
626
+ });
627
+ }
628
+ }
629
+ : undefined;
630
+
631
+ const result = await runSingleAgent(
632
+ ctx.cwd,
633
+ agents,
634
+ step.agent,
635
+ taskWithContext,
636
+ step.cwd,
637
+ i + 1,
638
+ signal,
639
+ step.timeoutMs ?? defaultTimeoutMs,
640
+ chainUpdate,
641
+ makeDetails("chain"),
642
+ );
643
+ results.push(result);
644
+
645
+ const isError =
646
+ result.exitCode !== 0 || result.stopReason === "error" || result.stopReason === "aborted";
647
+ if (isError) {
648
+ const errorMsg = result.errorMessage || result.stderr || getResultFinalOutput(result) || "(no output)";
649
+ return {
650
+ content: [{ type: "text", text: `Chain stopped at step ${i + 1} (${step.agent}): ${errorMsg}` }],
651
+ details: makeDetails("chain")(results),
652
+ isError: true,
653
+ };
654
+ }
655
+ previousOutput = getResultFinalOutput(result);
656
+ }
657
+ return {
658
+ content: [{ type: "text", text: getResultFinalOutput(results[results.length - 1]) || "(no output)" }],
659
+ details: makeDetails("chain")(results),
660
+ };
661
+ }
662
+
663
+ if (params.tasks && params.tasks.length > 0) {
664
+ if (params.tasks.length > MAX_PARALLEL_TASKS)
665
+ return {
666
+ content: [
667
+ {
668
+ type: "text",
669
+ text: `Too many parallel tasks (${params.tasks.length}). Max is ${MAX_PARALLEL_TASKS}.`,
670
+ },
671
+ ],
672
+ details: makeDetails("parallel")([]),
673
+ };
674
+
675
+ // Track all results for streaming updates
676
+ const allResults: SingleResult[] = new Array(params.tasks.length);
677
+
678
+ // Initialize placeholder results
679
+ for (let i = 0; i < params.tasks.length; i++) {
680
+ allResults[i] = {
681
+ agent: params.tasks[i].agent,
682
+ agentSource: "unknown",
683
+ task: params.tasks[i].task,
684
+ exitCode: -1, // -1 = still running
685
+ messages: [],
686
+ stderr: "",
687
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 },
688
+ finalOutput: "",
689
+ };
690
+ }
691
+
692
+ const emitParallelUpdate = () => {
693
+ if (onUpdate) {
694
+ const running = allResults.filter((r) => r.exitCode === -1).length;
695
+ const done = allResults.filter((r) => r.exitCode !== -1).length;
696
+ onUpdate({
697
+ content: [
698
+ { type: "text", text: `Parallel: ${done}/${allResults.length} done, ${running} running...` },
699
+ ],
700
+ details: makeDetails("parallel")([...allResults]),
701
+ });
702
+ }
703
+ };
704
+
705
+ const results = await mapWithConcurrencyLimit(params.tasks, MAX_CONCURRENCY, async (t, index) => {
706
+ const result = await runSingleAgent(
707
+ ctx.cwd,
708
+ agents,
709
+ t.agent,
710
+ t.task,
711
+ t.cwd,
712
+ undefined,
713
+ signal,
714
+ t.timeoutMs ?? defaultTimeoutMs,
715
+ // Per-task update callback
716
+ (partial) => {
717
+ if (partial.details?.results[0]) {
718
+ allResults[index] = partial.details.results[0];
719
+ emitParallelUpdate();
720
+ }
721
+ },
722
+ makeDetails("parallel"),
723
+ );
724
+ allResults[index] = result;
725
+ emitParallelUpdate();
726
+ return result;
727
+ });
728
+
729
+ let aggregatorResult: SingleResult | undefined;
730
+ if (params.aggregator) {
731
+ const fanInContext = buildFanInContext(results);
732
+ const aggregatorTask = params.aggregator.task.includes("{previous}")
733
+ ? params.aggregator.task.replace(/\{previous\}/g, fanInContext)
734
+ : `${params.aggregator.task}\n\nParallel task outputs:\n\n${fanInContext}`;
735
+ aggregatorResult = await runSingleAgent(
736
+ ctx.cwd,
737
+ agents,
738
+ params.aggregator.agent,
739
+ aggregatorTask,
740
+ params.aggregator.cwd,
741
+ undefined,
742
+ signal,
743
+ params.aggregator.timeoutMs ?? defaultTimeoutMs,
744
+ (partial) => {
745
+ if (onUpdate && partial.details?.results[0]) {
746
+ onUpdate({
747
+ content: partial.content,
748
+ details: makeDetails("parallel")(results, partial.details.results[0]),
749
+ });
750
+ }
751
+ },
752
+ makeDetails("parallel"),
753
+ );
754
+ }
755
+
756
+ const successCount = results.filter((r) => r.exitCode === 0).length;
757
+ const summaries = results.map((r) => {
758
+ const output = getResultFinalOutput(r);
759
+ const error = r.errorMessage || r.stderr.trim();
760
+ const summaryText = output || error;
761
+ const preview = summaryText.slice(0, 160) + (summaryText.length > 160 ? "..." : "");
762
+ return `[${r.agent}] ${r.exitCode === 0 ? "completed" : "failed"}: ${preview || "(no output)"}`;
763
+ });
764
+ const aggregatorOutput = aggregatorResult ? getResultFinalOutput(aggregatorResult) : "";
765
+ const aggregatorError = aggregatorResult?.errorMessage || aggregatorResult?.stderr.trim() || "";
766
+ return {
767
+ content: [
768
+ {
769
+ type: "text",
770
+ text: aggregatorResult
771
+ ? aggregatorOutput || aggregatorError || `(aggregator ${aggregatorResult.agent} produced no output)`
772
+ : `Parallel: ${successCount}/${results.length} succeeded\n\n${summaries.join("\n\n")}`,
773
+ },
774
+ ],
775
+ details: makeDetails("parallel")(results, aggregatorResult),
776
+ isError: aggregatorResult
777
+ ? aggregatorResult.exitCode !== 0 ||
778
+ aggregatorResult.stopReason === "error" ||
779
+ aggregatorResult.stopReason === "aborted"
780
+ : undefined,
781
+ };
782
+ }
783
+
784
+ if (params.agent && params.task) {
785
+ const result = await runSingleAgent(
786
+ ctx.cwd,
787
+ agents,
788
+ params.agent,
789
+ params.task,
790
+ params.cwd,
791
+ undefined,
792
+ signal,
793
+ params.timeoutMs ?? defaultTimeoutMs,
794
+ onUpdate,
795
+ makeDetails("single"),
796
+ );
797
+ const isError = result.exitCode !== 0 || result.stopReason === "error" || result.stopReason === "aborted";
798
+ if (isError) {
799
+ const errorMsg = result.errorMessage || result.stderr || getResultFinalOutput(result) || "(no output)";
800
+ return {
801
+ content: [{ type: "text", text: `Agent ${result.stopReason || "failed"}: ${errorMsg}` }],
802
+ details: makeDetails("single")([result]),
803
+ isError: true,
804
+ };
805
+ }
806
+ return {
807
+ content: [{ type: "text", text: getResultFinalOutput(result) || "(no output)" }],
808
+ details: makeDetails("single")([result]),
809
+ };
810
+ }
811
+
812
+ const available = agents.map((a) => `${a.name} (${a.source})`).join(", ") || "none";
813
+ return {
814
+ content: [{ type: "text", text: `Invalid parameters. Available agents: ${available}` }],
815
+ details: makeDetails("single")([]),
816
+ };
817
+ },
818
+
819
+ renderCall(args, theme, _context) {
820
+ const scope: AgentScope = args.agentScope ?? "user";
821
+ if (args.chain && args.chain.length > 0) {
822
+ let text =
823
+ theme.fg("toolTitle", theme.bold("subagent ")) +
824
+ theme.fg("accent", `chain (${args.chain.length} steps)`) +
825
+ theme.fg("muted", ` [${scope}]`);
826
+ for (let i = 0; i < Math.min(args.chain.length, 3); i++) {
827
+ const step = args.chain[i];
828
+ // Clean up {previous} placeholder for display
829
+ const cleanTask = step.task.replace(/\{previous\}/g, "").trim();
830
+ const preview = cleanTask.length > 40 ? `${cleanTask.slice(0, 40)}...` : cleanTask;
831
+ text +=
832
+ "\n " +
833
+ theme.fg("muted", `${i + 1}.`) +
834
+ " " +
835
+ theme.fg("accent", step.agent) +
836
+ theme.fg("dim", ` ${preview}`);
837
+ }
838
+ if (args.chain.length > 3) text += `\n ${theme.fg("muted", `... +${args.chain.length - 3} more`)}`;
839
+ return new Text(text, 0, 0);
840
+ }
841
+ if (args.tasks && args.tasks.length > 0) {
842
+ let text =
843
+ theme.fg("toolTitle", theme.bold("subagent ")) +
844
+ theme.fg("accent", `parallel (${args.tasks.length} tasks)`) +
845
+ theme.fg("muted", ` [${scope}]`);
846
+ for (const t of args.tasks.slice(0, 3)) {
847
+ const preview = t.task.length > 40 ? `${t.task.slice(0, 40)}...` : t.task;
848
+ text += `\n ${theme.fg("accent", t.agent)}${theme.fg("dim", ` ${preview}`)}`;
849
+ }
850
+ if (args.tasks.length > 3) text += `\n ${theme.fg("muted", `... +${args.tasks.length - 3} more`)}`;
851
+ if (args.aggregator) {
852
+ const preview =
853
+ args.aggregator.task.length > 40 ? `${args.aggregator.task.slice(0, 40)}...` : args.aggregator.task;
854
+ text += `\n ${theme.fg("muted", "fan-in → ")}${theme.fg("accent", args.aggregator.agent)}${theme.fg(
855
+ "dim",
856
+ ` ${preview}`,
857
+ )}`;
858
+ }
859
+ return new Text(text, 0, 0);
860
+ }
861
+ const agentName = args.agent || "...";
862
+ const preview = args.task ? (args.task.length > 60 ? `${args.task.slice(0, 60)}...` : args.task) : "...";
863
+ let text =
864
+ theme.fg("toolTitle", theme.bold("subagent ")) +
865
+ theme.fg("accent", agentName) +
866
+ theme.fg("muted", ` [${scope}]`);
867
+ text += `\n ${theme.fg("dim", preview)}`;
868
+ return new Text(text, 0, 0);
869
+ },
870
+
871
+ renderResult(result, { expanded }, theme, _context) {
872
+ const details = result.details as SubagentDetails | undefined;
873
+ if (!details || details.results.length === 0) {
874
+ const text = result.content[0];
875
+ return new Text(text?.type === "text" ? text.text : "(no output)", 0, 0);
876
+ }
877
+
878
+ const mdTheme = getMarkdownTheme();
879
+
880
+ const renderDisplayItems = (items: DisplayItem[], limit?: number) => {
881
+ const toShow = limit ? items.slice(-limit) : items;
882
+ const skipped = limit && items.length > limit ? items.length - limit : 0;
883
+ let text = "";
884
+ if (skipped > 0) text += theme.fg("muted", `... ${skipped} earlier items\n`);
885
+ for (const item of toShow) {
886
+ if (item.type === "text") {
887
+ const preview = expanded ? item.text : item.text.split("\n").slice(0, 3).join("\n");
888
+ text += `${theme.fg("toolOutput", preview)}\n`;
889
+ } else {
890
+ text += `${theme.fg("muted", "→ ") + formatToolCall(item.name, item.args, theme.fg.bind(theme))}\n`;
891
+ }
892
+ }
893
+ return text.trimEnd();
894
+ };
895
+
896
+ if (details.mode === "single" && details.results.length === 1) {
897
+ const r = details.results[0];
898
+ const isError = r.exitCode !== 0 || r.stopReason === "error" || r.stopReason === "aborted";
899
+ const icon = isError ? theme.fg("error", "✗") : theme.fg("success", "✓");
900
+ const displayItems = getDisplayItems(r.messages);
901
+ const finalOutput = getResultFinalOutput(r);
902
+
903
+ if (expanded) {
904
+ const container = new Container();
905
+ let header = `${icon} ${theme.fg("toolTitle", theme.bold(r.agent))}${theme.fg("muted", ` (${r.agentSource})`)}`;
906
+ if (isError && r.stopReason) header += ` ${theme.fg("error", `[${r.stopReason}]`)}`;
907
+ container.addChild(new Text(header, 0, 0));
908
+ if (isError && r.errorMessage)
909
+ container.addChild(new Text(theme.fg("error", `Error: ${r.errorMessage}`), 0, 0));
910
+ container.addChild(new Spacer(1));
911
+ container.addChild(new Text(theme.fg("muted", "─── Task ───"), 0, 0));
912
+ container.addChild(new Text(theme.fg("dim", r.task), 0, 0));
913
+ container.addChild(new Spacer(1));
914
+ container.addChild(new Text(theme.fg("muted", "─── Output ───"), 0, 0));
915
+ if (displayItems.length === 0 && !finalOutput) {
916
+ container.addChild(new Text(theme.fg("muted", "(no output)"), 0, 0));
917
+ } else {
918
+ for (const item of displayItems) {
919
+ if (item.type === "toolCall")
920
+ container.addChild(
921
+ new Text(
922
+ theme.fg("muted", "→ ") + formatToolCall(item.name, item.args, theme.fg.bind(theme)),
923
+ 0,
924
+ 0,
925
+ ),
926
+ );
927
+ }
928
+ if (finalOutput) {
929
+ container.addChild(new Spacer(1));
930
+ container.addChild(new Markdown(finalOutput.trim(), 0, 0, mdTheme));
931
+ }
932
+ }
933
+ const usageStr = formatUsageStats(r.usage, r.model);
934
+ if (usageStr) {
935
+ container.addChild(new Spacer(1));
936
+ container.addChild(new Text(theme.fg("dim", usageStr), 0, 0));
937
+ }
938
+ return container;
939
+ }
940
+
941
+ let text = `${icon} ${theme.fg("toolTitle", theme.bold(r.agent))}${theme.fg("muted", ` (${r.agentSource})`)}`;
942
+ if (isError && r.stopReason) text += ` ${theme.fg("error", `[${r.stopReason}]`)}`;
943
+ if (isError && r.errorMessage) text += `\n${theme.fg("error", `Error: ${r.errorMessage}`)}`;
944
+ else if (displayItems.length === 0) text += `\n${theme.fg("muted", "(no output)")}`;
945
+ else {
946
+ text += `\n${renderDisplayItems(displayItems, COLLAPSED_ITEM_COUNT)}`;
947
+ if (displayItems.length > COLLAPSED_ITEM_COUNT) text += `\n${theme.fg("muted", "(Ctrl+O to expand)")}`;
948
+ }
949
+ const usageStr = formatUsageStats(r.usage, r.model);
950
+ if (usageStr) text += `\n${theme.fg("dim", usageStr)}`;
951
+ return new Text(text, 0, 0);
952
+ }
953
+
954
+ const aggregateUsage = (results: SingleResult[]) => {
955
+ const total = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, turns: 0 };
956
+ for (const r of results) {
957
+ total.input += r.usage.input;
958
+ total.output += r.usage.output;
959
+ total.cacheRead += r.usage.cacheRead;
960
+ total.cacheWrite += r.usage.cacheWrite;
961
+ total.cost += r.usage.cost;
962
+ total.turns += r.usage.turns;
963
+ }
964
+ return total;
965
+ };
966
+
967
+ if (details.mode === "chain") {
968
+ const successCount = details.results.filter((r) => r.exitCode === 0).length;
969
+ const icon = successCount === details.results.length ? theme.fg("success", "✓") : theme.fg("error", "✗");
970
+
971
+ if (expanded) {
972
+ const container = new Container();
973
+ container.addChild(
974
+ new Text(
975
+ icon +
976
+ " " +
977
+ theme.fg("toolTitle", theme.bold("chain ")) +
978
+ theme.fg("accent", `${successCount}/${details.results.length} steps`),
979
+ 0,
980
+ 0,
981
+ ),
982
+ );
983
+
984
+ for (const r of details.results) {
985
+ const rIcon = r.exitCode === 0 ? theme.fg("success", "✓") : theme.fg("error", "✗");
986
+ const displayItems = getDisplayItems(r.messages);
987
+ const finalOutput = getResultFinalOutput(r);
988
+
989
+ container.addChild(new Spacer(1));
990
+ container.addChild(
991
+ new Text(
992
+ `${theme.fg("muted", `─── Step ${r.step}: `) + theme.fg("accent", r.agent)} ${rIcon}`,
993
+ 0,
994
+ 0,
995
+ ),
996
+ );
997
+ container.addChild(new Text(theme.fg("muted", "Task: ") + theme.fg("dim", r.task), 0, 0));
998
+
999
+ // Show tool calls
1000
+ for (const item of displayItems) {
1001
+ if (item.type === "toolCall") {
1002
+ container.addChild(
1003
+ new Text(
1004
+ theme.fg("muted", "→ ") + formatToolCall(item.name, item.args, theme.fg.bind(theme)),
1005
+ 0,
1006
+ 0,
1007
+ ),
1008
+ );
1009
+ }
1010
+ }
1011
+
1012
+ // Show final output as markdown
1013
+ if (finalOutput) {
1014
+ container.addChild(new Spacer(1));
1015
+ container.addChild(new Markdown(finalOutput.trim(), 0, 0, mdTheme));
1016
+ }
1017
+
1018
+ const stepUsage = formatUsageStats(r.usage, r.model);
1019
+ if (stepUsage) container.addChild(new Text(theme.fg("dim", stepUsage), 0, 0));
1020
+ }
1021
+
1022
+ const usageStr = formatUsageStats(aggregateUsage(details.results));
1023
+ if (usageStr) {
1024
+ container.addChild(new Spacer(1));
1025
+ container.addChild(new Text(theme.fg("dim", `Total: ${usageStr}`), 0, 0));
1026
+ }
1027
+ return container;
1028
+ }
1029
+
1030
+ // Collapsed view
1031
+ let text =
1032
+ icon +
1033
+ " " +
1034
+ theme.fg("toolTitle", theme.bold("chain ")) +
1035
+ theme.fg("accent", `${successCount}/${details.results.length} steps`);
1036
+ for (const r of details.results) {
1037
+ const rIcon = r.exitCode === 0 ? theme.fg("success", "✓") : theme.fg("error", "✗");
1038
+ const displayItems = getDisplayItems(r.messages);
1039
+ text += `\n\n${theme.fg("muted", `─── Step ${r.step}: `)}${theme.fg("accent", r.agent)} ${rIcon}`;
1040
+ if (displayItems.length === 0) text += `\n${theme.fg("muted", "(no output)")}`;
1041
+ else text += `\n${renderDisplayItems(displayItems, 5)}`;
1042
+ }
1043
+ const usageStr = formatUsageStats(aggregateUsage(details.results));
1044
+ if (usageStr) text += `\n\n${theme.fg("dim", `Total: ${usageStr}`)}`;
1045
+ text += `\n${theme.fg("muted", "(Ctrl+O to expand)")}`;
1046
+ return new Text(text, 0, 0);
1047
+ }
1048
+
1049
+ if (details.mode === "parallel") {
1050
+ const running = details.results.filter((r) => r.exitCode === -1).length;
1051
+ const successCount = details.results.filter((r) => r.exitCode === 0).length;
1052
+ const failCount = details.results.filter((r) => r.exitCode > 0).length;
1053
+ const aggregator = details.aggregator;
1054
+ const aggregatorRunning = aggregator?.exitCode === -1;
1055
+ const aggregatorFailed = aggregator ? aggregator.exitCode > 0 || aggregator.stopReason === "error" : false;
1056
+ const isRunning = running > 0 || aggregatorRunning;
1057
+ const icon = isRunning
1058
+ ? theme.fg("warning", "⏳")
1059
+ : failCount > 0 || aggregatorFailed
1060
+ ? theme.fg("warning", "◐")
1061
+ : theme.fg("success", "✓");
1062
+ const status = isRunning
1063
+ ? aggregatorRunning
1064
+ ? `${successCount + failCount}/${details.results.length} done, fan-in running`
1065
+ : `${successCount + failCount}/${details.results.length} done, ${running} running`
1066
+ : aggregator
1067
+ ? `${successCount}/${details.results.length} tasks + fan-in`
1068
+ : `${successCount}/${details.results.length} tasks`;
1069
+
1070
+ if (expanded && !isRunning) {
1071
+ const container = new Container();
1072
+ container.addChild(
1073
+ new Text(
1074
+ `${icon} ${theme.fg("toolTitle", theme.bold("parallel "))}${theme.fg("accent", status)}`,
1075
+ 0,
1076
+ 0,
1077
+ ),
1078
+ );
1079
+
1080
+ for (const r of details.results) {
1081
+ const rIcon = r.exitCode === 0 ? theme.fg("success", "✓") : theme.fg("error", "✗");
1082
+ const displayItems = getDisplayItems(r.messages);
1083
+ const finalOutput = getResultFinalOutput(r);
1084
+
1085
+ container.addChild(new Spacer(1));
1086
+ container.addChild(
1087
+ new Text(`${theme.fg("muted", "─── ") + theme.fg("accent", r.agent)} ${rIcon}`, 0, 0),
1088
+ );
1089
+ container.addChild(new Text(theme.fg("muted", "Task: ") + theme.fg("dim", r.task), 0, 0));
1090
+
1091
+ // Show tool calls
1092
+ for (const item of displayItems) {
1093
+ if (item.type === "toolCall") {
1094
+ container.addChild(
1095
+ new Text(
1096
+ theme.fg("muted", "→ ") + formatToolCall(item.name, item.args, theme.fg.bind(theme)),
1097
+ 0,
1098
+ 0,
1099
+ ),
1100
+ );
1101
+ }
1102
+ }
1103
+
1104
+ // Show final output as markdown
1105
+ if (finalOutput) {
1106
+ container.addChild(new Spacer(1));
1107
+ container.addChild(new Markdown(finalOutput.trim(), 0, 0, mdTheme));
1108
+ }
1109
+
1110
+ const taskUsage = formatUsageStats(r.usage, r.model);
1111
+ if (taskUsage) container.addChild(new Text(theme.fg("dim", taskUsage), 0, 0));
1112
+ }
1113
+
1114
+ if (aggregator) {
1115
+ const rIcon = aggregator.exitCode === 0 ? theme.fg("success", "✓") : theme.fg("error", "✗");
1116
+ const displayItems = getDisplayItems(aggregator.messages);
1117
+ const finalOutput = getResultFinalOutput(aggregator);
1118
+
1119
+ container.addChild(new Spacer(1));
1120
+ container.addChild(
1121
+ new Text(
1122
+ `${theme.fg("muted", "─── fan-in → ") + theme.fg("accent", aggregator.agent)} ${rIcon}`,
1123
+ 0,
1124
+ 0,
1125
+ ),
1126
+ );
1127
+ container.addChild(new Text(theme.fg("muted", "Task: ") + theme.fg("dim", aggregator.task), 0, 0));
1128
+ for (const item of displayItems) {
1129
+ if (item.type === "toolCall") {
1130
+ container.addChild(
1131
+ new Text(
1132
+ theme.fg("muted", "→ ") + formatToolCall(item.name, item.args, theme.fg.bind(theme)),
1133
+ 0,
1134
+ 0,
1135
+ ),
1136
+ );
1137
+ }
1138
+ }
1139
+ if (finalOutput) {
1140
+ container.addChild(new Spacer(1));
1141
+ container.addChild(new Markdown(finalOutput.trim(), 0, 0, mdTheme));
1142
+ }
1143
+ const fanInUsage = formatUsageStats(aggregator.usage, aggregator.model);
1144
+ if (fanInUsage) container.addChild(new Text(theme.fg("dim", fanInUsage), 0, 0));
1145
+ }
1146
+
1147
+ const usageResults = aggregator ? [...details.results, aggregator] : details.results;
1148
+ const usageStr = formatUsageStats(aggregateUsage(usageResults));
1149
+ if (usageStr) {
1150
+ container.addChild(new Spacer(1));
1151
+ container.addChild(new Text(theme.fg("dim", `Total: ${usageStr}`), 0, 0));
1152
+ }
1153
+ return container;
1154
+ }
1155
+
1156
+ // Collapsed view (or still running)
1157
+ let text = `${icon} ${theme.fg("toolTitle", theme.bold("parallel "))}${theme.fg("accent", status)}`;
1158
+ for (const r of details.results) {
1159
+ const rIcon =
1160
+ r.exitCode === -1
1161
+ ? theme.fg("warning", "⏳")
1162
+ : r.exitCode === 0
1163
+ ? theme.fg("success", "✓")
1164
+ : theme.fg("error", "✗");
1165
+ const displayItems = getDisplayItems(r.messages);
1166
+ text += `\n\n${theme.fg("muted", "─── ")}${theme.fg("accent", r.agent)} ${rIcon}`;
1167
+ if (displayItems.length === 0)
1168
+ text += `\n${theme.fg("muted", r.exitCode === -1 ? "(running...)" : "(no output)")}`;
1169
+ else text += `\n${renderDisplayItems(displayItems, 5)}`;
1170
+ }
1171
+ if (aggregator) {
1172
+ const rIcon =
1173
+ aggregator.exitCode === -1
1174
+ ? theme.fg("warning", "⏳")
1175
+ : aggregator.exitCode === 0
1176
+ ? theme.fg("success", "✓")
1177
+ : theme.fg("error", "✗");
1178
+ const displayItems = getDisplayItems(aggregator.messages);
1179
+ text += `\n\n${theme.fg("muted", "─── fan-in → ")}${theme.fg("accent", aggregator.agent)} ${rIcon}`;
1180
+ if (displayItems.length === 0)
1181
+ text += `\n${theme.fg("muted", aggregator.exitCode === -1 ? "(running...)" : "(no output)")}`;
1182
+ else text += `\n${renderDisplayItems(displayItems, 5)}`;
1183
+ }
1184
+ if (!isRunning) {
1185
+ const usageResults = aggregator ? [...details.results, aggregator] : details.results;
1186
+ const usageStr = formatUsageStats(aggregateUsage(usageResults));
1187
+ if (usageStr) text += `\n\n${theme.fg("dim", `Total: ${usageStr}`)}`;
1188
+ }
1189
+ if (!expanded) text += `\n${theme.fg("muted", "(Ctrl+O to expand)")}`;
1190
+ return new Text(text, 0, 0);
1191
+ }
1192
+
1193
+ const text = result.content[0];
1194
+ return new Text(text?.type === "text" ? text.text : "(no output)", 0, 0);
1195
+ },
1196
+ });
1197
+ }