oira666_pi-subagent 0.7.13 → 0.7.16

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/README.md CHANGED
@@ -123,6 +123,23 @@ When Pi aborts the main agent, pi-subagent also stops running, queued, and parke
123
123
 
124
124
  Press **Alt+W** to abort only the main agent and keep subagents running. This exception ends when that run settles; a later normal abort stops subagents again. Your terminal must send Alt/Option+W as a Meta key sequence, such as `ESC w`, or use the Kitty keyboard protocol. Kitty is not required for this binding. Pi 1.4.0 does not match modified Escape shortcuts, so Shift+Escape and Alt+Escape cannot be used for this action.
125
125
 
126
+ Other extensions can request the same exception through Pi's shared event bus. Emit `pi-subagent:keep-on-next-abort` right before aborting an active run; the payload is ignored:
127
+
128
+ ```ts
129
+ pi.events.emit("pi-subagent:keep-on-next-abort", {});
130
+ ctx.abort();
131
+ ```
132
+
133
+ The signal covers only the next aborted settlement and is ignored while the session is idle.
134
+
135
+ ### Recovering interrupted workers
136
+
137
+ Opening a saved session may offer to recover interrupted workers, but always asks **yes or no** first. Browsing the session tree never offers or starts recovery. Print/JSON modes cannot ask and do not recover automatically. Old settings that disabled confirmation are ignored.
138
+
139
+ ### Reloading Pi
140
+
141
+ `/reload` and `ctx.reload()` keep running, queued, and parked workers. The reloaded extension instance takes them over: completions and lead messages raised during the reload are delivered afterwards, and `stop_subagent`, `message_subagent`, Escape, the activity line, and the shared concurrency cap keep working. Running worker processes keep their old code; a worker's next resume starts with the reloaded code. If the reloaded instance cannot take over, for example after an incompatible upgrade, a different session, or no reloaded session within 60 seconds, the old work stops as on quit.
142
+
126
143
  ## Agent definitions
127
144
 
128
145
  There are no bundled agents. Without user-created definitions, every task uses the same default worker, with no agent-specific system prompt or instructions. It receives the parent's task text unchanged. Pi's normal system prompt and delegation limits still apply.
package/broker/root.ts CHANGED
@@ -11,6 +11,7 @@ import { buildSubagentDetails, emptyUsage, type SingleResult } from "../types.js
11
11
  import { listBrokerJobs, persistBrokerResult, writeExclusive } from "./files.js";
12
12
  import type { BrokerEndpoint, BrokerJobSpec } from "./contracts.js";
13
13
  import { processBrokerCommands } from "./commands.js";
14
+ import { processRegistry } from "../storage/process-registry.js";
14
15
 
15
16
  interface RootBroker {
16
17
  endpoint: BrokerEndpoint;
@@ -24,7 +25,7 @@ interface RootBroker {
24
25
  poll?: ReturnType<typeof setTimeout>;
25
26
  closed: boolean;
26
27
  }
27
- const roots = new Map<string, RootBroker>();
28
+ const roots = processRegistry("root-brokers", () => new Map<string, RootBroker>());
28
29
 
29
30
  export function registerBrokerHandle(endpoint: BrokerEndpoint, token: string, handle?: RunningSubagentHandle): void {
30
31
  const root = roots.get(endpoint.directory);
package/budget.ts CHANGED
@@ -229,6 +229,15 @@ export function overrideResumeBudgets(
229
229
  }
230
230
  }
231
231
 
232
+ /** The grants an earlier tool call reserved, in task order, without changing the ledger. */
233
+ export function reservedSubagentBudgets(budget: SubagentBudget, callId: string): Reservation | undefined {
234
+ return latestState(budget).state.reservations[reservationKey(callId)];
235
+ }
236
+
237
+ function reservationKey(callId: string): string {
238
+ return createHash("sha256").update(callId).digest("hex");
239
+ }
240
+
232
241
  /** Reserve the whole batch before any child starts. Failed requests change nothing. */
233
242
  export function reserveSubagentBudgets(
234
243
  budget: SubagentBudget,
@@ -248,7 +257,7 @@ export function reserveSubagentBudgets(
248
257
  throw new SubagentBudgetError("Requested subagent budget is too large. Reduce the child allowances.");
249
258
  }
250
259
  if (!tasks.length) return [];
251
- const key = createHash("sha256").update(callId).digest("hex");
260
+ const key = reservationKey(callId);
252
261
  // A successful commit consumes at least one slot, so competing writers
253
262
  // cannot keep retrying forever within a finite allowance.
254
263
  for (;;) {
@@ -57,7 +57,7 @@ For each setting, an explicitly set environment variable wins over JSON, then th
57
57
  "agents": { "confirmProject": "ask" },
58
58
  "limits": { "total": 50, "tasksPerCall": 20, "concurrency": 8 },
59
59
  "delegation": { "depth": 3, "preventCycles": true },
60
- "resume": { "disableAuto": false, "prompt": true },
60
+ "resume": { "disableAuto": false },
61
61
  "models": { "intelligence": true },
62
62
  "runner": {
63
63
  "startupTimeoutMs": 120000,
@@ -77,7 +77,6 @@ For each setting, an explicitly set environment variable wins over JSON, then th
77
77
  | `delegation.depth` | `PI_SUBAGENT_MAX_DEPTH` | `3` |
78
78
  | `delegation.preventCycles` | `PI_SUBAGENT_PREVENT_CYCLES` | `true` |
79
79
  | `resume.disableAuto` | `PI_SUBAGENT_DISABLE_RESUME` | `false` |
80
- | `resume.prompt` | `PI_SUBAGENT_RESUME_PROMPT` | `true` |
81
80
  | `models.intelligence` | `PI_SUBAGENT_INTELLIGENCE` | `true` |
82
81
  | `models.fallback` | `PI_SUBAGENT_FALLBACK_MODEL` | No configured fallback |
83
82
  | `runner.startupTimeoutMs` | `PI_SUBAGENT_STARTUP_TIMEOUT` | `120000` |
@@ -97,7 +96,7 @@ Only user-configurable extension variables have JSON counterparts. Inherited run
97
96
 
98
97
  ## Session settings commands
99
98
 
100
- Use `/subagent:settings` to list controls and their current values. Separate `/subagent:enable` and `/subagent:disable` commands avoid an ambiguous toggle. Disabling blocks new launches and resumes without stopping running workers. Whenever delegation is enabled, workers receive durable names and `message_subagent` is available. Automatic recovery and its confirmation prompt have separate controls below.
99
+ Use `/subagent:settings` to list controls and their current values. Separate `/subagent:enable` and `/subagent:disable` commands avoid an ambiguous toggle. Disabling blocks new launches and resumes without stopping running workers. Whenever delegation is enabled, workers receive durable names and `message_subagent` is available. Session-open recovery always requires yes/no confirmation; tree navigation never offers recovery.
101
100
 
102
101
  | Command | Setting or behavior |
103
102
  | --- | --- |
@@ -106,8 +105,7 @@ Use `/subagent:settings` to list controls and their current values. Separate `/s
106
105
  | `/subagent:max-concurency 4` | Root-only session override for the shared cap of 4 live workers across the entire tree; extra launches and saved-worker resumes wait in one cross-process FIFO queue |
107
106
  | `/subagent:max-depth 2` | Maximum delegation depth |
108
107
  | `/subagent:prevent-cycles on` | Block delegation cycles |
109
- | `/subagent:auto-resume off` | Stop automatic recovery of unfinished tasks when reopening a chat or navigating history |
110
- | `/subagent:resume-prompt on` | Ask before recovery in the interactive terminal. `off` recovers without asking; it does not disable recovery |
108
+ | `/subagent:auto-resume off` | Disable recovery offers when opening a session |
111
109
  | `/subagent:intelligence on` | Use configured worker model presets, such as junior and senior |
112
110
  | `/subagent:confirm-project session` | Approval for repository-defined agents. `ask` requests approval, `session` preapproves for the session, `never` skips prompts rather than blocking agents |
113
111
 
@@ -119,7 +117,9 @@ Waiting parents park instead of rejecting blocked descendants or exceeding the c
119
117
 
120
118
  Preset definitions, the fallback model, extension exclusions, runner executables, retry counts and timeouts remain file settings.
121
119
 
122
- Commands apply to the main session. `/subagent:max-concurency` and `/subagent:max-total` take effect even while the main agent is busy; other settings commands require it to be idle. They override startup environment values and CLI delegation flags for this session, without changing `process.env`. A startup environment disable prevents the entire extension from loading, so commands are unavailable in that case. Child sessions cannot use commands to change inherited grants.
120
+ Commands apply to the main session. Enable/disable, limits, delegation and recovery controls, inspection, and saving settings remain available while the main agent is busy. Changing `intelligence` requires an idle main agent because in-flight calls retain the previous preset schema. Changes affect subsequent launches and resumes; they do not stop or reconfigure existing workers. Tool availability and schemas update for subsequent model requests, but an already-running request cannot see the updated tool list. Disabling also rejects launch or resume calls from that request if execution has not started. Calls already preparing, including those waiting for project-agent approval, may finish admission. Concurrency changes update the live queue immediately.
121
+
122
+ Session commands override startup environment values and CLI delegation flags without changing `process.env`. A startup environment disable prevents the entire extension from loading, so commands are unavailable in that case. Child sessions cannot use commands to change inherited grants.
123
123
 
124
124
  Changes are session-only and clear on session replacement, resume or reload. The concurrency cap is shared across processes, not saved to configuration unless explicitly requested. Lowering the live cap does not stop active workers. Queued work waits until the live-worker count falls below the new cap. Raising the cap admits queued work immediately. Changing the tasks-per-call limit affects new submissions only, not already accepted batches. Budget changes preserve all spent and reserved slots, cannot go below that spending, and cannot enlarge a child's grant. Temporary budget increases disappear when the session ends, but any slots used under them remain spent.
125
125
 
package/docs/sessions.md CHANGED
@@ -67,22 +67,21 @@ Relative `--skill`, `--prompt-template`, and theme file/directory arguments keep
67
67
 
68
68
  ## Crash recovery
69
69
 
70
- Worker sessions live in `sessions-subagents`, beside Pi's normal `sessions` directory. Async recovery tracks outstanding workers durably on the active branch, even though their launch calls already returned `started`. On parent resume or session-tree navigation, recovery checks that work rather than waiting for an unfinished blocking tool call.
70
+ Worker sessions live in `sessions-subagents`, beside Pi's normal `sessions` directory. Async recovery tracks outstanding workers durably on the active branch, even though their launch calls already returned `started`. Opening a saved parent session checks that work rather than waiting for an unfinished blocking tool call. Navigating the session tree never offers or starts recovery and cancels any pending startup recovery.
71
71
 
72
- - Interactive mode asks whether to resume. Non-UI modes resume automatically.
73
- - Finished siblings reuse their saved output and statistics without rerunning. Unfinished siblings continue their own sessions. Completion steering wakes a live idle lead; parked parents resume through the root broker.
72
+ - Recovery always asks yes or no, including through RPC clients. Only an explicit yes resumes work. Print/JSON modes cannot ask and leave saved workers untouched.
73
+ - The question lists only interrupted workers, not completed siblings or workers with recorded failed/stopped completions. Recovery keeps each worker's original name, session directory, and reserved budget. Completion steering wakes a live idle lead; parked parents resume through the root broker.
74
74
  - Durable references retain output, usage, model, and tool counts across JSON/session restarts.
75
- - Nested workers recover in the same way.
75
+ - Parked nested workers reattach to broker-owned children without relaunching them.
76
76
  - Provider fallback preserves the selected model's effective provider, authentication, endpoints, headers, and environment.
77
- - `/resume`, `/new`, `/fork`, and `/reload` discard pending recovery state and callbacks from the previous runtime.
77
+ - `/resume`, `/new`, `/fork`, and `/reload` discard pending recovery state and callbacks from the previous runtime. `/reload` keeps live workers: the old instance parks them on a process-global hand-off, and the reloaded instance adopts them when the same session starts with reason `reload`. A different session, an incompatible hand-off protocol, or no adoption within 60 seconds stops them as on quit. The same applies inside nested workers.
78
78
 
79
79
  Message acknowledgement is separate from worker completion. Recovery uses durable worker state rather than treating an acknowledged message as completed work. Retrying contact uses the same name without allocating a new worker or charging the same funded increase twice.
80
80
 
81
81
  | Variable | Default | Meaning |
82
82
  | --- | --- | --- |
83
- | `PI_SUBAGENT_RESUME_PROMPT` | `true` | `false` skips the interactive question and resumes automatically |
84
83
  | `PI_SUBAGENT_DISABLE_RESUME` | `false` | `true` disables automatic crash recovery |
85
84
  | `PI_SUBAGENT_NAMES_FILE` | Internal | Shared registry path, propagated to children |
86
85
  | `PI_SUBAGENT_BUDGET_DIR` | Internal | Reserved branch ledger, propagated and saved in session metadata |
87
86
 
88
- The recovery controls also have JSON settings: `resume.prompt` and `resume.disableAuto`, respectively. Neither disables worker names or `message_subagent`. Use `/subagent:auto-resume` and `/subagent:resume-prompt` to change recovery behavior for the current session. See [settings files](configuration.md#settings-files). Internal storage paths are managed by the extension and have no JSON counterpart.
87
+ `resume.disableAuto` is the JSON recovery switch; `/subagent:auto-resume` controls offers for the current session. It does not disable worker names or `message_subagent`. The former `resume.prompt`, `PI_SUBAGENT_RESUME_PROMPT`, and `/subagent:resume-prompt` bypass controls are no longer supported: confirmation cannot be disabled. See [settings files](configuration.md#settings-files). Internal storage paths are managed by the extension and have no JSON counterpart.
package/docs/usage.md CHANGED
@@ -16,7 +16,7 @@ Completion is a custom message with `customType: "subagent_completion"`, display
16
16
 
17
17
  A worker that settles while descendants remain active sends `Idle, waiting for children.` and its own last answer as ordinary lead steering. That is not a final completion or a final usage total. If parked, the parent saves context and exits while the root broker preserves child execution. `Finished` still waits for subtree settlement.
18
18
 
19
- When Pi aborts the main agent, all running, queued, and parked subagent work stops, including detached descendants. In the interactive TUI, Escape uses Pi's normal interrupt handling. Escape consumed by a focused overlay or dialog stops no agents; idle Escape retains Pi's normal behavior. Alt+W aborts only the main agent and leaves subagents running for that run. A later normal abort stops them again. Alt+W requires a terminal that reports Alt/Meta+W, through a legacy Meta sequence or the Kitty keyboard protocol. Explicitly stopped workers do not automatically resume; their usage and spent budget still count.
19
+ When Pi aborts the main agent, all running, queued, and parked subagent work stops, including detached descendants. In the interactive TUI, Escape uses Pi's normal interrupt handling. Escape consumed by a focused overlay or dialog stops no agents; idle Escape retains Pi's normal behavior. Alt+W aborts only the main agent and leaves subagents running for that run. A later normal abort stops them again. Alt+W requires a terminal that reports Alt/Meta+W, through a legacy Meta sequence or the Kitty keyboard protocol. An extension that aborts the lead can emit `pi-subagent:keep-on-next-abort` on `pi.events` right before `ctx.abort()` to get the same exception for that abort; the payload is ignored. A Pi reload keeps subagent work running and hands it to the reloaded instance. Explicitly stopped workers do not automatically resume; their usage and spent budget still count.
20
20
 
21
21
  Do not run Bash `sleep` or polling loops while waiting for workers. Do other work, or end the turn and wait for completion steering. Keep the session open. When the lead is idle with running, queued, or parked work pending, the TUI shows an animated `Waiting for subagents - don't close the session` line above `Running N`. It disappears when the lead becomes busy or all worker work finishes; Pi's native `Working` indicator is unchanged.
22
22
 
@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto";
2
2
  import { SUBAGENT_COMPLETION_TYPE, SUBAGENT_MESSAGE_TYPE } from "../types.js";
3
3
  import type { ProgressUpdate } from "./contracts.js";
4
4
  import type { ExtensionState } from "./state.js";
5
- import { updateCombinedUsageStatus } from "./runtime.js";
5
+ import { deferDuringReload, updateCombinedUsageStatus } from "./runtime.js";
6
6
  import { ackBrokerJob } from "../broker/files.js";
7
7
  import { inheritedBrokerEndpoint, BROKER_CONSUMED_ENTRY } from "./broker-jobs.js";
8
8
 
@@ -133,6 +133,7 @@ export function notifyLead(
133
133
  generation = state.lifecycleGeneration,
134
134
  interruptEpoch = state.interruptEpoch ?? 0,
135
135
  ): void {
136
+ if (deferDuringReload(state, generation, () => notifyLead(state, content, generation, interruptEpoch))) return;
136
137
  if (
137
138
  !state.sessionActive ||
138
139
  state.lifecycleGeneration !== generation ||
@@ -9,9 +9,10 @@ import { startBackground, notifyLead } from "./async-jobs.js";
9
9
  import { publishCompletion } from "./completion.js";
10
10
  import type { SessionContext } from "./contracts.js";
11
11
  import type { ExtensionState } from "./state.js";
12
+ import { processRegistry } from "../storage/process-registry.js";
12
13
 
13
14
  export const BROKER_CONSUMED_ENTRY = "pi-subagent-broker-consumed";
14
- const watches = new WeakMap<ExtensionState, Set<AbortController>>();
15
+ const watches = processRegistry("broker-watches", () => new WeakMap<ExtensionState, Set<AbortController>>());
15
16
  export function inheritedBrokerEndpoint(): BrokerEndpoint | undefined {
16
17
  const directory = process.env[BROKER_DIR_ENV],
17
18
  secret = process.env[BROKER_SECRET_ENV];
@@ -8,7 +8,7 @@ import {
8
8
  type AsyncExecutionKey,
9
9
  } from "../types.js";
10
10
  import { releaseCompletionDelivery, retainCompletionDelivery } from "./async-jobs.js";
11
- import { scheduleSessionTask } from "./runtime.js";
11
+ import { deferDuringReload, scheduleSessionTask } from "./runtime.js";
12
12
  import type { ExtensionState } from "./state.js";
13
13
  import { readWorkerStops } from "../storage/worker-stops.js";
14
14
 
@@ -31,6 +31,8 @@ export function publishCompletion(
31
31
  brokerJobId?: string,
32
32
  interruptEpoch = state.interruptEpoch ?? 0,
33
33
  ): void {
34
+ const replay = () => publishCompletion(state, result, generation, executionKey, brokerJobId, interruptEpoch);
35
+ if (deferDuringReload(state, generation, replay)) return;
34
36
  if (!state.sessionActive || generation !== state.lifecycleGeneration) return;
35
37
  const failed = isResultError(result);
36
38
  const output = failed
@@ -73,5 +75,5 @@ export function publishCompletion(
73
75
  }
74
76
  };
75
77
  (state.pendingCompletionInterrupts ??= new Map()).set(deliveryId, () => deliver(true));
76
- scheduleSessionTask(state, () => deliver(), 0);
78
+ scheduleSessionTask(state, () => deliver(), 0, false, true);
77
79
  }
@@ -1,12 +1,8 @@
1
1
  import { refreshWorkerAllowance } from "./tool-registration.js";
2
2
  import { registerAsyncDeliveryEvents } from "./async-jobs.js";
3
- import { configuredEnv } from "../settings.js";
4
- import { SUBAGENT_RESUME_DISABLE_ENV, parseBooleanEnv } from "../resume.js";
5
- import { RESUME_PROVIDER } from "../shared.js";
6
3
  import { isSubagentToolName, subagentDetailsHaveErrors } from "../types.js";
7
4
  import { decodeNestedBroadcast, forwardNestedBroadcast } from "./broadcast.js";
8
5
  import { RESUME_INTERACTIVE_DELAY_MS } from "./models.js";
9
- import { maybeOfferSubagentResume } from "./resume-offer.js";
10
6
  import {
11
7
  restoreModelAfterResumeFailure,
12
8
  scheduleSessionTask,
@@ -17,29 +13,14 @@ import type { ExtensionState } from "./state.js";
17
13
 
18
14
  export function registerSessionEvents(state: ExtensionState): void {
19
15
  registerAsyncDeliveryEvents(state);
20
- state.pi.on("session_tree", async (event, ctx) => {
16
+ state.pi.on("session_tree", async (_event, ctx) => {
21
17
  state.latestSessionCtx = ctx;
22
18
  updateCombinedUsageStatus(state, ctx);
23
- try {
24
- if (!state.canDelegate) return;
25
- // Skip extension-driven navigation (e.g. compaction) and any state where
26
- // a resume is already pending or subagents are still running.
27
- if (event?.fromExtension) return;
28
- if (state.activeSubagents.size > 0 || state.backgroundJobs.size > 0 || state.pendingCompletionDeliveries.size > 0)
29
- return;
30
- if (state.pendingResumePlans.length > 0) return;
31
- if (state.pendingInteractiveResumePrompt) return;
32
- if (ctx.model?.provider === RESUME_PROVIDER) return;
33
- if (typeof ctx.isIdle === "function" && !ctx.isIdle()) return;
34
-
35
- const resumeDisabled = parseBooleanEnv(configuredEnv(SUBAGENT_RESUME_DISABLE_ENV, state.settings)) === true;
36
- if (resumeDisabled) return;
37
-
38
- await maybeOfferSubagentResume(state, ctx, { deferInteractivePrompt: false });
39
- } catch (err) {
40
- console.error("[pi-subagent] Error in session_tree:", err);
41
- await restoreModelAfterResumeFailure(state, ctx);
42
- }
19
+ // Browsing history is read-only for recovery. Invalidate even a startup
20
+ // confirmation or deferred turn approved for the branch we just left.
21
+ state.resumeEpoch = (state.resumeEpoch ?? 0) + 1;
22
+ state.pendingInteractiveResumePrompt = null;
23
+ await restoreModelAfterResumeFailure(state, ctx);
43
24
  });
44
25
 
45
26
  state.pi.on("agent_end", async (_event, ctx) => {
@@ -73,9 +54,11 @@ export function registerSessionEvents(state: ExtensionState): void {
73
54
  const prompt = state.pendingInteractiveResumePrompt;
74
55
  if (!prompt) return;
75
56
  state.pendingInteractiveResumePrompt = null;
57
+ const resumeEpoch = state.resumeEpoch ?? 0;
76
58
  scheduleSessionTask(
77
59
  state,
78
60
  () => {
61
+ if (resumeEpoch !== (state.resumeEpoch ?? 0)) return;
79
62
  try {
80
63
  sendAutomaticResumePrompt(state, prompt);
81
64
  } catch (err) {
@@ -5,13 +5,21 @@ import { clearSyntheticResumeState, restoreModelAfterResumeFailure } from "./run
5
5
  import { stopBranches } from "./stop-tool.js";
6
6
  import type { ExtensionState } from "./state.js";
7
7
 
8
+ /**
9
+ * Event-bus signal for other extensions: emit it right before aborting an active run, and that
10
+ * abort stops only the main agent, like Alt+W. One-shot; the payload is ignored.
11
+ */
12
+ export const KEEP_ON_NEXT_ABORT_EVENT = "pi-subagent:keep-on-next-abort";
13
+
8
14
  /** Follow Pi's settled abort signal, never raw terminal input. */
9
15
  export function registerSubagentInterrupt(state: ExtensionState): void {
10
16
  let keepSubagents = false;
11
- let startingResumeEpoch: number | undefined;
17
+ let startingResume: ExtensionState["pendingAutomaticResume"];
18
+ const resumeCanceled = (pending: NonNullable<ExtensionState["pendingAutomaticResume"]>) =>
19
+ pending.interruptEpoch !== (state.interruptEpoch ?? 0) || pending.resumeEpoch !== (state.resumeEpoch ?? 0);
12
20
  state.onSessionReadyForInterrupt = () => {
13
21
  keepSubagents = false;
14
- startingResumeEpoch = undefined;
22
+ startingResume = undefined;
15
23
  };
16
24
  state.pi.registerShortcut("alt+w", {
17
25
  description: "Interrupt only the main agent, leaving subagents running",
@@ -21,6 +29,11 @@ export function registerSubagentInterrupt(state: ExtensionState): void {
21
29
  ctx.abort();
22
30
  },
23
31
  });
32
+ state.pi.events.on(KEEP_ON_NEXT_ABORT_EVENT, () => {
33
+ // An idle session has no run to abort; a stale flag must not spare a later Escape.
34
+ if (state.latestSessionCtx?.isIdle() === true) return;
35
+ keepSubagents = true;
36
+ });
24
37
  state.pi.on("agent_settled", (event, ctx) => {
25
38
  const keep = keepSubagents;
26
39
  keepSubagents = false;
@@ -93,32 +106,26 @@ export function registerSubagentInterrupt(state: ExtensionState): void {
93
106
  });
94
107
  state.pi.on("input", (event) => {
95
108
  const pending = state.pendingAutomaticResume;
96
- if (
97
- pending &&
98
- event.source === "extension" &&
99
- event.text === pending.prompt &&
100
- pending.interruptEpoch !== (state.interruptEpoch ?? 0)
101
- ) {
109
+ if (pending && event.source === "extension" && event.text === pending.prompt && resumeCanceled(pending)) {
102
110
  state.pendingAutomaticResume = undefined;
103
111
  return { action: "handled" as const };
104
112
  }
105
113
  });
106
114
  state.pi.on("before_agent_start", (event) => {
107
115
  const pending = state.pendingAutomaticResume;
108
- startingResumeEpoch =
109
- event.messageType === "user" && pending && event.prompt === pending.prompt ? pending.interruptEpoch : undefined;
110
- if (startingResumeEpoch !== undefined) state.pendingAutomaticResume = undefined;
116
+ startingResume = event.messageType === "user" && pending && event.prompt === pending.prompt ? pending : undefined;
117
+ if (startingResume) state.pendingAutomaticResume = undefined;
111
118
  });
112
119
  state.pi.on("agent_start", (_event, ctx) => {
113
- const epoch = startingResumeEpoch;
114
- startingResumeEpoch = undefined;
115
- // Pi can await prompt preflight after submission. Abort at loop entry if Escape
116
- // canceled that automatic prompt while it was outside the active agent loop.
117
- if (epoch !== undefined && epoch !== (state.interruptEpoch ?? 0)) ctx.abort();
120
+ const pending = startingResume;
121
+ startingResume = undefined;
122
+ // Pi can await prompt preflight after submission. Abort at loop entry if
123
+ // an interrupt or tree switch canceled recovery during that preflight.
124
+ if (pending && resumeCanceled(pending)) ctx.abort();
118
125
  });
119
126
  state.pi.on("session_shutdown", () => {
120
127
  keepSubagents = false;
121
- startingResumeEpoch = undefined;
128
+ startingResume = undefined;
122
129
  state.pendingAutomaticResume = undefined;
123
130
  });
124
131
  }
@@ -0,0 +1,84 @@
1
+ import * as path from "node:path";
2
+ import {
3
+ createBudget,
4
+ reservedSubagentBudgets,
5
+ reserveSubagentBudgets,
6
+ type BudgetTask,
7
+ type SubagentBudget,
8
+ } from "../budget.js";
9
+ import { getTaskBranchSize, type ResumableSubagentCall } from "../resume.js";
10
+ import { ensureBudget } from "./runtime.js";
11
+ import type { ExtensionState } from "./state.js";
12
+
13
+ interface RunnableTask {
14
+ index: number;
15
+ task: BudgetTask;
16
+ }
17
+
18
+ function sameBudgetTask(a: BudgetTask, b: BudgetTask): boolean {
19
+ return a.agent === b.agent && a.task === b.task && a.max_subagents_allowed === b.max_subagents_allowed;
20
+ }
21
+
22
+ /**
23
+ * Branch grants for runnable tasks, aligned with the call's task list.
24
+ *
25
+ * A recovery plan may hold only the interrupted subset of its launch, so it
26
+ * never re-reserves under the original call: that would either conflict with
27
+ * the full reservation or charge the branch twice. Each worker keeps its
28
+ * recorded grant, falls back to its child in the original reservation, and
29
+ * otherwise gets no descendant allowance.
30
+ */
31
+ export function launchBudgets(
32
+ state: ExtensionState,
33
+ toolCallId: string,
34
+ taskCount: number,
35
+ runnable: RunnableTask[],
36
+ plan: ResumableSubagentCall | null,
37
+ sessionDirFor: (index: number) => string,
38
+ ): Array<SubagentBudget | undefined> {
39
+ const budgets: Array<SubagentBudget | undefined> = Array.from({ length: taskCount }, () => undefined);
40
+ const audience = state.currentDepth === 0 ? "main" : "subagent";
41
+ if (!plan) {
42
+ const reserved = reserveSubagentBudgets(
43
+ ensureBudget(state),
44
+ toolCallId,
45
+ runnable.map(({ task }) => task),
46
+ audience,
47
+ );
48
+ runnable.forEach(({ index }, position) => (budgets[index] = reserved[position]));
49
+ return budgets;
50
+ }
51
+
52
+ for (const { index } of runnable) budgets[index] = plan.details?.results[index]?.budget;
53
+ const missing = runnable.filter(({ index }) => !budgets[index]);
54
+ if (!missing.length) return budgets;
55
+ const zeroAllowance = (index: number) => createBudget(path.join(sessionDirFor(index), "legacy-budget"), 0);
56
+ // Legacy launches recorded no allowance to grant again.
57
+ if (plan.tasks.every((task) => getTaskBranchSize(task) === undefined)) {
58
+ for (const { index } of missing) budgets[index] = zeroAllowance(index);
59
+ return budgets;
60
+ }
61
+ const original = reservedSubagentBudgets(ensureBudget(state), plan.previousToolCallId);
62
+ if (!original) {
63
+ // The launch was interrupted before it reserved anything.
64
+ const reserved = reserveSubagentBudgets(
65
+ ensureBudget(state),
66
+ plan.previousToolCallId,
67
+ missing.map(({ task }) => task),
68
+ audience,
69
+ );
70
+ missing.forEach(({ index }, position) => (budgets[index] = reserved[position]));
71
+ return budgets;
72
+ }
73
+ const claimed = new Set(budgets.map((budget) => budget?.directory));
74
+ for (const { index, task } of missing) {
75
+ const position = original.tasks.findIndex(
76
+ (reservedTask, candidate) =>
77
+ sameBudgetTask(reservedTask, task) && !claimed.has(original.children[candidate]?.directory),
78
+ );
79
+ const child = original.children[position];
80
+ budgets[index] = child ?? zeroAllowance(index);
81
+ if (child) claimed.add(child.directory);
82
+ }
83
+ return budgets;
84
+ }
@@ -1,18 +1,10 @@
1
1
  import { createIntelligenceSchemas, validatePreparedArguments } from "./schemas.js";
2
2
  import { selectIntelligence } from "../intelligence.js";
3
3
  import { resolveLaunchModelSettings } from "../runner/arguments.js";
4
- import * as path from "node:path";
5
4
  import { DEFAULT_AGENT, discoverAgents } from "../agents.js";
6
- import {
7
- createBudget,
8
- isBranchBudgetAmount,
9
- reserveSubagentBudgets,
10
- SubagentBudgetError,
11
- type SubagentBudget,
12
- } from "../budget.js";
5
+ import { isBranchBudgetAmount, SubagentBudgetError } from "../budget.js";
13
6
  import { allocateSubagentNames } from "../names.js";
14
7
  import { recordToolCallStart, renderCall, renderResult } from "../render.js";
15
- import { getTaskBranchSize } from "../resume.js";
16
8
  import { buildSubagentDetails, DEFAULT_DELEGATION_MODE, SUBAGENT_TOOL_NAME } from "../types.js";
17
9
  import { updateLatestBroadcastTargets } from "./broadcast.js";
18
10
  import { makeDetailsFactory } from "./details.js";
@@ -34,7 +26,8 @@ import {
34
26
  } from "./policy.js";
35
27
  import { trackProgress } from "./progress.js";
36
28
  import { getSubagentsToolDescription } from "./prompts.js";
37
- import { ensureBudget, getParentModelForSubagent, getSessionDirForTask } from "./runtime.js";
29
+ import { getParentModelForSubagent, getSessionDirForTask } from "./runtime.js";
30
+ import { launchBudgets } from "./launch-budgets.js";
38
31
  import {
39
32
  findRecoveryPlanIndex,
40
33
  getPreparedRecoveryPlan,
@@ -196,41 +189,24 @@ export function registerSubagentsTool(state: ExtensionState) {
196
189
  }
197
190
  if (launchGeneration !== state.lifecycleGeneration || signal?.aborted)
198
191
  throw new SubagentBudgetError("Launch canceled or session changed. No slots were reserved.");
199
- const budgets: Array<SubagentBudget | undefined> = tasks.map(() => undefined);
192
+ // A recovery plan may hold only the interrupted subset of its launch,
193
+ // so each worker keeps its recorded or original-slot session directory.
194
+ const sessionDirFor = (index: number) =>
195
+ resumePlan?.details?.results[index]?.sessionDir ??
196
+ getSessionDirForTask(
197
+ state,
198
+ resumePlan?.previousToolCallId ?? toolCallId,
199
+ resumePlan?.taskIndexes?.[index] ?? index,
200
+ );
200
201
  const runnable = tasks
201
- .map((task, index) => ({ task, index }))
202
+ .map(({ agent, task, max_subagents_allowed }, index) => ({
203
+ index,
204
+ task: { agent, task, max_subagents_allowed },
205
+ }))
202
206
  .filter(
203
207
  ({ task, index }) => !cyclicTaskIndexes.has(index) && agents.some((agent) => agent.name === task.agent),
204
208
  );
205
- if (resumePlan && resumePlan.tasks.every((task) => getTaskBranchSize(task) === undefined)) {
206
- // Legacy recovery cannot grant fresh descendant allowances.
207
- for (const { index } of runnable) {
208
- budgets[index] =
209
- resumePlan.details?.results[index]?.budget ??
210
- createBudget(
211
- path.join(
212
- resumePlan.details?.results[index]?.sessionDir ??
213
- getSessionDirForTask(state, resumePlan.previousToolCallId, index),
214
- "legacy-budget",
215
- ),
216
- 0,
217
- );
218
- }
219
- } else if (runnable.length) {
220
- const reserved = reserveSubagentBudgets(
221
- ensureBudget(state),
222
- resumePlan?.previousToolCallId ?? toolCallId,
223
- runnable.map(({ task }) => ({
224
- agent: task.agent,
225
- task: task.task,
226
- max_subagents_allowed: task.max_subagents_allowed,
227
- })),
228
- state.currentDepth === 0 ? "main" : "subagent",
229
- );
230
- runnable.forEach(({ index }, position) => {
231
- budgets[index] = reserved[position];
232
- });
233
- }
209
+ const budgets = launchBudgets(state, toolCallId, tasks.length, runnable, resumePlan, sessionDirFor);
234
210
 
235
211
  if (resumePlanIndex >= 0) state.pendingResumePlans.splice(resumePlanIndex, 1);
236
212
  state.recoveryPlansByToolCallId?.delete(toolCallId);
@@ -261,9 +237,7 @@ export function registerSubagentsTool(state: ExtensionState) {
261
237
  state.settings,
262
238
  ),
263
239
  tools: agentConfig?.tools,
264
- sessionDir:
265
- resumePlan?.details?.results[index]?.sessionDir ??
266
- getSessionDirForTask(state, resumePlan?.previousToolCallId ?? toolCallId, index),
240
+ sessionDir: sessionDirFor(index),
267
241
  };
268
242
  }),
269
243
  );
@@ -297,7 +271,7 @@ export function registerSubagentsTool(state: ExtensionState) {
297
271
  trackedOnUpdate,
298
272
  makeDetails,
299
273
  resumePlan?.details?.results,
300
- (index) => getSessionDirForTask(state, resumePlan?.previousToolCallId ?? toolCallId, index),
274
+ sessionDirFor,
301
275
  !!resumePlan,
302
276
  formatModelFlag(getParentModelForSubagent(state, ctx)),
303
277
  topLevelBaseId,
@@ -317,7 +291,7 @@ export function registerSubagentsTool(state: ExtensionState) {
317
291
  names,
318
292
  budgets,
319
293
  admissions,
320
- (index) => getSessionDirForTask(state, resumePlan?.previousToolCallId ?? toolCallId, index),
294
+ sessionDirFor,
321
295
  (index) => selectIntelligence(state.intelligencePresets, tasks[index].intelligence, state.settings)?.name,
322
296
  makeDetails(executionMode),
323
297
  toolCallId,
@@ -66,7 +66,8 @@ export function trackProgress(
66
66
  if (isSubagentDetails(partial.details)) {
67
67
  state.activeSubagentUsageSummaries.set(toolCallId, collectLiveUsageSummary(partial.details));
68
68
  updateLatestBroadcastTargets(state, partial.details, topLevelBaseId);
69
- refreshUsage(state, ctx);
69
+ // The tool ctx goes stale on reload while background workers keep reporting.
70
+ refreshUsage(state, state.latestSessionCtx ?? ctx);
70
71
  emitNestedProgressToParent(state, toolCallId, partial.details);
71
72
  }
72
73
  onUpdate?.(partial);
@@ -1,5 +1,4 @@
1
1
  import { createFauxCore, createProvider, fauxAssistantMessage, fauxToolCall, lazyStream } from "@earendil-works/pi-ai";
2
- import { findLatestResumableSubagentCalls } from "../resume.js";
3
2
  import { RESUME_PROVIDER } from "../shared.js";
4
3
  import { SUBAGENT_TOOL_NAME } from "../types.js";
5
4
  import type { ResumeModel, StreamOptions, ProviderContext } from "./contracts.js";
@@ -103,19 +102,9 @@ export function registerResumeProvider(state: ExtensionState): void {
103
102
  streamSimple: (model, context, options) => {
104
103
  const resume = state.resumeState;
105
104
  const expectedGeneration = state.lifecycleGeneration;
106
- const discoveredPlans =
107
- resume.plans.length > 0
108
- ? resume.plans
109
- : state.pendingResumePlans.length > 0
110
- ? state.pendingResumePlans
111
- : state.latestSessionCtx
112
- ? findLatestResumableSubagentCalls(state.latestSessionCtx)
113
- : [];
114
- if (discoveredPlans.length > 0 && resume.plans.length === 0) {
115
- resume.plans = [...discoveredPlans];
116
- state.pendingResumePlans = [...discoveredPlans];
117
- }
118
- const plans = discoveredPlans;
105
+ // Only session-open confirmation may arm recovery. A saved synthetic
106
+ // model or matching prompt must never rediscover and launch old work.
107
+ const plans = resume.plans.length > 0 ? resume.plans : state.pendingResumePlans;
119
108
  const totalTaskCount = plans.reduce((sum, plan) => sum + plan.tasks.length, 0);
120
109
  const phase = resume.phase;
121
110
  const triggerMatches =