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,2261 @@
|
|
|
1
|
+
// Purpose: The delegate_task tool — its definition, the dispatch pre-flight, the foreground run path — returned to the composition root to register.
|
|
2
|
+
/**
|
|
3
|
+
* brl-subagent — the `delegate_task` definition (ADR 0027 S5, issue #483)
|
|
4
|
+
*
|
|
5
|
+
* This was the largest single literal in `src/index.ts`: a ~1,200-line
|
|
6
|
+
* `pi.registerTool({ … })` whose `execute` carried the whole dispatch seam —
|
|
7
|
+
* template resolution, the retry restore, shape selection, the #412 pre-flight,
|
|
8
|
+
* the single foreground run (git work branch, approval flow, finalize). The
|
|
9
|
+
* definition moves here; the REGISTRATION does not (D7): the composition root
|
|
10
|
+
* calls `pi.registerTool(createDelegateHandler(rt, deps))`, so the tool surface
|
|
11
|
+
* is still registered in exactly one place.
|
|
12
|
+
*
|
|
13
|
+
* **Instance identity is the contract (D5).** Four things this body calls must
|
|
14
|
+
* be the SAME instances `index.ts` created, and they arrive through `deps`:
|
|
15
|
+
*
|
|
16
|
+
* - the three S2 mode runners (chain/parallel/graph);
|
|
17
|
+
* - the S3 background pipeline's fan-out and single-spawn entry (a second
|
|
18
|
+
* `createBackgroundPipeline` would carry a second spawn queue);
|
|
19
|
+
* - the S4 boot cluster's `visibleRunsFor` (a second `createBootRecovery`
|
|
20
|
+
* would carry a second notice latch).
|
|
21
|
+
*
|
|
22
|
+
* Nothing in this module calls a `create*` factory. The three `type` imports of
|
|
23
|
+
* those factories exist only to NAME the dep types — `ReturnType<…>` on a
|
|
24
|
+
* type-only import resolves to the factory's published contract without
|
|
25
|
+
* instantiating anything, so the seam cannot drift from the real signature the
|
|
26
|
+
* way a hand-copied function type would.
|
|
27
|
+
*
|
|
28
|
+
* The move is verbatim. The factory's own first lines destructure the runtime
|
|
29
|
+
* (the S2/S3 pattern) so the moved statements keep the names they read from
|
|
30
|
+
* their old closure; a body line that differs from 876bb5d is a bug in this
|
|
31
|
+
* commit, not a refactor.
|
|
32
|
+
*
|
|
33
|
+
* S6 (#430) then splits the validation/pre-flight/run seams INSIDE this module
|
|
34
|
+
* into the private same-file helpers below. They are private on purpose (D7):
|
|
35
|
+
* nothing outside this file may depend on a seam, and the tests drive them
|
|
36
|
+
* through `createDelegateHandler` — a seam is an implementation detail of the
|
|
37
|
+
* definition, not a second public surface.
|
|
38
|
+
*/
|
|
39
|
+
|
|
40
|
+
import type { createBackgroundPipeline } from "./background-pipeline";
|
|
41
|
+
import type { createBootRecovery } from "./boot-recovery";
|
|
42
|
+
import type { Logger } from "./logging";
|
|
43
|
+
import type { BatchGuardContext, createModeRunners } from "./mode-runners";
|
|
44
|
+
import type { RuntimeContext } from "./runtime";
|
|
45
|
+
import type { AgentToolResult, AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
|
|
46
|
+
import type { ExtensionAPI, ExtensionContext, Theme, ToolDefinition, ToolRenderResultOptions } from "@earendil-works/pi-coding-agent";
|
|
47
|
+
import * as path from "node:path";
|
|
48
|
+
import {
|
|
49
|
+
DEFAULT_PRIORITY,
|
|
50
|
+
EMPTY_USAGE,
|
|
51
|
+
MAX_CHAIN_STEPS,
|
|
52
|
+
MAX_PARALLEL_TASKS,
|
|
53
|
+
declaredThinkingLevel,
|
|
54
|
+
getFinalOutput,
|
|
55
|
+
isSubagentError,
|
|
56
|
+
type DelegateTaskDetails,
|
|
57
|
+
type DelegateTaskParams,
|
|
58
|
+
type ApprovalMode,
|
|
59
|
+
type GitMode,
|
|
60
|
+
type Priority,
|
|
61
|
+
type SubagentResult,
|
|
62
|
+
type SubagentRun,
|
|
63
|
+
type SubagentPreset,
|
|
64
|
+
type SubagentToolOptions,
|
|
65
|
+
type TaskTemplate,
|
|
66
|
+
type ThinkingLevel,
|
|
67
|
+
} from "./types";
|
|
68
|
+
import { resolveTemplate, loadBuiltinTemplates, extractParamNames } from "./templates";
|
|
69
|
+
import { pkgPath } from "./paths";
|
|
70
|
+
import { sanitizeTask, validateCwd, validateOutputFile, stripAnsi, capOutput, getCurrentDepth, buildCrashResult } from "./sanitize";
|
|
71
|
+
import {
|
|
72
|
+
hasUncommittedChanges,
|
|
73
|
+
createWorkBranch,
|
|
74
|
+
newWorkBranchName,
|
|
75
|
+
captureDiff,
|
|
76
|
+
getHeadState,
|
|
77
|
+
getRepoRoot,
|
|
78
|
+
restoreHead,
|
|
79
|
+
deleteBranch,
|
|
80
|
+
mergeWorkBranch,
|
|
81
|
+
type HeadState,
|
|
82
|
+
} from "./git";
|
|
83
|
+
import { preflightCheck } from "./preflight";
|
|
84
|
+
import {
|
|
85
|
+
depthLimitRejection,
|
|
86
|
+
formatValidationWarnings,
|
|
87
|
+
gateSessionCost,
|
|
88
|
+
invalidThinkingLevelRejection,
|
|
89
|
+
modelNotConfiguredRejection,
|
|
90
|
+
resolveSubagentModelPrecedence,
|
|
91
|
+
} from "./prelude";
|
|
92
|
+
import { loadBuiltinPresets, formatPresetRestriction, formatToolRestriction } from "./presets";
|
|
93
|
+
import { resolveTerminalRunEntry, type SessionState } from "./state";
|
|
94
|
+
import { makeLiveOnUpdate, pruneHistoryIfNeeded, registerLiveRun } from "./unit-run";
|
|
95
|
+
import { prepareRunScratch } from "./scratch-spawn";
|
|
96
|
+
import { validatePreTask, diagnoseFailure } from "./validate";
|
|
97
|
+
import {
|
|
98
|
+
defaultBackgroundFor,
|
|
99
|
+
findUnknownParams,
|
|
100
|
+
KNOWN_DELEGATE_KEYS,
|
|
101
|
+
resolveDispatchPreset,
|
|
102
|
+
resolveEffectiveApprovalMode,
|
|
103
|
+
resolveSubagentParams,
|
|
104
|
+
resolveThinkingDispatchSwitch,
|
|
105
|
+
shouldRejectBackgroundForBatch,
|
|
106
|
+
snapshotOriginalParams,
|
|
107
|
+
THINKING_SWITCH_NOTICE,
|
|
108
|
+
THINKING_TIMEOUT_DROP_NOTICE,
|
|
109
|
+
type DispatchShape,
|
|
110
|
+
} from "./params";
|
|
111
|
+
import { delegateTaskParamsSchema } from "./schema";
|
|
112
|
+
import { readProcessChecks } from "./project-flags";
|
|
113
|
+
import { buildSubagentPrompt, describePromptMode } from "./prompt";
|
|
114
|
+
import { runSubagent } from "./runner";
|
|
115
|
+
import { currentProcessOwner, newDispatchIdentity } from "./recovery";
|
|
116
|
+
import { writeHeadState, clearHeadState, HEAD_STATE_VERSION } from "./headstate";
|
|
117
|
+
import { clearInflightRun } from "./run-registry";
|
|
118
|
+
import { acquireSlot, releaseSlot } from "./concurrency";
|
|
119
|
+
import { finalizeRunRecord, resolveRetryParams } from "./history";
|
|
120
|
+
import { computeSLAMetrics, computeDegradation } from "./metrics";
|
|
121
|
+
import { showApprovalDialog, renderDelegateCall, renderDelegateResult } from "./tui";
|
|
122
|
+
import { appendWorktreeState } from "./worktree-report";
|
|
123
|
+
|
|
124
|
+
// ---------------------------------------------------------------------------
|
|
125
|
+
// Registration-time inventory summaries (moved with the guidance they feed)
|
|
126
|
+
// ---------------------------------------------------------------------------
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* DRY helper (issue #154 review): shape an inventory of items into a single
|
|
130
|
+
* comma-delimited summary line for the LLM-facing delegation guidance. Both
|
|
131
|
+
* the B1 preset-restriction summary and the B1b template summary load an
|
|
132
|
+
* inventory at registration, map each item to a formatted string, then join.
|
|
133
|
+
*/
|
|
134
|
+
export function buildInventorySummary<T>(items: T[], formatItem: (item: T) => string): string {
|
|
135
|
+
return items.map(formatItem).join(", ");
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Format one built-in template into a compact summary entry for the conductor:
|
|
140
|
+
* `name` (+ ` (lowercased description; slots ${a}, ${b})`) — the slot note is
|
|
141
|
+
* omitted when the template declares no params, and the description is omitted
|
|
142
|
+
* when it is empty. Mirrors the B1b summary shape (issue #154 review).
|
|
143
|
+
*/
|
|
144
|
+
export function formatTemplateSummaryItem(t: TaskTemplate): string {
|
|
145
|
+
const slots = [...new Set([
|
|
146
|
+
...extractParamNames(t.task),
|
|
147
|
+
...(t.outputFile ? extractParamNames(t.outputFile) : []),
|
|
148
|
+
])];
|
|
149
|
+
const slotNote = slots.length > 0
|
|
150
|
+
? `; slots ${slots.map((s) => `\${${s}}`).join(", ")}`
|
|
151
|
+
: "";
|
|
152
|
+
const desc = t.description
|
|
153
|
+
? `${t.description.charAt(0).toLowerCase()}${t.description.slice(1)}`
|
|
154
|
+
: "";
|
|
155
|
+
return `${t.name}${desc ? ` (${desc}${slotNote})` : slotNote}`;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Render the template guideline line with the built-in inventory summary
|
|
160
|
+
* interpolated. Exported so the guidance test can assert the RENDERED text
|
|
161
|
+
* rather than the literal `${templateSummary}` placeholder that a double-quoted
|
|
162
|
+
* string would leave in the conductor-facing guidance (issue #154 review).
|
|
163
|
+
*/
|
|
164
|
+
export function buildTemplateGuideline(templateSummary: string): string {
|
|
165
|
+
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.`;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* What the dispatch needs from the composition root. Every entry is an instance
|
|
170
|
+
* `index.ts` already built — see the header's instance-identity note. The types
|
|
171
|
+
* are the factories' own return members (`ReturnType<…>` on a type-only import),
|
|
172
|
+
* so this seam cannot drift from the functions it names.
|
|
173
|
+
*/
|
|
174
|
+
export interface DelegateHandlerDeps {
|
|
175
|
+
/** S2: the three foreground batch runners. */
|
|
176
|
+
runChainMode: ReturnType<typeof createModeRunners>["runChainMode"];
|
|
177
|
+
runParallelMode: ReturnType<typeof createModeRunners>["runParallelMode"];
|
|
178
|
+
runGraphMode: ReturnType<typeof createModeRunners>["runGraphMode"];
|
|
179
|
+
/** S3: the background fan-out (the `tasks` shape) — one spawn queue. */
|
|
180
|
+
runBackgroundFanOut: ReturnType<typeof createBackgroundPipeline>["runBackgroundFanOut"];
|
|
181
|
+
/** S3: the single-task background spawn (`useBackground` on the single shape). */
|
|
182
|
+
spawnBackgroundRun: ReturnType<typeof createBackgroundPipeline>["spawnBackgroundRun"];
|
|
183
|
+
/** S4: the run-visibility bridge the retry restore resolves through. */
|
|
184
|
+
visibleRunsFor: ReturnType<typeof createBootRecovery>["visibleRunsFor"];
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* The definition `pi.registerTool` consumes. The two generics are the ones the
|
|
189
|
+
* inline literal used to have inferred for it: the params schema (so `execute`
|
|
190
|
+
* keeps its `DelegateTaskParams` parameter and `renderCall`/`renderResult` their
|
|
191
|
+
* `Static<…>` shapes) and the details type the result/update callbacks carry.
|
|
192
|
+
*/
|
|
193
|
+
export type DelegateTaskTool = ToolDefinition<
|
|
194
|
+
typeof delegateTaskParamsSchema,
|
|
195
|
+
DelegateTaskDetails
|
|
196
|
+
>;
|
|
197
|
+
|
|
198
|
+
// ---------------------------------------------------------------------------
|
|
199
|
+
// Dispatch seams (issue #430) — private to this module, driven by `execute`
|
|
200
|
+
// ---------------------------------------------------------------------------
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* What `execute` returns: `ToolDefinition`'s result for this tool. Named once
|
|
204
|
+
* so an `Outcome` can carry an early rejection without re-spelling the
|
|
205
|
+
* `AgentToolResult<DelegateTaskDetails>` generic at every seam boundary.
|
|
206
|
+
*/
|
|
207
|
+
type ToolResult = AgentToolResult<DelegateTaskDetails>;
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* The seam result type: either the value the next seam needs, or a finished
|
|
211
|
+
* tool result the caller returns unchanged.
|
|
212
|
+
*
|
|
213
|
+
* A rejection is a RETURNED result rather than a thrown error because every
|
|
214
|
+
* early exit in the original body returned a tool result. Throwing would land
|
|
215
|
+
* in the foreground `catch`, which builds a crash result — the caller would
|
|
216
|
+
* see different content, and the trace contract (issue #430) forbids that.
|
|
217
|
+
*/
|
|
218
|
+
type Outcome<T> = { ok: true; value: T } | { ok: false; result: ToolResult };
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* What seam A reads from its surroundings. A narrow `Pick`-style object, not
|
|
222
|
+
* the whole `RuntimeContext`: A needs `ctx`/`pi` for the retry lookup and the
|
|
223
|
+
* two notification channels, and `visibleRunsFor` for the registry fallback.
|
|
224
|
+
*/
|
|
225
|
+
interface NormalizeDeps {
|
|
226
|
+
state: SessionState;
|
|
227
|
+
ctx: ExtensionContext;
|
|
228
|
+
pi: ExtensionAPI;
|
|
229
|
+
log: Logger;
|
|
230
|
+
/** S4's run-visibility bridge — the retry restore's post-boot fallback. */
|
|
231
|
+
visibleRunsFor: DelegateHandlerDeps["visibleRunsFor"];
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** Seam A's value: the resolved inputs every later seam reads. */
|
|
235
|
+
interface NormalizedDispatch {
|
|
236
|
+
/** The original object (mutated in place) or the retry-rebound replacement. */
|
|
237
|
+
params: DelegateTaskParams;
|
|
238
|
+
/** The run a `retryRunId` resolved to — identity and source retirement. */
|
|
239
|
+
retrySourceRun: SubagentRun | undefined;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** Seam B's value: the sanitized params plus the one shape the dispatch names. */
|
|
243
|
+
interface DispatchSelection {
|
|
244
|
+
/** The same object seam A produced (the sanitizer writes `params.task`). */
|
|
245
|
+
params: DelegateTaskParams;
|
|
246
|
+
isChain: boolean;
|
|
247
|
+
isParallel: boolean;
|
|
248
|
+
isGraph: boolean;
|
|
249
|
+
dispatchShape: DispatchShape;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Seam A1 — the unknown-param warning (issues #99/#110).
|
|
254
|
+
*
|
|
255
|
+
* Typebox allows additional properties by default (pi's validateToolArguments
|
|
256
|
+
* passes unknown keys through), so a typo like `thinkinglevel` or a
|
|
257
|
+
* schema-drifted param is otherwise silently ignored. Warn-not-reject: never
|
|
258
|
+
* break a delegation. Both channels speak — `log.warn` for the file, and
|
|
259
|
+
* `pi.sendMessage` because pi's TUI swallows extension console output, so the
|
|
260
|
+
* LLM (followUp) and the human (session transcript) both see the correction.
|
|
261
|
+
*/
|
|
262
|
+
function warnUnknownParams(
|
|
263
|
+
params: DelegateTaskParams,
|
|
264
|
+
deps: Pick<NormalizeDeps, "pi" | "log">,
|
|
265
|
+
): void {
|
|
266
|
+
const { pi, log } = deps;
|
|
267
|
+
const unknownKeys = findUnknownParams(params, KNOWN_DELEGATE_KEYS);
|
|
268
|
+
if (unknownKeys.length === 0) return;
|
|
269
|
+
log.warn("delegate_task: unknown param(s) ignored — check spelling or add to schema", { unknown: unknownKeys });
|
|
270
|
+
pi.sendMessage({
|
|
271
|
+
customType: "delegate-notification",
|
|
272
|
+
content: `delegate_task: unknown param(s) ignored — check spelling or add to schema: ${unknownKeys.join(", ")}`,
|
|
273
|
+
display: true,
|
|
274
|
+
details: { unknown: unknownKeys },
|
|
275
|
+
}, { deliverAs: "followUp" });
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* Seam A2 — apply a task template to the dispatch params (issues #57/#175).
|
|
280
|
+
*
|
|
281
|
+
* MUST run before the single-mode sanitize seam: a template ASSIGNS
|
|
282
|
+
* `params.task`, so resolving first lets the sanitizer validate the real
|
|
283
|
+
* resolved body (a template-only call has no task yet) and lets mode detection
|
|
284
|
+
* see a non-empty task.
|
|
285
|
+
*
|
|
286
|
+
* Two rules that look contradictory and are not: the resolved BODY is
|
|
287
|
+
* template-wins (it replaces any supplied `task` unconditionally — issue #57),
|
|
288
|
+
* while the template's other fields are DEFAULTS an explicit param overrides.
|
|
289
|
+
* A supplied task the sanitizer would have rejected is reported rather than
|
|
290
|
+
* silently dropped — but only when it would actually have failed, so a valid
|
|
291
|
+
* task alongside a template stays the intended override, not noise.
|
|
292
|
+
*
|
|
293
|
+
* Mutates `params` and returns the same object's outcome; no notice is a value.
|
|
294
|
+
*/
|
|
295
|
+
function applyTemplate(
|
|
296
|
+
params: DelegateTaskParams,
|
|
297
|
+
templates: readonly TaskTemplate[],
|
|
298
|
+
deps: Pick<NormalizeDeps, "pi" | "log">,
|
|
299
|
+
): Outcome<void> {
|
|
300
|
+
const { pi, log } = deps;
|
|
301
|
+
if (!params.template) return { ok: true, value: undefined };
|
|
302
|
+
|
|
303
|
+
const templateEntry = templates.find((t) => t.name === params.template);
|
|
304
|
+
if (!templateEntry) {
|
|
305
|
+
const available = templates.map((t) => t.name).join(", ") || "none";
|
|
306
|
+
return {
|
|
307
|
+
ok: false,
|
|
308
|
+
result: {
|
|
309
|
+
content: [
|
|
310
|
+
{
|
|
311
|
+
type: "text" as const,
|
|
312
|
+
text: `Template '${params.template}' not found. Available: ${available}`,
|
|
313
|
+
},
|
|
314
|
+
],
|
|
315
|
+
details: undefined,
|
|
316
|
+
isError: true,
|
|
317
|
+
},
|
|
318
|
+
};
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
const resolved = resolveTemplate(templateEntry, params.params ?? {});
|
|
322
|
+
if (!resolved.ok) {
|
|
323
|
+
return {
|
|
324
|
+
ok: false,
|
|
325
|
+
result: {
|
|
326
|
+
content: [
|
|
327
|
+
{
|
|
328
|
+
type: "text" as const,
|
|
329
|
+
text: `Template '${params.template}' resolution failed: ${resolved.error}`,
|
|
330
|
+
},
|
|
331
|
+
],
|
|
332
|
+
details: undefined,
|
|
333
|
+
isError: true,
|
|
334
|
+
},
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
const tv = resolved.value;
|
|
339
|
+
// Issue #175 review (fix 4): template-wins silently replaces a supplied
|
|
340
|
+
// `task`. If that task would itself have failed sanitization (e.g.
|
|
341
|
+
// over-length), the caller gets no signal — pre-#175 `dev` rejected it.
|
|
342
|
+
// Warn (never reject — #99/#110 precedent, same pi.sendMessage channel as
|
|
343
|
+
// the unknown-param warning) so both the LLM and the human see the ignored
|
|
344
|
+
// task. Emitted ONLY when the supplied task actually fails sanitization: a
|
|
345
|
+
// valid task alongside a template is the intended template-wins override
|
|
346
|
+
// (issue #57), not noise.
|
|
347
|
+
if (params.task !== undefined) {
|
|
348
|
+
const suppliedTask = sanitizeTask(params.task);
|
|
349
|
+
if (!suppliedTask.ok) {
|
|
350
|
+
log.warn("delegate_task: supplied task ignored because a template was given", {
|
|
351
|
+
template: params.template,
|
|
352
|
+
error: suppliedTask.error,
|
|
353
|
+
});
|
|
354
|
+
pi.sendMessage({
|
|
355
|
+
customType: "delegate-notification",
|
|
356
|
+
content: `delegate_task: the supplied 'task' was ignored because a template ('${params.template}') was given. The task would otherwise have been rejected: ${suppliedTask.error}`,
|
|
357
|
+
display: true,
|
|
358
|
+
details: { template: params.template, rejectedTask: suppliedTask.error },
|
|
359
|
+
}, { deliverAs: "followUp" });
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
// Issue #175 review (fix direction item 4): this assignment is
|
|
363
|
+
// UNCONDITIONAL — the resolved template task replaces any supplied `task`
|
|
364
|
+
// (template-wins, issue #57); it is NOT a default the caller can override.
|
|
365
|
+
// The fields below, by contrast, ARE defaults: an explicitly provided param
|
|
366
|
+
// wins over the template's value.
|
|
367
|
+
params.task = tv.task;
|
|
368
|
+
if (tv.preset && !params.preset) params.preset = tv.preset;
|
|
369
|
+
if (tv.thinkingLevel && !params.thinkingLevel) params.thinkingLevel = tv.thinkingLevel;
|
|
370
|
+
if (tv.outputFile && !params.outputFile) params.outputFile = tv.outputFile;
|
|
371
|
+
if (tv.timeout !== undefined && params.timeout === undefined) params.timeout = tv.timeout;
|
|
372
|
+
if (tv.tools && !params.tools) params.tools = tv.tools;
|
|
373
|
+
if (tv.excludeTools && !params.excludeTools) params.excludeTools = tv.excludeTools;
|
|
374
|
+
if (tv.noBuiltinTools !== undefined && params.noBuiltinTools === undefined) params.noBuiltinTools = tv.noBuiltinTools;
|
|
375
|
+
if (tv.inheritSystemPrompt !== undefined && params.inheritSystemPrompt === undefined) params.inheritSystemPrompt = tv.inheritSystemPrompt;
|
|
376
|
+
return { ok: true, value: undefined };
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/**
|
|
380
|
+
* Seam A — resolve the dispatch inputs: unknown-param warning, template
|
|
381
|
+
* resolution, retry restore (issue #430).
|
|
382
|
+
*
|
|
383
|
+
* ORDER IS THE CONTRACT. Template resolution MUST run first: it ASSIGNS
|
|
384
|
+
* `params.task`, so the sanitizer in seam B validates the real resolved body
|
|
385
|
+
* and mode detection sees a non-empty task (issue #175). The retry restore
|
|
386
|
+
* MUST run after it: `resolveRetryParams` returns a fresh object that DROPS
|
|
387
|
+
* `template`, so resolving first keeps a combined template + retryRunId call
|
|
388
|
+
* from silently disabling template resolution (issue #175 review).
|
|
389
|
+
*
|
|
390
|
+
* RETURNS SYNCHRONOUSLY unless the retry needs the visibility bridge. The lazy
|
|
391
|
+
* `import('./session-manager')` is the only asynchronous arm and is entered
|
|
392
|
+
* only when the session store has no entry for the id — an unconditional
|
|
393
|
+
* `async` here would suspend every dispatch a microtask earlier than it ran
|
|
394
|
+
* before, which the S6 timing probe pins (issue #430 amendment 2).
|
|
395
|
+
*/
|
|
396
|
+
function normalizeInput(
|
|
397
|
+
params: DelegateTaskParams,
|
|
398
|
+
deps: NormalizeDeps,
|
|
399
|
+
): Outcome<NormalizedDispatch> | Promise<Outcome<NormalizedDispatch>> {
|
|
400
|
+
const { state, ctx, pi, log, visibleRunsFor } = deps;
|
|
401
|
+
|
|
402
|
+
// A1: the two pre-resolution notices (unknown keys, ignored task) and the
|
|
403
|
+
// template application itself.
|
|
404
|
+
warnUnknownParams(params, { pi, log });
|
|
405
|
+
const templated = applyTemplate(params, state.config.templates, { pi, log });
|
|
406
|
+
if (!templated.ok) return templated;
|
|
407
|
+
|
|
408
|
+
// Handle retryRunId — MUST run after template resolution and before the
|
|
409
|
+
// single-mode sanitize block. resolveRetryParams assigns params.task from
|
|
410
|
+
// the recorded run, so the sanitizer must see the retried body (a
|
|
411
|
+
// retry-only call has no task yet). It MUST run AFTER template resolution:
|
|
412
|
+
// resolveRetryParams returns a fresh object that DROPS `template`, so
|
|
413
|
+
// resolving templates first keeps a combined template + retryRunId call
|
|
414
|
+
// from silently disabling template resolution (issue #175 review).
|
|
415
|
+
if (!params.retryRunId) {
|
|
416
|
+
return { ok: true, value: { params, retrySourceRun: undefined } };
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
const retryRunId = params.retryRunId;
|
|
420
|
+
// Fix A: prefer the session spawn entry (it carries `originalParams`);
|
|
421
|
+
// a run that exists ONLY in the durable registry after a fresh boot
|
|
422
|
+
// resolves through the visibility bridge instead of being rejected as
|
|
423
|
+
// not found — the id the boot notice names must resolve here.
|
|
424
|
+
const sessionEntry = state.findSpawnRunById(ctx, retryRunId);
|
|
425
|
+
if (sessionEntry) return resolveRetrySource(params, retryRunId, sessionEntry, log);
|
|
426
|
+
|
|
427
|
+
// The one asynchronous arm. `then` keeps the continuation in the turn the
|
|
428
|
+
// original `await import(...)` resumed in; only the caller's own `await`
|
|
429
|
+
// of this promise adds a turn, and only on this path (the import already
|
|
430
|
+
// suspends through the module loader, so that turn is inside an existing
|
|
431
|
+
// suspension — see the S6 timing probe).
|
|
432
|
+
return import("./session-manager").then(({ getAgent }) =>
|
|
433
|
+
resolveRetrySource(
|
|
434
|
+
params,
|
|
435
|
+
retryRunId,
|
|
436
|
+
resolveTerminalRunEntry(visibleRunsFor(ctx, getAgent), retryRunId),
|
|
437
|
+
log,
|
|
438
|
+
),
|
|
439
|
+
);
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/**
|
|
443
|
+
* The tail of the retry restore, shared by the session hit and the visibility
|
|
444
|
+
* bridge so the two cannot diverge on the not-found message (issue #98: a
|
|
445
|
+
* silent no-op here made retries of background runs start as FRESH runs with
|
|
446
|
+
* no signal to the caller).
|
|
447
|
+
*/
|
|
448
|
+
function resolveRetrySource(
|
|
449
|
+
params: DelegateTaskParams,
|
|
450
|
+
retryRunId: string,
|
|
451
|
+
runEntry: SubagentRun | undefined,
|
|
452
|
+
log: Logger,
|
|
453
|
+
): Outcome<NormalizedDispatch> {
|
|
454
|
+
if (runEntry) {
|
|
455
|
+
return {
|
|
456
|
+
ok: true,
|
|
457
|
+
value: {
|
|
458
|
+
params: resolveRetryParams(params, runEntry) as DelegateTaskParams,
|
|
459
|
+
retrySourceRun: runEntry,
|
|
460
|
+
},
|
|
461
|
+
};
|
|
462
|
+
}
|
|
463
|
+
log.warn("Retry run ID not found", { retryRunId });
|
|
464
|
+
return {
|
|
465
|
+
ok: false,
|
|
466
|
+
result: {
|
|
467
|
+
content: [{
|
|
468
|
+
type: "text" as const,
|
|
469
|
+
text: `Retry run ID not found: ${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.`,
|
|
470
|
+
}],
|
|
471
|
+
details: undefined,
|
|
472
|
+
isError: true,
|
|
473
|
+
},
|
|
474
|
+
};
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
/**
|
|
478
|
+
* Seam B — sanitize the single-task body and classify the dispatch shape
|
|
479
|
+
* (issue #430).
|
|
480
|
+
*
|
|
481
|
+
* Mutates `params.task` to the sanitizer's value and then reads that value for
|
|
482
|
+
* `isSingle`, exactly as the inline block did: the sanitizer's trim/normalize
|
|
483
|
+
* is what makes " " a rejection rather than a single-task dispatch. The
|
|
484
|
+
* shape flags stay the raw `params.chain/tasks/graph` truthiness tests; the
|
|
485
|
+
* exactly-one check is what turns them into a dispatch.
|
|
486
|
+
*/
|
|
487
|
+
function resolveShape(
|
|
488
|
+
params: DelegateTaskParams,
|
|
489
|
+
log: Logger,
|
|
490
|
+
): Outcome<DispatchSelection> {
|
|
491
|
+
// F1: Sanitize task input — skip for chain/parallel/graph modes
|
|
492
|
+
const hasChain = params.chain && params.chain.length > 0;
|
|
493
|
+
const hasParallel = params.tasks && params.tasks.length > 0;
|
|
494
|
+
const hasGraph = params.graph && params.graph.length > 0;
|
|
495
|
+
if (!hasChain && !hasParallel && !hasGraph) {
|
|
496
|
+
// task is optional per the schema; single mode requires it. When absent,
|
|
497
|
+
// feed "" to the sanitizer — same rejection path ("Task must not be
|
|
498
|
+
// empty.") as when task was a required field.
|
|
499
|
+
const taskResult = sanitizeTask(params.task ?? "");
|
|
500
|
+
if (!taskResult.ok) {
|
|
501
|
+
log.warn("Task rejected by sanitizer", { error: taskResult.error });
|
|
502
|
+
return {
|
|
503
|
+
ok: false,
|
|
504
|
+
result: {
|
|
505
|
+
content: [{ type: "text" as const, text: `Invalid task: ${taskResult.error}` }],
|
|
506
|
+
details: undefined,
|
|
507
|
+
isError: true,
|
|
508
|
+
},
|
|
509
|
+
};
|
|
510
|
+
}
|
|
511
|
+
params.task = taskResult.value;
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
// P1+P2+P10: Mode detection — graph > chain > parallel > single
|
|
515
|
+
const isChain = Boolean(hasChain);
|
|
516
|
+
const isParallel = Boolean(hasParallel);
|
|
517
|
+
const isGraph = Boolean(hasGraph);
|
|
518
|
+
const isSingle = typeof params.task === "string" && params.task.length > 0;
|
|
519
|
+
|
|
520
|
+
const modeCount = [isChain, isParallel, isGraph, isSingle].filter(Boolean).length;
|
|
521
|
+
if (modeCount !== 1) {
|
|
522
|
+
return {
|
|
523
|
+
ok: false,
|
|
524
|
+
result: {
|
|
525
|
+
content: [
|
|
526
|
+
{
|
|
527
|
+
type: "text" as const,
|
|
528
|
+
text:
|
|
529
|
+
"Provide exactly one of: task (single), chain (sequential), tasks (parallel), or graph (dependency graph).",
|
|
530
|
+
},
|
|
531
|
+
],
|
|
532
|
+
details: undefined,
|
|
533
|
+
isError: true,
|
|
534
|
+
},
|
|
535
|
+
};
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
const dispatchShape: DispatchShape = isChain
|
|
539
|
+
? "chain"
|
|
540
|
+
: isGraph
|
|
541
|
+
? "graph"
|
|
542
|
+
: isParallel
|
|
543
|
+
? "parallel"
|
|
544
|
+
: "single";
|
|
545
|
+
|
|
546
|
+
return { ok: true, value: { params, isChain, isParallel, isGraph, dispatchShape } };
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/** What seam C reads from its surroundings — the #412 pre-flight's inputs. */
|
|
550
|
+
interface ShapeDeps {
|
|
551
|
+
state: SessionState;
|
|
552
|
+
ctx: ExtensionContext;
|
|
553
|
+
pi: ExtensionAPI;
|
|
554
|
+
log: Logger;
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/** Seam C's value: the routing decisions every downstream seam reads. */
|
|
558
|
+
interface ShapePreparation {
|
|
559
|
+
/** Whether the dispatch runs detached (background) or blocks (foreground). */
|
|
560
|
+
useBackground: boolean;
|
|
561
|
+
/** The #434 unit-projection inputs the batch runners consume. */
|
|
562
|
+
batchGuard: BatchGuardContext;
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
/**
|
|
566
|
+
* Seam C — the dispatch pre-flight and the background default (issues #361,
|
|
567
|
+
* #412, #415, #431, #434, #443) — plus the recorded background decision.
|
|
568
|
+
*
|
|
569
|
+
* This is the seam where the dispatch can be CHANGED (the #412 high-thinking
|
|
570
|
+
* switch / #431 timeout drop) and REJECTED (a declared thinking level outside
|
|
571
|
+
* the cap, an explicit `background: true` batch). The order is load-bearing:
|
|
572
|
+
*
|
|
573
|
+
* 1. `explicitBackground` is captured BEFORE the default is recorded on
|
|
574
|
+
* `params.background` — the batch guard judges what the caller asked for,
|
|
575
|
+
* not what the default made true;
|
|
576
|
+
* 2. the switch is applied BEFORE `useBackground` resolves and before any
|
|
577
|
+
* run record exists, so the spawn, the retry snapshot and the pending-work
|
|
578
|
+
* record all see the switched shape;
|
|
579
|
+
* 3. `useBackground` resolves ONCE (single + fan-out share it) from the
|
|
580
|
+
* EFFECTIVE approval mode, so the default can never route a run into a
|
|
581
|
+
* background context that needs an interactive gate;
|
|
582
|
+
* 4. `batchGuard` closes over the switch outcome so a unit never re-announces
|
|
583
|
+
* a notice the dispatch already delivered.
|
|
584
|
+
*
|
|
585
|
+
* Effects: `log.*`, `pi.sendMessage` and `ctx.ui.notify` on the switch arms;
|
|
586
|
+
* `params.background`/`params.timeout` mutations. Returns the caller's
|
|
587
|
+
* rejection unchanged when a gate trips.
|
|
588
|
+
*/
|
|
589
|
+
function prepareShape(
|
|
590
|
+
params: DelegateTaskParams,
|
|
591
|
+
shape: Pick<DispatchSelection, "dispatchShape" | "isParallel">,
|
|
592
|
+
deps: ShapeDeps,
|
|
593
|
+
): Outcome<ShapePreparation> {
|
|
594
|
+
const { state, ctx, pi, log } = deps;
|
|
595
|
+
const { dispatchShape, isParallel } = shape;
|
|
596
|
+
|
|
597
|
+
// Capture the caller's value BEFORE the default is recorded on
|
|
598
|
+
// `params.background` below. The guard must judge what the caller
|
|
599
|
+
// actually asked for; reading the recorded value would make it depend
|
|
600
|
+
// on the default. Keeping the capture first makes that ordering
|
|
601
|
+
// self-evident (issue #361 review).
|
|
602
|
+
const explicitBackground = params.background;
|
|
603
|
+
|
|
604
|
+
// Issue #412 (rule 2: "no deadline ⇒ durable path") — the dispatch-shape
|
|
605
|
+
// pre-flight. A high/xhigh-thinking run the conductor asked to run
|
|
606
|
+
// FOREGROUND with an explicit timeout is the shape that lost 14 minutes of
|
|
607
|
+
// plan critique on 2026-10-31: foreground runs persist nothing, so the
|
|
608
|
+
// deadline kills the work outright, while a background run keeps its
|
|
609
|
+
// session and is retried on a transport error. The switch is applied HERE
|
|
610
|
+
// — after template/retry resolution and BEFORE `useBackground` is resolved
|
|
611
|
+
// and before any run record is written — so the shape every downstream
|
|
612
|
+
// reader sees (the spawn, the retry snapshot, the pending-work record) is
|
|
613
|
+
// the switched one. Moving it after `snapshotOriginalParams` would record
|
|
614
|
+
// `background:false` and silently cost the run its transport auto-retry
|
|
615
|
+
// (`transport-retry.ts` classifies off that snapshot).
|
|
616
|
+
// Issue #415: the switch is OUR process (a conductor decision rule), not
|
|
617
|
+
// product behavior — a user's explicit foreground timeout is usually a
|
|
618
|
+
// budget cap, so a GLOBAL switch could triple time and cost against
|
|
619
|
+
// their instruction. The umbrella project-local `processChecks` flag
|
|
620
|
+
// gates it (fail-open: no/malformed manifest → off). Resolve the
|
|
621
|
+
// dispatch cwd ONCE, the way the target validation below will.
|
|
622
|
+
const processChecksCwd =
|
|
623
|
+
params.cwd === undefined ? ctx.cwd : path.resolve(ctx.cwd, params.cwd);
|
|
624
|
+
const processChecks = readProcessChecks(processChecksCwd);
|
|
625
|
+
// The preset the dispatch will actually run with — an auto-routed
|
|
626
|
+
// `code-reviewer`/`debugger` is a high-thinking run even though the
|
|
627
|
+
// caller declared no level, so the pre-flight resolves the SAME preset
|
|
628
|
+
// the merge below will (one rule, `resolveDispatchPreset`).
|
|
629
|
+
const declaredPresetForSwitch = resolveDispatchPreset(params, state).preset;
|
|
630
|
+
// Issue #443: guard the EFFECTIVE DECLARED level here — the per-call value
|
|
631
|
+
// or the selected preset's (named, or auto-routed by the line above) —
|
|
632
|
+
// BEFORE `resolveSubagentParams` clamps it. `params.thinkingLevel` is
|
|
633
|
+
// already the post-template, post-`retryRunId` value by this point, so a
|
|
634
|
+
// level restored from a run record is judged too; a preset object injected
|
|
635
|
+
// in memory never passed a schema or the preset-file validator, so this
|
|
636
|
+
// is its only check. Everything below runs through this one seam: the
|
|
637
|
+
// single, background, chain, parallel and graph handlers are all reached
|
|
638
|
+
// from here, and the per-unit declarations are guarded by the pre-passes.
|
|
639
|
+
const effectiveDeclaredThinkingLevel = declaredThinkingLevel(
|
|
640
|
+
params.thinkingLevel,
|
|
641
|
+
declaredPresetForSwitch?.thinkingLevel,
|
|
642
|
+
);
|
|
643
|
+
const declaredThinkingError = invalidThinkingLevelRejection(effectiveDeclaredThinkingLevel);
|
|
644
|
+
if (declaredThinkingError) return { ok: false, result: declaredThinkingError };
|
|
645
|
+
// The EFFECTIVE approval mode (call param, else the configured default) —
|
|
646
|
+
// the same resolver `resolveSubagentParams` and the #361 default use, so the
|
|
647
|
+
// pre-flight cannot judge a mode the child will not run with. Reading
|
|
648
|
+
// `params.approvalMode` raw here would miss a config-tier mode entirely.
|
|
649
|
+
const effectiveApprovalModeForSwitch = resolveEffectiveApprovalMode(
|
|
650
|
+
params.approvalMode,
|
|
651
|
+
state,
|
|
652
|
+
);
|
|
653
|
+
const thinkingSwitch = resolveThinkingDispatchSwitch({
|
|
654
|
+
processChecks,
|
|
655
|
+
thinkingLevel: effectiveDeclaredThinkingLevel as ThinkingLevel | undefined,
|
|
656
|
+
explicitBackground,
|
|
657
|
+
timeout: params.timeout,
|
|
658
|
+
force: params.force,
|
|
659
|
+
shape: dispatchShape,
|
|
660
|
+
effectiveApprovalMode: effectiveApprovalModeForSwitch,
|
|
661
|
+
});
|
|
662
|
+
if (thinkingSwitch === "switch") {
|
|
663
|
+
params.background = true;
|
|
664
|
+
// Drop the foreground deadline: the 30-minute background default
|
|
665
|
+
// (DEFAULT_BACKGROUND_DEADLINE_MS) applies instead. Recorded as
|
|
666
|
+
// undefined, so a retry re-derives it rather than restoring the cap.
|
|
667
|
+
params.timeout = undefined;
|
|
668
|
+
log.info("Dispatch pre-flight: high-thinking foreground switched to background", {
|
|
669
|
+
thinkingLevel: params.thinkingLevel,
|
|
670
|
+
timeout: "dropped (background default applies)",
|
|
671
|
+
});
|
|
672
|
+
pi.sendMessage({
|
|
673
|
+
customType: "delegate-notification",
|
|
674
|
+
content: THINKING_SWITCH_NOTICE,
|
|
675
|
+
display: true,
|
|
676
|
+
details: { thinkingLevel: params.thinkingLevel, previousTimeout: "dropped" },
|
|
677
|
+
}, { deliverAs: "followUp" });
|
|
678
|
+
ctx.ui.notify(THINKING_SWITCH_NOTICE, "warning");
|
|
679
|
+
} else if (thinkingSwitch === "drop-timeout") {
|
|
680
|
+
// Issue #431 — the second arm: the shape cannot move (an effective
|
|
681
|
+
// 'always'/'writes' run needs the interactive gate, and switching an
|
|
682
|
+
// explicit-foreground 'always' dispatch would be REJECTED — #433), so
|
|
683
|
+
// the only thing the pre-flight can remove is the deadline. Clearing it
|
|
684
|
+
// HERE, before `snapshotOriginalParams` records the run (:3035
|
|
685
|
+
// foreground, :2374 background), is what makes a retry re-derive an
|
|
686
|
+
// absent deadline instead of restoring the cap (ADR 0009).
|
|
687
|
+
const previousTimeout = params.timeout;
|
|
688
|
+
params.timeout = undefined;
|
|
689
|
+
log.info("Dispatch pre-flight: high-thinking foreground timeout dropped, shape kept", {
|
|
690
|
+
thinkingLevel: params.thinkingLevel,
|
|
691
|
+
previousTimeout,
|
|
692
|
+
effectiveApprovalMode: effectiveApprovalModeForSwitch,
|
|
693
|
+
});
|
|
694
|
+
pi.sendMessage({
|
|
695
|
+
customType: "delegate-notification",
|
|
696
|
+
content: THINKING_TIMEOUT_DROP_NOTICE,
|
|
697
|
+
display: true,
|
|
698
|
+
details: {
|
|
699
|
+
thinkingLevel: params.thinkingLevel,
|
|
700
|
+
// The ACTUAL ms value, not "dropped": the friction log needs the
|
|
701
|
+
// number to tell a budget cap from a tight clock.
|
|
702
|
+
previousTimeout,
|
|
703
|
+
effectiveApprovalMode: effectiveApprovalModeForSwitch,
|
|
704
|
+
},
|
|
705
|
+
}, { deliverAs: "followUp" });
|
|
706
|
+
ctx.ui.notify(THINKING_TIMEOUT_DROP_NOTICE, "warning");
|
|
707
|
+
} else if (thinkingSwitch === "forced") {
|
|
708
|
+
// The override is recorded, not silent: the dispatch text is the reason
|
|
709
|
+
// (`force` has no reason field — ADR 0007's contract stays unchanged).
|
|
710
|
+
log.info("Dispatch pre-flight: high-thinking foreground forced", {
|
|
711
|
+
thinkingLevel: params.thinkingLevel,
|
|
712
|
+
timeout: params.timeout,
|
|
713
|
+
});
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
// background: true with chain/graph was silently ignored — the batch ran
|
|
717
|
+
// foreground (blocking until every unit finished) while the caller believed
|
|
718
|
+
// it was background. Both remain rejected loudly at dispatch validation;
|
|
719
|
+
// tasks (parallel) fans out into independent background agents instead.
|
|
720
|
+
// Only an EXPLICIT true trips this (issue #361): an omitted `background`
|
|
721
|
+
// now defaults to foreground here rather than being rejected.
|
|
722
|
+
if (shouldRejectBackgroundForBatch(dispatchShape, explicitBackground)) {
|
|
723
|
+
const batchMode = dispatchShape === "chain" ? "chain" : "graph";
|
|
724
|
+
return {
|
|
725
|
+
ok: false,
|
|
726
|
+
result: {
|
|
727
|
+
content: [
|
|
728
|
+
{
|
|
729
|
+
type: "text" as const,
|
|
730
|
+
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.`,
|
|
731
|
+
},
|
|
732
|
+
],
|
|
733
|
+
details: undefined,
|
|
734
|
+
isError: true,
|
|
735
|
+
},
|
|
736
|
+
};
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
// Issue #361: background is the CONDITIONAL default for the shapes that
|
|
740
|
+
// can run unattended. Resolved ONCE per dispatch and reused by the
|
|
741
|
+
// single and fan-out paths below, so the decision cannot drift between
|
|
742
|
+
// them. The approval mode is the EFFECTIVE one (call param, else the
|
|
743
|
+
// configured default — presets declare no approvalMode today) — the same
|
|
744
|
+
// value the child will run with — so the default never routes a run into a
|
|
745
|
+
// background context that would break or silently auto-approve it
|
|
746
|
+
// ('always' has no dialog; 'writes' gates the diff on approval).
|
|
747
|
+
const useBackground =
|
|
748
|
+
params.background ??
|
|
749
|
+
defaultBackgroundFor(dispatchShape, resolveEffectiveApprovalMode(params.approvalMode, state));
|
|
750
|
+
// Record the EFFECTIVE value on the dispatch (a no-op when the caller was
|
|
751
|
+
// explicit): a run started by the default must retry as what it actually
|
|
752
|
+
// was instead of re-deriving the default, which may since have moved with
|
|
753
|
+
// the config. Fan-out units still record no background of their own — a
|
|
754
|
+
// unit retries as a single foreground run (issue #229), unaffected here.
|
|
755
|
+
params.background ??= useBackground;
|
|
756
|
+
|
|
757
|
+
// Issue #434: the unit projection's inputs, resolved ONCE here so no
|
|
758
|
+
// unit site can re-derive them (a relative `params.cwd` re-read of the
|
|
759
|
+
// manifest measured `false` where this resolution measured `true`).
|
|
760
|
+
// `noticeEmitted` starts true when the DISPATCH arm announced its own
|
|
761
|
+
// change: the drop still reaches every eligible unit, but the dispatch
|
|
762
|
+
// already spoke, and a second notice would double-report one decision.
|
|
763
|
+
// (`forced` emits nothing — the caller asked for the explicit pair, so
|
|
764
|
+
// there is nothing to announce and no arm acted.)
|
|
765
|
+
const batchGuard: BatchGuardContext = {
|
|
766
|
+
processChecks,
|
|
767
|
+
dispatchDeclaredLevel: effectiveDeclaredThinkingLevel as ThinkingLevel | undefined,
|
|
768
|
+
force: params.force as boolean | undefined,
|
|
769
|
+
// A `tasks` fan-out spawns detached background units (their deadline is
|
|
770
|
+
// the legitimate budget); every other batch handler runs its units
|
|
771
|
+
// foreground. Chain/graph can never be background: an explicit
|
|
772
|
+
// `background: true` batch was rejected above.
|
|
773
|
+
unitShape: isParallel && useBackground ? "background" : "foreground",
|
|
774
|
+
noticeEmitted: thinkingSwitch === "switch" || thinkingSwitch === "drop-timeout",
|
|
775
|
+
};
|
|
776
|
+
|
|
777
|
+
return { ok: true, value: { useBackground, batchGuard } };
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
/** The injected entry points seam D routes to (the composition root's instances). */
|
|
781
|
+
type RouteRunners = Pick<
|
|
782
|
+
DelegateHandlerDeps,
|
|
783
|
+
"runChainMode" | "runParallelMode" | "runGraphMode" | "runBackgroundFanOut" | "spawnBackgroundRun"
|
|
784
|
+
>;
|
|
785
|
+
|
|
786
|
+
/** What seam D reads: the tool call's live arguments and the injected runners. */
|
|
787
|
+
interface RouteDeps {
|
|
788
|
+
pi: ExtensionAPI;
|
|
789
|
+
ctx: ExtensionContext;
|
|
790
|
+
signal: AbortSignal | undefined;
|
|
791
|
+
onUpdate: AgentToolUpdateCallback<DelegateTaskDetails> | undefined;
|
|
792
|
+
/** The run a `retryRunId` resolved to — the background spawn's identity. */
|
|
793
|
+
retrySourceRun: SubagentRun | undefined;
|
|
794
|
+
runners: RouteRunners;
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
/**
|
|
798
|
+
* Seam D's value. `returned` carries the injected runner's result — possibly a
|
|
799
|
+
* PROMISE, which the caller returns as-is: awaiting it inside the seam would
|
|
800
|
+
* add a settlement turn the inline call did not have. `foreground` means the
|
|
801
|
+
* dispatch is a single foreground run, carrying the task it will block on.
|
|
802
|
+
*/
|
|
803
|
+
type RouteOutcome =
|
|
804
|
+
| { kind: "returned"; result: ToolResult | Promise<ToolResult> }
|
|
805
|
+
| { kind: "foreground"; singleTask: string };
|
|
806
|
+
|
|
807
|
+
/**
|
|
808
|
+
* Seam D — route the dispatch to the one thing that runs it (issue #430).
|
|
809
|
+
*
|
|
810
|
+
* A selector, not an executor: every branch hands the call to an entry point
|
|
811
|
+
* the composition root INJECTED (ADR 0027 D5) — never a locally built runner or
|
|
812
|
+
* pipeline, whose second spawn queue / notice latch would be invisible to the
|
|
813
|
+
* rest of the session. The two batch limits are checked here rather than in the
|
|
814
|
+
* runners so every shape is rejected at the same seam.
|
|
815
|
+
*
|
|
816
|
+
* Single mode falls through to the foreground path and hands back the task.
|
|
817
|
+
* `params.task` is a non-empty string by then (seam B's exactly-one check plus
|
|
818
|
+
* the sanitizer); the assertion mirrors the `params.chain!`/`params.tasks!`
|
|
819
|
+
* reads for the same reason — TS cannot narrow through the boolean count.
|
|
820
|
+
*/
|
|
821
|
+
function routeDispatch(
|
|
822
|
+
params: DelegateTaskParams,
|
|
823
|
+
selection: DispatchSelection,
|
|
824
|
+
prepared: ShapePreparation,
|
|
825
|
+
deps: RouteDeps,
|
|
826
|
+
): RouteOutcome {
|
|
827
|
+
const { pi, ctx, signal, onUpdate, retrySourceRun, runners } = deps;
|
|
828
|
+
const { isChain, isParallel, isGraph } = selection;
|
|
829
|
+
const { useBackground, batchGuard } = prepared;
|
|
830
|
+
|
|
831
|
+
if (isChain) {
|
|
832
|
+
if (params.chain!.length > MAX_CHAIN_STEPS) {
|
|
833
|
+
return {
|
|
834
|
+
kind: "returned",
|
|
835
|
+
result: {
|
|
836
|
+
content: [
|
|
837
|
+
{
|
|
838
|
+
type: "text" as const,
|
|
839
|
+
text: `Chain exceeds max ${MAX_CHAIN_STEPS} steps.`,
|
|
840
|
+
},
|
|
841
|
+
],
|
|
842
|
+
details: undefined,
|
|
843
|
+
isError: true,
|
|
844
|
+
},
|
|
845
|
+
};
|
|
846
|
+
}
|
|
847
|
+
return { kind: "returned", result: runners.runChainMode(params, signal, onUpdate, ctx, batchGuard) };
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
if (isParallel) {
|
|
851
|
+
if (params.tasks!.length > MAX_PARALLEL_TASKS) {
|
|
852
|
+
return {
|
|
853
|
+
kind: "returned",
|
|
854
|
+
result: {
|
|
855
|
+
content: [
|
|
856
|
+
{
|
|
857
|
+
type: "text" as const,
|
|
858
|
+
text: `Parallel exceeds max ${MAX_PARALLEL_TASKS} tasks.`,
|
|
859
|
+
},
|
|
860
|
+
],
|
|
861
|
+
details: undefined,
|
|
862
|
+
isError: true,
|
|
863
|
+
},
|
|
864
|
+
};
|
|
865
|
+
}
|
|
866
|
+
if (useBackground) {
|
|
867
|
+
return { kind: "returned", result: runners.runBackgroundFanOut(pi, ctx, params, signal, batchGuard) };
|
|
868
|
+
}
|
|
869
|
+
return { kind: "returned", result: runners.runParallelMode(params, signal, onUpdate, ctx, batchGuard) };
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
if (isGraph) {
|
|
873
|
+
return { kind: "returned", result: runners.runGraphMode(params, signal, onUpdate, ctx, batchGuard) };
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
// Single mode: isSingle is true (modeCount===1, none of chain/parallel/graph),
|
|
877
|
+
// so params.task is a non-empty string. TS can't infer this through the
|
|
878
|
+
// boolean-array filter — assert, mirroring params.chain!/params.tasks! above.
|
|
879
|
+
const singleTask = params.task!; // non-empty (sanitizer guarantees; isSingle confirms)
|
|
880
|
+
|
|
881
|
+
if (useBackground) {
|
|
882
|
+
return {
|
|
883
|
+
kind: "returned",
|
|
884
|
+
result: runners.spawnBackgroundRun(pi, ctx, params, singleTask, retrySourceRun),
|
|
885
|
+
};
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
return { kind: "foreground", singleTask };
|
|
889
|
+
}
|
|
890
|
+
|
|
891
|
+
/** What seam E reads — the three gates' surroundings (not the whole runtime). */
|
|
892
|
+
interface ForegroundDeps {
|
|
893
|
+
state: SessionState;
|
|
894
|
+
ctx: ExtensionContext;
|
|
895
|
+
log: Logger;
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
/**
|
|
899
|
+
* Seam E's value: every foreground input resolved ONCE, so no later seam can
|
|
900
|
+
* re-derive one and drift (the failure mode #434's second `processChecks` read
|
|
901
|
+
* demonstrated). Named fields, not a bag: a seam that needs the whole
|
|
902
|
+
* `RuntimeContext` would be a seam with the wrong boundary.
|
|
903
|
+
*/
|
|
904
|
+
interface ForegroundPrepared {
|
|
905
|
+
/** The sanitized single-task body the child runs. */
|
|
906
|
+
task: string;
|
|
907
|
+
label: string | undefined;
|
|
908
|
+
inheritSP: boolean;
|
|
909
|
+
customSP: string | undefined;
|
|
910
|
+
/** The merged (preset/template-aware) deadline; undefined = no deadline. */
|
|
911
|
+
timeout: number | undefined;
|
|
912
|
+
thinkingLevel: ThinkingLevel;
|
|
913
|
+
toolOptions: SubagentToolOptions | undefined;
|
|
914
|
+
resolvedGitMode: GitMode;
|
|
915
|
+
resolvedApprovalMode: ApprovalMode;
|
|
916
|
+
resolvedPreset: SubagentPreset | undefined;
|
|
917
|
+
autoRoutedPreset: SubagentPreset | undefined;
|
|
918
|
+
autoRouteKeyword: string | undefined;
|
|
919
|
+
/** The validated absolute cwd the child runs in. */
|
|
920
|
+
resolvedCwd: string;
|
|
921
|
+
/** The validated output file, or undefined when the caller set none. */
|
|
922
|
+
resolvedOutputFile: string | undefined;
|
|
923
|
+
/** The H1 warnings note appended to the returned text (empty when clean). */
|
|
924
|
+
warningsNote: string;
|
|
925
|
+
/** The resolved model — provider/id, precedence already applied. */
|
|
926
|
+
subagentModel: { provider: string; id: string };
|
|
927
|
+
/** The depth THIS dispatch sits at; the child runs at `currentDepth + 1`. */
|
|
928
|
+
currentDepth: number;
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
/**
|
|
932
|
+
* Seam E — foreground admission (issue #430).
|
|
933
|
+
*
|
|
934
|
+
* Every gate that must hold BEFORE a run exists: the session cost limit, the
|
|
935
|
+
* recursion-depth cap, cwd + outputFile validation, the pi pre-flight, the H1
|
|
936
|
+
* capability validation, and model resolution. Each rejection is returned
|
|
937
|
+
* unchanged and NOTHING has been persisted — which is exactly why these gates
|
|
938
|
+
* live above seam F's run record: a rejection here leaves no dangling row.
|
|
939
|
+
*
|
|
940
|
+
* FOREGROUND-ONLY, and it must stay that way: seam D routes batch/background
|
|
941
|
+
* dispatches to their own runners before this runs, and those paths apply their
|
|
942
|
+
* own cost/model policy (`runModePrologue`). Moving E above D would re-gate a
|
|
943
|
+
* background dispatch the caller asked for.
|
|
944
|
+
*
|
|
945
|
+
* `force` degrades a capability error to a warning (B2's override) — the flag
|
|
946
|
+
* is read off `params` here because it is a CALL-level decision, not a resolved
|
|
947
|
+
* value; `cwd`/`noJev` likewise reach H1 straight from the dispatch.
|
|
948
|
+
*/
|
|
949
|
+
function prepareForeground(
|
|
950
|
+
params: DelegateTaskParams,
|
|
951
|
+
singleTask: string,
|
|
952
|
+
deps: ForegroundDeps,
|
|
953
|
+
): Outcome<ForegroundPrepared> {
|
|
954
|
+
const { state, ctx, log } = deps;
|
|
955
|
+
|
|
956
|
+
// R5: Check session cost limit before spawning
|
|
957
|
+
// Use a default per-task estimate of $0.05 if no perTaskCostEstimate is set
|
|
958
|
+
const costError = gateSessionCost({
|
|
959
|
+
state,
|
|
960
|
+
ctx,
|
|
961
|
+
log,
|
|
962
|
+
units: 1,
|
|
963
|
+
label: "Subagent delegation",
|
|
964
|
+
});
|
|
965
|
+
if (costError) return { ok: false, result: costError };
|
|
966
|
+
|
|
967
|
+
// Reject delegation if recursion depth exceeds configured max.
|
|
968
|
+
// This prevents subagents from spawning infinite sub-subagents while
|
|
969
|
+
// still allowing other extensions to function normally in subprocesses.
|
|
970
|
+
const currentDepth = getCurrentDepth();
|
|
971
|
+
if (currentDepth >= state.config.maxSubagentDepth) {
|
|
972
|
+
log.warn("Subagent delegation rejected: max depth reached", {
|
|
973
|
+
currentDepth,
|
|
974
|
+
maxDepth: state.config.maxSubagentDepth,
|
|
975
|
+
});
|
|
976
|
+
return { ok: false, result: depthLimitRejection(currentDepth, state.config.maxSubagentDepth) };
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
const {
|
|
980
|
+
task,
|
|
981
|
+
label,
|
|
982
|
+
inheritSP,
|
|
983
|
+
customSP,
|
|
984
|
+
outputFile,
|
|
985
|
+
timeout,
|
|
986
|
+
effectiveCwd,
|
|
987
|
+
thinkingLevel,
|
|
988
|
+
toolOptions,
|
|
989
|
+
resolvedGitMode,
|
|
990
|
+
resolvedApprovalMode,
|
|
991
|
+
resolvedPreset,
|
|
992
|
+
autoRoutedPreset,
|
|
993
|
+
autoRouteKeyword,
|
|
994
|
+
} = resolveSubagentParams({ ...params, task: singleTask }, state, ctx, log);
|
|
995
|
+
|
|
996
|
+
// F1: Validate CWD
|
|
997
|
+
const cwdResult = validateCwd(effectiveCwd, ctx.cwd);
|
|
998
|
+
if (!cwdResult.ok) {
|
|
999
|
+
return {
|
|
1000
|
+
ok: false,
|
|
1001
|
+
result: {
|
|
1002
|
+
content: [{ type: "text" as const, text: `Invalid cwd: ${cwdResult.error}` }],
|
|
1003
|
+
details: undefined,
|
|
1004
|
+
isError: true,
|
|
1005
|
+
},
|
|
1006
|
+
};
|
|
1007
|
+
}
|
|
1008
|
+
const resolvedCwd = cwdResult.value;
|
|
1009
|
+
|
|
1010
|
+
// F1: Validate outputFile
|
|
1011
|
+
let resolvedOutputFile: string | undefined;
|
|
1012
|
+
if (outputFile) {
|
|
1013
|
+
const ofResult = validateOutputFile(outputFile, resolvedCwd);
|
|
1014
|
+
if (!ofResult.ok) {
|
|
1015
|
+
return {
|
|
1016
|
+
ok: false,
|
|
1017
|
+
result: {
|
|
1018
|
+
content: [
|
|
1019
|
+
{ type: "text" as const, text: `Invalid outputFile: ${ofResult.error}` },
|
|
1020
|
+
],
|
|
1021
|
+
details: undefined,
|
|
1022
|
+
isError: true,
|
|
1023
|
+
},
|
|
1024
|
+
};
|
|
1025
|
+
}
|
|
1026
|
+
resolvedOutputFile = ofResult.value;
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
// R3: Pre-flight checks — fail fast before consuming resources
|
|
1030
|
+
const pfResult = preflightCheck(resolvedCwd);
|
|
1031
|
+
if (!pfResult.ok) {
|
|
1032
|
+
log.warn("Pre-flight check failed", { error: pfResult.error });
|
|
1033
|
+
return {
|
|
1034
|
+
ok: false,
|
|
1035
|
+
result: {
|
|
1036
|
+
content: [{ type: "text" as const, text: `Pre-flight check failed: ${pfResult.error}` }],
|
|
1037
|
+
details: undefined,
|
|
1038
|
+
isError: true,
|
|
1039
|
+
},
|
|
1040
|
+
};
|
|
1041
|
+
}
|
|
1042
|
+
|
|
1043
|
+
// H1: Pre-task validation — deterministic check that tools/thinking match task
|
|
1044
|
+
// (`force` degrades capability errors to warnings — B2's override).
|
|
1045
|
+
const validation = validatePreTask({
|
|
1046
|
+
task,
|
|
1047
|
+
toolOptions,
|
|
1048
|
+
thinkingLevel,
|
|
1049
|
+
gitMode: resolvedGitMode,
|
|
1050
|
+
outputFile: resolvedOutputFile,
|
|
1051
|
+
force: params.force,
|
|
1052
|
+
cwd: resolvedCwd,
|
|
1053
|
+
noJev: params.noJev,
|
|
1054
|
+
});
|
|
1055
|
+
if (validation.warnings.length > 0) {
|
|
1056
|
+
log.warn("Pre-task validation warnings", { warnings: validation.warnings });
|
|
1057
|
+
}
|
|
1058
|
+
if (!validation.valid) {
|
|
1059
|
+
const errText = validation.errors.join("; ");
|
|
1060
|
+
log.warn("Pre-task validation failed", { errors: validation.errors });
|
|
1061
|
+
return {
|
|
1062
|
+
ok: false,
|
|
1063
|
+
result: {
|
|
1064
|
+
content: [{
|
|
1065
|
+
type: "text" as const,
|
|
1066
|
+
text: errText,
|
|
1067
|
+
}],
|
|
1068
|
+
details: undefined,
|
|
1069
|
+
isError: true,
|
|
1070
|
+
},
|
|
1071
|
+
};
|
|
1072
|
+
}
|
|
1073
|
+
// C: surface warnings in the returned result (not just the log) —
|
|
1074
|
+
// shared renderer so foreground/background wording stays identical.
|
|
1075
|
+
const warningsNote = formatValidationWarnings(validation.warnings);
|
|
1076
|
+
|
|
1077
|
+
// Resolve model (per-call top-level model override beats preset)
|
|
1078
|
+
const modelResult = resolveSubagentModelPrecedence({
|
|
1079
|
+
state,
|
|
1080
|
+
ctx,
|
|
1081
|
+
log,
|
|
1082
|
+
preset: resolvedPreset,
|
|
1083
|
+
perCallModel: params.model,
|
|
1084
|
+
});
|
|
1085
|
+
if (!modelResult.ok) return { ok: false, result: modelResult.error };
|
|
1086
|
+
const subagentModel = modelResult.model;
|
|
1087
|
+
|
|
1088
|
+
// R3: Verify resolved model provider+id is non-empty
|
|
1089
|
+
const modelStr = `${subagentModel.provider}/${subagentModel.id}`.trim();
|
|
1090
|
+
if (!modelStr || modelStr === "/") {
|
|
1091
|
+
log.warn("Model string is empty after resolution", { model: subagentModel });
|
|
1092
|
+
return { ok: false, result: modelNotConfiguredRejection() };
|
|
1093
|
+
}
|
|
1094
|
+
|
|
1095
|
+
return {
|
|
1096
|
+
ok: true,
|
|
1097
|
+
value: {
|
|
1098
|
+
task,
|
|
1099
|
+
label,
|
|
1100
|
+
inheritSP,
|
|
1101
|
+
customSP,
|
|
1102
|
+
timeout,
|
|
1103
|
+
thinkingLevel,
|
|
1104
|
+
toolOptions,
|
|
1105
|
+
resolvedGitMode,
|
|
1106
|
+
resolvedApprovalMode,
|
|
1107
|
+
resolvedPreset,
|
|
1108
|
+
autoRoutedPreset,
|
|
1109
|
+
autoRouteKeyword,
|
|
1110
|
+
resolvedCwd,
|
|
1111
|
+
resolvedOutputFile,
|
|
1112
|
+
warningsNote,
|
|
1113
|
+
subagentModel,
|
|
1114
|
+
currentDepth,
|
|
1115
|
+
},
|
|
1116
|
+
};
|
|
1117
|
+
}
|
|
1118
|
+
|
|
1119
|
+
/** What the foreground orchestrator reads from the tool call and the runtime. */
|
|
1120
|
+
interface ForegroundRunDeps {
|
|
1121
|
+
pi: ExtensionAPI;
|
|
1122
|
+
state: SessionState;
|
|
1123
|
+
ctx: ExtensionContext;
|
|
1124
|
+
log: Logger;
|
|
1125
|
+
signal: AbortSignal | undefined;
|
|
1126
|
+
onUpdate: AgentToolUpdateCallback<DelegateTaskDetails> | undefined;
|
|
1127
|
+
}
|
|
1128
|
+
|
|
1129
|
+
/**
|
|
1130
|
+
* Seam F–L — the single foreground run (issue #430): the run record, the git
|
|
1131
|
+
* work branch, the pre-start gates, the child (with its timeout retry), the
|
|
1132
|
+
* diff/approval flow, the terminal record and the crash/finally.
|
|
1133
|
+
*
|
|
1134
|
+
* An ORCHESTRATOR, not a decision table: every await, every early return and
|
|
1135
|
+
* the whole `try`/`catch`/`finally` stay here, in the order the inline body had
|
|
1136
|
+
* them, and the decision-bearing parts are the named seams it calls.
|
|
1137
|
+
*
|
|
1138
|
+
* Ownership invariants that must not move:
|
|
1139
|
+
* - `success` is this function's, and `releaseSlot` fires exactly once for
|
|
1140
|
+
* exactly this run, in the `finally` that encloses the same `try`;
|
|
1141
|
+
* - `acquireSlot` and the pre-start rejections stay ABOVE the `try` — a
|
|
1142
|
+
* pre-try throw therefore does not release, which is the behaviour the
|
|
1143
|
+
* #340 tests and `dangling-row` pin (a known leak, deliberately preserved
|
|
1144
|
+
* by this refactor, not repaired by it);
|
|
1145
|
+
* - the transcript import stays above the `try` (F7/#65) so the catch can
|
|
1146
|
+
* complete a transcript it never started;
|
|
1147
|
+
* - `success = true` sits at the exact point it always did — after the
|
|
1148
|
+
* failure arm's return, before the completed transcript and the log line —
|
|
1149
|
+
* so a throw from either still leaves the release counting a success;
|
|
1150
|
+
* - the timeout retry re-registers the live row and calls the runner again
|
|
1151
|
+
* with the same marker: same run, refreshed deadline.
|
|
1152
|
+
*/
|
|
1153
|
+
async function runForeground(
|
|
1154
|
+
params: DelegateTaskParams,
|
|
1155
|
+
prepared: ForegroundPrepared,
|
|
1156
|
+
retrySourceRun: SubagentRun | undefined,
|
|
1157
|
+
deps: ForegroundRunDeps,
|
|
1158
|
+
): Promise<ToolResult> {
|
|
1159
|
+
const { pi, state, ctx, log, signal, onUpdate } = deps;
|
|
1160
|
+
const {
|
|
1161
|
+
task,
|
|
1162
|
+
label,
|
|
1163
|
+
timeout,
|
|
1164
|
+
thinkingLevel,
|
|
1165
|
+
toolOptions,
|
|
1166
|
+
resolvedGitMode,
|
|
1167
|
+
resolvedApprovalMode,
|
|
1168
|
+
resolvedCwd,
|
|
1169
|
+
warningsNote,
|
|
1170
|
+
subagentModel,
|
|
1171
|
+
} = prepared;
|
|
1172
|
+
|
|
1173
|
+
// Seam F: persist the running record, prune history, register the live entry.
|
|
1174
|
+
const { runId, run } = registerForegroundRun(params, prepared, retrySourceRun, { state, ctx, pi, log });
|
|
1175
|
+
|
|
1176
|
+
// Seam G: set up the work branch and take its teardown.
|
|
1177
|
+
const branch = prepareWorkBranch({ resolvedCwd, resolvedGitMode, runId, log });
|
|
1178
|
+
|
|
1179
|
+
// Seam H: the pre-start gates. The circuit decision is pure; the slot
|
|
1180
|
+
// acquisition keeps its own await here so no seam adds a suspension.
|
|
1181
|
+
const gate = decidePreStartRejection(state);
|
|
1182
|
+
if (gate.kind === "rejected") {
|
|
1183
|
+
terminalizePreStartRejection(run, gate.message, { state, pi });
|
|
1184
|
+
branch.cleanup();
|
|
1185
|
+
return preStartRejectionResult(gate.message);
|
|
1186
|
+
}
|
|
1187
|
+
|
|
1188
|
+
// Acquire concurrency slot
|
|
1189
|
+
const acquired = await acquireSlot(state, ctx, signal, resolveSinglePriority(params));
|
|
1190
|
+
if (!acquired) {
|
|
1191
|
+
terminalizePreStartRejection(run, SLOT_CANCEL_MESSAGE, { state, pi });
|
|
1192
|
+
branch.cleanup();
|
|
1193
|
+
return preStartRejectionResult(SLOT_CANCEL_MESSAGE);
|
|
1194
|
+
}
|
|
1195
|
+
|
|
1196
|
+
let success = false;
|
|
1197
|
+
|
|
1198
|
+
// Retire-on-retry (O3 fold, decision 2026-10-11): the retry has passed
|
|
1199
|
+
// every pre-spawn gate and is about to start, so the SOURCE interrupted
|
|
1200
|
+
// registry entry is superseded — clear it here so the old run is not
|
|
1201
|
+
// re-offered at every subsequent boot. A failed pre-start (circuit open,
|
|
1202
|
+
// slot cancelled) returns ABOVE this point: the source is left intact
|
|
1203
|
+
// and retryable, while the NEW twin has already been finalized terminal
|
|
1204
|
+
// by the gate (#340) — nothing dangles. `retrySourceRun` is set only on
|
|
1205
|
+
// a `retryRunId` call.
|
|
1206
|
+
if (retrySourceRun) clearInflightRun(retrySourceRun.id);
|
|
1207
|
+
|
|
1208
|
+
// F7 (issue #65): import BEFORE the try — the crash-path catch calls
|
|
1209
|
+
// completeTranscript, and block-scoped consts declared inside the try
|
|
1210
|
+
// are invisible in its catch (pre-fix, a crash here threw
|
|
1211
|
+
// "completeTranscript is not defined" instead of returning the
|
|
1212
|
+
// sanitized crash result).
|
|
1213
|
+
const { startTranscript, completeTranscript } = await import('./transcript');
|
|
1214
|
+
|
|
1215
|
+
try {
|
|
1216
|
+
// Seam I: assemble the child's input (sync), then announce the start.
|
|
1217
|
+
const input = buildForegroundRunInput(prepared, ctx);
|
|
1218
|
+
onUpdate?.({
|
|
1219
|
+
content: [
|
|
1220
|
+
{
|
|
1221
|
+
type: "text" as const,
|
|
1222
|
+
text: `Starting subagent (${input.modeInfo})...`,
|
|
1223
|
+
},
|
|
1224
|
+
],
|
|
1225
|
+
details: {
|
|
1226
|
+
messages: [],
|
|
1227
|
+
usage: { ...EMPTY_USAGE },
|
|
1228
|
+
exitCode: -1,
|
|
1229
|
+
stderr: "",
|
|
1230
|
+
},
|
|
1231
|
+
});
|
|
1232
|
+
|
|
1233
|
+
// Wrap onUpdate to feed live monitor
|
|
1234
|
+
const liveOnUpdate = makeLiveOnUpdate(state, runId, onUpdate);
|
|
1235
|
+
|
|
1236
|
+
// Start transcript for audit trail
|
|
1237
|
+
startTranscript(runId, task);
|
|
1238
|
+
|
|
1239
|
+
let result = await runSubagent(
|
|
1240
|
+
resolvedCwd,
|
|
1241
|
+
input.subagentPrompt,
|
|
1242
|
+
subagentModel,
|
|
1243
|
+
thinkingLevel,
|
|
1244
|
+
task,
|
|
1245
|
+
signal,
|
|
1246
|
+
liveOnUpdate,
|
|
1247
|
+
toolOptions,
|
|
1248
|
+
timeout,
|
|
1249
|
+
getFinalOutput,
|
|
1250
|
+
log,
|
|
1251
|
+
input.childDepth,
|
|
1252
|
+
undefined, // intercom
|
|
1253
|
+
undefined, // subagentId
|
|
1254
|
+
run.childMarker,
|
|
1255
|
+
// Issue #511 (U2): the run record's id names the scratch directory.
|
|
1256
|
+
run.id,
|
|
1257
|
+
);
|
|
1258
|
+
|
|
1259
|
+
// Auto-retry on timeout
|
|
1260
|
+
if (isTimeoutRetry(params, result)) {
|
|
1261
|
+
log.info("Auto-retrying after timeout", { runId });
|
|
1262
|
+
// Issue #423: the retry restarts the clock, so its display deadline is
|
|
1263
|
+
// re-anchored on it (the same clock `startedAt` carries). Registering
|
|
1264
|
+
// also clears the finalize claim, so the row is live again.
|
|
1265
|
+
const retryStartedAt = Date.now();
|
|
1266
|
+
const retryDeadlineAt = deadlineFrom(retryStartedAt, timeout);
|
|
1267
|
+
state.registerLiveSubagent(runId, {
|
|
1268
|
+
id: runId,
|
|
1269
|
+
label,
|
|
1270
|
+
task,
|
|
1271
|
+
model: run.model,
|
|
1272
|
+
thinkingLevel,
|
|
1273
|
+
priority: params.priority,
|
|
1274
|
+
startedAt: retryStartedAt,
|
|
1275
|
+
...(retryDeadlineAt !== undefined ? { deadlineAt: retryDeadlineAt } : {}),
|
|
1276
|
+
ctx,
|
|
1277
|
+
});
|
|
1278
|
+
|
|
1279
|
+
onUpdate?.({
|
|
1280
|
+
content: [
|
|
1281
|
+
{ type: "text" as const, text: "Retrying after timeout..." },
|
|
1282
|
+
],
|
|
1283
|
+
details: {
|
|
1284
|
+
messages: [],
|
|
1285
|
+
usage: { ...EMPTY_USAGE },
|
|
1286
|
+
exitCode: -1,
|
|
1287
|
+
stderr: "",
|
|
1288
|
+
},
|
|
1289
|
+
});
|
|
1290
|
+
|
|
1291
|
+
result = await runSubagent(
|
|
1292
|
+
resolvedCwd,
|
|
1293
|
+
input.subagentPrompt,
|
|
1294
|
+
subagentModel,
|
|
1295
|
+
thinkingLevel,
|
|
1296
|
+
task,
|
|
1297
|
+
signal,
|
|
1298
|
+
liveOnUpdate,
|
|
1299
|
+
toolOptions,
|
|
1300
|
+
timeout,
|
|
1301
|
+
getFinalOutput,
|
|
1302
|
+
log,
|
|
1303
|
+
input.childDepth,
|
|
1304
|
+
undefined, // intercom
|
|
1305
|
+
undefined, // subagentId
|
|
1306
|
+
run.childMarker,
|
|
1307
|
+
// Issue #511 (U2): the run record's id names the scratch directory.
|
|
1308
|
+
run.id,
|
|
1309
|
+
);
|
|
1310
|
+
}
|
|
1311
|
+
|
|
1312
|
+
// F3: Sanitize and cap output
|
|
1313
|
+
let finalOutput = getFinalOutput(result.messages);
|
|
1314
|
+
finalOutput = stripAnsi(finalOutput);
|
|
1315
|
+
finalOutput = capOutput(finalOutput);
|
|
1316
|
+
|
|
1317
|
+
// Attach label for display
|
|
1318
|
+
result.label = label;
|
|
1319
|
+
|
|
1320
|
+
// P3: Capture git diff if we created a work branch
|
|
1321
|
+
if (branch.workBranchName && branch.headState) {
|
|
1322
|
+
const headState = branch.headState;
|
|
1323
|
+
const workBranch = branch.workBranchName;
|
|
1324
|
+
// Diff against the captured starting sha rather than the branch
|
|
1325
|
+
// name: a detached start's branch label is the "HEAD" pseudo-ref,
|
|
1326
|
+
// for which `git diff HEAD...HEAD` is always empty.
|
|
1327
|
+
const diffResult = captureDiff(resolvedCwd, headState.sha);
|
|
1328
|
+
if (diffResult.ok) {
|
|
1329
|
+
result.gitBranch = workBranch;
|
|
1330
|
+
result.gitDiff = diffResult.diff;
|
|
1331
|
+
}
|
|
1332
|
+
|
|
1333
|
+
// Restore the starting HEAD (branch, or detached sha)
|
|
1334
|
+
const restoreResult = restoreHead(resolvedCwd, headState);
|
|
1335
|
+
if (restoreResult.ok) {
|
|
1336
|
+
log.info("Restored original HEAD", {
|
|
1337
|
+
branch: headState.branch,
|
|
1338
|
+
detached: headState.detached,
|
|
1339
|
+
});
|
|
1340
|
+
// Issue #466: the tree is verified off the work branch, so the
|
|
1341
|
+
// durable record has nothing left to repair.
|
|
1342
|
+
branch.clearHeadState();
|
|
1343
|
+
|
|
1344
|
+
// P4: Change approval workflow — let user review the diff. The
|
|
1345
|
+
// TABLE is seam J's; the dialog await and the git calls stay here.
|
|
1346
|
+
const hasChanges = (result.gitDiff ?? "").trim().length > 0;
|
|
1347
|
+
const decided = decideBranchOutcome({
|
|
1348
|
+
hasUI: ctx.hasUI !== false,
|
|
1349
|
+
approvalMode: resolvedApprovalMode,
|
|
1350
|
+
hasChanges,
|
|
1351
|
+
});
|
|
1352
|
+
|
|
1353
|
+
if (decided === "prompt") {
|
|
1354
|
+
const choice = await showApprovalDialog(ctx, label, result.gitDiff ?? "", workBranch);
|
|
1355
|
+
|
|
1356
|
+
if (choice === "apply") {
|
|
1357
|
+
const mergeResult = mergeWorkBranch(resolvedCwd, workBranch);
|
|
1358
|
+
if (mergeResult.ok) {
|
|
1359
|
+
log.info("Merged work branch (approved)", { branch: workBranch });
|
|
1360
|
+
result.approved = true;
|
|
1361
|
+
} else {
|
|
1362
|
+
log.error("Failed to merge work branch", {
|
|
1363
|
+
branch: workBranch,
|
|
1364
|
+
error: mergeResult.error,
|
|
1365
|
+
});
|
|
1366
|
+
result.approved = false;
|
|
1367
|
+
}
|
|
1368
|
+
} else {
|
|
1369
|
+
// Discard or cancelled
|
|
1370
|
+
deleteBranch(resolvedCwd, workBranch);
|
|
1371
|
+
log.info("Discarded work branch", { branch: workBranch });
|
|
1372
|
+
result.approved = false;
|
|
1373
|
+
}
|
|
1374
|
+
branch.workBranchName = undefined; // Prevent double-cleanup
|
|
1375
|
+
} else if (decided === "merge") {
|
|
1376
|
+
// Auto-approve: merge the work branch
|
|
1377
|
+
const mergeResult = mergeWorkBranch(resolvedCwd, workBranch);
|
|
1378
|
+
if (mergeResult.ok) {
|
|
1379
|
+
log.info("Merged work branch (auto-approve)", { branch: workBranch });
|
|
1380
|
+
result.approved = true;
|
|
1381
|
+
} else {
|
|
1382
|
+
log.error("Failed to merge work branch (auto-approve)", {
|
|
1383
|
+
branch: workBranch,
|
|
1384
|
+
error: mergeResult.error,
|
|
1385
|
+
});
|
|
1386
|
+
}
|
|
1387
|
+
// #308: a DETACHED start has no branch of its own to hold the
|
|
1388
|
+
// merge result — teardown re-detached at the captured sha and
|
|
1389
|
+
// the merge fast-forwarded THAT detached HEAD, so deleting the
|
|
1390
|
+
// work branch would leave the committed work reachable only
|
|
1391
|
+
// from the detached HEAD (silently lost on the next checkout).
|
|
1392
|
+
// Keep the branch as the durable ref and log where the work
|
|
1393
|
+
// lives. An ATTACHED start merged onto its own branch, which
|
|
1394
|
+
// already retains the commit, so the temporary work branch is
|
|
1395
|
+
// safe to drop.
|
|
1396
|
+
if (headState.detached) {
|
|
1397
|
+
log.info("detached checkout: work preserved on branch", {
|
|
1398
|
+
branch: workBranch,
|
|
1399
|
+
});
|
|
1400
|
+
} else {
|
|
1401
|
+
deleteBranch(resolvedCwd, workBranch);
|
|
1402
|
+
}
|
|
1403
|
+
branch.workBranchName = undefined;
|
|
1404
|
+
} else {
|
|
1405
|
+
// No changes — just delete the empty branch
|
|
1406
|
+
deleteBranch(resolvedCwd, workBranch);
|
|
1407
|
+
branch.workBranchName = undefined;
|
|
1408
|
+
}
|
|
1409
|
+
} else {
|
|
1410
|
+
log.warn("Failed to restore original HEAD after work-branch run", {
|
|
1411
|
+
branch: headState.branch,
|
|
1412
|
+
error: restoreResult.error,
|
|
1413
|
+
});
|
|
1414
|
+
}
|
|
1415
|
+
|
|
1416
|
+
// Nothing may leave teardown with the work branch still present: the
|
|
1417
|
+
// approval flow above clears workBranchName on every terminal choice
|
|
1418
|
+
// (including "apply", where keeping the branch is intentional), so a
|
|
1419
|
+
// still-set name means the restore failed and the flow was skipped.
|
|
1420
|
+
if (branch.workBranchName) {
|
|
1421
|
+
deleteBranch(resolvedCwd, branch.workBranchName);
|
|
1422
|
+
branch.workBranchName = undefined;
|
|
1423
|
+
}
|
|
1424
|
+
}
|
|
1425
|
+
|
|
1426
|
+
// Seam K: terminal record, live finalize and SLA accounting.
|
|
1427
|
+
finalizeForegroundResult(run, result, finalOutput, { state, ctx, pi, log });
|
|
1428
|
+
|
|
1429
|
+
if (isSubagentError(result)) {
|
|
1430
|
+
// The report first (its log line, H3 diagnostics and the circuit
|
|
1431
|
+
// failure come before the transcript), then the transcript, then the
|
|
1432
|
+
// result — the order the inline body had.
|
|
1433
|
+
const failureText = buildFailureReport(result, {
|
|
1434
|
+
state,
|
|
1435
|
+
log,
|
|
1436
|
+
runId,
|
|
1437
|
+
task,
|
|
1438
|
+
toolOptions,
|
|
1439
|
+
thinkingLevel,
|
|
1440
|
+
resolvedGitMode,
|
|
1441
|
+
timeout,
|
|
1442
|
+
warningsNote,
|
|
1443
|
+
resolvedCwd,
|
|
1444
|
+
finalOutput,
|
|
1445
|
+
});
|
|
1446
|
+
|
|
1447
|
+
completeTranscript(runId, 'failed');
|
|
1448
|
+
|
|
1449
|
+
return {
|
|
1450
|
+
content: [
|
|
1451
|
+
{ type: "text" as const, text: failureText },
|
|
1452
|
+
],
|
|
1453
|
+
details: result,
|
|
1454
|
+
isError: true,
|
|
1455
|
+
};
|
|
1456
|
+
}
|
|
1457
|
+
|
|
1458
|
+
// The success flag is assigned HERE and nowhere else: the `finally` below
|
|
1459
|
+
// reads it, so a throw from the transcript or the log line must still
|
|
1460
|
+
// count as a success (the run itself completed).
|
|
1461
|
+
success = true;
|
|
1462
|
+
completeTranscript(runId, 'completed');
|
|
1463
|
+
log.info("Subagent completed successfully",{
|
|
1464
|
+
runId,
|
|
1465
|
+
tokensIn: result.usage.input,
|
|
1466
|
+
tokensOut: result.usage.output,
|
|
1467
|
+
cost: result.usage.cost,
|
|
1468
|
+
sessionTotalCost: state.getSessionTotalCost(ctx),
|
|
1469
|
+
});
|
|
1470
|
+
|
|
1471
|
+
// R1: Record success in circuit breaker
|
|
1472
|
+
state.recordSuccess();
|
|
1473
|
+
|
|
1474
|
+
return successResult(result, finalOutput, prepared);
|
|
1475
|
+
} catch (err) {
|
|
1476
|
+
// P3: Clean up git branch on crash
|
|
1477
|
+
branch.cleanup();
|
|
1478
|
+
completeTranscript(runId, 'failed');
|
|
1479
|
+
|
|
1480
|
+
return finalizeCrashedRun(err, run, { state, pi, log, resolvedCwd });
|
|
1481
|
+
} finally {
|
|
1482
|
+
releaseSlot(state, success, ctx);
|
|
1483
|
+
}
|
|
1484
|
+
}
|
|
1485
|
+
|
|
1486
|
+
// ---------------------------------------------------------------------------
|
|
1487
|
+
// Foreground run seams (issue #430, step 6)
|
|
1488
|
+
// ---------------------------------------------------------------------------
|
|
1489
|
+
|
|
1490
|
+
/** What seam F reads: the persisted record's surroundings. */
|
|
1491
|
+
interface RegisterRunDeps {
|
|
1492
|
+
state: SessionState;
|
|
1493
|
+
ctx: ExtensionContext;
|
|
1494
|
+
pi: ExtensionAPI;
|
|
1495
|
+
log: Logger;
|
|
1496
|
+
}
|
|
1497
|
+
|
|
1498
|
+
/**
|
|
1499
|
+
* Seam F — create and register the foreground run record.
|
|
1500
|
+
*
|
|
1501
|
+
* The ORDER is the whole seam: persist the `running` record first (which also
|
|
1502
|
+
* mirrors the in-flight registry row), prune history, then register the live
|
|
1503
|
+
* monitor entry. `dangling-row`/`run-registry` pin that a crash between step 1
|
|
1504
|
+
* and step 3 is recoverable — the durable row exists — while a live entry
|
|
1505
|
+
* without a record would leave the monitor looping on a run nothing can
|
|
1506
|
+
* settle.
|
|
1507
|
+
*
|
|
1508
|
+
* The identity fields are the retry contract (Option B U1): a retry inherits
|
|
1509
|
+
* the original `dispatchId` and records `resumeOf`/`attempt`, while
|
|
1510
|
+
* `childMarker` is fresh per run so boot-time orphan discovery keys the child
|
|
1511
|
+
* process correctly.
|
|
1512
|
+
*/
|
|
1513
|
+
function registerForegroundRun(
|
|
1514
|
+
params: DelegateTaskParams,
|
|
1515
|
+
prepared: ForegroundPrepared,
|
|
1516
|
+
retrySourceRun: SubagentRun | undefined,
|
|
1517
|
+
deps: RegisterRunDeps,
|
|
1518
|
+
): { runId: string; run: SubagentRun } {
|
|
1519
|
+
const { state, ctx, pi, log } = deps;
|
|
1520
|
+
const { task, label, thinkingLevel, timeout, subagentModel } = prepared;
|
|
1521
|
+
|
|
1522
|
+
// Create run record
|
|
1523
|
+
const runId = crypto.randomUUID();
|
|
1524
|
+
// Option B U1: durability identity — a retry inherits the original
|
|
1525
|
+
// dispatchId and records resumeOf/attempt; a fresh marker keys the
|
|
1526
|
+
// child process for boot-time orphan discovery.
|
|
1527
|
+
const identity = newDispatchIdentity(retrySourceRun);
|
|
1528
|
+
// Issue #511 (U2): create this run's scratch directory at record creation so
|
|
1529
|
+
// the record can name it (the retry preamble, U3, reads `scratchDir`). The
|
|
1530
|
+
// spawn seam in `runner.ts` re-prepares idempotently and is the gate that
|
|
1531
|
+
// refuses to start the child when the root cannot be placed.
|
|
1532
|
+
const scratch = prepareRunScratch(runId, { log });
|
|
1533
|
+
const run: SubagentRun = {
|
|
1534
|
+
id: runId,
|
|
1535
|
+
task,
|
|
1536
|
+
label,
|
|
1537
|
+
status: "running",
|
|
1538
|
+
model: `${subagentModel.provider}/${subagentModel.id}`,
|
|
1539
|
+
thinkingLevel,
|
|
1540
|
+
// Issue #114: record-level visibility — the run's priority (absent
|
|
1541
|
+
// when the caller left it to the default).
|
|
1542
|
+
priority: params.priority,
|
|
1543
|
+
startedAt: new Date().toISOString(),
|
|
1544
|
+
originalParams: snapshotOriginalParams(params),
|
|
1545
|
+
dispatchId: identity.dispatchId,
|
|
1546
|
+
resumeOf: identity.resumeOf,
|
|
1547
|
+
attempt: identity.attempt,
|
|
1548
|
+
owner: currentProcessOwner(),
|
|
1549
|
+
childMarker: crypto.randomUUID(),
|
|
1550
|
+
// U3 (D4): the session recovery posture at dispatch.
|
|
1551
|
+
recoveryPosture: state.config.recovery,
|
|
1552
|
+
// Issue #511 (U2): absent only when the root could not be placed — the
|
|
1553
|
+
// spawn seam then refuses the child and reports the named code.
|
|
1554
|
+
scratchDir: scratch.ok ? scratch.runDir : undefined,
|
|
1555
|
+
};
|
|
1556
|
+
state.persistRun(pi, run, "foreground");
|
|
1557
|
+
|
|
1558
|
+
// R2: Prune old run entries if history exceeds limit
|
|
1559
|
+
pruneHistoryIfNeeded(state, ctx, log);
|
|
1560
|
+
|
|
1561
|
+
// Register for live monitor
|
|
1562
|
+
// Issue #423: the merged timeout is the display deadline (absent → no
|
|
1563
|
+
// deadline; a foreground run has no 30m default).
|
|
1564
|
+
registerLiveRun(state, run, ctx, undefined, timeout);
|
|
1565
|
+
|
|
1566
|
+
return { runId, run };
|
|
1567
|
+
}
|
|
1568
|
+
|
|
1569
|
+
/** What seam G reads — one dispatch's cwd, git mode, run id and logger. */
|
|
1570
|
+
interface WorkBranchDeps {
|
|
1571
|
+
resolvedCwd: string;
|
|
1572
|
+
resolvedGitMode: GitMode;
|
|
1573
|
+
runId: string;
|
|
1574
|
+
log: Logger;
|
|
1575
|
+
}
|
|
1576
|
+
|
|
1577
|
+
/**
|
|
1578
|
+
* Seam G's value: the per-invocation work-branch record.
|
|
1579
|
+
*
|
|
1580
|
+
* Mutable BY DESIGN and owned by one run — the approval flow (seam J) clears
|
|
1581
|
+
* `workBranchName` when the branch reaches a terminal choice, and the crash
|
|
1582
|
+
* path (seam L) calls `cleanup()` with whatever the flow left behind. A
|
|
1583
|
+
* per-call record, never module state: two handlers must not share one.
|
|
1584
|
+
*/
|
|
1585
|
+
interface WorkBranch {
|
|
1586
|
+
headState: HeadState | undefined;
|
|
1587
|
+
workBranchName: string | undefined;
|
|
1588
|
+
/** Clear the durable head-state record. Idempotent; no record ⇒ no-op. */
|
|
1589
|
+
clearHeadState(): void;
|
|
1590
|
+
/** Restore the starting HEAD and delete the work branch (teardown path). */
|
|
1591
|
+
cleanup(): void;
|
|
1592
|
+
}
|
|
1593
|
+
|
|
1594
|
+
/**
|
|
1595
|
+
* Seam G — set up the git work branch and hand back its teardown (issues #308,
|
|
1596
|
+
* #466; ADR 0026 D6).
|
|
1597
|
+
*
|
|
1598
|
+
* The durable head-state record is written BEFORE the branch exists (D1): the
|
|
1599
|
+
* branch name is minted here, so a crash inside `createWorkBranch` must already
|
|
1600
|
+
* name the base it has to repair. Every failure path falls back to
|
|
1601
|
+
* `gitMode: "none"` — a non-repository cwd is not an error — and, because
|
|
1602
|
+
* nothing was created in those paths, clears the record rather than leaving a
|
|
1603
|
+
* phantom.
|
|
1604
|
+
*
|
|
1605
|
+
* `cleanup()` deletes the branch UNCONDITIONALLY, not gated on the restore
|
|
1606
|
+
* succeeding: a branch must never survive teardown, and a still-checked-out
|
|
1607
|
+
* branch simply makes `deleteBranch` fail (logged) instead of silently leaking
|
|
1608
|
+
* the ref. A FAILED restore keeps the durable record — the base lives only
|
|
1609
|
+
* there.
|
|
1610
|
+
*/
|
|
1611
|
+
function prepareWorkBranch(deps: WorkBranchDeps): WorkBranch {
|
|
1612
|
+
const { resolvedCwd, resolvedGitMode, runId, log } = deps;
|
|
1613
|
+
// Issue #466 (ADR 0026 D6): the foreground path creates the same work
|
|
1614
|
+
// branch with the same crash exposure, so it writes and clears the same
|
|
1615
|
+
// durable record — with `kind: "foreground"`, so "no record" means "no
|
|
1616
|
+
// orphan" for every branch run, not just background ones.
|
|
1617
|
+
let headStateRoot: string | undefined;
|
|
1618
|
+
const branch: WorkBranch = {
|
|
1619
|
+
headState: undefined,
|
|
1620
|
+
workBranchName: undefined,
|
|
1621
|
+
clearHeadState: () => {
|
|
1622
|
+
if (!headStateRoot) return;
|
|
1623
|
+
clearHeadState(headStateRoot);
|
|
1624
|
+
headStateRoot = undefined;
|
|
1625
|
+
},
|
|
1626
|
+
cleanup: () => {
|
|
1627
|
+
const { headState, workBranchName } = branch;
|
|
1628
|
+
if (!workBranchName) return;
|
|
1629
|
+
if (headState) {
|
|
1630
|
+
const restoreResult = restoreHead(resolvedCwd, headState);
|
|
1631
|
+
if (restoreResult.ok) {
|
|
1632
|
+
log.info("Restored original HEAD", {
|
|
1633
|
+
branch: headState.branch,
|
|
1634
|
+
detached: headState.detached,
|
|
1635
|
+
});
|
|
1636
|
+
// Issue #466: verified off the work branch — the record is done.
|
|
1637
|
+
// A FAILED restore keeps it: the base lives only in the record.
|
|
1638
|
+
branch.clearHeadState();
|
|
1639
|
+
} else {
|
|
1640
|
+
log.warn("Failed to restore original HEAD during cleanup", {
|
|
1641
|
+
branch: headState.branch,
|
|
1642
|
+
error: restoreResult.error,
|
|
1643
|
+
});
|
|
1644
|
+
}
|
|
1645
|
+
}
|
|
1646
|
+
// Attempt to delete the work branch (non-critical)
|
|
1647
|
+
const deleteResult = deleteBranch(resolvedCwd, workBranchName);
|
|
1648
|
+
if (!deleteResult.ok) {
|
|
1649
|
+
log.warn("Failed to delete work branch during cleanup", {
|
|
1650
|
+
branch: workBranchName,
|
|
1651
|
+
error: deleteResult.error,
|
|
1652
|
+
});
|
|
1653
|
+
}
|
|
1654
|
+
},
|
|
1655
|
+
};
|
|
1656
|
+
|
|
1657
|
+
// P3: Git integration — set up work branch if gitMode is "branch"
|
|
1658
|
+
if (resolvedGitMode === "branch") {
|
|
1659
|
+
try {
|
|
1660
|
+
const headState = getHeadState(resolvedCwd);
|
|
1661
|
+
branch.headState = headState;
|
|
1662
|
+
|
|
1663
|
+
if (hasUncommittedChanges(resolvedCwd)) {
|
|
1664
|
+
log.warn("Uncommitted changes detected; proceeding with branch-based workflow anyway", {
|
|
1665
|
+
cwd: resolvedCwd,
|
|
1666
|
+
});
|
|
1667
|
+
}
|
|
1668
|
+
|
|
1669
|
+
// Written BEFORE the branch exists (D1): the name must be minted here.
|
|
1670
|
+
headStateRoot = getRepoRoot(resolvedCwd) ?? resolvedCwd;
|
|
1671
|
+
branch.workBranchName = newWorkBranchName();
|
|
1672
|
+
if (!writeHeadState({
|
|
1673
|
+
version: HEAD_STATE_VERSION,
|
|
1674
|
+
repoRoot: headStateRoot,
|
|
1675
|
+
runId,
|
|
1676
|
+
kind: "foreground",
|
|
1677
|
+
base: headState,
|
|
1678
|
+
workBranch: branch.workBranchName,
|
|
1679
|
+
owner: currentProcessOwner(),
|
|
1680
|
+
createdAt: new Date().toISOString(),
|
|
1681
|
+
})) {
|
|
1682
|
+
log.warn("headState record could not be written — an interrupted run will name no base", {
|
|
1683
|
+
runId,
|
|
1684
|
+
workBranch: branch.workBranchName,
|
|
1685
|
+
});
|
|
1686
|
+
}
|
|
1687
|
+
|
|
1688
|
+
const branchResult = createWorkBranch(resolvedCwd, headState.sha, branch.workBranchName);
|
|
1689
|
+
if (branchResult.ok) {
|
|
1690
|
+
log.info("Created work branch for subagent", {
|
|
1691
|
+
branch: branch.workBranchName,
|
|
1692
|
+
base: headState.branch,
|
|
1693
|
+
});
|
|
1694
|
+
} else {
|
|
1695
|
+
log.error("Failed to create work branch, falling back to 'none'", {
|
|
1696
|
+
error: branchResult.error,
|
|
1697
|
+
});
|
|
1698
|
+
// Nothing was created: nothing to repair.
|
|
1699
|
+
branch.clearHeadState();
|
|
1700
|
+
branch.headState = undefined;
|
|
1701
|
+
branch.workBranchName = undefined;
|
|
1702
|
+
}
|
|
1703
|
+
} catch (err) {
|
|
1704
|
+
log.warn("Not a git repository or git error; falling back to gitMode 'none'", {
|
|
1705
|
+
error: (err as Error).message,
|
|
1706
|
+
});
|
|
1707
|
+
branch.clearHeadState();
|
|
1708
|
+
branch.headState = undefined;
|
|
1709
|
+
branch.workBranchName = undefined;
|
|
1710
|
+
}
|
|
1711
|
+
}
|
|
1712
|
+
|
|
1713
|
+
return branch;
|
|
1714
|
+
}
|
|
1715
|
+
|
|
1716
|
+
/** The gate message the slot-cancel rejection returns and records (#340). */
|
|
1717
|
+
const SLOT_CANCEL_MESSAGE = "Subagent cancelled while waiting for concurrency slot.";
|
|
1718
|
+
|
|
1719
|
+
/**
|
|
1720
|
+
* Seam H's decision: is a pre-start gate already closed? Pure — the circuit
|
|
1721
|
+
* breaker is read, nothing is written — so the terminalize step and the slot
|
|
1722
|
+
* acquisition stay visible at the call site.
|
|
1723
|
+
*/
|
|
1724
|
+
function decidePreStartRejection(
|
|
1725
|
+
state: SessionState,
|
|
1726
|
+
): { kind: "proceed" } | { kind: "rejected"; message: string } {
|
|
1727
|
+
// R1: Circuit breaker check — reject if circuit is open
|
|
1728
|
+
const circuitCheck = state.checkCircuit();
|
|
1729
|
+
return circuitCheck.isOpen
|
|
1730
|
+
? { kind: "rejected", message: circuitCheck.message! }
|
|
1731
|
+
: { kind: "proceed" };
|
|
1732
|
+
}
|
|
1733
|
+
|
|
1734
|
+
/** What the pre-start terminalize step writes through. */
|
|
1735
|
+
interface PreStartDeps {
|
|
1736
|
+
state: SessionState;
|
|
1737
|
+
pi: ExtensionAPI;
|
|
1738
|
+
}
|
|
1739
|
+
|
|
1740
|
+
/**
|
|
1741
|
+
* Seam H's effect — terminalize the `running` record a pre-start gate rejected
|
|
1742
|
+
* (#340).
|
|
1743
|
+
*
|
|
1744
|
+
* The `running` record was persisted moments earlier, so without this the
|
|
1745
|
+
* session entry stays non-terminal, the in-flight registry row is never
|
|
1746
|
+
* cleared and the live registration is never released: a phantom interrupted
|
|
1747
|
+
* run at the next boot, and on a retry a dangling twin beside the source.
|
|
1748
|
+
*
|
|
1749
|
+
* The fabricated result drives `finalizeRunRecord` to terminal `failed`;
|
|
1750
|
+
* `stopReason: "aborted"` keeps the D1 `aborted` category coherent; the exact
|
|
1751
|
+
* gate message the caller will receive is recorded as `errorMessage`. The
|
|
1752
|
+
* terminal `state.persistRun` (no kind) clears the registry row via its
|
|
1753
|
+
* terminal-clear rule.
|
|
1754
|
+
*/
|
|
1755
|
+
function terminalizePreStartRejection(
|
|
1756
|
+
run: SubagentRun,
|
|
1757
|
+
errorMessage: string,
|
|
1758
|
+
deps: PreStartDeps,
|
|
1759
|
+
): void {
|
|
1760
|
+
const { state, pi } = deps;
|
|
1761
|
+
const rejection: SubagentResult = {
|
|
1762
|
+
messages: [],
|
|
1763
|
+
usage: { ...EMPTY_USAGE },
|
|
1764
|
+
exitCode: 1,
|
|
1765
|
+
stderr: "",
|
|
1766
|
+
stopReason: "aborted",
|
|
1767
|
+
errorMessage,
|
|
1768
|
+
errorCategory: "aborted",
|
|
1769
|
+
};
|
|
1770
|
+
finalizeRunRecord(run, rejection, "", new Date(run.startedAt).getTime());
|
|
1771
|
+
run.originalParams = { ...run.originalParams, errorCategory: rejection.errorCategory };
|
|
1772
|
+
state.persistRun(pi, run);
|
|
1773
|
+
state.finalizeLiveSubagent(run.id);
|
|
1774
|
+
}
|
|
1775
|
+
|
|
1776
|
+
/** The caller-facing result of a pre-start gate rejection (#340). */
|
|
1777
|
+
function preStartRejectionResult(message: string): ToolResult {
|
|
1778
|
+
return {
|
|
1779
|
+
content: [{ type: "text" as const, text: message }],
|
|
1780
|
+
details: undefined,
|
|
1781
|
+
isError: true,
|
|
1782
|
+
};
|
|
1783
|
+
}
|
|
1784
|
+
|
|
1785
|
+
/**
|
|
1786
|
+
* The concurrency priority a single foreground run queues with (issue #99 R2:
|
|
1787
|
+
* single mode honors priority like chain/parallel/graph do).
|
|
1788
|
+
*/
|
|
1789
|
+
function resolveSinglePriority(params: DelegateTaskParams): Priority {
|
|
1790
|
+
return params.priority && ["critical", "high", "normal", "low"].includes(params.priority)
|
|
1791
|
+
? (params.priority as Priority)
|
|
1792
|
+
: DEFAULT_PRIORITY;
|
|
1793
|
+
}
|
|
1794
|
+
|
|
1795
|
+
/** Seam I's value: everything the child is assembled from, computed once. */
|
|
1796
|
+
interface ForegroundRunInput {
|
|
1797
|
+
/** The full system prompt (base + the inheritance/custom rules). */
|
|
1798
|
+
subagentPrompt: string;
|
|
1799
|
+
/** The `describePromptMode` label for the initial progress update. */
|
|
1800
|
+
modeInfo: string;
|
|
1801
|
+
/** This depth + 1 — the child's recursion level. */
|
|
1802
|
+
childDepth: number;
|
|
1803
|
+
}
|
|
1804
|
+
|
|
1805
|
+
/**
|
|
1806
|
+
* Seam I — assemble the child's input (issue #430).
|
|
1807
|
+
*
|
|
1808
|
+
* Synchronous and side-effect free ON PURPOSE: the prompt build reads the
|
|
1809
|
+
* caller's live system prompt and the resolved tool/preset options, and the
|
|
1810
|
+
* initial `onUpdate` payload is derived from `modeInfo`. Keeping the awaits
|
|
1811
|
+
* (the runner call, the timeout retry) out of this seam is what lets it be
|
|
1812
|
+
* tested and measured without a process.
|
|
1813
|
+
*/
|
|
1814
|
+
function buildForegroundRunInput(
|
|
1815
|
+
prepared: Pick<
|
|
1816
|
+
ForegroundPrepared,
|
|
1817
|
+
"inheritSP" | "customSP" | "resolvedOutputFile" | "toolOptions" | "resolvedPreset" | "currentDepth"
|
|
1818
|
+
>,
|
|
1819
|
+
ctx: ExtensionContext,
|
|
1820
|
+
): ForegroundRunInput {
|
|
1821
|
+
const { inheritSP, customSP, resolvedOutputFile, toolOptions, resolvedPreset, currentDepth } = prepared;
|
|
1822
|
+
// Build system prompt
|
|
1823
|
+
const basePrompt = ctx.getSystemPrompt();
|
|
1824
|
+
const subagentPrompt = buildSubagentPrompt(
|
|
1825
|
+
basePrompt,
|
|
1826
|
+
inheritSP,
|
|
1827
|
+
customSP,
|
|
1828
|
+
resolvedOutputFile,
|
|
1829
|
+
toolOptions?.tools,
|
|
1830
|
+
resolvedPreset?.promptGuideline,
|
|
1831
|
+
);
|
|
1832
|
+
return {
|
|
1833
|
+
subagentPrompt,
|
|
1834
|
+
modeInfo: describePromptMode(inheritSP, Boolean(customSP)),
|
|
1835
|
+
childDepth: currentDepth + 1,
|
|
1836
|
+
};
|
|
1837
|
+
}
|
|
1838
|
+
|
|
1839
|
+
/**
|
|
1840
|
+
* Whether the child's failure is the auto-retry trigger (issue #229 rule):
|
|
1841
|
+
* an explicit `retryOnTimeout` on a run the runner reported as timed out.
|
|
1842
|
+
* Extracted so the retry's SHAPE (one retry, same run, refreshed deadline)
|
|
1843
|
+
* stays at the call site while the predicate is nameable.
|
|
1844
|
+
*/
|
|
1845
|
+
function isTimeoutRetry(params: DelegateTaskParams, result: SubagentResult): boolean {
|
|
1846
|
+
return Boolean(
|
|
1847
|
+
params.retryOnTimeout &&
|
|
1848
|
+
isSubagentError(result) &&
|
|
1849
|
+
result.errorMessage?.includes("timed out"),
|
|
1850
|
+
);
|
|
1851
|
+
}
|
|
1852
|
+
|
|
1853
|
+
/** How the approval flow should treat a finished work branch. */
|
|
1854
|
+
type BranchPlan =
|
|
1855
|
+
/** Ask the user (a UI gate exists and the mode wants a decision). */
|
|
1856
|
+
| "prompt"
|
|
1857
|
+
/** No prompt: merge the changes (auto-approve). */
|
|
1858
|
+
| "merge"
|
|
1859
|
+
/** No prompt: no changes to keep — delete the empty branch. */
|
|
1860
|
+
| "discard";
|
|
1861
|
+
|
|
1862
|
+
/** The inputs the approval decision keys on. */
|
|
1863
|
+
interface BranchDecision {
|
|
1864
|
+
hasUI: boolean;
|
|
1865
|
+
approvalMode: ApprovalMode;
|
|
1866
|
+
hasChanges: boolean;
|
|
1867
|
+
}
|
|
1868
|
+
|
|
1869
|
+
/**
|
|
1870
|
+
* Seam J's decision table (P4, #308) — pure.
|
|
1871
|
+
*
|
|
1872
|
+
* `prompt` requires a UI and a mode that wants a decision: `always` always
|
|
1873
|
+
* asks; `writes` asks only when the branch actually carries changes. Without a
|
|
1874
|
+
* UI nothing can ask, so the mode degrades to the auto-approve path (its own
|
|
1875
|
+
* log line names it) rather than silently discarding work.
|
|
1876
|
+
*/
|
|
1877
|
+
function decideBranchOutcome(input: BranchDecision): BranchPlan {
|
|
1878
|
+
if (input.hasUI && (input.approvalMode === "always" || (input.approvalMode === "writes" && input.hasChanges))) {
|
|
1879
|
+
return "prompt";
|
|
1880
|
+
}
|
|
1881
|
+
return input.hasChanges ? "merge" : "discard";
|
|
1882
|
+
}
|
|
1883
|
+
|
|
1884
|
+
/** What seam K's accounting reads. */
|
|
1885
|
+
interface FinalizeDeps {
|
|
1886
|
+
state: SessionState;
|
|
1887
|
+
ctx: ExtensionContext;
|
|
1888
|
+
pi: ExtensionAPI;
|
|
1889
|
+
log: Logger;
|
|
1890
|
+
}
|
|
1891
|
+
|
|
1892
|
+
/**
|
|
1893
|
+
* Seam K (record/accounting half) — finalize the run record, the live entry and
|
|
1894
|
+
* the SLA snapshot, in that order (issues #114, #179, E4).
|
|
1895
|
+
*
|
|
1896
|
+
* Sequence preserved exactly: `finalizeRunRecord` (terminal fields + output
|
|
1897
|
+
* summary), stamp `errorCategory` onto the retry snapshot, persist (which
|
|
1898
|
+
* clears the in-flight registry row), prune, release the live entry, then the
|
|
1899
|
+
* SLA window. A throw anywhere in here reaches the caller's `catch` — the same
|
|
1900
|
+
* boundary the inline statements had.
|
|
1901
|
+
*/
|
|
1902
|
+
function finalizeForegroundResult(
|
|
1903
|
+
run: SubagentRun,
|
|
1904
|
+
result: SubagentResult,
|
|
1905
|
+
finalOutput: string,
|
|
1906
|
+
deps: FinalizeDeps,
|
|
1907
|
+
): void {
|
|
1908
|
+
const { state, ctx, pi, log } = deps;
|
|
1909
|
+
// Finalize run record
|
|
1910
|
+
finalizeRunRecord(
|
|
1911
|
+
run,
|
|
1912
|
+
result,
|
|
1913
|
+
finalOutput,
|
|
1914
|
+
new Date(run.startedAt).getTime(),
|
|
1915
|
+
);
|
|
1916
|
+
run.originalParams = {
|
|
1917
|
+
...run.originalParams,
|
|
1918
|
+
errorCategory: result.errorCategory,
|
|
1919
|
+
};
|
|
1920
|
+
state.persistRun(pi, run);
|
|
1921
|
+
|
|
1922
|
+
// R2: Prune old run entries
|
|
1923
|
+
pruneHistoryIfNeeded(state, ctx, log);
|
|
1924
|
+
|
|
1925
|
+
// Finalize live monitor
|
|
1926
|
+
state.finalizeLiveSubagent(run.id);
|
|
1927
|
+
|
|
1928
|
+
// E4: SLA tracking — compute metrics if enabled
|
|
1929
|
+
if (state.config.slaTrackingEnabled) {
|
|
1930
|
+
const recentRuns = state.getLogicalRunEntries(ctx).slice(0, state.config.slaWindowSize);
|
|
1931
|
+
const metrics = computeSLAMetrics(recentRuns);
|
|
1932
|
+
log.info("SLA metrics computed", {
|
|
1933
|
+
totalRuns: metrics.totalRuns,
|
|
1934
|
+
successRate: metrics.successRate,
|
|
1935
|
+
p95DurationMs: metrics.p95DurationMs,
|
|
1936
|
+
totalCost: metrics.totalCost,
|
|
1937
|
+
});
|
|
1938
|
+
if (state.config.lastSLAMetrics) {
|
|
1939
|
+
const report = computeDegradation(metrics, state.config.lastSLAMetrics);
|
|
1940
|
+
if (report.degraded) {
|
|
1941
|
+
log.warn("SLA degradation detected", {
|
|
1942
|
+
successRateChange: report.successRateChange,
|
|
1943
|
+
p95Change: report.p95Change,
|
|
1944
|
+
recommendations: report.recommendations,
|
|
1945
|
+
});
|
|
1946
|
+
}
|
|
1947
|
+
}
|
|
1948
|
+
state.config.lastSLAMetrics = metrics;
|
|
1949
|
+
}
|
|
1950
|
+
}
|
|
1951
|
+
|
|
1952
|
+
/** What the classified-failure report reads. */
|
|
1953
|
+
interface FailureReportDeps {
|
|
1954
|
+
state: SessionState;
|
|
1955
|
+
log: Logger;
|
|
1956
|
+
runId: string;
|
|
1957
|
+
task: string;
|
|
1958
|
+
toolOptions: SubagentToolOptions | undefined;
|
|
1959
|
+
thinkingLevel: ThinkingLevel;
|
|
1960
|
+
resolvedGitMode: GitMode;
|
|
1961
|
+
timeout: number | undefined;
|
|
1962
|
+
warningsNote: string;
|
|
1963
|
+
resolvedCwd: string;
|
|
1964
|
+
/** The sanitized child output — the last-resort failure message. */
|
|
1965
|
+
finalOutput: string;
|
|
1966
|
+
}
|
|
1967
|
+
|
|
1968
|
+
/**
|
|
1969
|
+
* Seam K (failure half) — build the classified-failure message and record the
|
|
1970
|
+
* failure (H3 diagnostics, R1 circuit breaker).
|
|
1971
|
+
*
|
|
1972
|
+
* The message order is part of the result the conductor reads: cause first,
|
|
1973
|
+
* the H3 suggestions next, then the H1 warnings, and the worktree residue
|
|
1974
|
+
* LAST (issue #474). Returns the text; the transcript call and the returned
|
|
1975
|
+
* result stay at the call site so their order cannot drift.
|
|
1976
|
+
*/
|
|
1977
|
+
function buildFailureReport(result: SubagentResult, deps: FailureReportDeps): string {
|
|
1978
|
+
const { state, log, runId, task, toolOptions, thinkingLevel, resolvedGitMode, timeout, warningsNote, resolvedCwd, finalOutput } = deps;
|
|
1979
|
+
const errorMsg =
|
|
1980
|
+
result.errorMessage ||
|
|
1981
|
+
result.stderr ||
|
|
1982
|
+
finalOutput ||
|
|
1983
|
+
"(no output from subagent)";
|
|
1984
|
+
log.warn("Subagent failed", {
|
|
1985
|
+
runId,
|
|
1986
|
+
error: errorMsg,
|
|
1987
|
+
exitCode: result.exitCode,
|
|
1988
|
+
errorCategory: result.errorCategory,
|
|
1989
|
+
});
|
|
1990
|
+
|
|
1991
|
+
// H3: Post-mortem diagnostics — suggest fixes for the failure
|
|
1992
|
+
const suggestions = diagnoseFailure({
|
|
1993
|
+
task,
|
|
1994
|
+
toolOptions,
|
|
1995
|
+
thinkingLevel,
|
|
1996
|
+
gitMode: resolvedGitMode,
|
|
1997
|
+
errorMessage: result.errorMessage,
|
|
1998
|
+
exitCode: result.exitCode,
|
|
1999
|
+
timeout,
|
|
2000
|
+
});
|
|
2001
|
+
|
|
2002
|
+
// R1: Record failure in circuit breaker
|
|
2003
|
+
state.recordFailure();
|
|
2004
|
+
|
|
2005
|
+
let finalMsg = `Subagent failed: ${errorMsg}`;
|
|
2006
|
+
if (suggestions.length > 0) {
|
|
2007
|
+
finalMsg += "\n\nSuggestions:\n" + suggestions.map((s) => `- ${s}`).join("\n");
|
|
2008
|
+
}
|
|
2009
|
+
// C: warnings ride the returned result too — a failed run is
|
|
2010
|
+
// exactly when the conductor most needs the mismatch signal.
|
|
2011
|
+
finalMsg += warningsNote;
|
|
2012
|
+
// Issue #474: the failure path reports the tree it may have left
|
|
2013
|
+
// behind. Appended LAST — the cause and its H1 warnings read
|
|
2014
|
+
// first, the residue after. This is the classified-failure exit
|
|
2015
|
+
// (no throw), the second foreground surface beside the crash seam.
|
|
2016
|
+
return appendWorktreeState(finalMsg, resolvedCwd);
|
|
2017
|
+
}
|
|
2018
|
+
|
|
2019
|
+
/** Seam K's successful result: the child's output plus the dispatch notes. */
|
|
2020
|
+
function successResult(
|
|
2021
|
+
result: SubagentResult,
|
|
2022
|
+
finalOutput: string,
|
|
2023
|
+
prepared: Pick<
|
|
2024
|
+
ForegroundPrepared,
|
|
2025
|
+
"autoRoutedPreset" | "autoRouteKeyword" | "toolOptions" | "warningsNote"
|
|
2026
|
+
>,
|
|
2027
|
+
): ToolResult {
|
|
2028
|
+
// B2: Surface auto-route decisions in the tool result so the conductor
|
|
2029
|
+
// sees WHICH preset was auto-selected, the KEYWORD evidence for it,
|
|
2030
|
+
// and what it restricts. Derive the restriction from the RESOLVED
|
|
2031
|
+
// toolOptions (reflects per-call overrides) rather than the preset's
|
|
2032
|
+
// declared values.
|
|
2033
|
+
const { autoRoutedPreset, autoRouteKeyword, toolOptions, warningsNote } = prepared;
|
|
2034
|
+
const autoRouteNote = autoRoutedPreset
|
|
2035
|
+
? `\n\n[auto-routed to preset '${autoRoutedPreset.name}'${autoRouteKeyword ? ` (matched keyword '${autoRouteKeyword}')` : ""} — ${toolOptions ? formatToolRestriction(toolOptions) : formatPresetRestriction(autoRoutedPreset)}]`
|
|
2036
|
+
: "";
|
|
2037
|
+
|
|
2038
|
+
return {
|
|
2039
|
+
content: [
|
|
2040
|
+
{ type: "text" as const, text: (finalOutput || "(no output)") + autoRouteNote + warningsNote },
|
|
2041
|
+
],
|
|
2042
|
+
details: result,
|
|
2043
|
+
};
|
|
2044
|
+
}
|
|
2045
|
+
|
|
2046
|
+
/** What the crash path reads. */
|
|
2047
|
+
interface CrashDeps {
|
|
2048
|
+
state: SessionState;
|
|
2049
|
+
pi: ExtensionAPI;
|
|
2050
|
+
log: Logger;
|
|
2051
|
+
resolvedCwd: string;
|
|
2052
|
+
}
|
|
2053
|
+
|
|
2054
|
+
/**
|
|
2055
|
+
* Seam L (crash half) — turn a thrown error into the sanitized crash result,
|
|
2056
|
+
* release the live entry and persist the FAILED record (P3 R2).
|
|
2057
|
+
*
|
|
2058
|
+
* Mirrors the completion path: without the live finalize + terminal persist the
|
|
2059
|
+
* entry stays `running` forever, the stale sweep never reclaims it, and the
|
|
2060
|
+
* monitor drills into a run that cannot settle. The git cleanup and the failed
|
|
2061
|
+
* transcript happen at the call site, BEFORE this, exactly where they were.
|
|
2062
|
+
*/
|
|
2063
|
+
function finalizeCrashedRun(err: unknown, run: SubagentRun, deps: CrashDeps): ToolResult {
|
|
2064
|
+
const { state, pi, log, resolvedCwd } = deps;
|
|
2065
|
+
const result = buildCrashResult("Subagent", err, resolvedCwd);
|
|
2066
|
+
log.error("Subagent crashed", { runId: run.id, error: result.details.errorMessage });
|
|
2067
|
+
|
|
2068
|
+
state.finalizeLiveSubagent(run.id);
|
|
2069
|
+
const crashOutput = state.subagentSessions.get(run.id)?.liveOutput ?? "";
|
|
2070
|
+
finalizeRunRecord(
|
|
2071
|
+
run,
|
|
2072
|
+
result.details,
|
|
2073
|
+
crashOutput,
|
|
2074
|
+
new Date(run.startedAt).getTime(),
|
|
2075
|
+
);
|
|
2076
|
+
state.persistRun(pi, run);
|
|
2077
|
+
|
|
2078
|
+
return result;
|
|
2079
|
+
}
|
|
2080
|
+
|
|
2081
|
+
/**
|
|
2082
|
+
* The retry's display deadline, re-anchored on the retry's own start clock
|
|
2083
|
+
* (issue #423). A zero/absent timeout arms no deadline at all.
|
|
2084
|
+
*/
|
|
2085
|
+
function deadlineFrom(startedAt: number, timeout: number | undefined): number | undefined {
|
|
2086
|
+
return timeout && timeout > 0 ? startedAt + timeout : undefined;
|
|
2087
|
+
}
|
|
2088
|
+
|
|
2089
|
+
/**
|
|
2090
|
+
* Build the `delegate_task` definition over one runtime context (ADR 0027 D1/D3).
|
|
2091
|
+
*
|
|
2092
|
+
* The destructures are the whole wrapper: they re-create, as locals, the three
|
|
2093
|
+
* names the moved bodies read from their old closure. `deps` is destructured too
|
|
2094
|
+
* so the four injected entry points read exactly as they did inline.
|
|
2095
|
+
*/
|
|
2096
|
+
export function createDelegateHandler(
|
|
2097
|
+
rt: RuntimeContext,
|
|
2098
|
+
deps: DelegateHandlerDeps,
|
|
2099
|
+
): DelegateTaskTool {
|
|
2100
|
+
const { pi, log, state } = rt;
|
|
2101
|
+
const {
|
|
2102
|
+
runChainMode,
|
|
2103
|
+
runParallelMode,
|
|
2104
|
+
runGraphMode,
|
|
2105
|
+
runBackgroundFanOut,
|
|
2106
|
+
spawnBackgroundRun,
|
|
2107
|
+
visibleRunsFor,
|
|
2108
|
+
} = deps;
|
|
2109
|
+
|
|
2110
|
+
// B1: Load built-in presets once at registration to expose their tool
|
|
2111
|
+
// restrictions to the conductor before any delegate_task call happens.
|
|
2112
|
+
const registrationPresets = loadBuiltinPresets(pkgPath("presets"));
|
|
2113
|
+
const presetRestrictionSummary = buildInventorySummary(registrationPresets, (p) => {
|
|
2114
|
+
const restricted = p.excludeTools?.length || p.tools?.length;
|
|
2115
|
+
if (!restricted) return p.name;
|
|
2116
|
+
return `${p.name} (${formatPresetRestriction(p)})`;
|
|
2117
|
+
});
|
|
2118
|
+
|
|
2119
|
+
// B1b: Load built-in templates once at registration to expose the built-in
|
|
2120
|
+
// inventory (name + purpose + ${param} slots) to the conductor before any
|
|
2121
|
+
// delegate_task call. Custom/user templates can't be enumerated statically,
|
|
2122
|
+
// so the summary covers built-ins only and points at /brl-subagent templates.
|
|
2123
|
+
const registrationTemplates = loadBuiltinTemplates(pkgPath("templates"));
|
|
2124
|
+
const templateSummary = buildInventorySummary(registrationTemplates, formatTemplateSummaryItem);
|
|
2125
|
+
|
|
2126
|
+
// Issue #158: resolve the shipped AGENT.md from the extension's own directory
|
|
2127
|
+
// rather than a hardcoded sync-copy destination, so npm-installed packages
|
|
2128
|
+
// (installed via `pi install npm:brl-subagent`) can find it.
|
|
2129
|
+
const agentMdPath = pkgPath("AGENT.md");
|
|
2130
|
+
|
|
2131
|
+
return {
|
|
2132
|
+
name: "delegate_task",
|
|
2133
|
+
label: "Delegate Task",
|
|
2134
|
+
description: [
|
|
2135
|
+
"Delegate a task to the brl-subagent with isolated context.",
|
|
2136
|
+
"The subagent inherits your current system prompt and runs with",
|
|
2137
|
+
"its configured model and thinking level (set via /brl-subagent).",
|
|
2138
|
+
"If no subagent model is configured, your current model is used.",
|
|
2139
|
+
"The subagent reports what it did when complete.",
|
|
2140
|
+
"Optionally provide a custom systemPrompt and control inheritance via inheritSystemPrompt.",
|
|
2141
|
+
].join(" "),
|
|
2142
|
+
promptSnippet:
|
|
2143
|
+
"Delegate tasks to a subagent for isolated, parallel or background work",
|
|
2144
|
+
promptGuidelines: [
|
|
2145
|
+
"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).",
|
|
2146
|
+
`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.`,
|
|
2147
|
+
"The subagent inherits your system prompt and runs with its own model (configurable via /brl-subagent). It reports what it did when done.",
|
|
2148
|
+
"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.",
|
|
2149
|
+
"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.",
|
|
2150
|
+
"Use outputFile to have the subagent write full findings to disk and return only a structured summary — saves context tokens for large investigations.",
|
|
2151
|
+
"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).",
|
|
2152
|
+
"Set cwd to override the subagent's working directory. Defaults to the current project directory.",
|
|
2153
|
+
"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.",
|
|
2154
|
+
`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.`,
|
|
2155
|
+
buildTemplateGuideline(templateSummary),
|
|
2156
|
+
"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.",
|
|
2157
|
+
"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.",
|
|
2158
|
+
"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.",
|
|
2159
|
+
"",
|
|
2160
|
+
"## Conductor Guardrails",
|
|
2161
|
+
"",
|
|
2162
|
+
"Before delegating, verify the subagent configuration matches the task:",
|
|
2163
|
+
"",
|
|
2164
|
+
"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.",
|
|
2165
|
+
"3. **Git mode**: Use gitMode='branch' for tasks that create commits or PRs. Use gitMode='none' for read-only tasks.",
|
|
2166
|
+
"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.",
|
|
2167
|
+
"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.",
|
|
2168
|
+
"",
|
|
2169
|
+
"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.",
|
|
2170
|
+
"",
|
|
2171
|
+
"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.",
|
|
2172
|
+
"The autoRoutePreset() function can automatically select the best preset based on task keywords. Consider using it for preset selection.",
|
|
2173
|
+
"Prefer a preset when the delegation matches a standard shape — review/audit/test/docs; override per-call deliberately.",
|
|
2174
|
+
],
|
|
2175
|
+
parameters: delegateTaskParamsSchema,
|
|
2176
|
+
|
|
2177
|
+
async execute(
|
|
2178
|
+
_toolCallId: string,
|
|
2179
|
+
params: DelegateTaskParams,
|
|
2180
|
+
signal: AbortSignal | undefined,
|
|
2181
|
+
onUpdate: AgentToolUpdateCallback<DelegateTaskDetails> | undefined,
|
|
2182
|
+
ctx: ExtensionContext,
|
|
2183
|
+
) {
|
|
2184
|
+
// Seam A: unknown-param warning, template resolution, retry restore.
|
|
2185
|
+
// Synchronous unless the retry falls back through the visibility bridge.
|
|
2186
|
+
const normalized = normalizeInput(params, { state, ctx, pi, log, visibleRunsFor });
|
|
2187
|
+
const pre: Outcome<NormalizedDispatch> =
|
|
2188
|
+
normalized instanceof Promise ? await normalized : normalized;
|
|
2189
|
+
if (!pre.ok) return pre.result;
|
|
2190
|
+
params = pre.value.params;
|
|
2191
|
+
// Option B U1: the run the retryRunId resolved to (spawn entry).
|
|
2192
|
+
// Internal record identity — dispatchId/resumeOf/attempt are threaded
|
|
2193
|
+
// onto the new record, NOT through the delegate-param surface (D4).
|
|
2194
|
+
const retrySourceRun = pre.value.retrySourceRun;
|
|
2195
|
+
|
|
2196
|
+
// Seam B: sanitize the single-task body, then classify the shape.
|
|
2197
|
+
const shape = resolveShape(params, log);
|
|
2198
|
+
if (!shape.ok) return shape.result;
|
|
2199
|
+
|
|
2200
|
+
// Seam C: the #412 pre-flight, the background default and the #434
|
|
2201
|
+
// unit-projection inputs — one resolution per dispatch.
|
|
2202
|
+
const prepared = prepareShape(params, shape.value, { state, ctx, pi, log });
|
|
2203
|
+
if (!prepared.ok) return prepared.result;
|
|
2204
|
+
|
|
2205
|
+
// Seam D: hand the dispatch to the injected runner, or keep the single
|
|
2206
|
+
// foreground run below. The runner's own promise is RETURNED, never
|
|
2207
|
+
// awaited here — a seam that awaited it would add a settlement turn.
|
|
2208
|
+
const route = routeDispatch(params, shape.value, prepared.value, {
|
|
2209
|
+
pi,
|
|
2210
|
+
ctx,
|
|
2211
|
+
signal,
|
|
2212
|
+
onUpdate,
|
|
2213
|
+
retrySourceRun,
|
|
2214
|
+
runners: {
|
|
2215
|
+
runChainMode,
|
|
2216
|
+
runParallelMode,
|
|
2217
|
+
runGraphMode,
|
|
2218
|
+
runBackgroundFanOut,
|
|
2219
|
+
spawnBackgroundRun,
|
|
2220
|
+
},
|
|
2221
|
+
});
|
|
2222
|
+
if (route.kind === "returned") return route.result;
|
|
2223
|
+
const singleTask = route.singleTask;
|
|
2224
|
+
|
|
2225
|
+
// Seam E: foreground admission — cost, depth, cwd/output, preflight,
|
|
2226
|
+
// capability validation, model resolution. No run record exists yet, so
|
|
2227
|
+
// every rejection here returns without persisting anything.
|
|
2228
|
+
const admitted = prepareForeground(params, singleTask, { state, ctx, log });
|
|
2229
|
+
if (!admitted.ok) return admitted.result;
|
|
2230
|
+
|
|
2231
|
+
// Seam F–L: the single foreground run. Everything that outlives this
|
|
2232
|
+
// call — the run record, the work branch, the slot, the child process,
|
|
2233
|
+
// the approval gate — is owned by the orchestrator below.
|
|
2234
|
+
return runForeground(params, admitted.value, retrySourceRun, {
|
|
2235
|
+
pi,
|
|
2236
|
+
state,
|
|
2237
|
+
ctx,
|
|
2238
|
+
log,
|
|
2239
|
+
signal,
|
|
2240
|
+
onUpdate,
|
|
2241
|
+
});
|
|
2242
|
+
},
|
|
2243
|
+
|
|
2244
|
+
renderCall(
|
|
2245
|
+
args: DelegateTaskParams,
|
|
2246
|
+
theme: Theme,
|
|
2247
|
+
_context: unknown,
|
|
2248
|
+
) {
|
|
2249
|
+
return renderDelegateCall(args, theme);
|
|
2250
|
+
},
|
|
2251
|
+
|
|
2252
|
+
renderResult(
|
|
2253
|
+
result: AgentToolResult<DelegateTaskDetails>,
|
|
2254
|
+
options: ToolRenderResultOptions,
|
|
2255
|
+
theme: Theme,
|
|
2256
|
+
_context: unknown,
|
|
2257
|
+
) {
|
|
2258
|
+
return renderDelegateResult(result, options, theme);
|
|
2259
|
+
},
|
|
2260
|
+
};
|
|
2261
|
+
}
|