@timmyjl12/pi-subagents 0.20.0 → 0.21.1

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.
Files changed (159) hide show
  1. package/CHANGELOG.md +862 -827
  2. package/README.md +1125 -1080
  3. package/dist/active-agents-prompt.d.ts +31 -9
  4. package/dist/active-agents-prompt.js +73 -9
  5. package/dist/agent-color.js +9 -1
  6. package/dist/agent-file-toggle.d.ts +1 -1
  7. package/dist/agent-manager.d.ts +405 -18
  8. package/dist/agent-manager.js +1661 -131
  9. package/dist/agent-runner.d.ts +45 -6
  10. package/dist/agent-runner.js +109 -18
  11. package/dist/agent-types.d.ts +30 -7
  12. package/dist/agent-types.js +38 -9
  13. package/dist/awaited-result.d.ts +37 -0
  14. package/dist/awaited-result.js +150 -0
  15. package/dist/child-session-shutdown.d.ts +19 -1
  16. package/dist/child-session-shutdown.js +60 -11
  17. package/dist/cleanup-plans.d.ts +10 -0
  18. package/dist/cleanup-plans.js +112 -0
  19. package/dist/cross-extension-rpc.d.ts +8 -1
  20. package/dist/cross-extension-rpc.js +59 -5
  21. package/dist/custom-agents.d.ts +34 -9
  22. package/dist/custom-agents.js +308 -111
  23. package/dist/default-agents.d.ts +1 -1
  24. package/dist/env.d.ts +1 -1
  25. package/dist/error-log.d.ts +6 -0
  26. package/dist/error-log.js +8 -0
  27. package/dist/force-main-model.d.ts +21 -0
  28. package/dist/force-main-model.js +28 -0
  29. package/dist/goal-bridge.d.ts +155 -0
  30. package/dist/goal-bridge.js +305 -0
  31. package/dist/group-join.d.ts +5 -1
  32. package/dist/group-join.js +52 -7
  33. package/dist/index.d.ts +5 -5
  34. package/dist/index.js +2827 -333
  35. package/dist/invocation-config.d.ts +30 -3
  36. package/dist/invocation-config.js +30 -1
  37. package/dist/memory.d.ts +1 -1
  38. package/dist/mention-clone.d.ts +1 -1
  39. package/dist/model-scope.d.ts +1 -1
  40. package/dist/nested-tools.d.ts +22 -1
  41. package/dist/nested-tools.js +120 -26
  42. package/dist/output-file.d.ts +15 -4
  43. package/dist/output-file.js +146 -43
  44. package/dist/prompts.d.ts +1 -1
  45. package/dist/recovery.d.ts +1 -1
  46. package/dist/report-cleanup.d.ts +204 -0
  47. package/dist/report-cleanup.js +1632 -0
  48. package/dist/report-store.d.ts +738 -0
  49. package/dist/report-store.js +3616 -0
  50. package/dist/schedule-store.d.ts +14 -6
  51. package/dist/schedule-store.js +88 -58
  52. package/dist/schedule.d.ts +20 -8
  53. package/dist/schedule.js +135 -74
  54. package/dist/settings.d.ts +39 -11
  55. package/dist/settings.js +22 -5
  56. package/dist/status-note.d.ts +1 -1
  57. package/dist/structured-output.d.ts +1 -1
  58. package/dist/types.d.ts +32 -3
  59. package/dist/ui/agent-mention.d.ts +2 -2
  60. package/dist/ui/agent-widget.d.ts +82 -13
  61. package/dist/ui/agent-widget.js +155 -37
  62. package/dist/ui/cleanup-preview.d.ts +59 -0
  63. package/dist/ui/cleanup-preview.js +466 -0
  64. package/dist/ui/conversation-viewer.d.ts +4 -4
  65. package/dist/ui/conversation-viewer.js +10 -6
  66. package/dist/ui/fleet-list.d.ts +3 -3
  67. package/dist/ui/fleet-list.js +3 -3
  68. package/dist/ui/fleet-overlay.d.ts +37 -6
  69. package/dist/ui/fleet-overlay.js +214 -18
  70. package/dist/ui/hub-feed.d.ts +52 -0
  71. package/dist/ui/hub-feed.js +148 -0
  72. package/dist/ui/native-transcript.js +5 -1
  73. package/dist/ui/schedule-menu.d.ts +1 -1
  74. package/dist/ui/schedule-menu.js +1 -1
  75. package/dist/ui/workflow-card.d.ts +4 -4
  76. package/dist/ui/workflow-dialog.d.ts +4 -4
  77. package/dist/ui/workflow-dialog.js +8 -3
  78. package/dist/ui/workflow-menu.d.ts +2 -2
  79. package/dist/usage.d.ts +12 -0
  80. package/dist/usage.js +28 -1
  81. package/dist/workflow/entry.d.ts +3 -3
  82. package/dist/workflow/host.d.ts +7 -4
  83. package/dist/workflow/host.js +162 -48
  84. package/dist/workflow/journal.d.ts +23 -7
  85. package/dist/workflow/journal.js +80 -23
  86. package/dist/workflow/progress.d.ts +1 -1
  87. package/dist/workflow/runtime.d.ts +45 -6
  88. package/dist/workflow/runtime.js +105 -16
  89. package/dist/workflow/task.d.ts +13 -4
  90. package/dist/workflow/task.js +7 -1
  91. package/dist/workflow/tool-description.d.ts +7 -2
  92. package/dist/workflow/tool-description.js +10 -5
  93. package/docs/{FORK.md → DEVELOPMENT.md} +4 -4
  94. package/docs/artifacts.md +93 -0
  95. package/docs/rpc.md +252 -189
  96. package/docs/runtime-performance.md +53 -0
  97. package/docs/workflows.md +48 -18
  98. package/examples/agent-tool-description.md +2 -2
  99. package/examples/workflows/review-panel.js +6 -3
  100. package/package.json +5 -5
  101. package/src/active-agents-prompt.ts +115 -39
  102. package/src/agent-color.ts +10 -2
  103. package/src/agent-file-toggle.ts +2 -2
  104. package/src/agent-manager.ts +3312 -1601
  105. package/src/agent-runner.ts +164 -36
  106. package/src/agent-types.ts +56 -11
  107. package/src/awaited-result.ts +187 -0
  108. package/src/child-session-shutdown.ts +114 -46
  109. package/src/cleanup-plans.ts +112 -0
  110. package/src/cross-extension-rpc.ts +68 -9
  111. package/src/custom-agents.ts +384 -112
  112. package/src/default-agents.ts +1 -1
  113. package/src/enabled-models.ts +1 -1
  114. package/src/env.ts +1 -1
  115. package/src/error-log.ts +10 -1
  116. package/src/force-main-model.ts +29 -0
  117. package/src/goal-bridge.ts +468 -0
  118. package/src/group-join.ts +56 -9
  119. package/src/index.ts +2987 -349
  120. package/src/invocation-config.ts +50 -4
  121. package/src/memory.ts +1 -1
  122. package/src/mention-clone.ts +3 -3
  123. package/src/model-scope.ts +1 -1
  124. package/src/nested-tools.ts +164 -33
  125. package/src/output-file.ts +168 -46
  126. package/src/prompts.ts +1 -1
  127. package/src/recovery.ts +2 -2
  128. package/src/report-cleanup.ts +2044 -0
  129. package/src/report-store.ts +4133 -0
  130. package/src/schedule-store.ts +244 -201
  131. package/src/schedule.ts +144 -80
  132. package/src/settings.ts +61 -16
  133. package/src/skill-loader.ts +1 -1
  134. package/src/standalone-fallback.ts +2 -2
  135. package/src/status-note.ts +1 -1
  136. package/src/structured-output.ts +1 -1
  137. package/src/types.ts +33 -3
  138. package/src/ui/agent-mention.ts +3 -3
  139. package/src/ui/agent-widget.ts +179 -45
  140. package/src/ui/cleanup-preview.ts +518 -0
  141. package/src/ui/conversation-viewer.ts +19 -15
  142. package/src/ui/fleet-list.ts +7 -7
  143. package/src/ui/fleet-overlay.ts +1048 -847
  144. package/src/ui/hub-feed.ts +179 -0
  145. package/src/ui/native-transcript.ts +7 -3
  146. package/src/ui/schedule-menu.ts +4 -4
  147. package/src/ui/workflow-card.ts +4 -4
  148. package/src/ui/workflow-dialog.ts +10 -6
  149. package/src/ui/workflow-menu.ts +4 -4
  150. package/src/usage.ts +53 -3
  151. package/src/workflow/collisions.ts +1 -1
  152. package/src/workflow/entry.ts +3 -3
  153. package/src/workflow/host.ts +174 -54
  154. package/src/workflow/journal.ts +80 -23
  155. package/src/workflow/progress.ts +1 -1
  156. package/src/workflow/runtime.ts +146 -23
  157. package/src/workflow/saved.ts +3 -3
  158. package/src/workflow/task.ts +18 -7
  159. package/src/workflow/tool-description.ts +10 -5
@@ -15,15 +15,16 @@
15
15
  */
16
16
  import { randomUUID } from "node:crypto";
17
17
  import { statSync } from "node:fs";
18
- import { isAbsolute } from "node:path";
18
+ import { isAbsolute, resolve } from "node:path";
19
19
  import { resumeAgent, runAgent } from "./agent-runner.js";
20
+ import { cloneAgentDefinition, getAgentConfig } from "./agent-types.js";
20
21
  import { shutdownChildSession } from "./child-session-shutdown.js";
21
22
  import { assignHandle, handleBase } from "./mention.js";
22
23
  import { describeModel } from "./model-resolver.js";
23
24
  import { isChildRequestActive } from "./recovery.js";
24
25
  import { releaseToolProgress } from "./ui/tool-progress.js";
25
26
  import { addUsage } from "./usage.js";
26
- import { cleanupWorktree, createWorktree, isWorktreeIsolationEnabled, pruneWorktrees, } from "./worktree.js";
27
+ import { cleanupWorktree, createWorktree, isWorktreeIsolationEnabled, pruneWorktrees } from "./worktree.js";
27
28
  /**
28
29
  * Default max concurrent background agents.
29
30
  *
@@ -52,6 +53,23 @@ const DEFAULT_MAX_CONCURRENT_FOREGROUND = 0;
52
53
  * far above the handful anyone keeps in their head.
53
54
  */
54
55
  const MAX_TOMBSTONES = 100;
56
+ /**
57
+ * Bound on the COMMON shutdown window: SDK session handlers and run/startup/
58
+ * finalizer promises are awaited together for at most this long. Past it, the
59
+ * manager reports explicit uncertainty rather than claiming quiescence.
60
+ */
61
+ const MANAGER_SHUTDOWN_DEADLINE_MS = 3_000;
62
+ /**
63
+ * Path identity for cleanup readiness. Deliberately the same normalization the
64
+ * report store uses for its lock and inventory keys — absolute, case-folded on
65
+ * Windows — so the manager and the cleanup backend never disagree about whether
66
+ * two requested history files are the same file. No filesystem lookup: symlink
67
+ * proof and deletion belong to the backend.
68
+ */
69
+ function cleanupPathKey(path) {
70
+ const resolved = resolve(path);
71
+ return process.platform === "win32" ? resolved.toLowerCase() : resolved;
72
+ }
55
73
  /**
56
74
  * Validate a caller-supplied SpawnOptions.cwd. `undefined`/`null` mean "unset"
57
75
  * (parent cwd). Anything else must be an absolute path to an existing
@@ -149,6 +167,40 @@ export class AgentManager {
149
167
  onStart;
150
168
  onCompact;
151
169
  onUsage;
170
+ reportArchiver;
171
+ archivedReportReader;
172
+ /** Highest run generation already handed to the archiver, per agent id. */
173
+ archivedGenerations = new Map();
174
+ /**
175
+ * Full run finalizers still in flight, per record. A finalizer is the spawn or
176
+ * resume promise INCLUDING its output flush and worktree cleanup. One record
177
+ * can hold several: a newer resume may settle while an older generation's
178
+ * flush is still pending, so replacing `record.promise` must not lose the
179
+ * older work. Entries are removed on either resolution branch.
180
+ */
181
+ pendingFinalizers = new Map();
182
+ /**
183
+ * Proof that a prepareCleanup pass found a live record settled and quiescent.
184
+ * forgetCleanup only forgets records with a matching generation here, so new
185
+ * work or a stale pass can never remove a report. Bounded by live records:
186
+ * cleared with the record, on a new run, on disposal and on forget.
187
+ */
188
+ cleanupQuiescence = new Map();
189
+ /** Acquire-side artifact barrier; see setArtifactAccessGuard. */
190
+ artifactAccessGuard;
191
+ /**
192
+ * Every session-instance teardown that is pending or never proved quiescence,
193
+ * plus unfinished run finalizers. Rows are lightweight plain data; unresolved
194
+ * rows are NEVER capped or dropped (their paths stay protected).
195
+ */
196
+ teardowns = new Map();
197
+ /** One teardown identity per SDK session instance (not per session file). */
198
+ teardownIds = new WeakMap();
199
+ /** Sessions allocated before `onSessionCreated`, keyed by agent id. */
200
+ allocations = new Map();
201
+ /** Readiness of each pre-ready allocation (bind/session_start settlement). */
202
+ allocationStates = new WeakMap();
203
+ teardownSequence = 0;
152
204
  maxConcurrent;
153
205
  maxConcurrentForeground = DEFAULT_MAX_CONCURRENT_FOREGROUND;
154
206
  /** Base repos worktrees were created from — so dispose() can prune them all,
@@ -190,6 +242,42 @@ export class AgentManager {
190
242
  runningBackground = 0;
191
243
  /** Number of currently running foreground (blocking) agents. */
192
244
  runningForeground = 0;
245
+ /**
246
+ * Capacity claimed by a start that has not reached its run yet (it is still
247
+ * awaiting an async acquire guard, a worktree copy or a cwd re-check).
248
+ * `poolHasRoom` counts these, so a synchronous queue drain can never start
249
+ * more runs than the limit while earlier starts are suspended.
250
+ */
251
+ pendingBackground = 0;
252
+ pendingForeground = 0;
253
+ /**
254
+ * Pending capacity claims, keyed by the record that owns them. A cancellation
255
+ * releases the claim still pending here at once; a TRANSFERRED claim is gone
256
+ * from this map and is a running charge the run's own finalizer releases, so
257
+ * abort can never free a slot that real work still occupies. A later claim
258
+ * for the same record replaces the entry: an older continuation that settles
259
+ * afterwards releases only its own already-idempotent claim.
260
+ */
261
+ pendingClaims = new WeakMap();
262
+ /**
263
+ * Resume admission, claimed synchronously before the acquire guard awaits.
264
+ * A settled record can be resumed by two callers in the same tick; only the
265
+ * first may mutate its generation and terminal fields. Cleared on refusal or
266
+ * once the record is queued/running (status then provides exclusivity).
267
+ */
268
+ resumeAdmissions = new WeakSet();
269
+ /** Individual queued aborts already delivered completion for this generation. */
270
+ notifiedQueuedAborts = new WeakMap();
271
+ /**
272
+ * The parent-signal abort listener currently owned by a record, with the
273
+ * generation that attached it. A start wires its signal BEFORE the acquire
274
+ * guard can suspend, so abort()/abortAll()/dispose() must be able to detach it
275
+ * immediately: a guard that never settles must not leave the manager reachable
276
+ * from a live parent signal. One wire per record — only the current generation
277
+ * is wired, and detach is identity-aware, so a stale continuation can never
278
+ * remove a newer generation's listener.
279
+ */
280
+ signalWires = new WeakMap();
193
281
  constructor(onComplete, maxConcurrent = DEFAULT_MAX_CONCURRENT, onStart, onCompact, onUsage) {
194
282
  this.onComplete = onComplete;
195
283
  this.onStart = onStart;
@@ -209,6 +297,444 @@ export class AgentManager {
209
297
  getMaxConcurrent() {
210
298
  return this.maxConcurrent;
211
299
  }
300
+ /** Wire durable report capture; see {@link AgentReportArchiver}. */
301
+ setReportArchiver(archiver) {
302
+ this.reportArchiver = archiver;
303
+ }
304
+ /** Wire the async parent-scoped archived reader injected into nested tools. */
305
+ setArchivedReportReader(reader) {
306
+ this.archivedReportReader = reader;
307
+ }
308
+ /**
309
+ * Wire the acquire-side artifact barrier. The callback runs at the ACTUAL
310
+ * boundaries where a run would first touch artifacts: the real start of
311
+ * `startAgent` (before the running slot is transferred), again immediately
312
+ * before `runAgent` (after an awaited worktree copy and/or assert), at resume
313
+ * acquisition before any run bookkeeping, and at a queued resume's actual
314
+ * start. The pool capacity itself is reserved synchronously in `launch` /
315
+ * the queued start BEFORE this callback can suspend, so awaiting a guard can
316
+ * never let a queue drain oversubscribe its pool.
317
+ *
318
+ * A throw (or a rejected promise) is an ordinary startup/refusal failure: no
319
+ * model starts, no pool slot or record generation is mutated, and a fresh
320
+ * worktree copy is released. The callback owns any ownership/lock check; the
321
+ * manager never inspects the filesystem or an SDK session here.
322
+ *
323
+ * A callback that returns a promise is awaited before worktree creation, and
324
+ * again immediately before `runAgent`. A callback that returns `void` keeps
325
+ * the historical synchronous start path unchanged (no extra suspension, so a
326
+ * spawn that has room starts in the same tick).
327
+ */
328
+ setArtifactAccessGuard(guard) {
329
+ this.artifactAccessGuard = guard;
330
+ }
331
+ /** Invoke the configured acquire-side barrier; original behavior when unset. */
332
+ assertArtifactAccess(record) {
333
+ return this.artifactAccessGuard?.(record);
334
+ }
335
+ /** Teardowns that did not prove quiescence, newest first. Cleanup keeps them leased. */
336
+ listUncertainTeardowns() {
337
+ return [...this.teardowns.values()]
338
+ .map(row => ({
339
+ agentId: row.agentId,
340
+ status: row.status,
341
+ phase: row.phase,
342
+ teardownId: row.id,
343
+ ...(row.sessionFile === undefined ? {} : { sessionFile: row.sessionFile }),
344
+ ...(row.sessionId === undefined ? {} : { sessionId: row.sessionId }),
345
+ ...(row.rootSessionId === undefined ? {} : { rootSessionId: row.rootSessionId }),
346
+ ...(row.rootCwd === undefined ? {} : { rootCwd: row.rootCwd }),
347
+ ...(row.rootSessionFile === undefined ? {} : { rootSessionFile: row.rootSessionFile }),
348
+ ...(row.reason === undefined ? {} : { reason: row.reason }),
349
+ at: row.at,
350
+ }))
351
+ .sort((a, b) => b.at - a.at);
352
+ }
353
+ hasUncertainTeardowns() {
354
+ return this.teardowns.size > 0;
355
+ }
356
+ /**
357
+ * Every agent whose work is not quiescent. Includes running/queued records,
358
+ * startup work (an awaited worktree copy), in-flight run finalizers (output
359
+ * flush and worktree cleanup) and older-generation finalizers that outlived a
360
+ * newer settled run. Cleanup callers combine this with
361
+ * {@link listUncertainTeardowns} for evicted-record protection; nothing here
362
+ * aborts, evicts or notifies anything.
363
+ */
364
+ getBusyAgentIds() {
365
+ const busy = new Set();
366
+ for (const record of this.agents.values()) {
367
+ if (this.busyReason(record) !== undefined)
368
+ busy.add(record.id);
369
+ }
370
+ // dispose() clears `agents` before its bounded sweep; a finalizer/startup
371
+ // still running in that window is still busy for an observer.
372
+ for (const record of this.pendingFinalizers.keys())
373
+ busy.add(record.id);
374
+ for (const id of this.startups.keys())
375
+ busy.add(id);
376
+ return [...busy];
377
+ }
378
+ /**
379
+ * Decide which requested reports and session files may be deleted, and close
380
+ * the settled SDK sessions that make them quiescent.
381
+ *
382
+ * Synchronous-before-await guarantees: the readiness recheck, the session
383
+ * detach and the bounded teardown registration all happen before the first
384
+ * `await`. A resume therefore sees `record.session === undefined` for every
385
+ * session this pass is closing, and work that starts during the await is
386
+ * refused by the second readiness check rather than reported ready.
387
+ *
388
+ * Never aborts/stops running work, never evicts records, never disposes or
389
+ * clears the manager, and never consumes a result or fires a notification.
390
+ * A settled record stays in the manager; {@link forgetCleanup} removes it only
391
+ * after the backend actually deleted its files.
392
+ */
393
+ async prepareCleanup(agentIds, sessionFiles) {
394
+ const blockedAgentIds = {};
395
+ const blockedSessionFiles = {};
396
+ const readyAgentIds = [];
397
+ const readySessionFiles = [];
398
+ const requestedAgentIds = [...new Set(agentIds)];
399
+ const requestedSessionFiles = [];
400
+ const seenPaths = new Set();
401
+ for (const path of sessionFiles) {
402
+ const key = cleanupPathKey(path);
403
+ if (seenPaths.has(key))
404
+ continue;
405
+ seenPaths.add(key);
406
+ requestedSessionFiles.push(path);
407
+ }
408
+ if (this.disposed) {
409
+ for (const id of requestedAgentIds)
410
+ blockedAgentIds[id] = "manager is disposed";
411
+ for (const path of requestedSessionFiles)
412
+ blockedSessionFiles[path] = "manager is disposed";
413
+ return { readyAgentIds, blockedAgentIds, readySessionFiles, blockedSessionFiles };
414
+ }
415
+ // ---- synchronous pre-check, against every record (selected or not) ----
416
+ const initialGuard = this.cleanupGuardSnapshot();
417
+ let guard = initialGuard;
418
+ const agentCandidates = [];
419
+ for (const id of requestedAgentIds) {
420
+ const reason = this.cleanupAgentRefusal(id, guard);
421
+ if (reason !== undefined) {
422
+ blockedAgentIds[id] = reason;
423
+ this.cleanupQuiescence.delete(id);
424
+ }
425
+ else {
426
+ agentCandidates.push(id);
427
+ }
428
+ }
429
+ const sessionCandidates = [];
430
+ for (const path of requestedSessionFiles) {
431
+ const reason = this.cleanupPathRefusal(path, guard);
432
+ if (reason !== undefined)
433
+ blockedSessionFiles[path] = reason;
434
+ else
435
+ sessionCandidates.push(path);
436
+ }
437
+ // ---- synchronous detach + register: still nothing awaited ----
438
+ const jobs = new Map();
439
+ const jobsByRecord = new Map();
440
+ for (const id of agentCandidates) {
441
+ const record = this.agents.get(id);
442
+ if (record)
443
+ this.attachCleanupTeardown(jobs, jobsByRecord, record, { agentId: id });
444
+ }
445
+ for (const path of sessionCandidates) {
446
+ const key = cleanupPathKey(path);
447
+ for (const record of this.agents.values()) {
448
+ if (record.sessionFile === undefined || cleanupPathKey(record.sessionFile) !== key)
449
+ continue;
450
+ this.attachCleanupTeardown(jobs, jobsByRecord, record, { sessionFile: path });
451
+ }
452
+ }
453
+ const outcomes = new Map();
454
+ await Promise.all([...jobs.values()].map(async (job) => {
455
+ try {
456
+ outcomes.set(job.session, await this.trackSessionShutdown(job.record, job.session));
457
+ }
458
+ catch (error) {
459
+ outcomes.set(job.session, {
460
+ status: "failed",
461
+ timedOut: false,
462
+ reason: error instanceof Error ? error.message : String(error),
463
+ });
464
+ }
465
+ }));
466
+ // ---- post-check: work that appeared while awaiting must not slip through ----
467
+ guard = this.cleanupGuardSnapshot();
468
+ for (const id of agentCandidates) {
469
+ const record = this.agents.get(id);
470
+ const reason = this.teardownRefusalForAgent(jobs, outcomes, id)
471
+ ?? this.cleanupAgentRefusal(id, guard)
472
+ ?? this.attachedDuringCleanupRefusal({ agentId: id }, initialGuard, guard, jobs);
473
+ if (reason !== undefined) {
474
+ blockedAgentIds[id] = reason;
475
+ this.cleanupQuiescence.delete(id);
476
+ continue;
477
+ }
478
+ readyAgentIds.push(id);
479
+ if (record)
480
+ this.cleanupQuiescence.set(id, { generation: record.runGeneration ?? 0 });
481
+ }
482
+ for (const path of sessionCandidates) {
483
+ const reason = this.teardownRefusalForSessionFile(jobs, outcomes, path)
484
+ ?? this.cleanupPathRefusal(path, guard)
485
+ ?? this.attachedDuringCleanupRefusal({ sessionFile: path }, initialGuard, guard, jobs);
486
+ if (reason !== undefined) {
487
+ blockedSessionFiles[path] = reason;
488
+ continue;
489
+ }
490
+ readySessionFiles.push(path);
491
+ }
492
+ return { readyAgentIds, blockedAgentIds, readySessionFiles, blockedSessionFiles };
493
+ }
494
+ /**
495
+ * Drop manager-side traces of cleanup items the backend ACTUALLY deleted.
496
+ *
497
+ * A live record is forgotten only when a prepareCleanup pass proved it
498
+ * quiescent, it is still on that same run generation, its session was
499
+ * detached by that pass, and nothing is busy or uncertain now. Nothing is
500
+ * tombstoned and no teardown is started: the report was deliberately deleted
501
+ * and must not resurrect through a mention or a late archive.
502
+ *
503
+ * Tombstones are dropped by the actual deleted agent id or the actual deleted
504
+ * session file, and a surviving record's session pointer is cleared only for
505
+ * a path that was actually deleted. Unrelated records, tombstones and failed
506
+ * deletions are never touched.
507
+ */
508
+ forgetCleanup(deletedAgentIds, deletedSessionFiles) {
509
+ const deletedIds = new Set(deletedAgentIds);
510
+ const deletedPaths = new Set();
511
+ for (const path of deletedSessionFiles)
512
+ deletedPaths.add(cleanupPathKey(path));
513
+ for (const id of deletedIds) {
514
+ const proof = this.cleanupQuiescence.get(id);
515
+ this.cleanupQuiescence.delete(id);
516
+ const record = this.agents.get(id);
517
+ if (record === undefined || proof === undefined)
518
+ continue;
519
+ if (proof.generation !== (record.runGeneration ?? 0))
520
+ continue;
521
+ // prepareCleanup always detaches before it reports ready; a live session
522
+ // here means this record was not closed by that pass (no async disposal).
523
+ if (record.session !== undefined)
524
+ continue;
525
+ if (this.busyReason(record) !== undefined)
526
+ continue;
527
+ if ([...this.teardowns.values()].some(row => row.agentId === id && this.uncertaintyReason(row) !== undefined)) {
528
+ continue;
529
+ }
530
+ this.pendingFinalizers.delete(record);
531
+ this.archivedGenerations.delete(id);
532
+ this.releaseAllocation(id);
533
+ this.startups.delete(id);
534
+ this.agents.delete(id);
535
+ }
536
+ for (const [handle, entry] of [...this.tombstones]) {
537
+ if (deletedIds.has(entry.id) || deletedPaths.has(cleanupPathKey(entry.sessionFile))) {
538
+ this.tombstones.delete(handle);
539
+ }
540
+ }
541
+ for (const record of this.agents.values()) {
542
+ if (record.sessionFile !== undefined && deletedPaths.has(cleanupPathKey(record.sessionFile))) {
543
+ record.sessionFile = undefined;
544
+ }
545
+ }
546
+ }
547
+ /** Why a live record is not quiescent, or undefined when it is settled and idle. */
548
+ busyReason(record) {
549
+ if (this.startups.has(record.id))
550
+ return "agent startup is in flight";
551
+ if (record.status === "running" || this.activeRuns.has(record))
552
+ return "agent is running";
553
+ if (record.status === "queued")
554
+ return "agent is queued";
555
+ if (record.outputCleanup !== undefined)
556
+ return "output finalizer is pending";
557
+ if (this.pendingFinalizers.has(record))
558
+ return "run finalizer is pending";
559
+ return undefined;
560
+ }
561
+ /** Explicit reason an unresolved teardown row blocks deletion. */
562
+ uncertaintyReason(row) {
563
+ if (row.status === "completed")
564
+ return undefined;
565
+ const phase = row.phase === "run" ? "run finalizer" : "session teardown";
566
+ if (row.status === "pending")
567
+ return `${phase} is still pending`;
568
+ if (row.status === "timed_out")
569
+ return `${phase} timed out`;
570
+ return `${phase} failed`;
571
+ }
572
+ cleanupGuardSnapshot() {
573
+ const records = [...this.agents.values()];
574
+ const busySessions = new Set();
575
+ const attachedSessions = new Map();
576
+ for (const record of records) {
577
+ const session = record.session;
578
+ if (session === undefined)
579
+ continue;
580
+ attachedSessions.set(record, session);
581
+ if (this.busyReason(record) !== undefined)
582
+ busySessions.add(session);
583
+ }
584
+ return { records, rows: [...this.teardowns.values()], busySessions, attachedSessions };
585
+ }
586
+ cleanupAgentRefusal(agentId, guard) {
587
+ const record = this.agents.get(agentId);
588
+ if (record !== undefined) {
589
+ const busy = this.busyReason(record);
590
+ if (busy !== undefined)
591
+ return busy;
592
+ }
593
+ // An evicted record leaves a tombstone, which still names the history file
594
+ // a later reopen would share. Archive-only ids (no record, no tombstone)
595
+ // have no live reference and stay ready.
596
+ const tombstone = record === undefined
597
+ ? [...this.tombstones.values()].find(entry => entry.id === agentId)
598
+ : undefined;
599
+ const sessionFile = record?.sessionFile ?? tombstone?.sessionFile;
600
+ const sessionKey = sessionFile === undefined ? undefined : cleanupPathKey(sessionFile);
601
+ // Sharing is checked against ALL busy records, including ones the caller
602
+ // did not select: deleting this report's history would catch them too.
603
+ for (const other of guard.records) {
604
+ if (other === record || this.busyReason(other) === undefined)
605
+ continue;
606
+ if (sessionKey !== undefined && other.sessionFile !== undefined
607
+ && cleanupPathKey(other.sessionFile) === sessionKey) {
608
+ return "session file is shared with a busy agent";
609
+ }
610
+ if (record?.session !== undefined && other.session === record.session) {
611
+ return "session instance is shared with a busy agent";
612
+ }
613
+ }
614
+ for (const row of guard.rows) {
615
+ if (row.agentId !== agentId)
616
+ continue;
617
+ const reason = this.uncertaintyReason(row);
618
+ if (reason !== undefined)
619
+ return reason;
620
+ }
621
+ return undefined;
622
+ }
623
+ cleanupPathRefusal(path, guard) {
624
+ const key = cleanupPathKey(path);
625
+ for (const row of guard.rows) {
626
+ const namesPath = (value) => value !== undefined && cleanupPathKey(value) === key;
627
+ if (!namesPath(row.sessionFile) && !namesPath(row.rootSessionFile))
628
+ continue;
629
+ const reason = this.uncertaintyReason(row);
630
+ if (reason !== undefined)
631
+ return reason;
632
+ }
633
+ for (const record of guard.records) {
634
+ if (record.sessionFile === undefined || cleanupPathKey(record.sessionFile) !== key)
635
+ continue;
636
+ if (this.busyReason(record) !== undefined)
637
+ return "session file is shared with a busy agent";
638
+ if (record.session !== undefined && guard.busySessions.has(record.session)) {
639
+ return "session instance is shared with a busy agent";
640
+ }
641
+ }
642
+ return undefined;
643
+ }
644
+ /**
645
+ * Refuse readiness for an attachment that appeared while the pass awaited.
646
+ *
647
+ * The pre-check deliberately allows settled attached sessions so this pass can
648
+ * detach and tear them down. That proof covers only the attachments in the
649
+ * initial snapshot: a record that attaches the same report/history during the
650
+ * await was never detached by this pass and stays resumable. Refuse it; the
651
+ * newly attached handle is not closed.
652
+ */
653
+ attachedDuringCleanupRefusal(target, before, after, jobs) {
654
+ const record = target.agentId === undefined ? undefined : this.agents.get(target.agentId);
655
+ const sessionFile = target.sessionFile ?? record?.sessionFile;
656
+ const sessionKey = sessionFile === undefined ? undefined : cleanupPathKey(sessionFile);
657
+ for (const other of after.records) {
658
+ const session = other.session;
659
+ if (session === undefined || jobs.has(session))
660
+ continue;
661
+ if (before.attachedSessions.get(other) === session)
662
+ continue;
663
+ if (other === record)
664
+ return "session was attached during cleanup";
665
+ if (sessionKey !== undefined && other.sessionFile !== undefined
666
+ && cleanupPathKey(other.sessionFile) === sessionKey) {
667
+ return "session file was attached during cleanup";
668
+ }
669
+ }
670
+ return undefined;
671
+ }
672
+ /**
673
+ * Detach a record's session synchronously and attach it to the pass's unique
674
+ * teardown job. The detach MUST precede the first await and the SDK teardown:
675
+ * a resume during shutdown then has no session to reopen.
676
+ */
677
+ attachCleanupTeardown(jobs, jobsByRecord, record, target) {
678
+ const session = record.session;
679
+ let job = jobsByRecord.get(record) ?? (session === undefined ? undefined : jobs.get(session));
680
+ if (job === undefined) {
681
+ if (session === undefined)
682
+ return;
683
+ record.session = undefined;
684
+ job = { record, session, agentIds: new Set(), sessionFiles: new Set() };
685
+ jobs.set(session, job);
686
+ // A record is free to share one SDK instance with a settled sibling.
687
+ // Once that instance is being closed, no handle may keep it for resume.
688
+ for (const other of this.agents.values()) {
689
+ if (other.session !== session)
690
+ continue;
691
+ other.session = undefined;
692
+ jobsByRecord.set(other, job);
693
+ }
694
+ }
695
+ else if (session !== undefined) {
696
+ record.session = undefined;
697
+ }
698
+ // Pin the most descriptive identity for a teardown protection row: a
699
+ // shared instance must still protect a file name known by any handle.
700
+ if (job.record.sessionFile === undefined && record.sessionFile !== undefined)
701
+ job.record = record;
702
+ jobsByRecord.set(record, job);
703
+ if (target.agentId !== undefined)
704
+ job.agentIds.add(target.agentId);
705
+ if (target.sessionFile !== undefined)
706
+ job.sessionFiles.add(target.sessionFile);
707
+ }
708
+ teardownRefusal(outcome) {
709
+ // Fail closed: a job that never produced an outcome is not proof of
710
+ // quiescence, and a missing key must never read as "completed".
711
+ if (outcome === undefined)
712
+ return "session teardown did not prove completion";
713
+ if (outcome.status === "completed")
714
+ return undefined;
715
+ return outcome.reason
716
+ ?? (outcome.status === "timed_out" ? "session teardown timed out" : "session teardown failed");
717
+ }
718
+ teardownRefusalForAgent(jobs, outcomes, agentId) {
719
+ for (const job of jobs.values()) {
720
+ if (!job.agentIds.has(agentId))
721
+ continue;
722
+ const reason = this.teardownRefusal(outcomes.get(job.session));
723
+ if (reason !== undefined)
724
+ return reason;
725
+ }
726
+ return undefined;
727
+ }
728
+ teardownRefusalForSessionFile(jobs, outcomes, path) {
729
+ for (const job of jobs.values()) {
730
+ if (!job.sessionFiles.has(path))
731
+ continue;
732
+ const reason = this.teardownRefusal(outcomes.get(job.session));
733
+ if (reason !== undefined)
734
+ return reason;
735
+ }
736
+ return undefined;
737
+ }
212
738
  /** Update the max concurrent foreground (blocking) agents limit. 0 = unlimited. */
213
739
  setMaxConcurrentForeground(n) {
214
740
  // Floor 0, not 1: unlimited is a meaningful value here and the default.
@@ -241,8 +767,154 @@ export class AgentManager {
241
767
  }
242
768
  poolHasRoom(pool) {
243
769
  return pool === "background"
244
- ? this.runningBackground < this.maxConcurrent
245
- : this.maxConcurrentForeground === 0 || this.runningForeground < this.maxConcurrentForeground;
770
+ ? this.runningBackground + this.pendingBackground < this.maxConcurrent
771
+ : this.maxConcurrentForeground === 0
772
+ || this.runningForeground + this.pendingForeground < this.maxConcurrentForeground;
773
+ }
774
+ /**
775
+ * Claim one slot for a start that is about to await work, synchronously.
776
+ * `transfer()` moves the claim to the running counter before the run is
777
+ * launched; `releasePending()` gives it back when acquisition is refused or
778
+ * the record was superseded. Repeated calls are no-ops, so a refusal that
779
+ * unwinds through `launch` cannot decrement twice.
780
+ *
781
+ * The claim is associated with `record` while pending so `abort()`/`abortAll()`
782
+ * can release it without waiting for the suspended continuation.
783
+ */
784
+ reservePoolSlot(pool, record) {
785
+ if (pool === undefined)
786
+ return undefined;
787
+ if (pool === "background")
788
+ this.pendingBackground++;
789
+ else
790
+ this.pendingForeground++;
791
+ let claimed = true;
792
+ // Declared before the closures below read it; only referenced after the
793
+ // object exists, so the claim can compare its own identity.
794
+ let reservation;
795
+ const forget = () => {
796
+ if (record !== undefined && this.pendingClaims.get(record) === reservation) {
797
+ this.pendingClaims.delete(record);
798
+ }
799
+ };
800
+ reservation = {
801
+ transfer: () => {
802
+ if (!claimed)
803
+ return;
804
+ claimed = false;
805
+ forget();
806
+ if (pool === "background") {
807
+ this.pendingBackground--;
808
+ this.runningBackground++;
809
+ }
810
+ else {
811
+ this.pendingForeground--;
812
+ this.runningForeground++;
813
+ }
814
+ },
815
+ releasePending: () => {
816
+ if (!claimed)
817
+ return;
818
+ claimed = false;
819
+ forget();
820
+ if (pool === "background")
821
+ this.pendingBackground--;
822
+ else
823
+ this.pendingForeground--;
824
+ },
825
+ };
826
+ if (record !== undefined)
827
+ this.pendingClaims.set(record, reservation);
828
+ return reservation;
829
+ }
830
+ /**
831
+ * Free a record's still-PENDING capacity claim, immediately and exactly once.
832
+ * A transferred claim is absent from the map, so a real run's charge is never
833
+ * touched here — that is released only by its finalizer.
834
+ *
835
+ * `drain` is false while a bulk cancellation is still marking entries: freeing
836
+ * one entry's capacity must not start another entry that has not been canceled
837
+ * yet. Individual cancellation drains as soon as the record is stopped.
838
+ */
839
+ releasePendingClaim(record, drain) {
840
+ const claim = this.pendingClaims.get(record);
841
+ if (claim === undefined)
842
+ return false;
843
+ this.pendingClaims.delete(record);
844
+ claim.releasePending();
845
+ if (drain)
846
+ this.drainQueue();
847
+ return true;
848
+ }
849
+ /**
850
+ * The pending claim a record holds RIGHT NOW, captured before anything the
851
+ * caller is about to do can re-enter the manager. abort() hands this exact
852
+ * reservation back afterwards: its completion callback is free to resume the
853
+ * same record, and that newer generation installs its OWN claim in the map.
854
+ * Freeing by lookup at the tail would free that one instead — a running charge
855
+ * the new generation still owns, whose transfer then no-ops and whose
856
+ * finalizer underflows the pool counter (oversubscription).
857
+ */
858
+ capturePendingClaim(record) {
859
+ return this.pendingClaims.get(record);
860
+ }
861
+ /**
862
+ * Release the exact claim {@link capturePendingClaim} captured. The map entry
863
+ * is forgotten only if it still names that object, and a claim that already
864
+ * transferred or was already released is an idempotent no-op, so a transferred
865
+ * running charge is never freed here.
866
+ */
867
+ releaseCapturedClaim(record, claim, drain) {
868
+ if (claim === undefined)
869
+ return false;
870
+ if (this.pendingClaims.get(record) === claim)
871
+ this.pendingClaims.delete(record);
872
+ claim.releasePending();
873
+ if (drain)
874
+ this.drainQueue();
875
+ return true;
876
+ }
877
+ /**
878
+ * Attach the parent-signal abort listener owned by `generation` and register
879
+ * it where abort()/abortAll()/dispose() can detach it immediately. Only one
880
+ * wire exists per record: an older generation's listener (a queued start's, or
881
+ * the previous run's) is detached first, so a late abort of THAT signal can
882
+ * never stop this run. A detached start (`undefined`) stays detached, and an
883
+ * already-aborted signal is left to its caller's explicit `abort()` call.
884
+ */
885
+ attachSignalWire(record, signal, generation) {
886
+ if (signal === undefined || signal.aborted)
887
+ return undefined;
888
+ // Only the record's current generation may own the wire: a superseded
889
+ // caller arming one would let a stale signal stop a later run.
890
+ if ((record.runGeneration ?? 0) !== generation)
891
+ return undefined;
892
+ this.detachSignalWire(record, this.signalWires.get(record));
893
+ const onParentAbort = () => this.abort(record.id);
894
+ signal.addEventListener("abort", onParentAbort, { once: true });
895
+ const wire = {
896
+ generation,
897
+ detach: () => signal.removeEventListener("abort", onParentAbort),
898
+ };
899
+ this.signalWires.set(record, wire);
900
+ return wire;
901
+ }
902
+ /**
903
+ * Detach one CAPTURED wire. The registry entry is forgotten only if it still
904
+ * names that wire, and `detach` is idempotent, so a stale continuation — or an
905
+ * old abort resuming after its callbacks — cannot remove a newer generation's
906
+ * listener.
907
+ */
908
+ detachSignalWire(record, wire) {
909
+ if (wire === undefined)
910
+ return;
911
+ if (this.signalWires.get(record) === wire)
912
+ this.signalWires.delete(record);
913
+ wire.detach();
914
+ }
915
+ /** Detach whatever parent-signal listener the record's current generation owns. */
916
+ releaseSignalWire(record) {
917
+ this.detachSignalWire(record, this.signalWires.get(record));
246
918
  }
247
919
  /**
248
920
  * Spawn an agent and return its ID immediately (for background use).
@@ -262,6 +934,21 @@ export class AgentManager {
262
934
  assertValidSpawnCwd(options.cwd);
263
935
  const id = randomUUID().slice(0, 17);
264
936
  const abortController = new AbortController();
937
+ // Ownership and root provenance are pinned at SPAWN, from the live parent
938
+ // chain when one exists — not reconstructed from whatever still lives at
939
+ // settle time. Cleanup later needs an ancestor that may itself have been
940
+ // evicted, and a child session's worktree cwd is not the root project.
941
+ const parentRecord = options.parentAgentId === undefined ? undefined : this.agents.get(options.parentAgentId);
942
+ const ownerIds = options.parentAgentId === undefined
943
+ ? undefined
944
+ : [options.parentAgentId, ...(parentRecord?.ownerIds ?? [])];
945
+ const rootSessionId = options.rootSessionId
946
+ ?? parentRecord?.rootSessionId
947
+ ?? ctx.sessionManager?.getSessionId?.();
948
+ const rootCwd = options.rootCwd ?? parentRecord?.rootCwd ?? ctx.cwd;
949
+ const rootSessionFile = options.rootSessionFile
950
+ ?? parentRecord?.rootSessionFile
951
+ ?? ctx.sessionManager?.getSessionFile?.();
265
952
  const record = {
266
953
  id,
267
954
  type,
@@ -300,9 +987,17 @@ export class AgentManager {
300
987
  invocation: options.invocation,
301
988
  depth: options.depth ?? 1,
302
989
  parentAgentId: options.parentAgentId,
303
- workflowId: options.workflowId,
990
+ // A workflow's descendant is still the workflow's: keep the owner id
991
+ // separate from the agent lineage so both protections apply.
992
+ workflowId: options.workflowId ?? parentRecord?.workflowId,
993
+ ownerIds,
304
994
  maxSubagentDepth: options.maxSubagentDepth,
305
- rootSessionId: options.rootSessionId,
995
+ rootSessionId,
996
+ rootCwd,
997
+ rootSessionFile,
998
+ // The reopen source is known before the session object exists. Pinning it
999
+ // here lets cleanup protect the shared history during a tombstone reopen.
1000
+ sessionFile: options.resumeSessionFile,
306
1001
  };
307
1002
  this.agents.set(id, record);
308
1003
  // After the insert, so `takenHandles()` already counts this record's own
@@ -311,7 +1006,14 @@ export class AgentManager {
311
1006
  if (record.handle !== undefined && record.alias === undefined && options.name !== undefined) {
312
1007
  record.alias = assignHandle(handleBase(options.name), this.takenHandles());
313
1008
  }
314
- const args = { pi, ctx, type, prompt, options };
1009
+ // Admission snapshot: queued spawns and async acquire guards can start long
1010
+ // after this call, so the definition that named this agent is pinned now.
1011
+ // A caller that resolved against a scoped registry supplies its own; only
1012
+ // a caller that did not gets the process-global definition read here.
1013
+ const agentDefinition = options.agentDefinition === undefined
1014
+ ? cloneAgentDefinition(getAgentConfig(type))
1015
+ : cloneAgentDefinition(options.agentDefinition);
1016
+ const args = { pi, ctx, type, prompt, options: { ...options, agentDefinition } };
315
1017
  const pool = this.poolFor(record);
316
1018
  if (pool !== undefined && !options.bypassQueue && !this.poolHasRoom(pool)) {
317
1019
  // Queue it — started when a running agent in the same pool completes.
@@ -320,7 +1022,7 @@ export class AgentManager {
320
1022
  record.status = "queued";
321
1023
  // A queued record never reaches startAgent's signal wiring, so arm the
322
1024
  // parent abort here or Esc could not release the position.
323
- if (!this.armQueuedAbort(id, options.signal))
1025
+ if (!this.armQueuedAbort(record, options.signal))
324
1026
  return id;
325
1027
  let release;
326
1028
  record.startGate = new Promise(resolve => { release = resolve; });
@@ -346,54 +1048,93 @@ export class AgentManager {
346
1048
  * an aborted signal, so a `spawnAndWait` on it would wait forever — pi has no
347
1049
  * tool-execution timeout to bail it out.
348
1050
  *
349
- * The listener is left in place when the agent starts. `startAgent` adds its
350
- * own, so both fire on a later abort, but `abort()` on an already-stopped
351
- * record is a no-op — so detaching would only be tidiness, and tidiness the
352
- * `abortAll`/`dispose` paths could not offer anyway.
1051
+ * The wire is generation-owned and registered for immediate detach: the start
1052
+ * that leaves the queue REPLACES it with its own run wire, and
1053
+ * abort()/abortAll()/dispose() detach it at once — so this listener never
1054
+ * outlives the generation that armed it, and a late abort of the queue signal
1055
+ * cannot stop a later resumed generation.
353
1056
  */
354
- armQueuedAbort(id, signal) {
1057
+ armQueuedAbort(record, signal) {
355
1058
  if (signal === undefined)
356
1059
  return true;
357
1060
  if (signal.aborted) {
358
- const record = this.agents.get(id);
359
- if (record) {
360
- record.status = "stopped";
361
- record.completedAt = Date.now();
362
- }
1061
+ record.status = "stopped";
1062
+ record.completedAt = Date.now();
1063
+ if (!record.isBackground)
1064
+ record.resultConsumed = true;
1065
+ this.archiveTerminal(record);
363
1066
  return false;
364
1067
  }
365
- signal.addEventListener("abort", () => this.abort(id), { once: true });
1068
+ this.attachSignalWire(record, signal, record.runGeneration ?? 0);
366
1069
  return true;
367
1070
  }
368
1071
  /**
369
1072
  * Kick off an agent's startup and register it under `startups`. The returned
370
1073
  * promise never rejects — the failure is delivered through `awaitStartup`,
371
- * and to the record.
1074
+ * and to the record. Background startup failures use ordinary completion;
1075
+ * callers delivering the failure inline consume it themselves.
372
1076
  *
373
1077
  * @param queuedPool - The pool this start was QUEUED on, or undefined for an
374
1078
  * immediate start. A queue drain can be minutes after `spawn()` returned,
375
1079
  * and nobody is awaiting `awaitStartup` by then, so a failure has to live
376
1080
  * on the record as status "error" — what drainQueue did when the throw was
377
- * still synchronous. An immediate start instead drops the record, exactly
378
- * as the throw out of `spawn()` did: no orphan in `listAgents()`, and the
379
- * handle goes back.
1081
+ * still synchronous. Immediate foreground failures drop the unreturned
1082
+ * record; detached callers keep a retrievable failure and ordinary wakeup.
380
1083
  */
381
1084
  launch(id, record, args, queuedPool) {
382
- const startup = this.startAgent(id, record, args).then(() => { this.startups.delete(id); }, (err) => {
1085
+ // Claim the pool slot BEFORE `startAgent` can await an async guard or a
1086
+ // worktree copy. `drainQueue` walks the queue synchronously and checks the
1087
+ // same counters, so without this reservation two entries would both pass
1088
+ // `poolHasRoom` while the first is still suspended — oversubscribing a
1089
+ // maxConcurrent of 1 by the whole backlog. The pool is resolved here (not
1090
+ // later in startAgent) so the reservation, the run's charge and its release
1091
+ // all name the same pool even if the user changes a limit mid-run.
1092
+ const pool = this.poolFor(record);
1093
+ const reservation = this.reservePoolSlot(pool, record);
1094
+ const generation = record.runGeneration ?? 0;
1095
+ const startup = this.startAgent(id, record, args, pool, reservation).then((settledOnQueuedStop) => {
383
1096
  this.startups.delete(id);
384
- if (queuedPool !== undefined) {
385
- // Mirrors settleRun: an inline caller gets this failure as a throw
386
- // out of spawnAndWait, so an unconsumed record would ALSO nudge the
387
- // session about it — the same failure reported twice.
388
- if (queuedPool === "foreground")
389
- record.resultConsumed = true;
390
- record.status = "error";
391
- record.error = err instanceof Error ? err.message : String(err);
392
- record.completedAt = Date.now();
393
- this.onComplete?.(record);
1097
+ if (record.status === "stopped" && !record.promise) {
1098
+ // An abort that landed while this record was still QUEUED already
1099
+ // archived and notified it; startAgent says so to avoid a second
1100
+ // completion callback here. A stop during the worktree copy has not
1101
+ // been notified yet, so it still settles through the normal path.
1102
+ if (settledOnQueuedStop !== false && this.agents.get(id) === record) {
1103
+ this.settleRun(record, true, undefined);
1104
+ }
1105
+ this.drainQueue();
394
1106
  }
395
- else {
396
- this.agents.delete(id);
1107
+ }, (err) => {
1108
+ this.startups.delete(id);
1109
+ // No-op once transferred; covers every pre-run refusal path.
1110
+ reservation?.releasePending();
1111
+ // abort() can land after startAgent rejected but before this callback.
1112
+ // Its queued generation is already archived/notified; do not settle it again.
1113
+ if (this.notifiedQueuedAborts.get(record) === generation) {
1114
+ this.drainQueue();
1115
+ return;
1116
+ }
1117
+ if (this.agents.get(id) === record) {
1118
+ if (queuedPool !== undefined || record.isBackground || record.status === "stopped") {
1119
+ if (record.status !== "stopped") {
1120
+ record.status = "error";
1121
+ record.error = err instanceof Error ? err.message : String(err);
1122
+ }
1123
+ record.completedAt ??= Date.now();
1124
+ // Startup already released its slot; reuse normal consumption,
1125
+ // disposal suppression and completion routing.
1126
+ this.settleRun(record, true, undefined);
1127
+ }
1128
+ else {
1129
+ // Immediate foreground failure: the caller gets the throw and the
1130
+ // row is not kept, but the terminal generation is still archived
1131
+ // honestly as an error rather than silently disappearing.
1132
+ record.status = "error";
1133
+ record.error = err instanceof Error ? err.message : String(err);
1134
+ record.completedAt ??= Date.now();
1135
+ this.archiveTerminal(record);
1136
+ this.agents.delete(id);
1137
+ }
397
1138
  }
398
1139
  // The agent never kept its slot (startAgent gives it back on failure),
399
1140
  // so anything queued behind it can go now.
@@ -412,37 +1153,129 @@ export class AgentManager {
412
1153
  * repo copy became async. Resolves immediately for an agent that is already
413
1154
  * running, still queued, or unknown — so callers can await it unconditionally.
414
1155
  *
415
- * Call it in the same tick as the `spawn()` it belongs to: a failed startup
416
- * takes its record (and this entry) with it, exactly as the throw did.
1156
+ * Call it in the same tick as the `spawn()` it belongs to: a settled startup
1157
+ * removes this promise entry. Detached failures remain on their records.
417
1158
  */
418
1159
  awaitStartup(id) {
419
1160
  return this.startups.get(id) ?? Promise.resolve();
420
1161
  }
1162
+ /**
1163
+ * Whether a start that suspended on an acquire guard still owns the record.
1164
+ * A stop, dispose, eviction or newer run during the await must not create a
1165
+ * worktree, child session or model call afterwards.
1166
+ */
1167
+ startIsCurrent(id, record, session, generation) {
1168
+ return !this.disposed
1169
+ && this.agents.get(id) === record
1170
+ && record.session === session
1171
+ && (record.runGeneration ?? 0) === generation
1172
+ && (record.status === "queued" || record.status === "running")
1173
+ && record.abortController?.signal.aborted !== true;
1174
+ }
1175
+ /** Same check once the start has claimed "running" and begun worktree work. */
1176
+ runIsCurrent(id, record, generation) {
1177
+ return !this.disposed
1178
+ && this.agents.get(id) === record
1179
+ && (record.runGeneration ?? 0) === generation
1180
+ && record.status === "running"
1181
+ && record.abortController?.signal.aborted !== true;
1182
+ }
421
1183
  /** Actually start an agent (called immediately or from queue drain). */
422
- async startAgent(id, record, { pi, ctx, type, prompt, options }) {
1184
+ async startAgent(id, record, { pi, ctx, type, prompt, options }, pool, reservation) {
1185
+ // Capture admission identity before the guard can suspend. Any stop,
1186
+ // dispose or newer run is then detectable on the far side of the await.
1187
+ const generation = record.runGeneration ?? 0;
1188
+ const admittedSession = record.session;
1189
+ // A queued record that a stop reaches has already been archived and
1190
+ // notified by abort(); tell launch() not to settle it a second time.
1191
+ const queuedAtEntry = record.status === "queued";
1192
+ // Wire the caller's abort signal BEFORE the first acquire await. Aborting a
1193
+ // supplied controller must reach `abort()` while the start is still only
1194
+ // CLAIMING capacity: otherwise a start suspended on a guard keeps its claim
1195
+ // (and every job behind it) until that guard settles, however long stalled
1196
+ // I/O takes. A detached, signal-less launch stays detached.
1197
+ let signalWire;
1198
+ if (options.signal) {
1199
+ if (options.signal.aborted)
1200
+ this.abort(id);
1201
+ else {
1202
+ // Replaces a queued start's early listener rather than stacking on it:
1203
+ // a stale queue signal must not be able to stop this run, and the
1204
+ // registry lets abort()/dispose() detach this one immediately.
1205
+ signalWire = this.attachSignalWire(record, options.signal, generation);
1206
+ }
1207
+ }
1208
+ const detach = () => {
1209
+ this.detachSignalWire(record, signalWire);
1210
+ signalWire = undefined;
1211
+ };
1212
+ // Already aborted before any work: abort() released the pending claim and
1213
+ // made the record terminal; do not enter an acquire guard for it.
1214
+ if (!this.startIsCurrent(id, record, admittedSession, generation)) {
1215
+ detach();
1216
+ // Idempotent for the abort path, and the safety net for any other way a
1217
+ // start can arrive already superseded: a claim must never outlive it.
1218
+ reservation?.releasePending();
1219
+ this.drainQueue();
1220
+ return queuedAtEntry && record.status === "stopped" ? false : undefined;
1221
+ }
1222
+ // Acquire-side barrier at the ACTUAL start: before a pool slot is taken and
1223
+ // before any worktree/session/model work. A throw follows the ordinary
1224
+ // startup-failure path, leaving counters and the record unmutated here.
1225
+ // A guard returning void keeps the whole path synchronous; only a real
1226
+ // promise suspends, and launch() has already reserved the slot for it.
1227
+ try {
1228
+ const guard = this.assertArtifactAccess(record);
1229
+ if (guard !== undefined)
1230
+ await guard;
1231
+ }
1232
+ catch (error) {
1233
+ detach();
1234
+ reservation?.releasePending();
1235
+ this.drainQueue();
1236
+ if (options.signal?.aborted)
1237
+ this.abort(id);
1238
+ // Rejection owns no more authority than success after suspension. A
1239
+ // cancelled/superseded admission must not deliver another completion.
1240
+ if (!this.startIsCurrent(id, record, admittedSession, generation)) {
1241
+ return queuedAtEntry && record.status === "stopped" ? false : undefined;
1242
+ }
1243
+ throw error;
1244
+ }
1245
+ // Revalidate after the guard's suspension. A stop, dispose or superseded
1246
+ // record must not create a late worktree, child session or model call.
1247
+ if (options.signal?.aborted)
1248
+ this.abort(id);
1249
+ if (!this.startIsCurrent(id, record, admittedSession, generation)) {
1250
+ detach();
1251
+ reservation?.releasePending();
1252
+ this.drainQueue();
1253
+ return queuedAtEntry && record.status === "stopped" ? false : undefined;
1254
+ }
423
1255
  // Re-validate a caller-supplied cwd: queued spawns can start minutes after
424
1256
  // spawn()'s check, and the directory may be gone by then (TOCTOU). Same
425
1257
  // curated errors; drainQueue parks a throw on the record as an error.
426
- assertValidSpawnCwd(options.cwd);
1258
+ try {
1259
+ assertValidSpawnCwd(options.cwd);
1260
+ }
1261
+ catch (error) {
1262
+ detach();
1263
+ reservation?.releasePending();
1264
+ this.drainQueue();
1265
+ throw error;
1266
+ }
427
1267
  // Single resolution point for the caller-supplied cwd — the worktree base
428
1268
  // repo and both cleanup calls below MUST agree on this value forever.
429
1269
  const customCwd = options.cwd ?? undefined; // null (RPC "unset") → undefined
430
1270
  const baseCwd = customCwd ?? ctx.cwd;
431
- // Take the running state — and with it the concurrency slot — BEFORE the
432
- // first await. Creating a worktree is an awaited git call, and drainQueue
433
- // reads the pool counters synchronously in a loop: incrementing after the
434
- // await would let it start every queued agent at once while the first is
435
- // still copying its repo. Claiming "running" here also keeps abort() and
436
- // abortAll() able to reach an agent whose worktree is still being created.
437
- //
438
- // The pool is resolved ONCE, here, and carried to `settleRun` below:
439
- // `poolFor` reads `maxConcurrentForeground`, which the user can change from
440
- // `/agents → Settings` mid-run, so recomputing it at settle time would
1271
+ // Take the running state — and with it the concurrency slot — AFTER the
1272
+ // acquire barrier but BEFORE any worktree/session/model work. The pending
1273
+ // claim made synchronously in launch() transfers here. The pool is pinned
1274
+ // there and carried to `settleRun`: recomputing it at settle time would
441
1275
  // decrement a pool this run never charged (counter underflow, limit
442
1276
  // silently lifted) or skip the decrement for one it did (leaked slot —
443
- // every later blocking spawn queues forever). The two startup exits below
444
- // never reach `settleRun`, so they hand the slot back themselves.
445
- const pool = this.poolFor(record);
1277
+ // every later blocking spawn queues forever).
1278
+ reservation?.transfer();
446
1279
  const releaseSlot = () => {
447
1280
  if (pool === "background")
448
1281
  this.runningBackground--;
@@ -452,10 +1285,19 @@ export class AgentManager {
452
1285
  record.status = "running";
453
1286
  record.startedAt = Date.now();
454
1287
  record.startGate = undefined;
455
- if (pool === "background")
456
- this.runningBackground++;
457
- else if (pool === "foreground")
458
- this.runningForeground++;
1288
+ // Discard a copy created for a start that turned out to be superseded. The
1289
+ // copy is by definition unchanged, so it is safe to remove; a cleanup
1290
+ // failure never masks the refusal that got us here.
1291
+ const discardWorktree = async () => {
1292
+ const worktree = record.worktree;
1293
+ record.worktree = undefined;
1294
+ if (!worktree)
1295
+ return;
1296
+ try {
1297
+ record.worktreeResult = await cleanupWorktree(pi, baseCwd, worktree, options.description);
1298
+ }
1299
+ catch { /* never mask the refusal */ }
1300
+ };
459
1301
  // Worktree isolation: try to create a temporary git worktree. Strict —
460
1302
  // fail loud if not possible (no silent fallback to main tree). Done BEFORE
461
1303
  // the run is kicked off so a failure doesn't leave a half-running agent.
@@ -464,8 +1306,17 @@ export class AgentManager {
464
1306
  // that omits the field can't stop a caller that never saw the schema.
465
1307
  let worktreeCwd;
466
1308
  if (options.isolation === "worktree" && isWorktreeIsolationEnabled()) {
467
- const wt = await createWorktree(pi, baseCwd, id);
1309
+ let wt;
1310
+ try {
1311
+ wt = await createWorktree(pi, baseCwd, id);
1312
+ }
1313
+ catch (error) {
1314
+ detach();
1315
+ releaseSlot();
1316
+ throw error;
1317
+ }
468
1318
  if (!wt) {
1319
+ detach();
469
1320
  releaseSlot();
470
1321
  throw new Error('Cannot run with isolation: "worktree" — not a git repo, no commits yet, or `git worktree add` failed. ' +
471
1322
  'Initialize git and commit at least once, or omit `isolation`.');
@@ -479,38 +1330,53 @@ export class AgentManager {
479
1330
  // subdirectory, silently dropping extensions/skills.
480
1331
  worktreeCwd = customCwd !== undefined ? wt.workPath : wt.path;
481
1332
  this.worktreeRepos.add(baseCwd);
482
- // No longer "running" means a stop landed while the copy was being made
483
- // (abort(), abortAll()) — a window that did not exist when creation was
484
- // synchronous. The record is already terminal, so launching the run would
485
- // burn tokens on work nobody is waiting for: discard the fresh (and by
486
- // definition unchanged) worktree instead.
487
- if (record.status !== "running") {
1333
+ // No longer current means a stop/dispose/supersession landed while the
1334
+ // copy was being made (abort(), abortAll(), a cleared session). The
1335
+ // record is already terminal, so launching the run would burn tokens on
1336
+ // work nobody is waiting for: discard the fresh (and by definition
1337
+ // unchanged) worktree instead.
1338
+ if (options.signal?.aborted)
1339
+ this.abort(id);
1340
+ if (!this.runIsCurrent(id, record, generation)) {
1341
+ detach();
488
1342
  releaseSlot();
489
- record.worktreeResult = await cleanupWorktree(pi, baseCwd, wt, options.description);
1343
+ await discardWorktree();
490
1344
  this.drainQueue();
491
1345
  return;
492
1346
  }
493
1347
  }
494
- this.onStart?.(record);
495
- // Wire parent abort signal to stop the subagent when the parent is interrupted
496
- let detachParentSignal;
497
- if (options.signal) {
498
- // A queued spawn can start minutes after the caller handed us its signal,
499
- // by which time it may already be aborted — and `addEventListener` would
500
- // never fire, leaving a child the parent can no longer reach.
501
- if (options.signal.aborted)
502
- this.abort(id);
503
- else {
504
- const onParentAbort = () => this.abort(id);
505
- options.signal.addEventListener("abort", onParentAbort, { once: true });
506
- detachParentSignal = () => options.signal.removeEventListener("abort", onParentAbort);
507
- }
1348
+ // Re-check immediately before the run: the awaited worktree copy and an
1349
+ // async acquire guard are suspensions between the first check and the
1350
+ // first artifact/model work, and acquisition can be revoked while they
1351
+ // run. A refusal releases the slot and the fresh copy instead of leaving
1352
+ // either behind; a supersession does the same without starting anything.
1353
+ try {
1354
+ const guard = this.assertArtifactAccess(record);
1355
+ if (guard !== undefined)
1356
+ await guard;
508
1357
  }
509
- const detach = () => { detachParentSignal?.(); detachParentSignal = undefined; };
1358
+ catch (error) {
1359
+ detach();
1360
+ releaseSlot();
1361
+ await discardWorktree();
1362
+ this.drainQueue();
1363
+ throw error;
1364
+ }
1365
+ if (options.signal?.aborted)
1366
+ this.abort(id);
1367
+ if (!this.runIsCurrent(id, record, generation)) {
1368
+ detach();
1369
+ releaseSlot();
1370
+ await discardWorktree();
1371
+ this.drainQueue();
1372
+ return;
1373
+ }
1374
+ this.onStart?.(record);
510
1375
  this.activeRuns.add(record);
511
1376
  const promise = runAgent(ctx, type, prompt, {
512
1377
  pi,
513
1378
  agentId: id,
1379
+ agentDefinition: options.agentDefinition,
514
1380
  model: options.model,
515
1381
  maxTurns: options.maxTurns,
516
1382
  isolated: options.isolated,
@@ -550,11 +1416,15 @@ export class AgentManager {
550
1416
  this.onCompact?.(record, info);
551
1417
  options.onCompaction?.(info);
552
1418
  },
1419
+ rootSessionId: record.rootSessionId,
1420
+ rootCwd: record.rootCwd,
1421
+ rootSessionFile: record.rootSessionFile,
553
1422
  nestedRuntime: {
554
1423
  manager: this,
555
1424
  parentAgentId: id,
556
1425
  depth: record.depth ?? 1,
557
1426
  maxSubagentDepth: record.maxSubagentDepth,
1427
+ archive: this.archivedReportReader,
558
1428
  },
559
1429
  onSessionCreated: (session) => {
560
1430
  if (record.session && record.session !== session)
@@ -569,16 +1439,23 @@ export class AgentManager {
569
1439
  // stubbed session must degrade to "not resumable" rather than throw
570
1440
  // and take the whole spawn down with it.
571
1441
  record.sessionFile = session.sessionManager?.getSessionFile?.();
1442
+ record.sessionId = session.sessionManager?.getSessionId?.();
572
1443
  // Same reason, different field: the model and thinking level are only
573
1444
  // knowable once pi has resolved its defaults and clamped the level to
574
1445
  // what the model supports. Writing them back here makes the record
575
1446
  // authoritative, so every surface reads one place instead of each
576
1447
  // re-deriving "session, else the request" for itself.
577
1448
  updateEffectiveModel(record, session);
578
- if (this.disposed || record.status === "stopped") {
1449
+ if (this.disposed) {
1450
+ record.pendingSteers = undefined;
1451
+ void this.trackSessionShutdown(record, session);
1452
+ return;
1453
+ }
1454
+ // Ready now: the live record itself protects this session until its
1455
+ // teardown actually starts, so a provisional allocation row must go.
1456
+ this.markSessionReady(record, session);
1457
+ if (record.status === "stopped") {
579
1458
  record.pendingSteers = undefined;
580
- if (this.disposed)
581
- void shutdownChildSession(session);
582
1459
  return;
583
1460
  }
584
1461
  // Flush any steers that arrived before the session was ready
@@ -590,6 +1467,8 @@ export class AgentManager {
590
1467
  }
591
1468
  options.onSessionCreated?.(session);
592
1469
  },
1470
+ onSessionAllocated: (session) => this.noteSessionAllocated(record, session),
1471
+ onSessionTeardown: (session, outcome) => this.noteSessionTeardown(record, session, outcome),
593
1472
  })
594
1473
  .then(({ responseText, session, aborted, steered, failure, structuredJson, structuredRetried }) => {
595
1474
  // Keep the record running through cleanup: terminal status promises a
@@ -666,11 +1545,12 @@ export class AgentManager {
666
1545
  this.abortOwnedChildren(id);
667
1546
  this.activeRuns.delete(record);
668
1547
  if (this.disposed)
669
- await shutdownChildSession(record.session);
1548
+ await this.trackSessionShutdown(record, record.session);
670
1549
  this.settleRun(record, succeeded, pool);
671
1550
  return text;
672
1551
  });
673
1552
  record.promise = promise;
1553
+ this.trackPendingFinalizer(record, promise);
674
1554
  // Notify caller that spawn is complete (record is in the map, promise is set).
675
1555
  // Called synchronously — onSessionCreated fires asynchronously inside runAgent.
676
1556
  // Used by spawnAndWait to let the caller set up output files before streaming
@@ -699,6 +1579,11 @@ export class AgentManager {
699
1579
  settleRun(record, guardCallback, pool) {
700
1580
  if (!record.isBackground)
701
1581
  record.resultConsumed = true;
1582
+ // Before every completion callback: a durable copy of THIS generation's
1583
+ // report, while the record still describes the run that just settled.
1584
+ // Run protection is released separately, only after the COMPLETE finalizer
1585
+ // promise (including any output flush) settles.
1586
+ this.archiveTerminal(record);
702
1587
  if (pool === "background")
703
1588
  this.runningBackground--;
704
1589
  else if (pool === "foreground")
@@ -728,6 +1613,248 @@ export class AgentManager {
728
1613
  // A drain with nothing freed is a no-op anyway, but "no-op" is a claim
729
1614
  // about reachability, and matching the old condition needs no such claim.
730
1615
  }
1616
+ /**
1617
+ * Hand one settled generation to the durable-report archiver exactly once.
1618
+ *
1619
+ * Every terminal path calls this — fresh runs, foreground/background resumes,
1620
+ * queued cancellations, startup failures and the dispose sweep. Generation
1621
+ * dedupe matters because a run can be stopped while queued and then swept by
1622
+ * `dispose`: the first snapshot is the truthful one. A deadline FALLBACK may
1623
+ * still be replaced by the real same-generation finalizer (never the reverse),
1624
+ * so a run that settles just after the bounded window is not lost forever.
1625
+ */
1626
+ archiveTerminal(record, options = {}) {
1627
+ if (record.status === "running" || record.status === "queued")
1628
+ return;
1629
+ const generation = record.runGeneration ?? 0;
1630
+ const fallback = options.fallback === true;
1631
+ const prior = this.archivedGenerations.get(record.id);
1632
+ if (prior !== undefined) {
1633
+ if (prior.generation > generation)
1634
+ return;
1635
+ if (prior.generation === generation) {
1636
+ // Same generation: only a provisional fallback may be upgraded. A real
1637
+ // snapshot must never be replaced by a partial/stopped view.
1638
+ if (!(prior.fallback && !fallback))
1639
+ return;
1640
+ }
1641
+ }
1642
+ this.archivedGenerations.set(record.id, { generation, fallback });
1643
+ try {
1644
+ this.reportArchiver?.save(record);
1645
+ }
1646
+ catch (error) {
1647
+ // Report durability is never allowed to break settlement or shutdown.
1648
+ console.warn("[pi-subagents] durable report archive failed:", error);
1649
+ }
1650
+ }
1651
+ /**
1652
+ * Track a full run finalizer (output flush and worktree cleanup included) as
1653
+ * pending work for this record. Removed on either resolution branch; a record
1654
+ * can hold more than one because a newer generation settles first and
1655
+ * overwrites `record.promise` while the older flush is still in flight.
1656
+ */
1657
+ trackPendingFinalizer(record, promise) {
1658
+ let pending = this.pendingFinalizers.get(record);
1659
+ if (pending === undefined) {
1660
+ pending = new Set();
1661
+ this.pendingFinalizers.set(record, pending);
1662
+ }
1663
+ pending.add(promise);
1664
+ const release = () => {
1665
+ const current = this.pendingFinalizers.get(record);
1666
+ if (current === undefined)
1667
+ return;
1668
+ current.delete(promise);
1669
+ if (current.size === 0)
1670
+ this.pendingFinalizers.delete(record);
1671
+ };
1672
+ void promise.then(release, release);
1673
+ }
1674
+ identityFromRecord(record) {
1675
+ return {
1676
+ agentId: record.id,
1677
+ ...(record.sessionFile === undefined ? {} : { sessionFile: record.sessionFile }),
1678
+ ...(record.sessionId === undefined ? {} : { sessionId: record.sessionId }),
1679
+ ...(record.rootSessionId === undefined ? {} : { rootSessionId: record.rootSessionId }),
1680
+ ...(record.rootCwd === undefined ? {} : { rootCwd: record.rootCwd }),
1681
+ ...(record.rootSessionFile === undefined ? {} : { rootSessionFile: record.rootSessionFile }),
1682
+ };
1683
+ }
1684
+ /**
1685
+ * One protection identity per SDK session INSTANCE. The same session file can
1686
+ * be reopened as a different instance (A timed out, B later succeeds): B's
1687
+ * completion must not delete A's still-unresolved protection row.
1688
+ */
1689
+ ensureSessionTeardown(identity, session) {
1690
+ const knownId = this.teardownIds.get(session);
1691
+ if (knownId !== undefined) {
1692
+ const known = this.teardowns.get(knownId);
1693
+ if (known)
1694
+ return known;
1695
+ }
1696
+ const id = `session:${++this.teardownSequence}`;
1697
+ this.teardownIds.set(session, id);
1698
+ const row = {
1699
+ id,
1700
+ phase: "session",
1701
+ status: "pending",
1702
+ at: Date.now(),
1703
+ ...identity,
1704
+ session,
1705
+ };
1706
+ this.teardowns.set(id, row);
1707
+ return row;
1708
+ }
1709
+ applyTeardownOutcome(row, outcome) {
1710
+ row.status = outcome.status;
1711
+ row.reason = outcome.reason;
1712
+ // The SDK object must not outlive its teardown, even when the row is kept
1713
+ // forever as protection.
1714
+ row.session = undefined;
1715
+ if (outcome.status === "completed") {
1716
+ this.teardowns.delete(row.id);
1717
+ }
1718
+ else {
1719
+ row.at = Date.now();
1720
+ }
1721
+ }
1722
+ /**
1723
+ * Register protection synchronously, then start the bounded shutdown. The row
1724
+ * exists BEFORE the first await: an immediate dispose after eviction sees the
1725
+ * pending promise and cannot report `completed` for an unresolved handler.
1726
+ */
1727
+ startSessionTeardown(identity, session) {
1728
+ if (!session)
1729
+ return Promise.resolve({ status: "completed", timedOut: false });
1730
+ const row = this.ensureSessionTeardown(identity, session);
1731
+ if (row.promise)
1732
+ return row.promise;
1733
+ if (row.status !== "pending") {
1734
+ return Promise.resolve({
1735
+ status: row.status,
1736
+ timedOut: row.status === "timed_out",
1737
+ ...(row.reason === undefined ? {} : { reason: row.reason }),
1738
+ });
1739
+ }
1740
+ row.promise = shutdownChildSession(session).then(outcome => {
1741
+ this.applyTeardownOutcome(row, outcome);
1742
+ return outcome;
1743
+ }, (error) => {
1744
+ const outcome = {
1745
+ status: "failed",
1746
+ timedOut: false,
1747
+ reason: error instanceof Error ? error.message : String(error),
1748
+ };
1749
+ this.applyTeardownOutcome(row, outcome);
1750
+ return outcome;
1751
+ });
1752
+ return row.promise;
1753
+ }
1754
+ trackSessionShutdown(record, session) {
1755
+ return this.startSessionTeardown(this.identityFromRecord(record), session);
1756
+ }
1757
+ /** Record the allocated instance before binding; no ready announcement yet. */
1758
+ noteSessionAllocated(record, session) {
1759
+ record.sessionFile ??= session.sessionManager?.getSessionFile?.();
1760
+ record.sessionId ??= session.sessionManager?.getSessionId?.();
1761
+ const identity = this.identityFromRecord(record);
1762
+ this.ensureSessionTeardown(identity, session);
1763
+ if (!this.allocationStates.has(session)) {
1764
+ let resolveReady;
1765
+ const ready = new Promise(resolve => { resolveReady = resolve; });
1766
+ this.allocationStates.set(session, {
1767
+ session,
1768
+ identity,
1769
+ ready,
1770
+ resolveReady,
1771
+ settled: false,
1772
+ });
1773
+ }
1774
+ let allocated = this.allocations.get(record.id);
1775
+ if (!allocated) {
1776
+ allocated = new Set();
1777
+ this.allocations.set(record.id, allocated);
1778
+ }
1779
+ allocated.add(session);
1780
+ }
1781
+ /** Bind/session_start settled (successfully, or its failure teardown ran). */
1782
+ settleAllocation(session) {
1783
+ const state = this.allocationStates.get(session);
1784
+ if (!state || state.settled)
1785
+ return;
1786
+ state.settled = true;
1787
+ state.resolveReady();
1788
+ }
1789
+ /** The session is now a live, addressable record; teardown is not in flight. */
1790
+ markSessionReady(record, session) {
1791
+ const knownId = this.teardownIds.get(session);
1792
+ const row = knownId === undefined ? undefined : this.teardowns.get(knownId);
1793
+ if (row && row.promise === undefined && row.status === "pending") {
1794
+ this.teardowns.delete(row.id);
1795
+ }
1796
+ this.settleAllocation(session);
1797
+ this.releaseAllocation(record.id, session);
1798
+ }
1799
+ /** Bind-failure (or equivalent partial startup) outcome handed back by runner. */
1800
+ noteSessionTeardown(record, session, outcome) {
1801
+ this.ensureSessionTeardown(this.identityFromRecord(record), session);
1802
+ const knownId = this.teardownIds.get(session);
1803
+ const row = knownId === undefined ? undefined : this.teardowns.get(knownId);
1804
+ if (row)
1805
+ this.applyTeardownOutcome(row, outcome);
1806
+ this.settleAllocation(session);
1807
+ this.releaseAllocation(record.id, session);
1808
+ }
1809
+ releaseAllocation(agentId, session) {
1810
+ const allocated = this.allocations.get(agentId);
1811
+ if (!allocated)
1812
+ return;
1813
+ if (session)
1814
+ allocated.delete(session);
1815
+ else
1816
+ allocated.clear();
1817
+ if (allocated.size === 0)
1818
+ this.allocations.delete(agentId);
1819
+ }
1820
+ /** Protection row for a run/finalizer that outlived the shutdown deadline. */
1821
+ recordRunUncertainty(record, generation = record.runGeneration ?? 0) {
1822
+ const id = `run:${record.id}:${generation}`;
1823
+ const existing = this.teardowns.get(id);
1824
+ if (existing)
1825
+ return;
1826
+ this.teardowns.set(id, {
1827
+ id,
1828
+ phase: "run",
1829
+ status: "timed_out",
1830
+ at: Date.now(),
1831
+ reason: `run finalizer did not settle within ${MANAGER_SHUTDOWN_DEADLINE_MS}ms`,
1832
+ ...this.identityFromRecord(record),
1833
+ });
1834
+ }
1835
+ /**
1836
+ * Release protection for exactly the run generation whose COMPLETE disposal
1837
+ * aggregate (including every generation's output flush) settled. Called only
1838
+ * by dispose/reconcileLateFinalizer, never by an individual run finalizer: a
1839
+ * newer generation must not release an older generation's pending flush.
1840
+ */
1841
+ clearRunUncertainty(agentId, generation) {
1842
+ this.teardowns.delete(`run:${agentId}:${generation}`);
1843
+ }
1844
+ /**
1845
+ * A captured startup/run finalizer that outlived dispose's sweep still owes a
1846
+ * real report and the release of its provisional run protection. This runs
1847
+ * independently of map membership and never calls settleRun/callbacks or
1848
+ * releases a pool slot again.
1849
+ */
1850
+ reconcileLateFinalizer(record, generation) {
1851
+ if ((record.runGeneration ?? 0) !== generation)
1852
+ return;
1853
+ if (record.status === "running" || record.status === "queued")
1854
+ return;
1855
+ this.archiveTerminal(record);
1856
+ this.clearRunUncertainty(record.id, generation);
1857
+ }
731
1858
  /**
732
1859
  * Stop the nested children a settled parent owns. Nested records are hidden
733
1860
  * from the UI and only their owner can consume them, so a child outliving its
@@ -846,6 +1973,67 @@ export class AgentManager {
846
1973
  if (!record?.session || this.disposed || this.activeRuns.has(record)
847
1974
  || record.status === "running" || record.status === "queued")
848
1975
  return undefined;
1976
+ // Admission exclusivity is claimed SYNCHRONOUSLY, before the acquire guard
1977
+ // can suspend. Two callers can otherwise pass the settled-state check in
1978
+ // the same tick and both stamp a generation. The loser returns undefined
1979
+ // without touching terminal data; the winner releases the claim once the
1980
+ // record is queued/running (status carries exclusivity from then on) or
1981
+ // when admission is refused.
1982
+ if (this.resumeAdmissions.has(record))
1983
+ return undefined;
1984
+ this.resumeAdmissions.add(record);
1985
+ const admittedSession = record.session;
1986
+ const admittedGeneration = record.runGeneration ?? 0;
1987
+ // Acquire-side barrier BEFORE any run bookkeeping: a refusal leaves the
1988
+ // settled record (status, result, generation, session) exactly as it was.
1989
+ // An async guard is awaited here; everything below is the acceptance
1990
+ // decision, taken atomically in one synchronous continuation.
1991
+ try {
1992
+ const guard = this.assertArtifactAccess(record);
1993
+ if (guard !== undefined)
1994
+ await guard;
1995
+ }
1996
+ catch (error) {
1997
+ this.resumeAdmissions.delete(record);
1998
+ throw error;
1999
+ }
2000
+ // Revalidate after the guard's suspension: a dispose, eviction, newer run
2001
+ // or changed session must not be resumed by stale admission state.
2002
+ if (!this.resumeAdmissionIsCurrent(id, record, admittedSession, admittedGeneration)) {
2003
+ this.resumeAdmissions.delete(record);
2004
+ return undefined;
2005
+ }
2006
+ // Every guarded identity check has passed and the synchronous claim is
2007
+ // still held: this caller is the sole accepted resume. Hand it the record
2008
+ // NOW — before the generation stamp, terminal reset or any start — so shared
2009
+ // per-run wiring belongs to the winner only. A throwing hook is an ordinary
2010
+ // refusal: release the claim and leave the settled record untouched rather
2011
+ // than leaking admission and blocking every later resume.
2012
+ try {
2013
+ options?.onAdmitted?.(record);
2014
+ }
2015
+ catch (error) {
2016
+ this.resumeAdmissions.delete(record);
2017
+ throw error;
2018
+ }
2019
+ // The hook is caller code running while the claim is held: it may
2020
+ // synchronously dispose the manager, evict the record or replace its
2021
+ // session. Repeat the WHOLE admission identity check AFTER it — the same
2022
+ // capture the guard's suspension is revalidated against — so a
2023
+ // shutting-down record is never stamped, reset, queued or resumed, and hand
2024
+ // the claim back when the admission is refused.
2025
+ if (!this.resumeAdmissionIsCurrent(id, record, admittedSession, admittedGeneration)) {
2026
+ this.resumeAdmissions.delete(record);
2027
+ return undefined;
2028
+ }
2029
+ // A resume is a new run of the same record. Stamp it before any state is
2030
+ // reset so a superseded completion (held group, pending nudge) can be told
2031
+ // apart from this run's — a timestamp cannot, since a resume can land in
2032
+ // the same millisecond as the settle it replaces. Any earlier cleanup
2033
+ // readiness proof is now stale.
2034
+ record.runGeneration = admittedGeneration + 1;
2035
+ const generation = record.runGeneration;
2036
+ this.cleanupQuiescence.delete(id);
849
2037
  // Background resume: settle asynchronously and notify on completion exactly
850
2038
  // like a background spawn, returning immediately with the record still
851
2039
  // "running" — or "queued" when at the concurrency limit. Previously
@@ -870,8 +2058,10 @@ export class AgentManager {
870
2058
  record.status = "queued";
871
2059
  const start = () => this.startResume(id, record, prompt, signal, options);
872
2060
  if (occupiesPoolSlot(record) && !this.poolHasRoom("background")) {
873
- if (!this.armQueuedAbort(id, signal))
2061
+ if (!this.armQueuedAbort(record, signal)) {
2062
+ this.resumeAdmissions.delete(record);
874
2063
  return record;
2064
+ }
875
2065
  // At the concurrency limit — queue it, drains when a slot frees. A
876
2066
  // detached resume has no inline caller, hence nothing to release. The
877
2067
  // queue is shared with spawns, whose startup is async, so entries are
@@ -880,16 +2070,53 @@ export class AgentManager {
880
2070
  this.queue.push({
881
2071
  id,
882
2072
  pool: "background",
883
- start: async () => {
884
- try {
885
- start();
886
- }
887
- catch (err) {
888
- record.status = "error";
889
- record.error = err instanceof Error ? err.message : String(err);
890
- record.completedAt = Date.now();
891
- this.onComplete?.(record);
892
- }
2073
+ start: () => {
2074
+ const startup = (async () => {
2075
+ // Reserve capacity SYNCHRONOUSLY, before the acquire guard can
2076
+ // suspend. drainQueue checked this entry's pool a moment ago, but
2077
+ // a sync-guard sibling started earlier in the same drain would
2078
+ // otherwise still be invisible here and the backlog would all
2079
+ // start at once.
2080
+ const reservation = this.reservePoolSlot("background", record);
2081
+ try {
2082
+ // Actual (drained) start: acquisition was checked when the resume
2083
+ // was requested, but the reserved root may have changed while this
2084
+ // waited for a slot. A refusal follows this catch's ordinary
2085
+ // queued-start failure path; no model starts.
2086
+ const guard = this.assertArtifactAccess(record);
2087
+ if (guard !== undefined)
2088
+ await guard;
2089
+ }
2090
+ catch (err) {
2091
+ reservation?.releasePending();
2092
+ this.failQueuedResume(id, record, admittedSession, generation, err);
2093
+ return;
2094
+ }
2095
+ // Revalidate after the guard's suspension: abort while queued sets
2096
+ // "stopped", and a dispose or newer generation must not start a
2097
+ // late child on this session.
2098
+ if (!this.queuedResumeIsCurrent(id, record, admittedSession, generation)) {
2099
+ reservation?.releasePending();
2100
+ this.drainQueue();
2101
+ return;
2102
+ }
2103
+ try {
2104
+ this.startResume(id, record, prompt, signal, options, reservation);
2105
+ }
2106
+ catch (err) {
2107
+ this.failQueuedResume(id, record, admittedSession, generation, err);
2108
+ }
2109
+ })();
2110
+ // Expose the real start as pending startup work even though it is
2111
+ // routed from the queue, not launch(): waitForAll and dispose must
2112
+ // not treat a guard-suspended record as idle. Never left behind.
2113
+ this.startups.set(id, startup);
2114
+ const settle = () => {
2115
+ if (this.startups.get(id) === startup)
2116
+ this.startups.delete(id);
2117
+ };
2118
+ void startup.then(settle, settle);
2119
+ return startup;
893
2120
  },
894
2121
  release: () => { },
895
2122
  });
@@ -897,14 +2124,64 @@ export class AgentManager {
897
2124
  else {
898
2125
  start();
899
2126
  }
2127
+ this.resumeAdmissions.delete(record);
900
2128
  return record;
901
2129
  }
902
2130
  // Foreground resumes use the same controller and stopped-state guard, but
903
2131
  // keep their historical inline-only result (no background notification/pool).
904
2132
  this.startResume(id, record, prompt, signal, { ...options, isBackground: false });
2133
+ this.resumeAdmissions.delete(record);
905
2134
  await record.promise;
906
2135
  return record;
907
2136
  }
2137
+ /**
2138
+ * A resume that suspended on its acquire guard still owns the record only if
2139
+ * nothing terminal happened while it waited. Kept separate from the queued
2140
+ * variant: a queued resume legitimately sits in "queued" while admitting.
2141
+ */
2142
+ resumeAdmissionIsCurrent(id, record, session, generation) {
2143
+ return !this.disposed
2144
+ && this.agents.get(id) === record
2145
+ && record.session === session
2146
+ && (record.runGeneration ?? 0) === generation
2147
+ && record.status !== "running"
2148
+ && record.status !== "queued"
2149
+ && !this.activeRuns.has(record);
2150
+ }
2151
+ /** Same revalidation for a resume whose queued start just awaited its guard. */
2152
+ queuedResumeIsCurrent(id, record, session, generation) {
2153
+ return !this.disposed
2154
+ && this.agents.get(id) === record
2155
+ && record.session === session
2156
+ && (record.runGeneration ?? 0) === generation
2157
+ && record.status === "queued"
2158
+ && !this.activeRuns.has(record);
2159
+ }
2160
+ /** The queued-start refusal path: this generation is terminal, no run began. */
2161
+ failQueuedResume(id, record, session, generation, error) {
2162
+ // A dispose, eviction, abort or newer generation during the guard owns the
2163
+ // record now. A late rejection must not overwrite that generation's state.
2164
+ if (!this.queuedResumeIsCurrent(id, record, session, generation)) {
2165
+ this.drainQueue();
2166
+ return;
2167
+ }
2168
+ // No run finalizer will detach this queued wire. Retire it before any
2169
+ // terminal observer can resume the record without a parent signal.
2170
+ this.releaseSignalWire(record);
2171
+ record.status = "error";
2172
+ record.error = error instanceof Error ? error.message : String(error);
2173
+ record.completedAt = Date.now();
2174
+ // The refusal is this generation's terminal report. No pool slot was
2175
+ // claimed, so archive before notifying without settling.
2176
+ this.archiveTerminal(record);
2177
+ try {
2178
+ this.onComplete?.(record);
2179
+ }
2180
+ finally {
2181
+ // An observer failure must not strand siblings behind this refused start.
2182
+ this.drainQueue();
2183
+ }
2184
+ }
908
2185
  /**
909
2186
  * Start a background resume run: detached, settling and notifying like
910
2187
  * startAgent's background path. Invoked immediately, or from drainQueue when
@@ -912,9 +2189,11 @@ export class AgentManager {
912
2189
  * there is no onSessionCreated to hang per-run wiring off — callers use
913
2190
  * `options.onStarted`, which fires on both the immediate and the drained path.
914
2191
  */
915
- startResume(id, record, prompt, parentSignal, options) {
916
- if (!record.session)
2192
+ startResume(id, record, prompt, parentSignal, options, reservation) {
2193
+ if (!record.session) {
2194
+ reservation?.releasePending();
917
2195
  return;
2196
+ }
918
2197
  const background = options.isBackground === true;
919
2198
  const holdsSlot = background && occupiesPoolSlot(record);
920
2199
  this.activeRuns.add(record);
@@ -923,8 +2202,18 @@ export class AgentManager {
923
2202
  record.completedAt = undefined;
924
2203
  record.result = undefined;
925
2204
  record.error = undefined;
926
- if (holdsSlot)
927
- this.runningBackground++;
2205
+ if (holdsSlot) {
2206
+ // A queued start reserved this capacity before its guard awaited; an
2207
+ // immediate start increments it here, still synchronously with the
2208
+ // capacity decision made by resume().
2209
+ if (reservation)
2210
+ reservation.transfer();
2211
+ else
2212
+ this.runningBackground++;
2213
+ }
2214
+ else {
2215
+ reservation?.releasePending();
2216
+ }
928
2217
  if (background)
929
2218
  this.onStart?.(record);
930
2219
  // Fresh abort controller so /agents stop and steering target THIS run rather
@@ -935,15 +2224,15 @@ export class AgentManager {
935
2224
  // parent signal aborts on the parent's own interrupt (user Esc), which is
936
2225
  // right for a foreground run whose result the caller is awaiting, and wrong
937
2226
  // for a detached one — background spawns omit it for exactly this reason.
938
- let detachParentSignal;
2227
+ // Generation-owned: this replaces the queued wire this resume carried, and
2228
+ // abort()/abortAll()/dispose() can detach it without waiting for `settle`.
2229
+ const generation = record.runGeneration ?? 0;
2230
+ let signalWire;
939
2231
  if (parentSignal) {
940
- const onParentAbort = () => this.abort(id);
941
2232
  if (parentSignal.aborted)
942
- onParentAbort();
943
- else {
944
- parentSignal.addEventListener("abort", onParentAbort, { once: true });
945
- detachParentSignal = () => parentSignal.removeEventListener("abort", onParentAbort);
946
- }
2233
+ this.abort(id);
2234
+ else
2235
+ signalWire = this.attachSignalWire(record, parentSignal, generation);
947
2236
  }
948
2237
  // Per-run side effects (output streaming) — see ResumeOptions.onStarted.
949
2238
  // After the record is in its running shape, before the run is kicked off.
@@ -959,11 +2248,16 @@ export class AgentManager {
959
2248
  if (settled)
960
2249
  return undefined;
961
2250
  settled = true;
2251
+ // Synchronous terminal bookkeeping FIRST: a foreground resume has no
2252
+ // onComplete, so its archived snapshot is the only report — it must not
2253
+ // omit discarded steers or the model the resumed turn actually used.
962
2254
  discardStaleSteers(record);
963
2255
  if (record.session)
964
2256
  updateEffectiveModel(record, record.session);
965
- detachParentSignal?.();
966
- detachParentSignal = undefined;
2257
+ this.detachSignalWire(record, signalWire);
2258
+ signalWire = undefined;
2259
+ // Then clone/archive, still before any awaited flush or caller callback.
2260
+ this.archiveTerminal(record);
967
2261
  // Final flush of streaming output file
968
2262
  let flushed;
969
2263
  if (record.outputCleanup) {
@@ -1037,6 +2331,7 @@ export class AgentManager {
1037
2331
  return "";
1038
2332
  });
1039
2333
  record.promise = promise;
2334
+ this.trackPendingFinalizer(record, promise);
1040
2335
  }
1041
2336
  /**
1042
2337
  * Send a steering message to an agent from the UI (mirrors the steer_subagent
@@ -1121,38 +2416,41 @@ export class AgentManager {
1121
2416
  }
1122
2417
  /**
1123
2418
  * Resolve an `@name` from the prompt. Matches a top-level agent's handle
1124
- * case-insensitively, preferring one that can still be steered and otherwise
1125
- * the most recently started (which is the one a resume should continue), then
1126
- * falls back to an exact agent id so `@<agentId>` works too.
2419
+ * case-insensitively, preferring active work, then the newest usable session.
2420
+ * A failed startup cannot shadow a saved conversation. Exact ids still name
2421
+ * their own record, including a retained startup failure.
1127
2422
  */
1128
2423
  resolveMention(name) {
1129
2424
  const wanted = name.toLowerCase();
1130
2425
  let fallback;
2426
+ let resumable;
1131
2427
  for (const record of this.agents.values()) {
1132
2428
  if (record.parentAgentId !== undefined)
1133
2429
  continue;
1134
- // Handle and alias share one namespace, so at most one agent answers a
1135
- // name and it makes no difference which of the two matched.
2430
+ // Reclaimed names can have older failed records; active work or an
2431
+ // established session takes precedence over those sessionless attempts.
1136
2432
  if (record.handle?.toLowerCase() !== wanted && record.alias?.toLowerCase() !== wanted)
1137
2433
  continue;
1138
2434
  if (record.status === "running" || record.status === "queued")
1139
2435
  return { kind: "live", record };
1140
2436
  if (!fallback || record.startedAt > fallback.startedAt)
1141
2437
  fallback = record;
2438
+ if (record.session && (!resumable || record.startedAt > resumable.startedAt))
2439
+ resumable = record;
1142
2440
  }
1143
- if (fallback)
1144
- return { kind: "live", record: fallback };
2441
+ if (resumable)
2442
+ return { kind: "live", record: resumable };
1145
2443
  const byId = this.agents.get(name);
1146
- if (byId?.parentAgentId === undefined && byId !== undefined)
2444
+ if (!fallback && byId?.parentAgentId === undefined && byId !== undefined)
1147
2445
  return { kind: "live", record: byId };
1148
- // Only once nothing live answers: a tombstone is a conversation to reopen,
1149
- // and reopening one while its record still exists would fork the session.
2446
+ // A failed startup has no session to continue. Do not let its retained
2447
+ // error record shadow the last usable conversation under the same name.
1150
2448
  for (const entry of this.tombstones.values()) {
1151
2449
  if (entry.handle.toLowerCase() === wanted || entry.alias?.toLowerCase() === wanted || entry.id === name) {
1152
2450
  return { kind: "tombstone", entry };
1153
2451
  }
1154
2452
  }
1155
- return undefined;
2453
+ return fallback ? { kind: "live", record: fallback } : undefined;
1156
2454
  }
1157
2455
  /**
1158
2456
  * Forget an evicted agent, by handle. For the case where its session file has
@@ -1170,6 +2468,10 @@ export class AgentManager {
1170
2468
  listTombstones() {
1171
2469
  return [...this.tombstones.values()].sort((a, b) => b.completedAt - a.completedAt);
1172
2470
  }
2471
+ /** Actual pool queue membership, excluding a start suspended on its guard. */
2472
+ isQueued(id) {
2473
+ return this.queue.some(entry => entry.id === id);
2474
+ }
1173
2475
  listAgents() {
1174
2476
  return [...this.agents.values()].sort((a, b) => b.startedAt - a.startedAt);
1175
2477
  }
@@ -1177,13 +2479,47 @@ export class AgentManager {
1177
2479
  const record = this.agents.get(id);
1178
2480
  if (!record)
1179
2481
  return false;
1180
- // Remove from queue if queued. No decrement — the slot was never taken —
1181
- // and no onComplete, matching what a queued background abort has always
1182
- // done; a blocking caller learns of the stop from its own tool result.
2482
+ // Capture both generation-owned resources BEFORE any callback, signal or
2483
+ // archive can re-enter. A completion observer may immediately resume this
2484
+ // same record — its admission is free, the status is already terminal — and
2485
+ // that newer generation installs its OWN pending claim and its own parent
2486
+ // signal wire. Freeing by lookup afterwards would free those instead: a
2487
+ // running charge the new generation still owns, whose transfer would then
2488
+ // no-op and whose finalizer would underflow the pool counter.
2489
+ const pendingClaim = this.capturePendingClaim(record);
2490
+ const signalWire = this.signalWires.get(record);
2491
+ // Reach the parent signal FIRST: a start suspended on a guard that never
2492
+ // settles must not keep this manager reachable from a live parent signal,
2493
+ // and the identity-aware detach cannot silence a newer generation's
2494
+ // listener installed later in this call.
2495
+ this.detachSignalWire(record, signalWire);
2496
+ // Remove from queue if queued. No decrement — the slot was never taken.
2497
+ // It still settles through the ordinary completion path, so a yielded
2498
+ // result wait (and every lifecycle listener) hears about the stop; a
2499
+ // foreground record suppresses that notification exactly as a foreground
2500
+ // settle does, since its inline caller gets the outcome itself.
1183
2501
  if (record.status === "queued") {
1184
2502
  this.dequeue(q => q.id === id);
1185
2503
  record.status = "stopped";
1186
2504
  record.completedAt = Date.now();
2505
+ if (!record.isBackground)
2506
+ record.resultConsumed = true;
2507
+ this.archiveTerminal(record);
2508
+ if (!this.disposed) {
2509
+ this.notifiedQueuedAborts.set(record, record.runGeneration ?? 0);
2510
+ try {
2511
+ this.onComplete?.(record);
2512
+ }
2513
+ catch {
2514
+ console.warn(`[pi-subagents] Completion callback failed for stopped queued agent ${record.id}.`);
2515
+ }
2516
+ }
2517
+ // A start suspended on its acquire guard has no queue entry but still
2518
+ // owns pending capacity. Free it NOW — the guard may never settle — so
2519
+ // the next queued job can start; a real run's charge is not in this map.
2520
+ // Only the claim captured above: a callback that resumed this record has
2521
+ // already given its newer generation one of its own.
2522
+ this.releaseCapturedClaim(record, pendingClaim, true);
1187
2523
  return true;
1188
2524
  }
1189
2525
  if (record.status !== "running")
@@ -1191,6 +2527,11 @@ export class AgentManager {
1191
2527
  record.abortController?.abort();
1192
2528
  record.status = "stopped";
1193
2529
  record.completedAt = Date.now();
2530
+ // Marked stopped first, then drain: a start suspended on its acquire guard
2531
+ // may still be "running" here with only a pending claim. Release only that
2532
+ // captured claim; a real run's charge remains with its finalizer, and a
2533
+ // claim a re-entrant callback installed for a newer generation is not ours.
2534
+ this.releaseCapturedClaim(record, pendingClaim, true);
1194
2535
  return true;
1195
2536
  }
1196
2537
  /** Dispose a record's session and remove it from the map. */
@@ -1201,13 +2542,18 @@ export class AgentManager {
1201
2542
  // nothing can observe a session that is half torn down.
1202
2543
  record.session = undefined;
1203
2544
  this.agents.delete(id);
2545
+ this.archivedGenerations.delete(id);
2546
+ this.cleanupQuiescence.delete(id);
2547
+ this.releaseAllocation(id);
1204
2548
  // A failed startup keeps its (rejected) entry so a late awaitStartup still
1205
2549
  // sees it; drop it with the record so the map can't grow unbounded.
1206
2550
  this.startups.delete(id);
1207
2551
  // Fire-and-forget is right here and only here: this runs from the 60s cleanup timer
1208
2552
  // and from `clearCompleted()` on session boundaries, with the process staying alive,
1209
2553
  // so handlers get their full window. The quit path awaits instead — see dispose().
1210
- void shutdownChildSession(session);
2554
+ // The outcome is still tracked: an evicted row whose teardown timed out must
2555
+ // remain protected even though nothing is left to resume.
2556
+ void this.trackSessionShutdown(record, session);
1211
2557
  }
1212
2558
  /**
1213
2559
  * Preserve enough of a departing record for `@handle` to reopen its
@@ -1239,6 +2585,10 @@ export class AgentManager {
1239
2585
  for (const [id, record] of this.agents) {
1240
2586
  if (this.activeRuns.has(record) || record.status === "running" || record.status === "queued")
1241
2587
  continue;
2588
+ // A settled record can still own a pending output/worktree finalizer.
2589
+ // Evicting it would drop the only handle to that work.
2590
+ if (this.pendingFinalizers.has(record))
2591
+ continue;
1242
2592
  if ((record.completedAt ?? 0) >= cutoff)
1243
2593
  continue;
1244
2594
  this.removeRecord(id, record);
@@ -1254,6 +2604,10 @@ export class AgentManager {
1254
2604
  for (const [id, record] of this.agents) {
1255
2605
  if (this.activeRuns.has(record) || record.status === "running" || record.status === "queued")
1256
2606
  continue;
2607
+ // Same rule as the 10-minute sweep: a still-finalizing settled record is
2608
+ // not evictable until its output/worktree finalizer settles.
2609
+ if (this.pendingFinalizers.has(record))
2610
+ continue;
1257
2611
  if (skipUnconsumed && !record.resultConsumed)
1258
2612
  continue;
1259
2613
  this.removeRecord(id, record);
@@ -1273,25 +2627,60 @@ export class AgentManager {
1273
2627
  /** Abort all running and queued agents immediately. */
1274
2628
  abortAll() {
1275
2629
  let count = 0;
1276
- // Clear queued agents first
2630
+ // Clear queued agents first. Claims are released WITHOUT draining: a drain
2631
+ // here could start an entry this same loop has not canceled yet.
1277
2632
  for (const queued of this.queue) {
1278
2633
  const record = this.agents.get(queued.id);
1279
2634
  if (record) {
2635
+ // Generation-owned cleanup is reachable immediately: a start suspended
2636
+ // on a guard that never settles must not keep a live parent signal
2637
+ // pointing at this manager after the bulk cancel.
2638
+ this.releaseSignalWire(record);
1280
2639
  record.status = "stopped";
1281
2640
  record.completedAt = Date.now();
2641
+ if (!record.isBackground)
2642
+ record.resultConsumed = true;
2643
+ this.archiveTerminal(record);
2644
+ this.releasePendingClaim(record, false);
1282
2645
  count++;
1283
2646
  }
1284
2647
  }
1285
2648
  this.dequeue(() => true);
1286
- // Abort running agents
2649
+ // A start that was already spliced out of the queue (or launched while it
2650
+ // had room) may still be "queued" while it awaits an async acquire guard.
2651
+ // It has no queue entry for the loop above to reach, but it is still queued
2652
+ // work and must be stopped before the guard resolves — otherwise the start
2653
+ // would continue after abortAll and burn a run nobody can reach. Its pending
2654
+ // claim is freed too, still without draining anything mid-cancel.
2655
+ for (const record of this.agents.values()) {
2656
+ if (record.status !== "queued")
2657
+ continue;
2658
+ this.releaseSignalWire(record);
2659
+ record.status = "stopped";
2660
+ record.completedAt = Date.now();
2661
+ if (!record.isBackground)
2662
+ record.resultConsumed = true;
2663
+ this.archiveTerminal(record);
2664
+ this.releasePendingClaim(record, false);
2665
+ count++;
2666
+ }
2667
+ // Abort running agents. A "running" record suspended in its guard still
2668
+ // owns only a pending claim (released here); a transferred claim is a real
2669
+ // charge and stays until that run's finalizer settles.
1287
2670
  for (const record of this.agents.values()) {
1288
2671
  if (record.status === "running") {
2672
+ this.releaseSignalWire(record);
2673
+ this.releasePendingClaim(record, false);
1289
2674
  record.abortController?.abort();
1290
2675
  record.status = "stopped";
1291
2676
  record.completedAt = Date.now();
1292
2677
  count++;
1293
2678
  }
1294
2679
  }
2680
+ // Everything is stopped now; only here may freed capacity let a queued
2681
+ // entry through. Nothing is left in the queue, so this is a no-op drain
2682
+ // kept for symmetry with the individual cancellation path.
2683
+ this.drainQueue();
1295
2684
  return count;
1296
2685
  }
1297
2686
  /** Wait for all running and queued agents to complete (including queued ones). */
@@ -1338,17 +2727,158 @@ export class AgentManager {
1338
2727
  for (const repo of this.worktreeRepos)
1339
2728
  prune(repo);
1340
2729
  }
1341
- if (this.disposed)
1342
- return this.shutdown;
2730
+ if (this.disposed) {
2731
+ return this.shutdown ?? { status: "completed", uncertain: this.listUncertainTeardowns() };
2732
+ }
1343
2733
  this.disposed = true;
1344
2734
  clearInterval(this.cleanupInterval);
2735
+ // Publish the shutdown promise BEFORE aborting: abort/archiver callbacks can
2736
+ // re-enter dispose() synchronously, and must observe this teardown rather
2737
+ // than an early "completed" snapshot.
2738
+ let resolveShutdown;
2739
+ this.shutdown = new Promise(resolve => {
2740
+ resolveShutdown = resolve;
2741
+ });
2742
+ const shutdown = this.shutdown;
1345
2743
  this.abortAll();
1346
- const sessions = [...this.agents.values()].map(record => record.session);
2744
+ // Capture every promise BEFORE the maps are cleared: an agent whose run,
2745
+ // startup or output/worktree finalizer is still pending owes this manager a
2746
+ // terminal report, and its teardown outcome must not be forgotten.
2747
+ const entries = [...this.agents.values()].map(record => ({
2748
+ record,
2749
+ session: record.session,
2750
+ startup: this.startups.get(record.id),
2751
+ run: record.promise,
2752
+ // EVERY generation's finalizer, not just the one currently published on
2753
+ // the record: a resumed run can replace `record.promise` while an older
2754
+ // generation still owes its output flush.
2755
+ finalizers: [...(this.pendingFinalizers.get(record) ?? [])],
2756
+ allocations: [...(this.allocations.get(record.id) ?? [])],
2757
+ }));
2758
+ // Every pre-ready allocation, including one whose record was already
2759
+ // evicted. Teardown must wait for its active bind/session_start.
2760
+ const allocationSessions = [
2761
+ ...entries.flatMap(entry => entry.allocations),
2762
+ ...Array.from(this.allocations.values()).flatMap(allocated => [...allocated]),
2763
+ ];
2764
+ const allocationStates = [...new Set(allocationSessions)]
2765
+ .map(session => this.allocationStates.get(session))
2766
+ .filter((state) => state !== undefined);
1347
2767
  this.agents.clear();
1348
2768
  this.startups.clear();
1349
- // Awaited, unlike eviction: bounded shutdown handlers run before Pi exits.
1350
- this.shutdown = Promise.all(sessions.map(session => shutdownChildSession(session))).then(() => { });
1351
- return this.shutdown;
2769
+ this.allocations.clear();
2770
+ this.cleanupQuiescence.clear();
2771
+ void (async () => {
2772
+ const jobs = new Set();
2773
+ // Already-evicted teardowns still in flight (finding 2): include them even
2774
+ // though no runtime record remains to consult.
2775
+ for (const row of this.teardowns.values()) {
2776
+ if (row.promise)
2777
+ jobs.add(row.promise);
2778
+ }
2779
+ for (const entry of entries) {
2780
+ if (entry.session) {
2781
+ jobs.add(this.trackSessionShutdown(entry.record, entry.session));
2782
+ }
2783
+ }
2784
+ // Pre-ready allocations are sequenced AFTER bind/session_start settles.
2785
+ // Emitting shutdown into an active bind can miss a resource the handler
2786
+ // allocates later; a hang stays pending/uncertain instead of `completed`.
2787
+ for (const state of allocationStates) {
2788
+ jobs.add(state.ready.then(() => this.startSessionTeardown(state.identity, state.session)));
2789
+ }
2790
+ // If the run settles before `onSessionCreated` (for example a non-bind
2791
+ // failure after allocation), the bind phase is over and teardown may run.
2792
+ for (const entry of entries) {
2793
+ const release = () => {
2794
+ for (const allocated of entry.allocations)
2795
+ this.settleAllocation(allocated);
2796
+ };
2797
+ if (entry.run)
2798
+ void entry.run.then(release, release);
2799
+ }
2800
+ // Other pending rows: never start one owned by a pre-ready allocation —
2801
+ // its gated job above decides when that instance may be torn down.
2802
+ for (const row of [...this.teardowns.values()]) {
2803
+ if (row.promise || !row.session)
2804
+ continue;
2805
+ if (this.allocationStates.has(row.session))
2806
+ continue;
2807
+ jobs.add(this.startSessionTeardown(row, row.session));
2808
+ }
2809
+ const finalizers = entries.map(entry => {
2810
+ const generation = entry.record.runGeneration ?? 0;
2811
+ const finalized = (async () => {
2812
+ if (entry.startup)
2813
+ await entry.startup.catch(() => { });
2814
+ // A run can be created while startup settles (worktree copy), so read
2815
+ // the record after the startup promise rather than only the snapshot.
2816
+ const pending = new Set(entry.finalizers);
2817
+ const run = entry.run ?? entry.record.promise;
2818
+ if (run)
2819
+ pending.add(run);
2820
+ // Finalizers can be registered while the startup awaited above.
2821
+ for (const promise of this.pendingFinalizers.get(entry.record) ?? [])
2822
+ pending.add(promise);
2823
+ await Promise.allSettled([...pending]);
2824
+ })();
2825
+ return { entry, generation, promise: finalized.then(() => true, () => true) };
2826
+ });
2827
+ const finished = entries.map(() => false);
2828
+ finalizers.forEach((finalized, index) => {
2829
+ void finalized.promise.then(() => { finished[index] = true; });
2830
+ });
2831
+ let timer;
2832
+ const deadline = new Promise(resolve => {
2833
+ timer = setTimeout(() => resolve("deadline"), MANAGER_SHUTDOWN_DEADLINE_MS);
2834
+ timer.unref?.();
2835
+ });
2836
+ // One COMMON deadline for SDK handlers, bind jobs, run promises and
2837
+ // finalizers. A live worker is never awaited indefinitely.
2838
+ try {
2839
+ await Promise.race([
2840
+ Promise.all([...jobs, ...finalizers.map(finalizer => finalizer.promise)]),
2841
+ deadline,
2842
+ ]);
2843
+ }
2844
+ finally {
2845
+ if (timer !== undefined)
2846
+ clearTimeout(timer);
2847
+ }
2848
+ finalizers.forEach(({ entry, generation, promise }, index) => {
2849
+ if (finished[index]) {
2850
+ // Real terminal state and result, after every finalizer had its turn.
2851
+ this.archiveTerminal(entry.record);
2852
+ this.clearRunUncertainty(entry.record.id, generation);
2853
+ }
2854
+ else {
2855
+ // Explicit uncertainty, never "completed": the run still owns its
2856
+ // agent/root/path protection. A later same-generation finalizer may
2857
+ // upgrade this provisional stopped view.
2858
+ this.recordRunUncertainty(entry.record, generation);
2859
+ this.archiveTerminal(entry.record, { fallback: true });
2860
+ void promise.then(() => this.reconcileLateFinalizer(entry.record, generation));
2861
+ }
2862
+ });
2863
+ let status = "completed";
2864
+ for (const row of this.teardowns.values()) {
2865
+ if (row.status === "pending" || row.status === "timed_out") {
2866
+ status = "timed_out";
2867
+ break;
2868
+ }
2869
+ if (row.status === "failed")
2870
+ status = "failed";
2871
+ }
2872
+ resolveShutdown({ status, uncertain: this.listUncertainTeardowns() });
2873
+ })().catch(error => {
2874
+ // A teardown failure is uncertainty, never a completed shutdown.
2875
+ console.warn("[pi-subagents] manager shutdown bookkeeping failed:", error);
2876
+ resolveShutdown({
2877
+ status: "failed",
2878
+ uncertain: this.listUncertainTeardowns(),
2879
+ });
2880
+ });
2881
+ return shutdown;
1352
2882
  }
1353
2883
  }
1354
2884
  /**