brl-subagent 2.5.1 → 2.6.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/src/index.ts CHANGED
@@ -73,9 +73,18 @@ import { gateSessionCost, rejectApprovalAlwaysInBackground, runPreTaskValidation
73
73
  import { loadBuiltinPresets, loadCustomPresets, getAllPresets, writePresetFile, formatPresetRestriction, formatToolRestriction } from "./presets";
74
74
  import { modelIsAvailable } from "./model-availability";
75
75
  import { validatePreTask, diagnoseFailure, DEFAULT_BACKGROUND_DEADLINE_MS } from "./validate";
76
- import { findUnknownParams, KNOWN_DELEGATE_KEYS, resolveSubagentParams, snapshotOriginalParams } from "./params";
76
+ import {
77
+ defaultBackgroundFor,
78
+ findUnknownParams,
79
+ KNOWN_DELEGATE_KEYS,
80
+ resolveEffectiveApprovalMode,
81
+ resolveSubagentParams,
82
+ shouldRejectBackgroundForBatch,
83
+ snapshotOriginalParams,
84
+ type DispatchShape,
85
+ } from "./params";
77
86
  import { delegateTaskParamsSchema } from "./schema";
78
- import { createSessionState, resolveTerminalRunEntry } from "./state";
87
+ import { createSessionState, resolveTerminalRunEntry, type SessionState } from "./state";
79
88
  import { makeLiveOnUpdate, createUnitRun, finalizeUnitRun, finalizeUnitRunCrash, pruneHistoryIfNeeded, registerLiveRun } from "./unit-run";
80
89
  import { buildSubagentPrompt, describePromptMode } from "./prompt";
81
90
  import { runSubagent, cleanupTempDirs, reapActiveChildren } from "./runner";
@@ -85,7 +94,7 @@ import {
85
94
  newDispatchIdentity,
86
95
  } from "./recovery";
87
96
  import { markInterrupted, listInflightRuns, clearInflightRun } from "./run-registry";
88
- import { acquireSlot, releaseSlot, updateStatus, updateProgressStatus } from "./concurrency";
97
+ import { acquireSlot, clearProgressLinger, releaseSlot, repaintStatus, stopProgressTicker } from "./concurrency";
89
98
  import { transcriptDisplayPath } from "./transcript-path";
90
99
  import {
91
100
  finalizeRunRecord,
@@ -182,6 +191,34 @@ export function buildTemplateGuideline(templateSummary: string): string {
182
191
  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.`;
183
192
  }
184
193
 
194
+ /**
195
+ * Issue #354 review minor: the synchronous shutdown cleanup, extracted so the
196
+ * real body (not a hand-mirrored copy) is exercised by tests. Clears every
197
+ * session-bound live collection, resets the counters, and stops both footer
198
+ * timers. Ordering is significant: the ticker is stopped before the linger is
199
+ * cleared, and the maps are cleared before their guard claim set.
200
+ */
201
+ export function cleanupSessionState(state: SessionState): void {
202
+ // Clear all live subagent sessions
203
+ state.subagentSessions.clear();
204
+ // Drop pending finalize claims too (PR #71 review: the claim set must
205
+ // not outlive the map it guards — a fresh session could otherwise
206
+ // no-op on an id a stale claim still remembers).
207
+ state.resetLiveFinalizeClaims();
208
+ // Reset counters
209
+ state.activeSubagents = 0;
210
+ state.completedSubagents = 0;
211
+ state.failedSubagents = 0;
212
+ state.unseenSubagents = 0;
213
+ // Issue #354: the footer ticker must not outlive the session (it also
214
+ // drops the elapsed anchor, so a new session starts its own clock), and
215
+ // neither may the 3 s linger timer (F2) — it would repaint a dead pane.
216
+ stopProgressTicker(state);
217
+ clearProgressLinger(state);
218
+ // Clear pending queue
219
+ state.pendingQueue.length = 0;
220
+ }
221
+
185
222
  // ---------------------------------------------------------------------------
186
223
  // Extension entry point
187
224
  // ---------------------------------------------------------------------------
@@ -219,7 +256,10 @@ export default function (pi: ExtensionAPI) {
219
256
  // -------------------------------------------------------------------
220
257
 
221
258
  function applyConfig(ctx: ExtensionContext, message: string) {
222
- updateStatus(state, ctx);
259
+ // Issue #354: a config change mid-run must not blank the footer —
260
+ // repaintStatus renders the activity line while runs are active and
261
+ // falls back to the idle config line when none are.
262
+ repaintStatus(state, ctx);
223
263
  state.persistState(pi);
224
264
  ctx.ui.notify(message, "info");
225
265
  }
@@ -239,7 +279,7 @@ export default function (pi: ExtensionAPI) {
239
279
  getAllPresets(state.builtinPresets, state.customPresets),
240
280
  log,
241
281
  );
242
- updateStatus(state, ctx);
282
+ repaintStatus(state, ctx);
243
283
  state.persistState(pi);
244
284
  ctx.ui.notify("Subagent configuration reset", "info");
245
285
  }
@@ -694,10 +734,10 @@ export default function (pi: ExtensionAPI) {
694
734
  };
695
735
  // Issue #133: render the breakdown — the chain holds ONE mode-level
696
736
  // slot (acquired at mode start, released in the finally), so no
697
- // per-step acquire/release calls updateProgressStatus while the
737
+ // per-step acquire/release calls repaintStatus while the
698
738
  // mode context is set. Call it directly here (mirrors how the
699
739
  // graph path's per-node slot operations trigger the render).
700
- updateProgressStatus(state, ctx);
740
+ repaintStatus(state, ctx);
701
741
 
702
742
  // Emit initial progress for this step
703
743
  const modeInfo = describePromptMode(
@@ -2362,7 +2402,7 @@ export default function (pi: ExtensionAPI) {
2362
2402
 
2363
2403
  // Update footer counters
2364
2404
  state.activeSubagents++;
2365
- updateProgressStatus(state, ctx);
2405
+ repaintStatus(state, ctx);
2366
2406
 
2367
2407
  let completed = false;
2368
2408
 
@@ -2394,7 +2434,7 @@ export default function (pi: ExtensionAPI) {
2394
2434
  if (state.activeSubagents < 0) state.activeSubagents = 0;
2395
2435
  }
2396
2436
  state.failedSubagents++;
2397
- updateProgressStatus(state, ctx);
2437
+ repaintStatus(state, ctx);
2398
2438
  sendCrashNotice(`Background agent "${agent.description}" crashed.`);
2399
2439
  return;
2400
2440
  }
@@ -2441,7 +2481,7 @@ export default function (pi: ExtensionAPI) {
2441
2481
 
2442
2482
  if (agent.status === 'failed') {
2443
2483
  state.failedSubagents++;
2444
- updateProgressStatus(state, ctx);
2484
+ repaintStatus(state, ctx);
2445
2485
  // Issue #315: the terminal wake (`subagent-completion`, emitted by
2446
2486
  // the session-manager settle) is the ONE notice for a failed run.
2447
2487
  // The status here was set by that settle, so the wake already
@@ -2449,11 +2489,11 @@ export default function (pi: ExtensionAPI) {
2449
2489
  } else if (agent.status === 'stopped') {
2450
2490
  // User-initiated stop (stop_subagent) or deadline abort
2451
2491
  // (timeout/deadline) — not a failure.
2452
- updateProgressStatus(state, ctx);
2492
+ repaintStatus(state, ctx);
2453
2493
  } else {
2454
2494
  state.completedSubagents++;
2455
2495
  state.unseenSubagents++;
2456
- updateProgressStatus(state, ctx);
2496
+ repaintStatus(state, ctx);
2457
2497
  }
2458
2498
  }
2459
2499
  } catch (err) {
@@ -2472,7 +2512,7 @@ export default function (pi: ExtensionAPI) {
2472
2512
  if (state.activeSubagents < 0) state.activeSubagents = 0;
2473
2513
  }
2474
2514
  state.failedSubagents++;
2475
- updateProgressStatus(state, ctx);
2515
+ repaintStatus(state, ctx);
2476
2516
  sendCrashNotice(`Background agent "${agent.description}" crashed: ${sanitizeErrorMessage((err as Error).message, spawn.sanitizeCwd)}`);
2477
2517
  }
2478
2518
  }
@@ -2517,7 +2557,7 @@ export default function (pi: ExtensionAPI) {
2517
2557
  }
2518
2558
  // m6: deadline abort is a stop, not a completion — mirror the
2519
2559
  // W3/poller stopped path (no completedSubagents increment).
2520
- updateProgressStatus(state, ctx);
2560
+ repaintStatus(state, ctx);
2521
2561
  } catch (err) {
2522
2562
  // Defensive: never let the deadline timer throw uncaught — that would
2523
2563
  // skip finalizeLiveSubagent, the counter decrement, and the notification.
@@ -2543,7 +2583,7 @@ export default function (pi: ExtensionAPI) {
2543
2583
  if (state.activeSubagents < 0) state.activeSubagents = 0;
2544
2584
  }
2545
2585
  state.failedSubagents++;
2546
- updateProgressStatus(state, ctx);
2586
+ repaintStatus(state, ctx);
2547
2587
  }
2548
2588
  }
2549
2589
  }, hardCapMs);
@@ -2823,7 +2863,7 @@ export default function (pi: ExtensionAPI) {
2823
2863
  buildTemplateGuideline(templateSummary),
2824
2864
  "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.",
2825
2865
  "Set retryOnTimeout: true to automatically retry a FOREGROUND subagent that times out. Only retries once — the second timeout is treated as a final failure. Background runs are not auto-retried; re-dispatch with retryRunId.",
2826
- "Set background: true to run the subagent in the background without blocking. The tool returns immediately with an agent ID. With tasks, background fans out: every task starts as its own background agent, the call returns one ID per task in task order, and the conductor is woken once per agent as each finishes; chain and graph cannot be combined with background (rejected). 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.",
2866
+ "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.",
2827
2867
  "",
2828
2868
  "## Conductor Guardrails",
2829
2869
  "",
@@ -3026,12 +3066,29 @@ export default function (pi: ExtensionAPI) {
3026
3066
  };
3027
3067
  }
3028
3068
 
3069
+ const dispatchShape: DispatchShape = isChain
3070
+ ? "chain"
3071
+ : isGraph
3072
+ ? "graph"
3073
+ : isParallel
3074
+ ? "parallel"
3075
+ : "single";
3076
+
3077
+ // Capture the caller's value BEFORE the default is recorded on
3078
+ // `params.background` below. The guard must judge what the caller
3079
+ // actually asked for; reading the recorded value would make it depend
3080
+ // on the default. Keeping the capture first makes that ordering
3081
+ // self-evident (issue #361 review).
3082
+ const explicitBackground = params.background;
3083
+
3029
3084
  // background: true with chain/graph was silently ignored — the batch ran
3030
3085
  // foreground (blocking until every unit finished) while the caller believed
3031
3086
  // it was background. Both remain rejected loudly at dispatch validation;
3032
3087
  // tasks (parallel) fans out into independent background agents instead.
3033
- if (params.background && (isChain || isGraph)) {
3034
- const batchMode = isChain ? "chain" : "graph";
3088
+ // Only an EXPLICIT true trips this (issue #361): an omitted `background`
3089
+ // now defaults to foreground here rather than being rejected.
3090
+ if (shouldRejectBackgroundForBatch(dispatchShape, explicitBackground)) {
3091
+ const batchMode = dispatchShape === "chain" ? "chain" : "graph";
3035
3092
  return {
3036
3093
  content: [
3037
3094
  {
@@ -3044,6 +3101,24 @@ export default function (pi: ExtensionAPI) {
3044
3101
  };
3045
3102
  }
3046
3103
 
3104
+ // Issue #361: background is the CONDITIONAL default for the shapes that
3105
+ // can run unattended. Resolved ONCE per dispatch and reused by the
3106
+ // single and fan-out paths below, so the decision cannot drift between
3107
+ // them. The approval mode is the EFFECTIVE one (call param, else the
3108
+ // configured default — presets declare no approvalMode today) — the same
3109
+ // value the child will run with — so the default never routes a run into a
3110
+ // background context that would break or silently auto-approve it
3111
+ // ('always' has no dialog; 'writes' gates the diff on approval).
3112
+ const useBackground =
3113
+ params.background ??
3114
+ defaultBackgroundFor(dispatchShape, resolveEffectiveApprovalMode(params.approvalMode, state));
3115
+ // Record the EFFECTIVE value on the dispatch (a no-op when the caller was
3116
+ // explicit): a run started by the default must retry as what it actually
3117
+ // was instead of re-deriving the default, which may since have moved with
3118
+ // the config. Fan-out units still record no background of their own — a
3119
+ // unit retries as a single foreground run (issue #229), unaffected here.
3120
+ params.background ??= useBackground;
3121
+
3047
3122
  if (isChain) {
3048
3123
  if (params.chain!.length > MAX_CHAIN_STEPS) {
3049
3124
  return {
@@ -3073,7 +3148,7 @@ export default function (pi: ExtensionAPI) {
3073
3148
  isError: true,
3074
3149
  };
3075
3150
  }
3076
- if (params.background) return runBackgroundFanOut(pi, ctx, params, signal);
3151
+ if (useBackground) return runBackgroundFanOut(pi, ctx, params, signal);
3077
3152
  return runParallelMode(params, signal, onUpdate, ctx);
3078
3153
  }
3079
3154
 
@@ -3086,7 +3161,7 @@ export default function (pi: ExtensionAPI) {
3086
3161
  // boolean-array filter — assert, mirroring params.chain!/params.tasks! above.
3087
3162
  const singleTask = params.task!; // non-empty (sanitizer guarantees; isSingle confirms)
3088
3163
 
3089
- if (params.background) {
3164
+ if (useBackground) {
3090
3165
  return spawnBackgroundRun(pi, ctx, params, singleTask, retrySourceRun);
3091
3166
  }
3092
3167
 
@@ -3331,9 +3406,40 @@ export default function (pi: ExtensionAPI) {
3331
3406
  }
3332
3407
  };
3333
3408
 
3409
+ // #340: both pre-start gate rejections below must finalize the
3410
+ // `running` record persisted just above. Without this the session entry
3411
+ // stays non-terminal, the inflight registry row (written by
3412
+ // `persistRun(..., "foreground")`) is never cleared, and the live
3413
+ // registration is never released — a phantom interrupted run at the
3414
+ // next boot (and, on a retry, a dangling twin beside the source).
3415
+ // The fabricated result drives `finalizeRunRecord` to terminal
3416
+ // `failed`; `stopReason: "aborted"` makes `coherentFailureReason` keep
3417
+ // the D1 `aborted` category coherent. The exact gate message the caller
3418
+ // receives is recorded as `errorMessage`; the terminal
3419
+ // `state.persistRun` (no kind) clears the registry row via its
3420
+ // terminal-clear rule. Returned content/isError and the retry-source
3421
+ // retention below are unchanged.
3422
+ const SLOT_CANCEL_MESSAGE = "Subagent cancelled while waiting for concurrency slot.";
3423
+ const finalizePreStartRejection = (errorMessage: string): void => {
3424
+ const rejection: SubagentResult = {
3425
+ messages: [],
3426
+ usage: { ...EMPTY_USAGE },
3427
+ exitCode: 1,
3428
+ stderr: "",
3429
+ stopReason: "aborted",
3430
+ errorMessage,
3431
+ errorCategory: "aborted",
3432
+ };
3433
+ finalizeRunRecord(run, rejection, "", new Date(run.startedAt).getTime());
3434
+ run.originalParams = { ...run.originalParams, errorCategory: rejection.errorCategory };
3435
+ state.persistRun(pi, run);
3436
+ state.finalizeLiveSubagent(run.id);
3437
+ };
3438
+
3334
3439
  // R1: Circuit breaker check — reject if circuit is open
3335
3440
  const circuitCheck = state.checkCircuit();
3336
3441
  if (circuitCheck.isOpen) {
3442
+ finalizePreStartRejection(circuitCheck.message!);
3337
3443
  cleanupGitBranch();
3338
3444
  return {
3339
3445
  content: [{ type: "text" as const, text: circuitCheck.message! }],
@@ -3352,12 +3458,13 @@ export default function (pi: ExtensionAPI) {
3352
3458
  // Acquire concurrency slot
3353
3459
  const acquired = await acquireSlot(state, ctx, signal, singlePriority);
3354
3460
  if (!acquired) {
3461
+ finalizePreStartRejection(SLOT_CANCEL_MESSAGE);
3355
3462
  cleanupGitBranch();
3356
3463
  return {
3357
3464
  content: [
3358
3465
  {
3359
3466
  type: "text" as const,
3360
- text: "Subagent cancelled while waiting for concurrency slot.",
3467
+ text: SLOT_CANCEL_MESSAGE,
3361
3468
  },
3362
3469
  ],
3363
3470
  details: undefined,
@@ -3371,11 +3478,10 @@ export default function (pi: ExtensionAPI) {
3371
3478
  // every pre-spawn gate and is about to start, so the SOURCE interrupted
3372
3479
  // registry entry is superseded — clear it here so the old run is not
3373
3480
  // re-offered at every subsequent boot. A failed pre-start (circuit open,
3374
- // slot cancelled) returns ABOVE this point and leaves the source intact
3375
- // and retryable — but note it is NOT "one row only": the pre-existing
3376
- // pre-start path (`persistRun`, which precedes the circuit/slot gates)
3377
- // still leaves a dangling `running` NEW row behind until the backlogged
3378
- // dangling-row fix. `retrySourceRun` is set only on a `retryRunId` call.
3481
+ // slot cancelled) returns ABOVE this point: the source is left intact
3482
+ // and retryable, while the NEW twin has already been finalized terminal
3483
+ // by the gate (#340) — nothing dangles. `retrySourceRun` is set only on
3484
+ // a `retryRunId` call.
3379
3485
  if (retrySourceRun) clearInflightRun(retrySourceRun.id);
3380
3486
 
3381
3487
  // F7 (issue #65): import BEFORE the try — the crash-path catch calls
@@ -4156,7 +4262,10 @@ export default function (pi: ExtensionAPI) {
4156
4262
  // run ONCE, at the next turn boundary (never mid-turn).
4157
4263
  await maybeSendRecoveryNotice(ctx);
4158
4264
 
4159
- updateStatus(state, ctx);
4265
+ // Issue #356: boot is a config-paint edge — route it through the same
4266
+ // chokepoint as every other footer repaint. With no runs in flight the
4267
+ // chokepoint draws the idle config line the old direct call painted.
4268
+ repaintStatus(state, ctx);
4160
4269
  });
4161
4270
 
4162
4271
  // F7: Clean up session-bound state on shutdown
@@ -4173,19 +4282,7 @@ export default function (pi: ExtensionAPI) {
4173
4282
  log.warn("Shutdown reap failed", { error: (err as Error).message });
4174
4283
  }
4175
4284
 
4176
- // Clear all live subagent sessions
4177
- state.subagentSessions.clear();
4178
- // Drop pending finalize claims too (PR #71 review: the claim set must
4179
- // not outlive the map it guards — a fresh session could otherwise
4180
- // no-op on an id a stale claim still remembers).
4181
- state.resetLiveFinalizeClaims();
4182
- // Reset counters
4183
- state.activeSubagents = 0;
4184
- state.completedSubagents = 0;
4185
- state.failedSubagents = 0;
4186
- state.unseenSubagents = 0;
4187
- // Clear pending queue
4188
- state.pendingQueue.length = 0;
4285
+ cleanupSessionState(state);
4189
4286
  // U3: a new session boot may notify again.
4190
4287
  recoveryNoticeDelivered = false;
4191
4288
  });
package/src/params.ts CHANGED
@@ -121,6 +121,77 @@ export function snapshotOriginalParams(params: {
121
121
  };
122
122
  }
123
123
 
124
+ // ---------------------------------------------------------------------------
125
+ // Effective approval mode + the background default (issue #361)
126
+ // ---------------------------------------------------------------------------
127
+
128
+ /**
129
+ * The approval mode that would actually apply to a child dispatched with these
130
+ * params: per-call param > configured default.
131
+ *
132
+ * Single source of truth (issue #361): `resolveSubagentParams` resolves the
133
+ * child's mode through this function, and the dispatch chokepoint uses it to
134
+ * pick the background default, so the mode that decides "can this run
135
+ * unattended?" is always the mode the child runs with. Presets declare no
136
+ * `approvalMode` field today (see SubagentPreset), so there is no preset tier;
137
+ * should one be added, it would slot in between the call param and the
138
+ * configured default.
139
+ */
140
+ export function resolveEffectiveApprovalMode(
141
+ approvalMode: string | undefined,
142
+ state: Pick<SessionState, "config">,
143
+ ): ApprovalMode {
144
+ return approvalMode === "auto" || approvalMode === "writes" || approvalMode === "always"
145
+ ? approvalMode
146
+ : state.config.approvalMode;
147
+ }
148
+
149
+ /**
150
+ * Dispatch shapes that can select a `background` default. `parallel` is the
151
+ * `tasks` fan-out; `chain`/`graph` are batch modes that always block.
152
+ */
153
+ export type DispatchShape = "single" | "parallel" | "chain" | "graph";
154
+
155
+ /**
156
+ * Whether an EXPLICIT `background` value must be rejected for the dispatch
157
+ * shape. Only `chain`/`graph` reject, and only an explicit `true` — an omitted
158
+ * `background` (`undefined`) is not an explicit request and falls through to
159
+ * `defaultBackgroundFor`, while an explicit `false` is always honoured. Pure
160
+ * and separate from dispatch so the guard's strictness and its position ahead
161
+ * of default resolution can be pinned independently (issue #361 review).
162
+ */
163
+ export function shouldRejectBackgroundForBatch(
164
+ shape: DispatchShape,
165
+ explicit: boolean | undefined,
166
+ ): boolean {
167
+ return explicit === true && (shape === "chain" || shape === "graph");
168
+ }
169
+
170
+ /**
171
+ * Issue #361: the CONDITIONAL default for `background` when the caller omits
172
+ * it. Background wins only where it cannot weaken a gate:
173
+ *
174
+ * - `chain`/`graph` stay foreground — they block by definition and an
175
+ * explicit `background: true` is still rejected at dispatch.
176
+ * - an effective approval mode that needs the interactive dialog
177
+ * (`always`) or gates on writes (`writes`) stays foreground — a
178
+ * background run has no dialog, so defaulting there would either break
179
+ * the run or silently auto-approve diffs the user asked to review.
180
+ * - everything else (single task, `tasks` fan-out, effective `auto`) is
181
+ * background: the tool returns an agent id immediately and the conductor
182
+ * is woken on terminal state.
183
+ *
184
+ * Explicit `true`/`false` always wins — callers spread `params.background ??
185
+ * defaultBackgroundFor(...)`.
186
+ */
187
+ export function defaultBackgroundFor(
188
+ shape: DispatchShape,
189
+ effectiveApprovalMode: ApprovalMode,
190
+ ): boolean {
191
+ if (shape === "chain" || shape === "graph") return false;
192
+ return effectiveApprovalMode === "auto";
193
+ }
194
+
124
195
  export function resolveSubagentParams(
125
196
  params: {
126
197
  task: string;
@@ -212,11 +283,8 @@ export function resolveSubagentParams(
212
283
  : state.config.gitMode;
213
284
 
214
285
  // P4: Resolve approval mode: per-call param > state config > default "writes"
215
- const mergedApprovalMode = params.approvalMode as ApprovalMode | undefined;
216
- const resolvedApprovalMode: ApprovalMode =
217
- mergedApprovalMode === "auto" || mergedApprovalMode === "writes" || mergedApprovalMode === "always"
218
- ? mergedApprovalMode
219
- : state.config.approvalMode;
286
+ // (shared with the dispatch chokepoint's background default, issue #361).
287
+ const resolvedApprovalMode = resolveEffectiveApprovalMode(params.approvalMode, state);
220
288
 
221
289
  const thinkingLevel = resolveThinkingLevel(
222
290
  mergedThinkingLevel,
package/src/schema.ts CHANGED
@@ -169,7 +169,9 @@ export const delegateTaskParamsSchema = Type.Object({
169
169
  "When true, the tool returns immediately with an agent ID. " +
170
170
  "The conductor is woken with a completion message; use get_subagent_result for post-wake retrieval and stall checks. " +
171
171
  "Supports a single task or the tasks array (a fan-out that starts one background agent per task; with tasks the call returns one ID per task and the conductor is woken once per agent as each finishes); combining background with chain or graph is rejected. " +
172
- "Default: false (blocking mode).",
172
+ "Default: conditional. Omitted, a single task or tasks fan-out runs in the BACKGROUND when the effective approvalMode is 'auto' (call param, else config); it stays foreground for 'writes'/'always' (a background run has no approval dialog, so the gate must stay in front of the user) and for chain/graph, which block by definition. " +
173
+ "Pass background: false for a quick probe whose answer the next step needs inline. Explicit true/false always wins. " +
174
+ "A background run defaults to a 30-minute deadline when no timeout is given.",
173
175
  }),
174
176
  ),
175
177
  priority: Type.Optional(
package/src/state.ts CHANGED
@@ -20,6 +20,7 @@ import type {
20
20
  RecoveryMode,
21
21
  CircuitBreakerState,
22
22
  Priority,
23
+ ModeContext,
23
24
  } from "./types";
24
25
  import type { TranscriptMessage } from "./transcript-tail";
25
26
  import {
@@ -163,6 +164,32 @@ export class SessionState {
163
164
  failedSubagents = 0;
164
165
  unseenSubagents = 0;
165
166
 
167
+ /**
168
+ * Issue #354: the footer activity ticker — the single interval that animates
169
+ * the status-line spinner while a run is active. Owned by src/concurrency.ts
170
+ * (syncProgressTicker / stopProgressTicker), undefined when idle; it lives on
171
+ * the session so shutdown can clear it and no module-level timer leaks.
172
+ */
173
+ statusTicker: ReturnType<typeof setInterval> | undefined;
174
+
175
+ /**
176
+ * Issue #354 (F2): the single 3 s linger timer that clears the settled
177
+ * counters and hands the footer back to the idle config line. Owned by
178
+ * src/concurrency.ts (syncProgressLinger / clearProgressLinger): armed at
179
+ * most once per burst of settled runs — edge-triggered on `active === 0`,
180
+ * never re-armed by repeated renders — and cleared when a new run starts,
181
+ * when it fires, and on session_shutdown. Lives on the session for the same
182
+ * reason as `statusTicker`: no timer may outlive the session.
183
+ */
184
+ statusResetTimer: ReturnType<typeof setTimeout> | undefined;
185
+
186
+ /**
187
+ * Issue #354: epoch ms at which the oldest still-active run started — the
188
+ * ` · 1m 14s` suffix's anchor. Set when the active count first rises above
189
+ * zero, cleared when the last run settles.
190
+ */
191
+ activeSinceMs: number | undefined;
192
+
166
193
  /** Concurrency queue */
167
194
  pendingQueue: Array<{
168
195
  run: () => void;
@@ -177,13 +204,11 @@ export class SessionState {
177
204
  /**
178
205
  * Issue #133: multi-unit mode breakdown for the status bar — set by
179
206
  * runGraphMode / runChainMode (src/index.ts) while a dispatch is in
180
- * flight, composed into the status text by updateProgressStatus
207
+ * flight, composed into the status text by repaintStatus
181
208
  * (src/concurrency.ts), cleared in the mode's finally. Undefined when no
182
209
  * graph/chain dispatch is active.
183
210
  */
184
- modeContext?:
185
- | { kind: "graph"; wave: number; totalWaves: number; node: number; totalNodes: number }
186
- | { kind: "chain"; step: number; totalSteps: number };
211
+ modeContext?: ModeContext;
187
212
 
188
213
  /**
189
214
  * Ids whose live entry has been finalized (deferred delete pending).