@timmyjl12/pi-subagents 0.20.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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 +3612 -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 +4130 -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
@@ -8,6 +8,7 @@ import { appendFileSync, chmodSync, mkdirSync, writeFileSync } from "node:fs";
8
8
  import { appendFile } from "node:fs/promises";
9
9
  import { tmpdir } from "node:os";
10
10
  import { join } from "node:path";
11
+ import { setImmediate as yieldToEventLoop } from "node:timers/promises";
11
12
  import { logSubagentIssue } from "./error-log.js";
12
13
  import { assistantDiagnosticContext, sanitizeDiagnosticText } from "./output-diagnostics.js";
13
14
  /**
@@ -90,21 +91,102 @@ export function writeInitialEntry(path, agentId, prompt, cwd) {
90
91
  writeFileSync(path, JSON.stringify(entry) + "\n", "utf-8");
91
92
  }
92
93
  /**
93
- * Serialized write chains for transcript files: at most one in-flight append
94
- * per file. A drain coalesces everything queued while it writes — a burst of
95
- * finalized messages costs one append syscall per batch, not per message — and
96
- * a resume subscribing a second stream to the same transcript chains after the
97
- * previous stream's pending writes instead of interleaving with them.
94
+ * Lossless per-path output queues. Finalized lines are stringified at event
95
+ * time (snapshot semantics below) and appended by exactly one drain per file,
96
+ * so a resume subscribing a second stream to the same transcript queues behind
97
+ * the previous stream instead of interleaving. `pendingBytes` counts both
98
+ * queued and in-flight serialized bytes; appends are sliced into bounded
99
+ * batches, but a single oversized record is never split.
98
100
  */
99
- const writeChains = new Map();
100
- function chainWrite(path, run) {
101
- const chained = (writeChains.get(path) ?? Promise.resolve()).then(run);
102
- writeChains.set(path, chained);
103
- void chained.finally(() => {
104
- if (writeChains.get(path) === chained)
105
- writeChains.delete(path);
106
- });
107
- return chained;
101
+ const OUTPUT_HIGH_WATER_BYTES = 1024 * 1024;
102
+ const OUTPUT_BATCH_BYTES = 256 * 1024;
103
+ const OUTPUT_BATCH_RECORDS = 64;
104
+ const CONSUMED_LINE = { text: "", bytes: 0 };
105
+ const outputQueues = new Map();
106
+ function resolveWaiters(queue) {
107
+ for (const waiter of [...queue.waiters]) {
108
+ if (queue.pendingBytes >= waiter.below)
109
+ continue;
110
+ queue.waiters.delete(waiter);
111
+ waiter.resolve();
112
+ }
113
+ }
114
+ /** Wait until a path's accepted output falls below `below` bytes. No polling. */
115
+ function waitForOutput(path, below) {
116
+ const queue = outputQueues.get(path);
117
+ if (!queue || queue.pendingBytes < below)
118
+ return Promise.resolve();
119
+ return new Promise((resolve) => { queue.waiters.add({ below, resolve }); });
120
+ }
121
+ /**
122
+ * Write accepted records one batch at a time. Each append chunk is at most 256
123
+ * KiB or 64 records; the only exception is one larger indivisible record,
124
+ * which is written whole. Accounting is decremented in `finally`, so a failed
125
+ * best-effort write cannot strand pending bytes or waiters.
126
+ */
127
+ function drainQueue(path, queue) {
128
+ if (queue.draining)
129
+ return;
130
+ queue.draining = true;
131
+ void (async () => {
132
+ try {
133
+ while (queue.head < queue.lines.length) {
134
+ let records = 0;
135
+ let bytes = 0;
136
+ while (records < queue.lines.length - queue.head) {
137
+ const next = queue.lines[queue.head + records];
138
+ if (records > 0
139
+ && (records >= OUTPUT_BATCH_RECORDS || bytes + next.bytes > OUTPUT_BATCH_BYTES))
140
+ break;
141
+ bytes += next.bytes;
142
+ records += 1;
143
+ }
144
+ const end = queue.head + records;
145
+ const chunk = queue.lines.slice(queue.head, end);
146
+ // Release consumed payloads immediately; a long-lived busy path must not
147
+ // retain written strings. Compact geometrically instead of shifting the
148
+ // whole remaining queue for every bounded append (quadratic copying).
149
+ for (let index = queue.head; index < end; index++)
150
+ queue.lines[index] = CONSUMED_LINE;
151
+ queue.head = end;
152
+ if (queue.head === queue.lines.length) {
153
+ queue.lines = [];
154
+ queue.head = 0;
155
+ }
156
+ else if (queue.head >= OUTPUT_BATCH_RECORDS && queue.head * 2 >= queue.lines.length) {
157
+ queue.lines = queue.lines.slice(queue.head);
158
+ queue.head = 0;
159
+ }
160
+ try {
161
+ await appendFile(path, chunk.map(line => line.text).join(""), "utf-8");
162
+ }
163
+ catch { /* best-effort file output; never write raw errors into the TUI */ }
164
+ finally {
165
+ queue.pendingBytes -= bytes;
166
+ resolveWaiters(queue);
167
+ }
168
+ }
169
+ }
170
+ finally {
171
+ queue.draining = false;
172
+ if (queue.pendingBytes === 0 && queue.head === queue.lines.length) {
173
+ if (outputQueues.get(path) === queue)
174
+ outputQueues.delete(path);
175
+ resolveWaiters(queue);
176
+ }
177
+ }
178
+ })();
179
+ }
180
+ function enqueueOutput(path, text) {
181
+ let queue = outputQueues.get(path);
182
+ if (!queue) {
183
+ queue = { lines: [], head: 0, pendingBytes: 0, draining: false, waiters: new Set() };
184
+ outputQueues.set(path, queue);
185
+ }
186
+ const bytes = Buffer.byteLength(text, "utf-8");
187
+ queue.lines.push({ text, bytes });
188
+ queue.pendingBytes += bytes;
189
+ drainQueue(path, queue);
108
190
  }
109
191
  /**
110
192
  * Wait until every queued write to one transcript file has landed. Resolves
@@ -112,15 +194,24 @@ function chainWrite(path, run) {
112
194
  * so a caller can await the final flush.
113
195
  */
114
196
  export function drainOutputFile(path) {
115
- return writeChains.get(path) ?? Promise.resolve();
197
+ return waitForOutput(path, 1);
198
+ }
199
+ /** Diagnostic only: serialized bytes accepted for a path but not yet written. */
200
+ export function pendingOutputBytes(path) {
201
+ return outputQueues.get(path)?.pendingBytes ?? 0;
116
202
  }
117
203
  /**
118
204
  * Persist finalized events before retries can remove them from session.messages.
119
205
  * Snapshot flushes also preserve eventless SDK additions (e.g. bashExecution).
120
206
  * Lines are stringified at event time but written through an async per-file
121
- * queue (see chainWrite), so message-sized JSON work never blocks the loop.
122
- * Returns an idempotent final flush/unsubscribe that resolves once the flushed
123
- * writes are on disk; never changes retry policy.
207
+ * queue (see drainQueue). JSON serialization remains synchronous; disk waits
208
+ * and bounded producer checkpoints are asynchronous.
209
+ * A real Agent session also gets a producer listener registered after the
210
+ * session observer: it waits below the high-water mark at message_end and
211
+ * forces a drain at turn/run settlement, so slow disk stops the producer
212
+ * instead of growing an unbounded in-memory queue. Returns an idempotent final
213
+ * flush/unsubscribe that resolves once the flushed writes are on disk; never
214
+ * changes retry policy.
124
215
  */
125
216
  export function streamToOutputFile(session, path, agentId, cwd, startIndex,
126
217
  // Best-effort label for the central error log. Only call sites that know the
@@ -137,26 +228,10 @@ agentType) {
137
228
  let skipInitialUser = startIndex === undefined && !initial.some(msg => msg.role === "user");
138
229
  let lastAssistant;
139
230
  let closed = false;
140
- // Queued lines are stringified at event time — messages are live SDK state,
141
- // and a write must snapshot the finalized message, not a later mutation. The
142
- // drain coalesces everything queued while a write is in flight.
143
- let batch = [];
144
- let draining = false;
145
- const drain = async () => {
146
- try {
147
- while (batch.length > 0) {
148
- const chunk = batch;
149
- batch = [];
150
- try {
151
- await appendFile(path, chunk.join(""), "utf-8");
152
- }
153
- catch { /* best-effort file output; never write raw errors into the TUI */ }
154
- }
155
- }
156
- finally {
157
- draining = false;
158
- }
159
- };
231
+ // Lines are stringified at event time — messages are live SDK state, and a
232
+ // write must snapshot the finalized message, not a later mutation. enqueue
233
+ // adds the completed line to the shared per-path queue (one append in flight,
234
+ // bounded batches).
160
235
  const append = (fields) => {
161
236
  let line;
162
237
  try {
@@ -167,11 +242,7 @@ agentType) {
167
242
  catch { /* best-effort file output; never write raw errors into the TUI */
168
243
  return;
169
244
  }
170
- batch.push(line);
171
- if (!draining) {
172
- draining = true;
173
- void chainWrite(path, drain);
174
- }
245
+ enqueueOutput(path, line);
175
246
  };
176
247
  const capture = (msg) => {
177
248
  if (seen.has(msg) || (msg.role === "assistant" && msg.stopReason === "pending"))
@@ -205,6 +276,10 @@ agentType) {
205
276
  };
206
277
  const flush = () => { for (const msg of session.messages)
207
278
  capture(msg); };
279
+ // Observation snapshots happen synchronously in the session listener, before
280
+ // the producer listener below is registered. AgentSession installs its own
281
+ // agent listener in the constructor, so this is also the public observer order
282
+ // Agent.processEvents awaits.
208
283
  const unsubscribe = session.subscribe((event) => {
209
284
  if (closed)
210
285
  return;
@@ -237,11 +312,39 @@ agentType) {
237
312
  seen.add(msg);
238
313
  }
239
314
  });
315
+ // Attach after the observation subscription so capture (snapshot) precedes
316
+ // pressure. The producer hook is optional so legacy structural session
317
+ // doubles keep working; only the real SDK session supplies `session.agent`.
318
+ const producer = session.agent;
319
+ let finalizedSinceYield = 0;
320
+ const unsubscribeProducer = producer && typeof producer.subscribe === "function"
321
+ ? producer.subscribe(async (event) => {
322
+ if (closed)
323
+ return;
324
+ if (event.type === "message_end") {
325
+ if (pendingOutputBytes(path) >= OUTPUT_HIGH_WATER_BYTES) {
326
+ await waitForOutput(path, OUTPUT_HIGH_WATER_BYTES);
327
+ finalizedSinceYield = 0;
328
+ }
329
+ else if (++finalizedSinceYield >= OUTPUT_BATCH_RECORDS) {
330
+ // Awaiting already-resolved promises is not an event-loop yield.
331
+ // Small records also need periodic macrotask progress below HWM.
332
+ finalizedSinceYield = 0;
333
+ await yieldToEventLoop();
334
+ }
335
+ }
336
+ else if (event.type === "turn_end" || event.type === "agent_end") {
337
+ await drainOutputFile(path);
338
+ finalizedSinceYield = 0;
339
+ }
340
+ })
341
+ : undefined;
240
342
  return () => {
241
343
  if (closed)
242
344
  return drainOutputFile(path);
243
345
  closed = true;
244
346
  unsubscribe();
347
+ unsubscribeProducer?.();
245
348
  flush();
246
349
  return drainOutputFile(path);
247
350
  };
package/dist/prompts.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * prompts.ts — System prompt builder for agents.
3
3
  */
4
- import type { AgentConfig, EnvInfo } from "./types.js";
4
+ import type { AgentConfig, EnvInfo } from "./types.ts";
5
5
  /** Extra sections to inject into the system prompt (memory, skills, etc.). */
6
6
  export interface PromptExtras {
7
7
  /** Persistent memory content to inject (first 200 lines of MEMORY.md + instructions). */
@@ -1,5 +1,5 @@
1
1
  import type { AgentSession, EventBus, ExtensionError } from "@earendil-works/pi-coding-agent";
2
- import { type StandalonePolicy } from "./standalone-fallback.js";
2
+ import { type StandalonePolicy } from "./standalone-fallback.ts";
3
3
  export declare const RECOVERY_CHANNEL = "pi-fallback-chains:recovery";
4
4
  type RecoveryPhase = "idle" | "pending" | "switching" | "compacting" | "retrying" | "settled" | "cancelled" | "failed";
5
5
  export interface RecoverySnapshot {
@@ -0,0 +1,204 @@
1
+ /**
2
+ * report-cleanup.ts — read-only inventory, then explicitly confirmed file removal.
3
+ *
4
+ * This module is the backend half of `/subagents cleanup`: it never renders UI,
5
+ * never recursively deletes a directory and never uses `force`. A plan is an
6
+ * immutable snapshot of candidate paths, sizes, mtimes, hashes and read states.
7
+ * Apply is the only mutating half, and it revalidates every candidate — roots,
8
+ * ownership, symlink ancestors, file identity, root generation, dynamic live
9
+ * state and selected shared paths — immediately before each unlink.
10
+ *
11
+ * Ordering is deliberate:
12
+ * 1. cleanup acquires the exclusive per-root lock and rechecks foreign leases;
13
+ * 2. preparation (the integration owner's explicit teardown) returns ready and
14
+ * blocked sets; uncertain items are never unlinked;
15
+ * 3. live state is refreshed again, then a report body is replaced by a
16
+ * deletion receipt BEFORE its artifacts are unlinked, so parent-history or
17
+ * transcript re-import cannot resurrect it;
18
+ * 4. only unchanged, proven-owned regular files are unlinked one by one;
19
+ * 5. root session files and external/saved workflow sources are never candidates.
20
+ */
21
+ import { type CleanupScope, type ReportSnapshot, type ReportStore } from "./report-store.ts";
22
+ export type CleanupFileKind = "report-entry" | "report-output" | "workflow-generated" | "workflow-registration" | "child-session" | "legacy-output" | "diagnostics-log" | "root-metadata";
23
+ export type CleanupReadState = "read" | "unread" | "unknown";
24
+ /** What the live integration layer knows at the moment of the call. */
25
+ export interface CleanupLiveState {
26
+ /** Running/queued/starting/settling agent ids — never candidates. */
27
+ activeAgentIds?: Iterable<string>;
28
+ /** Running/paused workflow ids — never candidates. */
29
+ activeWorkflowIds?: Iterable<string>;
30
+ /** Exact transcript/output/shared paths referenced by active work. */
31
+ protectedPaths?: Iterable<string>;
32
+ /** Live results the parent has not consumed yet (`resultConsumed !== true`). */
33
+ unreadAgentIds?: Iterable<string>;
34
+ /** A protected writer still owns the shared diagnostics aggregate. */
35
+ diagnosticsBusy?: boolean;
36
+ /**
37
+ * Own roots with live SDK work (busy/startup/finalizer/uncertain) or a
38
+ * resumable owner dependency. Their whole root is refused: no lock is taken
39
+ * and no artifact of it is touched, so running/queued work keeps writing.
40
+ */
41
+ protectedRootSessionIds?: Iterable<string>;
42
+ }
43
+ /** Refreshed after teardown and at every final mutation boundary, including retries. */
44
+ export type CleanupLiveStateGetter = () => CleanupLiveState | Promise<CleanupLiveState>;
45
+ export interface CleanupFileInventory {
46
+ path: string;
47
+ kind: CleanupFileKind;
48
+ rootSessionId: string;
49
+ size: number;
50
+ mtimeMs: number;
51
+ fingerprint: string;
52
+ readState: CleanupReadState;
53
+ legacy: boolean;
54
+ shared: boolean;
55
+ agentId?: string;
56
+ workflowId?: string;
57
+ /** Registered child session path, present for `child-session` candidates. */
58
+ sessionFile?: string;
59
+ entryGeneration?: number;
60
+ workflowUpdatedAt?: number;
61
+ }
62
+ export interface CleanupSkip {
63
+ path?: string;
64
+ kind?: CleanupFileKind;
65
+ rootSessionId?: string;
66
+ agentId?: string;
67
+ workflowId?: string;
68
+ reason: string;
69
+ legacy?: boolean;
70
+ }
71
+ export interface CleanupPlanCounts {
72
+ files: number;
73
+ bytes: number;
74
+ reports: number;
75
+ legacy: number;
76
+ taskOutputs: number;
77
+ workflowFiles: number;
78
+ childSessions: number;
79
+ diagnostics: number;
80
+ rootMetadata: number;
81
+ unread: number;
82
+ unknownReadState: number;
83
+ }
84
+ export interface CleanupRootFingerprint {
85
+ rootSessionId: string;
86
+ generation: number;
87
+ rootSessionFile?: string;
88
+ }
89
+ export interface CleanupPlan {
90
+ planId: string;
91
+ scope: CleanupScope;
92
+ createdAt: number;
93
+ roots: readonly CleanupRootFingerprint[];
94
+ files: readonly CleanupFileInventory[];
95
+ skipped: readonly CleanupSkip[];
96
+ counts: CleanupPlanCounts;
97
+ agentIds: readonly string[];
98
+ sessionFiles: readonly string[];
99
+ /**
100
+ * Set when the global main-session inventory was incomplete at preview. Apply
101
+ * refuses identity-sensitive deletions under the same condition.
102
+ */
103
+ identityUncertainty?: string;
104
+ }
105
+ export interface CleanupPlanOptions {
106
+ /**
107
+ * Add legacy `.output` candidates. Even then they are only eligible for
108
+ * deletion after `confirmedLegacy` proves older unleased instances are closed.
109
+ */
110
+ includeLegacy?: boolean;
111
+ /** Read-only session preview root; apply continues to use the bound store. */
112
+ previewRootSessionId?: string;
113
+ }
114
+ export interface CleanupPrepareRequest {
115
+ scope: CleanupScope;
116
+ agentIds: readonly string[];
117
+ sessionFiles: readonly string[];
118
+ rootSessionIds: readonly string[];
119
+ }
120
+ /**
121
+ * Explicit teardown result from the integration layer. Omitted ready sets mean
122
+ * "not proven ready" for the resource class they cover (fail closed).
123
+ */
124
+ export interface CleanupPreparation {
125
+ readyAgentIds?: readonly string[];
126
+ blockedAgentIds?: Readonly<Record<string, string>>;
127
+ readySessionFiles?: readonly string[];
128
+ blockedSessionFiles?: Readonly<Record<string, string>>;
129
+ readyRootSessionIds?: readonly string[];
130
+ blockedRootSessionIds?: Readonly<Record<string, string>>;
131
+ }
132
+ export type CleanupPrepare = (request: CleanupPrepareRequest) => Promise<CleanupPreparation> | CleanupPreparation;
133
+ export interface CleanupApplyOptions {
134
+ confirmed: boolean;
135
+ /** Extra user confirmation that older unleased pi instances are closed. */
136
+ confirmedLegacy?: boolean;
137
+ liveStateGetter: CleanupLiveStateGetter;
138
+ /** Successful teardown/ready-blocked handoff. Uncertain items stay protected. */
139
+ prepare?: CleanupPrepare;
140
+ }
141
+ export interface CleanupDeletedItem {
142
+ path: string;
143
+ kind: CleanupFileKind;
144
+ bytes: number;
145
+ readState: CleanupReadState;
146
+ rootSessionId?: string;
147
+ agentId?: string;
148
+ workflowId?: string;
149
+ }
150
+ export interface CleanupFailure {
151
+ path?: string;
152
+ kind?: CleanupFileKind;
153
+ agentId?: string;
154
+ workflowId?: string;
155
+ reason: string;
156
+ }
157
+ export interface CleanupResult {
158
+ scope: CleanupScope;
159
+ deleted: CleanupDeletedItem[];
160
+ failed: CleanupFailure[];
161
+ skipped: CleanupSkip[];
162
+ deletedAgentIds: string[];
163
+ bytesDeleted: number;
164
+ }
165
+ /**
166
+ * A rejected apply that may still have mutated the disk. `result` is the exact
167
+ * partial progress of the rejecting apply call (never a re-plan or a guess), so
168
+ * the caller can forget/report the proven deletions before releasing its own
169
+ * barriers. Intentional refusals and normal failures are ordinary results.
170
+ */
171
+ export declare class CleanupApplyError extends Error {
172
+ readonly result: CleanupResult;
173
+ constructor(message: string, result: CleanupResult, options?: {
174
+ cause?: unknown;
175
+ });
176
+ }
177
+ /**
178
+ * Read-only inventory. No file is changed, no directory is created and no lock
179
+ * is acquired; the caller may render counts and cancel without side effects.
180
+ */
181
+ export declare function planCleanup(store: ReportStore, scope: CleanupScope, liveStateGetter: CleanupLiveStateGetter, options?: CleanupPlanOptions): Promise<CleanupPlan>;
182
+ /**
183
+ * Apply a prior preview. Anything not explicitly confirmed is skipped without a
184
+ * mutation; all dynamic uncertainty is reported, never forced.
185
+ */
186
+ export declare function applyCleanup(store: ReportStore, plan: CleanupPlan, options: CleanupApplyOptions): Promise<CleanupResult>;
187
+ /** Counts for a merged or partitioned preview, using the inventory's same rules. */
188
+ export declare function cleanupCounts(files: readonly CleanupFileInventory[]): CleanupPlanCounts;
189
+ /** True when a plan contains no mutation candidates at all. */
190
+ export declare function isCleanupPlanEmpty(plan: CleanupPlan): boolean;
191
+ /** Read-state labels the UI should show verbatim; archived "unknown" is never "read". */
192
+ export declare function cleanupReadStateLabel(state: CleanupReadState): string;
193
+ /** A marker type re-exported for integration code that keys candidate lists. */
194
+ export type CleanupCandidateIds = {
195
+ agentIds: readonly string[];
196
+ sessionFiles: readonly string[];
197
+ };
198
+ export declare function cleanupCandidateIds(plan: CleanupPlan): CleanupCandidateIds;
199
+ /** Guard used by callers before treating an exact id as canonical. */
200
+ export declare function isCleanupAgentId(value: string): boolean;
201
+ /** Exported only so fixture builders share the same normalization as apply. */
202
+ export declare function cleanupPathKey(path: string): string;
203
+ /** A report snapshot's provenance labels are part of the cleanup/read contract. */
204
+ export type CleanupRecoveredReport = ReportSnapshot;