@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,10 +15,12 @@
15
15
  */
16
16
  import type { Model } from "@earendil-works/pi-ai";
17
17
  import type { AgentSession, ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
18
- import { type ToolActivity } from "./agent-runner.js";
19
- import type { AgentInvocation, AgentRecord, AgentTombstone, IsolationMode, MentionResolution, SubagentType, ThinkingLevel } from "./types.js";
20
- import { type LifetimeUsage } from "./usage.js";
21
- import type { CompiledSchema } from "./workflow/json-schema.js";
18
+ import { type ToolActivity } from "./agent-runner.ts";
19
+ import { type ChildShutdownStatus } from "./child-session-shutdown.ts";
20
+ import type { ArchivedReportReader } from "./nested-tools.ts";
21
+ import type { AgentConfig, AgentInvocation, AgentRecord, AgentTombstone, IsolationMode, MentionResolution, SubagentType, ThinkingLevel } from "./types.ts";
22
+ import { type LifetimeUsage } from "./usage.ts";
23
+ import type { CompiledSchema } from "./workflow/json-schema.ts";
22
24
  export type OnAgentComplete = (record: AgentRecord) => void;
23
25
  export type OnAgentStart = (record: AgentRecord) => void;
24
26
  export type OnAgentCompact = (record: AgentRecord, info: CompactionInfo) => void;
@@ -36,6 +38,57 @@ export type CompactionInfo = {
36
38
  reason: "manual" | "threshold" | "overflow";
37
39
  tokensBefore: number;
38
40
  };
41
+ /**
42
+ * Purpose-specific hook for durable reports.
43
+ *
44
+ * Deliberately not a general observer: the manager calls it exactly once per
45
+ * terminal generation, synchronously, BEFORE any completion notification or
46
+ * other caller callback can re-enter `resume()`. An adapter must therefore
47
+ * copy whatever it keeps immediately — a report store does — rather than hold
48
+ * the live record, whose `status`/`result` a resume can overwrite.
49
+ *
50
+ * Unlike `OnAgentComplete`, this fires for foreground resumes (which have no
51
+ * completion notification), queued cancellations and shutdown sweeps.
52
+ */
53
+ export interface AgentReportArchiver {
54
+ save(record: AgentRecord): void;
55
+ }
56
+ /** A teardown that did not prove quiescence; cleanup must keep its paths protected. */
57
+ export interface UncertainTeardown {
58
+ agentId: string;
59
+ /**
60
+ * `pending` means the bounded teardown is still in flight. It is protection,
61
+ * not an outcome: cleanup must treat it exactly like a timeout.
62
+ */
63
+ status: ChildShutdownStatus | "pending";
64
+ /** Whether the unfinished work is child-session teardown or a run finalizer. */
65
+ phase?: "session" | "run";
66
+ /** Per-session-instance identity; never reuse this across reopen attempts. */
67
+ teardownId?: string;
68
+ sessionFile?: string;
69
+ sessionId?: string;
70
+ rootSessionId?: string;
71
+ rootCwd?: string;
72
+ rootSessionFile?: string;
73
+ reason?: string;
74
+ at: number;
75
+ }
76
+ /** Result of disposing a manager: what was torn down and what remains uncertain. */
77
+ export interface AgentManagerShutdown {
78
+ status: ChildShutdownStatus;
79
+ uncertain: UncertainTeardown[];
80
+ }
81
+ /**
82
+ * The manager half of a cleanup preparation pass: which requested reports and
83
+ * session files proved quiescent, and an explicit reason for every one that did
84
+ * not. Each requested item appears on exactly one side.
85
+ */
86
+ export interface AgentCleanupPreparation {
87
+ readyAgentIds: string[];
88
+ blockedAgentIds: Record<string, string>;
89
+ readySessionFiles: string[];
90
+ blockedSessionFiles: Record<string, string>;
91
+ }
39
92
  /**
40
93
  * Whether a record is one of the session's own agents, rather than something
41
94
  * another agent or a workflow owns.
@@ -46,6 +99,7 @@ export type CompactionInfo = {
46
99
  * it separately would double-count the same work in the places a person reads.
47
100
  */
48
101
  export declare function isTopLevelAgent(record: Pick<AgentRecord, "parentAgentId" | "workflowId">): boolean;
102
+ type ArtifactAccessGuard = (record: AgentRecord) => void | Promise<void>;
49
103
  interface SpawnOptions {
50
104
  description: string;
51
105
  /**
@@ -61,6 +115,14 @@ interface SpawnOptions {
61
115
  * the type's CURRENT config.
62
116
  */
63
117
  resumeSessionFile?: string;
118
+ /**
119
+ * Internal, manager-only: the definition admitted for this spawn. Callers
120
+ * that resolve against a scoped registry (nested delegation, RPC, the root
121
+ * Agent tool) capture it before their own admission await and pass it here;
122
+ * omitted, `spawn()` snapshots the process-global registry synchronously,
123
+ * before the spawn is queued or starts awaiting work.
124
+ */
125
+ agentDefinition?: AgentConfig;
64
126
  /**
65
127
  * Take an evicted agent's names back verbatim instead of allocating fresh
66
128
  * ones, so a resumed conversation keeps the handle the user just typed —
@@ -188,6 +250,15 @@ interface SpawnOptions {
188
250
  configCwd?: string;
189
251
  /** Root session id, inherited by nested launches so transcripts stay grouped. */
190
252
  rootSessionId?: string;
253
+ /** Stable root project dir, inherited by owned children (never a worktree cwd). */
254
+ rootCwd?: string;
255
+ /** Root session file, inherited by owned children for durable provenance. */
256
+ rootSessionFile?: string;
257
+ /**
258
+ * Internal ownership lineage, derived by the manager from the live parent
259
+ * chain. Never accepted from an external caller (`spawnTopLevel` strips it).
260
+ */
261
+ ownerIds?: string[];
191
262
  }
192
263
  interface ResumeOptions {
193
264
  /**
@@ -217,6 +288,21 @@ interface ResumeOptions {
217
288
  * torn that subscription down.
218
289
  */
219
290
  onStarted?: () => void;
291
+ /**
292
+ * Called synchronously exactly once by the WINNING resume, while the
293
+ * manager's exclusive per-record admission claim is still held: after the
294
+ * acquire guard and every identity revalidation, before the generation is
295
+ * stamped or any terminal/run bookkeeping begins. A losing concurrent caller,
296
+ * a refused guard, an evicted/disposed record or a superseded admission never
297
+ * reaches it.
298
+ *
299
+ * This is the ownership boundary for caller-visible per-run wiring (tool call
300
+ * id, join mode, output path/cleanup, anchors): mutation before this point can
301
+ * make a refused request masquerade as the accepted one. A throw is treated as
302
+ * a refusal — the claim is released and the record keeps its previous terminal
303
+ * state, so a later resume is not wedged.
304
+ */
305
+ onAdmitted?: (record: AgentRecord) => void;
220
306
  }
221
307
  export declare class AgentManager {
222
308
  private agents;
@@ -229,6 +315,40 @@ export declare class AgentManager {
229
315
  private onStart?;
230
316
  private onCompact?;
231
317
  private onUsage?;
318
+ private reportArchiver?;
319
+ private archivedReportReader?;
320
+ /** Highest run generation already handed to the archiver, per agent id. */
321
+ private archivedGenerations;
322
+ /**
323
+ * Full run finalizers still in flight, per record. A finalizer is the spawn or
324
+ * resume promise INCLUDING its output flush and worktree cleanup. One record
325
+ * can hold several: a newer resume may settle while an older generation's
326
+ * flush is still pending, so replacing `record.promise` must not lose the
327
+ * older work. Entries are removed on either resolution branch.
328
+ */
329
+ private pendingFinalizers;
330
+ /**
331
+ * Proof that a prepareCleanup pass found a live record settled and quiescent.
332
+ * forgetCleanup only forgets records with a matching generation here, so new
333
+ * work or a stale pass can never remove a report. Bounded by live records:
334
+ * cleared with the record, on a new run, on disposal and on forget.
335
+ */
336
+ private cleanupQuiescence;
337
+ /** Acquire-side artifact barrier; see setArtifactAccessGuard. */
338
+ private artifactAccessGuard?;
339
+ /**
340
+ * Every session-instance teardown that is pending or never proved quiescence,
341
+ * plus unfinished run finalizers. Rows are lightweight plain data; unresolved
342
+ * rows are NEVER capped or dropped (their paths stay protected).
343
+ */
344
+ private teardowns;
345
+ /** One teardown identity per SDK session instance (not per session file). */
346
+ private teardownIds;
347
+ /** Sessions allocated before `onSessionCreated`, keyed by agent id. */
348
+ private allocations;
349
+ /** Readiness of each pre-ready allocation (bind/session_start settlement). */
350
+ private allocationStates;
351
+ private teardownSequence;
232
352
  private maxConcurrent;
233
353
  private maxConcurrentForeground;
234
354
  /** Base repos worktrees were created from — so dispose() can prune them all,
@@ -270,10 +390,142 @@ export declare class AgentManager {
270
390
  private runningBackground;
271
391
  /** Number of currently running foreground (blocking) agents. */
272
392
  private runningForeground;
393
+ /**
394
+ * Capacity claimed by a start that has not reached its run yet (it is still
395
+ * awaiting an async acquire guard, a worktree copy or a cwd re-check).
396
+ * `poolHasRoom` counts these, so a synchronous queue drain can never start
397
+ * more runs than the limit while earlier starts are suspended.
398
+ */
399
+ private pendingBackground;
400
+ private pendingForeground;
401
+ /**
402
+ * Pending capacity claims, keyed by the record that owns them. A cancellation
403
+ * releases the claim still pending here at once; a TRANSFERRED claim is gone
404
+ * from this map and is a running charge the run's own finalizer releases, so
405
+ * abort can never free a slot that real work still occupies. A later claim
406
+ * for the same record replaces the entry: an older continuation that settles
407
+ * afterwards releases only its own already-idempotent claim.
408
+ */
409
+ private pendingClaims;
410
+ /**
411
+ * Resume admission, claimed synchronously before the acquire guard awaits.
412
+ * A settled record can be resumed by two callers in the same tick; only the
413
+ * first may mutate its generation and terminal fields. Cleared on refusal or
414
+ * once the record is queued/running (status then provides exclusivity).
415
+ */
416
+ private resumeAdmissions;
417
+ /** Individual queued aborts already delivered completion for this generation. */
418
+ private notifiedQueuedAborts;
419
+ /**
420
+ * The parent-signal abort listener currently owned by a record, with the
421
+ * generation that attached it. A start wires its signal BEFORE the acquire
422
+ * guard can suspend, so abort()/abortAll()/dispose() must be able to detach it
423
+ * immediately: a guard that never settles must not leave the manager reachable
424
+ * from a live parent signal. One wire per record — only the current generation
425
+ * is wired, and detach is identity-aware, so a stale continuation can never
426
+ * remove a newer generation's listener.
427
+ */
428
+ private signalWires;
273
429
  constructor(onComplete?: OnAgentComplete, maxConcurrent?: number, onStart?: OnAgentStart, onCompact?: OnAgentCompact, onUsage?: OnAgentUsage);
274
430
  /** Update the max concurrent background agents limit. */
275
431
  setMaxConcurrent(n: number): void;
276
432
  getMaxConcurrent(): number;
433
+ /** Wire durable report capture; see {@link AgentReportArchiver}. */
434
+ setReportArchiver(archiver: AgentReportArchiver | undefined): void;
435
+ /** Wire the async parent-scoped archived reader injected into nested tools. */
436
+ setArchivedReportReader(reader: ArchivedReportReader | undefined): void;
437
+ /**
438
+ * Wire the acquire-side artifact barrier. The callback runs at the ACTUAL
439
+ * boundaries where a run would first touch artifacts: the real start of
440
+ * `startAgent` (before the running slot is transferred), again immediately
441
+ * before `runAgent` (after an awaited worktree copy and/or assert), at resume
442
+ * acquisition before any run bookkeeping, and at a queued resume's actual
443
+ * start. The pool capacity itself is reserved synchronously in `launch` /
444
+ * the queued start BEFORE this callback can suspend, so awaiting a guard can
445
+ * never let a queue drain oversubscribe its pool.
446
+ *
447
+ * A throw (or a rejected promise) is an ordinary startup/refusal failure: no
448
+ * model starts, no pool slot or record generation is mutated, and a fresh
449
+ * worktree copy is released. The callback owns any ownership/lock check; the
450
+ * manager never inspects the filesystem or an SDK session here.
451
+ *
452
+ * A callback that returns a promise is awaited before worktree creation, and
453
+ * again immediately before `runAgent`. A callback that returns `void` keeps
454
+ * the historical synchronous start path unchanged (no extra suspension, so a
455
+ * spawn that has room starts in the same tick).
456
+ */
457
+ setArtifactAccessGuard(guard: ArtifactAccessGuard | undefined): void;
458
+ /** Invoke the configured acquire-side barrier; original behavior when unset. */
459
+ private assertArtifactAccess;
460
+ /** Teardowns that did not prove quiescence, newest first. Cleanup keeps them leased. */
461
+ listUncertainTeardowns(): UncertainTeardown[];
462
+ hasUncertainTeardowns(): boolean;
463
+ /**
464
+ * Every agent whose work is not quiescent. Includes running/queued records,
465
+ * startup work (an awaited worktree copy), in-flight run finalizers (output
466
+ * flush and worktree cleanup) and older-generation finalizers that outlived a
467
+ * newer settled run. Cleanup callers combine this with
468
+ * {@link listUncertainTeardowns} for evicted-record protection; nothing here
469
+ * aborts, evicts or notifies anything.
470
+ */
471
+ getBusyAgentIds(): string[];
472
+ /**
473
+ * Decide which requested reports and session files may be deleted, and close
474
+ * the settled SDK sessions that make them quiescent.
475
+ *
476
+ * Synchronous-before-await guarantees: the readiness recheck, the session
477
+ * detach and the bounded teardown registration all happen before the first
478
+ * `await`. A resume therefore sees `record.session === undefined` for every
479
+ * session this pass is closing, and work that starts during the await is
480
+ * refused by the second readiness check rather than reported ready.
481
+ *
482
+ * Never aborts/stops running work, never evicts records, never disposes or
483
+ * clears the manager, and never consumes a result or fires a notification.
484
+ * A settled record stays in the manager; {@link forgetCleanup} removes it only
485
+ * after the backend actually deleted its files.
486
+ */
487
+ prepareCleanup(agentIds: readonly string[], sessionFiles: readonly string[]): Promise<AgentCleanupPreparation>;
488
+ /**
489
+ * Drop manager-side traces of cleanup items the backend ACTUALLY deleted.
490
+ *
491
+ * A live record is forgotten only when a prepareCleanup pass proved it
492
+ * quiescent, it is still on that same run generation, its session was
493
+ * detached by that pass, and nothing is busy or uncertain now. Nothing is
494
+ * tombstoned and no teardown is started: the report was deliberately deleted
495
+ * and must not resurrect through a mention or a late archive.
496
+ *
497
+ * Tombstones are dropped by the actual deleted agent id or the actual deleted
498
+ * session file, and a surviving record's session pointer is cleared only for
499
+ * a path that was actually deleted. Unrelated records, tombstones and failed
500
+ * deletions are never touched.
501
+ */
502
+ forgetCleanup(deletedAgentIds: readonly string[], deletedSessionFiles: readonly string[]): void;
503
+ /** Why a live record is not quiescent, or undefined when it is settled and idle. */
504
+ private busyReason;
505
+ /** Explicit reason an unresolved teardown row blocks deletion. */
506
+ private uncertaintyReason;
507
+ private cleanupGuardSnapshot;
508
+ private cleanupAgentRefusal;
509
+ private cleanupPathRefusal;
510
+ /**
511
+ * Refuse readiness for an attachment that appeared while the pass awaited.
512
+ *
513
+ * The pre-check deliberately allows settled attached sessions so this pass can
514
+ * detach and tear them down. That proof covers only the attachments in the
515
+ * initial snapshot: a record that attaches the same report/history during the
516
+ * await was never detached by this pass and stays resumable. Refuse it; the
517
+ * newly attached handle is not closed.
518
+ */
519
+ private attachedDuringCleanupRefusal;
520
+ /**
521
+ * Detach a record's session synchronously and attach it to the pass's unique
522
+ * teardown job. The detach MUST precede the first await and the SDK teardown:
523
+ * a resume during shutdown then has no session to reopen.
524
+ */
525
+ private attachCleanupTeardown;
526
+ private teardownRefusal;
527
+ private teardownRefusalForAgent;
528
+ private teardownRefusalForSessionFile;
277
529
  /** Update the max concurrent foreground (blocking) agents limit. 0 = unlimited. */
278
530
  setMaxConcurrentForeground(n: number): void;
279
531
  getMaxConcurrentForeground(): number;
@@ -291,6 +543,62 @@ export declare class AgentManager {
291
543
  */
292
544
  private poolFor;
293
545
  private poolHasRoom;
546
+ /**
547
+ * Claim one slot for a start that is about to await work, synchronously.
548
+ * `transfer()` moves the claim to the running counter before the run is
549
+ * launched; `releasePending()` gives it back when acquisition is refused or
550
+ * the record was superseded. Repeated calls are no-ops, so a refusal that
551
+ * unwinds through `launch` cannot decrement twice.
552
+ *
553
+ * The claim is associated with `record` while pending so `abort()`/`abortAll()`
554
+ * can release it without waiting for the suspended continuation.
555
+ */
556
+ private reservePoolSlot;
557
+ /**
558
+ * Free a record's still-PENDING capacity claim, immediately and exactly once.
559
+ * A transferred claim is absent from the map, so a real run's charge is never
560
+ * touched here — that is released only by its finalizer.
561
+ *
562
+ * `drain` is false while a bulk cancellation is still marking entries: freeing
563
+ * one entry's capacity must not start another entry that has not been canceled
564
+ * yet. Individual cancellation drains as soon as the record is stopped.
565
+ */
566
+ private releasePendingClaim;
567
+ /**
568
+ * The pending claim a record holds RIGHT NOW, captured before anything the
569
+ * caller is about to do can re-enter the manager. abort() hands this exact
570
+ * reservation back afterwards: its completion callback is free to resume the
571
+ * same record, and that newer generation installs its OWN claim in the map.
572
+ * Freeing by lookup at the tail would free that one instead — a running charge
573
+ * the new generation still owns, whose transfer then no-ops and whose
574
+ * finalizer underflows the pool counter (oversubscription).
575
+ */
576
+ private capturePendingClaim;
577
+ /**
578
+ * Release the exact claim {@link capturePendingClaim} captured. The map entry
579
+ * is forgotten only if it still names that object, and a claim that already
580
+ * transferred or was already released is an idempotent no-op, so a transferred
581
+ * running charge is never freed here.
582
+ */
583
+ private releaseCapturedClaim;
584
+ /**
585
+ * Attach the parent-signal abort listener owned by `generation` and register
586
+ * it where abort()/abortAll()/dispose() can detach it immediately. Only one
587
+ * wire exists per record: an older generation's listener (a queued start's, or
588
+ * the previous run's) is detached first, so a late abort of THAT signal can
589
+ * never stop this run. A detached start (`undefined`) stays detached, and an
590
+ * already-aborted signal is left to its caller's explicit `abort()` call.
591
+ */
592
+ private attachSignalWire;
593
+ /**
594
+ * Detach one CAPTURED wire. The registry entry is forgotten only if it still
595
+ * names that wire, and `detach` is idempotent, so a stale continuation — or an
596
+ * old abort resuming after its callbacks — cannot remove a newer generation's
597
+ * listener.
598
+ */
599
+ private detachSignalWire;
600
+ /** Detach whatever parent-signal listener the record's current generation owns. */
601
+ private releaseSignalWire;
294
602
  /**
295
603
  * Spawn an agent and return its ID immediately (for background use).
296
604
  * If the concurrency limit is reached, the agent is queued.
@@ -311,24 +619,25 @@ export declare class AgentManager {
311
619
  * an aborted signal, so a `spawnAndWait` on it would wait forever — pi has no
312
620
  * tool-execution timeout to bail it out.
313
621
  *
314
- * The listener is left in place when the agent starts. `startAgent` adds its
315
- * own, so both fire on a later abort, but `abort()` on an already-stopped
316
- * record is a no-op — so detaching would only be tidiness, and tidiness the
317
- * `abortAll`/`dispose` paths could not offer anyway.
622
+ * The wire is generation-owned and registered for immediate detach: the start
623
+ * that leaves the queue REPLACES it with its own run wire, and
624
+ * abort()/abortAll()/dispose() detach it at once — so this listener never
625
+ * outlives the generation that armed it, and a late abort of the queue signal
626
+ * cannot stop a later resumed generation.
318
627
  */
319
628
  private armQueuedAbort;
320
629
  /**
321
630
  * Kick off an agent's startup and register it under `startups`. The returned
322
631
  * promise never rejects — the failure is delivered through `awaitStartup`,
323
- * and to the record.
632
+ * and to the record. Background startup failures use ordinary completion;
633
+ * callers delivering the failure inline consume it themselves.
324
634
  *
325
635
  * @param queuedPool - The pool this start was QUEUED on, or undefined for an
326
636
  * immediate start. A queue drain can be minutes after `spawn()` returned,
327
637
  * and nobody is awaiting `awaitStartup` by then, so a failure has to live
328
638
  * on the record as status "error" — what drainQueue did when the throw was
329
- * still synchronous. An immediate start instead drops the record, exactly
330
- * as the throw out of `spawn()` did: no orphan in `listAgents()`, and the
331
- * handle goes back.
639
+ * still synchronous. Immediate foreground failures drop the unreturned
640
+ * record; detached callers keep a retrievable failure and ordinary wakeup.
332
641
  */
333
642
  private launch;
334
643
  /**
@@ -337,10 +646,18 @@ export declare class AgentManager {
337
646
  * repo copy became async. Resolves immediately for an agent that is already
338
647
  * running, still queued, or unknown — so callers can await it unconditionally.
339
648
  *
340
- * Call it in the same tick as the `spawn()` it belongs to: a failed startup
341
- * takes its record (and this entry) with it, exactly as the throw did.
649
+ * Call it in the same tick as the `spawn()` it belongs to: a settled startup
650
+ * removes this promise entry. Detached failures remain on their records.
342
651
  */
343
652
  awaitStartup(id: string): Promise<void>;
653
+ /**
654
+ * Whether a start that suspended on an acquire guard still owns the record.
655
+ * A stop, dispose, eviction or newer run during the await must not create a
656
+ * worktree, child session or model call afterwards.
657
+ */
658
+ private startIsCurrent;
659
+ /** Same check once the start has claimed "running" and begun worktree work. */
660
+ private runIsCurrent;
344
661
  /** Actually start an agent (called immediately or from queue drain). */
345
662
  private startAgent;
346
663
  /**
@@ -362,6 +679,64 @@ export declare class AgentManager {
362
679
  * the release disagree with the acquire.
363
680
  */
364
681
  private settleRun;
682
+ /**
683
+ * Hand one settled generation to the durable-report archiver exactly once.
684
+ *
685
+ * Every terminal path calls this — fresh runs, foreground/background resumes,
686
+ * queued cancellations, startup failures and the dispose sweep. Generation
687
+ * dedupe matters because a run can be stopped while queued and then swept by
688
+ * `dispose`: the first snapshot is the truthful one. A deadline FALLBACK may
689
+ * still be replaced by the real same-generation finalizer (never the reverse),
690
+ * so a run that settles just after the bounded window is not lost forever.
691
+ */
692
+ private archiveTerminal;
693
+ /**
694
+ * Track a full run finalizer (output flush and worktree cleanup included) as
695
+ * pending work for this record. Removed on either resolution branch; a record
696
+ * can hold more than one because a newer generation settles first and
697
+ * overwrites `record.promise` while the older flush is still in flight.
698
+ */
699
+ private trackPendingFinalizer;
700
+ private identityFromRecord;
701
+ /**
702
+ * One protection identity per SDK session INSTANCE. The same session file can
703
+ * be reopened as a different instance (A timed out, B later succeeds): B's
704
+ * completion must not delete A's still-unresolved protection row.
705
+ */
706
+ private ensureSessionTeardown;
707
+ private applyTeardownOutcome;
708
+ /**
709
+ * Register protection synchronously, then start the bounded shutdown. The row
710
+ * exists BEFORE the first await: an immediate dispose after eviction sees the
711
+ * pending promise and cannot report `completed` for an unresolved handler.
712
+ */
713
+ private startSessionTeardown;
714
+ private trackSessionShutdown;
715
+ /** Record the allocated instance before binding; no ready announcement yet. */
716
+ private noteSessionAllocated;
717
+ /** Bind/session_start settled (successfully, or its failure teardown ran). */
718
+ private settleAllocation;
719
+ /** The session is now a live, addressable record; teardown is not in flight. */
720
+ private markSessionReady;
721
+ /** Bind-failure (or equivalent partial startup) outcome handed back by runner. */
722
+ private noteSessionTeardown;
723
+ private releaseAllocation;
724
+ /** Protection row for a run/finalizer that outlived the shutdown deadline. */
725
+ private recordRunUncertainty;
726
+ /**
727
+ * Release protection for exactly the run generation whose COMPLETE disposal
728
+ * aggregate (including every generation's output flush) settled. Called only
729
+ * by dispose/reconcileLateFinalizer, never by an individual run finalizer: a
730
+ * newer generation must not release an older generation's pending flush.
731
+ */
732
+ private clearRunUncertainty;
733
+ /**
734
+ * A captured startup/run finalizer that outlived dispose's sweep still owes a
735
+ * real report and the release of its provisional run protection. This runs
736
+ * independently of map membership and never calls settleRun/callbacks or
737
+ * releases a pool slot again.
738
+ */
739
+ private reconcileLateFinalizer;
365
740
  /**
366
741
  * Stop the nested children a settled parent owns. Nested records are hidden
367
742
  * from the UI and only their owner can consume them, so a child outliving its
@@ -402,6 +777,16 @@ export declare class AgentManager {
402
777
  * Resume an existing agent session with a new prompt.
403
778
  */
404
779
  resume(id: string, prompt: string, signal?: AbortSignal, options?: ResumeOptions): Promise<AgentRecord | undefined>;
780
+ /**
781
+ * A resume that suspended on its acquire guard still owns the record only if
782
+ * nothing terminal happened while it waited. Kept separate from the queued
783
+ * variant: a queued resume legitimately sits in "queued" while admitting.
784
+ */
785
+ private resumeAdmissionIsCurrent;
786
+ /** Same revalidation for a resume whose queued start just awaited its guard. */
787
+ private queuedResumeIsCurrent;
788
+ /** The queued-start refusal path: this generation is terminal, no run began. */
789
+ private failQueuedResume;
405
790
  /**
406
791
  * Start a background resume run: detached, settling and notifying like
407
792
  * startAgent's background path. Invoked immediately, or from drainQueue when
@@ -426,9 +811,9 @@ export declare class AgentManager {
426
811
  private takenHandles;
427
812
  /**
428
813
  * Resolve an `@name` from the prompt. Matches a top-level agent's handle
429
- * case-insensitively, preferring one that can still be steered and otherwise
430
- * the most recently started (which is the one a resume should continue), then
431
- * falls back to an exact agent id so `@<agentId>` works too.
814
+ * case-insensitively, preferring active work, then the newest usable session.
815
+ * A failed startup cannot shadow a saved conversation. Exact ids still name
816
+ * their own record, including a retained startup failure.
432
817
  */
433
818
  resolveMention(name: string): MentionResolution | undefined;
434
819
  /**
@@ -443,6 +828,8 @@ export declare class AgentManager {
443
828
  dropTombstone(handle: string): void;
444
829
  /** Evicted agents whose conversation can still be reopened, newest first. */
445
830
  listTombstones(): AgentTombstone[];
831
+ /** Actual pool queue membership, excluding a start suspended on its guard. */
832
+ isQueued(id: string): boolean;
446
833
  listAgents(): AgentRecord[];
447
834
  abort(id: string): boolean;
448
835
  /** Dispose a record's session and remove it from the map. */
@@ -473,7 +860,7 @@ export declare class AgentManager {
473
860
  * cannot be reached through a stored spawn argument at shutdown. Omitting
474
861
  * it (tests, teardown of a manager that never spawned) skips the prune.
475
862
  */
476
- dispose(pi?: ExtensionAPI): Promise<void>;
863
+ dispose(pi?: ExtensionAPI): Promise<AgentManagerShutdown>;
477
864
  }
478
865
  /**
479
866
  * Whether a child session will still consume a steering message. A session