@vicary/pi-subagents 0.87.0 → 0.88.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 (108) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/bundle/agents.js +3 -3
  3. package/bundle/child-tool-plan.js +3 -3
  4. package/bundle/{chunk-3CVOAS77.js → chunk-2DIEL4WG.js} +2 -2
  5. package/bundle/{chunk-75LVXBSA.js → chunk-2HKPEANZ.js} +114 -49
  6. package/bundle/{chunk-ESWW6XSX.js → chunk-47ZN7NKR.js} +1 -1
  7. package/bundle/{chunk-C3KWLXDH.js → chunk-4MVDMA5C.js} +9 -1
  8. package/bundle/{chunk-XV7RTWTS.js → chunk-4ZQBZDF3.js} +21 -6
  9. package/bundle/{chunk-LZKVUWIY.js → chunk-5EMPFFO4.js} +30 -5
  10. package/bundle/{chunk-OOE3R7IQ.js → chunk-6CG2VAG4.js} +2 -2
  11. package/bundle/{chunk-HDICKROY.js → chunk-7OX6O7DQ.js} +31 -14
  12. package/bundle/{chunk-Z4TR7MK6.js → chunk-AZPP3G4N.js} +14 -5
  13. package/bundle/{chunk-PUSTU4Q7.js → chunk-BKISQ5CJ.js} +130 -49
  14. package/bundle/{chunk-NMYBVCGP.js → chunk-CGWNA6EJ.js} +75 -44
  15. package/bundle/{chunk-PGU4TZV3.js → chunk-CPSUJHZE.js} +417 -455
  16. package/bundle/{chunk-W52LJANO.js → chunk-CYKNHFXB.js} +1 -1
  17. package/bundle/{chunk-SIAQXPJ4.js → chunk-D32H53HM.js} +21 -9
  18. package/bundle/{chunk-YEXKJJVS.js → chunk-DSHQWGHO.js} +4 -4
  19. package/bundle/{chunk-6O7YH2QV.js → chunk-GDR2ILWY.js} +1 -1
  20. package/bundle/{chunk-O7A26O6B.js → chunk-IYT7X46U.js} +6 -4
  21. package/bundle/{chunk-NJTSXIMG.js → chunk-JQTHG2ID.js} +12 -12
  22. package/bundle/{chunk-C5QWQSSM.js → chunk-KXW62VBU.js} +1 -1
  23. package/bundle/{chunk-BFF6YDK6.js → chunk-L4YY2TOE.js} +1 -1
  24. package/bundle/{chunk-2NY5PCKQ.js → chunk-LV3CPYXJ.js} +4 -4
  25. package/bundle/{chunk-2D2DQGC2.js → chunk-PYKBTBY6.js} +27 -10
  26. package/bundle/{chunk-M2VBGET6.js → chunk-RMZAAXIR.js} +7 -2
  27. package/bundle/{chunk-HTI7DD5D.js → chunk-V7SZMS6W.js} +2 -2
  28. package/bundle/{chunk-VFUFOZBU.js → chunk-W6HIYD2Z.js} +1 -1
  29. package/bundle/{chunk-USRX7QXD.js → chunk-XIA5GSEU.js} +2 -2
  30. package/bundle/{chunk-CTPAE36Y.js → chunk-YARY7JWU.js} +22 -0
  31. package/bundle/chunk-YDZ7BZD5.js +523 -0
  32. package/bundle/control-channel.js +2 -2
  33. package/bundle/index.js +1 -1
  34. package/bundle/intercom-bridge.js +2 -2
  35. package/bundle/preflight.js +9 -9
  36. package/bundle/project-panes.js +3 -3
  37. package/bundle/required-child-extensions.js +1 -1
  38. package/docs/agents.md +4 -2
  39. package/docs/configuration.md +4 -2
  40. package/docs/observability.md +2 -0
  41. package/docs/tool-reference.md +4 -1
  42. package/docs/workflows.md +3 -1
  43. package/package.json +3 -3
  44. package/skills/pi-subagents/SKILL.md +8 -2
  45. package/src/agents/agent-management.d.ts +1 -0
  46. package/src/agents/agent-management.js +12 -4
  47. package/src/agents/agents.d.ts +1 -0
  48. package/src/agents/agents.js +2 -2
  49. package/src/extension/config.d.ts +9 -0
  50. package/src/extension/config.js +13 -0
  51. package/src/extension/index.d.ts +1 -1
  52. package/src/extension/index.js +47 -23
  53. package/src/extension/schemas.d.ts +2 -0
  54. package/src/extension/schemas.js +1 -0
  55. package/src/extension/subagent-launch-tool.d.ts +6 -2
  56. package/src/extension/subagent-launch-tool.js +13 -9
  57. package/src/extension/tool-activation.js +20 -3
  58. package/src/runs/background/async-resume.js +2 -1
  59. package/src/runs/background/async-retention.d.ts +0 -2
  60. package/src/runs/background/async-retention.js +11 -5
  61. package/src/runs/background/async-status.d.ts +2 -0
  62. package/src/runs/background/async-status.js +4 -0
  63. package/src/runs/background/run-child-session.d.ts +2 -2
  64. package/src/runs/background/run-child-session.js +4 -7
  65. package/src/runs/background/stale-run-reconciler.js +17 -8
  66. package/src/runs/background/steering.d.ts +2 -11
  67. package/src/runs/background/steering.js +11 -6
  68. package/src/runs/background/subagent-runner.d.ts +0 -2
  69. package/src/runs/background/subagent-runner.js +73 -58
  70. package/src/runs/foreground/async-steering-action.js +24 -9
  71. package/src/runs/foreground/execution.js +32 -15
  72. package/src/runs/foreground/prompt-audit.js +1 -0
  73. package/src/runs/foreground/subagent-executor.d.ts +1 -8
  74. package/src/runs/foreground/subagent-executor.js +17 -21
  75. package/src/runs/shared/async-status-projection.d.ts +2 -0
  76. package/src/runs/shared/async-status-projection.js +10 -0
  77. package/src/runs/shared/child-launch.js +6 -3
  78. package/src/runs/shared/child-session.d.ts +1 -1
  79. package/src/runs/shared/child-session.js +24 -30
  80. package/src/runs/shared/mcp-config-sources.d.ts +2 -0
  81. package/src/runs/shared/mcp-direct-tool-allowlist.d.ts +5 -5
  82. package/src/runs/shared/mcp-direct-tool-allowlist.js +26 -15
  83. package/src/runs/shared/subagent-prompt-runtime.js +14 -2
  84. package/src/runs/shared/supervisor-wait-timer.d.ts +16 -0
  85. package/src/runs/shared/supervisor-wait-timer.js +61 -0
  86. package/src/shared/artifacts.d.ts +1 -0
  87. package/src/shared/artifacts.js +107 -9
  88. package/src/shared/compaction-interruption.d.ts +9 -0
  89. package/src/shared/compaction-interruption.js +47 -0
  90. package/src/shared/parent-wake.d.ts +3 -2
  91. package/src/shared/parent-wake.js +14 -3
  92. package/src/shared/reported-progress.d.ts +1 -0
  93. package/src/shared/reported-progress.js +12 -0
  94. package/src/shared/required-child-extensions.d.ts +2 -0
  95. package/src/shared/required-child-extensions.js +27 -0
  96. package/src/shared/status-format.d.ts +1 -0
  97. package/src/shared/status-format.js +1 -1
  98. package/src/shared/types.d.ts +9 -0
  99. package/src/shared/utils.d.ts +3 -1
  100. package/src/shared/utils.js +4 -0
  101. package/src/tui/fleet.d.ts +7 -2
  102. package/src/tui/fleet.js +22 -0
  103. package/src/tui/render.js +33 -2
  104. package/src/watchdog/permission-arbiter.js +1 -0
  105. package/src/watchdog/review.d.ts +0 -5
  106. package/src/watchdog/review.js +2 -1
  107. package/src/workflows/workflow-script-worker.js +3 -1
  108. package/bundle/chunk-XSDYTXHF.js +0 -242
@@ -0,0 +1,523 @@
1
+ import {
2
+ createAtomicJsonWriter,
3
+ getAgentDir,
4
+ readStatus
5
+ } from "./chunk-4MVDMA5C.js";
6
+ import {
7
+ DIRS,
8
+ TEMP_ARTIFACTS_DIR,
9
+ TEMP_ROOT_DIR
10
+ } from "./chunk-JEZOSEWG.js";
11
+
12
+ // src/shared/artifacts.ts
13
+ import * as fs2 from "node:fs";
14
+ import * as path2 from "node:path";
15
+
16
+ // src/runs/shared/session-lease.ts
17
+ import { createHash, randomUUID } from "node:crypto";
18
+ import * as fs from "node:fs";
19
+ import * as os from "node:os";
20
+ import * as path from "node:path";
21
+ var SESSION_LEASES_DIR = path.join(TEMP_ROOT_DIR, "session-leases");
22
+ var SessionLeaseConflictError = class extends Error {
23
+ owner;
24
+ constructor(message, owner) {
25
+ super(message);
26
+ this.name = "SessionLeaseConflictError";
27
+ this.owner = owner;
28
+ }
29
+ };
30
+ function getProcessStartIdentity(pid) {
31
+ if (process.platform === "linux") {
32
+ try {
33
+ const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf-8");
34
+ const commandEnd = stat.lastIndexOf(")");
35
+ if (commandEnd === -1) return void 0;
36
+ const fields = stat.slice(commandEnd + 1).trim().split(/\s+/);
37
+ const startTicks = fields[19];
38
+ return startTicks ? `linux:${startTicks}` : void 0;
39
+ } catch {
40
+ return void 0;
41
+ }
42
+ }
43
+ return void 0;
44
+ }
45
+ function processIsAlive(pid) {
46
+ try {
47
+ process.kill(pid, 0);
48
+ return true;
49
+ } catch (error) {
50
+ const code = error.code;
51
+ if (code === "ESRCH") return false;
52
+ if (code === "EPERM") return true;
53
+ return void 0;
54
+ }
55
+ }
56
+ function canonicalSessionFilePath(sessionFile) {
57
+ return fs.realpathSync.native(path.resolve(sessionFile));
58
+ }
59
+ function canonicalSessionId(sessionFile) {
60
+ const canonical = canonicalSessionFilePath(sessionFile);
61
+ const key = process.platform === "win32" ? canonical.toLowerCase() : canonical;
62
+ return createHash("sha256").update(key).digest("hex");
63
+ }
64
+ function sessionLeaseDir(sessionFile, rootDir = SESSION_LEASES_DIR) {
65
+ return path.join(rootDir, canonicalSessionId(sessionFile));
66
+ }
67
+ function inspectSessionLease(sessionFile, rootDir = SESSION_LEASES_DIR) {
68
+ const canonicalSessionFile = canonicalSessionFilePath(sessionFile);
69
+ const canonicalSessionIdValue = canonicalSessionId(canonicalSessionFile);
70
+ const leaseDir = path.join(rootDir, canonicalSessionIdValue);
71
+ if (!fs.existsSync(leaseDir)) return { state: "free", canonicalSessionFile, canonicalSessionId: canonicalSessionIdValue };
72
+ const owner = readLeaseOwner(leaseDir);
73
+ return owner ? { state: "owned", canonicalSessionFile, canonicalSessionId: canonicalSessionIdValue, owner } : { state: "unreadable", canonicalSessionFile, canonicalSessionId: canonicalSessionIdValue };
74
+ }
75
+ function parseOwner(value) {
76
+ if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
77
+ const owner = value;
78
+ if (owner.version !== 1 || typeof owner.token !== "string" || typeof owner.canonicalSessionFile !== "string" || typeof owner.runId !== "string" || typeof owner.sourceRunId !== "string" || typeof owner.pid !== "number" || !Number.isInteger(owner.pid) || owner.pid <= 0 || typeof owner.hostname !== "string" || owner.writerState !== "none" && owner.writerState !== "spawning" && owner.writerState !== "running" || typeof owner.acquiredAt !== "string" || typeof owner.acquiredAtMs !== "number" || typeof owner.updatedAtMs !== "number") return void 0;
79
+ if (owner.parentSessionId !== void 0 && typeof owner.parentSessionId !== "string") return void 0;
80
+ if (owner.processStartIdentity !== void 0 && typeof owner.processStartIdentity !== "string") return void 0;
81
+ if (owner.writerPid !== void 0 && (typeof owner.writerPid !== "number" || !Number.isInteger(owner.writerPid) || owner.writerPid <= 0)) return void 0;
82
+ if (owner.writerProcessStartIdentity !== void 0 && typeof owner.writerProcessStartIdentity !== "string") return void 0;
83
+ if (owner.writerState === "running" && owner.writerPid === void 0) return void 0;
84
+ if (owner.writerState !== "running" && (owner.writerPid !== void 0 || owner.writerProcessStartIdentity !== void 0)) return void 0;
85
+ return owner;
86
+ }
87
+ function readLeaseOwner(leaseDir) {
88
+ try {
89
+ return parseOwner(JSON.parse(fs.readFileSync(path.join(leaseDir, "owner.json"), "utf-8")));
90
+ } catch {
91
+ return void 0;
92
+ }
93
+ }
94
+ function conflictMessage(canonicalSessionFile, owner) {
95
+ if (!owner) {
96
+ return `Direct revival of session '${canonicalSessionFile}' is blocked by an existing lease with unreadable owner metadata. Refusing to reclaim it without proof that the owner is stale.`;
97
+ }
98
+ const parent = owner.parentSessionId ? `, parent session '${owner.parentSessionId}'` : "";
99
+ return `Direct revival of session '${canonicalSessionFile}' is already owned by run '${owner.runId}' (source run '${owner.sourceRunId}'${parent}, pid ${owner.pid} on ${owner.hostname}). Wait for that revival to finish or start a separate continuation without reusing this session file.`;
100
+ }
101
+ function processDemonstrablyGone(pid, startIdentity, options) {
102
+ const alive = options.isProcessAlive(pid);
103
+ if (alive === false) return true;
104
+ if (alive !== true || !startIdentity) return false;
105
+ const currentIdentity = options.getProcessStartIdentity(pid);
106
+ return currentIdentity !== void 0 && currentIdentity !== startIdentity;
107
+ }
108
+ function demonstrablyStale(owner, options) {
109
+ if (owner.hostname !== options.hostname) return false;
110
+ if (!processDemonstrablyGone(owner.pid, owner.processStartIdentity, options)) return false;
111
+ if (owner.writerState === "spawning") return false;
112
+ if (owner.writerState === "none") return true;
113
+ return owner.writerPid !== void 0 && processDemonstrablyGone(owner.writerPid, owner.writerProcessStartIdentity, options);
114
+ }
115
+ function createLeaseDirectory(leaseDir, owner) {
116
+ const tempDir = `${leaseDir}.candidate-${owner.token}`;
117
+ fs.mkdirSync(path.dirname(leaseDir), { recursive: true, mode: 448 });
118
+ fs.rmSync(tempDir, { recursive: true, force: true });
119
+ fs.mkdirSync(tempDir, { mode: 448 });
120
+ try {
121
+ fs.writeFileSync(path.join(tempDir, "owner.json"), JSON.stringify(owner, null, 2), { encoding: "utf-8", mode: 384 });
122
+ try {
123
+ fs.renameSync(tempDir, leaseDir);
124
+ return true;
125
+ } catch (error) {
126
+ if (fs.existsSync(leaseDir)) return false;
127
+ throw error;
128
+ }
129
+ } finally {
130
+ fs.rmSync(tempDir, { recursive: true, force: true });
131
+ }
132
+ }
133
+ function acquireSessionLease(request, options = {}) {
134
+ const canonicalSessionFile = canonicalSessionFilePath(request.sessionFile);
135
+ const rootDir = options.rootDir ?? SESSION_LEASES_DIR;
136
+ const leaseDir = sessionLeaseDir(canonicalSessionFile, rootDir);
137
+ const now = options.now ?? Date.now;
138
+ const pid = options.pid ?? process.pid;
139
+ const hostname2 = options.hostname ?? os.hostname();
140
+ const getIdentity = options.getProcessStartIdentity ?? getProcessStartIdentity;
141
+ const processStartIdentity = options.processStartIdentity ?? getIdentity(pid) ?? (pid === process.pid ? `runtime:${Math.round(Date.now() - process.uptime() * 1e3)}` : void 0);
142
+ const acquiredAtMs = now();
143
+ const owner = {
144
+ version: 1,
145
+ token: options.token?.() ?? randomUUID(),
146
+ canonicalSessionFile,
147
+ runId: request.runId,
148
+ sourceRunId: request.sourceRunId,
149
+ ...request.parentSessionId ? { parentSessionId: request.parentSessionId } : {},
150
+ pid,
151
+ hostname: hostname2,
152
+ ...processStartIdentity ? { processStartIdentity } : {},
153
+ writerState: "none",
154
+ acquiredAt: new Date(acquiredAtMs).toISOString(),
155
+ acquiredAtMs,
156
+ updatedAtMs: acquiredAtMs
157
+ };
158
+ const staleOptions = {
159
+ hostname: hostname2,
160
+ isProcessAlive: options.isProcessAlive ?? processIsAlive,
161
+ getProcessStartIdentity: getIdentity
162
+ };
163
+ for (let attempt = 0; attempt < 4; attempt++) {
164
+ if (createLeaseDirectory(leaseDir, owner)) {
165
+ const writeOwner = createAtomicJsonWriter();
166
+ return {
167
+ leaseDir,
168
+ owner,
169
+ updateWriter(writer) {
170
+ const currentOwner = readLeaseOwner(leaseDir);
171
+ if (!currentOwner || currentOwner.token !== owner.token) {
172
+ throw new Error(`Session revival lease ownership changed for run '${owner.runId}'.`);
173
+ }
174
+ const writerProcessStartIdentity = writer.state === "running" ? getIdentity(writer.pid) : void 0;
175
+ const nextOwner = {
176
+ ...owner,
177
+ writerState: writer.state,
178
+ ...writer.state === "running" ? { writerPid: writer.pid } : {},
179
+ ...writerProcessStartIdentity ? { writerProcessStartIdentity } : {},
180
+ updatedAtMs: now()
181
+ };
182
+ delete nextOwner.writerPid;
183
+ delete nextOwner.writerProcessStartIdentity;
184
+ if (writer.state === "running") {
185
+ nextOwner.writerPid = writer.pid;
186
+ if (writerProcessStartIdentity) nextOwner.writerProcessStartIdentity = writerProcessStartIdentity;
187
+ }
188
+ writeOwner(path.join(leaseDir, "owner.json"), nextOwner);
189
+ delete owner.writerPid;
190
+ delete owner.writerProcessStartIdentity;
191
+ Object.assign(owner, nextOwner);
192
+ },
193
+ release() {
194
+ const currentOwner = readLeaseOwner(leaseDir);
195
+ if (!currentOwner || currentOwner.token !== owner.token) return false;
196
+ fs.rmSync(leaseDir, { recursive: true, force: true });
197
+ return !fs.existsSync(leaseDir);
198
+ }
199
+ };
200
+ }
201
+ const existingOwner2 = readLeaseOwner(leaseDir);
202
+ if (!existingOwner2 || !demonstrablyStale(existingOwner2, staleOptions)) {
203
+ throw new SessionLeaseConflictError(conflictMessage(canonicalSessionFile, existingOwner2), existingOwner2);
204
+ }
205
+ const tombstone = `${leaseDir}.stale-${existingOwner2.token.replace(/[^A-Za-z0-9._-]/g, "-")}`;
206
+ try {
207
+ fs.renameSync(leaseDir, tombstone);
208
+ } catch (error) {
209
+ const code = error.code;
210
+ if (code === "ENOENT" || fs.existsSync(tombstone)) continue;
211
+ throw error;
212
+ }
213
+ }
214
+ const existingOwner = readLeaseOwner(leaseDir);
215
+ throw new SessionLeaseConflictError(conflictMessage(canonicalSessionFile, existingOwner), existingOwner);
216
+ }
217
+
218
+ // src/shared/artifacts.ts
219
+ var CLEANUP_MARKER_FILE = ".last-cleanup";
220
+ var FORK_CLEANUP_MARKER_FILE = ".pi-subagents-fork-cleanup";
221
+ var DAY_MS = 24 * 60 * 60 * 1e3;
222
+ var RETAINED_ARTIFACT_DIRS = /* @__PURE__ */ new Set(["handoffs", "worktree-diffs"]);
223
+ var PROJECT_SUBAGENTS_RELATIVE_DIR = ".pi/subagents";
224
+ var PROJECT_ARTIFACT_PATHS = [
225
+ `${PROJECT_SUBAGENTS_RELATIVE_DIR}/artifacts/output.md`,
226
+ `${PROJECT_SUBAGENTS_RELATIVE_DIR}/artifacts/run_worker_input.md`,
227
+ `${PROJECT_SUBAGENTS_RELATIVE_DIR}/artifacts/run_worker_output.md`,
228
+ `${PROJECT_SUBAGENTS_RELATIVE_DIR}/artifacts/run_worker.jsonl`,
229
+ `${PROJECT_SUBAGENTS_RELATIVE_DIR}/artifacts/run_worker_transcript.jsonl`,
230
+ `${PROJECT_SUBAGENTS_RELATIVE_DIR}/artifacts/run_worker_meta.json`,
231
+ `${PROJECT_SUBAGENTS_RELATIVE_DIR}/artifacts/progress/run/progress.md`,
232
+ `${PROJECT_SUBAGENTS_RELATIVE_DIR}/artifacts/outputs/output.md`,
233
+ `${PROJECT_SUBAGENTS_RELATIVE_DIR}/artifacts/outputs/run/output.md`,
234
+ `${PROJECT_SUBAGENTS_RELATIVE_DIR}/chain-runs/run.json`
235
+ ];
236
+ function globMatchesPath(pattern, filePath) {
237
+ let expression = "^";
238
+ for (let index = 0; index < pattern.length; index += 1) {
239
+ const character = pattern[index];
240
+ if (character === void 0) break;
241
+ if (character === "*" && pattern[index + 1] === "*") {
242
+ index += 1;
243
+ if (pattern[index + 1] === "/") {
244
+ index += 1;
245
+ expression += "(?:.*/)?";
246
+ } else {
247
+ expression += ".*";
248
+ }
249
+ } else if (character === "*") {
250
+ expression += "[^/]*";
251
+ } else if (character === "?") {
252
+ expression += "[^/]";
253
+ } else if (character === "[") {
254
+ const end = pattern.indexOf("]", index + 1);
255
+ if (end === -1) expression += "\\[";
256
+ else {
257
+ expression += pattern.slice(index, end + 1);
258
+ index = end;
259
+ }
260
+ } else {
261
+ expression += character.replace(/[|\\{}()[\]^$+?.]/g, "\\$&");
262
+ }
263
+ }
264
+ try {
265
+ return new RegExp(`${expression}$`).test(filePath);
266
+ } catch {
267
+ return false;
268
+ }
269
+ }
270
+ function normalizePattern(pattern) {
271
+ return pattern.replace(/^\.\//, "").replace(/^\//, "").replace(/\/+$/, "");
272
+ }
273
+ function patternMatchesArtifactPath(pattern, artifactPath) {
274
+ const normalized = normalizePattern(pattern);
275
+ return normalized === PROJECT_SUBAGENTS_RELATIVE_DIR || normalized === "*" || artifactPath.startsWith(`${normalized}/`) || globMatchesPath(normalized, artifactPath);
276
+ }
277
+ function ignoreFileExcludesProjectArtifacts(filePath) {
278
+ if (!fs2.existsSync(filePath)) return false;
279
+ try {
280
+ const excluded = /* @__PURE__ */ new Set();
281
+ for (const rawLine of fs2.readFileSync(filePath, "utf-8").split(/\r?\n/)) {
282
+ const line = rawLine.trim();
283
+ if (!line || line.startsWith("#")) continue;
284
+ const negated = line.startsWith("!");
285
+ const pattern = negated ? line.slice(1) : line;
286
+ for (const artifactPath of PROJECT_ARTIFACT_PATHS) {
287
+ if (!patternMatchesArtifactPath(pattern, artifactPath)) continue;
288
+ if (negated) excluded.delete(artifactPath);
289
+ else excluded.add(artifactPath);
290
+ }
291
+ }
292
+ return excluded.size === PROJECT_ARTIFACT_PATHS.length;
293
+ } catch {
294
+ return false;
295
+ }
296
+ }
297
+ function filesIncludeProjectArtifacts(files) {
298
+ if (!Array.isArray(files)) return void 0;
299
+ const included = /* @__PURE__ */ new Set();
300
+ for (const entry of files) {
301
+ if (typeof entry !== "string") continue;
302
+ const negated = entry.startsWith("!");
303
+ const pattern = negated ? entry.slice(1) : entry;
304
+ for (const artifactPath of PROJECT_ARTIFACT_PATHS) {
305
+ if (!patternMatchesArtifactPath(pattern, artifactPath)) continue;
306
+ if (negated) included.delete(artifactPath);
307
+ else included.add(artifactPath);
308
+ }
309
+ }
310
+ return included.size > 0;
311
+ }
312
+ function getProjectArtifactPackagingWarning(cwd) {
313
+ const packagePath = path2.join(cwd, "package.json");
314
+ if (!fs2.existsSync(packagePath)) return void 0;
315
+ let packageJson;
316
+ try {
317
+ const parsed = JSON.parse(fs2.readFileSync(packagePath, "utf-8"));
318
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return void 0;
319
+ packageJson = parsed;
320
+ } catch {
321
+ return void 0;
322
+ }
323
+ const filesIncludeArtifacts = filesIncludeProjectArtifacts(packageJson.files);
324
+ if (filesIncludeArtifacts === false) return void 0;
325
+ const npmIgnorePath = path2.join(cwd, ".npmignore");
326
+ const ignorePath = fs2.existsSync(npmIgnorePath) ? npmIgnorePath : path2.join(cwd, ".gitignore");
327
+ if (filesIncludeArtifacts === void 0 && ignoreFileExcludesProjectArtifacts(ignorePath)) return void 0;
328
+ return "Project-scoped subagent artifacts can be included when this package is published. Add '.pi/subagents/' to .npmignore, restrict package.json files, or set artifactDir to 'session' or 'temp'.";
329
+ }
330
+ function getProjectSubagentsDir(cwd) {
331
+ return path2.join(cwd, PROJECT_SUBAGENTS_RELATIVE_DIR);
332
+ }
333
+ function getProjectArtifactsDir(cwd) {
334
+ return path2.join(getProjectSubagentsDir(cwd), "artifacts");
335
+ }
336
+ function getArtifactsDir(sessionFile, projectCwd, dirPreference = "session") {
337
+ switch (dirPreference) {
338
+ case "session":
339
+ if (sessionFile) {
340
+ const sessionDir = path2.dirname(sessionFile);
341
+ return path2.join(sessionDir, "subagent-artifacts");
342
+ }
343
+ return TEMP_ARTIFACTS_DIR;
344
+ case "temp":
345
+ return TEMP_ARTIFACTS_DIR;
346
+ case "project":
347
+ if (projectCwd) return getProjectArtifactsDir(projectCwd);
348
+ if (sessionFile) {
349
+ const sessionDir = path2.dirname(sessionFile);
350
+ return path2.join(sessionDir, "subagent-artifacts");
351
+ }
352
+ return TEMP_ARTIFACTS_DIR;
353
+ default:
354
+ throw new Error(`Unsupported artifactDir ${JSON.stringify(dirPreference)}; expected "project", "session", or "temp".`);
355
+ }
356
+ }
357
+ function getArtifactPaths(artifactsDir, runId, agent, index) {
358
+ const suffix = index !== void 0 ? `_${index}` : "";
359
+ const safeAgent = agent.replace(/[^\w.-]/g, "_");
360
+ const base = `${runId}_${safeAgent}${suffix}`;
361
+ return {
362
+ inputPath: path2.join(artifactsDir, `${base}_input.md`),
363
+ outputPath: path2.join(artifactsDir, `${base}_output.md`),
364
+ jsonlPath: path2.join(artifactsDir, `${base}.jsonl`),
365
+ transcriptPath: path2.join(artifactsDir, `${base}_transcript.jsonl`),
366
+ metadataPath: path2.join(artifactsDir, `${base}_meta.json`)
367
+ };
368
+ }
369
+ function ensureArtifactsDir(dir) {
370
+ fs2.mkdirSync(dir, { recursive: true });
371
+ }
372
+ function writeArtifact(filePath, content) {
373
+ fs2.mkdirSync(path2.dirname(filePath), { recursive: true });
374
+ fs2.writeFileSync(filePath, content, "utf-8");
375
+ }
376
+ function formatOutputArtifactContent(input) {
377
+ if (input.output.trim() || !input.error) return input.output;
378
+ const lines = ["Subagent run failed before producing output.", "", "Error:", input.error];
379
+ if (input.transcriptPath) lines.push("", `Transcript: ${input.transcriptPath}`);
380
+ if (input.metadataPath) lines.push(`Metadata: ${input.metadataPath}`);
381
+ return lines.join("\n");
382
+ }
383
+ function writeMetadata(filePath, metadata) {
384
+ fs2.mkdirSync(path2.dirname(filePath), { recursive: true });
385
+ fs2.writeFileSync(filePath, JSON.stringify(metadata, null, 2), "utf-8");
386
+ }
387
+ function appendJsonl(filePath, line) {
388
+ fs2.appendFileSync(filePath, `${line}
389
+ `);
390
+ }
391
+ function cleanupOldArtifacts(dir, maxAgeDays) {
392
+ if (maxAgeDays <= 0 || !fs2.existsSync(dir)) return;
393
+ const markerPath = path2.join(dir, CLEANUP_MARKER_FILE);
394
+ const now = Date.now();
395
+ if (ranWithinDay(markerPath, now)) return;
396
+ const cutoff = now - maxAgeDays * DAY_MS;
397
+ for (const entry of fs2.readdirSync(dir, { withFileTypes: true })) {
398
+ if (entry.name === CLEANUP_MARKER_FILE || entry.isDirectory() && RETAINED_ARTIFACT_DIRS.has(entry.name)) continue;
399
+ removeOldEntry(path2.join(dir, entry.name), cutoff);
400
+ }
401
+ fs2.writeFileSync(markerPath, String(now));
402
+ }
403
+ function removeOldEntry(entryPath, cutoff) {
404
+ try {
405
+ const stat = fs2.lstatSync(entryPath);
406
+ const old = stat.mtimeMs < cutoff;
407
+ if (!stat.isDirectory()) {
408
+ if (old) fs2.unlinkSync(entryPath);
409
+ return;
410
+ }
411
+ for (const name of fs2.readdirSync(entryPath)) removeOldEntry(path2.join(entryPath, name), cutoff);
412
+ if (old && fs2.readdirSync(entryPath).length === 0) fs2.rmdirSync(entryPath);
413
+ } catch {
414
+ }
415
+ }
416
+ function cleanupAllArtifactDirs(maxAgeDays) {
417
+ cleanupOldArtifacts(TEMP_ARTIFACTS_DIR, maxAgeDays);
418
+ const sessionsBase = path2.join(getAgentDir(), "sessions");
419
+ if (!fs2.existsSync(sessionsBase)) return;
420
+ let dirs;
421
+ try {
422
+ dirs = fs2.readdirSync(sessionsBase);
423
+ } catch {
424
+ return;
425
+ }
426
+ const forkMarkerPath = path2.join(sessionsBase, FORK_CLEANUP_MARKER_FILE);
427
+ const now = Date.now();
428
+ const pruneForks = maxAgeDays > 0 && !ranWithinDay(forkMarkerPath, now);
429
+ for (const dir of dirs) {
430
+ const artifactsDir = path2.join(sessionsBase, dir, "subagent-artifacts");
431
+ try {
432
+ cleanupOldArtifacts(artifactsDir, maxAgeDays);
433
+ } catch {
434
+ }
435
+ if (pruneForks) removeOldForkCopies(path2.join(sessionsBase, dir), now - maxAgeDays * DAY_MS);
436
+ }
437
+ if (!pruneForks) return;
438
+ try {
439
+ fs2.writeFileSync(forkMarkerPath, String(now));
440
+ } catch {
441
+ }
442
+ }
443
+ function ranWithinDay(markerPath, now) {
444
+ try {
445
+ return now - fs2.statSync(markerPath).mtimeMs < DAY_MS;
446
+ } catch {
447
+ return false;
448
+ }
449
+ }
450
+ function removeOldForkCopies(projectDir, cutoff) {
451
+ let sessions;
452
+ try {
453
+ sessions = fs2.readdirSync(projectDir, { withFileTypes: true });
454
+ } catch {
455
+ return;
456
+ }
457
+ for (const session of sessions) {
458
+ if (!session.isDirectory()) continue;
459
+ const forksDir = path2.join(projectDir, session.name, "forks");
460
+ let runIds;
461
+ try {
462
+ if (!fs2.lstatSync(forksDir).isDirectory()) continue;
463
+ runIds = fs2.readdirSync(forksDir);
464
+ } catch {
465
+ continue;
466
+ }
467
+ for (const runId of runIds) {
468
+ const runDir = path2.join(forksDir, runId);
469
+ const leases = [];
470
+ try {
471
+ const sessionFiles = idleSessionFiles(runDir, cutoff);
472
+ if (!sessionFiles || asyncRunActive(runId)) continue;
473
+ for (const file of sessionFiles) leases.push(acquireSessionLease({ sessionFile: file, runId: "fork-cleanup", sourceRunId: runId }));
474
+ fs2.rmSync(runDir, { recursive: true, force: true });
475
+ } catch {
476
+ } finally {
477
+ for (const lease of leases) lease.release();
478
+ }
479
+ }
480
+ }
481
+ }
482
+ function idleSessionFiles(entryPath, cutoff, files = []) {
483
+ const stat = fs2.lstatSync(entryPath);
484
+ if (stat.mtimeMs >= cutoff) return void 0;
485
+ if (!stat.isDirectory()) {
486
+ if (stat.isFile() && entryPath.endsWith(".jsonl")) files.push(entryPath);
487
+ return files;
488
+ }
489
+ for (const name of fs2.readdirSync(entryPath)) {
490
+ if (!idleSessionFiles(path2.join(entryPath, name), cutoff, files)) return void 0;
491
+ }
492
+ return files;
493
+ }
494
+ function asyncRunActive(runId) {
495
+ try {
496
+ const state = readStatus(path2.join(DIRS.async, runId))?.state;
497
+ return state === "queued" || state === "running";
498
+ } catch {
499
+ return true;
500
+ }
501
+ }
502
+ function missingForkCopyNote(sessionFile) {
503
+ if (path2.basename(path2.dirname(path2.dirname(sessionFile))) !== "forks") return "";
504
+ return ". It was a forked child's copy of the parent session; such copies are deleted once nothing has written to them for artifactConfig.cleanupDays days (default 7).";
505
+ }
506
+
507
+ export {
508
+ canonicalSessionId,
509
+ inspectSessionLease,
510
+ PROJECT_SUBAGENTS_RELATIVE_DIR,
511
+ getProjectArtifactPackagingWarning,
512
+ getProjectSubagentsDir,
513
+ getArtifactsDir,
514
+ getArtifactPaths,
515
+ ensureArtifactsDir,
516
+ writeArtifact,
517
+ formatOutputArtifactContent,
518
+ writeMetadata,
519
+ appendJsonl,
520
+ cleanupOldArtifacts,
521
+ cleanupAllArtifactDirs,
522
+ missingForkCopyNote
523
+ };
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  requestAsyncStop
3
- } from "./chunk-VFUFOZBU.js";
3
+ } from "./chunk-W6HIYD2Z.js";
4
4
  import "./chunk-NIXWDZZV.js";
5
- import "./chunk-C3KWLXDH.js";
5
+ import "./chunk-4MVDMA5C.js";
6
6
  import "./chunk-JEZOSEWG.js";
7
7
  import "./chunk-YFCK7H2S.js";
8
8
  import "./chunk-QXASAHIA.js";
package/bundle/index.js CHANGED
@@ -17,7 +17,7 @@ function readInstalledPackageVersion() {
17
17
  var loadedPackageVersion = readInstalledPackageVersion();
18
18
 
19
19
  // index.ts
20
- var registerExtension = process.env[HERDR_PI_MODE_ENV] === "1" ? (await import("./chunk-NJTSXIMG.js")).default : process.env.PI_SUBAGENT_CHILD === "1" ? void 0 : (await import("./chunk-NMYBVCGP.js")).default;
20
+ var registerExtension = process.env[HERDR_PI_MODE_ENV] === "1" ? (await import("./chunk-JQTHG2ID.js")).default : process.env.PI_SUBAGENT_CHILD === "1" ? void 0 : (await import("./chunk-CGWNA6EJ.js")).default;
21
21
  function registerSubagentExtension(pi) {
22
22
  const installedVersion = readInstalledPackageVersion();
23
23
  if (installedVersion !== loadedPackageVersion) {
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  resolveIntercomSessionTarget
3
- } from "./chunk-ESWW6XSX.js";
3
+ } from "./chunk-47ZN7NKR.js";
4
4
  import "./chunk-7F6RKT6W.js";
5
- import "./chunk-C3KWLXDH.js";
5
+ import "./chunk-4MVDMA5C.js";
6
6
  import "./chunk-JEZOSEWG.js";
7
7
  import "./chunk-YFCK7H2S.js";
8
8
  import "./chunk-QXASAHIA.js";
@@ -2,22 +2,22 @@ import {
2
2
  buildEffectiveSystemPrompt,
3
3
  canPreferForkFromSnapshot,
4
4
  resolveSubagentLaunchContext
5
- } from "./chunk-HTI7DD5D.js";
6
- import "./chunk-USRX7QXD.js";
5
+ } from "./chunk-V7SZMS6W.js";
6
+ import "./chunk-XIA5GSEU.js";
7
7
  import {
8
8
  loadConfig
9
- } from "./chunk-M2VBGET6.js";
9
+ } from "./chunk-RMZAAXIR.js";
10
10
  import {
11
11
  nestedResultsPath,
12
12
  processTerminalCandidatePath,
13
13
  processTerminalPath,
14
14
  resultFilePath
15
- } from "./chunk-PGU4TZV3.js";
15
+ } from "./chunk-CPSUJHZE.js";
16
16
  import {
17
17
  applyIntercomBridgeToAgent,
18
18
  resolveIntercomBridge,
19
19
  validateIntercomBridgeConfig
20
- } from "./chunk-ESWW6XSX.js";
20
+ } from "./chunk-47ZN7NKR.js";
21
21
  import {
22
22
  AGENT_DEFINITION_PROJECTION_VERSION,
23
23
  resolveLaunchBinding,
@@ -26,15 +26,15 @@ import {
26
26
  import {
27
27
  applyThinkingSuffix,
28
28
  resolvePiLaunchToolPlan
29
- } from "./chunk-SIAQXPJ4.js";
29
+ } from "./chunk-D32H53HM.js";
30
30
  import {
31
31
  assertRequiredChildExtensionsAdmitted,
32
32
  resolveRequiredChildExtensions
33
- } from "./chunk-CTPAE36Y.js";
33
+ } from "./chunk-YARY7JWU.js";
34
34
  import {
35
35
  getArtifactPaths,
36
36
  getArtifactsDir
37
- } from "./chunk-XSDYTXHF.js";
37
+ } from "./chunk-YDZ7BZD5.js";
38
38
  import {
39
39
  assertClaudeCodeModelScope,
40
40
  assertThinkingWithinCeiling,
@@ -61,7 +61,7 @@ import {
61
61
  resolveSkillsWithFallback,
62
62
  resolveStepBehavior,
63
63
  unknownAgentDiagnosticContext
64
- } from "./chunk-C3KWLXDH.js";
64
+ } from "./chunk-4MVDMA5C.js";
65
65
  import {
66
66
  DIRS,
67
67
  SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
@@ -8,10 +8,10 @@ import {
8
8
  openProjectPane,
9
9
  projectPaneBindingPath,
10
10
  readProjectPaneBinding
11
- } from "./chunk-3CVOAS77.js";
11
+ } from "./chunk-2DIEL4WG.js";
12
12
  import "./chunk-7J4ZXMY7.js";
13
- import "./chunk-XSDYTXHF.js";
14
- import "./chunk-C3KWLXDH.js";
13
+ import "./chunk-YDZ7BZD5.js";
14
+ import "./chunk-4MVDMA5C.js";
15
15
  import "./chunk-JEZOSEWG.js";
16
16
  import "./chunk-YFCK7H2S.js";
17
17
  import "./chunk-QXASAHIA.js";
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  registerRequiredChildExtensions
3
- } from "./chunk-CTPAE36Y.js";
3
+ } from "./chunk-YARY7JWU.js";
4
4
  export {
5
5
  registerRequiredChildExtensions
6
6
  };
package/docs/agents.md CHANGED
@@ -591,9 +591,11 @@ Examples:
591
591
 
592
592
  ### MCP tools
593
593
 
594
- When [pi-mcp-adapter](https://github.com/nicobailon/pi-mcp-adapter) is not installed, `mcp:server` and `mcp:server/tool` entries resolve against Pi's built-in MCP. Name the server and tool as the server reports them: `mcp:my-docs/get-item` selects the tool Pi registers as `mcp__my_docs__get_item`. The server part may also use the `-`→`_` form of its name that Pi's MCP namespace uses, such as `mcp:my_docs`. The child connects the servers in Pi's `mcp.json` (the project's `.pi/mcp.json` only when the parent trusts the project) and gets only the selected tools, as direct tools, whatever exposure the server is configured with; tools configured as `hidden` cannot be selected. Servers that an extension adds with `pi.registerMcpServer()` work in background children, because the registering extension loads there too. They do not work in foreground children, which load no ambient extensions, so a foreground launch that selects one fails and says to use `async: true`. The child waits for the selected servers' current MCP connection attempts before its first prompt, then rejects the launch if any selected tool is missing or not available as a direct tool. Pi's MCP request timeout still bounds each connection; stopping, interrupting, timing out, or shutting down the child cancels the startup wait. An unrelated server does not delay this check.
594
+ When [pi-mcp-adapter](https://github.com/nicobailon/pi-mcp-adapter) is not installed, `mcp:server` and `mcp:server/tool` entries resolve against Pi's built-in MCP. Name the server and tool as the server reports them: `mcp:my-docs/get-item` selects the tool Pi registers as `mcp__my_docs__get_item`. The server part may also use the `-`→`_` form of its name that Pi's MCP namespace uses, such as `mcp:my_docs`. The child connects the servers in Pi's `mcp.json` (the project's `.pi/mcp.json` only when the parent trusts the project) and gets only the selected tools, as direct tools, whatever exposure the server is configured with; tools configured as `hidden` cannot be selected. Servers that an extension adds with `pi.registerMcpServer()` work in background children, because the registering extension loads there too. Foreground children load no ambient extensions, so they get only the servers their required child extensions (see Required host extensions) register, and a foreground launch that selects a server from any other extension fails and says to use `async: true`. The child waits for the selected servers' current MCP connection attempts before its first prompt, then rejects the launch if any selected tool is missing or not available as a direct tool. Pi's MCP request timeout still bounds each connection; stopping, interrupting, timing out, or shutting down the child cancels the startup wait. An unrelated server does not delay this check.
595
595
 
596
- When pi-mcp-adapter is installed, it keeps priority and provides the direct MCP tools. Subagents only receive direct MCP tools when `mcp:` entries are listed in their frontmatter; global `directTools: true` in the adapter's MCP config is not enough by itself. The generic `mcp` proxy tool can still be used for discovery when available. The adapter caches tool metadata at startup, so after connecting a new MCP server for the first time, restart Pi before relying on direct tools. Server `includeTools` and `excludeTools` policies are enforced while resolving cached metadata for children: both accept exact names and `*`/`?` glob patterns against raw, generated-resource, and server/short/mcp/none-prefixed names, with `excludeTools` taking precedence. `mcp:` entries must name servers from the adapter's configuration files. A server that exists only in the adapter's runtime snapshot (registered at runtime, not persisted) cannot be provided to a child: children are pi sessions inside the parent or the runner process, not `pi` processes that could receive an MCP config argument, so such a launch fails with an error saying that MCP tools must come from an ambient adapter extension in a background child. An `mcp:` entry named `subagent` does not authorize nested fanout; declare the builtin `subagent` tool or set `allowNestedSubagents: true`. If a resolved direct MCP name is missing from the child registry, pi-subagents keeps the launch failed under the strict allowlist and reports the registration mismatch; check the resolved names against what the host or pi-mcp-adapter actually registers before child startup.
596
+ When pi-mcp-adapter is installed, it keeps priority and provides the direct MCP tools. A background child with omitted `tools` and no capability ceiling uses the adapter's configured direct tools, including `directTools: true`. This also applies to agents that set only `excludeTools`: the child loads the configured tools, then excludes the listed names.
597
+
598
+ With an explicit `tools` allowlist, include `mcp:` entries for the direct MCP tools the child needs. A capability ceiling continues to restrict the child's MCP selections. The generic `mcp` proxy tool can still be used for discovery when available. The adapter caches tool metadata at startup, so after connecting a new MCP server for the first time, restart Pi before relying on direct tools. Selectors for servers explicitly configured with `disabled: true` are skipped; unknown servers and enabled servers without matching cached tools still fail the launch. Server `includeTools` and `excludeTools` policies are enforced while resolving cached metadata for children: both accept exact names and `*`/`?` glob patterns against raw, generated-resource, and server/short/mcp/none-prefixed names, with `excludeTools` taking precedence. `mcp:` entries must name servers from the adapter's configuration files. A server that exists only in the adapter's runtime snapshot (registered at runtime, not persisted) cannot be provided to a child: children are pi sessions inside the parent or the runner process, not `pi` processes that could receive an MCP config argument, so such a launch fails with an error saying that MCP tools must come from an ambient adapter extension in a background child. An `mcp:` entry named `subagent` does not authorize nested fanout; declare the builtin `subagent` tool or set `allowNestedSubagents: true`. If a resolved direct MCP name is missing from the child registry, pi-subagents keeps the launch failed under the strict allowlist and reports the registration mismatch; check the resolved names against what the host or pi-mcp-adapter actually registers before child startup.
597
599
 
598
600
  ### Extension loading
599
601