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