brl-subagent 2.7.0 → 2.9.0

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.
Files changed (51) hide show
  1. package/AGENT.md +3 -3
  2. package/README.md +18 -10
  3. package/package.json +6 -5
  4. package/src/agent-tools.ts +332 -0
  5. package/src/background-pipeline.ts +1025 -0
  6. package/src/boot-recovery.ts +313 -0
  7. package/src/commands.ts +137 -0
  8. package/src/concurrency.ts +26 -5
  9. package/src/delegate-handler.ts +2261 -0
  10. package/src/engineering-bar.ts +69 -0
  11. package/src/event-bus.ts +10 -0
  12. package/src/git.ts +274 -5
  13. package/src/headstate.ts +471 -0
  14. package/src/history.ts +21 -3
  15. package/src/index.ts +127 -3943
  16. package/src/kill-escalation.ts +87 -7
  17. package/src/loader.ts +47 -1
  18. package/src/logging.ts +1 -1
  19. package/src/mode-prologue.ts +4 -10
  20. package/src/mode-runners.ts +1575 -0
  21. package/src/notify-completion.ts +180 -12
  22. package/src/params.ts +211 -37
  23. package/src/preflight.ts +123 -16
  24. package/src/prelude.ts +92 -7
  25. package/src/presets.ts +85 -18
  26. package/src/proc.ts +2 -3
  27. package/src/project-flags.ts +3 -3
  28. package/src/recovery-engine.ts +11 -1
  29. package/src/recovery-surface.ts +1 -2
  30. package/src/recovery.ts +155 -20
  31. package/src/reports.ts +1 -7
  32. package/src/run-registry.ts +22 -3
  33. package/src/runner.ts +80 -21
  34. package/src/runtime.ts +50 -0
  35. package/src/sanitize.ts +20 -2
  36. package/src/scheduler.ts +1 -2
  37. package/src/schema.ts +37 -7
  38. package/src/scratch-root.ts +909 -0
  39. package/src/scratch-spawn.ts +256 -0
  40. package/src/session-manager.ts +854 -200
  41. package/src/state.ts +130 -30
  42. package/src/templates.ts +42 -17
  43. package/src/terminal-notifier.ts +405 -0
  44. package/src/transcript.ts +1 -1
  45. package/src/tui-format.ts +177 -7
  46. package/src/tui.ts +115 -57
  47. package/src/types.ts +206 -5
  48. package/src/unit-params.ts +113 -0
  49. package/src/unit-run.ts +45 -16
  50. package/src/validate.ts +89 -11
  51. package/src/worktree-report.ts +142 -0
package/src/index.ts CHANGED
@@ -1,203 +1,53 @@
1
- // Purpose: Entry point: tool/command registration, the delegate_task handlers, and the execution-mode runners.
1
+ // Purpose: Entry point: the composition root — runtime, registration surface, session lifecycle handlers and the terminal notifier.
2
2
  /**
3
3
  * brl-subagent — multi-agent orchestration for pi.
4
- * Entry point: tool registrations, command surface, and the multi-mode runners.
4
+ *
5
+ * Entry point: the COMPOSITION ROOT. It builds the runtime once per invocation
6
+ * and registers the surface (ADR 0027 D7) — the `pi.registerCommand` and the
7
+ * four `pi.registerTool` calls below stay here, and every surface they register
8
+ * is a definition returned by a factory:
9
+ *
10
+ * - `commands.ts` (ADR 0027 S5) — the `/brl-subagent` definition;
11
+ * - `delegate-handler.ts` (ADR 0027 S5) — the `delegate_task` definition
12
+ * (dispatch pre-flight and the foreground run path);
13
+ * - `agent-tools.ts` (ADR 0027 S5) — the three agent-lifecycle tools;
14
+ * - `mode-runners.ts` (ADR 0027 S2) — the three batch-mode runners;
15
+ * - `background-pipeline.ts` (ADR 0027 S3) — the fan-out, the shared spawn
16
+ * tail and the single-background spawn;
17
+ * - `boot-recovery.ts` + `terminal-notifier.ts` (ADR 0027 S4) — the boot scan
18
+ * with its notices, and the completion-push notifier.
19
+ *
20
+ * What is left here is what cannot be handed out: the two config writers
21
+ * (`applyConfig`, `resetState`), the session lifecycle handlers, and the deps
22
+ * assembly that guarantees each factory gets the SAME instances (D5) — one
23
+ * runtime, one spawn queue, one notice latch.
5
24
  * See AGENT.md for the conductor-facing capability reference.
6
25
  */
7
26
 
8
- import * as fs from "node:fs";
27
+ import type { SessionState } from "./state";
28
+ import type { DelegateTaskParams } from "./types";
29
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
9
30
  import * as path from "node:path";
10
- import type {
11
- AgentToolResult,
12
- AgentToolUpdateCallback,
13
- } from "@earendil-works/pi-agent-core";
14
- import type { ExtensionAPI, ExtensionContext, Theme, ToolRenderResultOptions } from "@earendil-works/pi-coding-agent";
15
- import { Type } from "typebox";
16
-
17
- import type {
18
- SubagentPreset,
19
- SubagentResult,
20
- SubagentRun,
21
- SubagentToolOptions,
22
- ResolvedParams,
23
- ThinkingLevel,
24
- ApprovalMode,
25
- SubTaskParams,
26
- SubTaskResult,
27
- ChainDetails,
28
- ParallelDetails,
29
- MultiSubagentDetails,
30
- GraphTask,
31
- GraphDetails,
32
- GraphWave,
33
- DelegateTaskDetails,
34
- DelegateTaskParams,
35
- Priority,
36
- TaskTemplate,
37
- ToolResult,
38
- SubagentEvent,
39
- } from "./types";
40
- import {
41
- resolveThinkingLevel,
42
- EMPTY_USAGE,
43
- getFinalOutput,
44
- isSubagentError,
45
- countSubagentOutcomes,
46
- classifyError,
47
- MAX_CHAIN_STEPS,
48
- MAX_PARALLEL_TASKS,
49
- MAX_GRAPH_TASKS,
50
- PREVIOUS_OUTPUT_PLACEHOLDER,
51
- GRAPH_OUTPUT_PLACEHOLDER_RE,
52
- DEFAULT_PRIORITY,
53
- type GitMode,
54
- type BackgroundAgent,
55
- type RecoveryMode,
56
- } from "./types";
57
- import { validateGraph, topologicalSort } from "./scheduler";
58
- import { runModePrologue } from "./mode-prologue";
59
- import { resolveTemplate, loadAllTemplates, loadBuiltinTemplates, validateTemplatePresetRefs, extractParamNames } from "./templates";
31
+ import { KNOWN_DELEGATE_KEYS, type ResolveInputParams } from "./params";
32
+ import { createBackgroundPipeline } from "./background-pipeline";
33
+ import { createBootRecovery } from "./boot-recovery";
34
+ import { createModeRunners } from "./mode-runners";
35
+ import { createRuntime } from "./runtime";
36
+ import { createCommands } from "./commands";
37
+ import { createDelegateHandler } from "./delegate-handler";
38
+ import { createAgentTools } from "./agent-tools";
39
+ import { loadAllTemplates, loadBuiltinTemplates, validateTemplatePresetRefs } from "./templates";
60
40
  import { pkgPath } from "./paths";
61
-
62
- import { sanitizeTask, validateCwd, validateOutputFile, stripAnsi, capOutput, getCurrentDepth, sanitizeErrorMessage, buildCrashResult } from "./sanitize";
63
- import {
64
- hasUncommittedChanges,
65
- createWorkBranch,
66
- captureDiff,
67
- getHeadState,
68
- restoreHead,
69
- deleteBranch,
70
- mergeWorkBranch,
71
- type HeadState,
72
- } from "./git";
73
- import { preflightCheck } from "./preflight";
74
- import { depthLimitRejection, formatValidationWarnings, gateSessionCost, modelNotConfiguredRejection, rejectApprovalAlwaysInBackground, rejection, resolveModeModel, resolveSubagentModelPrecedence, runPreTaskValidation, validateDelegationTargets, validateUnitPrePass, type SubagentModelResolution } from "./prelude";
75
- import { loadBuiltinPresets, loadCustomPresets, getAllPresets, writePresetFile, formatPresetRestriction, formatToolRestriction } from "./presets";
76
- import { modelIsAvailable, parseModelString } from "./model-availability";
77
- import { validatePreTask, diagnoseFailure, DEFAULT_BACKGROUND_DEADLINE_MS } from "./validate";
78
- import {
79
- defaultBackgroundFor,
80
- findUnknownParams,
81
- KNOWN_DELEGATE_KEYS,
82
- resolveDispatchPreset,
83
- resolveEffectiveApprovalMode,
84
- resolveSubagentParams,
85
- resolveThinkingDispatchSwitch,
86
- shouldRejectBackgroundForBatch,
87
- snapshotOriginalParams,
88
- THINKING_SWITCH_NOTICE,
89
- type DispatchShape,
90
- type ResolveInputParams,
91
- } from "./params";
92
- import { delegateTaskParamsSchema } from "./schema";
93
- import { readProcessChecks } from "./project-flags";
94
- import { createSessionState, resolveTerminalRunEntry, type SessionState } from "./state";
95
- import { makeLiveOnUpdate, createUnitRun, finalizeUnitRun, finalizeUnitRunCrash, pruneHistoryIfNeeded, registerLiveRun } from "./unit-run";
96
- import { buildSubagentPrompt, describePromptMode } from "./prompt";
97
- import { runSubagent, cleanupTempDirs, reapActiveChildren } from "./runner";
98
- import {
99
- recoverProduction,
100
- currentProcessOwner,
101
- newDispatchIdentity,
102
- } from "./recovery";
103
- import { markInterrupted, listInflightRuns, clearInflightRun } from "./run-registry";
104
- import { acquireSlot, clearProgressLinger, releaseSlot, repaintStatus, stopProgressTicker } from "./concurrency";
105
- import { transcriptDisplayPath } from "./transcript-path";
106
- import {
107
- finalizeRunRecord,
108
- resolveRetryParams,
109
- createEmptyResult,
110
- } from "./history";
111
- import { computeSLAMetrics, computeDegradation } from "./metrics";
112
- import {
113
- showSelectList,
114
- showModelSelector,
115
- showThinkingSelector,
116
- showConcurrencyInput,
117
- showDepthInput,
118
- showHistoryEntriesInput,
119
- showCostLimitInput,
120
- showApprovalModeSelector,
121
- showApprovalDialog,
122
- showCompletionNotifySelector,
123
- showRecoverySelector,
124
- showPresetManager,
125
- showTemplateManager,
126
- showSLAConfig,
127
- showSLAStats,
128
- showConfigMenu,
129
- showRunHistory,
130
- showMonitor,
131
- showDashboard,
132
- showComplianceMenu,
133
- showRetryMenu,
134
- renderDelegateCall,
135
- renderDelegateResult,
136
- } from "./tui";
137
- import { createLogger, setLogCwd, type Logger } from "./logging";
138
- import {
139
- collectInterruptedRuns,
140
- offeredInterruptedRuns,
141
- buildRecoveryNotice,
142
- resolveRecoveryNoticeDelivery,
143
- abandonInterruptedRun,
144
- visibleRunEntriesForSession,
145
- type RecoveryAgentLookup,
146
- } from "./recovery-surface";
147
- import { Intercom } from "./messaging";
148
- import * as eventBus from "./event-bus";
149
- import {
150
- buildCompletionMessage,
151
- resolveDelivery,
152
- sendCompletionNotification,
153
- claimTerminalNotice,
154
- resolveRunEntry,
155
- } from "./notify-completion";
156
- import { isTransportRetryable, TRANSPORT_RETRY_TOAST } from "./transport-retry";
41
+ import { loadBuiltinPresets, loadCustomPresets, getAllPresets, writePresetFile } from "./presets";
42
+ import { cleanupTempDirs, reapActiveChildren } from "./runner";
43
+ import { clearProgressLinger, repaintStatus, stopProgressTicker } from "./concurrency";
44
+ import { setLogCwd } from "./logging";
45
+ import { createTerminalNotifier } from "./terminal-notifier";
157
46
 
158
47
  // ---------------------------------------------------------------------------
159
48
  // Helpers
160
49
  // ---------------------------------------------------------------------------
161
50
 
162
- /**
163
- * DRY helper (issue #154 review): shape an inventory of items into a single
164
- * comma-delimited summary line for the LLM-facing delegation guidance. Both
165
- * the B1 preset-restriction summary and the B1b template summary load an
166
- * inventory at registration, map each item to a formatted string, then join.
167
- */
168
- export function buildInventorySummary<T>(items: T[], formatItem: (item: T) => string): string {
169
- return items.map(formatItem).join(", ");
170
- }
171
-
172
- /**
173
- * Format one built-in template into a compact summary entry for the conductor:
174
- * `name` (+ ` (lowercased description; slots ${a}, ${b})`) — the slot note is
175
- * omitted when the template declares no params, and the description is omitted
176
- * when it is empty. Mirrors the B1b summary shape (issue #154 review).
177
- */
178
- export function formatTemplateSummaryItem(t: TaskTemplate): string {
179
- const slots = [...new Set([
180
- ...extractParamNames(t.task),
181
- ...(t.outputFile ? extractParamNames(t.outputFile) : []),
182
- ])];
183
- const slotNote = slots.length > 0
184
- ? `; slots ${slots.map((s) => `\${${s}}`).join(", ")}`
185
- : "";
186
- const desc = t.description
187
- ? `${t.description.charAt(0).toLowerCase()}${t.description.slice(1)}`
188
- : "";
189
- return `${t.name}${desc ? ` (${desc}${slotNote})` : slotNote}`;
190
- }
191
-
192
- /**
193
- * Render the template guideline line with the built-in inventory summary
194
- * interpolated. Exported so the guidance test can assert the RENDERED text
195
- * rather than the literal `${templateSummary}` placeholder that a double-quoted
196
- * string would leave in the conductor-facing guidance (issue #154 review).
197
- */
198
- export function buildTemplateGuideline(templateSummary: string): string {
199
- return `Templates are file-backed task starters with \${param} slots. Built-in templates: ${templateSummary}. Custom templates are NOT listed here — inspect them via /brl-subagent templates before choosing one.`;
200
- }
201
51
 
202
52
  /**
203
53
  * Issue #354 review minor: the synchronous shutdown cleanup, extracted so the
@@ -227,53 +77,6 @@ export function cleanupSessionState(state: SessionState): void {
227
77
  state.pendingQueue.length = 0;
228
78
  }
229
79
 
230
- /**
231
- * Issue #401/#411: the resume preamble a transport auto-retry builds and delivers
232
- * as a `<resume-context>` section on the child's system prompt — never inside
233
- * the `<task>` fence. A dropped connection costs the child its context, not its
234
- * files: the retry spawns into the same directory, so the work it already did
235
- * (commits, written files, a bank) is still there. The preamble turns a blind
236
- * replay into a resume by naming what to inspect first.
237
- *
238
- * Kept bounded (5 lines max) and deliberately vetted for runtime vocabulary —
239
- * it is prompt text a user can see in the child's system prompt.
240
- *
241
- * Issue #404: it also names the retained SDK session directory when one exists.
242
- * That is the only artifact that holds attempt 1's CONVERSATION — the output log
243
- * is a start/steering stub — and the settle path retains it for exactly this
244
- * class of run. The pointer is absolute and computed conductor-side at build
245
- * time: the retry's child can run in a different cwd (worktree/branch mode), so
246
- * a relative path would point at the wrong tree. The exists gate is deliberate:
247
- * an attempt whose session was not retained (size floor, marker failure, a
248
- * legacy run) gets the bank-only preamble, never a dead path.
249
- */
250
- function buildRetryResumePreamble(
251
- run: SubagentRun,
252
- nextAttempt: number,
253
- retainedSessionDir?: string,
254
- ): string {
255
- const sanitize = (value: string): string => value.replace(/[^A-Za-z0-9._-]/g, "-");
256
- const label = sanitize(run.label ?? "");
257
- // A label made only of separators ("---") is not a filename; fall back to the
258
- // (UUID-shaped, hence already safe) id.
259
- const bankLabel = /[A-Za-z0-9]/.test(label) ? label : sanitize(run.id);
260
- const lines = [
261
- `[attempt ${nextAttempt} — the previous attempt (${run.id}) died on a transport failure.`,
262
- "This directory may already contain its uncommitted edits.",
263
- `Before acting, inspect: \`git status --short\`, \`git log --oneline -8\`, and the progress bank at /tmp/brl-${bankLabel}-bank.md if it exists.`,
264
- "Continue from what exists; do NOT redo committed, written, or banked work.]",
265
- ];
266
- if (retainedSessionDir) {
267
- // Insert before the closing line so the block still reads as one unit.
268
- lines.splice(
269
- lines.length - 1,
270
- 0,
271
- `The previous attempt's session is retained at ${retainedSessionDir} — read the newest .jsonl inside (ISO-prefixed names sort lexicographically) to recover what it had worked out.`,
272
- );
273
- }
274
- return lines.join("\n");
275
- }
276
-
277
80
  // ---------------------------------------------------------------------------
278
81
  // Extension entry point
279
82
  // ---------------------------------------------------------------------------
@@ -319,73 +122,45 @@ type _ResolveInputCoverage = _ExpectNever<
319
122
  Exclude<_KnownDelegateKey, keyof ResolveInputParams | _NonResolutionDelegateKey>
320
123
  >;
321
124
 
322
- /**
323
- * Issue #381 (audit D4): the one graph-node → SubTaskParams mapping, shared by
324
- * the graph pre-pass and the per-wave dispatch. GraphTask is a structural
325
- * superset of SubTaskParams, so the node-only scheduling fields are dropped by
326
- * destructuring instead of re-listing every per-subtask field — a field added
327
- * to either type can no longer be silently forgotten at one of the two sites.
328
- */
329
- function graphTaskToSubTaskParams(node: GraphTask): SubTaskParams {
330
- const { id: _id, dependsOn: _dependsOn, ...subTask } = node;
331
- return subTask;
332
- }
333
-
334
- /**
335
- * Issue #376 (audit D3): the one `SubagentResult` → `SubTaskResult` field
336
- * mapping, shared by every dispatch mode (chain, parallel, graph). The ten
337
- * assignments plus the error classification were copied per mode, so a field
338
- * added to `SubTaskResult` could be silently forgotten at one of the sites —
339
- * and `errorCategory` could be passed through unclassified. Callers add their
340
- * own mode-specific fields (`step`/`task`/`label`) around this mapping.
341
- */
342
- function toSubTaskResult(
343
- result: SubagentResult,
344
- ): Pick<
345
- SubTaskResult,
346
- | "exitCode"
347
- | "messages"
348
- | "stderr"
349
- | "usage"
350
- | "model"
351
- | "stopReason"
352
- | "errorMessage"
353
- | "errorCategory"
354
- | "gitBranch"
355
- | "gitDiff"
356
- > {
357
- return {
358
- exitCode: result.exitCode,
359
- messages: result.messages,
360
- stderr: result.stderr,
361
- usage: result.usage,
362
- model: result.model,
363
- stopReason: result.stopReason,
364
- errorMessage: result.errorMessage,
365
- // The classification path is part of the mapping: every mode derives the
366
- // category from the raw result, never from the runner's own field.
367
- errorCategory: classifyError(result),
368
- gitBranch: result.gitBranch,
369
- gitDiff: result.gitDiff,
370
- };
371
- }
372
-
373
125
  export default function (pi: ExtensionAPI) {
374
- const log = createLogger("brl-subagent");
375
-
376
- // F7: Session-bound state — initialized per session
377
- let state = createSessionState(log);
126
+ // ADR 0027 (S2): the composition root builds the runtime once per invocation
127
+ // and composes the mode runners over it. `state` is no longer a rebindable
128
+ // `let`: the context owns the instance, and a rebind here would be a second
129
+ // owner of the store the runners hold.
130
+ const rt = createRuntime(pi);
131
+ const { log, state } = rt;
132
+ const { runChainMode, runParallelMode, runGraphMode, resolveStepModel, applyUnitShapeGuard } = createModeRunners(rt);
133
+ // ADR 0027 (S3): the background pipeline. The loader thunk is invoked only
134
+ // inside `startBackgroundAgent`, so session-manager's lifecycle mutators stay
135
+ // lazily imported from the one module allowed to reach them. S6 (#430):
136
+ // `startBackgroundAgent` itself is no longer destructured here — nothing in
137
+ // the composition root calls it (`spawnBackgroundRun` does), and the unused
138
+ // binding only invited the illusion of a second entry point.
139
+ const backgroundPipeline = createBackgroundPipeline(rt, {
140
+ loadSessionManager: () => import("./session-manager"),
141
+ resolveStepModel,
142
+ applyUnitShapeGuard,
143
+ });
144
+ const { runBackgroundFanOut, spawnBackgroundRun } = backgroundPipeline;
378
145
 
379
146
  // Issue #147: the completion-push subscriber needs the session context to
380
- // resolve the run entry (state.getRunEntries(ctx)). The event-bus listener
147
+ // resolve the run entry (state.getLogicalRunEntries(ctx)). The event-bus listener
381
148
  // receives no ctx, so capture it in session_start where it is available.
382
149
  let sessionCtx: ExtensionContext | undefined;
383
150
 
384
- // Option B U3 (D2): "one recovery notice per boot". The boot scan may be
385
- // followed by more session_starts in the same process (reload); without this
386
- // guard every one would re-list the same interrupted runs. Reset on shutdown
387
- // so a genuinely new session notifies again.
388
- let recoveryNoticeDelivered = false;
151
+ // ADR 0027 (S4): the boot recovery cluster — the interrupted-run scan, the
152
+ // head-state reconcile, the two boot notices and the abandon action, built
153
+ // over this runtime. Its once-per-boot latch (`recoveryNoticeDelivered`) is
154
+ // the factory's own (D5): a latch here would be shared by two runtimes.
155
+ const {
156
+ performBootRecovery,
157
+ reconcileHeadStatesAtBoot,
158
+ maybeSendHeadStateNotice,
159
+ maybeSendRecoveryNotice,
160
+ abandonProductionRun,
161
+ visibleRunsFor,
162
+ resetRecoveryNotice,
163
+ } = createBootRecovery(rt);
389
164
 
390
165
  // -------------------------------------------------------------------
391
166
  // Config change callback
@@ -420,3545 +195,44 @@ export default function (pi: ExtensionAPI) {
420
195
  ctx.ui.notify("Subagent configuration reset", "info");
421
196
  }
422
197
 
423
- // -------------------------------------------------------------------
424
- // Parameter resolution (extracted to src/params.ts — issue #59)
425
- // -------------------------------------------------------------------
426
-
427
- // The model-precedence chain lives in prelude.ts (issue #379) so the batch
428
- // modes' tail (`resolveModeModel`) and these single/background paths resolve
429
- // identically; this wrapper keeps their call shape (context + preset +
430
- // per-call override) unchanged.
431
- function resolveSubagentModel(
432
- ctx: ExtensionContext,
433
- preset: SubagentPreset | undefined,
434
- perCallModel?: string, // NEW: top-level delegate_task model param (issue #96)
435
- ): SubagentModelResolution {
436
- return resolveSubagentModelPrecedence({ state, ctx, log, preset, perCallModel });
437
- }
438
-
439
- // C3: Resolve a step's model override (step.model > global resolved model).
440
- // Parsed + availability-checked; falls back to the global model on failure.
441
- function resolveStepModel(
442
- ctx: ExtensionContext,
443
- stepModel: string | undefined,
444
- globalModel: { provider: string; id: string },
445
- ): { provider: string; id: string } {
446
- if (stepModel) {
447
- const parsed = parseModelString(stepModel);
448
- if (!parsed) {
449
- log.warn("Step model is not a valid provider/model-id, falling back to global model", { model: stepModel });
450
- } else if (modelIsAvailable(ctx.modelRegistry, parsed)) {
451
- log.info("Using step model override", { model: stepModel });
452
- return parsed;
453
- } else {
454
- log.warn("Step model unavailable, falling back to global model", { model: stepModel });
455
- }
456
- }
457
- return globalModel;
458
- }
459
-
460
- // -------------------------------------------------------------------
461
- // P1+P2: mergeSubTaskParams
462
- // -------------------------------------------------------------------
463
-
464
- /**
465
- * Merge global resolved params with a SubTaskParams.
466
- * SubTask fields override global fields. Tools/excludeTools/noBuiltinTools
467
- * are replaced entirely if set in the subTask, otherwise inherited from global.
468
- */
469
- function mergeSubTaskParams(
470
- globalParams: ResolvedParams & { resolvedGitMode: GitMode; resolvedApprovalMode: ApprovalMode },
471
- subTask: SubTaskParams,
472
- ): {
473
- task: string;
474
- label: string | undefined;
475
- model: string | undefined;
476
- inheritSP: boolean;
477
- customSP: string | undefined;
478
- outputFile: string | undefined;
479
- timeout: number | undefined;
480
- effectiveCwd: string;
481
- thinkingLevel: ThinkingLevel;
482
- priority: Priority | undefined;
483
- toolOptions: SubagentToolOptions | undefined;
484
- resolvedGitMode: GitMode;
485
- resolvedApprovalMode: ApprovalMode;
486
- } {
487
- const mergedThinkingLevel = subTask.thinkingLevel
488
- ? resolveThinkingLevel(
489
- subTask.thinkingLevel as ThinkingLevel,
490
- state.config.maxThinkingLevel,
491
- )
492
- : globalParams.thinkingLevel;
493
-
494
- const mergedTools = subTask.tools ?? globalParams.toolOptions?.tools;
495
- // Fix: edit depends on write in pi's tool system.
496
- const resolvedTools = mergedTools && mergedTools.includes("edit") && !mergedTools.includes("write")
497
- ? [...mergedTools, "write"]
498
- : mergedTools;
499
- const mergedExcludeTools = subTask.excludeTools ?? globalParams.toolOptions?.excludeTools;
500
- const mergedNoBuiltinTools =
501
- subTask.noBuiltinTools ?? globalParams.toolOptions?.noBuiltinTools;
502
-
503
- const mergedToolOptions: SubagentToolOptions | undefined =
504
- resolvedTools || mergedExcludeTools || mergedNoBuiltinTools
505
- ? {
506
- tools: resolvedTools,
507
- excludeTools: mergedExcludeTools,
508
- noBuiltinTools: mergedNoBuiltinTools,
509
- }
510
- : undefined;
511
-
512
- return {
513
- task: subTask.task || globalParams.task,
514
- label: subTask.label ?? globalParams.label,
515
- model: subTask.model,
516
- inheritSP: subTask.inheritSystemPrompt ?? globalParams.inheritSP,
517
- customSP: subTask.systemPrompt ?? globalParams.customSP,
518
- outputFile: subTask.outputFile ?? globalParams.outputFile,
519
- timeout: subTask.timeout ?? globalParams.timeout,
520
- effectiveCwd: subTask.cwd ?? globalParams.effectiveCwd,
521
- thinkingLevel: mergedThinkingLevel,
522
- // Issue #114: per-unit priority — undefined when the step declares none
523
- // (the caller then falls back to the call-level priority).
524
- priority: subTask.priority && ["critical", "high", "normal", "low"].includes(subTask.priority)
525
- ? (subTask.priority as Priority)
526
- : undefined,
527
- toolOptions: mergedToolOptions,
528
- resolvedGitMode: globalParams.resolvedGitMode,
529
- resolvedApprovalMode: globalParams.resolvedApprovalMode,
530
- };
531
- }
532
-
533
- // Per-unit display name for validation prefixes: the label when present,
534
- // else the task truncated to 60 chars. Shared by the foreground parallel
535
- // pre-pass and the background fan-out pre-pass (issue #220) so a unit
536
- // renders identically in either shape.
537
- const displayTaskName = (merged: ReturnType<typeof mergeSubTaskParams>): string =>
538
- merged.label ??
539
- (merged.task.length > 60 ? `${merged.task.slice(0, 57)}...` : merged.task);
540
-
541
- // -------------------------------------------------------------------
542
- // P1: runChainMode
543
- // -------------------------------------------------------------------
544
-
545
- async function runChainMode(
546
- params: DelegateTaskParams,
547
- signal: AbortSignal | undefined,
548
- onUpdate: AgentToolUpdateCallback<DelegateTaskDetails> | undefined,
549
- ctx: ExtensionContext,
550
- ): Promise<ToolResult<SubagentResult | ChainDetails | undefined>> {
551
- const chainSteps: SubTaskParams[] = params.chain!;
552
-
553
- // Issue #133: dispatch-start timestamp — the aggregate run entry's
554
- // startedAt (captured once, at mode entry, not at completion).
555
- const chainModeStartedAt = new Date().toISOString();
556
-
557
- // Mode prologue (issue #379): cost → depth → resolve → targets →
558
- // preflight → H1, the sequence every batch mode shares (mode-prologue.ts).
559
- // Chain's per-mode inputs are only the label and the unit count; H1 here
560
- // validates the MODE-level params (top-level tasks are empty, so only the
561
- // hard outputFile-vs-write conflict applies), while every step's own
562
- // cwd/outputFile/tools belong to the per-step pass below (issue #222).
563
- const pro = runModePrologue({
564
- params,
565
- state,
566
- ctx,
567
- log,
568
- label: "Chain",
569
- units: chainSteps.length,
570
- });
571
- if (!pro.ok) return pro.error;
572
- const { globalParams, resolvedCwd, currentDepth } = pro;
573
-
574
- // Per-step pre-pass (issue #222): resolve + validate EVERY step before
575
- // any spawn, so a single bad step rejects the chain with nothing
576
- // started — the same all-before-any-spawn semantics the background
577
- // fan-out and the parallel `tasks` shape use. Chain steps are fully
578
- // known up front and a step's cwd/outputFile never depend on a previous
579
- // step's output (only its TASK text consumes {previous}), so the pass
580
- // can run up front — and must, because discovering step 5's bad cwd
581
- // after four steps already ran would waste their whole budget.
582
- const stepPass = validateUnitPrePass({
583
- units: chainSteps,
584
- label: "Chain",
585
- gitMode: globalParams.resolvedGitMode,
586
- ctx,
587
- log,
588
- force: params.force as boolean | undefined,
589
- noJev: params.noJev,
590
- merge: (step) => mergeSubTaskParams(globalParams, step),
591
- describe: (_step, merged, i) => ({
592
- prefix: `Step ${i + 1} ("${displayTaskName(merged)}")`,
593
- logContext: { step: i + 1 },
594
- }),
595
- });
596
- if (!stepPass.ok) return stepPass.error;
597
- const stepCwds = stepPass.units.map((u) => u.cwd);
598
- const stepWarnings = stepPass.warnings;
599
-
600
- // Mode tail (issue #379): resolve the model (preset + per-call override,
601
- // auto-route included in `resolvedPreset`), reject an empty resolution,
602
- // then the circuit breaker. It runs AFTER the per-step pass — IN8 keeps
603
- // a bad step's rejection ahead of an unconfigured model.
604
- const tail = resolveModeModel({
605
- state,
606
- ctx,
607
- log,
608
- preset: globalParams.resolvedPreset,
609
- perCallModel: params.model,
610
- });
611
- if (!tail.ok) return tail.error;
612
- const subagentModel = tail.model;
613
- const modelStr = tail.modelStr;
614
-
615
- // Resolve priority (issue #114: no config knob — the call-level default)
616
- const chainPriority: Priority = (
617
- params.priority && ["critical", "high", "normal", "low"].includes(params.priority as string)
618
- ? (params.priority as Priority)
619
- : DEFAULT_PRIORITY
620
- );
621
-
622
- // Acquire concurrency slot for the chain
623
- const acquired = await acquireSlot(state, ctx, signal, chainPriority);
624
- if (!acquired) {
625
- return {
626
- content: [
627
- {
628
- type: "text" as const,
629
- text: "Chain cancelled while waiting for concurrency slot.",
630
- },
631
- ],
632
- details: undefined,
633
- isError: true,
634
- };
635
- }
636
-
637
- let chainSuccess = false;
638
- try {
639
- const basePrompt = ctx.getSystemPrompt();
640
- let previousOutput = "";
641
- const chainResults: SubTaskResult[] = [];
642
- let stoppedEarly = false;
643
-
644
- for (let i = 0; i < chainSteps.length; i++) {
645
- const step = chainSteps[i];
646
-
647
- // Merge params for this step
648
- const merged = mergeSubTaskParams(globalParams, step);
649
-
650
- // C3: Resolve this step's model override (step.model > global resolved model)
651
- const stepModel = resolveStepModel(ctx, merged.model, subagentModel);
652
-
653
- // Substitute {previous} placeholder
654
- merged.task = merged.task.replaceAll(
655
- PREVIOUS_OUTPUT_PLACEHOLDER,
656
- previousOutput,
657
- );
658
-
659
- // Build system prompt
660
- const subagentPrompt = buildSubagentPrompt(
661
- basePrompt,
662
- merged.inheritSP,
663
- merged.customSP,
664
- merged.outputFile,
665
- merged.toolOptions?.tools,
666
- globalParams.resolvedPreset?.promptGuideline,
667
- );
668
-
669
- // Create SubTaskResult for this step
670
- const subTaskResult: SubTaskResult = {
671
- step: i + 1,
672
- task: merged.task,
673
- label: merged.label,
674
- exitCode: 0,
675
- messages: [],
676
- stderr: "",
677
- usage: { ...EMPTY_USAGE },
678
- };
679
-
680
- // Issue #133: status-bar breakdown — the mode context shows the
681
- // current step while the dispatch is in flight.
682
- state.modeContext = {
683
- kind: "chain",
684
- step: i + 1,
685
- totalSteps: chainSteps.length,
686
- };
687
- // Issue #133: render the breakdown — the chain holds ONE mode-level
688
- // slot (acquired at mode start, released in the finally), so no
689
- // per-step acquire/release calls repaintStatus while the
690
- // mode context is set. Call it directly here (mirrors how the
691
- // graph path's per-node slot operations trigger the render).
692
- repaintStatus(state, ctx);
693
-
694
- // Emit initial progress for this step
695
- const modeInfo = describePromptMode(
696
- merged.inheritSP,
697
- Boolean(merged.customSP),
698
- );
699
- onUpdate?.({
700
- content: [
701
- {
702
- type: "text" as const,
703
- text: `Chain step ${i + 1}/${chainSteps.length} (${modeInfo})...`,
704
- },
705
- ],
706
- details: {
707
- messages: [],
708
- usage: { ...EMPTY_USAGE },
709
- exitCode: -1,
710
- stderr: "",
711
- },
712
- });
713
-
714
- // Issue #133: per-step run entry — mirrors runParallelMode's
715
- // per-unit block (issue #119): the runId doubles as the live id,
716
- // so sweepStaleLiveSubagents finds a 'running' record for every
717
- // foreground live entry (the #130 invariant gap that swept
718
- // graph/chain entries immediately).
719
- const { runId, run } = createUnitRun(merged, stepModel, chainPriority, globalParams.resolvedPreset?.name, state.config.recovery);
720
- state.persistRun(pi, run, "unit");
721
-
722
- // R2: Prune old run entries if history exceeds limit
723
- pruneHistoryIfNeeded(state, ctx, log);
724
-
725
- // Register for live monitor — chain steps now appear in the
726
- // drill-in under the runId (issue #133 single identity, mirrors
727
- // parallel mode's issue #119 registration). Fall back to
728
- // "Step N" when the step carries no label (liveRowName would
729
- // otherwise show the truncated task).
730
- registerLiveRun(state, run, ctx, merged.label ?? `Step ${i + 1}`);
731
-
732
- // Wrap onUpdate so the live monitor sees per-step progress
733
- // (mirrors parallel mode's taskOnUpdate).
734
- const stepOnUpdate = makeLiveOnUpdate(state, runId, onUpdate);
735
-
736
- // Run the subagent for this step — crash-protected (issue #130,
737
- // #133 R1/C1 discipline): a throw must finalize the run entry as
738
- // failed AND release the live entry, or the persisted record stays
739
- // 'running' forever. finalizeLiveSubagent is idempotent; the
740
- // rethrow is handled by the mode's existing outer catch (chain is
741
- // sequential — no sibling wave to cancel).
742
- let result: SubagentResult;
743
- try {
744
- result = await runSubagent(
745
- // Issue #222: this step's OWN validated cwd (the pre-pass
746
- // resolved it against ctx.cwd) — the mode-level
747
- // resolvedCwd is the fallback for steps that declare none.
748
- stepCwds[i],
749
- subagentPrompt,
750
- stepModel,
751
- merged.thinkingLevel,
752
- merged.task,
753
- signal,
754
- stepOnUpdate,
755
- merged.toolOptions,
756
- merged.timeout,
757
- getFinalOutput,
758
- log,
759
- currentDepth + 1,
760
- undefined, // intercom
761
- undefined, // subagentId
762
- run.childMarker,
763
- );
764
- } catch (err) {
765
- // Issue #133 (mirrors the #119 R1/C1 discipline): finalize the
766
- // run entry as failed — crashOutput comes from the live entry's
767
- // last streamed output (the crash result itself has no
768
- // messages), and errorCategory is classified onto originalParams.
769
- finalizeUnitRunCrash(state, pi, run, err, "Chain step", stepCwds[i], log, {
770
- step: i + 1,
771
- });
772
- }
773
-
774
- // Issue #133: finalize the per-step run entry — status, duration,
775
- // cost, tokens and sanitized output land on the entry (mirrors
776
- // parallel's issue #119 finalize; result carries the SubagentResult
777
- // shape finalizeRunRecord expects, errorCategory included).
778
- finalizeUnitRun(state, pi, ctx, run, result, log);
779
-
780
- // Fill SubTaskResult (one shared field mapping — issue #376/D3).
781
- Object.assign(subTaskResult, toSubTaskResult(result));
782
-
783
- chainResults.push(subTaskResult);
784
-
785
- // Emit update with current ChainDetails
786
- const completedSteps = chainResults.length;
787
- const currentDetails: ChainDetails = {
788
- mode: "chain",
789
- results: chainResults,
790
- totalInput: chainResults.reduce(
791
- (s, r) => s + r.usage.input,
792
- 0,
793
- ),
794
- totalOutput: chainResults.reduce(
795
- (s, r) => s + r.usage.output,
796
- 0,
797
- ),
798
- totalCost: chainResults.reduce(
799
- (s, r) => s + r.usage.cost,
800
- 0,
801
- ),
802
- totalTurns: chainResults.reduce(
803
- (s, r) => s + r.usage.turns,
804
- 0,
805
- ),
806
- completedSteps,
807
- totalSteps: chainSteps.length,
808
- stoppedEarly: false,
809
- };
810
-
811
- const stepFailed = isSubagentError(result);
812
- onUpdate?.({
813
- content: [
814
- {
815
- type: "text" as const,
816
- text: `Chain step ${completedSteps}/${chainSteps.length} completed${stepFailed ? " (failed)" : ""}`,
817
- },
818
- ],
819
- details: currentDetails,
820
- });
821
-
822
- // Stop on failure (unless this was the last step)
823
- if (stepFailed && i < chainSteps.length - 1) {
824
- stoppedEarly = true;
825
- break;
826
- }
827
-
828
- // Set previous output for the next step
829
- previousOutput = getFinalOutput(result.messages);
830
- }
831
-
832
- chainSuccess = countSubagentOutcomes(chainResults).failed === 0;
833
-
834
- // Compute aggregated totals
835
- const totalInput = chainResults.reduce(
836
- (s, r) => s + r.usage.input,
837
- 0,
838
- );
839
- const totalOutput = chainResults.reduce(
840
- (s, r) => s + r.usage.output,
841
- 0,
842
- );
843
- const totalCost = chainResults.reduce(
844
- (s, r) => s + r.usage.cost,
845
- 0,
846
- );
847
- const totalTurns = chainResults.reduce(
848
- (s, r) => s + r.usage.turns,
849
- 0,
850
- );
851
-
852
- const chainDetails: ChainDetails = {
853
- mode: "chain",
854
- results: chainResults,
855
- totalInput,
856
- totalOutput,
857
- totalCost,
858
- totalTurns,
859
- completedSteps: chainResults.length,
860
- totalSteps: chainSteps.length,
861
- stoppedEarly,
862
- };
863
-
864
- // R1: Record circuit breaker outcome
865
- if (chainSuccess) {
866
- state.recordSuccess();
867
- } else {
868
- state.recordFailure();
869
- }
870
-
871
- log.info("Chain completed", {
872
- totalSteps: chainSteps.length,
873
- completedSteps: chainResults.length,
874
- stoppedEarly,
875
- totalInput,
876
- totalOutput,
877
- totalCost,
878
- });
879
-
880
- // Issue #133: one aggregate run entry per chain dispatch — fresh id,
881
- // persisted ONCE as done (no live entry: the drill-in shows the
882
- // per-step entries while running; the aggregate is a post-hoc audit
883
- // summary). Fields come from the dispatch-level resolved values and
884
- // the aggregate totals; startedAt is the mode-entry timestamp.
885
- const chainAggregateRun: SubagentRun = {
886
- id: crypto.randomUUID(),
887
- task: `Chain dispatch: ${chainSteps.length} steps`,
888
- label: globalParams.label ?? "chain",
889
- // Issue #133: persist the ACTUAL outcome — "failed" when any step
890
- // failed (chainSuccess === false), "done" otherwise.
891
- status: chainSuccess ? "done" : "failed",
892
- model: `${subagentModel.provider}/${subagentModel.id}`,
893
- thinkingLevel: globalParams.thinkingLevel,
894
- priority: chainPriority,
895
- startedAt: chainModeStartedAt,
896
- finishedAt: new Date().toISOString(),
897
- durationMs: Date.now() - new Date(chainModeStartedAt).getTime(),
898
- cost: totalCost,
899
- tokensIn: totalInput,
900
- tokensOut: totalOutput,
901
- outputSummary: capOutput(JSON.stringify(chainDetails, null, 2)),
902
- };
903
- state.persistRun(pi, chainAggregateRun);
904
-
905
- // Per-step validation warnings ride the result, prefixed with their
906
- // step (issue #222), after the JSON payload — empty renders nothing so
907
- // warning-free results stay byte-identical.
908
- return {
909
- content: [
910
- {
911
- type: "text" as const,
912
- text: JSON.stringify(chainDetails, null, 2) + formatValidationWarnings(stepWarnings),
913
- },
914
- ],
915
- details: chainDetails,
916
- };
917
- } catch (err) {
918
- // F7 (issue #65): err.message may embed absolute paths — sanitize
919
- // BEFORE it reaches the main agent's context (tool result content +
920
- // details.errorMessage). resolvedCwd is the validated subagent cwd.
921
- const result = buildCrashResult("Chain mode", err, resolvedCwd);
922
- log.error("Chain mode crashed", { error: result.details.errorMessage });
923
- return result;
924
- } finally {
925
- // Issue #133: clear the status-bar mode breakdown — the dispatch is
926
- // over (success or outer-catch crash).
927
- state.modeContext = undefined;
928
- releaseSlot(state, chainSuccess, ctx);
929
- }
930
- }
931
-
932
- // -------------------------------------------------------------------
933
- // P2: runParallelMode
934
- // -------------------------------------------------------------------
935
-
936
- async function runParallelMode(
937
- params: DelegateTaskParams,
938
- signal: AbortSignal | undefined,
939
- onUpdate: AgentToolUpdateCallback<DelegateTaskDetails> | undefined,
940
- ctx: ExtensionContext,
941
- ): Promise<ToolResult<SubagentResult | ParallelDetails | undefined>> {
942
- const taskList: SubTaskParams[] = params.tasks!;
943
-
944
- // Mode prologue (issue #379): cost → depth → resolve → targets →
945
- // preflight → H1, the sequence every batch mode shares (mode-prologue.ts).
946
- // Parallel's per-mode inputs are only the label and the unit count; H1
947
- // validates the MODE-level params (top-level tasks are empty, so only the
948
- // hard outputFile-vs-write conflict applies — issue #34), while every
949
- // task's own cwd/outputFile/tools belong to the per-task pass below.
950
- const pro = runModePrologue({
951
- params,
952
- state,
953
- ctx,
954
- log,
955
- label: "Parallel",
956
- units: taskList.length,
957
- });
958
- if (!pro.ok) return pro.error;
959
- const { globalParams, resolvedCwd, currentDepth } = pro;
960
-
961
- // Per-task pre-pass (issue #220, extended by #222): validate EVERY task
962
- // before any spawn, so a single bad task rejects the batch with nothing
963
- // started (`force` degrades capability errors to warnings) — the same
964
- // semantics runBackgroundFanOut applies. Each task's OWN cwd is resolved
965
- // and validated here (with its outputFile, resolved against that cwd) and
966
- // the resolved value is what that task spawns in — issue #222 closed the
967
- // gap where a per-task `cwd` was merged but the spawn still used the
968
- // mode-level cwd. Per-task warnings are prefixed with their unit and
969
- // collected here to ride the final result. The mode-entry validation
970
- // above stays for the mode-level outputFile (issue #34).
971
- const taskPass = validateUnitPrePass({
972
- units: taskList,
973
- label: "Parallel",
974
- gitMode: globalParams.resolvedGitMode,
975
- ctx,
976
- log,
977
- force: params.force as boolean | undefined,
978
- noJev: params.noJev,
979
- merge: (task) => mergeSubTaskParams(globalParams, task),
980
- describe: (_task, merged, i) => ({
981
- prefix: `Task ${i + 1} ("${displayTaskName(merged)}")`,
982
- logContext: { task: i + 1 },
983
- }),
984
- });
985
- if (!taskPass.ok) return taskPass.error;
986
- // Parallel index → the task's own validated cwd (issue #222).
987
- const taskCwds = taskPass.units.map((u) => u.cwd);
988
- const taskWarnings = taskPass.warnings;
989
-
990
- // Mode tail (issue #379): model resolution (preset + per-call override,
991
- // auto-route included in `resolvedPreset`), the empty-model rejection and
992
- // the circuit check. Runs AFTER the per-task pass (IN8).
993
- const tail = resolveModeModel({
994
- state,
995
- ctx,
996
- log,
997
- preset: globalParams.resolvedPreset,
998
- perCallModel: params.model,
999
- });
1000
- if (!tail.ok) return tail.error;
1001
- const subagentModel = tail.model;
1002
- const modelStr = tail.modelStr;
1003
-
1004
- // Build base prompt once
1005
- const basePrompt = ctx.getSystemPrompt();
1006
-
1007
- // Results array — final positions match taskList indices
1008
- const results: SubTaskResult[] = [];
1009
- let completedCount = 0;
1010
-
1011
- // E10: Intercom for subagent-to-subagent messaging
1012
- const intercom = new Intercom();
1013
-
1014
- // Individual task runner (captures merged params, runs subagent)
1015
- const runTask = async (
1016
- index: number,
1017
- merged: ReturnType<typeof mergeSubTaskParams>,
1018
- unitCwd: string,
1019
- ): Promise<boolean> => {
1020
-
1021
- // C3: Resolve this step's model override (step.model > global resolved model)
1022
- const stepModel = resolveStepModel(ctx, merged.model, subagentModel);
1023
-
1024
- // Build system prompt for this task
1025
- const subagentPrompt = buildSubagentPrompt(
1026
- basePrompt,
1027
- merged.inheritSP,
1028
- merged.customSP,
1029
- merged.outputFile,
1030
- merged.toolOptions?.tools,
1031
- globalParams.resolvedPreset?.promptGuideline,
1032
- );
1033
-
1034
- // Create SubTaskResult
1035
- const subTaskResult: SubTaskResult = {
1036
- task: merged.task,
1037
- label: merged.label,
1038
- exitCode: 0,
1039
- messages: [],
1040
- stderr: "",
1041
- usage: { ...EMPTY_USAGE },
1042
- };
1043
-
1044
- // E10: Register subagent ID for intercom
1045
- const subagentId = merged.label ?? `parallel-${index}`;
1046
- intercom.register(subagentId);
1047
-
1048
- // Issue #119: per-subtask run entry — created at spawn so the
1049
- // monitor drill-in shows per-unit priority and a post-hoc audit
1050
- // trail exists per subtask (mirrors single-mode run persistence).
1051
- const { runId, run } = createUnitRun(merged, stepModel, parallelPriority, globalParams.resolvedPreset?.name, state.config.recovery);
1052
- state.persistRun(pi, run, "unit");
1053
-
1054
- // R2: Prune old run entries if history exceeds limit
1055
- pruneHistoryIfNeeded(state, ctx, log);
1056
-
1057
- // Register for live monitor — parallel subtasks now appear in the
1058
- // drill-in with their per-unit priority (issue #119).
1059
- registerLiveRun(state, run, ctx);
1060
-
1061
- log.debug("Parallel subtask run registered", { runId, index });
1062
-
1063
- // Emit initial progress
1064
- const modeInfo = describePromptMode(
1065
- merged.inheritSP,
1066
- Boolean(merged.customSP),
1067
- );
1068
- onUpdate?.({
1069
- content: [
1070
- {
1071
- type: "text" as const,
1072
- text: `Parallel task ${index + 1}/${taskList.length} (${modeInfo})...`,
1073
- },
1074
- ],
1075
- details: {
1076
- messages: [],
1077
- usage: { ...EMPTY_USAGE },
1078
- exitCode: -1,
1079
- stderr: "",
1080
- },
1081
- });
1082
-
1083
- // Wrap onUpdate for per-task progress — also feed the live monitor so
1084
- // the drill-in streams output instead of showing "waiting for first
1085
- // output…" for the whole run (mirrors single mode's liveOnUpdate).
1086
- const taskOnUpdate = makeLiveOnUpdate(state, runId, onUpdate);
1087
-
1088
- // Run subagent — the post-spawn body is crash-protected (issue #119
1089
- // R1, C1 fix): a throw here (e.g. runner writeToTempFile) must
1090
- // finalize the run entry and release the live monitor, or the entry
1091
- // stays 'running' forever and sweepStaleLiveSubagents cannot reclaim
1092
- // the live ghost (grace logic treats a 'running' record as live).
1093
- try {
1094
- const result = await runSubagent(
1095
- // Issue #222: this task's OWN validated cwd.
1096
- unitCwd,
1097
- subagentPrompt,
1098
- stepModel,
1099
- merged.thinkingLevel,
1100
- merged.task,
1101
- signal,
1102
- taskOnUpdate,
1103
- merged.toolOptions,
1104
- merged.timeout,
1105
- getFinalOutput,
1106
- log,
1107
- currentDepth + 1,
1108
- intercom,
1109
- subagentId,
1110
- run.childMarker,
1111
- );
1112
-
1113
- // Fill SubTaskResult (one shared field mapping — issue #376/D3).
1114
- Object.assign(subTaskResult, toSubTaskResult(result));
1115
-
1116
- results[index] = subTaskResult;
1117
- completedCount++;
1118
-
1119
- // Issue #119: finalize the per-subtask run entry — status, duration,
1120
- // cost, tokens and sanitized output land on the entry (mirrors
1121
- // single-mode finalization; result carries the SubagentResult shape
1122
- // finalizeRunRecord expects, errorCategory included).
1123
- finalizeUnitRun(state, pi, ctx, run, result, log);
1124
- } catch (err) {
1125
- // Issue #119 R1 (C1 fix): mirror the single-mode crash catch — a
1126
- // post-spawn throw must finalize the entry as failed and release
1127
- // the live monitor, or the persisted entry stays 'running' and
1128
- // the live drill-in loops forever. finalizeLiveSubagent is
1129
- // idempotent; the rethrow keeps Promise.allSettled semantics (the
1130
- // caller's finally still releases the concurrency slot).
1131
- finalizeUnitRunCrash(state, pi, run, err, "Parallel subtask", unitCwd, log, {
1132
- index,
1133
- });
1134
- }
1135
-
1136
- // Emit progress update
1137
- const { succeeded, failed } = countSubagentOutcomes(results);
1138
- const completed = succeeded + failed;
1139
-
1140
- const partialDetails: ParallelDetails = {
1141
- mode: "parallel",
1142
- results: results.filter((r) => r !== undefined),
1143
- totalInput: results.reduce(
1144
- (s, r) => s + (r?.usage.input ?? 0),
1145
- 0,
1146
- ),
1147
- totalOutput: results.reduce(
1148
- (s, r) => s + (r?.usage.output ?? 0),
1149
- 0,
1150
- ),
1151
- totalCost: results.reduce(
1152
- (s, r) => s + (r?.usage.cost ?? 0),
1153
- 0,
1154
- ),
1155
- totalTurns: results.reduce(
1156
- (s, r) => s + (r?.usage.turns ?? 0),
1157
- 0,
1158
- ),
1159
- succeeded,
1160
- failed,
1161
- };
1162
-
1163
- onUpdate?.({
1164
- content: [
1165
- {
1166
- type: "text" as const,
1167
- text: `Parallel: ${completed}/${taskList.length} completed (${succeeded} succeeded, ${failed} failed)`,
1168
- },
1169
- ],
1170
- details: partialDetails,
1171
- });
1172
-
1173
- // Issue #137: return the unit's real success so the caller's slot
1174
- // release is honest — the status bar's "N failed" count reflects the
1175
- // true outcome (same check as the aggregate chainSuccess).
1176
- return !isSubagentError(subTaskResult);
1177
- };
1178
-
1179
- // Resolve priority — the FALLBACK for per-unit priority (issue #114): a
1180
- // task-level priority on tasks[] items wins per slot; this is the floor.
1181
- const parallelPriority: Priority = (
1182
- params.priority && ["critical", "high", "normal", "low"].includes(params.priority as string)
1183
- ? (params.priority as Priority)
1184
- : DEFAULT_PRIORITY
1185
- );
1186
-
1187
- // Launch all tasks concurrently using acquireSlot for natural concurrency limiting
1188
- const promises = taskList.map(async (_, index) => {
1189
- // Issue #114: per-unit priority wins the slot — the step's merged
1190
- // priority (if any) beats the call-level parallelPriority fallback.
1191
- const merged = mergeSubTaskParams(globalParams, taskList[index]);
1192
- const acquired = await acquireSlot(state, ctx, signal, merged.priority ?? parallelPriority);
1193
- if (!acquired) {
1194
- results[index] = {
1195
- task: taskList[index].task,
1196
- exitCode: 1,
1197
- messages: [],
1198
- stderr: "",
1199
- usage: { ...EMPTY_USAGE },
1200
- errorMessage:
1201
- "Cancelled while waiting for concurrency slot",
1202
- errorCategory: "aborted",
1203
- };
1204
- completedCount++;
1205
- return;
1206
- }
1207
- let taskSuccess = false;
1208
- try {
1209
- taskSuccess = await runTask(index, merged, taskCwds[index]);
1210
- } finally {
1211
- // Issue #137: release with the unit's real success — the status
1212
- // bar's "N failed" count reflects the true outcome.
1213
- releaseSlot(state, taskSuccess, ctx);
1214
- }
1215
- });
1216
-
1217
- await Promise.allSettled(promises);
1218
-
1219
- // Compute final aggregates
1220
- const finalResults = results.filter(Boolean);
1221
- const totalInput = finalResults.reduce(
1222
- (s, r) => s + r.usage.input,
1223
- 0,
1224
- );
1225
- const totalOutput = finalResults.reduce(
1226
- (s, r) => s + r.usage.output,
1227
- 0,
1228
- );
1229
- const totalCost = finalResults.reduce(
1230
- (s, r) => s + r.usage.cost,
1231
- 0,
1232
- );
1233
- const totalTurns = finalResults.reduce(
1234
- (s, r) => s + r.usage.turns,
1235
- 0,
1236
- );
1237
- const { succeeded, failed } = countSubagentOutcomes(finalResults);
1238
-
1239
- const parallelDetails: ParallelDetails = {
1240
- mode: "parallel",
1241
- results: finalResults,
1242
- totalInput,
1243
- totalOutput,
1244
- totalCost,
1245
- totalTurns,
1246
- succeeded,
1247
- failed,
1248
- };
1249
-
1250
- // R1: Record circuit breaker outcome
1251
- if (failed === 0) {
1252
- state.recordSuccess();
1253
- } else {
1254
- state.recordFailure();
1255
- }
1256
-
1257
- log.info("Parallel execution completed", {
1258
- totalTasks: taskList.length,
1259
- succeeded,
1260
- failed,
1261
- totalInput,
1262
- totalOutput,
1263
- totalCost,
1264
- });
1265
-
1266
- // C: per-task validation warnings ride the result, prefixed with their
1267
- // task (issue #220), after the JSON payload — empty renders nothing so
1268
- // warning-free results stay byte-identical.
1269
- return {
1270
- content: [
1271
- {
1272
- type: "text" as const,
1273
- text: JSON.stringify(parallelDetails, null, 2) + formatValidationWarnings(taskWarnings),
1274
- },
1275
- ],
1276
- details: parallelDetails,
1277
- };
1278
- }
1279
-
1280
- // -------------------------------------------------------------------
1281
- // P10: runGraphMode
1282
- // -------------------------------------------------------------------
1283
-
1284
- async function runGraphMode(
1285
- params: DelegateTaskParams,
1286
- signal: AbortSignal | undefined,
1287
- onUpdate: AgentToolUpdateCallback<DelegateTaskDetails> | undefined,
1288
- ctx: ExtensionContext,
1289
- ): Promise<ToolResult<SubagentResult | GraphDetails | undefined>> {
1290
- const graphTasks: GraphTask[] = params.graph!;
1291
-
1292
- // Issue #133: dispatch-start timestamp — the aggregate run entry's
1293
- // startedAt (captured once, at mode entry, not at completion).
1294
- const graphModeStartedAt = new Date().toISOString();
1295
-
1296
- // Mode prologue (issue #379): cost → depth → resolve → targets →
1297
- // preflight → H1, with the DAG check as the graph-only pre-cost hook — a
1298
- // malformed graph (empty / over-limit / duplicate id / missing dep) is
1299
- // rejected before the session spends anything (IN1 boundary). Cycles are
1300
- // NOT caught here; topologicalSort rejects them after the tail.
1301
- const pro = runModePrologue({
1302
- params,
1303
- state,
1304
- ctx,
1305
- log,
1306
- label: "Graph",
1307
- units: graphTasks.length,
1308
- beforeCost: () => {
1309
- const errors = validateGraph(graphTasks);
1310
- return errors.length === 0
1311
- ? undefined
1312
- : rejection(`Graph validation failed:\n${errors.map((e) => ` - ${e}`).join("\n")}`);
1313
- },
1314
- });
1315
- if (!pro.ok) return pro.error;
1316
- const { globalParams, resolvedCwd, currentDepth } = pro;
1317
-
1318
- // Mode tail (issue #379): model resolution (preset + per-call override,
1319
- // auto-route included in `resolvedPreset`), the empty-model rejection and
1320
- // the circuit check. It runs BEFORE the topological sort and the per-node
1321
- // pass (IN8/IN11): a graph with a bad node AND an unconfigured model
1322
- // reports the MODEL error first.
1323
- const tail = resolveModeModel({
1324
- state,
1325
- ctx,
1326
- log,
1327
- preset: globalParams.resolvedPreset,
1328
- perCallModel: params.model,
1329
- });
1330
- if (!tail.ok) return tail.error;
1331
- const subagentModel = tail.model;
1332
- const modelStr = tail.modelStr;
1333
-
1334
- // Resolve priority — the FALLBACK for per-unit priority (issue #114): a
1335
- // task-level priority on graph[] items wins per slot; this is the floor.
1336
- const graphPriority: Priority = (
1337
- params.priority && ["critical", "high", "normal", "low"].includes(params.priority as string)
1338
- ? (params.priority as Priority)
1339
- : DEFAULT_PRIORITY
1340
- );
1341
-
1342
- // Topological sort → execution waves
1343
- const sortResult = topologicalSort(graphTasks);
1344
- if (!sortResult.ok) {
1345
- return {
1346
- content: [
1347
- { type: "text" as const, text: `Graph scheduling failed: ${sortResult.error}` },
1348
- ],
1349
- details: undefined,
1350
- isError: true,
1351
- };
1352
- }
1353
- const waves = sortResult.waves;
1354
-
1355
- // Per-node pre-pass (issue #222): resolve + validate EVERY node before
1356
- // any spawn, so a single bad node rejects the whole graph with nothing
1357
- // started — the same all-before-any-spawn semantics the background
1358
- // fan-out, the parallel `tasks` shape and the chain use. Each node's OWN
1359
- // cwd is resolved and validated here (with its outputFile, resolved
1360
- // against that cwd) and the resolved value is what that node spawns in.
1361
- // The pre-pass runs on the DECLARED task text, before {id} substitution
1362
- // (the substituted text is only known mid-dispatch, once a dependency's
1363
- // output exists) — the declared text is validated with the placeholder
1364
- // TOKENS stripped (a dependency whose id happens to be a blocking
1365
- // keyword must not make `{<id>}` itself trip the keyword rules), while
1366
- // the SUBSTITUTED content stays unvalidated by design. The host's own
1367
- // wording is still validated, and refusing to validate up front would
1368
- // mean a bad node in the LAST wave is discovered after every earlier
1369
- // wave already spent its budget.
1370
- const nodePass = validateUnitPrePass({
1371
- units: graphTasks,
1372
- label: "Graph",
1373
- gitMode: globalParams.resolvedGitMode,
1374
- ctx,
1375
- log,
1376
- force: params.force as boolean | undefined,
1377
- noJev: params.noJev,
1378
- merge: (node) => mergeSubTaskParams(globalParams, graphTaskToSubTaskParams(node)),
1379
- describe: (node, merged) => ({
1380
- prefix: `Node "${node.id}"`,
1381
- logContext: { id: node.id },
1382
- // Placeholder TOKENS stripped (issue #222 review): the rules
1383
- // read the declared string, so a `{<id>}` whose dependency id
1384
- // is a blocking keyword would block on a token, not on text
1385
- // the host wrote. The declared wording around it is unchanged
1386
- // and still validated. Graph policy — it stays here, not in
1387
- // the shared helper.
1388
- task: merged.task.replace(GRAPH_OUTPUT_PLACEHOLDER_RE, " "),
1389
- }),
1390
- });
1391
- if (!nodePass.ok) return nodePass.error;
1392
- const nodeCwds = new Map(nodePass.units.map((u) => [u.unit.id, u.cwd] as const));
1393
- const nodeWarnings = nodePass.warnings;
1394
-
1395
- // Build base prompt once
1396
- const basePrompt = ctx.getSystemPrompt();
1397
-
1398
- // Results map: task id → SubTaskResult (populated as waves complete)
1399
- const resultMap = new Map<string, SubTaskResult>();
1400
- const allWaves: GraphWave[] = [];
1401
-
1402
- // E10: Intercom for subagent-to-subagent messaging
1403
- const intercom = new Intercom();
1404
-
1405
- // Issue #133: global node counter — node positions are reported against
1406
- // the WHOLE dispatch (dispatch-wide ordinal), not the current wave; a
1407
- // later wave's first node is its true global position (e.g. node 3/5),
1408
- // not "node 1/5". Incremented once per node as each wave's nodes run.
1409
- let globalNodeCounter = 0;
1410
- let chainSuccess = false;
1411
- try {
1412
- for (let w = 0; w < waves.length; w++) {
1413
- const wave = waves[w];
1414
- const waveIndex = w + 1;
1415
- const isParallel = wave.length > 1;
1416
-
1417
- // Issue #133: status-bar breakdown — wave-level context set at
1418
- // each wave start (nodes within the wave refine it as they start).
1419
- state.modeContext = {
1420
- kind: "graph",
1421
- wave: waveIndex,
1422
- totalWaves: waves.length,
1423
- node: 0,
1424
- totalNodes: graphTasks.length,
1425
- };
1426
-
1427
- // Emit initial progress
1428
- onUpdate?.({
1429
- content: [
1430
- {
1431
- type: "text" as const,
1432
- text: `Graph wave ${waveIndex}/${waves.length} (${wave.length} task${wave.length > 1 ? "s" : ""})...`,
1433
- },
1434
- ],
1435
- details: {
1436
- messages: [],
1437
- usage: { ...EMPTY_USAGE },
1438
- exitCode: -1,
1439
- stderr: "",
1440
- },
1441
- });
1442
-
1443
- // Run all tasks in this wave concurrently
1444
- const wavePromises = wave.map(async (graphTask, nodeIndex) => {
1445
- // Issue #133: capture this node's dispatch-wide ordinal before any
1446
- // sibling node advances the counter (same-wave siblings run
1447
- // concurrently, so the value must be pinned here).
1448
- const globalNode = ++globalNodeCounter;
1449
- const subTaskParams = graphTaskToSubTaskParams(graphTask);
1450
-
1451
- const merged = mergeSubTaskParams(globalParams, subTaskParams);
1452
- // Issue #222: the node's OWN validated cwd (pre-pass);
1453
- // resolvedCwd (the mode-level cwd) is the guaranteed
1454
- // fallback, so a node that declares none still resolves.
1455
- const nodeCwd = nodeCwds.get(graphTask.id) ?? resolvedCwd;
1456
-
1457
- // C3: Resolve this step's model override (step.model > global resolved model)
1458
- const stepModel = resolveStepModel(ctx, merged.model, subagentModel);
1459
-
1460
- // Substitute {id} placeholders with previous outputs
1461
- merged.task = merged.task.replace(GRAPH_OUTPUT_PLACEHOLDER_RE, (_match, id) => {
1462
- const depResult = resultMap.get(id);
1463
- if (!depResult) return _match; // Leave unchanged if dep not found
1464
- return getFinalOutput(depResult.messages);
1465
- });
1466
-
1467
- // Build system prompt
1468
- const subagentPrompt = buildSubagentPrompt(
1469
- basePrompt,
1470
- merged.inheritSP,
1471
- merged.customSP,
1472
- merged.outputFile,
1473
- merged.toolOptions?.tools,
1474
- globalParams.resolvedPreset?.promptGuideline,
1475
- );
1476
-
1477
- // Acquire concurrency slot — issue #114: per-unit priority wins the
1478
- // slot; the call-level graphPriority is the fallback.
1479
- const acquired = await acquireSlot(state, ctx, signal, merged.priority ?? graphPriority);
1480
- if (!acquired) {
1481
- return {
1482
- id: graphTask.id,
1483
- result: {
1484
- task: merged.task,
1485
- label: merged.label,
1486
- exitCode: 1,
1487
- messages: [],
1488
- stderr: "",
1489
- usage: { ...EMPTY_USAGE },
1490
- errorMessage: "Cancelled while waiting for concurrency slot",
1491
- errorCategory: "aborted" as const,
1492
- } satisfies SubTaskResult,
1493
- };
1494
- }
1495
-
1496
- const subagentId = graphTask.id;
1497
- intercom.register(subagentId);
1498
-
1499
- // Issue #133: status-bar breakdown — the node's dispatch-wide
1500
- // position (globalNode, not the wave-local nodeIndex) so a later
1501
- // wave reports its true global ordinal.
1502
- state.modeContext = {
1503
- kind: "graph",
1504
- wave: waveIndex,
1505
- totalWaves: waves.length,
1506
- node: globalNode,
1507
- totalNodes: graphTasks.length,
1508
- };
1509
-
1510
- // Issue #133: per-node run entry — mirrors runParallelMode's
1511
- // per-unit block (issue #119): the runId doubles as the live id,
1512
- // so sweepStaleLiveSubagents finds a 'running' record for every
1513
- // foreground live entry (the #130 invariant gap that swept
1514
- // graph/chain entries immediately).
1515
- const { runId, run } = createUnitRun(merged, stepModel, graphPriority, globalParams.resolvedPreset?.name, state.config.recovery);
1516
- state.persistRun(pi, run, "unit");
1517
-
1518
- // R2: Prune old run entries if history exceeds limit
1519
- pruneHistoryIfNeeded(state, ctx, log);
1520
-
1521
- // Register for live monitor — graph nodes now appear in the
1522
- // drill-in under the runId with their per-unit priority
1523
- // (issue #133 single identity, mirrors parallel mode's issue
1524
- // #119 registration). A FRESH runId per node: subagentSessions
1525
- // is host-global, so raw graph-task ids would collide across
1526
- // concurrent graph runs (the intercom namespace is per-run and
1527
- // stays untouched).
1528
- registerLiveRun(state, run, ctx);
1529
-
1530
- let nodeSuccess = false;
1531
- try {
1532
- // Wrap onUpdate for per-node progress — also feed the live
1533
- // monitor so the drill-in streams output instead of showing
1534
- // "waiting for first output…" (mirrors parallel mode's
1535
- // taskOnUpdate).
1536
- const stepOnUpdate = makeLiveOnUpdate(state, runId, onUpdate);
1537
-
1538
- const result = await runSubagent(
1539
- nodeCwd,
1540
- subagentPrompt,
1541
- stepModel,
1542
- merged.thinkingLevel,
1543
- merged.task,
1544
- signal,
1545
- stepOnUpdate,
1546
- merged.toolOptions,
1547
- merged.timeout,
1548
- getFinalOutput,
1549
- log,
1550
- currentDepth + 1,
1551
- intercom,
1552
- subagentId,
1553
- run.childMarker,
1554
- );
1555
-
1556
- // One shared field mapping — issue #376/D3 (the graph literal was a
1557
- // third copy of it).
1558
- const subTaskResult: SubTaskResult = {
1559
- task: merged.task,
1560
- label: merged.label,
1561
- ...toSubTaskResult(result),
1562
- };
1563
-
1564
- // Issue #133: finalize the per-node run entry — status, duration,
1565
- // cost, tokens and sanitized output land on the entry (mirrors
1566
- // parallel's issue #119 finalize; result carries the
1567
- // SubagentResult shape finalizeRunRecord expects, errorCategory
1568
- // included).
1569
- finalizeUnitRun(state, pi, ctx, run, result, log);
1570
- // Issue #137: the node's real success — the status bar's
1571
- // "N failed" count reflects the true outcome (same check as
1572
- // the aggregate chainSuccess).
1573
- nodeSuccess = !isSubagentError(result);
1574
-
1575
- return { id: graphTask.id, result: subTaskResult };
1576
- } catch (err) {
1577
- // Issue #133 (mirrors the #119 R1/C1 discipline): crash-protected
1578
- // — a post-spawn throw must finalize the run entry as failed AND
1579
- // release the live entry, or the persisted record stays
1580
- // 'running' forever and the sweep treats the ghost as live.
1581
- // finalizeLiveSubagent is idempotent; the rethrow keeps
1582
- // Promise.allSettled semantics (a failing node must NOT cancel
1583
- // sibling nodes in the wave).
1584
- finalizeUnitRunCrash(state, pi, run, err, "Graph node", nodeCwd, log, {
1585
- id: graphTask.id,
1586
- });
1587
- } finally {
1588
- releaseSlot(state, nodeSuccess, ctx);
1589
- }
1590
- });
1591
-
1592
- const waveResults = await Promise.allSettled(wavePromises);
1593
- const graphWaveTasks: SubTaskResult[] = [];
1594
-
1595
- for (const settled of waveResults) {
1596
- if (settled.status === "fulfilled") {
1597
- resultMap.set(settled.value.id, settled.value.result);
1598
- graphWaveTasks.push(settled.value.result);
1599
- } else {
1600
- log.error("Graph wave task rejected", { error: String(settled.reason) });
1601
- }
1602
- }
1603
-
1604
- const graphWave: GraphWave = {
1605
- waveIndex,
1606
- tasks: graphWaveTasks,
1607
- parallel: isParallel,
1608
- };
1609
- allWaves.push(graphWave);
1610
-
1611
- // Emit progress update
1612
- onUpdate?.({
1613
- details: undefined,
1614
- content: [
1615
- {
1616
- type: "text" as const,
1617
- text: `Graph wave ${waveIndex}/${waves.length} completed`,
1618
- },
1619
- ],
1620
- });
1621
- }
1622
-
1623
- // Compute final aggregates
1624
- const allResults = allWaves.flatMap((w) => w.tasks);
1625
- const totalInput = allResults.reduce((s, r) => s + r.usage.input, 0);
1626
- const totalOutput = allResults.reduce((s, r) => s + r.usage.output, 0);
1627
- const totalCost = allResults.reduce((s, r) => s + r.usage.cost, 0);
1628
- const totalTurns = allResults.reduce((s, r) => s + r.usage.turns, 0);
1629
-
1630
- chainSuccess = countSubagentOutcomes(allResults).failed === 0;
1631
-
1632
- const graphDetails: GraphDetails = {
1633
- mode: "graph",
1634
- waves: allWaves,
1635
- totalInput,
1636
- totalOutput,
1637
- totalCost,
1638
- totalTurns,
1639
- };
1640
-
1641
- // R1: Record circuit breaker outcome
1642
- if (chainSuccess) {
1643
- state.recordSuccess();
1644
- } else {
1645
- state.recordFailure();
1646
- }
1647
-
1648
- log.info("Graph completed", {
1649
- totalTasks: graphTasks.length,
1650
- waves: allWaves.length,
1651
- totalInput,
1652
- totalOutput,
1653
- totalCost,
1654
- });
1655
-
1656
- // Issue #133: one aggregate run entry per graph dispatch — fresh id,
1657
- // persisted ONCE as done (no live entry: the drill-in shows the
1658
- // per-node entries while running; the aggregate is a post-hoc audit
1659
- // summary). Fields come from the dispatch-level resolved values and
1660
- // the aggregate totals; startedAt is the mode-entry timestamp.
1661
- const graphAggregateRun: SubagentRun = {
1662
- id: crypto.randomUUID(),
1663
- task: `Graph dispatch: ${graphTasks.length} tasks in ${allWaves.length} waves`,
1664
- label: globalParams.label ?? "graph",
1665
- // Issue #133: persist the ACTUAL outcome — "failed" when any node
1666
- // failed (chainSuccess === false), "done" otherwise.
1667
- status: chainSuccess ? "done" : "failed",
1668
- model: `${subagentModel.provider}/${subagentModel.id}`,
1669
- thinkingLevel: globalParams.thinkingLevel,
1670
- priority: graphPriority,
1671
- startedAt: graphModeStartedAt,
1672
- finishedAt: new Date().toISOString(),
1673
- durationMs: Date.now() - new Date(graphModeStartedAt).getTime(),
1674
- cost: totalCost,
1675
- tokensIn: totalInput,
1676
- tokensOut: totalOutput,
1677
- outputSummary: capOutput(JSON.stringify(graphDetails, null, 2)),
1678
- };
1679
- state.persistRun(pi, graphAggregateRun);
1680
-
1681
- // Per-node validation warnings ride the result, prefixed with their
1682
- // node id (issue #222), after the JSON payload — empty renders
1683
- // nothing so warning-free results stay byte-identical.
1684
- return {
1685
- content: [
1686
- {
1687
- type: "text" as const,
1688
- text: JSON.stringify(graphDetails, null, 2) + formatValidationWarnings(nodeWarnings),
1689
- },
1690
- ],
1691
- details: graphDetails,
1692
- };
1693
- } catch (err) {
1694
- // F7 (issue #65): err.message may embed absolute paths — sanitize
1695
- // BEFORE it reaches the main agent's context (tool result content +
1696
- // details.errorMessage). resolvedCwd is the validated subagent cwd.
1697
- const result = buildCrashResult("Graph mode", err, resolvedCwd);
1698
- log.error("Graph mode crashed", { error: result.details.errorMessage });
1699
- return result;
1700
- } finally {
1701
- // Issue #133: clear the status-bar mode breakdown — the dispatch is
1702
- // over (success or outer-catch crash).
1703
- state.modeContext = undefined;
1704
- releaseSlot(state, chainSuccess, ctx);
1705
- }
1706
- }
1707
-
1708
- // -------------------------------------------------------------------
1709
- // runBackgroundFanOut — background fan-out for tasks mode.
1710
- // Resolves + validates the WHOLE batch up front (no spawn on any
1711
- // failure), then spawns the tasks sequentially, in task order, through the
1712
- // shared startBackgroundAgent tail, and returns immediately with their ids.
1713
- // Foreground-only gates (preflight, circuit breaker, recursion depth) are
1714
- // deliberately skipped — the single-background path skips them too.
1715
- // -------------------------------------------------------------------
1716
-
1717
- async function runBackgroundFanOut(
1718
- pi: ExtensionAPI,
1719
- ctx: ExtensionContext,
1720
- params: DelegateTaskParams,
1721
- signal: AbortSignal | undefined,
1722
- ): Promise<ToolResult<SubagentResult | undefined>> {
1723
- const taskList: SubTaskParams[] = params.tasks!;
1724
-
1725
- // Session cost limit gates the WHOLE batch before any spawn — same
1726
- // estimate/limit logic as runParallelMode, scaled by task count.
1727
- const costError = gateSessionCost({
1728
- state,
1729
- ctx,
1730
- log,
1731
- units: taskList.length,
1732
- label: "Background fan-out",
1733
- });
1734
- if (costError) return costError;
1735
-
1736
- // Resolve global params once — same call shape as runParallelMode.
1737
- const globalParams = resolveSubagentParams(params, state, ctx, log);
1738
-
1739
- // Resolve the global model once (per-call model beats preset/config).
1740
- const globalModelResult = resolveSubagentModel(
1741
- ctx,
1742
- globalParams.resolvedPreset,
1743
- params.model as string | undefined,
1744
- );
1745
- if (!globalModelResult.ok) return globalModelResult.error;
1746
- const globalModel = globalModelResult.model;
1747
-
1748
- // Same rejection as the single-background path: approvalMode 'always'
1749
- // cannot work in background — there is no interactive dialog to approve
1750
- // the diff, for any of the N agents.
1751
- const approvalError = rejectApprovalAlwaysInBackground(globalParams.resolvedApprovalMode);
1752
- if (approvalError) return approvalError;
1753
- // W5 parity with the single-background path: 'writes' silently
1754
- // auto-approves in background — warn once so the caller knows none of
1755
- // the N agents' diffs will be gated on approval.
1756
- if (globalParams.resolvedApprovalMode === 'writes') {
1757
- log.warn("Background fan-out spawned with approvalMode 'writes' — auto-approving (no dialog in background)", {
1758
- tasks: taskList.length,
1759
- });
1760
- }
1761
-
1762
- // gitMode 'branch' is rejected for the whole batch: the per-repository
1763
- // git lock is awaited inside the first spawn and held until that agent
1764
- // settles, so same-repository branch-mode spawns would serialize and
1765
- // block this call for the whole chain. The rule is blanket (not
1766
- // per-repository-checked) because the lock is keyed by the resolved
1767
- // repository root: units in different directories of one repo share the
1768
- // working tree and contend for the same lock.
1769
- if (globalParams.resolvedGitMode === 'branch') {
1770
- return {
1771
- content: [{ type: "text" as const, text:
1772
- `Cannot start ${taskList.length} background agents with gitMode 'branch': the per-repository git lock ` +
1773
- `is awaited by the first spawn and held until that agent settles, so same-repository branch-mode ` +
1774
- `spawns would serialize and block this call for the whole chain. Background fan-out therefore ` +
1775
- `rejects gitMode 'branch' for all tasks in this version. Use gitMode 'none' for the batch, or ` +
1776
- `dispatch each unit as a separate single-task background call.`
1777
- }],
1778
- details: undefined,
1779
- isError: true,
1780
- };
1781
- }
1782
-
1783
- // Per-task pre-pass: resolve + validate EVERYTHING before any spawn, so a
1784
- // single bad task rejects the whole batch with nothing started.
1785
- type FanOutTask = {
1786
- merged: ReturnType<typeof mergeSubTaskParams>;
1787
- model: { provider: string; id: string };
1788
- cwd: string;
1789
- outputFile: string | undefined;
1790
- };
1791
-
1792
- const fanOutTasks: FanOutTask[] = [];
1793
- // C: per-task warnings collect here to ride the immediate spawn result.
1794
- const taskWarnings: string[] = [];
1795
- for (let i = 0; i < taskList.length; i++) {
1796
- const merged = mergeSubTaskParams(globalParams, taskList[i]);
1797
- const name = displayTaskName(merged);
1798
- const taskPrefix = `Task ${i + 1} ("${name}")`;
1799
- // Per-task model override wins; the global model is the fallback.
1800
- const stepModel = resolveStepModel(ctx, merged.model, globalModel);
1801
-
1802
- const targets = validateDelegationTargets({
1803
- ctx,
1804
- effectiveCwd: merged.effectiveCwd,
1805
- outputFile: merged.outputFile,
1806
- prefix: taskPrefix,
1807
- });
1808
- if (!targets.ok) return targets.error;
1809
-
1810
- const preTask = runPreTaskValidation({
1811
- log,
1812
- label: "Background fan-out",
1813
- prefix: taskPrefix,
1814
- logContext: { task: i + 1 },
1815
- preTask: {
1816
- task: merged.task,
1817
- toolOptions: merged.toolOptions,
1818
- thinkingLevel: merged.thinkingLevel,
1819
- gitMode: globalParams.resolvedGitMode,
1820
- outputFile: merged.outputFile,
1821
- force: params.force as boolean | undefined,
1822
- cwd: targets.cwd,
1823
- noJev: params.noJev,
1824
- },
1825
- });
1826
- if (preTask.error) return preTask.error;
1827
- for (const w of preTask.warnings) taskWarnings.push(`${taskPrefix}: ${w}`);
1828
-
1829
- fanOutTasks.push({ merged, model: stepModel, cwd: targets.cwd, outputFile: targets.outputFile });
1830
- }
1831
-
1832
- // Spawn pass — sequential, in task order, through the shared tail.
1833
- const started: Array<{ id: string; label?: string }> = [];
1834
- const startedIdsText = (): string => started.map((s) => s.id).join(", ");
1835
-
1836
- for (let i = 0; i < fanOutTasks.length; i++) {
1837
- if (signal?.aborted) {
1838
- if (started.length === 0) {
1839
- return {
1840
- content: [{ type: "text" as const, text: `Background fan-out cancelled before any agent started.` }],
1841
- details: undefined,
1842
- isError: true,
1843
- };
1844
- }
1845
- return {
1846
- content: [{ type: "text" as const, text:
1847
- `Background fan-out cancelled after starting ${started.length} of ${fanOutTasks.length} agents ` +
1848
- `(${startedIdsText()}) — they are detached and will still wake you.`
1849
- }],
1850
- details: undefined,
1851
- isError: true,
1852
- };
1853
- }
1854
-
1855
- const { merged, model, cwd, outputFile } = fanOutTasks[i];
1856
- const name = displayTaskName(merged);
1857
- const subagentPrompt = buildSubagentPrompt(
1858
- ctx.getSystemPrompt(),
1859
- merged.inheritSP,
1860
- merged.customSP,
1861
- outputFile,
1862
- merged.toolOptions?.tools,
1863
- globalParams.resolvedPreset?.promptGuideline,
1864
- );
1865
- const unitPriority = merged.priority ?? (params.priority as string | undefined);
1866
-
1867
- let agent: BackgroundAgent;
1868
- try {
1869
- agent = await startBackgroundAgent(pi, ctx, {
1870
- task: merged.task,
1871
- type: (params.preset as string | undefined) || 'general-purpose',
1872
- description: merged.label,
1873
- model: `${model.provider}/${model.id}`,
1874
- thinkingLevel: merged.thinkingLevel,
1875
- priority: unitPriority,
1876
- systemPrompt: subagentPrompt,
1877
- cwd,
1878
- toolOptions: merged.toolOptions,
1879
- timeout: merged.timeout,
1880
- gitMode: globalParams.resolvedGitMode,
1881
- // Retry parity with createUnitRun: snapshot this unit's resolved
1882
- // values so a retry restores them. The execution-shape fields
1883
- // (background/gitMode/approvalMode/force) are deliberately NOT
1884
- // passed here — a fan-out unit is spec'd to retry as a single
1885
- // run, so it must not inherit this spawn's background-ness.
1886
- // Same omission in unit-run.ts's createUnitRun.
1887
- originalParams: snapshotOriginalParams({
1888
- systemPrompt: merged.customSP,
1889
- inheritSystemPrompt: merged.inheritSP,
1890
- model: merged.model,
1891
- thinkingLevel: merged.thinkingLevel,
1892
- priority: unitPriority,
1893
- outputFile: merged.outputFile,
1894
- timeout: merged.timeout,
1895
- cwd: merged.effectiveCwd,
1896
- tools: merged.toolOptions?.tools,
1897
- excludeTools: merged.toolOptions?.excludeTools,
1898
- noBuiltinTools: merged.toolOptions?.noBuiltinTools,
1899
- preset: globalParams.resolvedPreset?.name,
1900
- }),
1901
- sanitizeCwd: merged.effectiveCwd,
1902
- recoveryPosture: state.config.recovery,
1903
- });
1904
- } catch (err) {
1905
- const message = sanitizeErrorMessage(
1906
- err instanceof Error ? err.message : String(err),
1907
- merged.effectiveCwd,
1908
- );
1909
- log.error("Background fan-out spawn failed", { task: i + 1, error: message });
1910
- const alreadyStarted = started.length > 0
1911
- ? `\n\nAlready started: ${startedIdsText()} — they are detached and will still wake you.`
1912
- : "";
1913
- return {
1914
- content: [{ type: "text" as const, text:
1915
- `Failed to spawn background agent for Task ${i + 1} ("${name}"): ${message}` + alreadyStarted
1916
- }],
1917
- details: undefined,
1918
- isError: true,
1919
- };
1920
- }
1921
- started.push({ id: agent.id, label: merged.label });
1922
- }
1923
-
1924
- // Text-only result: ids in task order + the wake hint. C: per-task
1925
- // validation warnings ride the immediate SPAWN result (prefixed with
1926
- // their task) so the conductor can stop/re-dispatch in the same turn.
1927
- const lines = started
1928
- .map((s, i) => `${i + 1}. ${s.label ? `"${s.label}" ` : ""}— ${s.id}`)
1929
- .join("\n");
1930
- return {
1931
- content: [{ type: "text" as const, text:
1932
- `Background agents started: ${started.length}\n\n` +
1933
- `${lines}\n\n` +
1934
- `You'll be woken with a completion message as each finishes; use get_subagent_result({ agent_id }) for retrieval and stall checks.` +
1935
- formatValidationWarnings(taskWarnings)
1936
- }],
1937
- details: undefined,
1938
- };
1939
- }
1940
-
1941
- // -------------------------------------------------------------------
1942
- // startBackgroundAgent — the shared background-spawn tail.
1943
- // Used by BOTH spawnBackgroundRun (single task) and runBackgroundFanOut
1944
- // (tasks fan-out): the session-manager import, the spawn call, live-monitor
1945
- // registration, footer counters, the 2s progress poller and the default
1946
- // deadline timer live here exactly once. Callers keep their own prelude,
1947
- // checks, validations and result formatting. THROWS on spawn failure —
1948
- // callers translate the error into their own result shape.
1949
- // -------------------------------------------------------------------
1950
-
1951
- async function startBackgroundAgent(
1952
- pi: ExtensionAPI,
1953
- ctx: ExtensionContext,
1954
- spawn: {
1955
- task: string;
1956
- type?: string;
1957
- description?: string;
1958
- model?: string;
1959
- thinkingLevel: ThinkingLevel;
1960
- priority?: string;
1961
- systemPrompt: string;
1962
- /** Issue #411: conductor-authored resume context for an auto-retry,
1963
- * delivered on the system-prompt side (never inside the task fence). */
1964
- resumeContext?: string;
1965
- cwd: string;
1966
- toolOptions?: SubagentToolOptions;
1967
- timeout?: number;
1968
- gitMode: GitMode;
1969
- originalParams?: SubagentRun["originalParams"];
1970
- /** cwd used to redact paths from crash notifications. */
1971
- sanitizeCwd: string;
1972
- // Option B U1: durability identity threaded onto the background records.
1973
- dispatchId?: string;
1974
- resumeOf?: string;
1975
- attempt?: number;
1976
- // Option B U3 (D4): recovery posture snapshot for the background run.
1977
- recoveryPosture?: RecoveryMode;
1978
- },
1979
- ): Promise<BackgroundAgent> {
1980
- const { spawnBackgroundSession, setAgentFinalOutput, extractFinalOutput, updateAgentStatus } = await import('./session-manager');
1981
- // Issue #31 (PR #76 review, DRY): extract final output from a
1982
- // possibly-released ref — the poller may observe a terminal agent
1983
- // whose ref was already nulled by the settlement path.
1984
- const extractAgentFinalOutput = (a: BackgroundAgent): string =>
1985
- extractFinalOutput(a._sessionRef ?? { messages: [] });
1986
-
1987
- const agent = await spawnBackgroundSession(pi, ctx, {
1988
- task: spawn.task,
1989
- type: spawn.type,
1990
- description: spawn.description,
1991
- model: spawn.model,
1992
- thinkingLevel: spawn.thinkingLevel,
1993
- // Issue #114: per-unit priority rides the spawn so the background
1994
- // run entry + drill-in header carry it like foreground runs.
1995
- priority: spawn.priority,
1996
- systemPrompt: spawn.systemPrompt,
1997
- resumeContext: spawn.resumeContext,
1998
- cwd: spawn.cwd,
1999
- toolOptions: spawn.toolOptions,
2000
- timeout: spawn.timeout,
2001
- gitMode: spawn.gitMode,
2002
- // Issue #98/#108: snapshotOriginalParams is the single source of truth
2003
- // for the caller params a later retry restores.
2004
- originalParams: spawn.originalParams,
2005
- // Option B U1: durability identity for the agent record + run entry.
2006
- dispatchId: spawn.dispatchId,
2007
- resumeOf: spawn.resumeOf,
2008
- attempt: spawn.attempt,
2009
- // Option B U3 (D4): recovery posture snapshot for the background run.
2010
- recoveryPosture: spawn.recoveryPosture,
2011
- });
2012
-
2013
- // Issue #318 (from #316 review): the two poller crash sites share one
2014
- // claimed notification envelope. Content is the only variable; the
2015
- // claim guard, display, details and deliverAs live here once.
2016
- const sendCrashNotice = (content: string): void => {
2017
- if (claimTerminalNotice(agent.id)) {
2018
- pi.sendMessage({
2019
- customType: "subagent-notification",
2020
- content,
2021
- display: true,
2022
- details: { agentId: agent.id }
2023
- }, { deliverAs: "followUp" });
2024
- }
2025
- };
2026
-
2027
- // Register for live monitor
2028
- state.registerLiveSubagent(agent.id, {
2029
- id: agent.id,
2030
- label: agent.description,
2031
- task: agent.task,
2032
- model: agent.model,
2033
- thinkingLevel: agent.thinkingLevel,
2034
- priority: agent.priority,
2035
- startedAt: agent.startedAt,
2036
- ctx,
2037
- });
2038
-
2039
- // Update footer counters
2040
- state.activeSubagents++;
2041
- repaintStatus(state, ctx);
2042
-
2043
- let completed = false;
2044
-
2045
- // Poll for live progress
2046
- const pollInterval = setInterval(() => {
2047
- try {
2048
- if (completed) return;
2049
-
2050
- const session = agent._sessionRef;
2051
- // Issue #31: a nulled ref on a TERMINAL agent is expected (the
2052
- // settlement path releases the ref) — fall through to finalize
2053
- // below instead of treating it as a crash. A nulled ref on a
2054
- // live agent is still a crash.
2055
- if (!session && !agent.completedAt) {
2056
- // Session ref not available — session may have crashed.
2057
- // Defensive: the ref is assigned synchronously before the poller starts
2058
- // and is never nulled, so this is mostly unreachable — but keep the
2059
- // bookkeeping safe regardless.
2060
- completed = true;
2061
- clearInterval(pollInterval);
2062
- clearTimeout(hardCapHandle);
2063
- // Capture whatever output exists (may be empty — fine).
2064
- setAgentFinalOutput(agent.id, state.subagentSessions.get(agent.id)?.liveOutput ?? '');
2065
- // Gate the counter on the finalize claim: if the
2066
- // stale sweep already finalized this entry, the
2067
- // decrement happened there (PR #71 review).
2068
- if (state.finalizeLiveSubagent(agent.id)) {
2069
- state.activeSubagents--;
2070
- if (state.activeSubagents < 0) state.activeSubagents = 0;
2071
- }
2072
- state.failedSubagents++;
2073
- repaintStatus(state, ctx);
2074
- sendCrashNotice(`Background agent "${agent.description}" crashed.`);
2075
- return;
2076
- }
2077
-
2078
- // While running, update the live monitor.
2079
- // Once completedAt is set, skip straight to finalize below.
2080
- // Issue #31: past the guard above, the only nulled-ref path left is a
2081
- // TERMINAL agent (settlement releases the ref), so a live agent always
2082
- // has its session — the guard already returned on the live-nulled-ref
2083
- // crash path. The compiler can't correlate the two checks, so assert it.
2084
- if (!agent.completedAt) {
2085
- const finalOutput = extractFinalOutput(session!);
2086
-
2087
- try {
2088
- const stats = session!.getSessionStats();
2089
- state.updateLiveSubagent(agent.id, finalOutput, stats.tokens.input, stats.tokens.output);
2090
- } catch {
2091
- state.updateLiveSubagent(agent.id, finalOutput, 0, 0);
2092
- }
2093
- }
2094
-
2095
- // Authoritative completion: the prompt promise settled — status and
2096
- // completedAt are set by .then()/.catch() in spawnBackgroundSession.
2097
- // Do NOT rely on !session.isStreaming: it is false during prompt()
2098
- // preflight (auth check, model resolution) and for failed starts.
2099
- if (agent.completedAt) {
2100
- completed = true;
2101
- clearInterval(pollInterval);
2102
- clearTimeout(hardCapHandle);
2103
-
2104
- // Issue #31: prefer the output already captured at settlement;
2105
- // the ref may already be nulled on terminal agents, so never
2106
- // overwrite with empty and stay null-safe.
2107
- const finalOutput = agent.finalOutput ?? extractAgentFinalOutput(agent);
2108
- setAgentFinalOutput(agent.id, finalOutput);
2109
-
2110
- // Gate the counter on the finalize claim: if the
2111
- // stale sweep already finalized this entry, the
2112
- // decrement happened there (PR #71 review).
2113
- if (state.finalizeLiveSubagent(agent.id)) {
2114
- state.activeSubagents--;
2115
- if (state.activeSubagents < 0) state.activeSubagents = 0;
2116
- }
2117
-
2118
- if (agent.status === 'failed') {
2119
- state.failedSubagents++;
2120
- repaintStatus(state, ctx);
2121
- // Issue #315: the terminal wake (`subagent-completion`, emitted by
2122
- // the session-manager settle) is the ONE notice for a failed run.
2123
- // The status here was set by that settle, so the wake already
2124
- // delivered — this legacy poller notice would duplicate it.
2125
- } else if (agent.status === 'stopped') {
2126
- // User-initiated stop (stop_subagent) or deadline abort
2127
- // (timeout/deadline) — not a failure.
2128
- repaintStatus(state, ctx);
2129
- } else {
2130
- state.completedSubagents++;
2131
- state.unseenSubagents++;
2132
- repaintStatus(state, ctx);
2133
- }
2134
- }
2135
- } catch (err) {
2136
- if (!completed) {
2137
- completed = true;
2138
- clearInterval(pollInterval);
2139
- clearTimeout(hardCapHandle);
2140
- try {
2141
- setAgentFinalOutput(agent.id, extractAgentFinalOutput(agent));
2142
- } catch { /* ignore */ }
2143
- // Gate the counter on the finalize claim: if the
2144
- // stale sweep already finalized this entry, the
2145
- // decrement happened there (PR #71 review).
2146
- if (state.finalizeLiveSubagent(agent.id)) {
2147
- state.activeSubagents--;
2148
- if (state.activeSubagents < 0) state.activeSubagents = 0;
2149
- }
2150
- state.failedSubagents++;
2151
- repaintStatus(state, ctx);
2152
- sendCrashNotice(`Background agent "${agent.description}" crashed: ${sanitizeErrorMessage((err as Error).message, spawn.sanitizeCwd)}`);
2153
- }
2154
- }
2155
- }, 2000);
2156
-
2157
- // Default deadline: stop polling AND abort the session after the
2158
- // deadline. W2 (issue #28): previously this only stopped the poller —
2159
- // the pi session kept running forever (orphaned). Now it pre-sets
2160
- // 'stopped' (so the .then keeps it, per W1) and aborts the session.
2161
- // Issue #240: an explicit per-agent timeout is HONORED verbatim; this
2162
- // deadline DEFAULTS to 30m only when no timeout is given. It is a
2163
- // default, not a ceiling. Issue #244: exactly ONE deadline timer per
2164
- // run — an explicit timeout is owned by the session-manager W3 timer,
2165
- // so this index timer arms ONLY on the no-timeout path, mirroring
2166
- // spawnBackgroundSession's `params.timeout && params.timeout > 0` guard
2167
- // (with no timeout, it owns the 30m default, #28).
2168
- const hasExplicitDeadline = spawn.timeout !== undefined && spawn.timeout > 0;
2169
- const hardCapMs = spawn.timeout ?? DEFAULT_BACKGROUND_DEADLINE_MS;
2170
- const hardCapHandle: ReturnType<typeof setTimeout> | undefined =
2171
- hasExplicitDeadline ? undefined : setTimeout(() => {
2172
- if (!completed && !agent.completedAt) {
2173
- try {
2174
- completed = true;
2175
- clearInterval(pollInterval);
2176
- // Pre-set stopped BEFORE aborting so the .then in
2177
- // spawnBackgroundSession keeps the stopped state.
2178
- updateAgentStatus(agent.id, 'stopped', `Timed out (${hardCapMs}ms deadline)`);
2179
- agent._sessionRef?.abort().catch(() => {
2180
- // Abort may reject if the session is mid-dispose;
2181
- // the status flip above is already recorded.
2182
- });
2183
- // Capture whatever final output exists in the session
2184
- const hardCapSession = agent._sessionRef;
2185
- const hardCapFinalOutput = hardCapSession ? extractFinalOutput(hardCapSession) : '';
2186
- setAgentFinalOutput(agent.id, hardCapFinalOutput);
2187
- // Gate the counter on the finalize claim: if the
2188
- // stale sweep already finalized this entry, the
2189
- // decrement happened there (PR #71 review).
2190
- if (state.finalizeLiveSubagent(agent.id)) {
2191
- state.activeSubagents--;
2192
- if (state.activeSubagents < 0) state.activeSubagents = 0;
2193
- }
2194
- // m6: deadline abort is a stop, not a completion — mirror the
2195
- // W3/poller stopped path (no completedSubagents increment).
2196
- repaintStatus(state, ctx);
2197
- } catch (err) {
2198
- // Defensive: never let the deadline timer throw uncaught — that would
2199
- // skip finalizeLiveSubagent, the counter decrement, and the notification.
2200
- // Do all fallible work first (output capture), then mutate counters,
2201
- // then notify — a throw mid-path can't double-fire mutations.
2202
- completed = true;
2203
- clearInterval(pollInterval);
2204
- // m3: the try may have thrown BEFORE updateAgentStatus ran (e.g.
2205
- // persistAgent fs failure) — leave the record terminal so
2206
- // get_subagent_result doesn't report 'running' and the W3 timer
2207
- // guard (!agent.completedAt) can't re-fire later.
2208
- try {
2209
- updateAgentStatus(agent.id, 'stopped', `Timed out (${hardCapMs}ms deadline)`);
2210
- } catch { /* ignore */ }
2211
- try {
2212
- setAgentFinalOutput(agent.id, extractAgentFinalOutput(agent));
2213
- } catch { /* ignore */ }
2214
- // Gate the counter on the finalize claim: if the
2215
- // stale sweep already finalized this entry, the
2216
- // decrement happened there (PR #71 review).
2217
- if (state.finalizeLiveSubagent(agent.id)) {
2218
- state.activeSubagents--;
2219
- if (state.activeSubagents < 0) state.activeSubagents = 0;
2220
- }
2221
- state.failedSubagents++;
2222
- repaintStatus(state, ctx);
2223
- }
2224
- }
2225
- }, hardCapMs);
2226
-
2227
- log.info("Background agent spawned", { agentId: agent.id, task: spawn.task, model: agent.model });
2228
-
2229
- return agent;
2230
- }
2231
-
2232
- // -------------------------------------------------------------------
2233
- // spawnBackgroundRun — Phase 6.5 background spawn, extracted verbatim
2234
- // from execute() (#198 phase 1) so a later phase can fan out N runs.
2235
- // -------------------------------------------------------------------
2236
-
2237
- async function spawnBackgroundRun(
2238
- pi: ExtensionAPI,
2239
- ctx: ExtensionContext,
2240
- /**
2241
- * Two shapes, both passed WITHOUT an assertion (issue #379):
2242
- * - `DelegateTaskParams` — a fresh dispatch, schema-validated;
2243
- * - the `resolveRetryParams` bag — rebuilt from a run record, whose
2244
- * `priority` is the unvalidated persisted string. It is the only field
2245
- * the two shapes disagree on, and claiming the recorded value was
2246
- * schema-validated would be a lie: records are read back from disk.
2247
- */
2248
- params: (DelegateTaskParams & { noJev?: string }) | ReturnType<typeof resolveRetryParams>,
2249
- singleTask: string,
2250
- // Option B U1: the spawn entry a retryRunId resolved to, so a retried
2251
- // background run inherits dispatchId/resumeOf/attempt (record identity,
2252
- // not a delegate param — D4).
2253
- retrySourceRun?: SubagentRun,
2254
- /**
2255
- * Issue #401/#411: the resume preamble for a TRANSPORT auto-retry. It rides
2256
- * the child's system prompt only (as a `<resume-context>` section) — never
2257
- * inside the `<task>` fence. `resolveSubagentParams`, every gate and every
2258
- * H1 check above still see `singleTask` (which stays byte-identical to the
2259
- * recorded original), so routing, capability warnings and pre-flight checks
2260
- * cannot be steered by the preamble's wording.
2261
- */
2262
- attemptContext?: string,
2263
- ): Promise<ToolResult<undefined>> {
2264
- // Phase 6.5: Background execution — spawn session and return ID immediately.
2265
- // Resolve the preset and its model BEFORE the background branch so the
2266
- // preset's model (and system prompt) are honored in background mode.
2267
- const bgResolved = resolveSubagentParams({ ...params, task: singleTask }, state, ctx, log);
2268
- const {
2269
- resolvedPreset: bgResolvedPreset,
2270
- autoRoutedPreset: bgAutoRoutedPreset,
2271
- autoRouteKeyword: bgAutoRouteKeyword,
2272
- } = bgResolved;
2273
- const bgModelResult = resolveSubagentModel(ctx, bgResolvedPreset, params.model);
2274
- const bgModel = bgModelResult.ok
2275
- ? `${bgModelResult.model.provider}/${bgModelResult.model.id}`
2276
- : undefined;
2277
-
2278
- try {
2279
- // W5 (issue #28): approvalMode 'always' cannot work in background —
2280
- // there is no interactive dialog to approve the diff. Reject loudly
2281
- // instead of silently running unattended with write access.
2282
- const approvalError = rejectApprovalAlwaysInBackground(bgResolved.resolvedApprovalMode);
2283
- if (approvalError) return approvalError;
2284
- // W5: 'writes' in background silently auto-approves — warn once so the
2285
- // caller knows the diff will NOT be gated on approval.
2286
- if (bgResolved.resolvedApprovalMode === 'writes') {
2287
- log.warn("Background agent spawned with approvalMode 'writes' — auto-approving (no dialog in background)", {
2288
- task: params.task,
2289
- });
2290
- }
2291
-
2292
- // W6 (issue #28): session cost limit must gate background spawns too —
2293
- // the R5 check after the background branch never runs for them.
2294
- // Same estimate/limit logic as single mode.
2295
- const costError = gateSessionCost({
2296
- state,
2297
- ctx,
2298
- log,
2299
- units: 1,
2300
- label: "Background delegation",
2301
- });
2302
- if (costError) return costError;
2303
-
2304
- // F1: Validate cwd + outputFile the same way foreground single mode does —
2305
- // an unvalidated outputFile would reach the prompt and could steer the
2306
- // background agent's write tool outside the project root.
2307
- const targets = validateDelegationTargets({
2308
- ctx,
2309
- effectiveCwd: bgResolved.effectiveCwd,
2310
- outputFile: bgResolved.outputFile,
2311
- });
2312
- if (!targets.ok) return targets.error;
2313
- const bgResolvedOutputFile = targets.outputFile;
2314
-
2315
- // C: H1 validation for background mode — reject capability blocks and
2316
- // outputFile-vs-write conflicts before spawning (same as single mode;
2317
- // `force` honors the same override foreground does).
2318
- const bgPreTask = runPreTaskValidation({
2319
- log,
2320
- label: "Background",
2321
- preTask: {
2322
- task: singleTask,
2323
- toolOptions: bgResolved.toolOptions,
2324
- thinkingLevel: bgResolved.thinkingLevel,
2325
- gitMode: bgResolved.resolvedGitMode,
2326
- outputFile: bgResolvedOutputFile,
2327
- force: params.force,
2328
- cwd: targets.cwd,
2329
- noJev: params.noJev,
2330
- },
2331
- });
2332
- if (bgPreTask.error) return bgPreTask.error;
2333
-
2334
- // Build the full prompt the same way foreground single mode does:
2335
- // base prompt (optionally inherited) + custom prompt + preset guidance.
2336
- const bgPrompt = buildSubagentPrompt(
2337
- ctx.getSystemPrompt(),
2338
- bgResolved.inheritSP,
2339
- bgResolved.customSP,
2340
- bgResolvedOutputFile,
2341
- bgResolved.toolOptions?.tools,
2342
- bgResolvedPreset?.promptGuideline,
2343
- );
2344
-
2345
- // Option B U1: durability identity (retry inherits the original dispatch).
2346
- const bgIdentity = newDispatchIdentity(retrySourceRun);
2347
- const agent = await startBackgroundAgent(pi, ctx, {
2348
- // Issue #411: the preamble rides the system-prompt side
2349
- // (`resumeContext`), never the task. The task stays the recorded
2350
- // original, and the snapshot keeps it too, so a later retry of this
2351
- // retry resolves from the un-prefixed text and never compounds.
2352
- task: singleTask,
2353
- resumeContext: attemptContext,
2354
- type: params.preset || 'general-purpose',
2355
- description: params.label,
2356
- model: bgModel,
2357
- thinkingLevel: bgResolved.thinkingLevel,
2358
- priority: params.priority,
2359
- systemPrompt: bgPrompt,
2360
- cwd: targets.cwd,
2361
- toolOptions: bgResolved.toolOptions,
2362
- timeout: bgResolved.timeout,
2363
- gitMode: bgResolved.resolvedGitMode,
2364
- originalParams: attemptContext
2365
- ? { ...snapshotOriginalParams(params), task: singleTask }
2366
- : snapshotOriginalParams(params),
2367
- sanitizeCwd: bgResolved.effectiveCwd,
2368
- dispatchId: bgIdentity.dispatchId,
2369
- resumeOf: bgIdentity.resumeOf,
2370
- attempt: bgIdentity.attempt,
2371
- recoveryPosture: state.config.recovery,
2372
- });
2373
-
2374
- // Retire-on-retry (O3 fold, decision 2026-10-11): the source interrupted
2375
- // registry entry is superseded once the new background run is actually
2376
- // spawned (a throwing spawn is caught below and leaves the source intact
2377
- // and retryable).
2378
- if (retrySourceRun) clearInflightRun(retrySourceRun.id);
2379
-
2380
- // B2: Surface auto-route decisions in background spawn result too —
2381
- // preset name + matched-keyword evidence + restriction, derived from
2382
- // the RESOLVED toolOptions (reflects per-call overrides).
2383
- const bgAutoRouteNote = bgAutoRoutedPreset
2384
- ? `\n\n[auto-routed to preset '${bgAutoRoutedPreset.name}'${bgAutoRouteKeyword ? ` (matched keyword '${bgAutoRouteKeyword}')` : ""} — ${bgResolved.toolOptions ? formatToolRestriction(bgResolved.toolOptions) : formatPresetRestriction(bgAutoRoutedPreset)}]`
2385
- : "";
2386
-
2387
- return {
2388
- content: [{
2389
- type: "text" as const,
2390
- text: `Background agent started: ${agent.id}\n\n` +
2391
- `Description: ${agent.description}\n` +
2392
- `Task: ${agent.task}\n` +
2393
- `Status: ${agent.status}\n\n` +
2394
- `You'll be woken with a completion message when it finishes; use get_subagent_result({ agent_id: "${agent.id}" }) for retrieval and stall checks.` +
2395
- bgAutoRouteNote +
2396
- // C: warnings ride the immediate SPAWN result so the conductor
2397
- // can stop/re-dispatch in the same turn.
2398
- formatValidationWarnings(bgPreTask.warnings),
2399
- }],
2400
- details: undefined,
2401
- };
2402
- } catch (err) {
2403
- const message = sanitizeErrorMessage(
2404
- err instanceof Error ? err.message : String(err),
2405
- bgResolved.effectiveCwd,
2406
- );
2407
- log.error("Failed to spawn background agent", { error: message });
2408
- return {
2409
- content: [{ type: "text" as const, text: `Failed to spawn background agent: ${message}` }],
2410
- details: undefined,
2411
- isError: true,
2412
- };
2413
- }
2414
- }
2415
-
2416
198
  // -------------------------------------------------------------------
2417
199
  // /brl-subagent command
2418
200
  // -------------------------------------------------------------------
2419
201
 
2420
- pi.registerCommand("brl-subagent", {
2421
- description: "Configure subagent model and thinking level",
2422
- getArgumentCompletions: (prefix: string) => {
2423
- const options = [
2424
- "history", "historyentries", "monitor", "dashboard", "preset", "templates", "retry", "completionnotify", "recovery",
2425
- ];
2426
- const filtered = options.filter((o) => o.startsWith(prefix));
2427
- return filtered.length > 0
2428
- ? filtered.map((o) => ({ value: o, label: o }))
2429
- : null;
2430
- },
2431
- handler: async (args, ctx) => {
2432
- const trimmed = args?.trim();
2433
-
2434
- const handlers: Record<string, () => Promise<void> | void> = {
2435
- model: () => showModelSelector(ctx, state, applyConfig),
2436
- thinking: () => showThinkingSelector(ctx, state, applyConfig),
2437
- concurrency: () => showConcurrencyInput(ctx, state, applyConfig),
2438
- depth: () => showDepthInput(ctx, state, applyConfig),
2439
- approval: () => showApprovalModeSelector(ctx, state, applyConfig),
2440
- completionnotify: () => showCompletionNotifySelector(ctx, state, applyConfig),
2441
- recovery: () => showRecoverySelector(ctx, state, applyConfig),
2442
- costlimit: () => showCostLimitInput(ctx, state, applyConfig),
2443
- reset: () => resetState(ctx),
2444
- history: () => showRunHistory(ctx, state, () => state.persistState(pi)),
2445
- historyentries: () => showHistoryEntriesInput(ctx, state, applyConfig),
2446
- monitor: () => showMonitor(ctx, state),
2447
- dashboard: () => showDashboard(ctx, state),
2448
- preset: () => showPresetManager(ctx, state),
2449
- templates: () => showTemplateManager(ctx, state),
2450
- retry: () => showRetryMenu(ctx, state, (id) => abandonProductionRun(ctx, id)),
2451
- sla: () => showSLAConfig(ctx, state, applyConfig),
2452
- "sla-stats": () => showSLAStats(ctx, state),
2453
- // E5: the compliance report menu (file access / secrets exposure /
2454
- // full summary) shipped in tui.ts but had no handler key, so
2455
- // `/brl-subagent compliance` fell through to the config menu and the
2456
- // feature was unreachable (broken wiring, not dead code).
2457
- compliance: () => showComplianceMenu(ctx, state),
2458
- };
2459
-
2460
- if (trimmed && trimmed in handlers) {
2461
- await handlers[trimmed]();
2462
- } else if (trimmed?.startsWith("templates")) {
2463
- await handlers.templates();
2464
- } else if (trimmed?.startsWith("preset")) {
2465
- await handlers.preset();
2466
- } else {
2467
- await showConfigMenu(ctx, state, handlers);
2468
- }
2469
- },
2470
- });
2471
-
2472
- // -------------------------------------------------------------------
2473
- // delegate_task tool
2474
- // -------------------------------------------------------------------
2475
-
2476
- // B1: Load built-in presets once at registration to expose their tool
2477
- // restrictions to the conductor before any delegate_task call happens.
2478
- const registrationPresets = loadBuiltinPresets(pkgPath("presets"));
2479
- const presetRestrictionSummary = buildInventorySummary(registrationPresets, (p) => {
2480
- const restricted = p.excludeTools?.length || p.tools?.length;
2481
- if (!restricted) return p.name;
2482
- return `${p.name} (${formatPresetRestriction(p)})`;
2483
- });
2484
-
2485
- // B1b: Load built-in templates once at registration to expose the built-in
2486
- // inventory (name + purpose + ${param} slots) to the conductor before any
2487
- // delegate_task call. Custom/user templates can't be enumerated statically,
2488
- // so the summary covers built-ins only and points at /brl-subagent templates.
2489
- const registrationTemplates = loadBuiltinTemplates(pkgPath("templates"));
2490
- const templateSummary = buildInventorySummary(registrationTemplates, formatTemplateSummaryItem);
2491
-
2492
- // Issue #158: resolve the shipped AGENT.md from the extension's own directory
2493
- // rather than a hardcoded sync-copy destination, so npm-installed packages
2494
- // (installed via `pi install npm:brl-subagent`) can find it.
2495
- const agentMdPath = pkgPath("AGENT.md");
2496
-
2497
- pi.registerTool({
2498
- name: "delegate_task",
2499
- label: "Delegate Task",
2500
- description: [
2501
- "Delegate a task to the brl-subagent with isolated context.",
2502
- "The subagent inherits your current system prompt and runs with",
2503
- "its configured model and thinking level (set via /brl-subagent).",
2504
- "If no subagent model is configured, your current model is used.",
2505
- "The subagent reports what it did when complete.",
2506
- "Optionally provide a custom systemPrompt and control inheritance via inheritSystemPrompt.",
2507
- ].join(" "),
2508
- promptSnippet:
2509
- "Delegate tasks to a subagent for isolated, parallel or background work",
2510
- promptGuidelines: [
2511
- "Use delegate_task when the user asks you to hand off work to a subagent, or when a task would benefit from an isolated context window (e.g., deep investigation, parallel research, long-running analysis).",
2512
- `The authoritative capability reference for delegation is the extension's AGENT.md — read it at ${agentMdPath}, or ./AGENT.md in the project root when present, when planning delegation-heavy work.`,
2513
- "The subagent inherits your system prompt and runs with its own model (configurable via /brl-subagent). It reports what it did when done.",
2514
- "You can customize per-call via inheritSystemPrompt and systemPrompt: set inheritSystemPrompt: false to save context, provide a systemPrompt for custom instructions, or use both to add instructions on top of inheritance.",
2515
- "Set thinkingLevel per call to match task complexity. The level is capped at the user's configured maximum. Map tasks to levels using this heuristic: off = file listing, grep, simple read. minimal = file diff, syntax check, find-and-replace. low = refactoring, test generation, documentation. medium = default — code review, debugging, moderate analysis. high = security audit, architecture review, complex debugging. xhigh = multi-step causal reasoning, research, novel problem solving. Default to 'off' or 'minimal' for trivial tasks — do not waste the user's budget.",
2516
- "Use outputFile to have the subagent write full findings to disk and return only a structured summary — saves context tokens for large investigations.",
2517
- "Set timeout (in ms) to limit how long a subagent can run. Useful for tasks that might hang or get stuck. Background runs default to a 30-minute deadline when no timeout is given; an explicit timeout is honored as given (30 minutes is a default, not a ceiling).",
2518
- "Set cwd to override the subagent's working directory. Defaults to the current project directory.",
2519
- "Set label to give the subagent a human-readable name (e.g., 'security-audit' or 'docs-review'). Labels appear in the status bar and tool call display.",
2520
- `Use preset to apply a delegation configuration (built-in or custom via /brl-subagent preset). Preset values are defaults — explicit parameters override them. IMPORTANT: some presets restrict tools — e.g. outputFile requires the subagent's write tool, which security-auditor and code-reviewer exclude. Built-in presets: ${presetRestrictionSummary}. Custom presets are NOT listed here — inspect them via /brl-subagent preset before combining with outputFile or tool-dependent work. When combining a preset with outputFile or tool-dependent work, verify the preset allows the required tools.`,
2521
- buildTemplateGuideline(templateSummary),
2522
- "To retry a failed subagent, pass its run ID as retryRunId. The retry restores the recorded params - including background, gitMode, approvalMode, force - with explicit values on this call winning. Multi-step runs degrade to a single task. See the retryRunId description for the full field list.",
2523
- "Set retryOnTimeout: true to automatically retry a FOREGROUND subagent that times out. Only retries once — the second timeout is treated as a final failure. A background run is not retried on its deadline, but it IS retried once automatically when it dies on a transport-class error (a dropped connection before the work started), recorded as attempt 2 and announced with a warning toast — do not re-dispatch it yourself. Any other background failure needs an explicit retryRunId.",
2524
- "Background is the CONDITIONAL default for delegate_task. With background omitted, a single task or a tasks fan-out runs in the BACKGROUND when the effective approvalMode is 'auto' (call param, else config): the tool returns an agent ID immediately, and with tasks it fans out — every task starts as its own background agent, one ID per task in task order, and the conductor is woken once per agent as each finishes. It stays FOREGROUND when the effective approvalMode is 'writes' or 'always' (a background run has no approval dialog, so a gate that needs the user must keep blocking), and for chain and graph (they block by definition; an explicit background: true with chain/graph is rejected). Pass background: false for a quick probe whose answer the next step needs inline; pass background: true to force a background run where the default would block. Background runs wake the conductor with a structured completion message when they finish — do not poll: polling is only correct when completion notifications are disabled (completionNotify \"off\"); one status check as a stall check is legitimate. A background run defaults to a 30-minute deadline when no timeout is given.",
2525
- "",
2526
- "## Conductor Guardrails",
2527
- "",
2528
- "Before delegating, verify the subagent configuration matches the task:",
2529
- "",
2530
- "2. **Thinking level**: Match thinking level to task complexity: off/minimal for trivial tasks (file listing, grep), low for refactoring/docs, medium for code review/debugging, high for security audits/complex debugging, xhigh for multi-step reasoning/novel problems.",
2531
- "3. **Git mode**: Use gitMode='branch' for tasks that create commits or PRs. Use gitMode='none' for read-only tasks.",
2532
- "4. **Tools**: Verify the subagent has the tools it needs. If the task writes files, ensure write and edit are not excluded. If the task runs commands, ensure bash is not excluded.",
2533
- "5. **Timeout**: Set timeout based on task complexity. Simple: 30s. Medium: 60s. Complex: 120s+. xhigh thinking: at least 120s. Background runs default to a 30-minute deadline when no timeout is set; an explicit timeout is honored.",
2534
- "",
2535
- "These guardrails prevent common misconfigurations. The extension also validates configuration before spawning (H1): tool warnings are surfaced in the returned result, but two mismatches are HARD errors that reject the delegation — outputFile with the write tool excluded, and a capability-critical task/toolset mismatch (a run/execute/test/compile/benchmark task without bash, or an exploration task with none of find/ls/grep/bash; pass force: true to override the capability class). Getting it right the first time is faster and more efficient.",
2536
- "",
2537
- "Before delegating, evaluate existing presets to find the best match for the task: tech-writer (documentation), code-reviewer (code review), security-auditor (security analysis), test-engineer (test writing), debugger (debugging), refactorer (refactoring), data-analyst (data analysis), rapid-prototyper (quick prototypes). Use the preset parameter to apply the best match. If no preset fits, use dev-agent for general development tasks.",
2538
- "The autoRoutePreset() function can automatically select the best preset based on task keywords. Consider using it for preset selection.",
2539
- "Prefer a preset when the delegation matches a standard shape — review/audit/test/docs; override per-call deliberately.",
2540
- ],
2541
- parameters: delegateTaskParamsSchema,
2542
-
2543
- async execute(
2544
- _toolCallId: string,
2545
- params: DelegateTaskParams,
2546
- signal: AbortSignal | undefined,
2547
- onUpdate: AgentToolUpdateCallback<DelegateTaskDetails> | undefined,
2548
- ctx: ExtensionContext,
2549
- ) {
2550
- // Option B U1: the run a retryRunId resolves to (spawn entry). Internal
2551
- // record identity — dispatchId/resumeOf/attempt are threaded onto the new
2552
- // record, NOT through the delegate-param surface (D4).
2553
- let retrySourceRun: SubagentRun | undefined;
2554
- // Issue #99: warn on unknown params — typebox allows additional properties
2555
- // by default (pi's validateToolArguments passes unknown keys through), so a
2556
- // typo like `thinkinglevel` or a schema-drifted param is otherwise silently
2557
- // ignored. Warn-not-reject: never break a delegation.
2558
- const unknownKeys = findUnknownParams(params, KNOWN_DELEGATE_KEYS);
2559
- if (unknownKeys.length > 0) {
2560
- log.warn("delegate_task: unknown param(s) ignored — check spelling or add to schema", { unknown: unknownKeys });
2561
- // Issue #110: log.warn alone is invisible — pi's TUI swallows extension
2562
- // console output. Route through pi.sendMessage (the subagent-notification
2563
- // pattern, index.ts ~2312) so BOTH the LLM (followUp enters the
2564
- // conversation) and the human (session transcript) see the correction.
2565
- pi.sendMessage({
2566
- customType: "delegate-notification",
2567
- content: `delegate_task: unknown param(s) ignored — check spelling or add to schema: ${unknownKeys.join(", ")}`,
2568
- display: true,
2569
- details: { unknown: unknownKeys },
2570
- }, { deliverAs: "followUp" });
2571
- }
2572
-
2573
- // Handle template resolution — MUST run before the single-mode sanitize
2574
- // block below: a template ASSIGNS params.task, so resolving first lets the
2575
- // sanitizer validate the real resolved body (a template-only call has no
2576
- // task yet) and lets mode detection see a non-empty task (issue #175).
2577
- if (params.template) {
2578
- const templateEntry = state.config.templates.find((t) => t.name === params.template);
2579
- if (!templateEntry) {
2580
- const available = state.config.templates.map((t) => t.name).join(", ") || "none";
2581
- return {
2582
- content: [
2583
- {
2584
- type: "text" as const,
2585
- text: `Template '${params.template}' not found. Available: ${available}`,
2586
- },
2587
- ],
2588
- details: undefined,
2589
- isError: true,
2590
- };
2591
- }
2592
-
2593
- const resolved = resolveTemplate(templateEntry, params.params ?? {});
2594
- if (!resolved.ok) {
2595
- return {
2596
- content: [
2597
- {
2598
- type: "text" as const,
2599
- text: `Template '${params.template}' resolution failed: ${resolved.error}`,
2600
- },
2601
- ],
2602
- details: undefined,
2603
- isError: true,
2604
- };
2605
- }
2606
-
2607
- const tv = resolved.value;
2608
- // Issue #175 review (fix 4): template-wins silently replaces a
2609
- // supplied `task`. If that task would itself have failed sanitization
2610
- // (e.g. over-length), the caller gets no signal — pre-#175 `dev`
2611
- // rejected it. Warn (never reject — #99/#110 precedent, same
2612
- // pi.sendMessage channel as the unknown-param warning) so both the LLM
2613
- // and the human see the ignored task. Emitted ONLY when the supplied
2614
- // task actually fails sanitization: a valid task alongside a template
2615
- // is the intended template-wins override (issue #57), not noise.
2616
- if (params.task !== undefined) {
2617
- const suppliedTask = sanitizeTask(params.task);
2618
- if (!suppliedTask.ok) {
2619
- log.warn("delegate_task: supplied task ignored because a template was given", {
2620
- template: params.template,
2621
- error: suppliedTask.error,
2622
- });
2623
- pi.sendMessage({
2624
- customType: "delegate-notification",
2625
- content: `delegate_task: the supplied 'task' was ignored because a template ('${params.template}') was given. The task would otherwise have been rejected: ${suppliedTask.error}`,
2626
- display: true,
2627
- details: { template: params.template, rejectedTask: suppliedTask.error },
2628
- }, { deliverAs: "followUp" });
2629
- }
2630
- }
2631
- // Issue #175 review (fix direction item 4): this assignment is
2632
- // UNCONDITIONAL — the resolved template task replaces any supplied
2633
- // `task` (template-wins, issue #57); it is NOT a default the caller can
2634
- // override. The fields below, by contrast, ARE defaults: an explicitly
2635
- // provided param wins over the template's value.
2636
- params.task = tv.task;
2637
- if (tv.preset && !params.preset) params.preset = tv.preset;
2638
- if (tv.thinkingLevel && !params.thinkingLevel) params.thinkingLevel = tv.thinkingLevel;
2639
- if (tv.outputFile && !params.outputFile) params.outputFile = tv.outputFile;
2640
- if (tv.timeout !== undefined && params.timeout === undefined) params.timeout = tv.timeout;
2641
- if (tv.tools && !params.tools) params.tools = tv.tools;
2642
- if (tv.excludeTools && !params.excludeTools) params.excludeTools = tv.excludeTools;
2643
- if (tv.noBuiltinTools !== undefined && params.noBuiltinTools === undefined) params.noBuiltinTools = tv.noBuiltinTools;
2644
- if (tv.inheritSystemPrompt !== undefined && params.inheritSystemPrompt === undefined) params.inheritSystemPrompt = tv.inheritSystemPrompt;
2645
- }
2646
-
2647
- // Handle retryRunId — MUST run after template resolution and before the
2648
- // single-mode sanitize block. resolveRetryParams assigns params.task from
2649
- // the recorded run, so the sanitizer must see the retried body (a
2650
- // retry-only call has no task yet). It MUST run AFTER template resolution:
2651
- // resolveRetryParams returns a fresh object that DROPS `template`, so
2652
- // resolving templates first keeps a combined template + retryRunId call
2653
- // from silently disabling template resolution (issue #175 review).
2654
- if (params.retryRunId) {
2655
- // Fix A: prefer the session spawn entry (it carries `originalParams`);
2656
- // a run that exists ONLY in the durable registry after a fresh boot
2657
- // resolves through the visibility bridge instead of being rejected as
2658
- // not found — the id the boot notice names must resolve here.
2659
- let runEntry = state.findSpawnRunById(ctx, params.retryRunId);
2660
- if (!runEntry) {
2661
- const { getAgent } = await import("./session-manager");
2662
- runEntry = resolveTerminalRunEntry(
2663
- visibleRunsFor(ctx, getAgent),
2664
- params.retryRunId,
2665
- );
2666
- }
2667
- if (runEntry) {
2668
- retrySourceRun = runEntry;
2669
- params = resolveRetryParams(params, runEntry) as DelegateTaskParams;
2670
- } else {
2671
- // Issue #98: a silent no-op here made retries of background runs
2672
- // (which previously never wrote run entries) start as FRESH runs
2673
- // with no signal to the caller. Fail loudly instead.
2674
- log.warn("Retry run ID not found", { retryRunId: params.retryRunId });
2675
- return {
2676
- content: [{
2677
- type: "text" as const,
2678
- text: `Retry run ID not found: ${params.retryRunId}. The run may have been pruned, or it was a background run created before the run-entry fix. Pass the run's agent ID — for background runs the agent ID and run ID are now the same.`,
2679
- }],
2680
- details: undefined,
2681
- isError: true,
2682
- };
2683
- }
2684
- }
2685
-
2686
- // F1: Sanitize task input — skip for chain/parallel/graph modes
2687
- const hasChain = params.chain && params.chain.length > 0;
2688
- const hasParallel = params.tasks && params.tasks.length > 0;
2689
- const hasGraph = params.graph && params.graph.length > 0;
2690
- if (!hasChain && !hasParallel && !hasGraph) {
2691
- // task is optional per the schema; single mode requires it. When absent,
2692
- // feed "" to the sanitizer — same rejection path ("Task must not be
2693
- // empty.") as when task was a required field.
2694
- const taskResult = sanitizeTask(params.task ?? "");
2695
- if (!taskResult.ok) {
2696
- log.warn("Task rejected by sanitizer", { error: taskResult.error });
2697
- return {
2698
- content: [{ type: "text" as const, text: `Invalid task: ${taskResult.error}` }],
2699
- details: undefined,
2700
- isError: true,
2701
- };
2702
- }
2703
- params.task = taskResult.value;
2704
- }
2705
-
2706
- // P1+P2+P10: Mode detection — graph > chain > parallel > single
2707
- const isChain = hasChain;
2708
- const isParallel = hasParallel;
2709
- const isGraph = hasGraph;
2710
- const isSingle = typeof params.task === "string" && params.task.length > 0;
2711
-
2712
- const modeCount = [isChain, isParallel, isGraph, isSingle].filter(Boolean).length;
2713
- if (modeCount !== 1) {
2714
- return {
2715
- content: [
2716
- {
2717
- type: "text" as const,
2718
- text:
2719
- "Provide exactly one of: task (single), chain (sequential), tasks (parallel), or graph (dependency graph).",
2720
- },
2721
- ],
2722
- details: undefined,
2723
- isError: true,
2724
- };
2725
- }
2726
-
2727
- const dispatchShape: DispatchShape = isChain
2728
- ? "chain"
2729
- : isGraph
2730
- ? "graph"
2731
- : isParallel
2732
- ? "parallel"
2733
- : "single";
2734
-
2735
- // Capture the caller's value BEFORE the default is recorded on
2736
- // `params.background` below. The guard must judge what the caller
2737
- // actually asked for; reading the recorded value would make it depend
2738
- // on the default. Keeping the capture first makes that ordering
2739
- // self-evident (issue #361 review).
2740
- const explicitBackground = params.background;
2741
-
2742
- // Issue #412 (rule 2: "no deadline ⇒ durable path") — the dispatch-shape
2743
- // pre-flight. A high/xhigh-thinking run the conductor asked to run
2744
- // FOREGROUND with an explicit timeout is the shape that lost 14 minutes of
2745
- // plan critique on 2026-10-31: foreground runs persist nothing, so the
2746
- // deadline kills the work outright, while a background run keeps its
2747
- // session and is retried on a transport error. The switch is applied HERE
2748
- // — after template/retry resolution and BEFORE `useBackground` is resolved
2749
- // and before any run record is written — so the shape every downstream
2750
- // reader sees (the spawn, the retry snapshot, the pending-work record) is
2751
- // the switched one. Moving it after `snapshotOriginalParams` would record
2752
- // `background:false` and silently cost the run its transport auto-retry
2753
- // (`transport-retry.ts` classifies off that snapshot).
2754
- // Issue #415: the switch is OUR process (a conductor decision rule), not
2755
- // product behavior — a user's explicit foreground timeout is usually a
2756
- // budget cap, so a GLOBAL switch could triple time and cost against
2757
- // their instruction. The umbrella project-local `processChecks` flag
2758
- // gates it (fail-open: no/malformed manifest → off). Resolve the
2759
- // dispatch cwd ONCE, the way the target validation below will.
2760
- const processChecksCwd =
2761
- params.cwd === undefined ? ctx.cwd : path.resolve(ctx.cwd, params.cwd);
2762
- const processChecks = readProcessChecks(processChecksCwd);
2763
- // The preset the dispatch will actually run with — an auto-routed
2764
- // `code-reviewer`/`debugger` is a high-thinking run even though the
2765
- // caller declared no level, so the pre-flight resolves the SAME preset
2766
- // the merge below will (one rule, `resolveDispatchPreset`).
2767
- const declaredPresetForSwitch = resolveDispatchPreset(params, state).preset;
2768
- const thinkingSwitch = resolveThinkingDispatchSwitch({
2769
- processChecks,
2770
- thinkingLevel: (params.thinkingLevel ?? declaredPresetForSwitch?.thinkingLevel) as
2771
- | ThinkingLevel
2772
- | undefined,
2773
- explicitBackground,
2774
- timeout: params.timeout,
2775
- force: params.force,
2776
- shape: dispatchShape,
2777
- });
2778
- if (thinkingSwitch === "switch") {
2779
- params.background = true;
2780
- // Drop the foreground deadline: the 30-minute background default
2781
- // (DEFAULT_BACKGROUND_DEADLINE_MS) applies instead. Recorded as
2782
- // undefined, so a retry re-derives it rather than restoring the cap.
2783
- params.timeout = undefined;
2784
- log.info("Dispatch pre-flight: high-thinking foreground switched to background", {
2785
- thinkingLevel: params.thinkingLevel,
2786
- timeout: "dropped (background default applies)",
2787
- });
2788
- pi.sendMessage({
2789
- customType: "delegate-notification",
2790
- content: THINKING_SWITCH_NOTICE,
2791
- display: true,
2792
- details: { thinkingLevel: params.thinkingLevel, previousTimeout: "dropped" },
2793
- }, { deliverAs: "followUp" });
2794
- ctx.ui.notify(THINKING_SWITCH_NOTICE, "warning");
2795
- } else if (thinkingSwitch === "forced") {
2796
- // The override is recorded, not silent: the dispatch text is the reason
2797
- // (`force` has no reason field — ADR 0007's contract stays unchanged).
2798
- log.info("Dispatch pre-flight: high-thinking foreground forced", {
2799
- thinkingLevel: params.thinkingLevel,
2800
- timeout: params.timeout,
2801
- });
2802
- }
2803
-
2804
- // background: true with chain/graph was silently ignored — the batch ran
2805
- // foreground (blocking until every unit finished) while the caller believed
2806
- // it was background. Both remain rejected loudly at dispatch validation;
2807
- // tasks (parallel) fans out into independent background agents instead.
2808
- // Only an EXPLICIT true trips this (issue #361): an omitted `background`
2809
- // now defaults to foreground here rather than being rejected.
2810
- if (shouldRejectBackgroundForBatch(dispatchShape, explicitBackground)) {
2811
- const batchMode = dispatchShape === "chain" ? "chain" : "graph";
2812
- return {
2813
- content: [
2814
- {
2815
- type: "text" as const,
2816
- text: `background: true is not supported with ${batchMode} — batch modes run foreground and would block until every unit finishes. Remove background to run it foreground, or start each unit as its own single-task background call and sequence the dependencies yourself.`,
2817
- },
2818
- ],
2819
- details: undefined,
2820
- isError: true,
2821
- };
2822
- }
2823
-
2824
- // Issue #361: background is the CONDITIONAL default for the shapes that
2825
- // can run unattended. Resolved ONCE per dispatch and reused by the
2826
- // single and fan-out paths below, so the decision cannot drift between
2827
- // them. The approval mode is the EFFECTIVE one (call param, else the
2828
- // configured default — presets declare no approvalMode today) — the same
2829
- // value the child will run with — so the default never routes a run into a
2830
- // background context that would break or silently auto-approve it
2831
- // ('always' has no dialog; 'writes' gates the diff on approval).
2832
- const useBackground =
2833
- params.background ??
2834
- defaultBackgroundFor(dispatchShape, resolveEffectiveApprovalMode(params.approvalMode, state));
2835
- // Record the EFFECTIVE value on the dispatch (a no-op when the caller was
2836
- // explicit): a run started by the default must retry as what it actually
2837
- // was instead of re-deriving the default, which may since have moved with
2838
- // the config. Fan-out units still record no background of their own — a
2839
- // unit retries as a single foreground run (issue #229), unaffected here.
2840
- params.background ??= useBackground;
2841
-
2842
- if (isChain) {
2843
- if (params.chain!.length > MAX_CHAIN_STEPS) {
2844
- return {
2845
- content: [
2846
- {
2847
- type: "text" as const,
2848
- text: `Chain exceeds max ${MAX_CHAIN_STEPS} steps.`,
2849
- },
2850
- ],
2851
- details: undefined,
2852
- isError: true,
2853
- };
2854
- }
2855
- return runChainMode(params, signal, onUpdate, ctx);
2856
- }
2857
-
2858
- if (isParallel) {
2859
- if (params.tasks!.length > MAX_PARALLEL_TASKS) {
2860
- return {
2861
- content: [
2862
- {
2863
- type: "text" as const,
2864
- text: `Parallel exceeds max ${MAX_PARALLEL_TASKS} tasks.`,
2865
- },
2866
- ],
2867
- details: undefined,
2868
- isError: true,
2869
- };
2870
- }
2871
- if (useBackground) return runBackgroundFanOut(pi, ctx, params, signal);
2872
- return runParallelMode(params, signal, onUpdate, ctx);
2873
- }
2874
-
2875
- if (isGraph) {
2876
- return runGraphMode(params, signal, onUpdate, ctx);
2877
- }
2878
-
2879
- // Single mode: isSingle is true (modeCount===1, none of chain/parallel/graph),
2880
- // so params.task is a non-empty string. TS can't infer this through the
2881
- // boolean-array filter — assert, mirroring params.chain!/params.tasks! above.
2882
- const singleTask = params.task!; // non-empty (sanitizer guarantees; isSingle confirms)
2883
-
2884
- if (useBackground) {
2885
- return spawnBackgroundRun(pi, ctx, params, singleTask, retrySourceRun);
2886
- }
2887
-
2888
- // R5: Check session cost limit before spawning
2889
- // Use a default per-task estimate of $0.05 if no perTaskCostEstimate is set
2890
- const costError = gateSessionCost({
2891
- state,
2892
- ctx,
2893
- log,
2894
- units: 1,
2895
- label: "Subagent delegation",
2896
- });
2897
- if (costError) return costError;
2898
-
2899
- // Reject delegation if recursion depth exceeds configured max.
2900
- // This prevents subagents from spawning infinite sub-subagents while
2901
- // still allowing other extensions to function normally in subprocesses.
2902
- const currentDepth = getCurrentDepth();
2903
- if (currentDepth >= state.config.maxSubagentDepth) {
2904
- log.warn("Subagent delegation rejected: max depth reached", {
2905
- currentDepth,
2906
- maxDepth: state.config.maxSubagentDepth,
2907
- });
2908
- return depthLimitRejection(currentDepth, state.config.maxSubagentDepth);
2909
- }
2910
-
2911
- const {
2912
- task,
2913
- label,
2914
- inheritSP,
2915
- customSP,
2916
- outputFile,
2917
- timeout,
2918
- effectiveCwd,
2919
- thinkingLevel,
2920
- toolOptions,
2921
- resolvedGitMode,
2922
- resolvedApprovalMode,
2923
- resolvedPreset,
2924
- autoRoutedPreset,
2925
- autoRouteKeyword,
2926
- } = resolveSubagentParams({ ...params, task: singleTask }, state, ctx, log);
2927
-
2928
- // F1: Validate CWD
2929
- const cwdResult = validateCwd(effectiveCwd, ctx.cwd);
2930
- if (!cwdResult.ok) {
2931
- return {
2932
- content: [{ type: "text" as const, text: `Invalid cwd: ${cwdResult.error}` }],
2933
- details: undefined,
2934
- isError: true,
2935
- };
2936
- }
2937
- const resolvedCwd = cwdResult.value;
2938
-
2939
- // F1: Validate outputFile
2940
- let resolvedOutputFile: string | undefined;
2941
- if (outputFile) {
2942
- const ofResult = validateOutputFile(outputFile, resolvedCwd);
2943
- if (!ofResult.ok) {
2944
- return {
2945
- content: [
2946
- { type: "text" as const, text: `Invalid outputFile: ${ofResult.error}` },
2947
- ],
2948
- details: undefined,
2949
- isError: true,
2950
- };
2951
- }
2952
- resolvedOutputFile = ofResult.value;
2953
- }
2954
-
2955
- // R3: Pre-flight checks — fail fast before consuming resources
2956
- const pfResult = preflightCheck(resolvedCwd);
2957
- if (!pfResult.ok) {
2958
- log.warn("Pre-flight check failed", { error: pfResult.error });
2959
- return {
2960
- content: [{ type: "text" as const, text: `Pre-flight check failed: ${pfResult.error}` }],
2961
- details: undefined,
2962
- isError: true,
2963
- };
2964
- }
2965
-
2966
- // H1: Pre-task validation — deterministic check that tools/thinking match task
2967
- // (`force` degrades capability errors to warnings — B2's override).
2968
- const validation = validatePreTask({
2969
- task,
2970
- toolOptions,
2971
- thinkingLevel,
2972
- gitMode: resolvedGitMode,
2973
- outputFile: resolvedOutputFile,
2974
- force: params.force,
2975
- cwd: resolvedCwd,
2976
- noJev: params.noJev,
2977
- });
2978
- if (validation.warnings.length > 0) {
2979
- log.warn("Pre-task validation warnings", { warnings: validation.warnings });
2980
- }
2981
- if (!validation.valid) {
2982
- const errText = validation.errors.join("; ");
2983
- log.warn("Pre-task validation failed", { errors: validation.errors });
2984
- return {
2985
- content: [{
2986
- type: "text" as const,
2987
- text: errText,
2988
- }],
2989
- details: undefined,
2990
- isError: true,
2991
- };
2992
- }
2993
- // C: surface warnings in the returned result (not just the log) —
2994
- // shared renderer so foreground/background wording stays identical.
2995
- const warningsNote = formatValidationWarnings(validation.warnings);
2996
-
2997
- // Resolve model (per-call top-level model override beats preset)
2998
- const modelResult = resolveSubagentModel(ctx, resolvedPreset, params.model);
2999
- if (!modelResult.ok) return modelResult.error;
3000
- const subagentModel = modelResult.model;
3001
-
3002
- // R3: Verify resolved model provider+id is non-empty
3003
- const modelStr = `${subagentModel.provider}/${subagentModel.id}`.trim();
3004
- if (!modelStr || modelStr === "/") {
3005
- log.warn("Model string is empty after resolution", { model: subagentModel });
3006
- return modelNotConfiguredRejection();
3007
- }
3008
-
3009
- // Create run record
3010
- const runId = crypto.randomUUID();
3011
- // Option B U1: durability identity — a retry inherits the original
3012
- // dispatchId and records resumeOf/attempt; a fresh marker keys the
3013
- // child process for boot-time orphan discovery.
3014
- const identity = newDispatchIdentity(retrySourceRun);
3015
- const run: SubagentRun = {
3016
- id: runId,
3017
- task,
3018
- label,
3019
- status: "running",
3020
- model: `${subagentModel.provider}/${subagentModel.id}`,
3021
- thinkingLevel,
3022
- // Issue #114: record-level visibility — the run's priority (absent
3023
- // when the caller left it to the default).
3024
- priority: params.priority,
3025
- startedAt: new Date().toISOString(),
3026
- originalParams: snapshotOriginalParams(params),
3027
- dispatchId: identity.dispatchId,
3028
- resumeOf: identity.resumeOf,
3029
- attempt: identity.attempt,
3030
- owner: currentProcessOwner(),
3031
- childMarker: crypto.randomUUID(),
3032
- // U3 (D4): the session recovery posture at dispatch.
3033
- recoveryPosture: state.config.recovery,
3034
- };
3035
- state.persistRun(pi, run, "foreground");
3036
-
3037
- // R2: Prune old run entries if history exceeds limit
3038
- pruneHistoryIfNeeded(state, ctx, log);
3039
-
3040
- // Register for live monitor
3041
- registerLiveRun(state, run, ctx);
3042
-
3043
- // P3: Git integration — set up work branch if gitMode is "branch"
3044
- let headState: HeadState | undefined;
3045
- let workBranchName: string | undefined;
3046
- if (resolvedGitMode === "branch") {
3047
- try {
3048
- headState = getHeadState(resolvedCwd);
3049
-
3050
- if (hasUncommittedChanges(resolvedCwd)) {
3051
- log.warn("Uncommitted changes detected; proceeding with branch-based workflow anyway", {
3052
- cwd: resolvedCwd,
3053
- });
3054
- }
3055
-
3056
- const branchResult = createWorkBranch(resolvedCwd, headState.sha);
3057
- if (branchResult.ok) {
3058
- workBranchName = branchResult.branch;
3059
- log.info("Created work branch for subagent", {
3060
- branch: workBranchName,
3061
- base: headState.branch,
3062
- });
3063
- } else {
3064
- log.error("Failed to create work branch, falling back to 'none'", {
3065
- error: branchResult.error,
3066
- });
3067
- headState = undefined;
3068
- }
3069
- } catch (err) {
3070
- log.warn("Not a git repository or git error; falling back to gitMode 'none'", {
3071
- error: (err as Error).message,
3072
- });
3073
- headState = undefined;
3074
- workBranchName = undefined;
3075
- }
3076
- }
3077
-
3078
- // Helper to restore the starting HEAD and delete the work branch. The
3079
- // delete is NOT gated on the restore succeeding: the branch must never
3080
- // survive teardown. A still-checked-out branch simply makes deleteBranch
3081
- // fail (logged) rather than silently leaking the ref.
3082
- const cleanupGitBranch = () => {
3083
- if (!workBranchName) return;
3084
- if (headState) {
3085
- const restoreResult = restoreHead(resolvedCwd, headState);
3086
- if (restoreResult.ok) {
3087
- log.info("Restored original HEAD", {
3088
- branch: headState.branch,
3089
- detached: headState.detached,
3090
- });
3091
- } else {
3092
- log.warn("Failed to restore original HEAD during cleanup", {
3093
- branch: headState.branch,
3094
- error: restoreResult.error,
3095
- });
3096
- }
3097
- }
3098
- // Attempt to delete the work branch (non-critical)
3099
- const deleteResult = deleteBranch(resolvedCwd, workBranchName);
3100
- if (!deleteResult.ok) {
3101
- log.warn("Failed to delete work branch during cleanup", {
3102
- branch: workBranchName,
3103
- error: deleteResult.error,
3104
- });
3105
- }
3106
- };
3107
-
3108
- // #340: both pre-start gate rejections below must finalize the
3109
- // `running` record persisted just above. Without this the session entry
3110
- // stays non-terminal, the inflight registry row (written by
3111
- // `persistRun(..., "foreground")`) is never cleared, and the live
3112
- // registration is never released — a phantom interrupted run at the
3113
- // next boot (and, on a retry, a dangling twin beside the source).
3114
- // The fabricated result drives `finalizeRunRecord` to terminal
3115
- // `failed`; `stopReason: "aborted"` makes `coherentFailureReason` keep
3116
- // the D1 `aborted` category coherent. The exact gate message the caller
3117
- // receives is recorded as `errorMessage`; the terminal
3118
- // `state.persistRun` (no kind) clears the registry row via its
3119
- // terminal-clear rule. Returned content/isError and the retry-source
3120
- // retention below are unchanged.
3121
- const SLOT_CANCEL_MESSAGE = "Subagent cancelled while waiting for concurrency slot.";
3122
- const finalizePreStartRejection = (errorMessage: string): void => {
3123
- const rejection: SubagentResult = {
3124
- messages: [],
3125
- usage: { ...EMPTY_USAGE },
3126
- exitCode: 1,
3127
- stderr: "",
3128
- stopReason: "aborted",
3129
- errorMessage,
3130
- errorCategory: "aborted",
3131
- };
3132
- finalizeRunRecord(run, rejection, "", new Date(run.startedAt).getTime());
3133
- run.originalParams = { ...run.originalParams, errorCategory: rejection.errorCategory };
3134
- state.persistRun(pi, run);
3135
- state.finalizeLiveSubagent(run.id);
3136
- };
3137
-
3138
- // R1: Circuit breaker check — reject if circuit is open
3139
- const circuitCheck = state.checkCircuit();
3140
- if (circuitCheck.isOpen) {
3141
- finalizePreStartRejection(circuitCheck.message!);
3142
- cleanupGitBranch();
3143
- return {
3144
- content: [{ type: "text" as const, text: circuitCheck.message! }],
3145
- details: undefined,
3146
- isError: true,
3147
- };
3148
- }
3149
-
3150
- // Resolve priority (issue #99 R2: single mode honors priority like chain/parallel/graph)
3151
- const singlePriority: Priority = (
3152
- params.priority && ["critical", "high", "normal", "low"].includes(params.priority)
3153
- ? (params.priority as Priority)
3154
- : DEFAULT_PRIORITY
3155
- );
3156
-
3157
- // Acquire concurrency slot
3158
- const acquired = await acquireSlot(state, ctx, signal, singlePriority);
3159
- if (!acquired) {
3160
- finalizePreStartRejection(SLOT_CANCEL_MESSAGE);
3161
- cleanupGitBranch();
3162
- return {
3163
- content: [
3164
- {
3165
- type: "text" as const,
3166
- text: SLOT_CANCEL_MESSAGE,
3167
- },
3168
- ],
3169
- details: undefined,
3170
- isError: true,
3171
- };
3172
- }
3173
-
3174
- let success = false;
3175
-
3176
- // Retire-on-retry (O3 fold, decision 2026-10-11): the retry has passed
3177
- // every pre-spawn gate and is about to start, so the SOURCE interrupted
3178
- // registry entry is superseded — clear it here so the old run is not
3179
- // re-offered at every subsequent boot. A failed pre-start (circuit open,
3180
- // slot cancelled) returns ABOVE this point: the source is left intact
3181
- // and retryable, while the NEW twin has already been finalized terminal
3182
- // by the gate (#340) — nothing dangles. `retrySourceRun` is set only on
3183
- // a `retryRunId` call.
3184
- if (retrySourceRun) clearInflightRun(retrySourceRun.id);
3185
-
3186
- // F7 (issue #65): import BEFORE the try — the crash-path catch calls
3187
- // completeTranscript, and block-scoped consts declared inside the try
3188
- // are invisible in its catch (pre-fix, a crash here threw
3189
- // "completeTranscript is not defined" instead of returning the
3190
- // sanitized crash result).
3191
- const { startTranscript, completeTranscript } = await import('./transcript');
3192
-
3193
- try {
3194
- // Build system prompt
3195
- const basePrompt = ctx.getSystemPrompt();
3196
- const subagentPrompt = buildSubagentPrompt(
3197
- basePrompt,
3198
- inheritSP,
3199
- customSP,
3200
- resolvedOutputFile,
3201
- toolOptions?.tools,
3202
- resolvedPreset?.promptGuideline,
3203
- );
3204
-
3205
- // Emit initial progress
3206
- const modeInfo = describePromptMode(inheritSP, Boolean(customSP));
3207
- onUpdate?.({
3208
- content: [
3209
- {
3210
- type: "text" as const,
3211
- text: `Starting subagent (${modeInfo})...`,
3212
- },
3213
- ],
3214
- details: {
3215
- messages: [],
3216
- usage: { ...EMPTY_USAGE },
3217
- exitCode: -1,
3218
- stderr: "",
3219
- },
3220
- });
3221
-
3222
- // Wrap onUpdate to feed live monitor
3223
- const liveOnUpdate = makeLiveOnUpdate(state, runId, onUpdate);
3224
-
3225
- const childDepth = currentDepth + 1;
3226
-
3227
- // Start transcript for audit trail
3228
- startTranscript(runId, task);
3229
-
3230
- let result = await runSubagent(
3231
- resolvedCwd,
3232
- subagentPrompt,
3233
- subagentModel,
3234
- thinkingLevel,
3235
- task,
3236
- signal,
3237
- liveOnUpdate,
3238
- toolOptions,
3239
- timeout,
3240
- getFinalOutput,
3241
- log,
3242
- childDepth,
3243
- undefined, // intercom
3244
- undefined, // subagentId
3245
- run.childMarker,
3246
- );
3247
-
3248
- // Auto-retry on timeout
3249
- if (
3250
- params.retryOnTimeout &&
3251
- isSubagentError(result) &&
3252
- result.errorMessage?.includes("timed out")
3253
- ) {
3254
- log.info("Auto-retrying after timeout", { runId });
3255
- state.registerLiveSubagent(runId, {
3256
- id: runId,
3257
- label,
3258
- task,
3259
- model: run.model,
3260
- thinkingLevel,
3261
- priority: params.priority,
3262
- startedAt: Date.now(),
3263
- ctx,
3264
- });
3265
-
3266
- onUpdate?.({
3267
- content: [
3268
- { type: "text" as const, text: "Retrying after timeout..." },
3269
- ],
3270
- details: {
3271
- messages: [],
3272
- usage: { ...EMPTY_USAGE },
3273
- exitCode: -1,
3274
- stderr: "",
3275
- },
3276
- });
3277
-
3278
- result = await runSubagent(
3279
- resolvedCwd,
3280
- subagentPrompt,
3281
- subagentModel,
3282
- thinkingLevel,
3283
- task,
3284
- signal,
3285
- liveOnUpdate,
3286
- toolOptions,
3287
- timeout,
3288
- getFinalOutput,
3289
- log,
3290
- childDepth,
3291
- undefined, // intercom
3292
- undefined, // subagentId
3293
- run.childMarker,
3294
- );
3295
- }
3296
-
3297
- // F3: Sanitize and cap output
3298
- let finalOutput = getFinalOutput(result.messages);
3299
- finalOutput = stripAnsi(finalOutput);
3300
- finalOutput = capOutput(finalOutput);
3301
-
3302
- // Attach label for display
3303
- result.label = label;
3304
-
3305
- // P3: Capture git diff if we created a work branch
3306
- if (workBranchName && headState) {
3307
- // Diff against the captured starting sha rather than the branch
3308
- // name: a detached start's branch label is the "HEAD" pseudo-ref,
3309
- // for which `git diff HEAD...HEAD` is always empty.
3310
- const diffResult = captureDiff(resolvedCwd, headState.sha);
3311
- if (diffResult.ok) {
3312
- result.gitBranch = workBranchName;
3313
- result.gitDiff = diffResult.diff;
3314
- }
3315
-
3316
- // Restore the starting HEAD (branch, or detached sha)
3317
- const restoreResult = restoreHead(resolvedCwd, headState);
3318
- if (restoreResult.ok) {
3319
- log.info("Restored original HEAD", {
3320
- branch: headState.branch,
3321
- detached: headState.detached,
3322
- });
3323
-
3324
- // P4: Change approval workflow — let user review the diff
3325
- const diffContent = (result.gitDiff ?? "").trim();
3326
- const hasChanges = diffContent.length > 0;
3327
- const shouldPrompt =
3328
- ctx.hasUI !== false &&
3329
- (resolvedApprovalMode === "always" ||
3330
- (resolvedApprovalMode === "writes" && hasChanges));
3331
-
3332
- if (shouldPrompt) {
3333
- const choice = await showApprovalDialog(ctx, label, result.gitDiff ?? "", workBranchName);
3334
-
3335
- if (choice === "apply") {
3336
- const mergeResult = mergeWorkBranch(resolvedCwd, workBranchName);
3337
- if (mergeResult.ok) {
3338
- log.info("Merged work branch (approved)", { branch: workBranchName });
3339
- result.approved = true;
3340
- } else {
3341
- log.error("Failed to merge work branch", {
3342
- branch: workBranchName,
3343
- error: mergeResult.error,
3344
- });
3345
- result.approved = false;
3346
- }
3347
- } else {
3348
- // Discard or cancelled
3349
- deleteBranch(resolvedCwd, workBranchName);
3350
- log.info("Discarded work branch", { branch: workBranchName });
3351
- result.approved = false;
3352
- }
3353
- workBranchName = undefined; // Prevent double-cleanup
3354
- } else if (hasChanges) {
3355
- // Auto-approve: merge the work branch
3356
- const mergeResult = mergeWorkBranch(resolvedCwd, workBranchName);
3357
- if (mergeResult.ok) {
3358
- log.info("Merged work branch (auto-approve)", { branch: workBranchName });
3359
- result.approved = true;
3360
- } else {
3361
- log.error("Failed to merge work branch (auto-approve)", {
3362
- branch: workBranchName,
3363
- error: mergeResult.error,
3364
- });
3365
- }
3366
- // #308: a DETACHED start has no branch of its own to hold the
3367
- // merge result — teardown re-detached at the captured sha and
3368
- // the merge fast-forwarded THAT detached HEAD, so deleting the
3369
- // work branch would leave the committed work reachable only
3370
- // from the detached HEAD (silently lost on the next checkout).
3371
- // Keep the branch as the durable ref and log where the work
3372
- // lives. An ATTACHED start merged onto its own branch, which
3373
- // already retains the commit, so the temporary work branch is
3374
- // safe to drop.
3375
- if (headState.detached) {
3376
- log.info("detached checkout: work preserved on branch", {
3377
- branch: workBranchName,
3378
- });
3379
- } else {
3380
- deleteBranch(resolvedCwd, workBranchName);
3381
- }
3382
- workBranchName = undefined;
3383
- } else {
3384
- // No changes — just delete the empty branch
3385
- deleteBranch(resolvedCwd, workBranchName);
3386
- workBranchName = undefined;
3387
- }
3388
- } else {
3389
- log.warn("Failed to restore original HEAD after work-branch run", {
3390
- branch: headState.branch,
3391
- error: restoreResult.error,
3392
- });
3393
- }
3394
-
3395
- // Nothing may leave teardown with the work branch still present: the
3396
- // approval flow above clears workBranchName on every terminal choice
3397
- // (including "apply", where keeping the branch is intentional), so a
3398
- // still-set name means the restore failed and the flow was skipped.
3399
- if (workBranchName) {
3400
- deleteBranch(resolvedCwd, workBranchName);
3401
- workBranchName = undefined;
3402
- }
3403
- }
3404
-
3405
- // Finalize run record
3406
- finalizeRunRecord(
3407
- run,
3408
- result,
3409
- finalOutput,
3410
- new Date(run.startedAt).getTime(),
3411
- );
3412
- run.originalParams = {
3413
- ...run.originalParams,
3414
- errorCategory: result.errorCategory,
3415
- };
3416
- state.persistRun(pi, run);
3417
-
3418
- // R2: Prune old run entries
3419
- pruneHistoryIfNeeded(state, ctx, log);
3420
-
3421
- // Finalize live monitor
3422
- state.finalizeLiveSubagent(runId);
3423
-
3424
- // E4: SLA tracking — compute metrics if enabled
3425
- if (state.config.slaTrackingEnabled) {
3426
- const recentRuns = state.getRunEntries(ctx).slice(0, state.config.slaWindowSize);
3427
- const metrics = computeSLAMetrics(recentRuns);
3428
- log.info("SLA metrics computed", {
3429
- totalRuns: metrics.totalRuns,
3430
- successRate: metrics.successRate,
3431
- p95DurationMs: metrics.p95DurationMs,
3432
- totalCost: metrics.totalCost,
3433
- });
3434
- if (state.config.lastSLAMetrics) {
3435
- const report = computeDegradation(metrics, state.config.lastSLAMetrics);
3436
- if (report.degraded) {
3437
- log.warn("SLA degradation detected", {
3438
- successRateChange: report.successRateChange,
3439
- p95Change: report.p95Change,
3440
- recommendations: report.recommendations,
3441
- });
3442
- }
3443
- }
3444
- state.config.lastSLAMetrics = metrics;
3445
- }
3446
-
3447
- if (isSubagentError(result)) {
3448
- const errorMsg =
3449
- result.errorMessage ||
3450
- result.stderr ||
3451
- finalOutput ||
3452
- "(no output from subagent)";
3453
- log.warn("Subagent failed", {
3454
- runId,
3455
- error: errorMsg,
3456
- exitCode: result.exitCode,
3457
- errorCategory: result.errorCategory,
3458
- });
3459
-
3460
- // H3: Post-mortem diagnostics — suggest fixes for the failure
3461
- const suggestions = diagnoseFailure({
3462
- task,
3463
- toolOptions,
3464
- thinkingLevel,
3465
- gitMode: resolvedGitMode,
3466
- errorMessage: result.errorMessage,
3467
- exitCode: result.exitCode,
3468
- timeout,
3469
- });
3470
-
3471
- // R1: Record failure in circuit breaker
3472
- state.recordFailure();
3473
-
3474
- let finalMsg = `Subagent failed: ${errorMsg}`;
3475
- if (suggestions.length > 0) {
3476
- finalMsg += "\n\nSuggestions:\n" + suggestions.map((s) => `- ${s}`).join("\n");
3477
- }
3478
- // C: warnings ride the returned result too — a failed run is
3479
- // exactly when the conductor most needs the mismatch signal.
3480
- finalMsg += warningsNote;
3481
-
3482
- completeTranscript(runId, 'failed');
3483
-
3484
- return {
3485
- content: [
3486
- { type: "text" as const, text: finalMsg },
3487
- ],
3488
- details: result,
3489
- isError: true,
3490
- };
3491
- }
3492
-
3493
- success = true;
3494
- completeTranscript(runId, 'completed');
3495
- log.info("Subagent completed successfully",{
3496
- runId,
3497
- tokensIn: result.usage.input,
3498
- tokensOut: result.usage.output,
3499
- cost: result.usage.cost,
3500
- sessionTotalCost: state.getSessionTotalCost(ctx),
3501
- });
3502
-
3503
- // R1: Record success in circuit breaker
3504
- state.recordSuccess();
3505
-
3506
- // B2: Surface auto-route decisions in the tool result so the conductor
3507
- // sees WHICH preset was auto-selected, the KEYWORD evidence for it,
3508
- // and what it restricts. Derive the restriction from the RESOLVED
3509
- // toolOptions (reflects per-call overrides) rather than the preset's
3510
- // declared values.
3511
- const autoRouteNote = autoRoutedPreset
3512
- ? `\n\n[auto-routed to preset '${autoRoutedPreset.name}'${autoRouteKeyword ? ` (matched keyword '${autoRouteKeyword}')` : ""} — ${toolOptions ? formatToolRestriction(toolOptions) : formatPresetRestriction(autoRoutedPreset)}]`
3513
- : "";
3514
-
3515
- return {
3516
- content: [
3517
- { type: "text" as const, text: (finalOutput || "(no output)") + autoRouteNote + warningsNote },
3518
- ],
3519
- details: result,
3520
- };
3521
- } catch (err) {
3522
- // P3: Clean up git branch on crash
3523
- cleanupGitBranch();
3524
- completeTranscript(runId, 'failed');
3525
-
3526
- const result = buildCrashResult("Subagent", err, resolvedCwd);
3527
- log.error("Subagent crashed", { runId, error: result.details.errorMessage });
3528
-
3529
- // R2 (review): mirror the completion path — finalize the live entry
3530
- // and persist a FAILED run record. Without this the live entry stays
3531
- // 'running' forever, the stale sweep never reclaims it, and the
3532
- // drill-in loops on the live branch indefinitely. finalizeLiveSubagent
3533
- // is idempotent (true = THIS call claimed it; the foreground path has
3534
- // no activeSubagents counters to gate).
3535
- state.finalizeLiveSubagent(runId);
3536
- const crashOutput = state.subagentSessions.get(runId)?.liveOutput ?? "";
3537
- finalizeRunRecord(
3538
- run,
3539
- result.details,
3540
- crashOutput,
3541
- new Date(run.startedAt).getTime(),
3542
- );
3543
- state.persistRun(pi, run);
3544
-
3545
- return result;
3546
- } finally {
3547
- releaseSlot(state, success, ctx);
3548
- }
3549
- },
3550
-
3551
- renderCall(
3552
- args: DelegateTaskParams,
3553
- theme: Theme,
3554
- _context: unknown,
3555
- ) {
3556
- return renderDelegateCall(args, theme);
3557
- },
3558
-
3559
- renderResult(
3560
- result: AgentToolResult<DelegateTaskDetails>,
3561
- options: ToolRenderResultOptions,
3562
- theme: Theme,
3563
- _context: unknown,
3564
- ) {
3565
- return renderDelegateResult(result, options, theme);
3566
- },
3567
- });
202
+ pi.registerCommand(
203
+ "brl-subagent",
204
+ createCommands(rt, { applyConfig, resetState, abandonProductionRun }),
205
+ );
3568
206
 
3569
207
  // -------------------------------------------------------------------
3570
- // get_subagent_result tool — retrieve terminal status/result on demand
208
+ // delegate_task tool — the definition is built by `createDelegateHandler`
209
+ // and registered HERE: the registration surface stays in the composition
210
+ // root (ADR 0027 D7), and the handler receives the SAME mode-runner,
211
+ // background-pipeline and boot-recovery instances created above (D5).
3571
212
  // -------------------------------------------------------------------
3572
213
 
3573
- pi.registerTool({
3574
- name: "get_subagent_result",
3575
- label: "Get Subagent Result",
3576
- description: [
3577
- "Check the status of a background agent and retrieve its result.",
3578
- "The conductor is woken with a completion message when the agent finishes; use this for post-wake retrieval, stall checks, and detail access — not for polling.",
3579
- "Accepts a full agent id or a unique 8-character id prefix.",
3580
- "When the id belongs to a retried run, the answer names the latest attempt; a finished run that was superseded also reports its successor.",
3581
- "Returns the agent's status, result (if completed), and transcript path.",
3582
- ].join(" "),
3583
- parameters: Type.Object({
3584
- agent_id: Type.String({
3585
- description: "The agent ID returned by delegate_task when background=true",
3586
- }),
3587
- verbose: Type.Optional(
3588
- Type.Boolean({
3589
- description: "If true, include the full conversation log. Default: false.",
3590
- }),
3591
- ),
214
+ pi.registerTool(
215
+ createDelegateHandler(rt, {
216
+ runChainMode,
217
+ runParallelMode,
218
+ runGraphMode,
219
+ runBackgroundFanOut,
220
+ spawnBackgroundRun,
221
+ visibleRunsFor,
3592
222
  }),
3593
- execute: async (toolCallId, params) => {
3594
- const { getAgent, resolveAgentId, findRetryLineage, isTerminalAgentStatus, RETRY_SCAN_WINDOW_MS, RETRY_SCAN_WINDOW_DAYS } = await import('./session-manager');
3595
- const { getTranscript } = await import('./transcript');
3596
-
3597
- // The notices render the first 8 hex characters of an id; resolve a
3598
- // unique prefix before both the record read and the lineage lookup.
3599
- // Ambiguity fails closed — a guess here could report the wrong run.
3600
- const resolution = resolveAgentId(params.agent_id);
3601
- if (resolution.kind === 'ambiguous') {
3602
- return {
3603
- content: [{
3604
- type: "text" as const,
3605
- text: `Agent id prefix "${params.agent_id}" is ambiguous — matches: ${resolution.matches.join(', ')}`,
3606
- }],
3607
- details: undefined,
3608
- isError: true,
3609
- };
3610
- }
3611
- // Anything that is not a full id or a matching 8-hex prefix keeps
3612
- // today's message — there is no id to resolve against the stores.
3613
- if (resolution.kind === 'unresolved') {
3614
- return {
3615
- content: [{ type: "text" as const, text: `Agent ${params.agent_id} not found` }],
3616
- details: undefined,
3617
- isError: true,
3618
- };
3619
- }
3620
- const agentId = resolution.id;
3621
-
3622
- const agent = getAgent(agentId);
3623
-
3624
- if (!agent) {
3625
- const lineage = findRetryLineage(agentId);
3626
- if (lineage.latest && lineage.latest.id !== agentId) {
3627
- const latest = lineage.latest;
3628
- return {
3629
- content: [{
3630
- type: "text" as const,
3631
- text: `Agent ${params.agent_id} not found — run ${params.agent_id} was retried as ${latest.id} (attempt ${latest.attempt}, ${latest.status}, started ${new Date(latest.startedAt).toISOString()}).`,
3632
- }],
3633
- details: undefined,
3634
- isError: true,
3635
- };
3636
- }
3637
-
3638
- const registryRun = lineage.inflight.find((run) => run.id === agentId);
3639
- const registryStarted = registryRun
3640
- ? (Number.isFinite(Date.parse(registryRun.startedAt))
3641
- ? new Date(registryRun.startedAt).toISOString()
3642
- : registryRun.startedAt)
3643
- : undefined;
3644
- const registryText = registryRun
3645
- ? `no recent retry lineage recorded, but the registry still lists run ${registryRun.id} (attempt ${registryRun.attempt ?? 1}, started ${registryStarted}).`
3646
- : `no recent retry lineage recorded (scanned the last ${RETRY_SCAN_WINDOW_DAYS} days), and no registry record either.`;
3647
- return {
3648
- content: [{
3649
- type: "text" as const,
3650
- text: `Agent ${params.agent_id} not found — ${registryText}`,
3651
- }],
3652
- details: undefined,
3653
- isError: true,
3654
- };
3655
- }
3656
-
3657
- let resultText = `Agent: ${agent.description}\n`;
3658
- resultText += `Status: ${agent.status}\n`;
3659
- resultText += `Started: ${new Date(agent.startedAt).toISOString()}\n`;
3660
-
3661
- if (agent.completedAt) {
3662
- resultText += `Completed: ${new Date(agent.completedAt).toISOString()}\n`;
3663
- resultText += `Duration: ${agent.completedAt - agent.startedAt}ms\n`;
3664
- }
3665
-
3666
- if (agent.error) {
3667
- resultText += `Error: ${agent.error}\n`;
3668
- }
3669
-
3670
- // A terminal source can be the WRONG run to act on: the retry that
3671
- // actually finished is a later attempt of the same dispatch. Name it
3672
- // so a terminal status is not read as the final word.
3673
- if (isTerminalAgentStatus(agent.status)) {
3674
- const lineage = findRetryLineage(agentId, agent);
3675
- if (lineage.latest && lineage.latest.id !== agentId) {
3676
- const latest = lineage.latest;
3677
- resultText += `Superseded by ${latest.id} (attempt ${latest.attempt}, ${latest.status}, started ${new Date(latest.startedAt).toISOString()})\n`;
3678
- } else if (agent.startedAt < Date.now() - RETRY_SCAN_WINDOW_MS) {
3679
- // The lineage scan is windowed: an older run cannot be shown a
3680
- // later attempt that fell outside it. Say so instead of implying
3681
- // there is none.
3682
- resultText += `Retry lineage not checked: this run started more than ${RETRY_SCAN_WINDOW_DAYS} days ago.\n`;
3683
- }
3684
- }
3685
-
3686
- if (agent.result) {
3687
- resultText += `\nResult:\n`;
3688
- if (agent.result.messages && agent.result.messages.length > 0) {
3689
- resultText += agent.result.messages.join('\n');
3690
- }
3691
- // W4: surface the background agent's git work-branch diff so the
3692
- // captured changes are reviewable (the branch itself is discarded).
3693
- if (agent.result.gitBranch) {
3694
- resultText += `\nGit branch: ${agent.result.gitBranch}\n`;
3695
- }
3696
- if (agent.result.gitDiff) {
3697
- const diff = agent.result.gitDiff;
3698
- const truncated = diff.length > 8000 ? diff.slice(0, 8000) + "\n…[diff truncated]" : diff;
3699
- resultText += `\nGit diff (branch ${agent.result.gitBranch ?? 'work'}):\n${truncated}\n`;
3700
- }
3701
- }
3702
-
3703
- if (agent.finalOutput) {
3704
- const full = agent.finalOutput;
3705
- const truncated = full.length > 8000 ? full.slice(0, 8000) + "\n…[truncated — full output in transcript]" : full;
3706
- resultText += `\n\nFinal output:\n${truncated}`;
3707
- }
3708
-
3709
- // Include transcript if verbose
3710
- if (params.verbose) {
3711
- const transcript = getTranscript(agentId);
3712
- if (transcript.length > 0) {
3713
- resultText += `\n\nTranscript (${transcript.length} entries):\n`;
3714
- for (const entry of transcript.slice(-10)) { // Last 10 entries
3715
- resultText += `[${new Date(entry.timestamp).toISOString()}] ${entry.type}: ${entry.content.slice(0, 100)}\n`;
3716
- }
3717
- }
3718
- }
3719
-
3720
- // Include transcript path
3721
- resultText += `\nTranscript: ${transcriptDisplayPath(agentId)}`;
3722
-
3723
- return {
3724
- content: [{ type: "text" as const, text: resultText }],
3725
- details: undefined,
3726
- };
3727
- },
3728
- });
223
+ );
3729
224
 
3730
225
  // -------------------------------------------------------------------
3731
- // steer_subagent tool — inject messages into running agents
226
+ // Agent tools — get_subagent_result / steer_subagent / stop_subagent.
227
+ // Registered here, one `pi.registerTool` call per definition returned.
3732
228
  // -------------------------------------------------------------------
3733
229
 
3734
- // steer_subagent tool — inject messages into running agents
3735
- pi.registerTool({
3736
- name: "steer_subagent",
3737
- label: "Steer Subagent",
3738
- description: [
3739
- "Send a steering message to a running background agent.",
3740
- "The message is delivered after the agent's current tool call finishes, before its next model call.",
3741
- "Use this to redirect an agent's work without restarting it.",
3742
- ].join(" "),
3743
- parameters: Type.Object({
3744
- agent_id: Type.String({
3745
- description: "The agent ID to steer",
3746
- }),
3747
- message: Type.String({
3748
- description: "The message to inject into the agent's conversation",
3749
- }),
3750
- }),
3751
- execute: async (toolCallId, params, _signal, _onUpdate, ctx) => {
3752
- const { steerAgent } = await import('./session-manager');
3753
-
3754
- try {
3755
- const agent = await steerAgent(params.agent_id, params.message);
3756
-
3757
- if (!agent) {
3758
- return {
3759
- content: [{ type: "text" as const, text: `Agent ${params.agent_id} not found` }],
3760
- details: undefined,
3761
- isError: true,
3762
- };
3763
- }
3764
-
3765
- return {
3766
- content: [{
3767
- type: "text" as const,
3768
- text: `Steered agent ${params.agent_id}: "${params.message.slice(0, 50)}${params.message.length > 50 ? '...' : ''}"`,
3769
- }],
3770
- details: undefined,
3771
- };
3772
- } catch (err) {
3773
- // F7 (issue #65): sanitize BEFORE the message reaches the main
3774
- // agent's context. pi passes ctx as the 5th arg to tool execute,
3775
- // so ctx.cwd is in scope — sibling-project paths are properly
3776
- // masked (defensive process.cwd() fallback if ctx is undefined).
3777
- const message = sanitizeErrorMessage(err instanceof Error ? err.message : String(err), ctx?.cwd);
3778
- return {
3779
- content: [{ type: "text" as const, text: `Failed to steer agent: ${message}` }],
3780
- details: undefined,
3781
- isError: true,
3782
- };
3783
- }
3784
- },
3785
- });
3786
-
3787
- pi.registerTool({
3788
- name: "stop_subagent",
3789
- label: "Stop Subagent",
3790
- description: [
3791
- "Stop a running background agent by aborting its session.",
3792
- "The agent's current operation is aborted and the session is marked stopped.",
3793
- "Use this to halt a background agent that is no longer needed.",
3794
- ].join(" "),
3795
- parameters: Type.Object({
3796
- agent_id: Type.String({
3797
- description: "The agent ID to stop",
3798
- }),
3799
- }),
3800
- execute: async (toolCallId, params, _signal, _onUpdate, ctx) => {
3801
- const { stopAgent } = await import('./session-manager');
3802
-
3803
- try {
3804
- const agent = await stopAgent(params.agent_id);
3805
-
3806
- if (!agent) {
3807
- return {
3808
- content: [{ type: "text" as const, text: `Agent ${params.agent_id} not found` }],
3809
- details: undefined,
3810
- isError: true,
3811
- };
3812
- }
3813
-
3814
- return {
3815
- content: [{
3816
- type: "text" as const,
3817
- text: `Stopped agent ${params.agent_id} (${agent.description}).`,
3818
- }],
3819
- details: undefined,
3820
- };
3821
- } catch (err) {
3822
- // F7 (issue #65): sanitize BEFORE the message reaches the main
3823
- // agent's context. pi passes ctx as the 5th arg to tool execute,
3824
- // so ctx.cwd is in scope — sibling-project paths are properly
3825
- // masked (defensive process.cwd() fallback if ctx is undefined).
3826
- const message = sanitizeErrorMessage(err instanceof Error ? err.message : String(err), ctx?.cwd);
3827
- return {
3828
- content: [{ type: "text" as const, text: `Failed to stop agent: ${message}` }],
3829
- details: undefined,
3830
- isError: true,
3831
- };
3832
- }
3833
- },
3834
- });
230
+ for (const tool of createAgentTools()) pi.registerTool(tool);
3835
231
 
3836
232
  // -------------------------------------------------------------------
3837
233
  // Session lifecycle — F7: Session-bound state initialization
3838
234
  // -------------------------------------------------------------------
3839
235
 
3840
- // -------------------------------------------------------------------
3841
- // Option B U1: boot recovery — identity/liveness detection + child reap
3842
- // -------------------------------------------------------------------
3843
- // Runs AFTER restoreFromSession so config is ready. Candidate runs come from
3844
- // the DURABLE registry (`.pi/run-registry/`), NOT from this session's run
3845
- // entries: a crashed session's foreground/unit records are invisible to a
3846
- // default fresh startup, and the full `.pi/subagents/` store is too costly to
3847
- // parse (only the one agent record a background entry names is read). For
3848
- // each in-flight run whose owner is dead, its orphaned marker-verified child
3849
- // is reaped and the record is marked: the registry entry always, plus the
3850
- // agent record for background runs. The scan itself is SILENT in the UI —
3851
- // U3's `maybeSendRecoveryNotice` (below) is the one notice surface.
3852
- // Platforms without /proc skip the whole scan (one log line):
3853
- // pid-only liveness cannot rule out pid reuse, so nothing is killed or
3854
- // marked unverified.
3855
- async function performBootRecovery(): Promise<void> {
3856
- try {
3857
- const { getAgent, markAgentInterrupted } = await import("./session-manager");
3858
- // `recoverProduction` owns the /proc platform guard (nothing is marked or
3859
- // killed without start-token verification) — see src/recovery.ts.
3860
- const summary = await recoverProduction({
3861
- log,
3862
- // Read THAT ONE agent record by id — never the whole store.
3863
- readAgentRecord: (id) => getAgent(id),
3864
- mark(record, interruptedAt) {
3865
- // Registry entry = the durable mark for every kind. Issue #304: its
3866
- // boolean is the durable-write result — do NOT drop it, or the boot
3867
- // summary would claim a mark that never landed. The scan counts a
3868
- // `false` as `markFailures` and warns with the id.
3869
- const durable = markInterrupted(record.id, interruptedAt);
3870
- if (record.kind === "agent") markAgentInterrupted(record.id, interruptedAt);
3871
- return durable;
3872
- },
3873
- });
3874
- // Report the scan whenever it did anything durable OR attempted a mark
3875
- // that failed — a failure-only boot must not be silent (issue #304).
3876
- if (summary.marked > 0 || summary.markFailures > 0) {
3877
- log.warn("Boot recovery marked interrupted runs", { ...summary });
3878
- }
3879
- } catch (err) {
3880
- // Recovery is best-effort hygiene — it must never break session start.
3881
- log.warn("Boot recovery scan failed", { error: (err as Error).message });
3882
- }
3883
- }
3884
-
3885
- /**
3886
- * Option B U3 Fix A: the recovery visibility bridge, wired for the two
3887
- * extension consumers that resolve a run id (the retryRunId branch and the
3888
- * abandon action). Session run entries UNIONED with synthetic durable
3889
- * interrupted records the session has never seen (a genuine fresh boot), so
3890
- * an id named by the boot notice resolves here instead of being rejected as
3891
- * not found. `getAgent` is injected because the callers already load it
3892
- * dynamically — this keeps the registry/agent reads in ONE place.
3893
- */
3894
- function visibleRunsFor(
3895
- ctx: ExtensionContext,
3896
- getAgent: RecoveryAgentLookup,
3897
- ): SubagentRun[] {
3898
- return visibleRunEntriesForSession(state.getRunEntries(ctx), getAgent);
3899
- }
3900
-
3901
- /**
3902
- * Option B U3 (D2): after the boot scan, send ONE notice at the next turn
3903
- * boundary listing every unresolved interrupted run whose dispatch snapshot
3904
- * (and the session posture) says "offer". Delivery is `nextTurn` — the notice
3905
- * can never steer or arrive mid-turn (see `resolveRecoveryNoticeDelivery`).
3906
- * Silent when there is nothing to offer; at most once per session start.
3907
- */
3908
- async function maybeSendRecoveryNotice(ctx: ExtensionContext): Promise<void> {
3909
- if (recoveryNoticeDelivered) return;
3910
- recoveryNoticeDelivered = true;
3911
- // Session posture off silences the whole surface, regardless of per-run
3912
- // snapshots (a user opting out expects quiet).
3913
- if (state.config.recovery === "off") return;
3914
- try {
3915
- const { getAgent } = await import("./session-manager");
3916
- const offered = offeredInterruptedRuns(
3917
- collectInterruptedRuns({
3918
- listInflight: () => listInflightRuns(),
3919
- getAgent: (id) => getAgent(id),
3920
- findRun: (id) => state.findTerminalRunById(ctx, id),
3921
- }),
3922
- );
3923
- if (offered.length === 0) return;
3924
- pi.sendMessage(buildRecoveryNotice(offered), resolveRecoveryNoticeDelivery());
3925
- log.info("Recovery notice delivered", { count: offered.length });
3926
- } catch (err) {
3927
- // The notice is best-effort — it must never break session start.
3928
- log.warn("Recovery notice failed", { error: (err as Error).message });
3929
- }
3930
- }
3931
-
3932
- /**
3933
- * Option B U3 (D5): finalize ONE interrupted run as the existing terminal
3934
- * `stopped` outcome and prune its U2 session dir. Wired through injected deps
3935
- * so the pure core (`recovery-surface.ts`) stays testable; the run record is
3936
- * written terminal (the run store's `status` union has no `stopped` — a
3937
- * stopped outcome is represented as `failed` + `errorCategory: "aborted"`,
3938
- * exactly as every other stop path does) and the background agent record is
3939
- * flipped to `stopped`.
3940
- */
3941
- async function abandonProductionRun(ctx: ExtensionContext, id: string): Promise<void> {
3942
- const { updateAgentStatus, pruneBackgroundSession, getAgent } = await import("./session-manager");
3943
- // Fix A: the abandon lookup routes through the visibility bridge, so a run
3944
- // that exists ONLY in the durable registry after a fresh boot is
3945
- // abandonable instead of resolving to undefined (the silent `false`).
3946
- const visible = visibleRunsFor(ctx, getAgent);
3947
- abandonInterruptedRun(id, {
3948
- getRun: (runId) => resolveTerminalRunEntry(visible, runId),
3949
- writeRun: (run) => {
3950
- state.persistRun(pi, run);
3951
- pruneHistoryIfNeeded(state, ctx, log);
3952
- },
3953
- markAgentStopped: (agentId) => {
3954
- const agent = updateAgentStatus(agentId, "stopped");
3955
- if (agent) log.info("Abandoned background agent record", { agentId });
3956
- },
3957
- retireRegistry: (runId) => clearInflightRun(runId),
3958
- pruneSession: (runId) => pruneBackgroundSession(runId),
3959
- });
3960
- }
3961
-
3962
236
  pi.on("session_start", async (_event, ctx) => {
3963
237
  // Issue #147: capture the session context for the completion-push subscriber.
3964
238
  sessionCtx = ctx;
@@ -4013,10 +287,18 @@ export default function (pi: ExtensionAPI) {
4013
287
  // records interrupted BEFORE anything else touches their worktrees.
4014
288
  await performBootRecovery();
4015
289
 
290
+ // Issue #466 (ADR 0026 D2/D5): reconcile the durable head-state records —
291
+ // the ONE step allowed to move git at boot, and only for a record whose
292
+ // owner it has proved dead.
293
+ const headStateOutcomes = reconcileHeadStatesAtBoot();
294
+
4016
295
  // Option B U3 (D2): after the scan, surface every unresolved interrupted
4017
296
  // run ONCE, at the next turn boundary (never mid-turn).
4018
297
  await maybeSendRecoveryNotice(ctx);
4019
298
 
299
+ // Issue #466: the head-state verdicts ride the same nextTurn channel.
300
+ maybeSendHeadStateNotice(headStateOutcomes);
301
+
4020
302
  // Issue #356: boot is a config-paint edge — route it through the same
4021
303
  // chokepoint as every other footer repaint. With no runs in flight the
4022
304
  // chokepoint draws the idle config line the old direct call painted.
@@ -4025,6 +307,18 @@ export default function (pi: ExtensionAPI) {
4025
307
 
4026
308
  // F7: Clean up session-bound state on shutdown
4027
309
  pi.on("session_shutdown", async (_event, _ctx) => {
310
+ // Issue #437: release THIS runtime's terminal subscribers FIRST — before
311
+ // any await or fallible cleanup. A clean replacement (/new, /resume,
312
+ // /fork, /reload, quit) tears this runtime down and loads a new factory
313
+ // instance; the old listeners used to survive and win the shared terminal
314
+ // claim for the NEW session's run, delivering (or throwing) through dead
315
+ // pi/ctx handles. Only our three exact identities are removed, and the
316
+ // release is idempotent, so other subscribers and a later runtime are
317
+ // untouched. `releaseTerminalSubscriptions` is the notifier factory's own
318
+ // `release` (ADR 0027 D5), built below at the position the subscription
319
+ // block used to occupy — this handler body runs after init completes.
320
+ releaseTerminalSubscriptions();
321
+
4028
322
  log.info("Session shutting down", {
4029
323
  activeSubagents: state.activeSubagents,
4030
324
  });
@@ -4038,135 +332,25 @@ export default function (pi: ExtensionAPI) {
4038
332
  }
4039
333
 
4040
334
  cleanupSessionState(state);
4041
- // U3: a new session boot may notify again.
4042
- recoveryNoticeDelivered = false;
335
+ // U3: a new session boot may notify again (the latch is the boot
336
+ // factory's own — ADR 0027 D5, so the reset goes through it).
337
+ resetRecoveryNotice();
4043
338
  });
4044
339
 
4045
340
  // -------------------------------------------------------------------
4046
- // Issue #147: completion-push wake — subscribe to terminal event-bus events
341
+ // Issue #147: completion-push wake — the terminal notifier (ADR 0027 S4)
4047
342
  // -------------------------------------------------------------------
4048
- // The event-bus is the complete terminal chokepoint (subagent:completed /
4049
- // subagent:failed / subagent:stopped), so the conductor is woken via
4050
- // pi.sendMessage + triggerTurn when a background run reaches a terminal state.
4051
- // Delivery is always-on (minimum nextTurn); the completionNotify knob controls
4052
- // the WAKE (D1+D2 — see notify-completion.ts). The shared terminal claim
4053
- // (issue #315) defends the pathological double-emit path (first terminal
4054
- // event or crash notice per id wins); it is capped simply (cleared when it
4055
- // exceeds 200 entries).
4056
- //
4057
- // Stopped-run degradation — ACCEPTED BY DESIGN (review #2, adjudicated
4058
- // 2026-09-01): subagent:stopped fires at stop time (updateAgentStatus) BEFORE
4059
- // finalizeRunEntry stamps cost/duration/errorCategory and before finalOutput
4060
- // is captured. So the stopped shape may lack those fields and the run entry
4061
- // resolveRunEntry returns may be the pre-finalize spawn entry. The wake is
4062
- // the point; details are best-effort — the notification must never throw or
4063
- // block on their absence.
4064
- const terminalTypes = ["subagent:completed", "subagent:failed", "subagent:stopped"] as const;
4065
- for (const type of terminalTypes) {
4066
- eventBus.on(type, (event) => {
4067
- void deliverCompletionAlert(event);
4068
- });
4069
- }
4070
-
4071
- /**
4072
- * Issue #365: re-dispatch a background run that settled with a transport-class
4073
- * failure, using the `retryRunId` machinery. `resolveRetryParams({}, run)`
4074
- * restores the recorded params and `spawnBackgroundRun(..., run)` mints the
4075
- * lineage (`resumeOf` + `attempt: 2`), so the retry re-runs the normal gates
4076
- * (cost, approval, pre-task) and is visible in the record.
4077
- *
4078
- * Issue #401/#411: the retry carries a resume preamble (`attemptContext`) that
4079
- * is injected into the child's system prompt only (as a `<resume-context>`
4080
- * section), never inside the `<task>` fence. The task handed to
4081
- * `resolveSubagentParams` stays the recorded original, so auto-routing, H1
4082
- * keyword warnings and the capability checks behave exactly as they did on
4083
- * attempt 1.
4084
- *
4085
- * Returns TRUE when the retry was actually spawned — the caller then SUPPRESSES
4086
- * the source run's completion notice, because the retry's own terminal settle
4087
- * is the wake. A gate rejection or a throwing spawn returns FALSE and the
4088
- * caller reports the original failure exactly as before (no silent drop).
4089
- */
4090
- async function scheduleTransportRetry(
4091
- ctx: ExtensionContext,
4092
- run: SubagentRun,
4093
- ): Promise<boolean> {
4094
- const sourceAttempt = run.attempt ?? 1;
4095
- try {
4096
- const retryParams = resolveRetryParams({}, run);
4097
- // Issue #404: point at the retained session ONLY when it is really
4098
- // there. Resolve this conductor-side: the child may run in another cwd.
4099
- // An invalid id cannot have a session dir (and `backgroundSessionDir`
4100
- // throws on one) — no pointer, no throw.
4101
- let retainedSessionDir: string | undefined;
4102
- try {
4103
- const { retainedSessionPointer } = await import('./session-manager');
4104
- const candidate = retainedSessionPointer(run.id);
4105
- if (fs.existsSync(candidate)) retainedSessionDir = candidate;
4106
- } catch {
4107
- retainedSessionDir = undefined;
4108
- }
4109
- const result = await spawnBackgroundRun(
4110
- pi,
4111
- ctx,
4112
- retryParams,
4113
- retryParams.task!,
4114
- run,
4115
- buildRetryResumePreamble(run, sourceAttempt + 1, retainedSessionDir),
4116
- );
4117
- if (result.isError) {
4118
- log.warn("Transport auto-retry spawn rejected — surfacing the original failure", {
4119
- sourceId: run.id,
4120
- attempt: sourceAttempt,
4121
- error: result.content[0]?.type === "text" ? result.content[0].text : undefined,
4122
- });
4123
- return false;
4124
- }
4125
- } catch (err) {
4126
- log.warn("Transport auto-retry spawn failed — surfacing the original failure", {
4127
- sourceId: run.id,
4128
- attempt: sourceAttempt,
4129
- error: (err as Error).message,
4130
- });
4131
- return false;
4132
- }
4133
- log.info("Background run settled — transport auto-retry scheduled", {
4134
- sourceId: run.id,
4135
- attempt: sourceAttempt + 1,
4136
- });
4137
- ctx.ui.notify(TRANSPORT_RETRY_TOAST, "warning");
4138
- return true;
4139
- }
343
+ // The notifier owns its three subscriptions AND their release latch (D5).
344
+ // Created HERE, where the subscription block used to live, so the bus sees
345
+ // the same registration order. Its one backward edge — the transport-retry
346
+ // re-dispatch — reaches the S3 pipeline's spawn through this deps literal.
347
+ const terminalNotifier = createTerminalNotifier(rt, {
348
+ // ADR 0027 D2: `sessionCtx` stays a `let` here; the listener gets a getter.
349
+ getSession: () => sessionCtx,
350
+ spawnBackgroundRun,
351
+ });
352
+ // The shutdown hook keeps its old name and its position: `release` is
353
+ // idempotent and removes only this instance's three listeners (#437).
354
+ const releaseTerminalSubscriptions = terminalNotifier.release;
4140
355
 
4141
- async function deliverCompletionAlert(event: SubagentEvent): Promise<void> {
4142
- const id = event.agentId;
4143
- if (!claimTerminalNotice(id)) return;
4144
- const ctx = sessionCtx;
4145
- if (!ctx) return;
4146
- try {
4147
- const { getAgent } = await import("./session-manager");
4148
- const agent = getAgent(id);
4149
- if (!agent) return; // pruned or foreign id — nothing to notify
4150
- const knob = state.config.completionNotify ?? "all";
4151
- const run = resolveRunEntry(state.getRunEntries(ctx), id);
4152
- // Issue #365: a transport-class background failure is re-dispatched once
4153
- // and the source notice is suppressed (the retry's settle is the wake).
4154
- // Every other terminal type — and every non-retryable failure — keeps the
4155
- // existing path unchanged.
4156
- if (event.type === "subagent:failed" && run && isTransportRetryable(run)) {
4157
- const retried = await scheduleTransportRetry(ctx, run);
4158
- if (retried) return;
4159
- }
4160
- const message = buildCompletionMessage(agent, run);
4161
- // Issue #179 (D2): resolve delivery from the CLASSIFIED notification
4162
- // status, not the raw agent status — otherwise a run whose completion
4163
- // the builder downgraded to failed would still be delivered as a success.
4164
- const delivery = resolveDelivery(message.details.status, knob);
4165
- sendCompletionNotification(pi, message, delivery);
4166
- } catch (err) {
4167
- log.warn(`completion-push handler failed for ${id}`, {
4168
- error: (err as Error).message,
4169
- });
4170
- }
4171
- }
4172
356
  }