@ferris1225/pi-subagents 4.2.4 → 4.2.7

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/src/dispatch.ts CHANGED
@@ -1,541 +1,552 @@
1
- /**
2
- * The `subagent` tool: dispatches the enabled agents (explorer, executor,
3
- * plus custom roles) as isolated pi
4
- * child processes, single or parallel. Owns the public dispatch contract and
5
- * per-run status tracking. Stable thread generations, final integration, and
6
- * completion ownership live in thread-lifecycle.ts.
7
- */
8
-
9
- import { StringEnum } from "@earendil-works/pi-ai";
10
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
11
- import { Text } from "@earendil-works/pi-tui";
12
- import { join, resolve } from "node:path";
13
- import { Type } from "typebox";
14
- import { discoverAgents, isWriteCapableAgent, resolveAgentTools, type AgentConfig } from "./agents.ts";
15
- import { loadConfig } from "./config.ts";
16
- import { formatCompletionBlock, formatUsage, queuedResult } from "./format.ts";
17
- import {
18
- formatTaskSummary,
19
- formatToolActivity,
20
- monitor,
21
- statusIcon,
22
- type RunView,
23
- type RunWaitReason,
24
- } from "./monitor.ts";
25
- import type { SubagentRuntime } from "./runtime.ts";
26
- import { persistThreadCheckpoint } from "./thread-lifecycle.ts";
27
- import {
28
- getProjectRoot,
29
- getResultOutput,
30
- isFailedResult,
31
- runSingleAgentWithMainFallback,
32
- type SingleResult,
33
- type SubagentDetails,
34
- type SubagentLiveEvent,
35
- } from "./spawn.ts";
36
- import {
37
- createBackgroundDispatcher,
38
- projectResultsRoot,
39
- resolveDispatchModelRoute,
40
- runInManagedRepositoryLane,
41
- withWorktreeSystemPrompt,
42
- type DispatchEnvironment,
43
- } from "./thread-lifecycle.ts";
44
- import type { IsolationMode } from "./worktree.ts";
45
-
46
- export { isWorktreeCapableAgent, runInManagedRepositoryLane } from "./thread-lifecycle.ts";
47
-
48
- const NON_BLANK_TASK_OPTIONS = { minLength: 1, pattern: "\\S" } as const;
49
-
50
- const ISOLATION_DESCRIPTION =
51
- "Filesystem isolation: shared uses the caller's working tree; worktree creates a detached temporary Git worktree (write-capable agents, including executor, only)";
52
-
53
- const IsolationSchema = Type.Optional(
54
- StringEnum(["shared", "worktree"] as const, { description: ISOLATION_DESCRIPTION }),
55
- );
56
-
57
- const WaitSchema = Type.Optional(
58
- Type.Boolean({
59
- description:
60
- "Block until every run started by this call settles, then return their results in-turn (each result still arrives as a completion message too). Only for one-shot (pi -p) sessions or a next step that needs these results within this turn.",
61
- }),
62
- );
63
-
64
- const TaskItem = Type.Object({
65
- agent: Type.String({ description: "Name of the agent to invoke" }),
66
- task: Type.String({
67
- ...NON_BLANK_TASK_OPTIONS,
68
- description: "Self-contained task to delegate (the agent has no memory of this conversation)",
69
- }),
70
- cwd: Type.Optional(Type.String({ description: "Working directory for the agent process" })),
71
- isolation: IsolationSchema,
72
- });
73
-
74
- const SubagentParams = Type.Object({
75
- agent: Type.Optional(Type.String({ description: "Name of the agent to invoke (single mode)" })),
76
- task: Type.Optional(
77
- Type.String({ ...NON_BLANK_TASK_OPTIONS, description: "Self-contained task to delegate (single mode)" }),
78
- ),
79
- tasks: Type.Optional(Type.Array(TaskItem, { description: "Array of {agent, task} for parallel execution" })),
80
- cwd: Type.Optional(Type.String({ description: "Working directory for the agent process (single mode)" })),
81
- isolation: IsolationSchema,
82
- wait: WaitSchema,
83
- });
84
-
85
- /** Roles that default to worktree isolation in parallel dispatches even when
86
- * the live catalog cannot be consulted (render-only call sites). Custom
87
- * write-capable agents join them via isWriteCapableAgent on the execute path. */
88
- const WORKTREE_DEFAULT_AGENTS = new Set(["executor"]);
89
-
90
- /** Resolve the default isolation for a dispatch. Precedence: an explicit
91
- * per-call request, then the role's own frontmatter declaration (`worktree`
92
- * honored for write-capable roles only; `shared` always), then the parallel
93
- * write default — parallel write-capable agents get a detached worktree
94
- * because shared writers serialize on the repository lane, so defaulting them
95
- * to shared would turn one parallel batch into a convoy that also parks
96
- * process slots. */
97
- export function defaultIsolationMode(
98
- mode: "single" | "parallel",
99
- agentName: string,
100
- requested?: IsolationMode,
101
- writeCapable = WORKTREE_DEFAULT_AGENTS.has(agentName),
102
- declared?: IsolationMode,
103
- ): IsolationMode {
104
- if (requested) return requested;
105
- if (declared === "shared") return "shared";
106
- if (declared === "worktree" && writeCapable) return "worktree";
107
- return mode === "parallel" && writeCapable ? "worktree" : "shared";
108
- }
109
-
110
- /** In-turn wait behind dispatch `wait: true` — the escape hatch for one-shot
111
- * `pi -p` parents that exit at end of turn: hold the call until every run it
112
- * started settles, then hand back their result blocks. Interactive sessions
113
- * never take this path; their results arrive as completion wake-ups. No
114
- * timer: a waiter resolves the moment its run's result registers (children
115
- * are bounded by the idle watchdog), an already-parked run answers
116
- * immediately with its resume handle, and the turn's abort signal remains the
117
- * escape hatch. */
118
- export async function awaitRunResults(
119
- runtime: SubagentRuntime,
120
- runIds: number[],
121
- signal: AbortSignal | undefined,
122
- maxResultLines: number,
123
- fallbackCwd: string,
124
- ): Promise<string> {
125
- const waitForRun = (runId: number): Promise<{ result?: SingleResult; note?: string }> => {
126
- const already = runtime.settledRuns.get(runId);
127
- if (already) return Promise.resolve({ result: already });
128
- if (monitor.findRun(runId)?.status === "parked") {
129
- return Promise.resolve({ note: `run #${runId} is parked at a stable checkpoint; use subagent_control resume to continue it` });
130
- }
131
- return new Promise((resolve) => {
132
- let done = false;
133
- let unsub: (() => void) | undefined;
134
- const cleanup = (): void => {
135
- if (unsub) unsub();
136
- signal?.removeEventListener("abort", onAbort);
137
- const listeners = runtime.settledListeners.get(runId);
138
- if (listeners) {
139
- listeners.delete(onSettled);
140
- if (listeners.size === 0) runtime.settledListeners.delete(runId);
141
- }
142
- };
143
- const finish = (outcome: { result?: SingleResult; note?: string }): void => {
144
- if (done) return;
145
- done = true;
146
- cleanup();
147
- resolve(outcome);
148
- };
149
- const onSettled = (result: SingleResult): void => finish({ result });
150
- const onMonitor = (): void => {
151
- const current = runtime.settledRuns.get(runId);
152
- if (current) {
153
- finish({ result: current });
154
- return;
155
- }
156
- const live = monitor.findRun(runId);
157
- if (live?.status === "parked") {
158
- finish({ note: `run #${runId} was parked at a stable checkpoint; use subagent_control resume to continue it` });
159
- return;
160
- }
161
- if (!live) {
162
- // Removal is followed synchronously by registerRunResult in the
163
- // finishing task; re-check on the next tick so the result wins.
164
- setTimeout(() => {
165
- const late = runtime.settledRuns.get(runId);
166
- if (late) finish({ result: late });
167
- else finish({ note: `run #${runId} was removed before its result was recorded (cancelled or session ended)` });
168
- }, 0);
169
- }
170
- };
171
- const onAbort = (): void => finish({ note: "wait aborted" });
172
- let listeners = runtime.settledListeners.get(runId);
173
- if (!listeners) {
174
- listeners = new Set();
175
- runtime.settledListeners.set(runId, listeners);
176
- }
177
- listeners.add(onSettled);
178
- unsub = monitor.subscribe(onMonitor);
179
- if (signal?.aborted) onAbort();
180
- else signal?.addEventListener("abort", onAbort, { once: true });
181
- });
182
- };
183
- const outcomes = await Promise.all(runIds.map(waitForRun));
184
- return outcomes.map((outcome) =>
185
- outcome.result
186
- ? formatCompletionBlock(outcome.result, maxResultLines, { resultRoot: projectResultsRoot(runtime.configPath, outcome.result.projectCwd ?? fallbackCwd) })
187
- : (outcome.note ?? "(no outcome)"),
188
- ).join("\n\n");
189
- }
190
-
191
- export function registerSubagentTool(pi: ExtensionAPI, runtime: SubagentRuntime): void {
192
- // Latest dispatch environment. The dispatcher is created once per process so
193
- // restored threads can resume before any dispatch has run; each execute
194
- // refreshes the fallback context, config, and agent catalog it resolves.
195
- const environmentRef: { current: DispatchEnvironment | undefined } = { current: undefined };
196
-
197
- // Finished runs leave the active monitor immediately. Their final findings
198
- // are sent as a custom message that starts a follow-up turn.
199
- const finishRun = (
200
- runId: number,
201
- status: "done" | "failed",
202
- opts?: { silent?: boolean },
203
- ): void => {
204
- monitor.setStatus(runId, status); // stamps endedAt for the elapsed time
205
- const run = monitor.removeRun(runId);
206
- if (!run) return; // already finished stay idempotent
207
- if (opts?.silent || !runtime.sessionActive) return;
208
- const icon = status === "done" ? "✓" : "✗";
209
- environmentRef.current?.ctx.ui.notify(`${icon} #${run.id} ${monitor.summarize(run)}`, status === "done" ? "info" : "error");
210
- };
211
-
212
- // Live sub-agent activity → concise one-line status ("thinking",
213
- // "read src/index.ts", ...), never a raw args blob. The live handler
214
- // only updates monitor state; the queue task owns terminal removal,
215
- // notification, and lifecycle decisions.
216
- const makeLiveHandler =
217
- (runId: number, generation?: number) =>
218
- (e: SubagentLiveEvent): void => {
219
- if (generation !== undefined && runtime.threads.get(runId)?.generation !== generation) return;
220
- switch (e.kind) {
221
- case "status":
222
- monitor.setStatus(runId, e.status);
223
- // A fresh running segment refreshes the durable checkpoint (session
224
- // path plus child pids) so a crash mid-generation still restores.
225
- if (e.status === "running") {
226
- const thread = runtime.threads.get(runId);
227
- if (thread?.sessionId && thread.sessionDir) {
228
- persistThreadCheckpoint(runtime, thread, "parked");
229
- }
230
- }
231
- break;
232
- case "model":
233
- monitor.setModel(runId, e.model, e.fallbackFrom);
234
- monitor.setThinking(runId, e.thinking);
235
- break;
236
- case "usage":
237
- monitor.setUsage(runId, e.usage, e.model);
238
- break;
239
- case "session": {
240
- runtime.retainSession({ sessionDir: e.sessionDir });
241
- const thread = runtime.threads.get(runId);
242
- if (thread && (generation === undefined || runtime.threads.get(runId)?.generation === generation)) {
243
- thread.sessionId = e.sessionId;
244
- thread.sessionDir = e.sessionDir;
245
- persistThreadCheckpoint(runtime, thread, "parked");
246
- }
247
- break;
248
- }
249
- case "tool_start":
250
- monitor.recordToolStart(runId, e.toolName, formatToolActivity(e.toolName, e.args));
251
- break;
252
- case "tool_end":
253
- monitor.recordToolEnd(runId, e.toolName, e.isError);
254
- break;
255
- case "thinking":
256
- monitor.setActivity(runId, "thinking");
257
- break;
258
- case "text":
259
- // A text delta is model output, not a filesystem write.
260
- monitor.setActivity(runId, "responding");
261
- break;
262
- }
263
- };
264
-
265
- const makeDetails =
266
- (mode: "single" | "parallel", background = false) =>
267
- (results: SingleResult[]): SubagentDetails => ({ mode, results, background });
268
-
269
- /** Pacing note appended to dispatch confirmations whenever runs are actually
270
- * waiting. Slot waits and repository-lane waits are stated separately with
271
- * the real capacity: a lane-serialized shared writer or a starting child
272
- * must never read as an exhausted pool, or the model stops dispatching while
273
- * slots are free. Empty when nothing is waiting. */
274
- const queuePacingNote = (): string => {
275
- const runs = monitor.getRuns();
276
- const queuedWith = (reason: RunWaitReason): number =>
277
- runs.filter((run) => run.status === "queued" && run.waitReason === reason).length;
278
- const slotWaiting = queuedWith("process-slot");
279
- const laneWaiting = queuedWith("repository-lane");
280
- if (slotWaiting === 0 && laneWaiting === 0) return "";
281
- const executing = runs.filter((run) =>
282
- run.status === "running" || run.status === "interrupting" || (run.status === "queued" && run.waitReason === "starting"),
283
- ).length;
284
- const capacity = runtime.backgroundQueue.capacity;
285
- const freeSlots = Math.max(0, capacity - runtime.backgroundQueue.activeCount);
286
- const parts = [`${executing} running`];
287
- if (slotWaiting > 0) {
288
- parts.push(`${slotWaiting} waiting for a free process slot (capacity ${capacity}); they start automatically as slots free`);
289
- }
290
- if (laneWaiting > 0) {
291
- parts.push(
292
- `${laneWaiting} shared-checkout writer${laneWaiting === 1 ? "" : "s"} waiting for the repository write lane — write serialization, not slot capacity` +
293
- (slotWaiting === 0 ? ` (${freeSlots} of ${capacity} slots free; parallel writers avoid the lane via worktree isolation)` : ""),
294
- );
295
- }
296
- return ` Pacing: ${parts.join(" · ")}. Keep dispatching independent units.`;
297
- };
298
-
299
- const startBackground = createBackgroundDispatcher({
300
- runtime,
301
- getEnvironment: () => {
302
- if (!environmentRef.current) {
303
- throw new Error("pi-subagents dispatch environment is not ready yet.");
304
- }
305
- return environmentRef.current;
306
- },
307
- finishRun,
308
- makeLiveHandler,
309
- makeDetails,
310
- });
311
- runtime.dispatcher = startBackground;
312
-
313
- pi.registerTool({
314
- name: "subagent",
315
- label: "Subagent",
316
- description: [
317
- "Dispatch enabled agents as isolated leaf Pi child processes: single {agent, task} or parallel {tasks: [...]}. Dispatching never blocks your turn — runs proceed in the background and each completion resumes you automatically; never poll or restate delivered results.",
318
- "Put every genuinely independent unit in one `tasks` array: there is no per-call cap, and runs beyond the machine's free process slots simply wait and start as slots free.",
319
- "Parallel write-capable agents default to a detached Git worktree so writers run concurrently; explicit `shared` keeps the caller's checkout and serializes same-repository writers. Worktree setup failure never silently falls back to shared.",
320
- "A configured child-model failure continues the retained session on the current main model.",
321
- ].join(" "),
322
- promptSnippet:
323
- "Dispatch isolated background agents for recon, implementation, cleanup, docs sync, or result merging; never blocks your turn, and completions wake you automatically.",
324
- parameters: SubagentParams,
325
-
326
- async execute(_toolCallId, params, signal, _onUpdate, ctx) {
327
- // Run ids are allocated below; restore raises the allocator above every
328
- // id a durable record still owns, so a dispatch racing it could hand a
329
- // fresh run the id of a parked thread and overwrite its record.
330
- await runtime.durableRestore;
331
- monitor.beginTurn();
332
- const config = await loadConfig(runtime.configPath);
333
-
334
- const discovery = discoverAgents(ctx.cwd, {
335
- scope: config.agentScope,
336
- enabledNames: config.enabledAgents,
337
- projectTrusted: ctx.isProjectTrusted?.() === true,
338
- });
339
- const agents = discovery.agents;
340
- // Refresh the dispatcher's fallback environment so control operations
341
- // (resume of restored threads) never run on a stale context.
342
- environmentRef.current = { ctx, config, agents };
343
-
344
- const hasTasks = (params.tasks?.length ?? 0) > 0;
345
- const hasSingle = Boolean(params.agent) && params.task !== undefined;
346
-
347
- const catalog = agents.map((a) => a.name).join(", ") || "none";
348
-
349
- if (Number(hasTasks) + Number(hasSingle) !== 1) {
350
- return {
351
- content: [
352
- {
353
- type: "text",
354
- text: `Invalid parameters. Provide exactly one mode: single {agent, task} or parallel {tasks: [...]}. Enabled agents: ${catalog}.`,
355
- },
356
- ],
357
- details: makeDetails("single")([]),
358
- };
359
- }
360
-
361
- if (hasTasks) {
362
- const blankTaskIndex = params.tasks?.findIndex(({ task }) => task.trim().length === 0) ?? -1;
363
- if (blankTaskIndex !== -1) {
364
- return {
365
- content: [
366
- {
367
- type: "text",
368
- text: `Invalid parameters. tasks[${blankTaskIndex}].task must contain at least one non-whitespace character. No background tasks were started. Enabled agents: ${catalog}.`,
369
- },
370
- ],
371
- details: makeDetails("parallel")([]),
372
- };
373
- }
374
- } else if (params.task?.trim().length === 0) {
375
- return {
376
- content: [
377
- {
378
- type: "text",
379
- text: `Invalid parameters. task must contain at least one non-whitespace character. Enabled agents: ${catalog}.`,
380
- },
381
- ],
382
- details: makeDetails("single")([]),
383
- };
384
- }
385
-
386
- // Sub-agents run detached from the foreground turn: the editor stays
387
- // available and completion messages later wake the main agent. The turn is
388
- // NOT terminated here the model can keep dispatching independent units
389
- // or do its own work, and the background queue paces how many child
390
- // processes actually run at once, so no per-call task cap is enforced.
391
- if (params.tasks && params.tasks.length > 0) {
392
- const results: SingleResult[] = [];
393
- // Preserve caller order (and deterministic completion batching) while
394
- // preparing each isolated filesystem before its queue entry can start.
395
- for (const item of params.tasks) {
396
- const catalogAgent = agents.find((candidate) => candidate.name === item.agent);
397
- results.push(await startBackground(
398
- item.agent,
399
- item.task,
400
- item.cwd,
401
- defaultIsolationMode(
402
- "parallel",
403
- item.agent,
404
- item.isolation as IsolationMode | undefined,
405
- catalogAgent ? isWriteCapableAgent(catalogAgent) : undefined,
406
- catalogAgent?.isolation,
407
- ),
408
- ));
409
- }
410
- const startedRuns = results.filter((result) => result.exitCode === -1);
411
- const started = startedRuns.length;
412
- const startedRefs = startedRuns.map((result) =>
413
- result.runId === undefined ? result.agent : `#${result.runId} ${result.agent}`,
414
- );
415
- const failureLines = results.flatMap((result, index) => {
416
- if (result.exitCode === -1) return [];
417
- const reason = getResultOutput(result).trim() || "unknown startup failure";
418
- return [
419
- `- tasks[${index}] (${params.tasks![index]!.agent}) failed to start: ${reason.replace(/\n/g, "\n ")}`,
420
- ];
421
- });
422
- if (started === 0) {
423
- // Pi marks custom-tool failures only when execute throws; returning an
424
- // `isError` property is still a successful AgentToolResult.
425
- throw new Error(`No background subagents were started.\n${failureLines.join("\n")}`);
426
- }
427
- if (params.wait) {
428
- const startedIds = startedRuns
429
- .map((result) => result.runId)
430
- .filter((id): id is number => id !== undefined);
431
- const blocks = await awaitRunResults(runtime, startedIds, signal, config.maxResultLines, ctx.cwd);
432
- const text = [
433
- `Started ${started} subagent${started === 1 ? "" : "s"} (${startedRefs.join(", ")}) and waited in-turn.`,
434
- ...(failureLines.length > 0
435
- ? [`${failureLines.length} task${failureLines.length === 1 ? "" : "s"} failed before launch:`, ...failureLines]
436
- : []),
437
- "",
438
- blocks,
439
- ].join("\n");
440
- return {
441
- content: [{ type: "text", text }],
442
- details: makeDetails("parallel", true)(results),
443
- };
444
- }
445
- const text = [
446
- `Started ${started} background subagent${started === 1 ? "" : "s"}: ${startedRefs.join(", ")}. They run in the background and never block you — dispatch more independent units now or keep working; each result resumes you automatically when you are idle.`,
447
- ...(failureLines.length > 0
448
- ? [`${failureLines.length} task${failureLines.length === 1 ? "" : "s"} failed before launch:`, ...failureLines]
449
- : []),
450
- ].join("\n") + queuePacingNote();
451
- return {
452
- content: [{ type: "text", text }],
453
- details: makeDetails("parallel", true)(results),
454
- };
455
- }
456
-
457
- const singleCatalogAgent = agents.find((candidate) => candidate.name === params.agent);
458
- const result = await startBackground(
459
- params.agent as string,
460
- params.task as string,
461
- params.cwd,
462
- defaultIsolationMode(
463
- "single",
464
- params.agent as string,
465
- params.isolation as IsolationMode | undefined,
466
- singleCatalogAgent ? isWriteCapableAgent(singleCatalogAgent) : undefined,
467
- singleCatalogAgent?.isolation,
468
- ),
469
- );
470
- if (result.exitCode !== -1) {
471
- throw new Error(getResultOutput(result));
472
- }
473
- const runRef = result.runId === undefined ? result.agent : `#${result.runId} ${result.agent}`;
474
- if (params.wait && result.runId !== undefined) {
475
- const blocks = await awaitRunResults(runtime, [result.runId], signal, config.maxResultLines, ctx.cwd);
476
- return {
477
- content: [{ type: "text", text: `Started ${runRef} and waited in-turn.\n\n${blocks}` }],
478
- details: makeDetails("single", true)([result]),
479
- };
480
- }
481
- return {
482
- content: [{ type: "text", text: `Started ${runRef} in the background. It never blocks you — dispatch more independent units now or keep working; its result resumes you automatically when you are idle.${queuePacingNote()}` }],
483
- details: makeDetails("single", true)([result]),
484
- };
485
-
486
- },
487
-
488
- renderCall(args, theme) {
489
- if (args.tasks && args.tasks.length > 0) {
490
- let text = `${theme.fg("toolTitle", theme.bold("subagent "))}${theme.fg("accent", `parallel (${args.tasks.length})`)}`;
491
- for (const t of args.tasks.slice(0, 4)) {
492
- const preview = formatTaskSummary(t.task, 48);
493
- const isolation = defaultIsolationMode("parallel", t.agent, t.isolation) === "worktree" ? " [worktree]" : "";
494
- text += `\n ${theme.fg("accent", t.agent)}${theme.fg("dim", isolation)} ${theme.fg("dim", preview)}`;
495
- }
496
- if (args.tasks.length > 4) text += `\n ${theme.fg("dim", `… +${args.tasks.length - 4} more`)}`;
497
- return new Text(text, 0, 0);
498
- }
499
- const task: string = args.task ?? "";
500
- const preview = formatTaskSummary(task, 60);
501
- const isolation = args.isolation === "worktree" ? " [worktree]" : "";
502
- return new Text(
503
- `${theme.fg("toolTitle", theme.bold("subagent "))}${theme.fg("accent", args.agent ?? "?")}${theme.fg("dim", `${isolation}`)} ${theme.fg("dim", preview)}`,
504
- 0,
505
- 0,
506
- );
507
- },
508
-
509
- renderResult(result, _options, theme) {
510
- const details = result.details as SubagentDetails | undefined;
511
- if (!details || details.results.length === 0) return new Text(theme.fg("dim", "(no output)"), 0, 0);
512
-
513
- if (details.mode === "single") {
514
- const r = details.results[0];
515
- const pending = r.exitCode === -1;
516
- const icon = statusIcon(pending ? "running" : isFailedResult(r) ? "failed" : "done", theme);
517
- const usage = formatUsage(r.usage);
518
- const model = `${r.model ?? "?"}${r.modelFallbackFrom ? ` (main after ${r.modelFallbackFrom} failed)` : ""}`;
519
- const isolation = r.isolation === "worktree" ? ` · worktree ${r.integrationStatus ?? "active"}` : "";
520
- const runId = r.runId === undefined ? "" : `${theme.fg("dim", `#${r.runId}`)} `;
521
- const line = `${theme.fg("toolTitle", theme.bold("subagent "))}${icon} ${runId}${theme.fg("accent", r.agent)} ${theme.fg("dim", `· ${model}${r.thinking ? ` · thinking ${r.thinking}` : ""}${isolation}${pending ? " · background" : ""}${usage ? ` · ${usage}` : ""}`)}`;
522
- return new Text(line, 0, 0);
523
- }
524
-
525
- // Parallel mode: header + one compact line per agent
526
- const lines: string[] = [
527
- `${theme.fg("toolTitle", theme.bold("subagent "))}${theme.fg("accent", `parallel (${details.results.length})`)}`,
528
- ];
529
- for (const r of details.results) {
530
- const pending = r.exitCode === -1;
531
- const icon = statusIcon(pending ? "running" : isFailedResult(r) ? "failed" : "done", theme);
532
- const usage = formatUsage(r.usage);
533
- const model = `${r.model ?? "?"}${r.modelFallbackFrom ? ` (main after ${r.modelFallbackFrom} failed)` : ""}`;
534
- const isolation = r.isolation === "worktree" ? ` · worktree ${r.integrationStatus ?? "active"}` : "";
535
- const runId = r.runId === undefined ? "" : `${theme.fg("dim", `#${r.runId}`)} `;
536
- lines.push(` ${icon} ${runId}${theme.fg("accent", r.agent)} ${theme.fg("dim", `· ${model}${r.thinking ? ` · thinking ${r.thinking}` : ""}${isolation}${pending ? " · background" : ""}${usage ? ` · ${usage}` : ""}`)}`);
537
- }
538
- return new Text(lines.join("\n"), 0, 0);
539
- },
540
- });
541
- }
1
+ /**
2
+ * The `subagent` tool: dispatches the enabled agents (explorer, executor,
3
+ * plus custom roles) as isolated pi
4
+ * child processes, single or parallel. Owns the public dispatch contract and
5
+ * per-run status tracking. Stable thread generations, final integration, and
6
+ * completion ownership live in thread-lifecycle.ts.
7
+ */
8
+
9
+ import { StringEnum } from "@earendil-works/pi-ai";
10
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
11
+ import { Text } from "@earendil-works/pi-tui";
12
+ import { join, resolve } from "node:path";
13
+ import { Type } from "typebox";
14
+ import { discoverAgents, isWriteCapableAgent, resolveAgentTools, type AgentConfig } from "./agents.ts";
15
+ import { loadConfig, THINKING_LEVEL_VALUES, type ThinkingLevel } from "./config.ts";
16
+ import { formatCompletionBlock, formatUsage, queuedResult } from "./format.ts";
17
+ import {
18
+ formatTaskSummary,
19
+ formatToolActivity,
20
+ monitor,
21
+ statusIcon,
22
+ type RunView,
23
+ type RunWaitReason,
24
+ } from "./monitor.ts";
25
+ import type { SubagentRuntime } from "./runtime.ts";
26
+ import { persistThreadCheckpoint } from "./thread-lifecycle.ts";
27
+ import {
28
+ getProjectRoot,
29
+ getResultOutput,
30
+ isFailedResult,
31
+ runSingleAgentWithMainFallback,
32
+ type SingleResult,
33
+ type SubagentDetails,
34
+ type SubagentLiveEvent,
35
+ } from "./spawn.ts";
36
+ import {
37
+ createBackgroundDispatcher,
38
+ projectResultsRoot,
39
+ resolveDispatchModelRoute,
40
+ runInManagedRepositoryLane,
41
+ withWorktreeSystemPrompt,
42
+ type DispatchEnvironment,
43
+ } from "./thread-lifecycle.ts";
44
+ import type { IsolationMode } from "./worktree.ts";
45
+
46
+ export { isWorktreeCapableAgent, runInManagedRepositoryLane } from "./thread-lifecycle.ts";
47
+
48
+ const NON_BLANK_TASK_OPTIONS = { minLength: 1, pattern: "\\S" } as const;
49
+
50
+ const ISOLATION_DESCRIPTION =
51
+ "Filesystem isolation: shared uses the caller's working tree; worktree creates a detached temporary Git worktree (write-capable agents, including executor, only)";
52
+
53
+ const IsolationSchema = Type.Optional(
54
+ StringEnum(["shared", "worktree"] as const, { description: ISOLATION_DESCRIPTION }),
55
+ );
56
+
57
+ const ThinkingSchema = Type.Optional(
58
+ StringEnum(THINKING_LEVEL_VALUES, {
59
+ description:
60
+ "Optional reasoning strength for this task; omit to keep the agent's own level",
61
+ }),
62
+ );
63
+
64
+ const WaitSchema = Type.Optional(
65
+ Type.Boolean({
66
+ description:
67
+ "Block until every run started by this call settles, then return their results in-turn (each result still arrives as a completion message too). Only for one-shot (pi -p) sessions or a next step that needs these results within this turn.",
68
+ }),
69
+ );
70
+
71
+ const TaskItem = Type.Object({
72
+ agent: Type.String({ description: "Name of the agent to invoke" }),
73
+ task: Type.String({
74
+ ...NON_BLANK_TASK_OPTIONS,
75
+ description: "Self-contained task to delegate (the agent has no memory of this conversation)",
76
+ }),
77
+ cwd: Type.Optional(Type.String({ description: "Working directory for the agent process" })),
78
+ isolation: IsolationSchema,
79
+ thinking: ThinkingSchema,
80
+ });
81
+
82
+ const SubagentParams = Type.Object({
83
+ agent: Type.Optional(Type.String({ description: "Name of the agent to invoke (single mode)" })),
84
+ task: Type.Optional(
85
+ Type.String({ ...NON_BLANK_TASK_OPTIONS, description: "Self-contained task to delegate (single mode)" }),
86
+ ),
87
+ tasks: Type.Optional(Type.Array(TaskItem, { description: "Array of {agent, task} for parallel execution" })),
88
+ cwd: Type.Optional(Type.String({ description: "Working directory for the agent process (single mode)" })),
89
+ isolation: IsolationSchema,
90
+ thinking: ThinkingSchema,
91
+ wait: WaitSchema,
92
+ });
93
+
94
+ /** Roles that default to worktree isolation in parallel dispatches even when
95
+ * the live catalog cannot be consulted (render-only call sites). Custom
96
+ * write-capable agents join them via isWriteCapableAgent on the execute path. */
97
+ const WORKTREE_DEFAULT_AGENTS = new Set(["executor"]);
98
+
99
+ /** Resolve the default isolation for a dispatch. Precedence: an explicit
100
+ * per-call request, then the role's own frontmatter declaration (`worktree`
101
+ * honored for write-capable roles only; `shared` always), then the parallel
102
+ * write default — parallel write-capable agents get a detached worktree
103
+ * because shared writers serialize on the repository lane, so defaulting them
104
+ * to shared would turn one parallel batch into a convoy that also parks
105
+ * process slots. */
106
+ export function defaultIsolationMode(
107
+ mode: "single" | "parallel",
108
+ agentName: string,
109
+ requested?: IsolationMode,
110
+ writeCapable = WORKTREE_DEFAULT_AGENTS.has(agentName),
111
+ declared?: IsolationMode,
112
+ ): IsolationMode {
113
+ if (requested) return requested;
114
+ if (declared === "shared") return "shared";
115
+ if (declared === "worktree" && writeCapable) return "worktree";
116
+ return mode === "parallel" && writeCapable ? "worktree" : "shared";
117
+ }
118
+
119
+ /** In-turn wait behind dispatch `wait: true` — the escape hatch for one-shot
120
+ * `pi -p` parents that exit at end of turn: hold the call until every run it
121
+ * started settles, then hand back their result blocks. Interactive sessions
122
+ * never take this path; their results arrive as completion wake-ups. No
123
+ * timer: a waiter resolves the moment its run's result registers (children
124
+ * are bounded by the idle watchdog), an already-parked run answers
125
+ * immediately with its resume handle, and the turn's abort signal remains the
126
+ * escape hatch. */
127
+ export async function awaitRunResults(
128
+ runtime: SubagentRuntime,
129
+ runIds: number[],
130
+ signal: AbortSignal | undefined,
131
+ maxResultLines: number,
132
+ fallbackCwd: string,
133
+ ): Promise<string> {
134
+ const waitForRun = (runId: number): Promise<{ result?: SingleResult; note?: string }> => {
135
+ const already = runtime.settledRuns.get(runId);
136
+ if (already) return Promise.resolve({ result: already });
137
+ if (monitor.findRun(runId)?.status === "parked") {
138
+ return Promise.resolve({ note: `run #${runId} is parked at a stable checkpoint; use subagent_control resume to continue it` });
139
+ }
140
+ return new Promise((resolve) => {
141
+ let done = false;
142
+ let unsub: (() => void) | undefined;
143
+ const cleanup = (): void => {
144
+ if (unsub) unsub();
145
+ signal?.removeEventListener("abort", onAbort);
146
+ const listeners = runtime.settledListeners.get(runId);
147
+ if (listeners) {
148
+ listeners.delete(onSettled);
149
+ if (listeners.size === 0) runtime.settledListeners.delete(runId);
150
+ }
151
+ };
152
+ const finish = (outcome: { result?: SingleResult; note?: string }): void => {
153
+ if (done) return;
154
+ done = true;
155
+ cleanup();
156
+ resolve(outcome);
157
+ };
158
+ const onSettled = (result: SingleResult): void => finish({ result });
159
+ const onMonitor = (): void => {
160
+ const current = runtime.settledRuns.get(runId);
161
+ if (current) {
162
+ finish({ result: current });
163
+ return;
164
+ }
165
+ const live = monitor.findRun(runId);
166
+ if (live?.status === "parked") {
167
+ finish({ note: `run #${runId} was parked at a stable checkpoint; use subagent_control resume to continue it` });
168
+ return;
169
+ }
170
+ if (!live) {
171
+ // Removal is followed synchronously by registerRunResult in the
172
+ // finishing task; re-check on the next tick so the result wins.
173
+ setTimeout(() => {
174
+ const late = runtime.settledRuns.get(runId);
175
+ if (late) finish({ result: late });
176
+ else finish({ note: `run #${runId} was removed before its result was recorded (cancelled or session ended)` });
177
+ }, 0);
178
+ }
179
+ };
180
+ const onAbort = (): void => finish({ note: "wait aborted" });
181
+ let listeners = runtime.settledListeners.get(runId);
182
+ if (!listeners) {
183
+ listeners = new Set();
184
+ runtime.settledListeners.set(runId, listeners);
185
+ }
186
+ listeners.add(onSettled);
187
+ unsub = monitor.subscribe(onMonitor);
188
+ if (signal?.aborted) onAbort();
189
+ else signal?.addEventListener("abort", onAbort, { once: true });
190
+ });
191
+ };
192
+ const outcomes = await Promise.all(runIds.map(waitForRun));
193
+ return outcomes.map((outcome) =>
194
+ outcome.result
195
+ ? formatCompletionBlock(outcome.result, maxResultLines, { resultRoot: projectResultsRoot(runtime.configPath, outcome.result.projectCwd ?? fallbackCwd) })
196
+ : (outcome.note ?? "(no outcome)"),
197
+ ).join("\n\n");
198
+ }
199
+
200
+ export function registerSubagentTool(pi: ExtensionAPI, runtime: SubagentRuntime): void {
201
+ // Latest dispatch environment. The dispatcher is created once per process so
202
+ // restored threads can resume before any dispatch has run; each execute
203
+ // refreshes the fallback context, config, and agent catalog it resolves.
204
+ const environmentRef: { current: DispatchEnvironment | undefined } = { current: undefined };
205
+
206
+ // Finished runs leave the active monitor immediately. Their final findings
207
+ // are sent as a custom message that starts a follow-up turn.
208
+ const finishRun = (
209
+ runId: number,
210
+ status: "done" | "failed",
211
+ opts?: { silent?: boolean },
212
+ ): void => {
213
+ monitor.setStatus(runId, status); // stamps endedAt for the elapsed time
214
+ const run = monitor.removeRun(runId);
215
+ if (!run) return; // already finished stay idempotent
216
+ if (opts?.silent || !runtime.sessionActive) return;
217
+ const icon = status === "done" ? "✓" : "✗";
218
+ environmentRef.current?.ctx.ui.notify(`${icon} #${run.id} ${monitor.summarize(run)}`, status === "done" ? "info" : "error");
219
+ };
220
+
221
+ // Live sub-agent activity → concise one-line status ("thinking",
222
+ // "read src/index.ts", ...), never a raw args blob. The live handler
223
+ // only updates monitor state; the queue task owns terminal removal,
224
+ // notification, and lifecycle decisions.
225
+ const makeLiveHandler =
226
+ (runId: number, generation?: number) =>
227
+ (e: SubagentLiveEvent): void => {
228
+ if (generation !== undefined && runtime.threads.get(runId)?.generation !== generation) return;
229
+ switch (e.kind) {
230
+ case "status":
231
+ monitor.setStatus(runId, e.status);
232
+ // A fresh running segment refreshes the durable checkpoint (session
233
+ // path plus child pids) so a crash mid-generation still restores.
234
+ if (e.status === "running") {
235
+ const thread = runtime.threads.get(runId);
236
+ if (thread?.sessionId && thread.sessionDir) {
237
+ persistThreadCheckpoint(runtime, thread, "parked");
238
+ }
239
+ }
240
+ break;
241
+ case "model":
242
+ monitor.setModel(runId, e.model, e.fallbackFrom);
243
+ monitor.setThinking(runId, e.thinking);
244
+ break;
245
+ case "usage":
246
+ monitor.setUsage(runId, e.usage, e.model);
247
+ break;
248
+ case "session": {
249
+ runtime.retainSession({ sessionDir: e.sessionDir });
250
+ const thread = runtime.threads.get(runId);
251
+ if (thread && (generation === undefined || runtime.threads.get(runId)?.generation === generation)) {
252
+ thread.sessionId = e.sessionId;
253
+ thread.sessionDir = e.sessionDir;
254
+ persistThreadCheckpoint(runtime, thread, "parked");
255
+ }
256
+ break;
257
+ }
258
+ case "tool_start":
259
+ monitor.recordToolStart(runId, e.toolName, formatToolActivity(e.toolName, e.args));
260
+ break;
261
+ case "tool_end":
262
+ monitor.recordToolEnd(runId, e.toolName, e.isError);
263
+ break;
264
+ case "thinking":
265
+ monitor.setActivity(runId, "thinking");
266
+ break;
267
+ case "text":
268
+ // A text delta is model output, not a filesystem write.
269
+ monitor.setActivity(runId, "responding");
270
+ break;
271
+ }
272
+ };
273
+
274
+ const makeDetails =
275
+ (mode: "single" | "parallel", background = false) =>
276
+ (results: SingleResult[]): SubagentDetails => ({ mode, results, background });
277
+
278
+ /** Pacing note appended to dispatch confirmations whenever runs are actually
279
+ * waiting. Slot waits and repository-lane waits are stated separately with
280
+ * the real capacity: a lane-serialized shared writer or a starting child
281
+ * must never read as an exhausted pool, or the model stops dispatching while
282
+ * slots are free. Empty when nothing is waiting. */
283
+ const queuePacingNote = (): string => {
284
+ const runs = monitor.getRuns();
285
+ const queuedWith = (reason: RunWaitReason): number =>
286
+ runs.filter((run) => run.status === "queued" && run.waitReason === reason).length;
287
+ const slotWaiting = queuedWith("process-slot");
288
+ const laneWaiting = queuedWith("repository-lane");
289
+ if (slotWaiting === 0 && laneWaiting === 0) return "";
290
+ const executing = runs.filter((run) =>
291
+ run.status === "running" || run.status === "interrupting" || (run.status === "queued" && run.waitReason === "starting"),
292
+ ).length;
293
+ const capacity = runtime.backgroundQueue.capacity;
294
+ const freeSlots = Math.max(0, capacity - runtime.backgroundQueue.activeCount);
295
+ const parts = [`${executing} running`];
296
+ if (slotWaiting > 0) {
297
+ parts.push(`${slotWaiting} waiting for a free process slot (capacity ${capacity}); they start automatically as slots free`);
298
+ }
299
+ if (laneWaiting > 0) {
300
+ parts.push(
301
+ `${laneWaiting} shared-checkout writer${laneWaiting === 1 ? "" : "s"} waiting for the repository write lane — write serialization, not slot capacity` +
302
+ (slotWaiting === 0 ? ` (${freeSlots} of ${capacity} slots free; parallel writers avoid the lane via worktree isolation)` : ""),
303
+ );
304
+ }
305
+ return ` Pacing: ${parts.join(" · ")}. Keep dispatching independent units.`;
306
+ };
307
+
308
+ const startBackground = createBackgroundDispatcher({
309
+ runtime,
310
+ getEnvironment: () => {
311
+ if (!environmentRef.current) {
312
+ throw new Error("pi-subagents dispatch environment is not ready yet.");
313
+ }
314
+ return environmentRef.current;
315
+ },
316
+ finishRun,
317
+ makeLiveHandler,
318
+ makeDetails,
319
+ });
320
+ runtime.dispatcher = startBackground;
321
+
322
+ pi.registerTool({
323
+ name: "subagent",
324
+ label: "Subagent",
325
+ description: [
326
+ "Dispatch enabled agents as isolated leaf Pi child processes: single {agent, task} or parallel {tasks: [...]}. Dispatching never blocks your turn — runs proceed in the background and each completion resumes you automatically; never poll or restate delivered results.",
327
+ "Put every genuinely independent unit in one `tasks` array: there is no per-call cap, and runs beyond the machine's free process slots simply wait and start as slots free.",
328
+ "Parallel write-capable agents default to a detached Git worktree so writers run concurrently; explicit `shared` keeps the caller's checkout and serializes same-repository writers. Worktree setup failure never silently falls back to shared.",
329
+ "A configured child-model failure continues the retained session on the current main model.",
330
+ ].join(" "),
331
+ promptSnippet:
332
+ "Dispatch isolated background agents for recon, implementation, cleanup, docs sync, or result merging; never blocks your turn, and completions wake you automatically.",
333
+ parameters: SubagentParams,
334
+
335
+ async execute(_toolCallId, params, signal, _onUpdate, ctx) {
336
+ // Run ids are allocated below; restore raises the allocator above every
337
+ // id a durable record still owns, so a dispatch racing it could hand a
338
+ // fresh run the id of a parked thread and overwrite its record.
339
+ await runtime.durableRestore;
340
+ monitor.beginTurn();
341
+ const config = await loadConfig(runtime.configPath);
342
+
343
+ const discovery = discoverAgents(ctx.cwd, {
344
+ scope: config.agentScope,
345
+ enabledNames: config.enabledAgents,
346
+ projectTrusted: ctx.isProjectTrusted?.() === true,
347
+ });
348
+ const agents = discovery.agents;
349
+ // Refresh the dispatcher's fallback environment so control operations
350
+ // (resume of restored threads) never run on a stale context.
351
+ environmentRef.current = { ctx, config, agents };
352
+
353
+ const hasTasks = (params.tasks?.length ?? 0) > 0;
354
+ const hasSingle = Boolean(params.agent) && params.task !== undefined;
355
+
356
+ const catalog = agents.map((a) => a.name).join(", ") || "none";
357
+
358
+ if (Number(hasTasks) + Number(hasSingle) !== 1) {
359
+ return {
360
+ content: [
361
+ {
362
+ type: "text",
363
+ text: `Invalid parameters. Provide exactly one mode: single {agent, task} or parallel {tasks: [...]}. Enabled agents: ${catalog}.`,
364
+ },
365
+ ],
366
+ details: makeDetails("single")([]),
367
+ };
368
+ }
369
+
370
+ if (hasTasks) {
371
+ const blankTaskIndex = params.tasks?.findIndex(({ task }) => task.trim().length === 0) ?? -1;
372
+ if (blankTaskIndex !== -1) {
373
+ return {
374
+ content: [
375
+ {
376
+ type: "text",
377
+ text: `Invalid parameters. tasks[${blankTaskIndex}].task must contain at least one non-whitespace character. No background tasks were started. Enabled agents: ${catalog}.`,
378
+ },
379
+ ],
380
+ details: makeDetails("parallel")([]),
381
+ };
382
+ }
383
+ } else if (params.task?.trim().length === 0) {
384
+ return {
385
+ content: [
386
+ {
387
+ type: "text",
388
+ text: `Invalid parameters. task must contain at least one non-whitespace character. Enabled agents: ${catalog}.`,
389
+ },
390
+ ],
391
+ details: makeDetails("single")([]),
392
+ };
393
+ }
394
+
395
+ // Sub-agents run detached from the foreground turn: the editor stays
396
+ // available and completion messages later wake the main agent. The turn is
397
+ // NOT terminated here — the model can keep dispatching independent units
398
+ // or do its own work, and the background queue paces how many child
399
+ // processes actually run at once, so no per-call task cap is enforced.
400
+ if (params.tasks && params.tasks.length > 0) {
401
+ const results: SingleResult[] = [];
402
+ // Preserve caller order (and deterministic completion batching) while
403
+ // preparing each isolated filesystem before its queue entry can start.
404
+ for (const item of params.tasks) {
405
+ const catalogAgent = agents.find((candidate) => candidate.name === item.agent);
406
+ results.push(await startBackground(
407
+ item.agent,
408
+ item.task,
409
+ item.cwd,
410
+ defaultIsolationMode(
411
+ "parallel",
412
+ item.agent,
413
+ item.isolation as IsolationMode | undefined,
414
+ catalogAgent ? isWriteCapableAgent(catalogAgent) : undefined,
415
+ catalogAgent?.isolation,
416
+ ),
417
+ { thinking: item.thinking as ThinkingLevel | undefined },
418
+ ));
419
+ }
420
+ const startedRuns = results.filter((result) => result.exitCode === -1);
421
+ const started = startedRuns.length;
422
+ const startedRefs = startedRuns.map((result) =>
423
+ result.runId === undefined ? result.agent : `#${result.runId} ${result.agent}`,
424
+ );
425
+ const failureLines = results.flatMap((result, index) => {
426
+ if (result.exitCode === -1) return [];
427
+ const reason = getResultOutput(result).trim() || "unknown startup failure";
428
+ return [
429
+ `- tasks[${index}] (${params.tasks![index]!.agent}) failed to start: ${reason.replace(/\n/g, "\n ")}`,
430
+ ];
431
+ });
432
+ if (started === 0) {
433
+ // Pi marks custom-tool failures only when execute throws; returning an
434
+ // `isError` property is still a successful AgentToolResult.
435
+ throw new Error(`No background subagents were started.\n${failureLines.join("\n")}`);
436
+ }
437
+ if (params.wait) {
438
+ const startedIds = startedRuns
439
+ .map((result) => result.runId)
440
+ .filter((id): id is number => id !== undefined);
441
+ const blocks = await awaitRunResults(runtime, startedIds, signal, config.maxResultLines, ctx.cwd);
442
+ const text = [
443
+ `Started ${started} subagent${started === 1 ? "" : "s"} (${startedRefs.join(", ")}) and waited in-turn.`,
444
+ ...(failureLines.length > 0
445
+ ? [`${failureLines.length} task${failureLines.length === 1 ? "" : "s"} failed before launch:`, ...failureLines]
446
+ : []),
447
+ "",
448
+ blocks,
449
+ ].join("\n");
450
+ return {
451
+ content: [{ type: "text", text }],
452
+ details: makeDetails("parallel", true)(results),
453
+ };
454
+ }
455
+ const text = [
456
+ `Started ${started} background subagent${started === 1 ? "" : "s"}: ${startedRefs.join(", ")}. They run in the background and never block you — dispatch more independent units now or keep working; each result resumes you automatically when you are idle.`,
457
+ ...(failureLines.length > 0
458
+ ? [`${failureLines.length} task${failureLines.length === 1 ? "" : "s"} failed before launch:`, ...failureLines]
459
+ : []),
460
+ ].join("\n") + queuePacingNote();
461
+ return {
462
+ content: [{ type: "text", text }],
463
+ details: makeDetails("parallel", true)(results),
464
+ };
465
+ }
466
+
467
+ const singleCatalogAgent = agents.find((candidate) => candidate.name === params.agent);
468
+ const result = await startBackground(
469
+ params.agent as string,
470
+ params.task as string,
471
+ params.cwd,
472
+ defaultIsolationMode(
473
+ "single",
474
+ params.agent as string,
475
+ params.isolation as IsolationMode | undefined,
476
+ singleCatalogAgent ? isWriteCapableAgent(singleCatalogAgent) : undefined,
477
+ singleCatalogAgent?.isolation,
478
+ ),
479
+ { thinking: params.thinking as ThinkingLevel | undefined },
480
+ );
481
+ if (result.exitCode !== -1) {
482
+ throw new Error(getResultOutput(result));
483
+ }
484
+ const runRef = result.runId === undefined ? result.agent : `#${result.runId} ${result.agent}`;
485
+ if (params.wait && result.runId !== undefined) {
486
+ const blocks = await awaitRunResults(runtime, [result.runId], signal, config.maxResultLines, ctx.cwd);
487
+ return {
488
+ content: [{ type: "text", text: `Started ${runRef} and waited in-turn.\n\n${blocks}` }],
489
+ details: makeDetails("single", true)([result]),
490
+ };
491
+ }
492
+ return {
493
+ content: [{ type: "text", text: `Started ${runRef} in the background. It never blocks you dispatch more independent units now or keep working; its result resumes you automatically when you are idle.${queuePacingNote()}` }],
494
+ details: makeDetails("single", true)([result]),
495
+ };
496
+
497
+ },
498
+
499
+ renderCall(args, theme) {
500
+ if (args.tasks && args.tasks.length > 0) {
501
+ let text = `${theme.fg("toolTitle", theme.bold("subagent "))}${theme.fg("accent", `parallel (${args.tasks.length})`)}`;
502
+ for (const t of args.tasks.slice(0, 4)) {
503
+ const preview = formatTaskSummary(t.task, 48);
504
+ const isolation = defaultIsolationMode("parallel", t.agent, t.isolation) === "worktree" ? " [worktree]" : "";
505
+ text += `\n ${theme.fg("accent", t.agent)}${theme.fg("dim", isolation)} ${theme.fg("dim", preview)}`;
506
+ }
507
+ if (args.tasks.length > 4) text += `\n ${theme.fg("dim", `… +${args.tasks.length - 4} more`)}`;
508
+ return new Text(text, 0, 0);
509
+ }
510
+ const task: string = args.task ?? "";
511
+ const preview = formatTaskSummary(task, 60);
512
+ const isolation = args.isolation === "worktree" ? " [worktree]" : "";
513
+ return new Text(
514
+ `${theme.fg("toolTitle", theme.bold("subagent "))}${theme.fg("accent", args.agent ?? "?")}${theme.fg("dim", `${isolation}`)} ${theme.fg("dim", preview)}`,
515
+ 0,
516
+ 0,
517
+ );
518
+ },
519
+
520
+ renderResult(result, _options, theme) {
521
+ const details = result.details as SubagentDetails | undefined;
522
+ if (!details || details.results.length === 0) return new Text(theme.fg("dim", "(no output)"), 0, 0);
523
+
524
+ if (details.mode === "single") {
525
+ const r = details.results[0];
526
+ const pending = r.exitCode === -1;
527
+ const icon = statusIcon(pending ? "running" : isFailedResult(r) ? "failed" : "done", theme);
528
+ const usage = formatUsage(r.usage);
529
+ const model = `${r.model ?? "?"}${r.modelFallbackFrom ? ` (main after ${r.modelFallbackFrom} failed)` : ""}`;
530
+ const isolation = r.isolation === "worktree" ? ` · worktree ${r.integrationStatus ?? "active"}` : "";
531
+ const runId = r.runId === undefined ? "" : `${theme.fg("dim", `#${r.runId}`)} `;
532
+ const line = `${theme.fg("toolTitle", theme.bold("subagent "))}${icon} ${runId}${theme.fg("accent", r.agent)} ${theme.fg("dim", `· ${model}${r.thinking ? ` · thinking ${r.thinking}` : ""}${isolation}${pending ? " · background" : ""}${usage ? ` · ${usage}` : ""}`)}`;
533
+ return new Text(line, 0, 0);
534
+ }
535
+
536
+ // Parallel mode: header + one compact line per agent
537
+ const lines: string[] = [
538
+ `${theme.fg("toolTitle", theme.bold("subagent "))}${theme.fg("accent", `parallel (${details.results.length})`)}`,
539
+ ];
540
+ for (const r of details.results) {
541
+ const pending = r.exitCode === -1;
542
+ const icon = statusIcon(pending ? "running" : isFailedResult(r) ? "failed" : "done", theme);
543
+ const usage = formatUsage(r.usage);
544
+ const model = `${r.model ?? "?"}${r.modelFallbackFrom ? ` (main after ${r.modelFallbackFrom} failed)` : ""}`;
545
+ const isolation = r.isolation === "worktree" ? ` · worktree ${r.integrationStatus ?? "active"}` : "";
546
+ const runId = r.runId === undefined ? "" : `${theme.fg("dim", `#${r.runId}`)} `;
547
+ lines.push(` ${icon} ${runId}${theme.fg("accent", r.agent)} ${theme.fg("dim", `· ${model}${r.thinking ? ` · thinking ${r.thinking}` : ""}${isolation}${pending ? " · background" : ""}${usage ? ` · ${usage}` : ""}`)}`);
548
+ }
549
+ return new Text(lines.join("\n"), 0, 0);
550
+ },
551
+ });
552
+ }