@ferris1225/pi-subagents 5.0.1 → 5.0.3

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.
@@ -1,258 +1,54 @@
1
- /**
2
- * Bounded background task scheduler.
3
- *
4
- * Tasks get their own AbortSignal rather than inheriting the foreground agent
5
- * turn's signal. The owning extension cancels all work only on session teardown.
6
- *
7
- * Task exceptions are never swallowed: the per-task onError callback receives
8
- * them (unless the task was cancelled) so callers can surface the failure to
9
- * the user and the main agent instead of it vanishing into the queue.
10
- */
11
-
12
- import { cpus } from "node:os";
1
+ /** Background tasks start immediately and remain owned until cleanup finishes. */
13
2
 
14
3
  export type BackgroundTask = (signal: AbortSignal, controller: AbortController) => Promise<void>;
15
4
 
16
- interface PendingTask {
17
- kind: "task";
18
- task: BackgroundTask;
19
- controller: AbortController;
20
- complete: () => void;
21
- /** Called when a queued task is aborted before its body ever runs (drain skips
22
- * an already-aborted entry; cancelAll aborts every pending entry), so the
23
- * task body never produces a result. Callers that resolve waiters on a run id
24
- * must register a synthetic result here (or via a stop path) — otherwise a
25
- * waiter resolves via a "removed before its result was recorded" note. Never
26
- * called for a task whose body already started; that path owns its result. */
27
- onCancelled?: () => void;
28
- /** Invoked when the task throws and was not cancelled (cancellation is not a
29
- * failure — e.g. session shutdown races must never be reported as errors). */
30
- onError?: (error: unknown) => void | Promise<void>;
31
- }
32
-
33
- interface PendingAcquire {
34
- kind: "acquire";
35
- controller: AbortController;
36
- resolve: (acquired: boolean) => void;
37
- }
38
-
39
- type PendingEntry = PendingTask | PendingAcquire;
40
-
41
- export const MAX_SUBAGENT_CONCURRENCY = 6;
42
-
43
- /** Automatic process capacity, not a target team size. Explicit configuration
44
- * may select a smaller pool; the queue paces wider batches. */
45
- export function resolveSubagentConcurrency(cpuCount: number = cpus().length): number {
46
- return Math.min(MAX_SUBAGENT_CONCURRENCY, Math.max(4, Math.floor(cpuCount / 2)));
47
- }
48
-
49
5
  export class BackgroundTaskQueue {
50
- private concurrency: number;
51
- private readonly pending: PendingEntry[] = [];
52
6
  private readonly active = new Set<AbortController>();
53
- /** Active tasks that no longer count toward the concurrency limit. They keep
54
- * every other guarantee: abortable, awaited by waitForTask/waitForIdle. */
55
- private readonly suspended = new Set<AbortController>();
56
7
  private readonly completions = new WeakMap<AbortController, Promise<void>>();
57
8
  private readonly idleWaiters = new Set<() => void>();
58
9
  private stopped = false;
59
10
 
60
- constructor(concurrency: number) {
61
- this.concurrency = Math.max(1, concurrency);
62
- }
63
-
64
11
  enqueue(task: BackgroundTask, onCancelled?: () => void, onError?: (error: unknown) => void | Promise<void>): AbortController {
65
12
  const controller = new AbortController();
66
- let complete!: () => void;
67
- const completion = new Promise<void>((resolve) => {
68
- complete = resolve;
69
- });
70
- this.completions.set(controller, completion);
71
13
  if (this.stopped) {
72
14
  controller.abort();
73
- this.runCancelled(onCancelled);
74
- complete();
15
+ try { onCancelled?.(); } catch { /* cancellation callbacks must not break teardown */ }
75
16
  return controller;
76
17
  }
77
-
78
- this.pending.push({ kind: "task", task, controller, complete, onCancelled, onError });
79
- this.drain();
18
+ let complete!: () => void;
19
+ this.completions.set(controller, new Promise<void>((resolve) => { complete = resolve; }));
20
+ this.active.add(controller);
21
+ // The async boundary catches synchronous throws as well as rejected tasks.
22
+ void (async () => task(controller.signal, controller))()
23
+ .catch(async (error: unknown) => {
24
+ if (controller.signal.aborted) return;
25
+ try { await onError?.(error); } catch { /* error reporting must not strand ownership */ }
26
+ })
27
+ .finally(() => {
28
+ this.active.delete(controller);
29
+ complete();
30
+ if (this.active.size !== 0) return;
31
+ for (const resolve of this.idleWaiters) resolve();
32
+ this.idleWaiters.clear();
33
+ });
80
34
  return controller;
81
35
  }
82
36
 
83
- /** Resolve after this exact task has left the pending/active sets. This is
84
- * stronger than waiting for its task body: callers may safely reuse a
85
- * concurrency slot or the task's persisted checkpoint after it resolves. */
37
+ /** Wait for the task body and error handler, including isolation cleanup. */
86
38
  waitForTask(controller: AbortController | undefined): Promise<void> {
87
- if (!controller) return Promise.resolve();
88
- return this.completions.get(controller) ?? Promise.resolve();
89
- }
90
-
91
- /** Slot count, exposed so dispatch/status output can state the real pacing
92
- * limit instead of leaving queued work looking like an unexplained cap. */
93
- get capacity(): number {
94
- return this.concurrency;
39
+ return (controller && this.completions.get(controller)) || Promise.resolve();
95
40
  }
96
41
 
97
- /** Apply a new capacity without aborting owners. Lowering the limit waits
98
- * for active work to release slots; increasing it drains the existing FIFO. */
99
- setConcurrency(concurrency: number): void {
100
- this.concurrency = Math.max(1, concurrency);
101
- this.drain();
102
- }
42
+ get activeCount(): number { return this.active.size; }
103
43
 
104
- /** Tasks still waiting for a free slot (never started). */
105
- get pendingCount(): number {
106
- return this.pending.filter((entry) => entry.kind === "task").length;
107
- }
108
-
109
- /** Tasks currently holding a slot. Suspended tasks (lane waits, managed
110
- * workflow continuations) hold none and are excluded. */
111
- get activeCount(): number {
112
- return this.active.size;
113
- }
44
+ cancel(controller: AbortController | undefined): void { controller?.abort(); }
114
45
 
115
- /** Stop counting a running task toward the concurrency limit. Its body keeps
116
- * running under the same abort signal; completion still releases everything
117
- * waitForTask/waitForIdle promise. Frees a slot for queued work immediately.
118
- *
119
- * Used by tasks whose execution is serialized elsewhere anyway (managed
120
- * workflow continuations, shared-checkout writers waiting on the repository
121
- * lane): letting such a task also hold a global slot would let waiters
122
- * starve independent work that could start right away. The controller is
123
- * handed to the task body directly, so a task can always suspend itself
124
- * without racing the enqueue() caller's assignment. */
125
- suspend(controller: AbortController | undefined): void {
126
- if (!controller || this.stopped) return;
127
- if (!this.active.delete(controller)) return;
128
- this.suspended.add(controller);
129
- this.drain();
130
- }
131
-
132
- /** Reacquire a released process slot before a suspended task starts another
133
- * child process. Reacquisitions share FIFO order with not-yet-started tasks,
134
- * so lane waiters cannot bypass work already queued for the pool. */
135
- acquire(controller: AbortController | undefined): Promise<boolean> {
136
- if (!controller || this.stopped || controller.signal.aborted) return Promise.resolve(false);
137
- if (this.active.has(controller)) return Promise.resolve(true);
138
- if (!this.suspended.has(controller)) return Promise.resolve(false);
139
- return new Promise<boolean>((resolve) => {
140
- this.pending.push({ kind: "acquire", controller, resolve });
141
- this.drain();
142
- });
143
- }
144
-
145
- /** Cancel one queued/running task. Queued entries are removed immediately;
146
- * active entries resolve waitForTask only after their body and error handler
147
- * have quiesced and the concurrency slot has been released. */
148
- cancel(controller: AbortController | undefined): void {
149
- if (!controller) return;
150
- controller.abort();
151
- const index = this.pending.findIndex((entry) => entry.controller === controller);
152
- if (index !== -1) {
153
- const [entry] = this.pending.splice(index, 1);
154
- if (entry.kind === "task") {
155
- this.runCancelled(entry.onCancelled);
156
- entry.complete();
157
- } else {
158
- this.suspended.delete(controller);
159
- entry.resolve(false);
160
- }
161
- this.drain();
162
- this.resolveIdleWaiters();
163
- }
164
- }
165
-
166
- /** Resolve once no queued or running task remains. */
167
46
  waitForIdle(): Promise<void> {
168
- if (this.pending.length === 0 && this.active.size === 0 && this.suspended.size === 0) return Promise.resolve();
169
- return new Promise<void>((resolve) => this.idleWaiters.add(resolve));
47
+ return this.active.size === 0 ? Promise.resolve() : new Promise<void>((resolve) => this.idleWaiters.add(resolve));
170
48
  }
171
49
 
172
- /** Stop queued work and request cancellation for running work. */
173
50
  cancelAll(): void {
174
- if (this.stopped) return;
175
51
  this.stopped = true;
176
-
177
- for (const entry of this.pending.splice(0)) {
178
- entry.controller.abort();
179
- if (entry.kind === "task") {
180
- this.runCancelled(entry.onCancelled);
181
- entry.complete();
182
- } else {
183
- this.suspended.delete(entry.controller);
184
- entry.resolve(false);
185
- }
186
- }
187
52
  for (const controller of this.active) controller.abort();
188
- for (const controller of this.suspended) controller.abort();
189
- this.resolveIdleWaiters();
190
- }
191
-
192
- /** Cancellation callbacks are user-supplied: a throw must never break the queue
193
- * (mirrors the try/catch around onError in drain). */
194
- private runCancelled(callback: (() => void) | undefined): void {
195
- if (!callback) return;
196
- try {
197
- callback();
198
- } catch {
199
- /* cancellation callbacks must never break the queue */
200
- }
201
- }
202
-
203
- private drain(): void {
204
- while (!this.stopped && this.active.size < this.concurrency) {
205
- const entry = this.pending.shift();
206
- if (!entry) {
207
- this.resolveIdleWaiters();
208
- return;
209
- }
210
- if (entry.controller.signal.aborted) {
211
- if (entry.kind === "task") {
212
- this.runCancelled(entry.onCancelled);
213
- entry.complete();
214
- } else {
215
- this.suspended.delete(entry.controller);
216
- entry.resolve(false);
217
- }
218
- continue;
219
- }
220
-
221
- if (entry.kind === "acquire") {
222
- if (!this.suspended.delete(entry.controller)) {
223
- entry.resolve(false);
224
- continue;
225
- }
226
- this.active.add(entry.controller);
227
- entry.resolve(true);
228
- continue;
229
- }
230
-
231
- this.active.add(entry.controller);
232
- void entry.task(entry.controller.signal, entry.controller)
233
- .catch(async (error: unknown) => {
234
- // Cancellation is not a failure: aborted work (e.g. session
235
- // shutdown) must never be reported as an exception.
236
- if (entry.controller.signal.aborted) return;
237
- try {
238
- await entry.onError?.(error);
239
- } catch {
240
- /* error reporting must never break the queue */
241
- }
242
- })
243
- .finally(() => {
244
- this.active.delete(entry.controller);
245
- this.suspended.delete(entry.controller);
246
- entry.complete();
247
- this.drain();
248
- this.resolveIdleWaiters();
249
- });
250
- }
251
- }
252
-
253
- private resolveIdleWaiters(): void {
254
- if (this.pending.length > 0 || this.active.size > 0 || this.suspended.size > 0) return;
255
- for (const resolve of this.idleWaiters) resolve();
256
- this.idleWaiters.clear();
257
53
  }
258
54
  }
@@ -13,6 +13,7 @@ import { existsSync, type Dirent, readdirSync, rmSync, statSync } from "node:fs"
13
13
  import { join } from "node:path";
14
14
  import { getSubagentsRoot, sweepProjectResultArtifacts } from "../execution/spawn.ts";
15
15
  import { pruneStaleProjectRoots, readReferencedDurablePaths, readThreadRecords } from "../lifecycle/durable.ts";
16
+ import type { SubagentRuntime } from "../lifecycle/runtime.ts";
16
17
  import { isProcessAlive, sweepProjectDurableDirs, sweepProjectTempDirs } from "./temp-hygiene.ts";
17
18
 
18
19
  /** Bytes a directory tree occupies, without following symlinks. */
@@ -172,3 +173,160 @@ export function formatBytes(bytes: number): string {
172
173
  }
173
174
  return value.toFixed(value >= 10 ? 0 : 1) + " " + units[unit];
174
175
  }
176
+
177
+ /** Sessions of settled runs are kept only so a follow-up can resume them. After
178
+ * this window they are pure disk cost: `subagent_message` with
179
+ * `context: "summary"` still works, and rework usually starts long before it. */
180
+ export const SETTLED_SESSION_MAX_AGE_MS = 30 * 60 * 1_000;
181
+
182
+ /** Recent sessions are never reclaimed regardless of budget: a follow-up can
183
+ * legitimately arrive seconds after settlement. */
184
+ const RECENT_SESSION_FLOOR_MS = 5 * 60 * 1_000;
185
+
186
+ /** Automatic passes are paced by settlement, so a burst of finished runs costs
187
+ * one sweep instead of one per run. */
188
+ const AUTO_CLEANUP_INTERVAL_MS = 5 * 60 * 1_000;
189
+
190
+ /** Upper bound for one project's artifacts; the oldest settled sessions go
191
+ * first until the project fits. */
192
+ export const PROJECT_BUDGET_BYTES = 1.5 * 1024 * 1024 * 1024;
193
+
194
+ let lastAutomaticCleanupAt = 0;
195
+
196
+ export interface AutomaticCleanupOptions {
197
+ now?: number;
198
+ /** Retained-session age before automatic reclamation. */
199
+ maxSessionAgeMs?: number;
200
+ /** Per-project artifact budget. */
201
+ budgetBytes?: number;
202
+ /** Ignore the pacing clock (tests, or an explicit pass). */
203
+ force?: boolean;
204
+ }
205
+
206
+ interface SettledSession {
207
+ path: string;
208
+ mtimeMs: number;
209
+ bytes: number;
210
+ }
211
+
212
+ function settledSessions(projectRoot: string): SettledSession[] {
213
+ const dir = join(projectRoot, "sessions");
214
+ let entries: Dirent[];
215
+ try {
216
+ entries = readdirSync(dir, { withFileTypes: true });
217
+ } catch {
218
+ return [];
219
+ }
220
+ return entries
221
+ .filter((entry) => entry.isDirectory() && !entry.isSymbolicLink() && entry.name.startsWith("pi-subagent-session-"))
222
+ .flatMap((entry) => {
223
+ const path = join(dir, entry.name);
224
+ try {
225
+ return [{ path, mtimeMs: statSync(path).mtimeMs, bytes: directoryBytes(path) }];
226
+ } catch {
227
+ return [];
228
+ }
229
+ });
230
+ }
231
+
232
+ /** Delete settled-session copies that nothing references: not a parked record,
233
+ * not a live or resumed thread, and older than the retention window. */
234
+ function reclaimSettledSessions(
235
+ projectRoot: string,
236
+ protectedPaths: readonly string[],
237
+ now: number,
238
+ maxAgeMs: number,
239
+ ): number {
240
+ let freed = 0;
241
+ for (const session of settledSessions(projectRoot)) {
242
+ if (now - session.mtimeMs < Math.max(maxAgeMs, RECENT_SESSION_FLOOR_MS)) continue;
243
+ if (protectedPaths.some((kept) => kept.startsWith(session.path) || session.path.startsWith(kept))) continue;
244
+ try {
245
+ rmSync(session.path, { recursive: true, force: true });
246
+ freed += session.bytes;
247
+ } catch {
248
+ /* a locked directory waits for the next pass */
249
+ }
250
+ }
251
+ return freed;
252
+ }
253
+
254
+ /** Delete the oldest settled sessions until the project fits its budget. */
255
+ function enforceProjectBudget(
256
+ projectRoot: string,
257
+ protectedPaths: readonly string[],
258
+ now: number,
259
+ budgetBytes: number,
260
+ ): number {
261
+ let used = directoryBytes(projectRoot);
262
+ if (used <= budgetBytes) return 0;
263
+ let freed = 0;
264
+ for (const session of settledSessions(projectRoot).sort((left, right) => left.mtimeMs - right.mtimeMs)) {
265
+ if (used - freed <= budgetBytes) break;
266
+ if (now - session.mtimeMs < RECENT_SESSION_FLOOR_MS) continue;
267
+ if (protectedPaths.some((kept) => kept.startsWith(session.path) || session.path.startsWith(kept))) continue;
268
+ try {
269
+ rmSync(session.path, { recursive: true, force: true });
270
+ freed += session.bytes;
271
+ } catch {
272
+ /* best-effort */
273
+ }
274
+ }
275
+ return freed;
276
+ }
277
+
278
+ function protectedSessionPaths(runtime: Pick<SubagentRuntime, "threads">, claimed: ReadonlySet<string>): string[] {
279
+ const protectedPaths = [...claimed];
280
+ for (const thread of runtime.threads.values()) {
281
+ // A parked or unfinished thread keeps its session for recovery; a live
282
+ // thread may be resumed by a follow-up that is already running.
283
+ if (thread.state === "queued" || thread.state === "running" || thread.state === "interrupting" || thread.state === "parked") {
284
+ if (thread.sessionDir) protectedPaths.push(thread.sessionDir);
285
+ continue;
286
+ }
287
+ if (thread.lifecycleOperation !== undefined && thread.sessionDir) protectedPaths.push(thread.sessionDir);
288
+ }
289
+ return protectedPaths;
290
+ }
291
+
292
+ /** Reclaim what nothing references, then keep each project inside its budget.
293
+ * Safe to call at any time: live runs, parked recovery work and recently
294
+ * settled sessions are all protected. */
295
+ export async function runAutomaticCleanup(
296
+ runtime: Pick<SubagentRuntime, "configPath" | "threads">,
297
+ options: AutomaticCleanupOptions = {},
298
+ ): Promise<{ freedBytes: number; skipped: boolean }> {
299
+ const now = options.now ?? Date.now();
300
+ if (!options.force && now - lastAutomaticCleanupAt < AUTO_CLEANUP_INTERVAL_MS) return { freedBytes: 0, skipped: true };
301
+ lastAutomaticCleanupAt = now;
302
+ const root = getSubagentsRoot(runtime.configPath);
303
+ const claimed = await readReferencedDurablePaths(runtime.configPath).catch(() => new Set<string>());
304
+ const records = await readThreadRecords(runtime.configPath).catch(() => []);
305
+ for (const record of records) if (record.sessionDir) claimed.add(record.sessionDir);
306
+ const protectedPaths = protectedSessionPaths(runtime, claimed);
307
+ const keep = (path: string) => protectedPaths.some((kept) => path.startsWith(kept) || kept.startsWith(path));
308
+ const before = measureDurableUsage(root).totalBytes;
309
+
310
+ sweepProjectTempDirs(root);
311
+ sweepProjectDurableDirs(root, { keep, isAlive: isProcessAlive });
312
+ sweepProjectResultArtifacts(root);
313
+ let projects: Dirent[] = [];
314
+ try {
315
+ projects = readdirSync(root, { withFileTypes: true });
316
+ } catch {
317
+ projects = [];
318
+ }
319
+ for (const project of projects) {
320
+ if (!project.isDirectory() || project.isSymbolicLink()) continue;
321
+ const path = join(root, project.name);
322
+ reclaimSettledSessions(path, protectedPaths, now, options.maxSessionAgeMs ?? SETTLED_SESSION_MAX_AGE_MS);
323
+ enforceProjectBudget(path, protectedPaths, now, options.budgetBytes ?? PROJECT_BUDGET_BYTES);
324
+ }
325
+ const after = measureDurableUsage(root).totalBytes;
326
+ return { freedBytes: Math.max(0, before - after), skipped: false };
327
+ }
328
+
329
+ /** Reset the pacing clock so the next settlement performs a real pass. */
330
+ export function resetAutomaticCleanupClock(): void {
331
+ lastAutomaticCleanupAt = 0;
332
+ }
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Detached Git worktree isolation for write-capable sub-agents.
3
3
  *
4
- * A handle is created in the bounded queue and stays owned by the logical run
4
+ * A handle is created by its background task and stays owned by the logical run
5
5
  * across startup retries and model candidates. Finalize
6
6
  * is idempotent: it records a binary patch, applies it to the original working
7
7
  * tree without touching its index, then removes/prunes the temporary worktree.
@@ -7,19 +7,22 @@ import { stopThreads } from "./stop.ts";
7
7
 
8
8
  const cancellations = new WeakMap<SubagentRuntime, Promise<void>>();
9
9
 
10
- export function cancelActiveWork(runtime: SubagentRuntime, reason: string): Promise<void> {
10
+ export function cancelActiveWork(runtime: SubagentRuntime, reason: string, notifyParent = true): Promise<void> {
11
11
  const existing = cancellations.get(runtime);
12
12
  if (existing) return existing;
13
13
  runtime.suppressCompletions = true;
14
14
  runtime.discardCompletions();
15
- // Start every interruption before awaiting cleanup: a worktree's integration
16
- // may need a repository lane held by a different shared writer.
15
+ // Interrupt every child before awaiting any integration cleanup.
17
16
  const graphs = [...runtime.workflows.values()].filter((graph) => graph.state === "running");
17
+ const activeThreads = [...runtime.threads.values()]
18
+ .filter((thread) => !thread.retired && (thread.lifecycleOperation !== undefined || ["queued", "running", "interrupting"].includes(thread.state)));
19
+ const threadIds = activeThreads.filter((thread) => !thread.workflow).map((thread) => thread.id);
18
20
  const graphStops = graphs.map(async (graph) => { await stopWorkflow(runtime, graph, reason); await graph.done; });
19
- const threadIds = [...runtime.threads.values()]
20
- .filter((thread) => !thread.workflow && (thread.lifecycleOperation !== undefined || ["queued", "running", "interrupting"].includes(thread.state)))
21
- .map((thread) => thread.id);
22
- const done = Promise.all([...graphStops, stopThreads(runtime, threadIds, reason)]).then(() => undefined).finally(() => {
21
+ const done = Promise.all([...graphStops, stopThreads(runtime, threadIds, reason)]).then(() => {
22
+ if (notifyParent && runtime.sessionActive && (activeThreads.length || graphs.length)) {
23
+ runtime.recordCancellation(activeThreads.map((thread) => thread.id), graphs.map((graph) => graph.id));
24
+ }
25
+ }).finally(() => {
23
26
  runtime.discardCompletions();
24
27
  runtime.suppressCompletions = false;
25
28
  cancellations.delete(runtime);
@@ -30,7 +33,7 @@ export function cancelActiveWork(runtime: SubagentRuntime, reason: string): Prom
30
33
 
31
34
  export function registerCancellationHooks(pi: ExtensionAPI, runtime: SubagentRuntime): void {
32
35
  pi.on("agent_settled", (event) => event.aborted ? cancelActiveWork(runtime, "Parent run was cancelled.") : undefined);
33
- pi.on("session_before_tree", () => cancelActiveWork(runtime, "Parent navigated to another conversation branch."));
36
+ pi.on("session_before_tree", () => cancelActiveWork(runtime, "Parent navigated to another conversation branch.", false));
34
37
  // Pi emits session_shutdown for new/resume/fork/reload. The runtime's
35
38
  // shutdown path stops children, retains recovery evidence, and disables delivery.
36
39
  }
@@ -143,22 +143,12 @@ export interface ActiveRunFoot {
143
143
  agent: string;
144
144
  /** Optional content label (task-derived) shown next to the agent name. */
145
145
  label?: string;
146
- /** Why a not-yet-executing run is waiting. Stated precisely so a repository
147
- * lane wait or a starting child is never mistaken for an exhausted pool. */
146
+ /** Startup state before a child emits activity. */
148
147
  wait?: RunWaitReason;
149
148
  }
150
149
 
151
150
  function activeRunWaitTag(wait: RunWaitReason | undefined): string {
152
- switch (wait) {
153
- case "process-slot":
154
- return " (queued, starts when a process slot frees)";
155
- case "repository-lane":
156
- return " (waiting for the repository write lane, not for a slot)";
157
- case "starting":
158
- return " (starting)";
159
- default:
160
- return "";
161
- }
151
+ return wait ? " (starting)" : "";
162
152
  }
163
153
 
164
154
  /**
@@ -4,7 +4,7 @@
4
4
  * The `subagent` tool and the workflow runner start children through the same
5
5
  * dispatcher, live-activity projection, terminal-notification path, and tool-card
6
6
  * details builder. Keeping them here means a workflow node is an ordinary
7
- * managed run: same queue pacing, isolation, admission, durable checkpointing,
7
+ * managed run: same lifecycle ownership, isolation, admission, durable checkpointing,
8
8
  * and completion accounting.
9
9
  */
10
10
 
@@ -14,6 +14,7 @@ import { formatTaskSummary, formatToolActivity, monitor } from "../presentation/
14
14
  import type { StartBackgroundInternal, DispatchEnvironment } from "./thread-shared.ts";
15
15
  import { persistThreadCheckpoint } from "./thread-shared.ts";
16
16
  import type { SubagentRuntime } from "./runtime.ts";
17
+ import { runAutomaticCleanup } from "../isolation/cleanup.ts";
17
18
 
18
19
  export interface DispatchCore {
19
20
  /** Publish the context/config/catalog a dispatch needs; every fresh call refreshes it. */
@@ -43,6 +44,9 @@ export function createDispatchCore(runtime: SubagentRuntime): DispatchCore {
43
44
  const endedAt = monitor.findRun(runId)?.endedAt;
44
45
  if (endedAt !== undefined && publishedEndedAt.get(runId) === endedAt) return;
45
46
  if (endedAt !== undefined) publishedEndedAt.set(runId, endedAt);
47
+ // Settlement is the natural moment to reclaim disk: a burst of runs costs
48
+ // one paced sweep, and every live or parked thread stays protected.
49
+ void runAutomaticCleanup(runtime).catch(() => undefined);
46
50
  if (opts?.silent || !runtime.sessionActive) return;
47
51
  const icon = status === "done" ? "✓" : "✗";
48
52
  const result = runtime.threads.get(runId)?.lastResult;
@@ -12,7 +12,7 @@ import type { ExtensionAPI, ToolInfo } from "@earendil-works/pi-coding-agent";
12
12
  import { findDuplicateDispatch } from "../delegation/prompt.ts";
13
13
  import type { PhaseScope } from "../delegation/phase-scope.ts";
14
14
  import { rmSync } from "node:fs";
15
- import { resolveSubagentConcurrency, BackgroundTaskQueue } from "../execution/background.ts";
15
+ import { BackgroundTaskQueue } from "../execution/background.ts";
16
16
  import {
17
17
  createCompletionBatcher,
18
18
  formatActiveRunsFooter,
@@ -89,6 +89,8 @@ export interface SubagentRuntime {
89
89
  /** Cancelling a parent must not wake it again with old child results. */
90
90
  suppressCompletions: boolean;
91
91
  discardCompletions: () => void;
92
+ /** Record cancellation for the next user turn without waking the parent. */
93
+ recordCancellation: (runIds: number[], workflowIds: number[]) => void;
92
94
  /** Resolves when the load-time durable restore pass has finished. Everything
93
95
  * that answers "which threads exist" awaits it — the lookup tools, a fresh
94
96
  * dispatch before it allocates a run id, and the restored-thread notice — so
@@ -158,7 +160,7 @@ export function findPendingWorkflowPhase(
158
160
  }
159
161
 
160
162
  export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRuntime {
161
- const backgroundQueue = new BackgroundTaskQueue(resolveSubagentConcurrency());
163
+ const backgroundQueue = new BackgroundTaskQueue();
162
164
  let nextWorkflowId = 1;
163
165
  // Compaction reads the whole history, summarizes it, and replaces it. A
164
166
  // completion injected into that window can be swallowed by the summary,
@@ -175,6 +177,18 @@ export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRun
175
177
  getToolInfos: () => pi.getAllTools(),
176
178
  sessionActive: true,
177
179
  suppressCompletions: false,
180
+ recordCancellation: (runIds, workflowIds) => {
181
+ const targets = [
182
+ ...(runIds.length ? ["runs " + runIds.map((id) => `#${id}`).join(", ")] : []),
183
+ ...(workflowIds.length ? ["workflows " + workflowIds.map((id) => `#${id}`).join(", ")] : []),
184
+ ].join("; ");
185
+ pi.sendMessage({
186
+ customType: "subagent-cancelled",
187
+ content: `Parent cancellation stopped ${targets}. These runs are already cancelled; no further subagent_stop is needed. Do not restart cancelled work unless the user requests it. Partial edits and retained integration artifacts may remain; inspect them only if continuing the task.`,
188
+ display: true,
189
+ details: { runIds, workflowIds },
190
+ }, { deliverAs: "nextTurn", triggerTurn: false });
191
+ },
178
192
  discardCompletions: () => {
179
193
  runtime.completionBatcher.dispose();
180
194
  heldCompletions = [];
@@ -213,11 +213,7 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
213
213
  if (isolation === "shared" || worktree) installCurrentLifecycle();
214
214
 
215
215
  const onLive = makeLiveHandler(runId, generation);
216
- // Shared write-capable runs serialize on the repository lane so their
217
- // edits cannot race; the lane wait releases the process slot because it
218
- // is write serialization, not pool pacing.
219
- const reserveManagedLane = isolation === "shared" && writeCapable;
220
- const runGeneration = async (backgroundSignal: AbortSignal, controller: AbortController): Promise<void> => {
216
+ const runGeneration = async (backgroundSignal: AbortSignal): Promise<void> => {
221
217
  if (runtime.threads.get(runId)?.generation !== generation) return;
222
218
  if (isolation === "worktree" && !worktree) {
223
219
  const prepared = await createWorktreeIsolation(originalCwd, { tempBaseDir: worktreesRoot });
@@ -233,14 +229,9 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
233
229
  monitor.setIsolation(runId, "worktree", "pending", worktreeGroup);
234
230
  installCurrentLifecycle();
235
231
  }
236
- // The generation body owns a process slot from here (a lane wait, if
237
- // any, was granted above). Recording the transition synchronously keeps
238
- // every "queued" surface truthful: only runs still pending in the pool
239
- // or behind the lane report a wait.
232
+ // Independent runs start immediately; only worktree integration serializes.
240
233
  monitor.setWaitReason(runId, "starting");
241
- // Model/thinking config may have changed while this generation sat
242
- // queued behind the concurrency limit. Re-resolve the route at actual
243
- // start so /subagents-setup edits apply to not-yet-started runs.
234
+ // Re-read model preferences after asynchronous worktree preparation.
244
235
  let activeRoute = route;
245
236
  const activeIdleTimeoutMs = DEFAULT_IDLE_TIMEOUT_SEC * 1000;
246
237
  try {
@@ -332,9 +323,7 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
332
323
  thread.lifecycleOperation === "settle" &&
333
324
  !thread.retired;
334
325
  try {
335
- // The child process has exited. Isolated Git finalization remains
336
- // lifecycle-owned and awaited, but no longer consumes a process slot.
337
- if (isolation === "worktree") runtime.backgroundQueue.suspend(controller);
326
+ // Keep ownership until isolated Git finalization finishes.
338
327
  await thread.finalizeIsolation(generation, result);
339
328
  if (!ownsSettlement()) return;
340
329
 
@@ -382,26 +371,8 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
382
371
  if (ownsSettlement()) thread.lifecycleOperation = undefined;
383
372
  }
384
373
  };
385
- const queuedGeneration = reserveManagedLane
386
- ? async (backgroundSignal: AbortSignal, controller: AbortController): Promise<void> => {
387
- // Waiting for repository serialization must not consume a process
388
- // slot. Once the lane is granted, reacquire through the same FIFO
389
- // scheduler before any child process can spawn.
390
- runtime.backgroundQueue.suspend(controller);
391
- monitor.setWaitReason(runId, "repository-lane");
392
- await runInManagedRepositoryLane(
393
- originalCwd,
394
- async () => {
395
- monitor.setWaitReason(runId, "process-slot");
396
- if (!(await runtime.backgroundQueue.acquire(controller))) return;
397
- await runGeneration(backgroundSignal, controller);
398
- },
399
- backgroundSignal,
400
- );
401
- }
402
- : runGeneration;
403
374
  const queueController = runtime.backgroundQueue.enqueue(
404
- queuedGeneration,
375
+ runGeneration,
405
376
  () => {
406
377
  if (runtime.threads.get(runId)?.generation !== generation) return;
407
378
  // A destructive stop owns publication and may still be finalizing an
@@ -455,7 +426,6 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
455
426
  };
456
427
  thread.lastResult = crashed;
457
428
  runtime.retainSession(crashed);
458
- if (isolation === "worktree" && thread.worktree) runtime.backgroundQueue.suspend(thread.queueController);
459
429
  await thread.finalizeIsolation(generation, crashed);
460
430
  if (!ownsSettlement()) return;
461
431
  thread.state = "failed";