brl-subagent 2.7.0 → 2.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENT.md +3 -3
- package/README.md +18 -10
- package/package.json +6 -5
- package/src/agent-tools.ts +332 -0
- package/src/background-pipeline.ts +1025 -0
- package/src/boot-recovery.ts +313 -0
- package/src/commands.ts +137 -0
- package/src/concurrency.ts +26 -5
- package/src/delegate-handler.ts +2261 -0
- package/src/engineering-bar.ts +69 -0
- package/src/event-bus.ts +10 -0
- package/src/git.ts +274 -5
- package/src/headstate.ts +471 -0
- package/src/history.ts +21 -3
- package/src/index.ts +127 -3943
- package/src/kill-escalation.ts +87 -7
- package/src/loader.ts +47 -1
- package/src/logging.ts +1 -1
- package/src/mode-prologue.ts +4 -10
- package/src/mode-runners.ts +1575 -0
- package/src/notify-completion.ts +180 -12
- package/src/params.ts +211 -37
- package/src/preflight.ts +123 -16
- package/src/prelude.ts +92 -7
- package/src/presets.ts +85 -18
- package/src/proc.ts +2 -3
- package/src/project-flags.ts +3 -3
- package/src/recovery-engine.ts +11 -1
- package/src/recovery-surface.ts +1 -2
- package/src/recovery.ts +155 -20
- package/src/reports.ts +1 -7
- package/src/run-registry.ts +22 -3
- package/src/runner.ts +80 -21
- package/src/runtime.ts +50 -0
- package/src/sanitize.ts +20 -2
- package/src/scheduler.ts +1 -2
- package/src/schema.ts +37 -7
- package/src/scratch-root.ts +909 -0
- package/src/scratch-spawn.ts +256 -0
- package/src/session-manager.ts +854 -200
- package/src/state.ts +130 -30
- package/src/templates.ts +42 -17
- package/src/terminal-notifier.ts +405 -0
- package/src/transcript.ts +1 -1
- package/src/tui-format.ts +177 -7
- package/src/tui.ts +115 -57
- package/src/types.ts +206 -5
- package/src/unit-params.ts +113 -0
- package/src/unit-run.ts +45 -16
- package/src/validate.ts +89 -11
- package/src/worktree-report.ts +142 -0
|
@@ -0,0 +1,1575 @@
|
|
|
1
|
+
// Purpose: The three foreground batch-mode runners (chain, parallel, graph) plus their per-unit helpers, built over one runtime context.
|
|
2
|
+
/**
|
|
3
|
+
* brl-subagent — the mode runners (cycle S2, ADR 0027 D1/D3/D6)
|
|
4
|
+
*
|
|
5
|
+
* `runChainMode`, `runParallelMode` and `runGraphMode` used to be closures
|
|
6
|
+
* inside `src/index.ts`'s default export, alongside the two per-unit helpers
|
|
7
|
+
* they share (`resolveStepModel`, `applyUnitShapeGuard`) and the two record
|
|
8
|
+
* mappings (`graphTaskToSubTaskParams`, `toSubTaskResult`). ~1,300 lines of the
|
|
9
|
+
* composition root were the mode implementations themselves.
|
|
10
|
+
*
|
|
11
|
+
* D3: this module may import the `src/*.ts` modules it needs, and NOT the
|
|
12
|
+
* composition root — `architecture-rules` forbids a non-entry module importing
|
|
13
|
+
* `index.ts`. The three bindings the moved bodies read from their old closure
|
|
14
|
+
* (`pi`, `log`, `state`) arrive as the `RuntimeContext` argument; everything else
|
|
15
|
+
* they touch was already a module import.
|
|
16
|
+
*
|
|
17
|
+
* The move is verbatim. `createModeRunners` destructures its context on its
|
|
18
|
+
* first lines and the bodies carry their original indentation, so a body line
|
|
19
|
+
* that differs from 46b427e is a bug in this commit, not a refactor: the diff is
|
|
20
|
+
* moves plus the alias wrapper. Notably NOT part of the wrapper: an adapter
|
|
21
|
+
* object, a re-stated signature per call, or a fourth context field (ADR 0027
|
|
22
|
+
* F1 — a runner needing one means the split is wrong).
|
|
23
|
+
*
|
|
24
|
+
* The factory's return properties ARE the interface the composition root
|
|
25
|
+
* consumes. Only `BatchGuardContext` is exported as a type: `execute` builds it
|
|
26
|
+
* and, until S3, `runBackgroundFanOut` takes it as a parameter.
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
import type { RuntimeContext } from "./runtime";
|
|
30
|
+
import type { AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
|
|
31
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
32
|
+
import { acquireSlot, releaseSlot, repaintStatus } from "./concurrency";
|
|
33
|
+
import { Intercom } from "./messaging";
|
|
34
|
+
import { runModePrologue } from "./mode-prologue";
|
|
35
|
+
import { modelIsAvailable, parseModelString } from "./model-availability";
|
|
36
|
+
import { shouldDropUnitTimeout, THINKING_UNIT_TIMEOUT_DROP_NOTICE, type UnitShape } from "./params";
|
|
37
|
+
import { formatValidationWarnings, rejection, resolveModeModel, validateUnitPrePass } from "./prelude";
|
|
38
|
+
import { buildSubagentPrompt, describePromptMode } from "./prompt";
|
|
39
|
+
import { runSubagent } from "./runner";
|
|
40
|
+
import { buildCrashResult, capOutput, sanitizeErrorMessage } from "./sanitize";
|
|
41
|
+
import { topologicalSort, validateGraph } from "./scheduler";
|
|
42
|
+
import { describeWorktreeState } from "./worktree-report";
|
|
43
|
+
import {
|
|
44
|
+
EMPTY_USAGE,
|
|
45
|
+
DEFAULT_PRIORITY,
|
|
46
|
+
PREVIOUS_OUTPUT_PLACEHOLDER,
|
|
47
|
+
GRAPH_OUTPUT_PLACEHOLDER_RE,
|
|
48
|
+
getFinalOutput,
|
|
49
|
+
isSubagentError,
|
|
50
|
+
countSubagentOutcomes,
|
|
51
|
+
classifyError,
|
|
52
|
+
type ChainDetails,
|
|
53
|
+
type DelegateTaskDetails,
|
|
54
|
+
type DelegateTaskParams,
|
|
55
|
+
type GraphDetails,
|
|
56
|
+
type GraphTask,
|
|
57
|
+
type GraphWave,
|
|
58
|
+
type ParallelDetails,
|
|
59
|
+
type Priority,
|
|
60
|
+
type SubagentResult,
|
|
61
|
+
type SubagentRun,
|
|
62
|
+
type SubTaskParams,
|
|
63
|
+
type SubTaskResult,
|
|
64
|
+
type ThinkingLevel,
|
|
65
|
+
type ToolResult,
|
|
66
|
+
} from "./types";
|
|
67
|
+
import { displayTaskName, mergeSubTaskParams, type MergedSubTaskParams } from "./unit-params";
|
|
68
|
+
import { createUnitRun, finalizeUnitRun, finalizeUnitRunCrash, makeLiveOnUpdate, pruneHistoryIfNeeded, registerLiveRun } from "./unit-run";
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Issue #434: what every unit of ONE dispatch needs from the dispatch-level
|
|
72
|
+
* pre-flight — threaded from `execute` into the four batch handlers, never
|
|
73
|
+
* re-derived at a unit site.
|
|
74
|
+
*
|
|
75
|
+
* - `processChecks` is the project opt-in `execute` already resolved from the
|
|
76
|
+
* dispatch's OWN cwd. Re-reading it per unit (from a relative
|
|
77
|
+
* `params.cwd`) judges a different directory than the dispatch did.
|
|
78
|
+
* - `dispatchDeclaredLevel` is the declared (uncapped) level the dispatch arm
|
|
79
|
+
* judged, so a unit that declares only a `timeout` is still judged against
|
|
80
|
+
* the thinking level it actually inherits.
|
|
81
|
+
* - `force` and `unitShape` are the dispatch-level facts the unit projection
|
|
82
|
+
* asks for; `params` is in scope at every unit site, so passing them here is
|
|
83
|
+
* what keeps the predicate's inputs in ONE place.
|
|
84
|
+
* - `noticeEmitted` is the one-shot flag on this shared object (all handlers
|
|
85
|
+
* received the same reference): the unit projection emits AT MOST one
|
|
86
|
+
* additional notice per dispatch, and a dispatch-arm notice starts it true
|
|
87
|
+
* (the drop still happens — the deadline is the hazard, the notice is the
|
|
88
|
+
* report). A flag on the shared context, not a boolean copy, because the
|
|
89
|
+
* first unit to reach its run is whichever won the slot, not the first in
|
|
90
|
+
* the array.
|
|
91
|
+
*/
|
|
92
|
+
export interface BatchGuardContext {
|
|
93
|
+
processChecks: boolean;
|
|
94
|
+
dispatchDeclaredLevel: ThinkingLevel | undefined;
|
|
95
|
+
/** The dispatch's `force` — the override applies to every unit of it. */
|
|
96
|
+
force: boolean | undefined;
|
|
97
|
+
unitShape: UnitShape;
|
|
98
|
+
/** True once any notice for this dispatch went out — mutated at the unit site. */
|
|
99
|
+
noticeEmitted: boolean;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* The five functions `createModeRunners` hands the composition root. Declared
|
|
104
|
+
* once as the module's public contract rather than inferred: the return
|
|
105
|
+
* statement is checked against it, so a runner whose signature drifts is a
|
|
106
|
+
* compile error here instead of a surprise at the `execute` call site. S3
|
|
107
|
+
* receives these as its function dependencies — the properties, not the module.
|
|
108
|
+
*/
|
|
109
|
+
interface ModeRunners {
|
|
110
|
+
runChainMode: (
|
|
111
|
+
params: DelegateTaskParams,
|
|
112
|
+
signal: AbortSignal | undefined,
|
|
113
|
+
onUpdate: AgentToolUpdateCallback<DelegateTaskDetails> | undefined,
|
|
114
|
+
ctx: ExtensionContext,
|
|
115
|
+
guard: BatchGuardContext,
|
|
116
|
+
) => Promise<ToolResult<SubagentResult | ChainDetails | undefined>>;
|
|
117
|
+
runParallelMode: (
|
|
118
|
+
params: DelegateTaskParams,
|
|
119
|
+
signal: AbortSignal | undefined,
|
|
120
|
+
onUpdate: AgentToolUpdateCallback<DelegateTaskDetails> | undefined,
|
|
121
|
+
ctx: ExtensionContext,
|
|
122
|
+
guard: BatchGuardContext,
|
|
123
|
+
) => Promise<ToolResult<SubagentResult | ParallelDetails | undefined>>;
|
|
124
|
+
runGraphMode: (
|
|
125
|
+
params: DelegateTaskParams,
|
|
126
|
+
signal: AbortSignal | undefined,
|
|
127
|
+
onUpdate: AgentToolUpdateCallback<DelegateTaskDetails> | undefined,
|
|
128
|
+
ctx: ExtensionContext,
|
|
129
|
+
guard: BatchGuardContext,
|
|
130
|
+
) => Promise<ToolResult<SubagentResult | GraphDetails | undefined>>;
|
|
131
|
+
resolveStepModel: (
|
|
132
|
+
ctx: ExtensionContext,
|
|
133
|
+
stepModel: string | undefined,
|
|
134
|
+
globalModel: { provider: string; id: string },
|
|
135
|
+
) => { provider: string; id: string };
|
|
136
|
+
applyUnitShapeGuard: (
|
|
137
|
+
ctx: ExtensionContext,
|
|
138
|
+
guard: BatchGuardContext,
|
|
139
|
+
step: SubTaskParams,
|
|
140
|
+
merged: MergedSubTaskParams,
|
|
141
|
+
) => void;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Build the three batch-mode runners over one runtime context (ADR 0027 D1).
|
|
146
|
+
*
|
|
147
|
+
* The destructure is the whole point of the wrapper: it re-creates, as locals,
|
|
148
|
+
* the three names the bodies read from their old closure, so every moved
|
|
149
|
+
* statement stays byte-identical. Nothing else is captured — `createModeRunners`
|
|
150
|
+
* allocates no state of its own, so two contexts produce two independent runner
|
|
151
|
+
* sets over two independent stores (the S2 boundary test pins exactly that).
|
|
152
|
+
*/
|
|
153
|
+
export function createModeRunners(rt: RuntimeContext): ModeRunners {
|
|
154
|
+
const { pi, log, state } = rt;
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Issue #381 (audit D4): the one graph-node → SubTaskParams mapping, shared by
|
|
158
|
+
* the graph pre-pass and the per-wave dispatch. GraphTask is a structural
|
|
159
|
+
* superset of SubTaskParams, so the node-only scheduling fields are dropped by
|
|
160
|
+
* destructuring instead of re-listing every per-subtask field — a field added
|
|
161
|
+
* to either type can no longer be silently forgotten at one of the two sites.
|
|
162
|
+
*/
|
|
163
|
+
function graphTaskToSubTaskParams(node: GraphTask): SubTaskParams {
|
|
164
|
+
const { id: _id, dependsOn: _dependsOn, ...subTask } = node;
|
|
165
|
+
return subTask;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Issue #376 (audit D3): the one `SubagentResult` → `SubTaskResult` field
|
|
170
|
+
* mapping, shared by every dispatch mode (chain, parallel, graph). The ten
|
|
171
|
+
* assignments plus the error classification were copied per mode, so a field
|
|
172
|
+
* added to `SubTaskResult` could be silently forgotten at one of the sites —
|
|
173
|
+
* and `errorCategory` could be passed through unclassified. Callers add their
|
|
174
|
+
* own mode-specific fields (`step`/`task`/`label`) around this mapping.
|
|
175
|
+
*
|
|
176
|
+
* Issue #474: the failure-only `worktreeState` rides the same mapping, probed at
|
|
177
|
+
* `cwd` — the unit's OWN resolved cwd, which the caller has and this function
|
|
178
|
+
* cannot guess. It is a subprocess read, so it runs only for a FAILED unit
|
|
179
|
+
* (successful runs pay nothing and carry no block).
|
|
180
|
+
*/
|
|
181
|
+
function toSubTaskResult(
|
|
182
|
+
result: SubagentResult,
|
|
183
|
+
cwd: string,
|
|
184
|
+
): Pick<
|
|
185
|
+
SubTaskResult,
|
|
186
|
+
| "exitCode"
|
|
187
|
+
| "messages"
|
|
188
|
+
| "stderr"
|
|
189
|
+
| "usage"
|
|
190
|
+
| "model"
|
|
191
|
+
| "stopReason"
|
|
192
|
+
| "errorMessage"
|
|
193
|
+
| "errorCategory"
|
|
194
|
+
| "gitBranch"
|
|
195
|
+
| "gitDiff"
|
|
196
|
+
| "worktreeState"
|
|
197
|
+
> {
|
|
198
|
+
return {
|
|
199
|
+
exitCode: result.exitCode,
|
|
200
|
+
messages: result.messages,
|
|
201
|
+
stderr: result.stderr,
|
|
202
|
+
usage: result.usage,
|
|
203
|
+
model: result.model,
|
|
204
|
+
stopReason: result.stopReason,
|
|
205
|
+
errorMessage: result.errorMessage,
|
|
206
|
+
// The classification path is part of the mapping: every mode derives the
|
|
207
|
+
// category from the raw result, never from the runner's own field.
|
|
208
|
+
errorCategory: classifyError(result),
|
|
209
|
+
gitBranch: result.gitBranch,
|
|
210
|
+
gitDiff: result.gitDiff,
|
|
211
|
+
...(isSubagentError(result) ? { worktreeState: describeWorktreeState(cwd) } : {}),
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* Issue #474: the `SubTaskResult` an allSettled REJECTION earns.
|
|
217
|
+
*
|
|
218
|
+
* Before this, a unit whose run threw (and whose crash finalizer rethrew) was
|
|
219
|
+
* logged and then silently dropped from the aggregate; every other unit's row
|
|
220
|
+
* survived, so the conductor read a shorter list as "nothing failed there".
|
|
221
|
+
* The synthesized row states the failure, carries the unit's own worktree block
|
|
222
|
+
* and classifies through the SAME `classifyError` as a real result (a subagent
|
|
223
|
+
* with this shape classifies identically — exitCode 1, the sanitized reason).
|
|
224
|
+
*/
|
|
225
|
+
function rejectedUnitResult(
|
|
226
|
+
task: string,
|
|
227
|
+
label: string | undefined,
|
|
228
|
+
cwd: string,
|
|
229
|
+
reason: unknown,
|
|
230
|
+
): SubTaskResult {
|
|
231
|
+
const entry: SubTaskResult = {
|
|
232
|
+
task,
|
|
233
|
+
label,
|
|
234
|
+
exitCode: 1,
|
|
235
|
+
messages: [],
|
|
236
|
+
// The raw reason persists for post-mortems, like a real unit's stderr;
|
|
237
|
+
// `errorMessage` is the sanitized half the conductor reads.
|
|
238
|
+
stderr: String(reason),
|
|
239
|
+
usage: { ...EMPTY_USAGE },
|
|
240
|
+
errorMessage: sanitizeErrorMessage(
|
|
241
|
+
reason instanceof Error ? reason.message || String(reason) : String(reason),
|
|
242
|
+
cwd,
|
|
243
|
+
),
|
|
244
|
+
worktreeState: describeWorktreeState(cwd),
|
|
245
|
+
};
|
|
246
|
+
entry.errorCategory = classifyError(entry);
|
|
247
|
+
return entry;
|
|
248
|
+
}
|
|
249
|
+
// C3: Resolve a step's model override (step.model > global resolved model).
|
|
250
|
+
// Parsed + availability-checked; falls back to the global model on failure.
|
|
251
|
+
function resolveStepModel(
|
|
252
|
+
ctx: ExtensionContext,
|
|
253
|
+
stepModel: string | undefined,
|
|
254
|
+
globalModel: { provider: string; id: string },
|
|
255
|
+
): { provider: string; id: string } {
|
|
256
|
+
if (stepModel) {
|
|
257
|
+
const parsed = parseModelString(stepModel);
|
|
258
|
+
if (!parsed) {
|
|
259
|
+
log.warn("Step model is not a valid provider/model-id, falling back to global model", { model: stepModel });
|
|
260
|
+
} else if (modelIsAvailable(ctx.modelRegistry, parsed)) {
|
|
261
|
+
log.info("Using step model override", { model: stepModel });
|
|
262
|
+
return parsed;
|
|
263
|
+
} else {
|
|
264
|
+
log.warn("Step model unavailable, falling back to global model", { model: stepModel });
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
return globalModel;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* Issue #434: apply the dispatch pre-flight's UNIT projection to one merged
|
|
272
|
+
* unit — `merged.timeout = undefined` before the unit's run record exists, so
|
|
273
|
+
* the retry snapshot records an absent deadline (ADR 0009) and no
|
|
274
|
+
* `createUnitRun`/`startBackgroundAgent` ever sees it. The decision itself
|
|
275
|
+
* lives in `shouldDropUnitTimeout` (params.ts): re-stating the condition here
|
|
276
|
+
* is the drift #361's resolver extraction exists to prevent.
|
|
277
|
+
*
|
|
278
|
+
* EVERY input is threaded (`ctx`'s guard) or the unit's own declaration
|
|
279
|
+
* (`step`) — the unit site reads no config, no manifest and no cap of its
|
|
280
|
+
* own. `merged.thinkingLevel` is deliberately not an input: it is the capped
|
|
281
|
+
* level, and the default cap would silently disable the guard.
|
|
282
|
+
*
|
|
283
|
+
* Emission discipline (issue #434 [c2]): called from the unit's dispatch
|
|
284
|
+
* point, AFTER its slot is held and immediately BEFORE its run — a pre-pass
|
|
285
|
+
* would announce a unit that a cancellation can still skip. At most ONE
|
|
286
|
+
* notice per dispatch: a dispatch-arm notice suppresses this one entirely
|
|
287
|
+
* (the drop still happens — the deadline is the hazard, the notice is the
|
|
288
|
+
* report), and the first unit to reach its run claims it.
|
|
289
|
+
*/
|
|
290
|
+
function applyUnitShapeGuard(
|
|
291
|
+
ctx: ExtensionContext,
|
|
292
|
+
guard: BatchGuardContext,
|
|
293
|
+
step: SubTaskParams,
|
|
294
|
+
merged: MergedSubTaskParams,
|
|
295
|
+
): void {
|
|
296
|
+
const shouldDrop = shouldDropUnitTimeout({
|
|
297
|
+
processChecks: guard.processChecks,
|
|
298
|
+
force: guard.force,
|
|
299
|
+
dispatchDeclaredLevel: guard.dispatchDeclaredLevel,
|
|
300
|
+
unitShape: guard.unitShape,
|
|
301
|
+
declaredLevel: step.thinkingLevel as ThinkingLevel | "" | undefined,
|
|
302
|
+
declaredTimeout: step.timeout,
|
|
303
|
+
mergedTimeout: merged.timeout,
|
|
304
|
+
});
|
|
305
|
+
if (!shouldDrop) return;
|
|
306
|
+
|
|
307
|
+
const previousTimeout = merged.timeout;
|
|
308
|
+
const unit = displayTaskName(merged);
|
|
309
|
+
const effectiveLevel = step.thinkingLevel || guard.dispatchDeclaredLevel;
|
|
310
|
+
// The drop precedes `createUnitRun`: that is what makes the recorded
|
|
311
|
+
// `originalParams.timeout` absent, so a retry re-derives instead of
|
|
312
|
+
// restoring the cap (ADR 0009). A drop after it passes every
|
|
313
|
+
// runner-argument assertion and still restores the deadline on retry.
|
|
314
|
+
merged.timeout = undefined;
|
|
315
|
+
log.info("Dispatch pre-flight: unit-declared timeout dropped, unit stays foreground", {
|
|
316
|
+
unit,
|
|
317
|
+
thinkingLevel: effectiveLevel,
|
|
318
|
+
previousTimeout,
|
|
319
|
+
});
|
|
320
|
+
if (!guard.noticeEmitted) {
|
|
321
|
+
guard.noticeEmitted = true;
|
|
322
|
+
pi.sendMessage({
|
|
323
|
+
customType: "delegate-notification",
|
|
324
|
+
content: THINKING_UNIT_TIMEOUT_DROP_NOTICE,
|
|
325
|
+
display: true,
|
|
326
|
+
details: {
|
|
327
|
+
unit,
|
|
328
|
+
thinkingLevel: effectiveLevel,
|
|
329
|
+
// The ACTUAL ms value, mirroring the dispatch drop arm: the
|
|
330
|
+
// friction log needs the number to tell a budget cap from a clock.
|
|
331
|
+
previousTimeout,
|
|
332
|
+
},
|
|
333
|
+
}, { deliverAs: "followUp" });
|
|
334
|
+
ctx.ui.notify(THINKING_UNIT_TIMEOUT_DROP_NOTICE, "warning");
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
// -------------------------------------------------------------------
|
|
339
|
+
// P1: runChainMode
|
|
340
|
+
// -------------------------------------------------------------------
|
|
341
|
+
|
|
342
|
+
async function runChainMode(
|
|
343
|
+
params: DelegateTaskParams,
|
|
344
|
+
signal: AbortSignal | undefined,
|
|
345
|
+
onUpdate: AgentToolUpdateCallback<DelegateTaskDetails> | undefined,
|
|
346
|
+
ctx: ExtensionContext,
|
|
347
|
+
guard: BatchGuardContext,
|
|
348
|
+
): Promise<ToolResult<SubagentResult | ChainDetails | undefined>> {
|
|
349
|
+
const chainSteps: SubTaskParams[] = params.chain!;
|
|
350
|
+
|
|
351
|
+
// Issue #133: dispatch-start timestamp — the aggregate run entry's
|
|
352
|
+
// startedAt (captured once, at mode entry, not at completion).
|
|
353
|
+
const chainModeStartedAt = new Date().toISOString();
|
|
354
|
+
|
|
355
|
+
// Mode prologue (issue #379): cost → depth → resolve → targets →
|
|
356
|
+
// preflight → H1, the sequence every batch mode shares (mode-prologue.ts).
|
|
357
|
+
// Chain's per-mode inputs are only the label and the unit count; H1 here
|
|
358
|
+
// validates the MODE-level params (top-level tasks are empty, so only the
|
|
359
|
+
// hard outputFile-vs-write conflict applies), while every step's own
|
|
360
|
+
// cwd/outputFile/tools belong to the per-step pass below (issue #222).
|
|
361
|
+
const pro = runModePrologue({
|
|
362
|
+
params,
|
|
363
|
+
state,
|
|
364
|
+
ctx,
|
|
365
|
+
log,
|
|
366
|
+
label: "Chain",
|
|
367
|
+
units: chainSteps.length,
|
|
368
|
+
});
|
|
369
|
+
if (!pro.ok) return pro.error;
|
|
370
|
+
const { globalParams, resolvedCwd, currentDepth } = pro;
|
|
371
|
+
|
|
372
|
+
// Per-step pre-pass (issue #222): resolve + validate EVERY step before
|
|
373
|
+
// any spawn, so a single bad step rejects the chain with nothing
|
|
374
|
+
// started — the same all-before-any-spawn semantics the background
|
|
375
|
+
// fan-out and the parallel `tasks` shape use. Chain steps are fully
|
|
376
|
+
// known up front and a step's cwd/outputFile never depend on a previous
|
|
377
|
+
// step's output (only its TASK text consumes {previous}), so the pass
|
|
378
|
+
// can run up front — and must, because discovering step 5's bad cwd
|
|
379
|
+
// after four steps already ran would waste their whole budget.
|
|
380
|
+
const stepPass = validateUnitPrePass({
|
|
381
|
+
units: chainSteps,
|
|
382
|
+
label: "Chain",
|
|
383
|
+
gitMode: globalParams.resolvedGitMode,
|
|
384
|
+
ctx,
|
|
385
|
+
log,
|
|
386
|
+
force: params.force as boolean | undefined,
|
|
387
|
+
noJev: params.noJev,
|
|
388
|
+
// Issue #443: the DECLARED per-step level (the merged one is resolved).
|
|
389
|
+
declaredThinkingLevel: (step) => step.thinkingLevel,
|
|
390
|
+
merge: (step) =>
|
|
391
|
+
mergeSubTaskParams(globalParams, step, state.config.maxThinkingLevel),
|
|
392
|
+
describe: (_step, merged, i) => ({
|
|
393
|
+
prefix: `Step ${i + 1} ("${displayTaskName(merged)}")`,
|
|
394
|
+
logContext: { step: i + 1 },
|
|
395
|
+
}),
|
|
396
|
+
});
|
|
397
|
+
if (!stepPass.ok) return stepPass.error;
|
|
398
|
+
const stepCwds = stepPass.units.map((u) => u.cwd);
|
|
399
|
+
const stepWarnings = stepPass.warnings;
|
|
400
|
+
|
|
401
|
+
// Mode tail (issue #379): resolve the model (preset + per-call override,
|
|
402
|
+
// auto-route included in `resolvedPreset`), reject an empty resolution,
|
|
403
|
+
// then the circuit breaker. It runs AFTER the per-step pass — IN8 keeps
|
|
404
|
+
// a bad step's rejection ahead of an unconfigured model.
|
|
405
|
+
const tail = resolveModeModel({
|
|
406
|
+
state,
|
|
407
|
+
ctx,
|
|
408
|
+
log,
|
|
409
|
+
preset: globalParams.resolvedPreset,
|
|
410
|
+
perCallModel: params.model,
|
|
411
|
+
});
|
|
412
|
+
if (!tail.ok) return tail.error;
|
|
413
|
+
const subagentModel = tail.model;
|
|
414
|
+
const modelStr = tail.modelStr;
|
|
415
|
+
|
|
416
|
+
// Resolve priority (issue #114: no config knob — the call-level default)
|
|
417
|
+
const chainPriority: Priority = (
|
|
418
|
+
params.priority && ["critical", "high", "normal", "low"].includes(params.priority as string)
|
|
419
|
+
? (params.priority as Priority)
|
|
420
|
+
: DEFAULT_PRIORITY
|
|
421
|
+
);
|
|
422
|
+
|
|
423
|
+
// Acquire concurrency slot for the chain
|
|
424
|
+
const acquired = await acquireSlot(state, ctx, signal, chainPriority);
|
|
425
|
+
if (!acquired) {
|
|
426
|
+
return {
|
|
427
|
+
content: [
|
|
428
|
+
{
|
|
429
|
+
type: "text" as const,
|
|
430
|
+
text: "Chain cancelled while waiting for concurrency slot.",
|
|
431
|
+
},
|
|
432
|
+
],
|
|
433
|
+
details: undefined,
|
|
434
|
+
isError: true,
|
|
435
|
+
};
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
let chainSuccess = false;
|
|
439
|
+
try {
|
|
440
|
+
const basePrompt = ctx.getSystemPrompt();
|
|
441
|
+
let previousOutput = "";
|
|
442
|
+
const chainResults: SubTaskResult[] = [];
|
|
443
|
+
let stoppedEarly = false;
|
|
444
|
+
|
|
445
|
+
for (let i = 0; i < chainSteps.length; i++) {
|
|
446
|
+
const step = chainSteps[i];
|
|
447
|
+
|
|
448
|
+
// Merge params for this step
|
|
449
|
+
const merged = mergeSubTaskParams(globalParams, step, state.config.maxThinkingLevel);
|
|
450
|
+
|
|
451
|
+
// Issue #434: the unit projection of the dispatch pre-flight (#412/#431).
|
|
452
|
+
// A chain holds its ONE mode-level slot across the whole loop, so the
|
|
453
|
+
// slot is already held here; the drop lands BEFORE `createUnitRun`
|
|
454
|
+
// below, or the retry snapshot would restore the deadline (ADR 0009).
|
|
455
|
+
applyUnitShapeGuard(ctx, guard, step, merged);
|
|
456
|
+
|
|
457
|
+
// C3: Resolve this step's model override (step.model > global resolved model)
|
|
458
|
+
const stepModel = resolveStepModel(ctx, merged.model, subagentModel);
|
|
459
|
+
|
|
460
|
+
// Substitute {previous} placeholder
|
|
461
|
+
merged.task = merged.task.replaceAll(
|
|
462
|
+
PREVIOUS_OUTPUT_PLACEHOLDER,
|
|
463
|
+
previousOutput,
|
|
464
|
+
);
|
|
465
|
+
|
|
466
|
+
// Build system prompt
|
|
467
|
+
const subagentPrompt = buildSubagentPrompt(
|
|
468
|
+
basePrompt,
|
|
469
|
+
merged.inheritSP,
|
|
470
|
+
merged.customSP,
|
|
471
|
+
merged.outputFile,
|
|
472
|
+
merged.toolOptions?.tools,
|
|
473
|
+
globalParams.resolvedPreset?.promptGuideline,
|
|
474
|
+
);
|
|
475
|
+
|
|
476
|
+
// Create SubTaskResult for this step
|
|
477
|
+
const subTaskResult: SubTaskResult = {
|
|
478
|
+
step: i + 1,
|
|
479
|
+
task: merged.task,
|
|
480
|
+
label: merged.label,
|
|
481
|
+
exitCode: 0,
|
|
482
|
+
messages: [],
|
|
483
|
+
stderr: "",
|
|
484
|
+
usage: { ...EMPTY_USAGE },
|
|
485
|
+
};
|
|
486
|
+
|
|
487
|
+
// Issue #133: status-bar breakdown — the mode context shows the
|
|
488
|
+
// current step while the dispatch is in flight.
|
|
489
|
+
state.modeContext = {
|
|
490
|
+
kind: "chain",
|
|
491
|
+
step: i + 1,
|
|
492
|
+
totalSteps: chainSteps.length,
|
|
493
|
+
};
|
|
494
|
+
// Issue #133: render the breakdown — the chain holds ONE mode-level
|
|
495
|
+
// slot (acquired at mode start, released in the finally), so no
|
|
496
|
+
// per-step acquire/release calls repaintStatus while the
|
|
497
|
+
// mode context is set. Call it directly here (mirrors how the
|
|
498
|
+
// graph path's per-node slot operations trigger the render).
|
|
499
|
+
repaintStatus(state, ctx);
|
|
500
|
+
|
|
501
|
+
// Emit initial progress for this step
|
|
502
|
+
const modeInfo = describePromptMode(
|
|
503
|
+
merged.inheritSP,
|
|
504
|
+
Boolean(merged.customSP),
|
|
505
|
+
);
|
|
506
|
+
onUpdate?.({
|
|
507
|
+
content: [
|
|
508
|
+
{
|
|
509
|
+
type: "text" as const,
|
|
510
|
+
text: `Chain step ${i + 1}/${chainSteps.length} (${modeInfo})...`,
|
|
511
|
+
},
|
|
512
|
+
],
|
|
513
|
+
details: {
|
|
514
|
+
messages: [],
|
|
515
|
+
usage: { ...EMPTY_USAGE },
|
|
516
|
+
exitCode: -1,
|
|
517
|
+
stderr: "",
|
|
518
|
+
},
|
|
519
|
+
});
|
|
520
|
+
|
|
521
|
+
// Issue #133: per-step run entry — mirrors runParallelMode's
|
|
522
|
+
// per-unit block (issue #119): the runId doubles as the live id,
|
|
523
|
+
// so sweepStaleLiveSubagents finds a 'running' record for every
|
|
524
|
+
// foreground live entry (the #130 invariant gap that swept
|
|
525
|
+
// graph/chain entries immediately).
|
|
526
|
+
const { runId, run } = createUnitRun(merged, stepModel, chainPriority, globalParams.resolvedPreset?.name, state.config.recovery);
|
|
527
|
+
state.persistRun(pi, run, "unit");
|
|
528
|
+
|
|
529
|
+
// R2: Prune old run entries if history exceeds limit
|
|
530
|
+
pruneHistoryIfNeeded(state, ctx, log);
|
|
531
|
+
|
|
532
|
+
// Register for live monitor — chain steps now appear in the
|
|
533
|
+
// drill-in under the runId (issue #133 single identity, mirrors
|
|
534
|
+
// parallel mode's issue #119 registration). Fall back to
|
|
535
|
+
// "Step N" when the step carries no label (liveRowName would
|
|
536
|
+
// otherwise show the truncated task).
|
|
537
|
+
registerLiveRun(state, run, ctx, merged.label ?? `Step ${i + 1}`, merged.timeout);
|
|
538
|
+
|
|
539
|
+
// Wrap onUpdate so the live monitor sees per-step progress
|
|
540
|
+
// (mirrors parallel mode's taskOnUpdate).
|
|
541
|
+
const stepOnUpdate = makeLiveOnUpdate(state, runId, onUpdate);
|
|
542
|
+
|
|
543
|
+
// Run the subagent for this step — crash-protected (issue #130,
|
|
544
|
+
// #133 R1/C1 discipline): a throw must finalize the run entry as
|
|
545
|
+
// failed AND release the live entry, or the persisted record stays
|
|
546
|
+
// 'running' forever. finalizeLiveSubagent is idempotent; the
|
|
547
|
+
// rethrow is handled by the mode's existing outer catch (chain is
|
|
548
|
+
// sequential — no sibling wave to cancel).
|
|
549
|
+
let result: SubagentResult;
|
|
550
|
+
try {
|
|
551
|
+
result = await runSubagent(
|
|
552
|
+
// Issue #222: this step's OWN validated cwd (the pre-pass
|
|
553
|
+
// resolved it against ctx.cwd) — the mode-level
|
|
554
|
+
// resolvedCwd is the fallback for steps that declare none.
|
|
555
|
+
stepCwds[i],
|
|
556
|
+
subagentPrompt,
|
|
557
|
+
stepModel,
|
|
558
|
+
merged.thinkingLevel,
|
|
559
|
+
merged.task,
|
|
560
|
+
signal,
|
|
561
|
+
stepOnUpdate,
|
|
562
|
+
merged.toolOptions,
|
|
563
|
+
merged.timeout,
|
|
564
|
+
getFinalOutput,
|
|
565
|
+
log,
|
|
566
|
+
currentDepth + 1,
|
|
567
|
+
undefined, // intercom
|
|
568
|
+
undefined, // subagentId
|
|
569
|
+
run.childMarker,
|
|
570
|
+
// Issue #511 (U2): the run record's id names the scratch directory.
|
|
571
|
+
run.id,
|
|
572
|
+
);
|
|
573
|
+
} catch (err) {
|
|
574
|
+
// Issue #133 (mirrors the #119 R1/C1 discipline): finalize the
|
|
575
|
+
// run entry as failed — crashOutput comes from the live entry's
|
|
576
|
+
// last streamed output (the crash result itself has no
|
|
577
|
+
// messages), and errorCategory is classified onto originalParams.
|
|
578
|
+
finalizeUnitRunCrash(state, pi, run, err, "Chain step", stepCwds[i], log, {
|
|
579
|
+
step: i + 1,
|
|
580
|
+
});
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
// Issue #133: finalize the per-step run entry — status, duration,
|
|
584
|
+
// cost, tokens and sanitized output land on the entry (mirrors
|
|
585
|
+
// parallel's issue #119 finalize; result carries the SubagentResult
|
|
586
|
+
// shape finalizeRunRecord expects, errorCategory included).
|
|
587
|
+
finalizeUnitRun(state, pi, ctx, run, result, log);
|
|
588
|
+
|
|
589
|
+
// Fill SubTaskResult (one shared field mapping — issue #376/D3).
|
|
590
|
+
// Issue #474: the step's OWN cwd, so a failed step reports the tree
|
|
591
|
+
// it ran in rather than the dispatch's.
|
|
592
|
+
Object.assign(subTaskResult, toSubTaskResult(result, stepCwds[i]));
|
|
593
|
+
|
|
594
|
+
chainResults.push(subTaskResult);
|
|
595
|
+
|
|
596
|
+
// Emit update with current ChainDetails
|
|
597
|
+
const completedSteps = chainResults.length;
|
|
598
|
+
const currentDetails: ChainDetails = {
|
|
599
|
+
mode: "chain",
|
|
600
|
+
results: chainResults,
|
|
601
|
+
totalInput: chainResults.reduce(
|
|
602
|
+
(s, r) => s + r.usage.input,
|
|
603
|
+
0,
|
|
604
|
+
),
|
|
605
|
+
totalOutput: chainResults.reduce(
|
|
606
|
+
(s, r) => s + r.usage.output,
|
|
607
|
+
0,
|
|
608
|
+
),
|
|
609
|
+
totalCost: chainResults.reduce(
|
|
610
|
+
(s, r) => s + r.usage.cost,
|
|
611
|
+
0,
|
|
612
|
+
),
|
|
613
|
+
totalTurns: chainResults.reduce(
|
|
614
|
+
(s, r) => s + r.usage.turns,
|
|
615
|
+
0,
|
|
616
|
+
),
|
|
617
|
+
completedSteps,
|
|
618
|
+
totalSteps: chainSteps.length,
|
|
619
|
+
stoppedEarly: false,
|
|
620
|
+
};
|
|
621
|
+
|
|
622
|
+
const stepFailed = isSubagentError(result);
|
|
623
|
+
onUpdate?.({
|
|
624
|
+
content: [
|
|
625
|
+
{
|
|
626
|
+
type: "text" as const,
|
|
627
|
+
text: `Chain step ${completedSteps}/${chainSteps.length} completed${stepFailed ? " (failed)" : ""}`,
|
|
628
|
+
},
|
|
629
|
+
],
|
|
630
|
+
details: currentDetails,
|
|
631
|
+
});
|
|
632
|
+
|
|
633
|
+
// Stop on failure (unless this was the last step)
|
|
634
|
+
if (stepFailed && i < chainSteps.length - 1) {
|
|
635
|
+
stoppedEarly = true;
|
|
636
|
+
break;
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
// Set previous output for the next step
|
|
640
|
+
previousOutput = getFinalOutput(result.messages);
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
chainSuccess = countSubagentOutcomes(chainResults).failed === 0;
|
|
644
|
+
|
|
645
|
+
// Compute aggregated totals
|
|
646
|
+
const totalInput = chainResults.reduce(
|
|
647
|
+
(s, r) => s + r.usage.input,
|
|
648
|
+
0,
|
|
649
|
+
);
|
|
650
|
+
const totalOutput = chainResults.reduce(
|
|
651
|
+
(s, r) => s + r.usage.output,
|
|
652
|
+
0,
|
|
653
|
+
);
|
|
654
|
+
const totalCost = chainResults.reduce(
|
|
655
|
+
(s, r) => s + r.usage.cost,
|
|
656
|
+
0,
|
|
657
|
+
);
|
|
658
|
+
const totalTurns = chainResults.reduce(
|
|
659
|
+
(s, r) => s + r.usage.turns,
|
|
660
|
+
0,
|
|
661
|
+
);
|
|
662
|
+
|
|
663
|
+
const chainDetails: ChainDetails = {
|
|
664
|
+
mode: "chain",
|
|
665
|
+
results: chainResults,
|
|
666
|
+
totalInput,
|
|
667
|
+
totalOutput,
|
|
668
|
+
totalCost,
|
|
669
|
+
totalTurns,
|
|
670
|
+
completedSteps: chainResults.length,
|
|
671
|
+
totalSteps: chainSteps.length,
|
|
672
|
+
stoppedEarly,
|
|
673
|
+
};
|
|
674
|
+
|
|
675
|
+
// R1: Record circuit breaker outcome
|
|
676
|
+
if (chainSuccess) {
|
|
677
|
+
state.recordSuccess();
|
|
678
|
+
} else {
|
|
679
|
+
state.recordFailure();
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
log.info("Chain completed", {
|
|
683
|
+
totalSteps: chainSteps.length,
|
|
684
|
+
completedSteps: chainResults.length,
|
|
685
|
+
stoppedEarly,
|
|
686
|
+
totalInput,
|
|
687
|
+
totalOutput,
|
|
688
|
+
totalCost,
|
|
689
|
+
});
|
|
690
|
+
|
|
691
|
+
// Issue #133: one aggregate run entry per chain dispatch — fresh id,
|
|
692
|
+
// persisted ONCE as done (no live entry: the drill-in shows the
|
|
693
|
+
// per-step entries while running; the aggregate is a post-hoc audit
|
|
694
|
+
// summary). Fields come from the dispatch-level resolved values and
|
|
695
|
+
// the aggregate totals; startedAt is the mode-entry timestamp.
|
|
696
|
+
const chainAggregateRun: SubagentRun = {
|
|
697
|
+
id: crypto.randomUUID(),
|
|
698
|
+
task: `Chain dispatch: ${chainSteps.length} steps`,
|
|
699
|
+
label: globalParams.label ?? "chain",
|
|
700
|
+
// Issue #133: persist the ACTUAL outcome — "failed" when any step
|
|
701
|
+
// failed (chainSuccess === false), "done" otherwise.
|
|
702
|
+
status: chainSuccess ? "done" : "failed",
|
|
703
|
+
model: `${subagentModel.provider}/${subagentModel.id}`,
|
|
704
|
+
thinkingLevel: globalParams.thinkingLevel,
|
|
705
|
+
priority: chainPriority,
|
|
706
|
+
startedAt: chainModeStartedAt,
|
|
707
|
+
finishedAt: new Date().toISOString(),
|
|
708
|
+
durationMs: Date.now() - new Date(chainModeStartedAt).getTime(),
|
|
709
|
+
cost: totalCost,
|
|
710
|
+
tokensIn: totalInput,
|
|
711
|
+
tokensOut: totalOutput,
|
|
712
|
+
outputSummary: capOutput(JSON.stringify(chainDetails, null, 2)),
|
|
713
|
+
};
|
|
714
|
+
state.persistRun(pi, chainAggregateRun);
|
|
715
|
+
|
|
716
|
+
// Per-step validation warnings ride the result, prefixed with their
|
|
717
|
+
// step (issue #222), after the JSON payload — empty renders nothing so
|
|
718
|
+
// warning-free results stay byte-identical.
|
|
719
|
+
return {
|
|
720
|
+
content: [
|
|
721
|
+
{
|
|
722
|
+
type: "text" as const,
|
|
723
|
+
text: JSON.stringify(chainDetails, null, 2) + formatValidationWarnings(stepWarnings),
|
|
724
|
+
},
|
|
725
|
+
],
|
|
726
|
+
details: chainDetails,
|
|
727
|
+
};
|
|
728
|
+
} catch (err) {
|
|
729
|
+
// F7 (issue #65): err.message may embed absolute paths — sanitize
|
|
730
|
+
// BEFORE it reaches the main agent's context (tool result content +
|
|
731
|
+
// details.errorMessage). resolvedCwd is the validated subagent cwd.
|
|
732
|
+
const result = buildCrashResult("Chain mode", err, resolvedCwd);
|
|
733
|
+
log.error("Chain mode crashed", { error: result.details.errorMessage });
|
|
734
|
+
return result;
|
|
735
|
+
} finally {
|
|
736
|
+
// Issue #133: clear the status-bar mode breakdown — the dispatch is
|
|
737
|
+
// over (success or outer-catch crash).
|
|
738
|
+
state.modeContext = undefined;
|
|
739
|
+
releaseSlot(state, chainSuccess, ctx);
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
// -------------------------------------------------------------------
|
|
744
|
+
// P2: runParallelMode
|
|
745
|
+
// -------------------------------------------------------------------
|
|
746
|
+
|
|
747
|
+
async function runParallelMode(
|
|
748
|
+
params: DelegateTaskParams,
|
|
749
|
+
signal: AbortSignal | undefined,
|
|
750
|
+
onUpdate: AgentToolUpdateCallback<DelegateTaskDetails> | undefined,
|
|
751
|
+
ctx: ExtensionContext,
|
|
752
|
+
guard: BatchGuardContext,
|
|
753
|
+
): Promise<ToolResult<SubagentResult | ParallelDetails | undefined>> {
|
|
754
|
+
const taskList: SubTaskParams[] = params.tasks!;
|
|
755
|
+
|
|
756
|
+
// Mode prologue (issue #379): cost → depth → resolve → targets →
|
|
757
|
+
// preflight → H1, the sequence every batch mode shares (mode-prologue.ts).
|
|
758
|
+
// Parallel's per-mode inputs are only the label and the unit count; H1
|
|
759
|
+
// validates the MODE-level params (top-level tasks are empty, so only the
|
|
760
|
+
// hard outputFile-vs-write conflict applies — issue #34), while every
|
|
761
|
+
// task's own cwd/outputFile/tools belong to the per-task pass below.
|
|
762
|
+
const pro = runModePrologue({
|
|
763
|
+
params,
|
|
764
|
+
state,
|
|
765
|
+
ctx,
|
|
766
|
+
log,
|
|
767
|
+
label: "Parallel",
|
|
768
|
+
units: taskList.length,
|
|
769
|
+
});
|
|
770
|
+
if (!pro.ok) return pro.error;
|
|
771
|
+
const { globalParams, resolvedCwd, currentDepth } = pro;
|
|
772
|
+
|
|
773
|
+
// Per-task pre-pass (issue #220, extended by #222): validate EVERY task
|
|
774
|
+
// before any spawn, so a single bad task rejects the batch with nothing
|
|
775
|
+
// started (`force` degrades capability errors to warnings) — the same
|
|
776
|
+
// semantics runBackgroundFanOut applies. Each task's OWN cwd is resolved
|
|
777
|
+
// and validated here (with its outputFile, resolved against that cwd) and
|
|
778
|
+
// the resolved value is what that task spawns in — issue #222 closed the
|
|
779
|
+
// gap where a per-task `cwd` was merged but the spawn still used the
|
|
780
|
+
// mode-level cwd. Per-task warnings are prefixed with their unit and
|
|
781
|
+
// collected here to ride the final result. The mode-entry validation
|
|
782
|
+
// above stays for the mode-level outputFile (issue #34).
|
|
783
|
+
const taskPass = validateUnitPrePass({
|
|
784
|
+
units: taskList,
|
|
785
|
+
label: "Parallel",
|
|
786
|
+
gitMode: globalParams.resolvedGitMode,
|
|
787
|
+
ctx,
|
|
788
|
+
log,
|
|
789
|
+
force: params.force as boolean | undefined,
|
|
790
|
+
noJev: params.noJev,
|
|
791
|
+
// Issue #443: the DECLARED per-task level (the merged one is resolved).
|
|
792
|
+
declaredThinkingLevel: (task) => task.thinkingLevel,
|
|
793
|
+
merge: (task) =>
|
|
794
|
+
mergeSubTaskParams(globalParams, task, state.config.maxThinkingLevel),
|
|
795
|
+
describe: (_task, merged, i) => ({
|
|
796
|
+
prefix: `Task ${i + 1} ("${displayTaskName(merged)}")`,
|
|
797
|
+
logContext: { task: i + 1 },
|
|
798
|
+
}),
|
|
799
|
+
});
|
|
800
|
+
if (!taskPass.ok) return taskPass.error;
|
|
801
|
+
// Parallel index → the task's own validated cwd (issue #222).
|
|
802
|
+
const taskCwds = taskPass.units.map((u) => u.cwd);
|
|
803
|
+
const taskWarnings = taskPass.warnings;
|
|
804
|
+
|
|
805
|
+
// Mode tail (issue #379): model resolution (preset + per-call override,
|
|
806
|
+
// auto-route included in `resolvedPreset`), the empty-model rejection and
|
|
807
|
+
// the circuit check. Runs AFTER the per-task pass (IN8).
|
|
808
|
+
const tail = resolveModeModel({
|
|
809
|
+
state,
|
|
810
|
+
ctx,
|
|
811
|
+
log,
|
|
812
|
+
preset: globalParams.resolvedPreset,
|
|
813
|
+
perCallModel: params.model,
|
|
814
|
+
});
|
|
815
|
+
if (!tail.ok) return tail.error;
|
|
816
|
+
const subagentModel = tail.model;
|
|
817
|
+
const modelStr = tail.modelStr;
|
|
818
|
+
|
|
819
|
+
// Build base prompt once
|
|
820
|
+
const basePrompt = ctx.getSystemPrompt();
|
|
821
|
+
|
|
822
|
+
// Results array — final positions match taskList indices
|
|
823
|
+
const results: SubTaskResult[] = [];
|
|
824
|
+
let completedCount = 0;
|
|
825
|
+
|
|
826
|
+
// E10: Intercom for subagent-to-subagent messaging
|
|
827
|
+
const intercom = new Intercom();
|
|
828
|
+
|
|
829
|
+
// Individual task runner (captures merged params, runs subagent)
|
|
830
|
+
const runTask = async (
|
|
831
|
+
index: number,
|
|
832
|
+
merged: MergedSubTaskParams,
|
|
833
|
+
unitCwd: string,
|
|
834
|
+
): Promise<boolean> => {
|
|
835
|
+
|
|
836
|
+
// Issue #434: the unit projection of the dispatch pre-flight. Applied
|
|
837
|
+
// HERE, not in the launcher's pre-merge: the launcher awaits
|
|
838
|
+
// `acquireSlot` and only then calls this, so a unit cancelled while
|
|
839
|
+
// waiting for its slot is never announced (and never dropped). The
|
|
840
|
+
// drop still precedes `createUnitRun` below, so the retry snapshot
|
|
841
|
+
// records an absent deadline rather than restoring the cap.
|
|
842
|
+
applyUnitShapeGuard(ctx, guard, taskList[index], merged);
|
|
843
|
+
|
|
844
|
+
// C3: Resolve this step's model override (step.model > global resolved model)
|
|
845
|
+
const stepModel = resolveStepModel(ctx, merged.model, subagentModel);
|
|
846
|
+
|
|
847
|
+
// Build system prompt for this task
|
|
848
|
+
const subagentPrompt = buildSubagentPrompt(
|
|
849
|
+
basePrompt,
|
|
850
|
+
merged.inheritSP,
|
|
851
|
+
merged.customSP,
|
|
852
|
+
merged.outputFile,
|
|
853
|
+
merged.toolOptions?.tools,
|
|
854
|
+
globalParams.resolvedPreset?.promptGuideline,
|
|
855
|
+
);
|
|
856
|
+
|
|
857
|
+
// Create SubTaskResult
|
|
858
|
+
const subTaskResult: SubTaskResult = {
|
|
859
|
+
task: merged.task,
|
|
860
|
+
label: merged.label,
|
|
861
|
+
exitCode: 0,
|
|
862
|
+
messages: [],
|
|
863
|
+
stderr: "",
|
|
864
|
+
usage: { ...EMPTY_USAGE },
|
|
865
|
+
};
|
|
866
|
+
|
|
867
|
+
// E10: Register subagent ID for intercom
|
|
868
|
+
const subagentId = merged.label ?? `parallel-${index}`;
|
|
869
|
+
intercom.register(subagentId);
|
|
870
|
+
|
|
871
|
+
// Issue #119: per-subtask run entry — created at spawn so the
|
|
872
|
+
// monitor drill-in shows per-unit priority and a post-hoc audit
|
|
873
|
+
// trail exists per subtask (mirrors single-mode run persistence).
|
|
874
|
+
const { runId, run } = createUnitRun(merged, stepModel, parallelPriority, globalParams.resolvedPreset?.name, state.config.recovery);
|
|
875
|
+
state.persistRun(pi, run, "unit");
|
|
876
|
+
|
|
877
|
+
// R2: Prune old run entries if history exceeds limit
|
|
878
|
+
pruneHistoryIfNeeded(state, ctx, log);
|
|
879
|
+
|
|
880
|
+
// Register for live monitor — parallel subtasks now appear in the
|
|
881
|
+
// drill-in with their per-unit priority (issue #119). The merged
|
|
882
|
+
// timeout rides along as the display deadline (issue #423).
|
|
883
|
+
registerLiveRun(state, run, ctx, undefined, merged.timeout);
|
|
884
|
+
|
|
885
|
+
log.debug("Parallel subtask run registered", { runId, index });
|
|
886
|
+
|
|
887
|
+
// Emit initial progress
|
|
888
|
+
const modeInfo = describePromptMode(
|
|
889
|
+
merged.inheritSP,
|
|
890
|
+
Boolean(merged.customSP),
|
|
891
|
+
);
|
|
892
|
+
onUpdate?.({
|
|
893
|
+
content: [
|
|
894
|
+
{
|
|
895
|
+
type: "text" as const,
|
|
896
|
+
text: `Parallel task ${index + 1}/${taskList.length} (${modeInfo})...`,
|
|
897
|
+
},
|
|
898
|
+
],
|
|
899
|
+
details: {
|
|
900
|
+
messages: [],
|
|
901
|
+
usage: { ...EMPTY_USAGE },
|
|
902
|
+
exitCode: -1,
|
|
903
|
+
stderr: "",
|
|
904
|
+
},
|
|
905
|
+
});
|
|
906
|
+
|
|
907
|
+
// Wrap onUpdate for per-task progress — also feed the live monitor so
|
|
908
|
+
// the drill-in streams output instead of showing "waiting for first
|
|
909
|
+
// output…" for the whole run (mirrors single mode's liveOnUpdate).
|
|
910
|
+
const taskOnUpdate = makeLiveOnUpdate(state, runId, onUpdate);
|
|
911
|
+
|
|
912
|
+
// Run subagent — the post-spawn body is crash-protected (issue #119
|
|
913
|
+
// R1, C1 fix): a throw here (e.g. runner writeToTempFile) must
|
|
914
|
+
// finalize the run entry and release the live monitor, or the entry
|
|
915
|
+
// stays 'running' forever and sweepStaleLiveSubagents cannot reclaim
|
|
916
|
+
// the live ghost (grace logic treats a 'running' record as live).
|
|
917
|
+
try {
|
|
918
|
+
const result = await runSubagent(
|
|
919
|
+
// Issue #222: this task's OWN validated cwd.
|
|
920
|
+
unitCwd,
|
|
921
|
+
subagentPrompt,
|
|
922
|
+
stepModel,
|
|
923
|
+
merged.thinkingLevel,
|
|
924
|
+
merged.task,
|
|
925
|
+
signal,
|
|
926
|
+
taskOnUpdate,
|
|
927
|
+
merged.toolOptions,
|
|
928
|
+
merged.timeout,
|
|
929
|
+
getFinalOutput,
|
|
930
|
+
log,
|
|
931
|
+
currentDepth + 1,
|
|
932
|
+
intercom,
|
|
933
|
+
subagentId,
|
|
934
|
+
run.childMarker,
|
|
935
|
+
// Issue #511 (U2): the run record's id names the scratch directory.
|
|
936
|
+
run.id,
|
|
937
|
+
);
|
|
938
|
+
|
|
939
|
+
// Fill SubTaskResult (one shared field mapping — issue #376/D3).
|
|
940
|
+
// Issue #474: probed at THIS task's own cwd.
|
|
941
|
+
Object.assign(subTaskResult, toSubTaskResult(result, unitCwd));
|
|
942
|
+
|
|
943
|
+
results[index] = subTaskResult;
|
|
944
|
+
completedCount++;
|
|
945
|
+
|
|
946
|
+
// Issue #119: finalize the per-subtask run entry — status, duration,
|
|
947
|
+
// cost, tokens and sanitized output land on the entry (mirrors
|
|
948
|
+
// single-mode finalization; result carries the SubagentResult shape
|
|
949
|
+
// finalizeRunRecord expects, errorCategory included).
|
|
950
|
+
finalizeUnitRun(state, pi, ctx, run, result, log);
|
|
951
|
+
} catch (err) {
|
|
952
|
+
// Issue #119 R1 (C1 fix): mirror the single-mode crash catch — a
|
|
953
|
+
// post-spawn throw must finalize the entry as failed and release
|
|
954
|
+
// the live monitor, or the persisted entry stays 'running' and
|
|
955
|
+
// the live drill-in loops forever. finalizeLiveSubagent is
|
|
956
|
+
// idempotent; the rethrow keeps Promise.allSettled semantics (the
|
|
957
|
+
// caller's finally still releases the concurrency slot).
|
|
958
|
+
finalizeUnitRunCrash(state, pi, run, err, "Parallel subtask", unitCwd, log, {
|
|
959
|
+
index,
|
|
960
|
+
});
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
// Emit progress update
|
|
964
|
+
const { succeeded, failed } = countSubagentOutcomes(results);
|
|
965
|
+
const completed = succeeded + failed;
|
|
966
|
+
|
|
967
|
+
const partialDetails: ParallelDetails = {
|
|
968
|
+
mode: "parallel",
|
|
969
|
+
results: results.filter((r) => r !== undefined),
|
|
970
|
+
totalInput: results.reduce(
|
|
971
|
+
(s, r) => s + (r?.usage.input ?? 0),
|
|
972
|
+
0,
|
|
973
|
+
),
|
|
974
|
+
totalOutput: results.reduce(
|
|
975
|
+
(s, r) => s + (r?.usage.output ?? 0),
|
|
976
|
+
0,
|
|
977
|
+
),
|
|
978
|
+
totalCost: results.reduce(
|
|
979
|
+
(s, r) => s + (r?.usage.cost ?? 0),
|
|
980
|
+
0,
|
|
981
|
+
),
|
|
982
|
+
totalTurns: results.reduce(
|
|
983
|
+
(s, r) => s + (r?.usage.turns ?? 0),
|
|
984
|
+
0,
|
|
985
|
+
),
|
|
986
|
+
succeeded,
|
|
987
|
+
failed,
|
|
988
|
+
};
|
|
989
|
+
|
|
990
|
+
onUpdate?.({
|
|
991
|
+
content: [
|
|
992
|
+
{
|
|
993
|
+
type: "text" as const,
|
|
994
|
+
text: `Parallel: ${completed}/${taskList.length} completed (${succeeded} succeeded, ${failed} failed)`,
|
|
995
|
+
},
|
|
996
|
+
],
|
|
997
|
+
details: partialDetails,
|
|
998
|
+
});
|
|
999
|
+
|
|
1000
|
+
// Issue #137: return the unit's real success so the caller's slot
|
|
1001
|
+
// release is honest — the status bar's "N failed" count reflects the
|
|
1002
|
+
// true outcome (same check as the aggregate chainSuccess).
|
|
1003
|
+
return !isSubagentError(subTaskResult);
|
|
1004
|
+
};
|
|
1005
|
+
|
|
1006
|
+
// Resolve priority — the FALLBACK for per-unit priority (issue #114): a
|
|
1007
|
+
// task-level priority on tasks[] items wins per slot; this is the floor.
|
|
1008
|
+
const parallelPriority: Priority = (
|
|
1009
|
+
params.priority && ["critical", "high", "normal", "low"].includes(params.priority as string)
|
|
1010
|
+
? (params.priority as Priority)
|
|
1011
|
+
: DEFAULT_PRIORITY
|
|
1012
|
+
);
|
|
1013
|
+
|
|
1014
|
+
// Launch all tasks concurrently using acquireSlot for natural concurrency limiting
|
|
1015
|
+
const promises = taskList.map(async (_, index) => {
|
|
1016
|
+
// Issue #114: per-unit priority wins the slot — the step's merged
|
|
1017
|
+
// priority (if any) beats the call-level parallelPriority fallback.
|
|
1018
|
+
const merged = mergeSubTaskParams(globalParams, taskList[index], state.config.maxThinkingLevel);
|
|
1019
|
+
const acquired = await acquireSlot(state, ctx, signal, merged.priority ?? parallelPriority);
|
|
1020
|
+
if (!acquired) {
|
|
1021
|
+
results[index] = {
|
|
1022
|
+
task: taskList[index].task,
|
|
1023
|
+
exitCode: 1,
|
|
1024
|
+
messages: [],
|
|
1025
|
+
stderr: "",
|
|
1026
|
+
usage: { ...EMPTY_USAGE },
|
|
1027
|
+
errorMessage:
|
|
1028
|
+
"Cancelled while waiting for concurrency slot",
|
|
1029
|
+
errorCategory: "aborted",
|
|
1030
|
+
};
|
|
1031
|
+
completedCount++;
|
|
1032
|
+
return;
|
|
1033
|
+
}
|
|
1034
|
+
let taskSuccess = false;
|
|
1035
|
+
try {
|
|
1036
|
+
taskSuccess = await runTask(index, merged, taskCwds[index]);
|
|
1037
|
+
} finally {
|
|
1038
|
+
// Issue #137: release with the unit's real success — the status
|
|
1039
|
+
// bar's "N failed" count reflects the true outcome.
|
|
1040
|
+
releaseSlot(state, taskSuccess, ctx);
|
|
1041
|
+
}
|
|
1042
|
+
});
|
|
1043
|
+
|
|
1044
|
+
const settledUnits = await Promise.allSettled(promises);
|
|
1045
|
+
// Issue #474: a rejected unit is a FAILED unit, not an absent one — it earns
|
|
1046
|
+
// a row (the crash finalizer rethrows, so "rejected" is the only trace of a
|
|
1047
|
+
// unit that died). `results[index]` is never set on that path (the rejection
|
|
1048
|
+
// skips the assignment inside `runTask`), so the guard is belt-and-braces.
|
|
1049
|
+
settledUnits.forEach((settled, index) => {
|
|
1050
|
+
if (settled.status !== "rejected" || results[index]) return;
|
|
1051
|
+
results[index] = rejectedUnitResult(
|
|
1052
|
+
taskList[index].task,
|
|
1053
|
+
taskList[index].label,
|
|
1054
|
+
taskCwds[index],
|
|
1055
|
+
settled.reason,
|
|
1056
|
+
);
|
|
1057
|
+
});
|
|
1058
|
+
|
|
1059
|
+
// Compute final aggregates
|
|
1060
|
+
const finalResults = results.filter(Boolean);
|
|
1061
|
+
const totalInput = finalResults.reduce(
|
|
1062
|
+
(s, r) => s + r.usage.input,
|
|
1063
|
+
0,
|
|
1064
|
+
);
|
|
1065
|
+
const totalOutput = finalResults.reduce(
|
|
1066
|
+
(s, r) => s + r.usage.output,
|
|
1067
|
+
0,
|
|
1068
|
+
);
|
|
1069
|
+
const totalCost = finalResults.reduce(
|
|
1070
|
+
(s, r) => s + r.usage.cost,
|
|
1071
|
+
0,
|
|
1072
|
+
);
|
|
1073
|
+
const totalTurns = finalResults.reduce(
|
|
1074
|
+
(s, r) => s + r.usage.turns,
|
|
1075
|
+
0,
|
|
1076
|
+
);
|
|
1077
|
+
const { succeeded, failed } = countSubagentOutcomes(finalResults);
|
|
1078
|
+
|
|
1079
|
+
const parallelDetails: ParallelDetails = {
|
|
1080
|
+
mode: "parallel",
|
|
1081
|
+
results: finalResults,
|
|
1082
|
+
totalInput,
|
|
1083
|
+
totalOutput,
|
|
1084
|
+
totalCost,
|
|
1085
|
+
totalTurns,
|
|
1086
|
+
succeeded,
|
|
1087
|
+
failed,
|
|
1088
|
+
};
|
|
1089
|
+
|
|
1090
|
+
// R1: Record circuit breaker outcome
|
|
1091
|
+
if (failed === 0) {
|
|
1092
|
+
state.recordSuccess();
|
|
1093
|
+
} else {
|
|
1094
|
+
state.recordFailure();
|
|
1095
|
+
}
|
|
1096
|
+
|
|
1097
|
+
log.info("Parallel execution completed", {
|
|
1098
|
+
totalTasks: taskList.length,
|
|
1099
|
+
succeeded,
|
|
1100
|
+
failed,
|
|
1101
|
+
totalInput,
|
|
1102
|
+
totalOutput,
|
|
1103
|
+
totalCost,
|
|
1104
|
+
});
|
|
1105
|
+
|
|
1106
|
+
// C: per-task validation warnings ride the result, prefixed with their
|
|
1107
|
+
// task (issue #220), after the JSON payload — empty renders nothing so
|
|
1108
|
+
// warning-free results stay byte-identical.
|
|
1109
|
+
return {
|
|
1110
|
+
content: [
|
|
1111
|
+
{
|
|
1112
|
+
type: "text" as const,
|
|
1113
|
+
text: JSON.stringify(parallelDetails, null, 2) + formatValidationWarnings(taskWarnings),
|
|
1114
|
+
},
|
|
1115
|
+
],
|
|
1116
|
+
details: parallelDetails,
|
|
1117
|
+
};
|
|
1118
|
+
}
|
|
1119
|
+
|
|
1120
|
+
// -------------------------------------------------------------------
|
|
1121
|
+
// P10: runGraphMode
|
|
1122
|
+
// -------------------------------------------------------------------
|
|
1123
|
+
|
|
1124
|
+
async function runGraphMode(
|
|
1125
|
+
params: DelegateTaskParams,
|
|
1126
|
+
signal: AbortSignal | undefined,
|
|
1127
|
+
onUpdate: AgentToolUpdateCallback<DelegateTaskDetails> | undefined,
|
|
1128
|
+
ctx: ExtensionContext,
|
|
1129
|
+
guard: BatchGuardContext,
|
|
1130
|
+
): Promise<ToolResult<SubagentResult | GraphDetails | undefined>> {
|
|
1131
|
+
const graphTasks: GraphTask[] = params.graph!;
|
|
1132
|
+
|
|
1133
|
+
// Issue #133: dispatch-start timestamp — the aggregate run entry's
|
|
1134
|
+
// startedAt (captured once, at mode entry, not at completion).
|
|
1135
|
+
const graphModeStartedAt = new Date().toISOString();
|
|
1136
|
+
|
|
1137
|
+
// Mode prologue (issue #379): cost → depth → resolve → targets →
|
|
1138
|
+
// preflight → H1, with the DAG check as the graph-only pre-cost hook — a
|
|
1139
|
+
// malformed graph (empty / over-limit / duplicate id / missing dep) is
|
|
1140
|
+
// rejected before the session spends anything (IN1 boundary). Cycles are
|
|
1141
|
+
// NOT caught here; topologicalSort rejects them after the tail.
|
|
1142
|
+
const pro = runModePrologue({
|
|
1143
|
+
params,
|
|
1144
|
+
state,
|
|
1145
|
+
ctx,
|
|
1146
|
+
log,
|
|
1147
|
+
label: "Graph",
|
|
1148
|
+
units: graphTasks.length,
|
|
1149
|
+
beforeCost: () => {
|
|
1150
|
+
const errors = validateGraph(graphTasks);
|
|
1151
|
+
return errors.length === 0
|
|
1152
|
+
? undefined
|
|
1153
|
+
: rejection(`Graph validation failed:\n${errors.map((e) => ` - ${e}`).join("\n")}`);
|
|
1154
|
+
},
|
|
1155
|
+
});
|
|
1156
|
+
if (!pro.ok) return pro.error;
|
|
1157
|
+
const { globalParams, resolvedCwd, currentDepth } = pro;
|
|
1158
|
+
|
|
1159
|
+
// Mode tail (issue #379): model resolution (preset + per-call override,
|
|
1160
|
+
// auto-route included in `resolvedPreset`), the empty-model rejection and
|
|
1161
|
+
// the circuit check. It runs BEFORE the topological sort and the per-node
|
|
1162
|
+
// pass (IN8/IN11): a graph with a bad node AND an unconfigured model
|
|
1163
|
+
// reports the MODEL error first.
|
|
1164
|
+
const tail = resolveModeModel({
|
|
1165
|
+
state,
|
|
1166
|
+
ctx,
|
|
1167
|
+
log,
|
|
1168
|
+
preset: globalParams.resolvedPreset,
|
|
1169
|
+
perCallModel: params.model,
|
|
1170
|
+
});
|
|
1171
|
+
if (!tail.ok) return tail.error;
|
|
1172
|
+
const subagentModel = tail.model;
|
|
1173
|
+
const modelStr = tail.modelStr;
|
|
1174
|
+
|
|
1175
|
+
// Resolve priority — the FALLBACK for per-unit priority (issue #114): a
|
|
1176
|
+
// task-level priority on graph[] items wins per slot; this is the floor.
|
|
1177
|
+
const graphPriority: Priority = (
|
|
1178
|
+
params.priority && ["critical", "high", "normal", "low"].includes(params.priority as string)
|
|
1179
|
+
? (params.priority as Priority)
|
|
1180
|
+
: DEFAULT_PRIORITY
|
|
1181
|
+
);
|
|
1182
|
+
|
|
1183
|
+
// Topological sort → execution waves
|
|
1184
|
+
const sortResult = topologicalSort(graphTasks);
|
|
1185
|
+
if (!sortResult.ok) {
|
|
1186
|
+
return {
|
|
1187
|
+
content: [
|
|
1188
|
+
{ type: "text" as const, text: `Graph scheduling failed: ${sortResult.error}` },
|
|
1189
|
+
],
|
|
1190
|
+
details: undefined,
|
|
1191
|
+
isError: true,
|
|
1192
|
+
};
|
|
1193
|
+
}
|
|
1194
|
+
const waves = sortResult.waves;
|
|
1195
|
+
|
|
1196
|
+
// Per-node pre-pass (issue #222): resolve + validate EVERY node before
|
|
1197
|
+
// any spawn, so a single bad node rejects the whole graph with nothing
|
|
1198
|
+
// started — the same all-before-any-spawn semantics the background
|
|
1199
|
+
// fan-out, the parallel `tasks` shape and the chain use. Each node's OWN
|
|
1200
|
+
// cwd is resolved and validated here (with its outputFile, resolved
|
|
1201
|
+
// against that cwd) and the resolved value is what that node spawns in.
|
|
1202
|
+
// The pre-pass runs on the DECLARED task text, before {id} substitution
|
|
1203
|
+
// (the substituted text is only known mid-dispatch, once a dependency's
|
|
1204
|
+
// output exists) — the declared text is validated with the placeholder
|
|
1205
|
+
// TOKENS stripped (a dependency whose id happens to be a blocking
|
|
1206
|
+
// keyword must not make `{<id>}` itself trip the keyword rules), while
|
|
1207
|
+
// the SUBSTITUTED content stays unvalidated by design. The host's own
|
|
1208
|
+
// wording is still validated, and refusing to validate up front would
|
|
1209
|
+
// mean a bad node in the LAST wave is discovered after every earlier
|
|
1210
|
+
// wave already spent its budget.
|
|
1211
|
+
const nodePass = validateUnitPrePass({
|
|
1212
|
+
units: graphTasks,
|
|
1213
|
+
label: "Graph",
|
|
1214
|
+
gitMode: globalParams.resolvedGitMode,
|
|
1215
|
+
ctx,
|
|
1216
|
+
log,
|
|
1217
|
+
force: params.force as boolean | undefined,
|
|
1218
|
+
noJev: params.noJev,
|
|
1219
|
+
// Issue #443: the DECLARED per-node level (the merged one is resolved).
|
|
1220
|
+
declaredThinkingLevel: (node) => node.thinkingLevel,
|
|
1221
|
+
merge: (node) =>
|
|
1222
|
+
mergeSubTaskParams(globalParams, graphTaskToSubTaskParams(node), state.config.maxThinkingLevel),
|
|
1223
|
+
describe: (node, merged) => ({
|
|
1224
|
+
prefix: `Node "${node.id}"`,
|
|
1225
|
+
logContext: { id: node.id },
|
|
1226
|
+
// Placeholder TOKENS stripped (issue #222 review): the rules
|
|
1227
|
+
// read the declared string, so a `{<id>}` whose dependency id
|
|
1228
|
+
// is a blocking keyword would block on a token, not on text
|
|
1229
|
+
// the host wrote. The declared wording around it is unchanged
|
|
1230
|
+
// and still validated. Graph policy — it stays here, not in
|
|
1231
|
+
// the shared helper.
|
|
1232
|
+
task: merged.task.replace(GRAPH_OUTPUT_PLACEHOLDER_RE, " "),
|
|
1233
|
+
}),
|
|
1234
|
+
});
|
|
1235
|
+
if (!nodePass.ok) return nodePass.error;
|
|
1236
|
+
const nodeCwds = new Map(nodePass.units.map((u) => [u.unit.id, u.cwd] as const));
|
|
1237
|
+
const nodeWarnings = nodePass.warnings;
|
|
1238
|
+
|
|
1239
|
+
// Build base prompt once
|
|
1240
|
+
const basePrompt = ctx.getSystemPrompt();
|
|
1241
|
+
|
|
1242
|
+
// Results map: task id → SubTaskResult (populated as waves complete)
|
|
1243
|
+
const resultMap = new Map<string, SubTaskResult>();
|
|
1244
|
+
const allWaves: GraphWave[] = [];
|
|
1245
|
+
|
|
1246
|
+
// E10: Intercom for subagent-to-subagent messaging
|
|
1247
|
+
const intercom = new Intercom();
|
|
1248
|
+
|
|
1249
|
+
// Issue #133: global node counter — node positions are reported against
|
|
1250
|
+
// the WHOLE dispatch (dispatch-wide ordinal), not the current wave; a
|
|
1251
|
+
// later wave's first node is its true global position (e.g. node 3/5),
|
|
1252
|
+
// not "node 1/5". Incremented once per node as each wave's nodes run.
|
|
1253
|
+
let globalNodeCounter = 0;
|
|
1254
|
+
let chainSuccess = false;
|
|
1255
|
+
try {
|
|
1256
|
+
for (let w = 0; w < waves.length; w++) {
|
|
1257
|
+
const wave = waves[w];
|
|
1258
|
+
const waveIndex = w + 1;
|
|
1259
|
+
const isParallel = wave.length > 1;
|
|
1260
|
+
|
|
1261
|
+
// Issue #133: status-bar breakdown — wave-level context set at
|
|
1262
|
+
// each wave start (nodes within the wave refine it as they start).
|
|
1263
|
+
state.modeContext = {
|
|
1264
|
+
kind: "graph",
|
|
1265
|
+
wave: waveIndex,
|
|
1266
|
+
totalWaves: waves.length,
|
|
1267
|
+
node: 0,
|
|
1268
|
+
totalNodes: graphTasks.length,
|
|
1269
|
+
};
|
|
1270
|
+
|
|
1271
|
+
// Emit initial progress
|
|
1272
|
+
onUpdate?.({
|
|
1273
|
+
content: [
|
|
1274
|
+
{
|
|
1275
|
+
type: "text" as const,
|
|
1276
|
+
text: `Graph wave ${waveIndex}/${waves.length} (${wave.length} task${wave.length > 1 ? "s" : ""})...`,
|
|
1277
|
+
},
|
|
1278
|
+
],
|
|
1279
|
+
details: {
|
|
1280
|
+
messages: [],
|
|
1281
|
+
usage: { ...EMPTY_USAGE },
|
|
1282
|
+
exitCode: -1,
|
|
1283
|
+
stderr: "",
|
|
1284
|
+
},
|
|
1285
|
+
});
|
|
1286
|
+
|
|
1287
|
+
// Run all tasks in this wave concurrently
|
|
1288
|
+
const wavePromises = wave.map(async (graphTask, nodeIndex) => {
|
|
1289
|
+
// Issue #133: capture this node's dispatch-wide ordinal before any
|
|
1290
|
+
// sibling node advances the counter (same-wave siblings run
|
|
1291
|
+
// concurrently, so the value must be pinned here).
|
|
1292
|
+
const globalNode = ++globalNodeCounter;
|
|
1293
|
+
const subTaskParams = graphTaskToSubTaskParams(graphTask);
|
|
1294
|
+
|
|
1295
|
+
const merged = mergeSubTaskParams(globalParams, subTaskParams, state.config.maxThinkingLevel);
|
|
1296
|
+
// Issue #222: the node's OWN validated cwd (pre-pass);
|
|
1297
|
+
// resolvedCwd (the mode-level cwd) is the guaranteed
|
|
1298
|
+
// fallback, so a node that declares none still resolves.
|
|
1299
|
+
const nodeCwd = nodeCwds.get(graphTask.id) ?? resolvedCwd;
|
|
1300
|
+
|
|
1301
|
+
// C3: Resolve this step's model override (step.model > global resolved model)
|
|
1302
|
+
const stepModel = resolveStepModel(ctx, merged.model, subagentModel);
|
|
1303
|
+
|
|
1304
|
+
// Substitute {id} placeholders with previous outputs
|
|
1305
|
+
merged.task = merged.task.replace(GRAPH_OUTPUT_PLACEHOLDER_RE, (_match, id) => {
|
|
1306
|
+
const depResult = resultMap.get(id);
|
|
1307
|
+
if (!depResult) return _match; // Leave unchanged if dep not found
|
|
1308
|
+
return getFinalOutput(depResult.messages);
|
|
1309
|
+
});
|
|
1310
|
+
|
|
1311
|
+
// Build system prompt
|
|
1312
|
+
const subagentPrompt = buildSubagentPrompt(
|
|
1313
|
+
basePrompt,
|
|
1314
|
+
merged.inheritSP,
|
|
1315
|
+
merged.customSP,
|
|
1316
|
+
merged.outputFile,
|
|
1317
|
+
merged.toolOptions?.tools,
|
|
1318
|
+
globalParams.resolvedPreset?.promptGuideline,
|
|
1319
|
+
);
|
|
1320
|
+
|
|
1321
|
+
// Acquire concurrency slot — issue #114: per-unit priority wins the
|
|
1322
|
+
// slot; the call-level graphPriority is the fallback.
|
|
1323
|
+
const acquired = await acquireSlot(state, ctx, signal, merged.priority ?? graphPriority);
|
|
1324
|
+
if (!acquired) {
|
|
1325
|
+
return {
|
|
1326
|
+
id: graphTask.id,
|
|
1327
|
+
result: {
|
|
1328
|
+
task: merged.task,
|
|
1329
|
+
label: merged.label,
|
|
1330
|
+
exitCode: 1,
|
|
1331
|
+
messages: [],
|
|
1332
|
+
stderr: "",
|
|
1333
|
+
usage: { ...EMPTY_USAGE },
|
|
1334
|
+
errorMessage: "Cancelled while waiting for concurrency slot",
|
|
1335
|
+
errorCategory: "aborted" as const,
|
|
1336
|
+
} satisfies SubTaskResult,
|
|
1337
|
+
};
|
|
1338
|
+
}
|
|
1339
|
+
|
|
1340
|
+
const subagentId = graphTask.id;
|
|
1341
|
+
intercom.register(subagentId);
|
|
1342
|
+
|
|
1343
|
+
// Issue #434: the unit projection of the dispatch pre-flight, applied
|
|
1344
|
+
// after this node's slot is held (a node cancelled above never
|
|
1345
|
+
// reaches here) and BEFORE `createUnitRun` below, so the retry
|
|
1346
|
+
// snapshot records the dropped deadline (ADR 0009).
|
|
1347
|
+
applyUnitShapeGuard(ctx, guard, subTaskParams, merged);
|
|
1348
|
+
|
|
1349
|
+
// Issue #133: status-bar breakdown — the node's dispatch-wide
|
|
1350
|
+
// position (globalNode, not the wave-local nodeIndex) so a later
|
|
1351
|
+
// wave reports its true global ordinal.
|
|
1352
|
+
state.modeContext = {
|
|
1353
|
+
kind: "graph",
|
|
1354
|
+
wave: waveIndex,
|
|
1355
|
+
totalWaves: waves.length,
|
|
1356
|
+
node: globalNode,
|
|
1357
|
+
totalNodes: graphTasks.length,
|
|
1358
|
+
};
|
|
1359
|
+
|
|
1360
|
+
// Issue #133: per-node run entry — mirrors runParallelMode's
|
|
1361
|
+
// per-unit block (issue #119): the runId doubles as the live id,
|
|
1362
|
+
// so sweepStaleLiveSubagents finds a 'running' record for every
|
|
1363
|
+
// foreground live entry (the #130 invariant gap that swept
|
|
1364
|
+
// graph/chain entries immediately).
|
|
1365
|
+
const { runId, run } = createUnitRun(merged, stepModel, graphPriority, globalParams.resolvedPreset?.name, state.config.recovery);
|
|
1366
|
+
state.persistRun(pi, run, "unit");
|
|
1367
|
+
|
|
1368
|
+
// R2: Prune old run entries if history exceeds limit
|
|
1369
|
+
pruneHistoryIfNeeded(state, ctx, log);
|
|
1370
|
+
|
|
1371
|
+
// Register for live monitor — graph nodes now appear in the
|
|
1372
|
+
// drill-in under the runId with their per-unit priority
|
|
1373
|
+
// (issue #133 single identity, mirrors parallel mode's issue
|
|
1374
|
+
// #119 registration). A FRESH runId per node: subagentSessions
|
|
1375
|
+
// is host-global, so raw graph-task ids would collide across
|
|
1376
|
+
// concurrent graph runs (the intercom namespace is per-run and
|
|
1377
|
+
// stays untouched).
|
|
1378
|
+
// Issue #423: the merged timeout rides along as the display deadline.
|
|
1379
|
+
registerLiveRun(state, run, ctx, undefined, merged.timeout);
|
|
1380
|
+
|
|
1381
|
+
let nodeSuccess = false;
|
|
1382
|
+
try {
|
|
1383
|
+
// Wrap onUpdate for per-node progress — also feed the live
|
|
1384
|
+
// monitor so the drill-in streams output instead of showing
|
|
1385
|
+
// "waiting for first output…" (mirrors parallel mode's
|
|
1386
|
+
// taskOnUpdate).
|
|
1387
|
+
const stepOnUpdate = makeLiveOnUpdate(state, runId, onUpdate);
|
|
1388
|
+
|
|
1389
|
+
const result = await runSubagent(
|
|
1390
|
+
nodeCwd,
|
|
1391
|
+
subagentPrompt,
|
|
1392
|
+
stepModel,
|
|
1393
|
+
merged.thinkingLevel,
|
|
1394
|
+
merged.task,
|
|
1395
|
+
signal,
|
|
1396
|
+
stepOnUpdate,
|
|
1397
|
+
merged.toolOptions,
|
|
1398
|
+
merged.timeout,
|
|
1399
|
+
getFinalOutput,
|
|
1400
|
+
log,
|
|
1401
|
+
currentDepth + 1,
|
|
1402
|
+
intercom,
|
|
1403
|
+
subagentId,
|
|
1404
|
+
run.childMarker,
|
|
1405
|
+
// Issue #511 (U2): the run record's id names the scratch directory.
|
|
1406
|
+
run.id,
|
|
1407
|
+
);
|
|
1408
|
+
|
|
1409
|
+
// One shared field mapping — issue #376/D3 (the graph literal was a
|
|
1410
|
+
// third copy of it).
|
|
1411
|
+
const subTaskResult: SubTaskResult = {
|
|
1412
|
+
task: merged.task,
|
|
1413
|
+
label: merged.label,
|
|
1414
|
+
// Issue #474: probed at THIS node's own cwd.
|
|
1415
|
+
...toSubTaskResult(result, nodeCwd),
|
|
1416
|
+
};
|
|
1417
|
+
|
|
1418
|
+
// Issue #133: finalize the per-node run entry — status, duration,
|
|
1419
|
+
// cost, tokens and sanitized output land on the entry (mirrors
|
|
1420
|
+
// parallel's issue #119 finalize; result carries the
|
|
1421
|
+
// SubagentResult shape finalizeRunRecord expects, errorCategory
|
|
1422
|
+
// included).
|
|
1423
|
+
finalizeUnitRun(state, pi, ctx, run, result, log);
|
|
1424
|
+
// Issue #137: the node's real success — the status bar's
|
|
1425
|
+
// "N failed" count reflects the true outcome (same check as
|
|
1426
|
+
// the aggregate chainSuccess).
|
|
1427
|
+
nodeSuccess = !isSubagentError(result);
|
|
1428
|
+
|
|
1429
|
+
return { id: graphTask.id, result: subTaskResult };
|
|
1430
|
+
} catch (err) {
|
|
1431
|
+
// Issue #133 (mirrors the #119 R1/C1 discipline): crash-protected
|
|
1432
|
+
// — a post-spawn throw must finalize the run entry as failed AND
|
|
1433
|
+
// release the live entry, or the persisted record stays
|
|
1434
|
+
// 'running' forever and the sweep treats the ghost as live.
|
|
1435
|
+
// finalizeLiveSubagent is idempotent; the rethrow keeps
|
|
1436
|
+
// Promise.allSettled semantics (a failing node must NOT cancel
|
|
1437
|
+
// sibling nodes in the wave).
|
|
1438
|
+
finalizeUnitRunCrash(state, pi, run, err, "Graph node", nodeCwd, log, {
|
|
1439
|
+
id: graphTask.id,
|
|
1440
|
+
});
|
|
1441
|
+
} finally {
|
|
1442
|
+
releaseSlot(state, nodeSuccess, ctx);
|
|
1443
|
+
}
|
|
1444
|
+
});
|
|
1445
|
+
|
|
1446
|
+
const waveResults = await Promise.allSettled(wavePromises);
|
|
1447
|
+
const graphWaveTasks: SubTaskResult[] = [];
|
|
1448
|
+
|
|
1449
|
+
for (const [nodeIndex, settled] of waveResults.entries()) {
|
|
1450
|
+
if (settled.status === "fulfilled") {
|
|
1451
|
+
resultMap.set(settled.value.id, settled.value.result);
|
|
1452
|
+
graphWaveTasks.push(settled.value.result);
|
|
1453
|
+
} else {
|
|
1454
|
+
log.error("Graph wave task rejected", { error: String(settled.reason) });
|
|
1455
|
+
// Issue #474: the rejected node keeps its place in the wave as a
|
|
1456
|
+
// FAILED row — a dropped row made a crashed node read as an
|
|
1457
|
+
// absent one, and the aggregate could settle `done`.
|
|
1458
|
+
const node = wave[nodeIndex];
|
|
1459
|
+
graphWaveTasks.push(
|
|
1460
|
+
rejectedUnitResult(
|
|
1461
|
+
node.task,
|
|
1462
|
+
node.label,
|
|
1463
|
+
nodeCwds.get(node.id) ?? resolvedCwd,
|
|
1464
|
+
settled.reason,
|
|
1465
|
+
),
|
|
1466
|
+
);
|
|
1467
|
+
}
|
|
1468
|
+
}
|
|
1469
|
+
|
|
1470
|
+
const graphWave: GraphWave = {
|
|
1471
|
+
waveIndex,
|
|
1472
|
+
tasks: graphWaveTasks,
|
|
1473
|
+
parallel: isParallel,
|
|
1474
|
+
};
|
|
1475
|
+
allWaves.push(graphWave);
|
|
1476
|
+
|
|
1477
|
+
// Emit progress update
|
|
1478
|
+
onUpdate?.({
|
|
1479
|
+
details: undefined,
|
|
1480
|
+
content: [
|
|
1481
|
+
{
|
|
1482
|
+
type: "text" as const,
|
|
1483
|
+
text: `Graph wave ${waveIndex}/${waves.length} completed`,
|
|
1484
|
+
},
|
|
1485
|
+
],
|
|
1486
|
+
});
|
|
1487
|
+
}
|
|
1488
|
+
|
|
1489
|
+
// Compute final aggregates
|
|
1490
|
+
const allResults = allWaves.flatMap((w) => w.tasks);
|
|
1491
|
+
const totalInput = allResults.reduce((s, r) => s + r.usage.input, 0);
|
|
1492
|
+
const totalOutput = allResults.reduce((s, r) => s + r.usage.output, 0);
|
|
1493
|
+
const totalCost = allResults.reduce((s, r) => s + r.usage.cost, 0);
|
|
1494
|
+
const totalTurns = allResults.reduce((s, r) => s + r.usage.turns, 0);
|
|
1495
|
+
|
|
1496
|
+
chainSuccess = countSubagentOutcomes(allResults).failed === 0;
|
|
1497
|
+
|
|
1498
|
+
const graphDetails: GraphDetails = {
|
|
1499
|
+
mode: "graph",
|
|
1500
|
+
waves: allWaves,
|
|
1501
|
+
totalInput,
|
|
1502
|
+
totalOutput,
|
|
1503
|
+
totalCost,
|
|
1504
|
+
totalTurns,
|
|
1505
|
+
};
|
|
1506
|
+
|
|
1507
|
+
// R1: Record circuit breaker outcome
|
|
1508
|
+
if (chainSuccess) {
|
|
1509
|
+
state.recordSuccess();
|
|
1510
|
+
} else {
|
|
1511
|
+
state.recordFailure();
|
|
1512
|
+
}
|
|
1513
|
+
|
|
1514
|
+
log.info("Graph completed", {
|
|
1515
|
+
totalTasks: graphTasks.length,
|
|
1516
|
+
waves: allWaves.length,
|
|
1517
|
+
totalInput,
|
|
1518
|
+
totalOutput,
|
|
1519
|
+
totalCost,
|
|
1520
|
+
});
|
|
1521
|
+
|
|
1522
|
+
// Issue #133: one aggregate run entry per graph dispatch — fresh id,
|
|
1523
|
+
// persisted ONCE as done (no live entry: the drill-in shows the
|
|
1524
|
+
// per-node entries while running; the aggregate is a post-hoc audit
|
|
1525
|
+
// summary). Fields come from the dispatch-level resolved values and
|
|
1526
|
+
// the aggregate totals; startedAt is the mode-entry timestamp.
|
|
1527
|
+
const graphAggregateRun: SubagentRun = {
|
|
1528
|
+
id: crypto.randomUUID(),
|
|
1529
|
+
task: `Graph dispatch: ${graphTasks.length} tasks in ${allWaves.length} waves`,
|
|
1530
|
+
label: globalParams.label ?? "graph",
|
|
1531
|
+
// Issue #133: persist the ACTUAL outcome — "failed" when any node
|
|
1532
|
+
// failed (chainSuccess === false), "done" otherwise.
|
|
1533
|
+
status: chainSuccess ? "done" : "failed",
|
|
1534
|
+
model: `${subagentModel.provider}/${subagentModel.id}`,
|
|
1535
|
+
thinkingLevel: globalParams.thinkingLevel,
|
|
1536
|
+
priority: graphPriority,
|
|
1537
|
+
startedAt: graphModeStartedAt,
|
|
1538
|
+
finishedAt: new Date().toISOString(),
|
|
1539
|
+
durationMs: Date.now() - new Date(graphModeStartedAt).getTime(),
|
|
1540
|
+
cost: totalCost,
|
|
1541
|
+
tokensIn: totalInput,
|
|
1542
|
+
tokensOut: totalOutput,
|
|
1543
|
+
outputSummary: capOutput(JSON.stringify(graphDetails, null, 2)),
|
|
1544
|
+
};
|
|
1545
|
+
state.persistRun(pi, graphAggregateRun);
|
|
1546
|
+
|
|
1547
|
+
// Per-node validation warnings ride the result, prefixed with their
|
|
1548
|
+
// node id (issue #222), after the JSON payload — empty renders
|
|
1549
|
+
// nothing so warning-free results stay byte-identical.
|
|
1550
|
+
return {
|
|
1551
|
+
content: [
|
|
1552
|
+
{
|
|
1553
|
+
type: "text" as const,
|
|
1554
|
+
text: JSON.stringify(graphDetails, null, 2) + formatValidationWarnings(nodeWarnings),
|
|
1555
|
+
},
|
|
1556
|
+
],
|
|
1557
|
+
details: graphDetails,
|
|
1558
|
+
};
|
|
1559
|
+
} catch (err) {
|
|
1560
|
+
// F7 (issue #65): err.message may embed absolute paths — sanitize
|
|
1561
|
+
// BEFORE it reaches the main agent's context (tool result content +
|
|
1562
|
+
// details.errorMessage). resolvedCwd is the validated subagent cwd.
|
|
1563
|
+
const result = buildCrashResult("Graph mode", err, resolvedCwd);
|
|
1564
|
+
log.error("Graph mode crashed", { error: result.details.errorMessage });
|
|
1565
|
+
return result;
|
|
1566
|
+
} finally {
|
|
1567
|
+
// Issue #133: clear the status-bar mode breakdown — the dispatch is
|
|
1568
|
+
// over (success or outer-catch crash).
|
|
1569
|
+
state.modeContext = undefined;
|
|
1570
|
+
releaseSlot(state, chainSuccess, ctx);
|
|
1571
|
+
}
|
|
1572
|
+
}
|
|
1573
|
+
|
|
1574
|
+
return { runChainMode, runParallelMode, runGraphMode, resolveStepModel, applyUnitShapeGuard };
|
|
1575
|
+
}
|