@ferris1225/pi-subagents 4.1.8 → 4.1.9

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,746 +1,721 @@
1
- /**
2
- * The `subagent` tool: dispatches explorer/worker/cleaner/documenter/reviewer agents as isolated pi
3
- * child processes, single or parallel. Owns the public dispatch contract,
4
- * per-run status tracking, managed worker/cleaner → reviewer workflows with a
5
- * conditional documenter, bounded worker/reviewer fix rounds, and internal
6
- * step launching. Stable
7
- * thread generations, final integration, and completion ownership live in
8
- * thread-lifecycle.ts.
9
- */
10
-
11
- import { StringEnum } from "@earendil-works/pi-ai";
12
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
13
- import { Text } from "@earendil-works/pi-tui";
14
- import { realpath } from "node:fs/promises";
15
- import { resolve } from "node:path";
16
- import { Type } from "typebox";
17
- import { discoverAgents, resolveAgentTools, type AgentConfig } from "./agents.ts";
18
- import { MAX_CONCURRENT_SUBAGENTS } from "./background.ts";
19
- import { loadConfig } from "./config.ts";
20
- import { formatUsage, queuedResult } from "./format.ts";
21
- import {
22
- buildFinalDocumenterBrief,
23
- buildFinalReviewBrief,
24
- buildFixTaskBrief,
25
- buildReReviewBrief,
26
- documentationDisposition,
27
- MAX_FIX_ROUNDS,
28
- type ChainStep,
29
- type ManagedWorkflowOutcome,
30
- } from "./fixloop.ts";
31
- import {
32
- formatTaskSummary,
33
- formatToolActivity,
34
- monitor,
35
- statusIcon,
36
- type RunChainMeta,
37
- type WorkflowStage,
38
- type WorkflowStageStatus,
39
- } from "./monitor.ts";
40
- import type { SubagentRuntime } from "./runtime.ts";
41
- import {
42
- getResultOutput,
43
- isFailedResult,
44
- reviewVerdict,
45
- runSingleAgentWithMainFallback,
46
- type SingleResult,
47
- type SubagentDetails,
48
- type SubagentLiveEvent,
49
- } from "./spawn.ts";
50
- import {
51
- createBackgroundDispatcher,
52
- resolveDispatchModelRoute,
53
- withWorktreeSystemPrompt,
54
- type ManagedWorkflowRequest,
55
- } from "./thread-lifecycle.ts";
56
- import { resolveRepositoryRoot, type IsolationMode } from "./worktree.ts";
57
-
58
- export { FORK_CONTINUATION_PROMPT, isWorktreeCapableAgent } from "./thread-lifecycle.ts";
59
-
60
- const NON_BLANK_TASK_OPTIONS = { minLength: 1, pattern: "\\S" } as const;
61
-
62
- const ISOLATION_DESCRIPTION =
63
- "Filesystem isolation: shared uses the caller's working tree; worktree creates a detached temporary Git worktree (write-capable agents, including worker, cleaner, and documenter, only)";
64
-
65
- const IsolationSchema = Type.Optional(
66
- StringEnum(["shared", "worktree"] as const, { description: ISOLATION_DESCRIPTION }),
67
- );
68
-
69
- const TaskItem = Type.Object({
70
- agent: Type.String({ description: "Name of the agent to invoke" }),
71
- task: Type.String({
72
- ...NON_BLANK_TASK_OPTIONS,
73
- description: "Self-contained task to delegate (the agent has no memory of this conversation)",
74
- }),
75
- cwd: Type.Optional(Type.String({ description: "Working directory for the agent process" })),
76
- isolation: IsolationSchema,
77
- });
78
-
79
- const SubagentParams = Type.Object({
80
- agent: Type.Optional(Type.String({ description: "Name of the agent to invoke (single mode)" })),
81
- task: Type.Optional(
82
- Type.String({ ...NON_BLANK_TASK_OPTIONS, description: "Self-contained task to delegate (single mode)" }),
83
- ),
84
- tasks: Type.Optional(Type.Array(TaskItem, { description: "Array of {agent, task} for parallel execution" })),
85
- cwd: Type.Optional(Type.String({ description: "Working directory for the agent process (single mode)" })),
86
- isolation: IsolationSchema,
87
- });
88
-
89
- export function defaultIsolationMode(mode: "single" | "parallel", agentName: string, requested?: IsolationMode): IsolationMode {
90
- if (requested) return requested;
91
- return mode === "parallel" && agentName === "worker" ? "worktree" : "shared";
92
- }
93
-
94
- function workflowStageStatus(result: SingleResult): WorkflowStageStatus {
95
- if (isFailedResult(result)) return "failed";
96
- if (result.agent !== "reviewer") return "done";
97
- const verdict = reviewVerdict(getResultOutput(result));
98
- if (verdict === "fail") return "changes";
99
- return verdict === "pass" ? "done" : "failed";
100
- }
101
-
102
- const managedRepositoryRootTails = new Map<string, Promise<void>>();
103
-
104
- async function canonicalManagedRepositoryRoot(cwd: string): Promise<string> {
105
- try {
106
- // Repository identity does not depend on HEAD: empty repositories must
107
- // serialize root and nested cwd requests under the same lane too.
108
- return await resolveRepositoryRoot(cwd);
109
- } catch {
110
- try {
111
- return await realpath(resolve(cwd));
112
- } catch {
113
- return resolve(cwd);
114
- }
115
- }
116
- }
117
-
118
- /** Run one operation under the canonical original-repository lane.
119
- *
120
- * Shared managed generations use the abortable overload for their complete
121
- * writer/reviewer workflow. Isolated generations use the non-abortable overload
122
- * only for their final worktree apply, so model work remains parallel while the
123
- * original checkout mutation cannot race a shared writer or reviewer snapshot.
124
- */
125
- async function runInManagedRepositoryLane<T>(
126
- cwd: string,
127
- task: () => Promise<T>,
128
- ): Promise<T>;
129
- async function runInManagedRepositoryLane<T>(
130
- cwd: string,
131
- task: () => Promise<T>,
132
- signal: AbortSignal,
133
- ): Promise<T | undefined>;
134
- async function runInManagedRepositoryLane<T>(
135
- cwd: string,
136
- task: () => Promise<T>,
137
- signal?: AbortSignal,
138
- ): Promise<T | undefined> {
139
- if (signal?.aborted) return undefined;
140
- const root = await canonicalManagedRepositoryRoot(cwd);
141
- const key = process.platform === "win32" ? root.toLowerCase() : root;
142
- const previous = managedRepositoryRootTails.get(key) ?? Promise.resolve();
143
- let release!: () => void;
144
- const gate = new Promise<void>((resolveGate) => {
145
- release = resolveGate;
146
- });
147
- const tail = previous.catch(() => undefined).then(() => gate);
148
- managedRepositoryRootTails.set(key, tail);
149
- let onAbort: (() => void) | undefined;
150
- try {
151
- if (signal) {
152
- await Promise.race([
153
- previous.catch(() => undefined),
154
- new Promise<void>((resolveAborted) => {
155
- if (signal.aborted) resolveAborted();
156
- else {
157
- onAbort = resolveAborted;
158
- signal.addEventListener("abort", onAbort, { once: true });
159
- }
160
- }),
161
- ]);
162
- } else {
163
- await previous.catch(() => undefined);
164
- }
165
- if (signal?.aborted) return undefined;
166
- return await task();
167
- } finally {
168
- if (signal && onAbort) signal.removeEventListener("abort", onAbort);
169
- release();
170
- // An aborted waiter may finish before the prior owner. Keep its chained
171
- // tail installed until that owner also settles, otherwise a newcomer could
172
- // observe an empty map and race the still-running workflow.
173
- void tail.then(() => {
174
- if (managedRepositoryRootTails.get(key) === tail) managedRepositoryRootTails.delete(key);
175
- });
176
- }
177
- }
178
-
179
- export function registerSubagentTool(pi: ExtensionAPI, runtime: SubagentRuntime): void {
180
- pi.registerTool({
181
- name: "subagent",
182
- label: "Subagent",
183
- description: [
184
- "Dispatch enabled specialized agents as isolated leaf Pi child processes, singly or in parallel; keep small known-target work in the main thread with direct tools.",
185
- "Built-ins: explorer for broad read-only reconnaissance (a retrieval index, never a gate); worker for implementation; cleaner as a separate explicitly authorized cleanup/removal/simplification/deduplication entry; documenter for explicit docs/comments work or conditional final diff sync; reviewer for generic read-only assessments and independent code gates.",
186
- "Work starts in the background. Successful worker/cleaner runs keep one enabled reviewer gate and bounded fix loop; documenter runs afterward only when REVIEW_PASS reports DOCUMENTATION: NEEDED or omits the marker, with a reviewer-disabled fallback. A top-level documenter delivers directly. Results resume the main agent and are already shown, so do not poll, duplicate downstream roles, or restate them.",
187
- "Single tasks default to shared; parallel workers default to detached Git worktrees. Only write-capable agents can use worktree isolation, and failures never fall back silently to shared.",
188
- "A selected-model or provider failure continues the retained session on the current main model; ordinary tool/task failures do not.",
189
- "Use subagent_control to steer/retarget an active top-level child, park/stop a managed downstream stage, or resume/fork retained context by stable run id.",
190
- ].join(" "),
191
- promptSnippet:
192
- "Dispatch isolated background agents for broad recon, self-contained implementation, authorized cleanup, explicit docs, or independent review; keep small known-target work on direct tools. Worker/cleaner gates and only needed/conservative docs sync run automatically, results resume automatically, and each workflow delivers once.",
193
- parameters: SubagentParams,
194
-
195
- async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
196
- monitor.beginTurn();
197
- const config = await loadConfig(runtime.configPath);
198
-
199
- // Finished runs leave the active monitor immediately. Their final findings
200
- // are sent as a custom message that starts a follow-up turn.
201
- const finishRun = (
202
- runId: number,
203
- status: "done" | "failed",
204
- opts?: { silent?: boolean },
205
- ): void => {
206
- monitor.setStatus(runId, status); // stamps endedAt for the elapsed time
207
- const run = monitor.removeRun(runId);
208
- if (!run) return; // already finished stay idempotent
209
- if (opts?.silent || !runtime.sessionActive) return;
210
- const icon = status === "done" ? "✓" : "✗";
211
- ctx.ui.notify(`${icon} #${run.id} ${monitor.summarize(run)}`, status === "done" ? "info" : "error");
212
- };
213
-
214
- // Live sub-agent activity → concise one-line status ("thinking",
215
- // "read src/index.ts", ...), never a raw args blob. The live handler
216
- // only updates monitor state; the queue task / launchInWorkflow owns
217
- // terminal removal, notification, and downstream workflow decisions.
218
- const makeLiveHandler =
219
- (runId: number, generation?: number) =>
220
- (e: SubagentLiveEvent): void => {
221
- if (generation !== undefined && runtime.threads.get(runId)?.generation !== generation) return;
222
- switch (e.kind) {
223
- case "status":
224
- monitor.setStatus(runId, e.status);
225
- break;
226
- case "model":
227
- monitor.setModel(runId, e.model, e.fallbackFrom);
228
- monitor.setThinking(runId, e.thinking);
229
- break;
230
- case "usage":
231
- monitor.setUsage(runId, e.usage, e.model);
232
- break;
233
- case "tool_start":
234
- monitor.recordToolStart(runId, e.toolName, formatToolActivity(e.toolName, e.args));
235
- break;
236
- case "tool_end":
237
- monitor.recordToolEnd(runId, e.toolName, e.isError);
238
- break;
239
- case "thinking":
240
- monitor.setActivity(runId, "thinking");
241
- break;
242
- case "text":
243
- // A text delta is model output, not a filesystem write.
244
- monitor.setActivity(runId, "responding");
245
- break;
246
- }
247
- };
248
-
249
- const discovery = discoverAgents(ctx.cwd, {
250
- scope: config.agentScope,
251
- enabledNames: config.enabledAgents,
252
- projectTrusted: ctx.isProjectTrusted?.() === true,
253
- });
254
- const agents = discovery.agents;
255
-
256
- const hasTasks = (params.tasks?.length ?? 0) > 0;
257
- const hasSingle = Boolean(params.agent) && params.task !== undefined;
258
-
259
- const makeDetails =
260
- (mode: "single" | "parallel", background = false) =>
261
- (results: SingleResult[]): SubagentDetails => ({ mode, results, background });
262
-
263
- const catalog = agents.map((a) => a.name).join(", ") || "none";
264
-
265
- if (Number(hasTasks) + Number(hasSingle) !== 1) {
266
- return {
267
- content: [
268
- {
269
- type: "text",
270
- text: `Invalid parameters. Provide exactly one mode: single {agent, task} or parallel {tasks: [...]}. Enabled agents: ${catalog}.`,
271
- },
272
- ],
273
- details: makeDetails("single")([]),
274
- };
275
- }
276
-
277
- if (hasTasks) {
278
- const blankTaskIndex = params.tasks?.findIndex(({ task }) => task.trim().length === 0) ?? -1;
279
- if (blankTaskIndex !== -1) {
280
- return {
281
- content: [
282
- {
283
- type: "text",
284
- text: `Invalid parameters. tasks[${blankTaskIndex}].task must contain at least one non-whitespace character. No background tasks were started. Enabled agents: ${catalog}.`,
285
- },
286
- ],
287
- details: makeDetails("parallel")([]),
288
- };
289
- }
290
- } else if (params.task?.trim().length === 0) {
291
- return {
292
- content: [
293
- {
294
- type: "text",
295
- text: `Invalid parameters. task must contain at least one non-whitespace character. Enabled agents: ${catalog}.`,
296
- },
297
- ],
298
- details: makeDetails("single")([]),
299
- };
300
- }
301
-
302
- /** Launch one workflow-internal child in a fresh model context. It sees the
303
- * parent's exact repository/worktree state and is registered by its own id,
304
- * but never enters top-level lifecycle policy or completion delivery. */
305
- const launchInWorkflow = async (
306
- request: ManagedWorkflowRequest,
307
- agentName: string,
308
- task: string,
309
- meta: RunChainMeta,
310
- ): Promise<{ runId: number; result: SingleResult }> => {
311
- const discoveredAgent = request.agents.find((candidate) => candidate.name === agentName);
312
- if (!discoveredAgent) {
313
- throw new Error(`Managed workflow requires enabled agent "${agentName}", but discovery did not provide it.`);
314
- }
315
- const resolveLiveAgentTools = (candidate: AgentConfig): AgentConfig =>
316
- resolveAgentTools({ ...candidate, tools: discoveredAgent.tools }, runtime.getActiveTools());
317
- const agent = resolveLiveAgentTools(discoveredAgent);
318
- // Workflow policy (fix-round caps, agents) stays fixed for the chain,
319
- // but model/thinking routes are re-read per stage so config edits
320
- // apply to stages that have not launched yet.
321
- const stageConfig = await loadConfig(runtime.configPath).catch(() => request.config);
322
- const resolvedRoute = resolveDispatchModelRoute(agent, stageConfig, request.ctx);
323
- const route = request.isolation === "worktree"
324
- ? { ...resolvedRoute, agent: withWorktreeSystemPrompt(resolvedRoute.agent) }
325
- : resolvedRoute;
326
- const thinkingLevel = route.thinkingLevel;
327
- const runId = monitor.addRun(agent.name, task, route.agent.model, thinkingLevel, {
328
- ...meta,
329
- isolation: request.isolation,
330
- ...(request.worktreeId ? { worktreeId: request.worktreeId } : {}),
331
- });
332
- const onLive = makeLiveHandler(runId);
333
- try {
334
- const result = await runSingleAgentWithMainFallback(
335
- {
336
- defaultCwd: request.executionCwd,
337
- cwd: request.executionCwd,
338
- agent: route.agent,
339
- resolveAgentForAttempt: resolveLiveAgentTools,
340
- agentName,
341
- task,
342
- thinkingLevel,
343
- thinkingLevelForModel: route.thinkingLevelForModel,
344
- signal: request.signal,
345
- onLive,
346
- makeDetails: makeDetails("single", true),
347
- idleTimeoutMs: stageConfig.idleTimeoutSec * 1000,
348
- },
349
- route.mainFallbackRef,
350
- );
351
- result.runId = runId;
352
- result.projectCwd = request.projectCwd;
353
- result.isolation = request.isolation;
354
- runtime.retainSession(result);
355
- monitor.setModel(runId, result.model, result.modelFallbackFrom);
356
- monitor.setThinking(runId, result.thinking);
357
- finishRun(runId, isFailedResult(result) ? "failed" : "done", { silent: true });
358
- runtime.registerRunResult(runId, result);
359
- return { runId, result };
360
- } catch (error) {
361
- finishRun(runId, "failed", { silent: true });
362
- const errorMessage = error instanceof Error ? error.message : String(error);
363
- const crashed: SingleResult = {
364
- ...queuedResult(route.agent, task, thinkingLevel),
365
- runId,
366
- projectCwd: request.projectCwd,
367
- isolation: request.isolation,
368
- exitCode: 1,
369
- stderr: errorMessage,
370
- stopReason: request.signal.aborted ? "aborted" : "error",
371
- errorMessage,
372
- dispatchFailed: true,
373
- };
374
- runtime.registerRunResult(runId, crashed);
375
- return { runId, result: crashed };
376
- }
377
- };
378
-
379
- /** Drop any in-flight internal row. Normal internal settlement already
380
- * removes rows; this is a cancellation/crash guard. */
381
- const removeWorkflowGroup = (groupId: string): void => {
382
- for (const run of [...monitor.getRuns()]) {
383
- if (run.groupId === groupId) monitor.removeRun(run.id);
384
- }
385
- };
386
-
387
- /** Run every downstream role inline under the parent generation's queue
388
- * controller. That gives park/stop/shutdown one lifecycle owner and keeps
389
- * isolated worktrees unintegrated until the final reviewer settles. */
390
- const runManagedWorkflow = async (
391
- request: ManagedWorkflowRequest,
392
- ): Promise<ManagedWorkflowOutcome> => {
393
- const initialStepRunId = monitor.reserveRunId();
394
- const initialStepResult: SingleResult = {
395
- ...request.initialResult,
396
- runId: initialStepRunId,
397
- };
398
- runtime.registerRunResult(initialStepRunId, initialStepResult);
399
- const steps: ChainStep[] = [{
400
- runId: initialStepRunId,
401
- result: initialStepResult,
402
- relation: request.plan.initialRelation,
403
- }];
404
- const enabled = (name: string): boolean =>
405
- request.agents.some((candidate) => candidate.name === name);
406
- const canContinue = (): boolean => runtime.sessionActive && !request.signal.aborted;
407
-
408
- // Keep a live parent-owned projection because settled internal rows are
409
- // intentionally removed. Only real/currently planned stages enter it.
410
- const initialStageRelation = initialStepResult.agent === "worker"
411
- ? "implement"
412
- : initialStepResult.agent === "cleaner"
413
- ? "cleanup"
414
- : "review";
415
- const workflowStages: WorkflowStage[] = [{
416
- agent: initialStepResult.agent,
417
- relation: initialStageRelation,
418
- status: workflowStageStatus(initialStepResult),
419
- }];
420
- let reviewStage: WorkflowStage | undefined;
421
- if (request.plan.kind === "post-writer" && enabled("reviewer")) {
422
- reviewStage = { agent: "reviewer", relation: "review", status: "pending" };
423
- workflowStages.push(reviewStage);
424
- }
425
- let documentationStage: WorkflowStage | undefined;
426
- if (enabled("documenter")) {
427
- documentationStage = { agent: "documenter", relation: "docs", status: "pending" };
428
- workflowStages.push(documentationStage);
429
- }
430
- const publishWorkflowStages = (): void => {
431
- monitor.setWorkflowStages(request.parentRunId, workflowStages);
432
- };
433
- const insertBeforeDocumentation = (stage: WorkflowStage): void => {
434
- const documentationIndex = documentationStage
435
- ? workflowStages.indexOf(documentationStage)
436
- : -1;
437
- if (documentationIndex === -1) workflowStages.push(stage);
438
- else workflowStages.splice(documentationIndex, 0, stage);
439
- };
440
- const removeDocumentationStage = (): void => {
441
- if (!documentationStage) return;
442
- const index = workflowStages.indexOf(documentationStage);
443
- if (index !== -1) workflowStages.splice(index, 1);
444
- documentationStage = undefined;
445
- publishWorkflowStages();
446
- };
447
- publishWorkflowStages();
448
-
449
- const launchStep = async (
450
- agentName: string,
451
- task: string,
452
- relation: string,
453
- projection: {
454
- stage?: WorkflowStage;
455
- timelineRelation?: string;
456
- childRelation?: string;
457
- } = {},
458
- ): Promise<SingleResult> => {
459
- if (!enabled(agentName)) {
460
- throw new Error(`Managed workflow cannot launch disabled or missing agent "${agentName}".`);
461
- }
462
- const stage: WorkflowStage = projection.stage ?? {
463
- agent: agentName,
464
- relation: projection.timelineRelation ?? relation,
465
- status: "pending",
466
- };
467
- if (!projection.stage) insertBeforeDocumentation(stage);
468
- stage.status = "active";
469
- publishWorkflowStages();
470
- try {
471
- const step = await launchInWorkflow(request, agentName, task, {
472
- groupId: request.groupId,
473
- relationLabel: projection.childRelation ?? relation,
474
- parentRunId: request.parentRunId,
475
- });
476
- stage.status = workflowStageStatus(step.result);
477
- publishWorkflowStages();
478
- request.rememberLatest(step.result);
479
- steps.push({ ...step, relation });
480
- return step.result;
481
- } catch (error) {
482
- stage.status = "failed";
483
- publishWorkflowStages();
484
- throw error;
485
- }
486
- };
487
-
488
- /** Bounded worker → reviewer fix rounds. A conditional documentation sync
489
- * deliberately stays out of the rounds: code fixes would invalidate it,
490
- * and the terminal review classifies whether the settled diff needs one. */
491
- const runFixRounds = async (
492
- triggeringReviewer: SingleResult,
493
- ): Promise<{ lastReview?: SingleResult; lastWorker?: SingleResult }> => {
494
- let lastReviewer = triggeringReviewer;
495
- const outcome: { lastReview?: SingleResult; lastWorker?: SingleResult } = {};
496
- for (let round = 1; round <= MAX_FIX_ROUNDS; round++) {
497
- if (!canContinue()) break;
498
- const fixRelation = `fix ${round}/${MAX_FIX_ROUNDS}`;
499
- const workerResult = await launchStep(
500
- "worker",
501
- buildFixTaskBrief(lastReviewer, round, MAX_FIX_ROUNDS),
502
- `fix round ${round}`,
503
- { timelineRelation: fixRelation, childRelation: fixRelation },
504
- );
505
- if (isFailedResult(workerResult) || !canContinue()) break;
506
- outcome.lastWorker = workerResult;
507
-
508
- const reReviewRelation = `re-review ${round}/${MAX_FIX_ROUNDS}`;
509
- const reviewResult = await launchStep(
510
- "reviewer",
511
- buildReReviewBrief(lastReviewer, round, workerResult, {
512
- documenterPending: enabled("documenter"),
513
- }),
514
- `re-review round ${round}`,
515
- { timelineRelation: reReviewRelation, childRelation: reReviewRelation },
516
- );
517
- if (isFailedResult(reviewResult) || !canContinue()) break;
518
- outcome.lastReview = reviewResult;
519
- const verdict = reviewVerdict(getResultOutput(reviewResult));
520
- // REVIEW_PASS settles. No verdict is advisory/malformed and must never
521
- // trigger another writer. Only an explicit REVIEW_FAIL consumes a fix.
522
- if (verdict !== "fail") break;
523
- lastReviewer = reviewResult;
524
- }
525
- return outcome;
526
- };
527
-
528
- /** Run the low-cost final documentation sync only when the terminal REVIEW_PASS
529
- * reports drift or omits the new marker. A failed process, missing verdict, or
530
- * REVIEW_FAIL never writes docs. With no reviewer, retain the conservative
531
- * writer → documenter fallback. */
532
- const runFinalDocumentation = async (
533
- lastWriterResult: SingleResult | undefined,
534
- finalReviewResult: SingleResult | undefined,
535
- ): Promise<void> => {
536
- if (!canContinue() || !enabled("documenter")) return;
537
- if (lastWriterResult?.agent === "documenter") {
538
- removeDocumentationStage();
539
- return;
540
- }
541
- if (finalReviewResult) {
542
- if (isFailedResult(finalReviewResult)) {
543
- removeDocumentationStage();
544
- return;
545
- }
546
- const reviewOutput = getResultOutput(finalReviewResult);
547
- if (
548
- reviewVerdict(reviewOutput) !== "pass" ||
549
- documentationDisposition(reviewOutput) === "clean"
550
- ) {
551
- removeDocumentationStage();
552
- return;
553
- }
554
- }
555
- documentationStage ??= { agent: "documenter", relation: "docs", status: "pending" };
556
- if (!workflowStages.includes(documentationStage)) workflowStages.push(documentationStage);
557
- await launchStep(
558
- "documenter",
559
- buildFinalDocumenterBrief(lastWriterResult, finalReviewResult),
560
- "final documentation sync",
561
- { stage: documentationStage },
562
- );
563
- };
564
-
565
- try {
566
- // Park/stop/shutdown may win after the top-level child settles but
567
- // before this continuation starts. Preserve that stable checkpoint and
568
- // never create an already-aborted downstream child.
569
- if (!canContinue()) return { kind: request.plan.kind, steps };
570
- if (request.plan.kind === "auto-fix") {
571
- const fixOutcome = await runFixRounds(initialStepResult);
572
- await runFinalDocumentation(fixOutcome.lastWorker, fixOutcome.lastReview ?? initialStepResult);
573
- } else if (request.plan.kind === "review-pass-sync") {
574
- // The direct passing review already gated the pending code. Its
575
- // disposition requested (or conservatively defaulted to) one docs sync.
576
- await runFinalDocumentation(undefined, initialStepResult);
577
- } else if (enabled("reviewer")) {
578
- const gateReview = await launchStep(
579
- "reviewer",
580
- buildFinalReviewBrief(initialStepResult, { documenterPending: enabled("documenter") }),
581
- "final review",
582
- { stage: reviewStage },
583
- );
584
- let fixOutcome: Awaited<ReturnType<typeof runFixRounds>> = {};
585
- if (
586
- !isFailedResult(gateReview) &&
587
- canContinue() &&
588
- reviewVerdict(getResultOutput(gateReview)) === "fail" &&
589
- enabled("worker")
590
- ) {
591
- fixOutcome = await runFixRounds(gateReview);
592
- }
593
- await runFinalDocumentation(
594
- fixOutcome.lastWorker ?? initialStepResult,
595
- fixOutcome.lastReview ?? gateReview,
596
- );
597
- } else {
598
- // No gate configured: the documenter is the only downstream stage.
599
- await runFinalDocumentation(initialStepResult, undefined);
600
- }
601
- return { kind: request.plan.kind, steps };
602
- } finally {
603
- removeWorkflowGroup(request.groupId);
604
- }
605
- };
606
-
607
- const startBackground = createBackgroundDispatcher({
608
- runtime,
609
- ctx,
610
- config,
611
- agents,
612
- finishRun,
613
- makeLiveHandler,
614
- makeDetails,
615
- runManagedWorkflow,
616
- runInManagedRepositoryLane,
617
- });
618
-
619
- // Sub-agents intentionally detach from the foreground turn. This makes the
620
- // editor available immediately; completion messages later wake the main agent.
621
- if (params.tasks && params.tasks.length > 0) {
622
- if (params.tasks.length > MAX_CONCURRENT_SUBAGENTS) {
623
- return {
624
- content: [
625
- {
626
- type: "text",
627
- text: `Too many parallel tasks (${params.tasks.length}). Max is ${MAX_CONCURRENT_SUBAGENTS}.`,
628
- },
629
- ],
630
- details: makeDetails("parallel", true)([]),
631
- };
632
- }
633
-
634
- const results: SingleResult[] = [];
635
- // Preserve caller order (and deterministic completion batching) while
636
- // preparing each isolated filesystem before its queue entry can start.
637
- for (const item of params.tasks) {
638
- results.push(await startBackground(
639
- item.agent,
640
- item.task,
641
- item.cwd,
642
- defaultIsolationMode("parallel", item.agent, item.isolation as IsolationMode | undefined),
643
- ));
644
- }
645
- const startedRuns = results.filter((result) => result.exitCode === -1);
646
- const started = startedRuns.length;
647
- const startedRefs = startedRuns.map((result) =>
648
- result.runId === undefined ? result.agent : `#${result.runId} ${result.agent}`,
649
- );
650
- const failureLines = results.flatMap((result, index) => {
651
- if (result.exitCode === -1) return [];
652
- const reason = getResultOutput(result).trim() || "unknown startup failure";
653
- return [
654
- `- tasks[${index}] (${params.tasks![index]!.agent}) failed to start: ${reason.replace(/\n/g, "\n ")}`,
655
- ];
656
- });
657
- if (started === 0) {
658
- // Pi marks custom-tool failures only when execute throws; returning an
659
- // `isError` property is still a successful AgentToolResult.
660
- throw new Error(`No background subagents were started.\n${failureLines.join("\n")}`);
661
- }
662
- const text = [
663
- `Started ${started} background subagent${started === 1 ? "" : "s"}: ${startedRefs.join(", ")}. Results will automatically resume the main agent when ready.`,
664
- ...(failureLines.length > 0
665
- ? [`${failureLines.length} task${failureLines.length === 1 ? "" : "s"} failed before launch:`, ...failureLines]
666
- : []),
667
- ].join("\n");
668
- return {
669
- content: [{ type: "text", text }],
670
- details: makeDetails("parallel", true)(results),
671
- terminate: true,
672
- };
673
- }
674
-
675
- const result = await startBackground(
676
- params.agent as string,
677
- params.task as string,
678
- params.cwd,
679
- defaultIsolationMode("single", params.agent as string, params.isolation as IsolationMode | undefined),
680
- );
681
- if (result.exitCode !== -1) {
682
- throw new Error(getResultOutput(result));
683
- }
684
- const runRef = result.runId === undefined ? result.agent : `#${result.runId} ${result.agent}`;
685
- return {
686
- content: [{ type: "text", text: `Started ${runRef} in the background. Its result will automatically resume the main agent when ready.` }],
687
- details: makeDetails("single", true)([result]),
688
- terminate: true,
689
- };
690
-
691
- },
692
-
693
- renderCall(args, theme) {
694
- if (args.tasks && args.tasks.length > 0) {
695
- let text = `${theme.fg("toolTitle", theme.bold("subagent "))}${theme.fg("accent", `parallel (${args.tasks.length})`)}`;
696
- for (const t of args.tasks.slice(0, 4)) {
697
- const preview = formatTaskSummary(t.task, 48);
698
- const isolation = defaultIsolationMode("parallel", t.agent, t.isolation) === "worktree" ? " [worktree]" : "";
699
- text += `\n ${theme.fg("accent", t.agent)}${theme.fg("dim", isolation)} ${theme.fg("dim", preview)}`;
700
- }
701
- if (args.tasks.length > 4) text += `\n ${theme.fg("dim", `… +${args.tasks.length - 4} more`)}`;
702
- return new Text(text, 0, 0);
703
- }
704
- const task: string = args.task ?? "";
705
- const preview = formatTaskSummary(task, 60);
706
- const isolation = args.isolation === "worktree" ? " [worktree]" : "";
707
- return new Text(
708
- `${theme.fg("toolTitle", theme.bold("subagent "))}${theme.fg("accent", args.agent ?? "?")}${theme.fg("dim", isolation)} ${theme.fg("dim", preview)}`,
709
- 0,
710
- 0,
711
- );
712
- },
713
-
714
- renderResult(result, _options, theme) {
715
- const details = result.details as SubagentDetails | undefined;
716
- if (!details || details.results.length === 0) return new Text(theme.fg("dim", "(no output)"), 0, 0);
717
-
718
- if (details.mode === "single") {
719
- const r = details.results[0];
720
- const pending = r.exitCode === -1;
721
- const icon = statusIcon(pending ? "running" : isFailedResult(r) ? "failed" : "done", theme);
722
- const usage = formatUsage(r.usage);
723
- const model = `${r.model ?? "?"}${r.modelFallbackFrom ? ` (main after ${r.modelFallbackFrom} failed)` : ""}`;
724
- const isolation = r.isolation === "worktree" ? ` · worktree ${r.integrationStatus ?? "active"}` : "";
725
- const runId = r.runId === undefined ? "" : `${theme.fg("dim", `#${r.runId}`)} `;
726
- 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}` : ""}`)}`;
727
- return new Text(line, 0, 0);
728
- }
729
-
730
- // Parallel mode: header + one compact line per agent
731
- const lines: string[] = [
732
- `${theme.fg("toolTitle", theme.bold("subagent "))}${theme.fg("accent", `parallel (${details.results.length})`)}`,
733
- ];
734
- for (const r of details.results) {
735
- const pending = r.exitCode === -1;
736
- const icon = statusIcon(pending ? "running" : isFailedResult(r) ? "failed" : "done", theme);
737
- const usage = formatUsage(r.usage);
738
- const model = `${r.model ?? "?"}${r.modelFallbackFrom ? ` (main after ${r.modelFallbackFrom} failed)` : ""}`;
739
- const isolation = r.isolation === "worktree" ? ` · worktree ${r.integrationStatus ?? "active"}` : "";
740
- const runId = r.runId === undefined ? "" : `${theme.fg("dim", `#${r.runId}`)} `;
741
- lines.push(` ${icon} ${runId}${theme.fg("accent", r.agent)} ${theme.fg("dim", `· ${model}${r.thinking ? ` · thinking ${r.thinking}` : ""}${isolation}${pending ? " · background" : ""}${usage ? ` · ${usage}` : ""}`)}`);
742
- }
743
- return new Text(lines.join("\n"), 0, 0);
744
- },
745
- });
746
- }
1
+ /**
2
+ * The `subagent` tool: dispatches explorer/worker/cleaner/documenter/reviewer agents as isolated pi
3
+ * child processes, single or parallel. Owns the public dispatch contract,
4
+ * per-run status tracking, managed worker/cleaner → reviewer workflows with a
5
+ * conditional documenter, bounded worker/reviewer fix rounds, and internal
6
+ * step launching. Stable
7
+ * thread generations, final integration, and completion ownership live in
8
+ * thread-lifecycle.ts.
9
+ */
10
+
11
+ import { StringEnum } from "@earendil-works/pi-ai";
12
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
13
+ import { Text } from "@earendil-works/pi-tui";
14
+ import { resolve } from "node:path";
15
+ import { Type } from "typebox";
16
+ import { discoverAgents, resolveAgentTools, type AgentConfig } from "./agents.ts";
17
+ import { MAX_CONCURRENT_SUBAGENTS } from "./background.ts";
18
+ import { getStateRoot } from "./durable.ts";
19
+ import { loadConfig } from "./config.ts";
20
+ import { formatUsage, queuedResult } from "./format.ts";
21
+ import {
22
+ buildFinalDocumenterBrief,
23
+ buildFinalReviewBrief,
24
+ buildFixTaskBrief,
25
+ buildReReviewBrief,
26
+ documentationDisposition,
27
+ MAX_FIX_ROUNDS,
28
+ type ChainStep,
29
+ type ManagedWorkflowOutcome,
30
+ } from "./fixloop.ts";
31
+ import {
32
+ formatTaskSummary,
33
+ formatToolActivity,
34
+ monitor,
35
+ statusIcon,
36
+ type RunChainMeta,
37
+ type WorkflowStage,
38
+ type WorkflowStageStatus,
39
+ } from "./monitor.ts";
40
+ import type { SubagentRuntime } from "./runtime.ts";
41
+ import { persistThreadCheckpoint } from "./thread-lifecycle.ts";
42
+ import {
43
+ getResultOutput,
44
+ isFailedResult,
45
+ reviewVerdict,
46
+ runSingleAgentWithMainFallback,
47
+ type SingleResult,
48
+ type SubagentDetails,
49
+ type SubagentLiveEvent,
50
+ } from "./spawn.ts";
51
+ import {
52
+ createBackgroundDispatcher,
53
+ resolveDispatchModelRoute,
54
+ runInManagedRepositoryLane,
55
+ withWorktreeSystemPrompt,
56
+ type DispatchEnvironment,
57
+ type ManagedWorkflowRequest,
58
+ } from "./thread-lifecycle.ts";
59
+ import type { IsolationMode } from "./worktree.ts";
60
+
61
+ export { isWorktreeCapableAgent, runInManagedRepositoryLane } from "./thread-lifecycle.ts";
62
+
63
+ const NON_BLANK_TASK_OPTIONS = { minLength: 1, pattern: "\\S" } as const;
64
+
65
+ const ISOLATION_DESCRIPTION =
66
+ "Filesystem isolation: shared uses the caller's working tree; worktree creates a detached temporary Git worktree (write-capable agents, including worker, cleaner, and documenter, only)";
67
+
68
+ const IsolationSchema = Type.Optional(
69
+ StringEnum(["shared", "worktree"] as const, { description: ISOLATION_DESCRIPTION }),
70
+ );
71
+
72
+ const ADVISORY_DESCRIPTION =
73
+ "Report-only reviewer dispatch: findings return to you for the decision; a verdict (if emitted anyway) never starts the auto-fix chain. Use when re-verifying work you already fixed yourself.";
74
+
75
+ const AdvisorySchema = Type.Optional(Type.Boolean({ description: ADVISORY_DESCRIPTION }));
76
+
77
+ const TaskItem = Type.Object({
78
+ agent: Type.String({ description: "Name of the agent to invoke" }),
79
+ task: Type.String({
80
+ ...NON_BLANK_TASK_OPTIONS,
81
+ description: "Self-contained task to delegate (the agent has no memory of this conversation)",
82
+ }),
83
+ cwd: Type.Optional(Type.String({ description: "Working directory for the agent process" })),
84
+ isolation: IsolationSchema,
85
+ advisory: AdvisorySchema,
86
+ });
87
+
88
+ const SubagentParams = Type.Object({
89
+ agent: Type.Optional(Type.String({ description: "Name of the agent to invoke (single mode)" })),
90
+ task: Type.Optional(
91
+ Type.String({ ...NON_BLANK_TASK_OPTIONS, description: "Self-contained task to delegate (single mode)" }),
92
+ ),
93
+ tasks: Type.Optional(Type.Array(TaskItem, { description: "Array of {agent, task} for parallel execution" })),
94
+ cwd: Type.Optional(Type.String({ description: "Working directory for the agent process (single mode)" })),
95
+ isolation: IsolationSchema,
96
+ advisory: AdvisorySchema,
97
+ });
98
+
99
+ export function defaultIsolationMode(mode: "single" | "parallel", agentName: string, requested?: IsolationMode): IsolationMode {
100
+ if (requested) return requested;
101
+ return mode === "parallel" && agentName === "worker" ? "worktree" : "shared";
102
+ }
103
+
104
+ function workflowStageStatus(result: SingleResult): WorkflowStageStatus {
105
+ if (isFailedResult(result)) return "failed";
106
+ if (result.agent !== "reviewer") return "done";
107
+ const verdict = reviewVerdict(getResultOutput(result));
108
+ if (verdict === "fail") return "changes";
109
+ return verdict === "pass" ? "done" : "failed";
110
+ }
111
+
112
+ export function registerSubagentTool(pi: ExtensionAPI, runtime: SubagentRuntime): void {
113
+ // Latest dispatch environment. The dispatcher is created once per process so
114
+ // restored threads can resume before any dispatch has run; each execute
115
+ // refreshes the fallback context, config, and agent catalog it resolves.
116
+ const environmentRef: { current: DispatchEnvironment | undefined } = { current: undefined };
117
+
118
+ // Finished runs leave the active monitor immediately. Their final findings
119
+ // are sent as a custom message that starts a follow-up turn.
120
+ const finishRun = (
121
+ runId: number,
122
+ status: "done" | "failed",
123
+ opts?: { silent?: boolean },
124
+ ): void => {
125
+ monitor.setStatus(runId, status); // stamps endedAt for the elapsed time
126
+ const run = monitor.removeRun(runId);
127
+ if (!run) return; // already finished — stay idempotent
128
+ if (opts?.silent || !runtime.sessionActive) return;
129
+ const icon = status === "done" ? "✓" : "✗";
130
+ environmentRef.current?.ctx.ui.notify(`${icon} #${run.id} ${monitor.summarize(run)}`, status === "done" ? "info" : "error");
131
+ };
132
+
133
+ // Live sub-agent activity → concise one-line status ("thinking",
134
+ // "read src/index.ts", ...), never a raw args blob. The live handler
135
+ // only updates monitor state; the queue task / launchInWorkflow owns
136
+ // terminal removal, notification, and downstream workflow decisions.
137
+ const makeLiveHandler =
138
+ (runId: number, generation?: number) =>
139
+ (e: SubagentLiveEvent): void => {
140
+ if (generation !== undefined && runtime.threads.get(runId)?.generation !== generation) return;
141
+ switch (e.kind) {
142
+ case "status":
143
+ monitor.setStatus(runId, e.status);
144
+ // A fresh running segment refreshes the durable checkpoint (session
145
+ // path plus child pids) so a crash mid-generation still restores.
146
+ if (e.status === "running") {
147
+ const thread = runtime.threads.get(runId);
148
+ if (thread?.sessionId && thread.sessionDir) {
149
+ persistThreadCheckpoint(runtime, thread, "parked");
150
+ }
151
+ }
152
+ break;
153
+ case "model":
154
+ monitor.setModel(runId, e.model, e.fallbackFrom);
155
+ monitor.setThinking(runId, e.thinking);
156
+ break;
157
+ case "usage":
158
+ monitor.setUsage(runId, e.usage, e.model);
159
+ break;
160
+ case "session": {
161
+ runtime.retainSession({ sessionDir: e.sessionDir });
162
+ const thread = runtime.threads.get(runId);
163
+ if (thread && (generation === undefined || runtime.threads.get(runId)?.generation === generation)) {
164
+ thread.sessionId = e.sessionId;
165
+ thread.sessionDir = e.sessionDir;
166
+ persistThreadCheckpoint(runtime, thread, "parked");
167
+ }
168
+ break;
169
+ }
170
+ case "tool_start":
171
+ monitor.recordToolStart(runId, e.toolName, formatToolActivity(e.toolName, e.args));
172
+ break;
173
+ case "tool_end":
174
+ monitor.recordToolEnd(runId, e.toolName, e.isError);
175
+ break;
176
+ case "thinking":
177
+ monitor.setActivity(runId, "thinking");
178
+ break;
179
+ case "text":
180
+ // A text delta is model output, not a filesystem write.
181
+ monitor.setActivity(runId, "responding");
182
+ break;
183
+ }
184
+ };
185
+
186
+ const makeDetails =
187
+ (mode: "single" | "parallel", background = false) =>
188
+ (results: SingleResult[]): SubagentDetails => ({ mode, results, background });
189
+
190
+ /** Launch one workflow-internal child in a fresh model context. It sees the
191
+ * parent's exact repository/worktree state and is registered by its own id,
192
+ * but never enters top-level lifecycle policy or completion delivery. */
193
+ const launchInWorkflow = async (
194
+ request: ManagedWorkflowRequest,
195
+ agentName: string,
196
+ task: string,
197
+ meta: RunChainMeta,
198
+ ): Promise<{ runId: number; result: SingleResult }> => {
199
+ const discoveredAgent = request.agents.find((candidate) => candidate.name === agentName);
200
+ if (!discoveredAgent) {
201
+ throw new Error(`Managed workflow requires enabled agent "${agentName}", but discovery did not provide it.`);
202
+ }
203
+ const resolveLiveAgentTools = (candidate: AgentConfig): AgentConfig =>
204
+ resolveAgentTools({ ...candidate, tools: discoveredAgent.tools }, runtime.getActiveTools());
205
+ const agent = resolveLiveAgentTools(discoveredAgent);
206
+ // Workflow policy (fix-round caps, agents) stays fixed for the chain,
207
+ // but model/thinking routes are re-read per stage so config edits
208
+ // apply to stages that have not launched yet.
209
+ const stageConfig = await loadConfig(runtime.configPath).catch(() => request.config);
210
+ const resolvedRoute = resolveDispatchModelRoute(agent, stageConfig, request.ctx);
211
+ const route = request.isolation === "worktree"
212
+ ? { ...resolvedRoute, agent: withWorktreeSystemPrompt(resolvedRoute.agent) }
213
+ : resolvedRoute;
214
+ const thinkingLevel = route.thinkingLevel;
215
+ const runId = monitor.addRun(agent.name, task, route.agent.model, thinkingLevel, {
216
+ ...meta,
217
+ isolation: request.isolation,
218
+ ...(request.worktreeId ? { worktreeId: request.worktreeId } : {}),
219
+ });
220
+ const onLive = makeLiveHandler(runId);
221
+ try {
222
+ const result = await runSingleAgentWithMainFallback(
223
+ {
224
+ defaultCwd: request.executionCwd,
225
+ cwd: request.executionCwd,
226
+ agent: route.agent,
227
+ resolveAgentForAttempt: resolveLiveAgentTools,
228
+ agentName,
229
+ task,
230
+ thinkingLevel,
231
+ thinkingLevelForModel: route.thinkingLevelForModel,
232
+ signal: request.signal,
233
+ onLive,
234
+ makeDetails: makeDetails("single", true),
235
+ idleTimeoutMs: stageConfig.idleTimeoutSec * 1000,
236
+ sessionRoot: getStateRoot(runtime.configPath),
237
+ },
238
+ route.mainFallbackRef,
239
+ );
240
+ result.runId = runId;
241
+ result.projectCwd = request.projectCwd;
242
+ result.isolation = request.isolation;
243
+ runtime.retainSession(result);
244
+ monitor.setModel(runId, result.model, result.modelFallbackFrom);
245
+ monitor.setThinking(runId, result.thinking);
246
+ finishRun(runId, isFailedResult(result) ? "failed" : "done", { silent: true });
247
+ runtime.registerRunResult(runId, result);
248
+ return { runId, result };
249
+ } catch (error) {
250
+ finishRun(runId, "failed", { silent: true });
251
+ const errorMessage = error instanceof Error ? error.message : String(error);
252
+ const crashed: SingleResult = {
253
+ ...queuedResult(route.agent, task, thinkingLevel),
254
+ runId,
255
+ projectCwd: request.projectCwd,
256
+ isolation: request.isolation,
257
+ exitCode: 1,
258
+ stderr: errorMessage,
259
+ stopReason: request.signal.aborted ? "aborted" : "error",
260
+ errorMessage,
261
+ dispatchFailed: true,
262
+ };
263
+ runtime.registerRunResult(runId, crashed);
264
+ return { runId, result: crashed };
265
+ }
266
+ };
267
+
268
+ /** Drop any in-flight internal row. Normal internal settlement already
269
+ * removes rows; this is a cancellation/crash guard. */
270
+ const removeWorkflowGroup = (groupId: string): void => {
271
+ for (const run of [...monitor.getRuns()]) {
272
+ if (run.groupId === groupId) monitor.removeRun(run.id);
273
+ }
274
+ };
275
+
276
+ /** Run every downstream role inline under the parent generation's queue
277
+ * controller. That gives park/stop/shutdown one lifecycle owner and keeps
278
+ * isolated worktrees unintegrated until the final reviewer settles. */
279
+ const runManagedWorkflow = async (
280
+ request: ManagedWorkflowRequest,
281
+ ): Promise<ManagedWorkflowOutcome> => {
282
+ const initialStepRunId = monitor.reserveRunId();
283
+ const initialStepResult: SingleResult = {
284
+ ...request.initialResult,
285
+ runId: initialStepRunId,
286
+ };
287
+ runtime.registerRunResult(initialStepRunId, initialStepResult);
288
+ const steps: ChainStep[] = [{
289
+ runId: initialStepRunId,
290
+ result: initialStepResult,
291
+ relation: request.plan.initialRelation,
292
+ }];
293
+ const enabled = (name: string): boolean =>
294
+ request.agents.some((candidate) => candidate.name === name);
295
+ const canContinue = (): boolean => runtime.sessionActive && !request.signal.aborted;
296
+
297
+ // Keep a live parent-owned projection because settled internal rows are
298
+ // intentionally removed. Only real/currently planned stages enter it.
299
+ const initialStageRelation = initialStepResult.agent === "worker"
300
+ ? "implement"
301
+ : initialStepResult.agent === "cleaner"
302
+ ? "cleanup"
303
+ : "review";
304
+ const workflowStages: WorkflowStage[] = [{
305
+ agent: initialStepResult.agent,
306
+ relation: initialStageRelation,
307
+ status: workflowStageStatus(initialStepResult),
308
+ }];
309
+ let reviewStage: WorkflowStage | undefined;
310
+ if (request.plan.kind === "post-writer" && enabled("reviewer")) {
311
+ reviewStage = { agent: "reviewer", relation: "review", status: "pending" };
312
+ workflowStages.push(reviewStage);
313
+ }
314
+ let documentationStage: WorkflowStage | undefined;
315
+ if (enabled("documenter")) {
316
+ documentationStage = { agent: "documenter", relation: "docs", status: "pending" };
317
+ workflowStages.push(documentationStage);
318
+ }
319
+ const publishWorkflowStages = (): void => {
320
+ monitor.setWorkflowStages(request.parentRunId, workflowStages);
321
+ };
322
+ const insertBeforeDocumentation = (stage: WorkflowStage): void => {
323
+ const documentationIndex = documentationStage
324
+ ? workflowStages.indexOf(documentationStage)
325
+ : -1;
326
+ if (documentationIndex === -1) workflowStages.push(stage);
327
+ else workflowStages.splice(documentationIndex, 0, stage);
328
+ };
329
+ const removeDocumentationStage = (): void => {
330
+ if (!documentationStage) return;
331
+ const index = workflowStages.indexOf(documentationStage);
332
+ if (index !== -1) workflowStages.splice(index, 1);
333
+ documentationStage = undefined;
334
+ publishWorkflowStages();
335
+ };
336
+ publishWorkflowStages();
337
+
338
+ const launchStep = async (
339
+ agentName: string,
340
+ task: string,
341
+ relation: string,
342
+ projection: {
343
+ stage?: WorkflowStage;
344
+ timelineRelation?: string;
345
+ childRelation?: string;
346
+ } = {},
347
+ ): Promise<SingleResult> => {
348
+ if (!enabled(agentName)) {
349
+ throw new Error(`Managed workflow cannot launch disabled or missing agent "${agentName}".`);
350
+ }
351
+ const stage: WorkflowStage = projection.stage ?? {
352
+ agent: agentName,
353
+ relation: projection.timelineRelation ?? relation,
354
+ status: "pending",
355
+ };
356
+ if (!projection.stage) insertBeforeDocumentation(stage);
357
+ stage.status = "active";
358
+ publishWorkflowStages();
359
+ try {
360
+ const step = await launchInWorkflow(request, agentName, task, {
361
+ groupId: request.groupId,
362
+ relationLabel: projection.childRelation ?? relation,
363
+ parentRunId: request.parentRunId,
364
+ });
365
+ stage.status = workflowStageStatus(step.result);
366
+ publishWorkflowStages();
367
+ request.rememberLatest(step.result);
368
+ steps.push({ ...step, relation });
369
+ return step.result;
370
+ } catch (error) {
371
+ stage.status = "failed";
372
+ publishWorkflowStages();
373
+ throw error;
374
+ }
375
+ };
376
+
377
+ /** Bounded worker → reviewer fix rounds. A conditional documentation sync
378
+ * deliberately stays out of the rounds: code fixes would invalidate it,
379
+ * and the terminal review classifies whether the settled diff needs one. */
380
+ const runFixRounds = async (
381
+ triggeringReviewer: SingleResult,
382
+ ): Promise<{ lastReview?: SingleResult; lastWorker?: SingleResult }> => {
383
+ let lastReviewer = triggeringReviewer;
384
+ const outcome: { lastReview?: SingleResult; lastWorker?: SingleResult } = {};
385
+ for (let round = 1; round <= MAX_FIX_ROUNDS; round++) {
386
+ if (!canContinue()) break;
387
+ const fixRelation = `fix ${round}/${MAX_FIX_ROUNDS}`;
388
+ const workerResult = await launchStep(
389
+ "worker",
390
+ buildFixTaskBrief(lastReviewer, round, MAX_FIX_ROUNDS),
391
+ `fix round ${round}`,
392
+ { timelineRelation: fixRelation, childRelation: fixRelation },
393
+ );
394
+ if (isFailedResult(workerResult) || !canContinue()) break;
395
+ outcome.lastWorker = workerResult;
396
+
397
+ const reReviewRelation = `re-review ${round}/${MAX_FIX_ROUNDS}`;
398
+ const reviewResult = await launchStep(
399
+ "reviewer",
400
+ buildReReviewBrief(lastReviewer, round, workerResult, {
401
+ documenterPending: enabled("documenter"),
402
+ }),
403
+ `re-review round ${round}`,
404
+ { timelineRelation: reReviewRelation, childRelation: reReviewRelation },
405
+ );
406
+ if (isFailedResult(reviewResult) || !canContinue()) break;
407
+ outcome.lastReview = reviewResult;
408
+ const verdict = reviewVerdict(getResultOutput(reviewResult));
409
+ // REVIEW_PASS settles. No verdict is advisory/malformed and must never
410
+ // trigger another writer. Only an explicit REVIEW_FAIL consumes a fix.
411
+ if (verdict !== "fail") break;
412
+ lastReviewer = reviewResult;
413
+ }
414
+ return outcome;
415
+ };
416
+
417
+ /** Run the low-cost final documentation sync only when the terminal REVIEW_PASS
418
+ * reports drift or omits the new marker. A failed process, missing verdict, or
419
+ * REVIEW_FAIL never writes docs. With no reviewer, retain the conservative
420
+ * writer documenter fallback. */
421
+ const runFinalDocumentation = async (
422
+ lastWriterResult: SingleResult | undefined,
423
+ finalReviewResult: SingleResult | undefined,
424
+ ): Promise<void> => {
425
+ if (!canContinue() || !enabled("documenter")) return;
426
+ if (lastWriterResult?.agent === "documenter") {
427
+ removeDocumentationStage();
428
+ return;
429
+ }
430
+ if (finalReviewResult) {
431
+ if (isFailedResult(finalReviewResult)) {
432
+ removeDocumentationStage();
433
+ return;
434
+ }
435
+ const reviewOutput = getResultOutput(finalReviewResult);
436
+ if (
437
+ reviewVerdict(reviewOutput) !== "pass" ||
438
+ documentationDisposition(reviewOutput) === "clean"
439
+ ) {
440
+ removeDocumentationStage();
441
+ return;
442
+ }
443
+ }
444
+ documentationStage ??= { agent: "documenter", relation: "docs", status: "pending" };
445
+ if (!workflowStages.includes(documentationStage)) workflowStages.push(documentationStage);
446
+ await launchStep(
447
+ "documenter",
448
+ buildFinalDocumenterBrief(lastWriterResult, finalReviewResult),
449
+ "final documentation sync",
450
+ { stage: documentationStage },
451
+ );
452
+ };
453
+
454
+ try {
455
+ // Park/stop/shutdown may win after the top-level child settles but
456
+ // before this continuation starts. Preserve that stable checkpoint and
457
+ // never create an already-aborted downstream child.
458
+ if (!canContinue()) return { kind: request.plan.kind, steps };
459
+ if (request.plan.kind === "auto-fix") {
460
+ const fixOutcome = await runFixRounds(initialStepResult);
461
+ await runFinalDocumentation(fixOutcome.lastWorker, fixOutcome.lastReview ?? initialStepResult);
462
+ } else if (request.plan.kind === "review-pass-sync") {
463
+ // The direct passing review already gated the pending code. Its
464
+ // disposition requested (or conservatively defaulted to) one docs sync.
465
+ await runFinalDocumentation(undefined, initialStepResult);
466
+ } else if (enabled("reviewer")) {
467
+ const gateReview = await launchStep(
468
+ "reviewer",
469
+ buildFinalReviewBrief(initialStepResult, { documenterPending: enabled("documenter") }),
470
+ "final review",
471
+ { stage: reviewStage },
472
+ );
473
+ let fixOutcome: Awaited<ReturnType<typeof runFixRounds>> = {};
474
+ if (
475
+ !isFailedResult(gateReview) &&
476
+ canContinue() &&
477
+ reviewVerdict(getResultOutput(gateReview)) === "fail" &&
478
+ enabled("worker")
479
+ ) {
480
+ fixOutcome = await runFixRounds(gateReview);
481
+ }
482
+ await runFinalDocumentation(
483
+ fixOutcome.lastWorker ?? initialStepResult,
484
+ fixOutcome.lastReview ?? gateReview,
485
+ );
486
+ } else {
487
+ // No gate configured: the documenter is the only downstream stage.
488
+ await runFinalDocumentation(initialStepResult, undefined);
489
+ }
490
+ return { kind: request.plan.kind, steps };
491
+ } finally {
492
+ removeWorkflowGroup(request.groupId);
493
+ }
494
+ };
495
+
496
+ const startBackground = createBackgroundDispatcher({
497
+ runtime,
498
+ getEnvironment: () => {
499
+ if (!environmentRef.current) {
500
+ throw new Error("pi-subagents dispatch environment is not ready yet.");
501
+ }
502
+ return environmentRef.current;
503
+ },
504
+ finishRun,
505
+ makeLiveHandler,
506
+ makeDetails,
507
+ runManagedWorkflow,
508
+ });
509
+ runtime.dispatcher = startBackground;
510
+
511
+ pi.registerTool({
512
+ name: "subagent",
513
+ label: "Subagent",
514
+ description: [
515
+ "Dispatch enabled specialized agents as isolated leaf Pi child processes, singly or in parallel; keep small known-target work in the main thread with direct tools.",
516
+ "Built-ins: explorer for broad read-only reconnaissance (a retrieval index, never a gate); worker for implementation; cleaner as a separate explicitly authorized cleanup/removal/simplification/deduplication entry; documenter for explicit docs/comments work or conditional final diff sync; reviewer for generic read-only assessments and independent code gates.",
517
+ "Work starts in the background. Successful worker/cleaner runs keep one enabled reviewer gate and bounded fix loop; documenter runs afterward only when REVIEW_PASS reports DOCUMENTATION: NEEDED or omits the marker, with a reviewer-disabled fallback. A top-level documenter delivers directly. Results resume the main agent and are already shown, so do not poll, duplicate downstream roles, or restate them.",
518
+ "Single tasks default to shared; parallel workers default to detached Git worktrees. Only write-capable agents can use worktree isolation, and failures never fall back silently to shared.",
519
+ "A selected-model or provider failure continues the retained session on the current main model; ordinary tool/task failures do not.",
520
+ "Use subagent_control to resume a parked or settled thread's retained context by stable run id; use subagent_stop for destructive cancellation.",
521
+ ].join(" "),
522
+ promptSnippet:
523
+ "Dispatch isolated background agents for broad recon, self-contained implementation, authorized cleanup, explicit docs, or independent review; keep small known-target work on direct tools. Worker/cleaner gates and only needed/conservative docs sync run automatically, results resume automatically, and each workflow delivers once.",
524
+ parameters: SubagentParams,
525
+
526
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
527
+ monitor.beginTurn();
528
+ const config = await loadConfig(runtime.configPath);
529
+
530
+ const discovery = discoverAgents(ctx.cwd, {
531
+ scope: config.agentScope,
532
+ enabledNames: config.enabledAgents,
533
+ projectTrusted: ctx.isProjectTrusted?.() === true,
534
+ });
535
+ const agents = discovery.agents;
536
+ // Refresh the dispatcher's fallback environment so control operations
537
+ // (resume of restored threads) never run on a stale context.
538
+ environmentRef.current = { ctx, config, agents };
539
+
540
+ const hasTasks = (params.tasks?.length ?? 0) > 0;
541
+ const hasSingle = Boolean(params.agent) && params.task !== undefined;
542
+
543
+ const catalog = agents.map((a) => a.name).join(", ") || "none";
544
+
545
+ if (Number(hasTasks) + Number(hasSingle) !== 1) {
546
+ return {
547
+ content: [
548
+ {
549
+ type: "text",
550
+ text: `Invalid parameters. Provide exactly one mode: single {agent, task} or parallel {tasks: [...]}. Enabled agents: ${catalog}.`,
551
+ },
552
+ ],
553
+ details: makeDetails("single")([]),
554
+ };
555
+ }
556
+
557
+ if (hasTasks) {
558
+ const blankTaskIndex = params.tasks?.findIndex(({ task }) => task.trim().length === 0) ?? -1;
559
+ if (blankTaskIndex !== -1) {
560
+ return {
561
+ content: [
562
+ {
563
+ type: "text",
564
+ text: `Invalid parameters. tasks[${blankTaskIndex}].task must contain at least one non-whitespace character. No background tasks were started. Enabled agents: ${catalog}.`,
565
+ },
566
+ ],
567
+ details: makeDetails("parallel")([]),
568
+ };
569
+ }
570
+ } else if (params.task?.trim().length === 0) {
571
+ return {
572
+ content: [
573
+ {
574
+ type: "text",
575
+ text: `Invalid parameters. task must contain at least one non-whitespace character. Enabled agents: ${catalog}.`,
576
+ },
577
+ ],
578
+ details: makeDetails("single")([]),
579
+ };
580
+ }
581
+
582
+ // Sub-agents intentionally detach from the foreground turn. This makes the
583
+ // editor available immediately; completion messages later wake the main agent.
584
+ if (params.tasks && params.tasks.length > 0) {
585
+ if (params.tasks.length > MAX_CONCURRENT_SUBAGENTS) {
586
+ return {
587
+ content: [
588
+ {
589
+ type: "text",
590
+ text: `Too many parallel tasks (${params.tasks.length}). Max is ${MAX_CONCURRENT_SUBAGENTS}.`,
591
+ },
592
+ ],
593
+ details: makeDetails("parallel", true)([]),
594
+ };
595
+ }
596
+
597
+ const results: SingleResult[] = [];
598
+ // Preserve caller order (and deterministic completion batching) while
599
+ // preparing each isolated filesystem before its queue entry can start.
600
+ for (const item of params.tasks) {
601
+ results.push(await startBackground(
602
+ item.agent,
603
+ item.task,
604
+ item.cwd,
605
+ defaultIsolationMode("parallel", item.agent, item.isolation as IsolationMode | undefined),
606
+ undefined,
607
+ false,
608
+ undefined,
609
+ undefined,
610
+ undefined,
611
+ { advisoryReview: item.advisory === true },
612
+ ));
613
+ }
614
+ const startedRuns = results.filter((result) => result.exitCode === -1);
615
+ const started = startedRuns.length;
616
+ const startedRefs = startedRuns.map((result) =>
617
+ result.runId === undefined ? result.agent : `#${result.runId} ${result.agent}`,
618
+ );
619
+ const failureLines = results.flatMap((result, index) => {
620
+ if (result.exitCode === -1) return [];
621
+ const reason = getResultOutput(result).trim() || "unknown startup failure";
622
+ return [
623
+ `- tasks[${index}] (${params.tasks![index]!.agent}) failed to start: ${reason.replace(/\n/g, "\n ")}`,
624
+ ];
625
+ });
626
+ if (started === 0) {
627
+ // Pi marks custom-tool failures only when execute throws; returning an
628
+ // `isError` property is still a successful AgentToolResult.
629
+ throw new Error(`No background subagents were started.\n${failureLines.join("\n")}`);
630
+ }
631
+ const text = [
632
+ `Started ${started} background subagent${started === 1 ? "" : "s"}: ${startedRefs.join(", ")}. Results will automatically resume the main agent when ready.`,
633
+ ...(failureLines.length > 0
634
+ ? [`${failureLines.length} task${failureLines.length === 1 ? "" : "s"} failed before launch:`, ...failureLines]
635
+ : []),
636
+ ].join("\n");
637
+ return {
638
+ content: [{ type: "text", text }],
639
+ details: makeDetails("parallel", true)(results),
640
+ terminate: true,
641
+ };
642
+ }
643
+
644
+ const result = await startBackground(
645
+ params.agent as string,
646
+ params.task as string,
647
+ params.cwd,
648
+ defaultIsolationMode("single", params.agent as string, params.isolation as IsolationMode | undefined),
649
+ undefined,
650
+ false,
651
+ undefined,
652
+ undefined,
653
+ undefined,
654
+ { advisoryReview: params.advisory === true },
655
+ );
656
+ if (result.exitCode !== -1) {
657
+ throw new Error(getResultOutput(result));
658
+ }
659
+ const runRef = result.runId === undefined ? result.agent : `#${result.runId} ${result.agent}`;
660
+ return {
661
+ content: [{ type: "text", text: `Started ${runRef} in the background. Its result will automatically resume the main agent when ready.` }],
662
+ details: makeDetails("single", true)([result]),
663
+ terminate: true,
664
+ };
665
+
666
+ },
667
+
668
+ renderCall(args, theme) {
669
+ if (args.tasks && args.tasks.length > 0) {
670
+ let text = `${theme.fg("toolTitle", theme.bold("subagent "))}${theme.fg("accent", `parallel (${args.tasks.length})`)}`;
671
+ for (const t of args.tasks.slice(0, 4)) {
672
+ const preview = formatTaskSummary(t.task, 48);
673
+ const isolation = defaultIsolationMode("parallel", t.agent, t.isolation) === "worktree" ? " [worktree]" : "";
674
+ text += `\n ${theme.fg("accent", t.agent)}${theme.fg("dim", isolation)} ${theme.fg("dim", preview)}`;
675
+ }
676
+ if (args.tasks.length > 4) text += `\n ${theme.fg("dim", `… +${args.tasks.length - 4} more`)}`;
677
+ return new Text(text, 0, 0);
678
+ }
679
+ const task: string = args.task ?? "";
680
+ const preview = formatTaskSummary(task, 60);
681
+ const isolation = args.isolation === "worktree" ? " [worktree]" : "";
682
+ return new Text(
683
+ `${theme.fg("toolTitle", theme.bold("subagent "))}${theme.fg("accent", args.agent ?? "?")}${theme.fg("dim", isolation)} ${theme.fg("dim", preview)}`,
684
+ 0,
685
+ 0,
686
+ );
687
+ },
688
+
689
+ renderResult(result, _options, theme) {
690
+ const details = result.details as SubagentDetails | undefined;
691
+ if (!details || details.results.length === 0) return new Text(theme.fg("dim", "(no output)"), 0, 0);
692
+
693
+ if (details.mode === "single") {
694
+ const r = details.results[0];
695
+ const pending = r.exitCode === -1;
696
+ const icon = statusIcon(pending ? "running" : isFailedResult(r) ? "failed" : "done", theme);
697
+ const usage = formatUsage(r.usage);
698
+ const model = `${r.model ?? "?"}${r.modelFallbackFrom ? ` (main after ${r.modelFallbackFrom} failed)` : ""}`;
699
+ const isolation = r.isolation === "worktree" ? ` · worktree ${r.integrationStatus ?? "active"}` : "";
700
+ const runId = r.runId === undefined ? "" : `${theme.fg("dim", `#${r.runId}`)} `;
701
+ 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}` : ""}`)}`;
702
+ return new Text(line, 0, 0);
703
+ }
704
+
705
+ // Parallel mode: header + one compact line per agent
706
+ const lines: string[] = [
707
+ `${theme.fg("toolTitle", theme.bold("subagent "))}${theme.fg("accent", `parallel (${details.results.length})`)}`,
708
+ ];
709
+ for (const r of details.results) {
710
+ const pending = r.exitCode === -1;
711
+ const icon = statusIcon(pending ? "running" : isFailedResult(r) ? "failed" : "done", theme);
712
+ const usage = formatUsage(r.usage);
713
+ const model = `${r.model ?? "?"}${r.modelFallbackFrom ? ` (main after ${r.modelFallbackFrom} failed)` : ""}`;
714
+ const isolation = r.isolation === "worktree" ? ` · worktree ${r.integrationStatus ?? "active"}` : "";
715
+ const runId = r.runId === undefined ? "" : `${theme.fg("dim", `#${r.runId}`)} `;
716
+ lines.push(` ${icon} ${runId}${theme.fg("accent", r.agent)} ${theme.fg("dim", `· ${model}${r.thinking ? ` · thinking ${r.thinking}` : ""}${isolation}${pending ? " · background" : ""}${usage ? ` · ${usage}` : ""}`)}`);
717
+ }
718
+ return new Text(lines.join("\n"), 0, 0);
719
+ },
720
+ });
721
+ }