@timmyjl12/pi-subagents 0.0.0-stage → 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 (244) hide show
  1. package/CHANGELOG.md +862 -0
  2. package/CONTRIBUTING.md +72 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1125 -3
  5. package/SECURITY.md +97 -0
  6. package/dist/abortable.d.ts +12 -0
  7. package/dist/abortable.js +42 -0
  8. package/dist/active-agents-prompt.d.ts +40 -0
  9. package/dist/active-agents-prompt.js +98 -0
  10. package/dist/advisor-status.d.ts +16 -0
  11. package/dist/advisor-status.js +74 -0
  12. package/dist/agent-color.d.ts +35 -0
  13. package/dist/agent-color.js +131 -0
  14. package/dist/agent-file-toggle.d.ts +125 -0
  15. package/dist/agent-file-toggle.js +264 -0
  16. package/dist/agent-manager.d.ts +872 -0
  17. package/dist/agent-manager.js +2910 -0
  18. package/dist/agent-runner.d.ts +358 -0
  19. package/dist/agent-runner.js +1219 -0
  20. package/dist/agent-types.d.ts +142 -0
  21. package/dist/agent-types.js +315 -0
  22. package/dist/awaited-result.d.ts +37 -0
  23. package/dist/awaited-result.js +150 -0
  24. package/dist/child-context.d.ts +15 -0
  25. package/dist/child-context.js +181 -0
  26. package/dist/child-session-shutdown.d.ts +21 -0
  27. package/dist/child-session-shutdown.js +97 -0
  28. package/dist/cleanup-plans.d.ts +10 -0
  29. package/dist/cleanup-plans.js +112 -0
  30. package/dist/context.d.ts +12 -0
  31. package/dist/context.js +56 -0
  32. package/dist/cross-extension-rpc.d.ts +73 -0
  33. package/dist/cross-extension-rpc.js +192 -0
  34. package/dist/custom-agents.d.ts +79 -0
  35. package/dist/custom-agents.js +583 -0
  36. package/dist/default-agents.d.ts +7 -0
  37. package/dist/default-agents.js +125 -0
  38. package/dist/enabled-models.d.ts +49 -0
  39. package/dist/enabled-models.js +145 -0
  40. package/dist/env.d.ts +6 -0
  41. package/dist/env.js +28 -0
  42. package/dist/error-log.d.ts +64 -0
  43. package/dist/error-log.js +176 -0
  44. package/dist/force-main-model.d.ts +21 -0
  45. package/dist/force-main-model.js +28 -0
  46. package/dist/goal-bridge.d.ts +155 -0
  47. package/dist/goal-bridge.js +305 -0
  48. package/dist/group-join.d.ts +36 -0
  49. package/dist/group-join.js +161 -0
  50. package/dist/index.d.ts +52 -0
  51. package/dist/index.js +6390 -0
  52. package/dist/invocation-config.d.ts +164 -0
  53. package/dist/invocation-config.js +158 -0
  54. package/dist/memory.d.ts +53 -0
  55. package/dist/memory.js +165 -0
  56. package/dist/mention-clone.d.ts +87 -0
  57. package/dist/mention-clone.js +178 -0
  58. package/dist/mention.d.ts +81 -0
  59. package/dist/mention.js +131 -0
  60. package/dist/model-resolver.d.ts +36 -0
  61. package/dist/model-resolver.js +95 -0
  62. package/dist/model-scope.d.ts +49 -0
  63. package/dist/model-scope.js +48 -0
  64. package/dist/nested-tools.d.ts +76 -0
  65. package/dist/nested-tools.js +393 -0
  66. package/dist/output-diagnostics.d.ts +11 -0
  67. package/dist/output-diagnostics.js +64 -0
  68. package/dist/output-file.d.ts +64 -0
  69. package/dist/output-file.js +351 -0
  70. package/dist/prompts.d.ts +61 -0
  71. package/dist/prompts.js +94 -0
  72. package/dist/recovery.d.ts +56 -0
  73. package/dist/recovery.js +341 -0
  74. package/dist/report-cleanup.d.ts +204 -0
  75. package/dist/report-cleanup.js +1632 -0
  76. package/dist/report-store.d.ts +738 -0
  77. package/dist/report-store.js +3612 -0
  78. package/dist/schedule-store.d.ts +52 -0
  79. package/dist/schedule-store.js +240 -0
  80. package/dist/schedule.d.ts +121 -0
  81. package/dist/schedule.js +420 -0
  82. package/dist/settings.d.ts +388 -0
  83. package/dist/settings.js +268 -0
  84. package/dist/skill-loader.d.ts +24 -0
  85. package/dist/skill-loader.js +93 -0
  86. package/dist/standalone-fallback.d.ts +30 -0
  87. package/dist/standalone-fallback.js +239 -0
  88. package/dist/status-note.d.ts +61 -0
  89. package/dist/status-note.js +85 -0
  90. package/dist/structured-output.d.ts +61 -0
  91. package/dist/structured-output.js +112 -0
  92. package/dist/terminal-progress.d.ts +115 -0
  93. package/dist/terminal-progress.js +206 -0
  94. package/dist/types.d.ts +411 -0
  95. package/dist/types.js +5 -0
  96. package/dist/ui/agent-mention.d.ts +82 -0
  97. package/dist/ui/agent-mention.js +187 -0
  98. package/dist/ui/agent-widget.d.ts +304 -0
  99. package/dist/ui/agent-widget.js +770 -0
  100. package/dist/ui/cleanup-preview.d.ts +59 -0
  101. package/dist/ui/cleanup-preview.js +466 -0
  102. package/dist/ui/conversation-viewer.d.ts +105 -0
  103. package/dist/ui/conversation-viewer.js +544 -0
  104. package/dist/ui/fleet-list.d.ts +183 -0
  105. package/dist/ui/fleet-list.js +494 -0
  106. package/dist/ui/fleet-overlay.d.ts +203 -0
  107. package/dist/ui/fleet-overlay.js +887 -0
  108. package/dist/ui/hub-feed.d.ts +52 -0
  109. package/dist/ui/hub-feed.js +148 -0
  110. package/dist/ui/native-transcript.d.ts +33 -0
  111. package/dist/ui/native-transcript.js +234 -0
  112. package/dist/ui/schedule-menu.d.ts +16 -0
  113. package/dist/ui/schedule-menu.js +94 -0
  114. package/dist/ui/select-item.d.ts +27 -0
  115. package/dist/ui/select-item.js +34 -0
  116. package/dist/ui/tool-progress.d.ts +22 -0
  117. package/dist/ui/tool-progress.js +56 -0
  118. package/dist/ui/viewer-keys.d.ts +20 -0
  119. package/dist/ui/viewer-keys.js +17 -0
  120. package/dist/ui/workflow-card.d.ts +175 -0
  121. package/dist/ui/workflow-card.js +332 -0
  122. package/dist/ui/workflow-dialog.d.ts +305 -0
  123. package/dist/ui/workflow-dialog.js +848 -0
  124. package/dist/ui/workflow-menu.d.ts +60 -0
  125. package/dist/ui/workflow-menu.js +147 -0
  126. package/dist/usage.d.ts +147 -0
  127. package/dist/usage.js +147 -0
  128. package/dist/workflow/collisions.d.ts +95 -0
  129. package/dist/workflow/collisions.js +88 -0
  130. package/dist/workflow/entry.d.ts +32 -0
  131. package/dist/workflow/entry.js +29 -0
  132. package/dist/workflow/host.d.ts +65 -0
  133. package/dist/workflow/host.js +477 -0
  134. package/dist/workflow/journal.d.ts +113 -0
  135. package/dist/workflow/journal.js +177 -0
  136. package/dist/workflow/json-schema.d.ts +51 -0
  137. package/dist/workflow/json-schema.js +111 -0
  138. package/dist/workflow/meta.d.ts +67 -0
  139. package/dist/workflow/meta.js +317 -0
  140. package/dist/workflow/progress.d.ts +224 -0
  141. package/dist/workflow/progress.js +361 -0
  142. package/dist/workflow/runtime.d.ts +373 -0
  143. package/dist/workflow/runtime.js +919 -0
  144. package/dist/workflow/saved.d.ts +90 -0
  145. package/dist/workflow/saved.js +203 -0
  146. package/dist/workflow/task.d.ts +145 -0
  147. package/dist/workflow/task.js +213 -0
  148. package/dist/workflow/tool-description.d.ts +43 -0
  149. package/dist/workflow/tool-description.js +204 -0
  150. package/dist/workflow/worker-source.d.ts +47 -0
  151. package/dist/workflow/worker-source.js +778 -0
  152. package/dist/worktree.d.ts +52 -0
  153. package/dist/worktree.js +164 -0
  154. package/dist/xml.d.ts +10 -0
  155. package/dist/xml.js +12 -0
  156. package/docs/DEVELOPMENT.md +40 -0
  157. package/docs/artifacts.md +93 -0
  158. package/docs/recovery.md +62 -0
  159. package/docs/rpc.md +252 -0
  160. package/docs/runtime-performance.md +53 -0
  161. package/docs/workflows.md +467 -0
  162. package/examples/agent-tool-description.md +43 -0
  163. package/examples/workflows/compose.js +51 -0
  164. package/examples/workflows/fan-out-audit.js +47 -0
  165. package/examples/workflows/gated-fix.js +60 -0
  166. package/examples/workflows/lib/count-child.js +27 -0
  167. package/examples/workflows/review-panel.js +66 -0
  168. package/examples/workflows/structured-findings.js +78 -0
  169. package/package.json +75 -6
  170. package/src/abortable.ts +43 -0
  171. package/src/active-agents-prompt.ts +115 -0
  172. package/src/advisor-status.ts +74 -0
  173. package/src/agent-color.ts +169 -0
  174. package/src/agent-file-toggle.ts +273 -0
  175. package/src/agent-manager.ts +3312 -0
  176. package/src/agent-runner.ts +1500 -0
  177. package/src/agent-types.ts +390 -0
  178. package/src/awaited-result.ts +187 -0
  179. package/src/child-context.ts +173 -0
  180. package/src/child-session-shutdown.ts +114 -0
  181. package/src/cleanup-plans.ts +112 -0
  182. package/src/context.ts +58 -0
  183. package/src/cross-extension-rpc.ts +257 -0
  184. package/src/custom-agents.ts +689 -0
  185. package/src/default-agents.ts +129 -0
  186. package/src/enabled-models.ts +180 -0
  187. package/src/env.ts +33 -0
  188. package/src/error-log.ts +202 -0
  189. package/src/force-main-model.ts +29 -0
  190. package/src/goal-bridge.ts +468 -0
  191. package/src/group-join.ts +188 -0
  192. package/src/index.ts +6856 -0
  193. package/src/invocation-config.ts +276 -0
  194. package/src/memory.ts +179 -0
  195. package/src/mention-clone.ts +221 -0
  196. package/src/mention.ts +141 -0
  197. package/src/model-resolver.ts +118 -0
  198. package/src/model-scope.ts +70 -0
  199. package/src/nested-tools.ts +553 -0
  200. package/src/output-diagnostics.ts +68 -0
  201. package/src/output-file.ts +380 -0
  202. package/src/prompts.ts +151 -0
  203. package/src/recovery.ts +320 -0
  204. package/src/report-cleanup.ts +2044 -0
  205. package/src/report-store.ts +4130 -0
  206. package/src/schedule-store.ts +244 -0
  207. package/src/schedule.ts +450 -0
  208. package/src/settings.ts +632 -0
  209. package/src/skill-loader.ts +102 -0
  210. package/src/standalone-fallback.ts +195 -0
  211. package/src/status-note.ts +90 -0
  212. package/src/structured-output.ts +130 -0
  213. package/src/terminal-progress.ts +215 -0
  214. package/src/types.ts +424 -0
  215. package/src/ui/agent-mention.ts +216 -0
  216. package/src/ui/agent-widget.ts +866 -0
  217. package/src/ui/cleanup-preview.ts +518 -0
  218. package/src/ui/conversation-viewer.ts +527 -0
  219. package/src/ui/fleet-list.ts +563 -0
  220. package/src/ui/fleet-overlay.ts +1048 -0
  221. package/src/ui/hub-feed.ts +179 -0
  222. package/src/ui/native-transcript.ts +224 -0
  223. package/src/ui/schedule-menu.ts +105 -0
  224. package/src/ui/select-item.ts +45 -0
  225. package/src/ui/tool-progress.ts +67 -0
  226. package/src/ui/viewer-keys.ts +39 -0
  227. package/src/ui/workflow-card.ts +470 -0
  228. package/src/ui/workflow-dialog.ts +1119 -0
  229. package/src/ui/workflow-menu.ts +193 -0
  230. package/src/usage.ts +217 -0
  231. package/src/workflow/collisions.ts +123 -0
  232. package/src/workflow/entry.ts +47 -0
  233. package/src/workflow/host.ts +524 -0
  234. package/src/workflow/journal.ts +221 -0
  235. package/src/workflow/json-schema.ts +128 -0
  236. package/src/workflow/meta.ts +325 -0
  237. package/src/workflow/progress.ts +550 -0
  238. package/src/workflow/runtime.ts +1342 -0
  239. package/src/workflow/saved.ts +217 -0
  240. package/src/workflow/task.ts +313 -0
  241. package/src/workflow/tool-description.ts +205 -0
  242. package/src/workflow/worker-source.ts +781 -0
  243. package/src/worktree.ts +205 -0
  244. package/src/xml.ts +13 -0
@@ -0,0 +1,341 @@
1
+ import { logSubagentIssue } from "./error-log.js";
2
+ import { isTransientProviderFailure, STANDALONE_CONTINUATION } from "./standalone-fallback.js";
3
+ export const RECOVERY_CHANNEL = "pi-fallback-chains:recovery";
4
+ const PHASES = new Set(["idle", "pending", "switching", "compacting", "retrying", "settled", "cancelled", "failed"]);
5
+ const controllers = new WeakMap();
6
+ function isSnapshot(value) {
7
+ if (!value || typeof value !== "object")
8
+ return false;
9
+ const s = value;
10
+ return s.version === 1 && typeof s.sessionId === "string" && typeof s.requestId === "string"
11
+ && Number.isSafeInteger(s.epoch) && s.epoch >= 0 && Number.isSafeInteger(s.revision) && s.revision >= 0
12
+ && PHASES.has(s.phase) && typeof s.pending === "boolean"
13
+ && s.pending === ["pending", "switching", "compacting", "retrying"].includes(s.phase)
14
+ && (s.model === undefined || typeof s.model === "string")
15
+ && (s.reason === undefined || typeof s.reason === "string");
16
+ }
17
+ export class ChildRecovery {
18
+ bus;
19
+ session;
20
+ snapshot;
21
+ cancelled = false;
22
+ disposed = false;
23
+ waiters = new Set();
24
+ unsubscribe;
25
+ onModelChange;
26
+ standalone;
27
+ ownerObserved = false;
28
+ generation = 0;
29
+ attempted = false;
30
+ prompting = false;
31
+ unfinishedTools = new Set();
32
+ unsafeTools = false;
33
+ configureStandalone(policy) { this.standalone = policy; }
34
+ /** A managed prompt — the run itself or its recovery continuation — is active. */
35
+ isPrompting() { return this.prompting && !this.disposed; }
36
+ /** Only managed request boundaries reset cancellation and the one-attempt budget. */
37
+ beginRequest() {
38
+ if (this.disposed || this.prompting)
39
+ throw new Error("Child recovery request is still active or disposed");
40
+ this.generation++;
41
+ this.cancelled = false;
42
+ this.attempted = false;
43
+ this.unsafeTools = false;
44
+ this.unfinishedTools.clear();
45
+ if (!this.standalone)
46
+ return;
47
+ // Prior unfinished calls cannot safely be replayed by a resumed request.
48
+ for (const message of this.session?.messages ?? []) {
49
+ if (message.role === "assistant") {
50
+ for (const part of message.content)
51
+ if (part.type === "toolCall")
52
+ this.unfinishedTools.add(part.id);
53
+ }
54
+ else if (message.role === "toolResult")
55
+ this.unfinishedTools.delete(message.toolCallId);
56
+ }
57
+ }
58
+ /** Construct before loading extensions, attach before bindExtensions/session_start. */
59
+ constructor(bus) {
60
+ this.bus = bus;
61
+ this.unsubscribe = bus.on(RECOVERY_CHANNEL, data => this.receive(data));
62
+ }
63
+ attach(session, onModelChange) {
64
+ this.session = session;
65
+ this.onModelChange = onModelChange;
66
+ controllers.set(session, this);
67
+ const dispose = session.dispose?.bind(session);
68
+ if (dispose)
69
+ session.dispose = () => { this.dispose(); dispose(); };
70
+ }
71
+ receive(data) {
72
+ if (this.disposed || !isSnapshot(data) || data.sessionId !== this.session?.sessionId)
73
+ return;
74
+ // Ownership is sticky and independent of lease state, age, or cancellation.
75
+ this.ownerObserved = true;
76
+ const previous = this.snapshot;
77
+ if (previous && (data.epoch < previous.epoch || data.revision <= previous.revision))
78
+ return;
79
+ if (previous && data.epoch === previous.epoch && data.requestId !== previous.requestId)
80
+ return;
81
+ if (this.cancelled && data.pending)
82
+ return;
83
+ // Copy: a producer mutating its next snapshot must not mutate our observed generation.
84
+ this.snapshot = { ...data };
85
+ this.onModelChange?.(this.session);
86
+ this.wake();
87
+ }
88
+ query() {
89
+ if (this.disposed || !this.session)
90
+ return;
91
+ this.bus.emit(`${RECOVERY_CHANNEL}:query`, {
92
+ version: 1,
93
+ sessionId: this.session.sessionId,
94
+ reply: (snapshot) => this.receive(snapshot),
95
+ });
96
+ }
97
+ wake() {
98
+ for (const resolve of this.waiters)
99
+ resolve();
100
+ this.waiters.clear();
101
+ }
102
+ cancel(reason) {
103
+ if (this.cancelled || this.disposed)
104
+ return;
105
+ this.cancelled = true;
106
+ this.generation++;
107
+ if (this.session) {
108
+ this.bus.emit(`${RECOVERY_CHANNEL}:cancel`, { version: 1, sessionId: this.session.sessionId, reason });
109
+ }
110
+ this.wake();
111
+ }
112
+ executionError(error) {
113
+ if (this.disposed || !this.session)
114
+ return;
115
+ this.unsafeTools = true; // Extension/tool exceptions are not provider failures.
116
+ if (error.event !== "send_user_message")
117
+ return;
118
+ // Provider errors can contain credentials or entire requests. The protocol needs
119
+ // the category, not the raw exception; the normal Pi error path still owns it.
120
+ this.bus.emit(`${RECOVERY_CHANNEL}:execution-error`, {
121
+ version: 1,
122
+ sessionId: this.session.sessionId,
123
+ event: error.event,
124
+ message: "Recovery prompt submission failed (send_user_message).",
125
+ });
126
+ }
127
+ async prompt(text, signal) {
128
+ const session = this.session;
129
+ if (!session || this.disposed)
130
+ throw new Error("Child recovery session is disposed");
131
+ if (signal?.aborted || this.cancelled)
132
+ return undefined;
133
+ if (this.prompting)
134
+ throw new Error("Child recovery prompt is already active");
135
+ this.prompting = true;
136
+ const generation = this.generation;
137
+ const current = () => !this.disposed && !this.cancelled && !signal?.aborted && generation === this.generation;
138
+ const abort = () => this.cancel("aborted");
139
+ signal?.addEventListener("abort", abort, { once: true });
140
+ let finalMessage;
141
+ const unsubscribe = this.standalone ? session.subscribe(event => {
142
+ if (!current())
143
+ return;
144
+ if (event.type === "message_end") {
145
+ if (event.message.role === "assistant") {
146
+ finalMessage = event.message;
147
+ for (const part of event.message.content)
148
+ if (part.type === "toolCall")
149
+ this.unfinishedTools.add(part.id);
150
+ }
151
+ else if (event.message.role === "toolResult") {
152
+ this.unfinishedTools.delete(event.message.toolCallId);
153
+ if (event.message.isError)
154
+ this.unsafeTools = true;
155
+ }
156
+ }
157
+ if (event.type === "tool_execution_start")
158
+ this.unfinishedTools.add(event.toolCallId);
159
+ if (event.type === "tool_execution_end" && event.isError)
160
+ this.unsafeTools = true;
161
+ }) : () => { };
162
+ this.query();
163
+ const revision = this.snapshot?.revision ?? -1;
164
+ try {
165
+ await session.prompt(text);
166
+ if (!current())
167
+ return undefined;
168
+ this.query();
169
+ if (this.snapshot)
170
+ await this.waitForSettlement(session);
171
+ if (!current())
172
+ return undefined;
173
+ this.query();
174
+ const policy = this.standalone;
175
+ const ownsLocally = () => {
176
+ this.query();
177
+ return current() && !this.ownerObserved && policy?.ownership() === "absent";
178
+ };
179
+ if (policy && !this.attempted && isTransientProviderFailure(finalMessage)
180
+ && !this.unsafeTools && this.unfinishedTools.size === 0 && ownsLocally()) {
181
+ this.attempted = true; // Consume before resolution, switching, or any await.
182
+ const failed = session.model;
183
+ if (!failed || finalMessage?.provider !== failed.provider || finalMessage.model !== failed.id)
184
+ return undefined;
185
+ // This layer has no agentId (records live in agent-manager); the
186
+ // sessionId is the correlation handle on the persistent aggregate log.
187
+ const logOutcome = (outcome, reason, to) => logSubagentIssue({ kind: "standalone_fallback", sessionId: session.sessionId,
188
+ from: { provider: failed.provider, model: failed.id }, to, outcome, reason });
189
+ let target;
190
+ try {
191
+ target = policy.resolve(session, failed);
192
+ }
193
+ catch {
194
+ logOutcome("failed", "Standalone fallback target could not be resolved.");
195
+ return "Standalone fallback target could not be resolved.";
196
+ }
197
+ if (!target)
198
+ logOutcome("blocked", "No eligible standalone fallback target.");
199
+ if (target && ownsLocally() && session.isIdle && !session.isCompacting) {
200
+ try {
201
+ await session.setModel(target, { persist: false });
202
+ }
203
+ catch {
204
+ logOutcome("failed", "Standalone fallback model switch failed.", { provider: target.provider, model: target.id });
205
+ if (!current())
206
+ return undefined;
207
+ this.query();
208
+ if (this.snapshot)
209
+ await this.waitForSettlement(session);
210
+ if (!current())
211
+ return undefined;
212
+ return "Standalone fallback model switch failed.";
213
+ }
214
+ if (!current())
215
+ return undefined;
216
+ this.onModelChange?.(session);
217
+ // A producer, scope change, cancellation, or manual switch can win
218
+ // while setModel awaits auth/model_select. Never undo that decision.
219
+ if (ownsLocally() && session.model?.provider === target.provider && session.model.id === target.id
220
+ && session.isIdle && !session.isCompacting && !this.unsafeTools && this.unfinishedTools.size === 0) {
221
+ let allowed;
222
+ try {
223
+ allowed = policy.resolve(session, failed);
224
+ }
225
+ catch {
226
+ logOutcome("failed", "Standalone fallback scope could not be checked.", { provider: target.provider, model: target.id });
227
+ return "Standalone fallback scope could not be checked.";
228
+ }
229
+ if (allowed?.provider === target.provider && allowed.id === target.id && ownsLocally()) {
230
+ await session.prompt(STANDALONE_CONTINUATION, { source: "extension", expandPromptTemplates: false });
231
+ logOutcome("success", undefined, { provider: target.provider, model: target.id });
232
+ if (!current())
233
+ return undefined;
234
+ this.query();
235
+ }
236
+ else {
237
+ logOutcome("blocked", "Post-switch scope re-check refused the standalone fallback target.", { provider: target.provider, model: target.id });
238
+ }
239
+ }
240
+ // An owner arriving during switching/continuation still retains its slot.
241
+ if (this.snapshot)
242
+ await this.waitForSettlement(session);
243
+ if (!current())
244
+ return undefined;
245
+ }
246
+ }
247
+ // A query/resolver can discover ownership even when no local switch ran.
248
+ if (this.snapshot?.pending)
249
+ await this.waitForSettlement(session);
250
+ if (!current())
251
+ return undefined;
252
+ this.onModelChange?.(session);
253
+ if (this.snapshot?.phase === "failed" && this.snapshot.revision > revision) {
254
+ return this.snapshot.reason || "Automatic recovery failed.";
255
+ }
256
+ return undefined;
257
+ }
258
+ catch (error) {
259
+ if (current())
260
+ this.cancel("prompt_failed");
261
+ throw error;
262
+ }
263
+ finally {
264
+ unsubscribe();
265
+ signal?.removeEventListener("abort", abort);
266
+ this.prompting = false;
267
+ }
268
+ }
269
+ async waitForSettlement(session) {
270
+ const unsubscribe = session.subscribe(event => {
271
+ if (event.type === "agent_settled" || event.type === "agent_start" || event.type === "compaction_end")
272
+ this.wake();
273
+ });
274
+ try {
275
+ while (!this.disposed) {
276
+ this.query();
277
+ if ((!this.cancelled && this.snapshot?.pending) || session.isCompacting) {
278
+ await new Promise(resolve => this.waiters.add(resolve));
279
+ continue;
280
+ }
281
+ const observed = this.snapshot;
282
+ let changed;
283
+ const change = new Promise(resolve => { changed = resolve; this.waiters.add(resolve); });
284
+ try {
285
+ await Promise.race([session.waitForIdle(), change]);
286
+ }
287
+ finally {
288
+ this.waiters.delete(changed);
289
+ }
290
+ if (this.disposed)
291
+ return;
292
+ this.query();
293
+ // A new lease can be claimed inside waitForIdle/agent_settled. Check the
294
+ // same snapshot generation AND session state, never just agent_end.
295
+ if ((this.cancelled || observed === this.snapshot) && (this.cancelled || !this.snapshot?.pending)
296
+ && session.isIdle && !session.isCompacting)
297
+ return;
298
+ }
299
+ }
300
+ finally {
301
+ unsubscribe();
302
+ }
303
+ }
304
+ dispose() {
305
+ if (this.disposed)
306
+ return;
307
+ this.cancel("shutdown");
308
+ this.disposed = true;
309
+ this.unsubscribe();
310
+ if (this.session)
311
+ controllers.delete(this.session);
312
+ this.wake();
313
+ }
314
+ }
315
+ /** True while a managed prompt (including fallback recovery) is still in flight. */
316
+ export function isChildRequestActive(session) {
317
+ return controllers.get(session)?.isPrompting() === true;
318
+ }
319
+ export function beginChildRequest(session) {
320
+ controllers.get(session)?.beginRequest();
321
+ }
322
+ export async function promptWithRecovery(session, text, signal) {
323
+ const recovery = controllers.get(session);
324
+ if (recovery)
325
+ return recovery.prompt(text, signal);
326
+ if (!signal?.aborted)
327
+ await session.prompt(text);
328
+ return undefined;
329
+ }
330
+ /** Invalidate extension timers/continuations synchronously BEFORE Pi aborts. */
331
+ export async function abortChildSession(session, reason = "aborted") {
332
+ controllers.get(session)?.cancel(reason);
333
+ if (session.isCompacting) {
334
+ session.abortCompaction();
335
+ session.abortBranchSummary();
336
+ }
337
+ await session.abort();
338
+ }
339
+ export function disposeChildRecovery(session) {
340
+ controllers.get(session)?.dispose();
341
+ }
@@ -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;