@xzzpig/pi-subagents 0.24.2 → 0.25.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 (258) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/bundle/agent-management.js +4 -4
  3. package/bundle/agents.js +3 -3
  4. package/bundle/child-tool-plan.js +2 -2
  5. package/bundle/chunk-34TUUBRN.js +1107 -0
  6. package/bundle/{chunk-SW2VMNIU.js → chunk-5OD3OWTE.js} +2 -2
  7. package/bundle/{chunk-XWWUDWUW.js → chunk-5YEOWNSD.js} +371 -135
  8. package/bundle/{chunk-EUPJB4S7.js → chunk-5Z7JAORM.js} +196 -1219
  9. package/bundle/{chunk-LCDJWBVM.js → chunk-66JNFRFS.js} +1 -1
  10. package/bundle/{chunk-4UH4WS4G.js → chunk-6MNRKUHY.js} +23 -12
  11. package/bundle/{chunk-ED55MIC2.js → chunk-CGFF4WA3.js} +42 -19
  12. package/bundle/{chunk-TMHVDPYW.js → chunk-DLVPMML3.js} +263 -154
  13. package/bundle/chunk-HXRB42AF.js +108 -0
  14. package/bundle/{chunk-355ECEP2.js → chunk-IH7LQVEE.js} +29 -14
  15. package/bundle/{chunk-CYY5UMJU.js → chunk-IJWITCC6.js} +411 -249
  16. package/bundle/{chunk-RU522D5W.js → chunk-IKFKH5EL.js} +369 -50
  17. package/bundle/{chunk-Z6TFJ6BR.js → chunk-INWSUNI6.js} +1 -1
  18. package/bundle/{chunk-JEA2ZKUA.js → chunk-IUDEI6FJ.js} +35 -200
  19. package/bundle/{chunk-WW76JRIX.js → chunk-JAXVBXGF.js} +1 -1
  20. package/bundle/{chunk-ICNYIALB.js → chunk-JH5H4CYJ.js} +784 -474
  21. package/bundle/{chunk-35GII5EF.js → chunk-JWFLPSTP.js} +41 -117
  22. package/bundle/{chunk-224WMDIV.js → chunk-KCJFGKVK.js} +350 -123
  23. package/bundle/{chunk-RB4GELQA.js → chunk-LPJEKHOY.js} +1 -1
  24. package/bundle/chunk-LYKG4FKH.js +523 -0
  25. package/bundle/{chunk-X6LOM3Z4.js → chunk-LZ3HBDTR.js} +161 -78
  26. package/bundle/{chunk-FG6SQJAR.js → chunk-OGPOCGWX.js} +24 -6
  27. package/bundle/{chunk-BQ2OAB4Q.js → chunk-OSVXFWPG.js} +67 -30
  28. package/bundle/{chunk-FJWI64H7.js → chunk-RMSABUN3.js} +27 -13
  29. package/bundle/{chunk-H36HBZB2.js → chunk-SJPABBZG.js} +2 -2
  30. package/bundle/{chunk-3U633XDZ.js → chunk-U3ZDUUTM.js} +11 -3
  31. package/bundle/{chunk-LVWU2HOO.js → chunk-ULGMXABL.js} +16 -7
  32. package/bundle/{chunk-WPW4V6HM.js → chunk-W7ZA6TYD.js} +2 -2
  33. package/bundle/{chunk-V2KFIGFH.js → chunk-XAC2XNAP.js} +503 -304
  34. package/bundle/{chunk-O4D5PBVI.js → chunk-YWXILP5N.js} +3 -2
  35. package/bundle/control-channel.js +2 -2
  36. package/bundle/index.js +1 -1
  37. package/bundle/intercom-bridge.js +2 -2
  38. package/bundle/preflight.js +12 -10
  39. package/bundle/project-panes.js +3 -3
  40. package/bundle/workflow-resources.js +1 -1
  41. package/docs/agents.md +27 -6
  42. package/docs/configuration.md +20 -8
  43. package/docs/extension-api.md +18 -1
  44. package/docs/models.md +6 -2
  45. package/docs/observability.md +2 -0
  46. package/docs/tool-reference.md +7 -1
  47. package/docs/workflows.md +30 -2
  48. package/package.json +2 -2
  49. package/skills/pi-subagents/SKILL.md +15 -6
  50. package/skills/pi-subagents/references/prompting-and-roles.md +1 -0
  51. package/src/agents/agent-management.d.ts +1 -0
  52. package/src/agents/agent-management.js +46 -18
  53. package/src/agents/agent-memory.d.ts +1 -4
  54. package/src/agents/agent-memory.js +1 -4
  55. package/src/agents/agent-serializer.d.ts +2 -0
  56. package/src/agents/agent-serializer.js +1 -1
  57. package/src/agents/agents.d.ts +2 -3
  58. package/src/agents/agents.js +46 -20
  59. package/src/agents/frontmatter.js +1 -8
  60. package/src/agents/global-npm-root.d.ts +1 -0
  61. package/src/agents/global-npm-root.js +11 -3
  62. package/src/agents/skills.d.ts +0 -3
  63. package/src/agents/skills.js +0 -3
  64. package/src/api/preflight.d.ts +3 -1
  65. package/src/api/preflight.js +2 -0
  66. package/src/extension/config.d.ts +1 -0
  67. package/src/extension/config.js +13 -1
  68. package/src/extension/herdr-pi-bridge.js +10 -2
  69. package/src/extension/index.d.ts +0 -13
  70. package/src/extension/index.js +51 -37
  71. package/src/extension/public-execution.d.ts +1 -0
  72. package/src/extension/public-execution.js +4 -0
  73. package/src/extension/reply-workflow-script.js +24 -4
  74. package/src/extension/schemas.d.ts +12 -3
  75. package/src/extension/schemas.js +7 -3
  76. package/src/extension/session-switch.d.ts +25 -0
  77. package/src/extension/session-switch.js +138 -0
  78. package/src/extension/subagent-guide.d.ts +1 -1
  79. package/src/extension/subagent-guide.js +1 -1
  80. package/src/extension/subagent-launch-tool.d.ts +25 -0
  81. package/src/extension/subagent-launch-tool.js +48 -0
  82. package/src/extension/tool-activation.js +55 -15
  83. package/src/extension/tool-description.d.ts +1 -1
  84. package/src/extension/tool-description.js +14 -8
  85. package/src/inspectors/herdr/actions.d.ts +0 -1
  86. package/src/inspectors/herdr/actions.js +0 -1
  87. package/src/inspectors/session-roots-codec.d.ts +0 -1
  88. package/src/inspectors/session-roots-codec.js +0 -1
  89. package/src/inspectors/tmux/actions.d.ts +0 -1
  90. package/src/inspectors/tmux/actions.js +0 -1
  91. package/src/integrations/herdr-status.js +3 -8
  92. package/src/intercom/native-supervisor-channel.js +65 -9
  93. package/src/runs/background/async-execution.d.ts +7 -10
  94. package/src/runs/background/async-execution.js +66 -29
  95. package/src/runs/background/async-job-tracker.js +12 -0
  96. package/src/runs/background/async-resume.d.ts +2 -1
  97. package/src/runs/background/async-resume.js +114 -40
  98. package/src/runs/background/async-retention.d.ts +0 -2
  99. package/src/runs/background/async-retention.js +17 -6
  100. package/src/runs/background/async-status.d.ts +2 -0
  101. package/src/runs/background/async-status.js +4 -0
  102. package/src/runs/background/auto-drain.js +2 -1
  103. package/src/runs/background/boot-id.d.ts +1 -3
  104. package/src/runs/background/boot-id.js +1 -3
  105. package/src/runs/background/completion-batcher.d.ts +3 -4
  106. package/src/runs/background/completion-batcher.js +2 -3
  107. package/src/runs/background/control-channel.d.ts +0 -6
  108. package/src/runs/background/control-channel.js +0 -6
  109. package/src/runs/background/fleet-view.js +2 -3
  110. package/src/runs/background/notify.d.ts +0 -2
  111. package/src/runs/background/notify.js +0 -2
  112. package/src/runs/background/result-watcher.d.ts +1 -0
  113. package/src/runs/background/result-watcher.js +59 -29
  114. package/src/runs/background/resume-guidance.js +4 -2
  115. package/src/runs/background/retained-children.js +2 -1
  116. package/src/runs/background/run-child-session.d.ts +2 -3
  117. package/src/runs/background/run-child-session.js +5 -8
  118. package/src/runs/background/run-status.js +9 -7
  119. package/src/runs/background/runner-aliases.js +15 -0
  120. package/src/runs/background/scheduled-runs.d.ts +3 -1
  121. package/src/runs/background/scheduled-runs.js +13 -16
  122. package/src/runs/background/steering.d.ts +2 -11
  123. package/src/runs/background/steering.js +11 -6
  124. package/src/runs/background/subagent-runner.d.ts +2 -6
  125. package/src/runs/background/subagent-runner.js +88 -70
  126. package/src/runs/background/subagent-wait.js +12 -15
  127. package/src/runs/background/wait-config.d.ts +2 -0
  128. package/src/runs/background/wait-config.js +17 -3
  129. package/src/runs/background/wait-subscriptions.js +124 -12
  130. package/src/runs/background/wait-tool.js +4 -2
  131. package/src/runs/background/workflow-terminal-proof.d.ts +0 -1
  132. package/src/runs/background/workflow-terminal-proof.js +0 -1
  133. package/src/runs/foreground/async-steering-action.js +24 -9
  134. package/src/runs/foreground/async-stop-action.d.ts +1 -1
  135. package/src/runs/foreground/async-stop-action.js +9 -1
  136. package/src/runs/foreground/execution.d.ts +0 -3
  137. package/src/runs/foreground/execution.js +56 -24
  138. package/src/runs/foreground/prompt-audit.js +1 -0
  139. package/src/runs/foreground/subagent-executor.d.ts +5 -10
  140. package/src/runs/foreground/subagent-executor.js +164 -49
  141. package/src/runs/shared/acceptance.js +69 -26
  142. package/src/runs/shared/async-status-projection.d.ts +2 -0
  143. package/src/runs/shared/async-status-projection.js +10 -0
  144. package/src/runs/shared/child-commands.js +15 -2
  145. package/src/runs/shared/child-hooks.d.ts +1 -7
  146. package/src/runs/shared/child-hooks.js +13 -5
  147. package/src/runs/shared/child-launch.js +6 -2
  148. package/src/runs/shared/child-runtime-config.d.ts +0 -1
  149. package/src/runs/shared/child-session.d.ts +6 -5
  150. package/src/runs/shared/child-session.js +85 -38
  151. package/src/runs/shared/child-tool-plan.d.ts +0 -1
  152. package/src/runs/shared/child-tool-plan.js +0 -1
  153. package/src/runs/shared/claude-code-adapter.js +11 -0
  154. package/src/runs/shared/external-cli-contract.d.ts +49 -0
  155. package/src/runs/shared/external-cli-contract.js +18 -13
  156. package/src/runs/shared/external-cli-runner.js +26 -6
  157. package/src/runs/shared/herdr-connection.js +2 -1
  158. package/src/runs/shared/herdr-pane-host.d.ts +2 -2
  159. package/src/runs/shared/herdr-pane-host.js +17 -1
  160. package/src/runs/shared/herdr-placed-run.js +51 -24
  161. package/src/runs/shared/lane-metadata.d.ts +0 -1
  162. package/src/runs/shared/lane-metadata.js +0 -1
  163. package/src/runs/shared/mcp-config-sources.d.ts +4 -1
  164. package/src/runs/shared/mcp-config-sources.js +1 -1
  165. package/src/runs/shared/mcp-direct-tool-allowlist.d.ts +0 -3
  166. package/src/runs/shared/mcp-direct-tool-allowlist.js +26 -17
  167. package/src/runs/shared/mcp-direct-tool-grant.js +8 -1
  168. package/src/runs/shared/model-resolution-diagnostic.d.ts +0 -1
  169. package/src/runs/shared/model-resolution.d.ts +20 -5
  170. package/src/runs/shared/model-resolution.js +55 -50
  171. package/src/runs/shared/model-scope.d.ts +1 -5
  172. package/src/runs/shared/model-scope.js +1 -5
  173. package/src/runs/shared/mutation-evidence.d.ts +1 -1
  174. package/src/runs/shared/mutation-evidence.js +52 -7
  175. package/src/runs/shared/nested-events.d.ts +1 -0
  176. package/src/runs/shared/nested-events.js +1 -1
  177. package/src/runs/shared/parallel-utils.d.ts +0 -1
  178. package/src/runs/shared/permissions.js +5 -3
  179. package/src/runs/shared/placement-host.d.ts +5 -1
  180. package/src/runs/shared/rex-pane-host.d.ts +0 -1
  181. package/src/runs/shared/rex-pane-host.js +0 -2
  182. package/src/runs/shared/run-launch-folder.d.ts +12 -0
  183. package/src/runs/shared/run-launch-folder.js +21 -0
  184. package/src/runs/shared/runner-launcher.d.ts +12 -1
  185. package/src/runs/shared/runner-launcher.js +16 -0
  186. package/src/runs/shared/single-output.d.ts +3 -3
  187. package/src/runs/shared/single-output.js +5 -3
  188. package/src/runs/shared/structured-output.d.ts +8 -0
  189. package/src/runs/shared/structured-output.js +40 -5
  190. package/src/runs/shared/subagent-prompt-runtime.d.ts +0 -1
  191. package/src/runs/shared/subagent-prompt-runtime.js +18 -4
  192. package/src/runs/shared/supervisor-wait-timer.d.ts +16 -0
  193. package/src/runs/shared/supervisor-wait-timer.js +61 -0
  194. package/src/runs/shared/tool-timeout.js +2 -1
  195. package/src/runs/shared/worktree-cleanup-plan.d.ts +0 -1
  196. package/src/runs/shared/worktree-cleanup-plan.js +0 -1
  197. package/src/runs/shared/worktree.d.ts +3 -0
  198. package/src/runs/shared/worktree.js +20 -0
  199. package/src/shared/artifacts.d.ts +1 -0
  200. package/src/shared/artifacts.js +132 -22
  201. package/src/shared/capacity-resilient-json.d.ts +1 -1
  202. package/src/shared/child-cache-retention.d.ts +1 -2
  203. package/src/shared/child-cache-retention.js +1 -2
  204. package/src/shared/fleet-transcript-reader.d.ts +51 -0
  205. package/src/shared/fleet-transcript-reader.js +333 -0
  206. package/src/shared/formatters.d.ts +0 -18
  207. package/src/shared/formatters.js +0 -18
  208. package/src/shared/pruned-fork.js +2 -2
  209. package/src/shared/reported-progress.d.ts +1 -0
  210. package/src/shared/reported-progress.js +12 -0
  211. package/src/shared/session-succession.d.ts +16 -1
  212. package/src/shared/session-succession.js +41 -2
  213. package/src/shared/session-warnings.d.ts +7 -0
  214. package/src/shared/session-warnings.js +26 -0
  215. package/src/shared/settings.d.ts +0 -23
  216. package/src/shared/settings.js +3 -35
  217. package/src/shared/status-format.d.ts +1 -0
  218. package/src/shared/status-format.js +1 -1
  219. package/src/shared/types.d.ts +108 -59
  220. package/src/shared/types.js +0 -12
  221. package/src/shared/utils.d.ts +3 -15
  222. package/src/shared/utils.js +4 -22
  223. package/src/shared/wait-tool-name.d.ts +8 -0
  224. package/src/shared/wait-tool-name.js +13 -0
  225. package/src/slash/slash-commands.js +2 -1
  226. package/src/slash/subagent-cost.d.ts +3 -2
  227. package/src/slash/subagent-cost.js +22 -3
  228. package/src/slash/subagents-admin.js +0 -1
  229. package/src/tui/fleet-status.d.ts +0 -5
  230. package/src/tui/fleet-status.js +4 -24
  231. package/src/tui/fleet.js +6 -4
  232. package/src/tui/render.d.ts +0 -9
  233. package/src/tui/render.js +194 -68
  234. package/src/tui/subagent-messages.js +3 -2
  235. package/src/watchdog/model-selection.js +2 -2
  236. package/src/watchdog/permission-arbiter.js +1 -0
  237. package/src/watchdog/register-child.d.ts +2 -3
  238. package/src/watchdog/register-child.js +2 -3
  239. package/src/watchdog/review.d.ts +0 -5
  240. package/src/watchdog/review.js +4 -3
  241. package/src/watchdog/turn-delta.js +2 -1
  242. package/src/workflows/scripted-workflow.d.ts +2 -0
  243. package/src/workflows/scripted-workflow.js +344 -59
  244. package/src/workflows/structured-workflow-scripts.d.ts +4 -3
  245. package/src/workflows/structured-workflow-scripts.js +32 -11
  246. package/src/workflows/workflow-launch-record.d.ts +15 -6
  247. package/src/workflows/workflow-launch-record.js +30 -12
  248. package/src/workflows/workflow-receipt.js +36 -53
  249. package/src/workflows/workflow-resources.js +4 -4
  250. package/src/workflows/workflow-resume-claim.d.ts +2 -0
  251. package/src/workflows/workflow-resume-claim.js +3 -3
  252. package/src/workflows/workflow-resume.d.ts +1 -1
  253. package/src/workflows/workflow-resume.js +13 -8
  254. package/src/workflows/workflow-script-worker.d.ts +13 -0
  255. package/src/workflows/workflow-script-worker.js +81 -0
  256. package/workflow-script-process.cjs +36 -0
  257. package/workflow-script-worker.cjs +4 -1
  258. package/bundle/chunk-U4ODUYAG.js +0 -235
@@ -4,7 +4,7 @@ import {
4
4
  import {
5
5
  resolveWatchPath,
6
6
  writeAtomicJson
7
- } from "./chunk-V2KFIGFH.js";
7
+ } from "./chunk-XAC2XNAP.js";
8
8
  import {
9
9
  POLL_INTERVAL_MS
10
10
  } from "./chunk-UQDHXMUG.js";
@@ -0,0 +1,523 @@
1
+ import {
2
+ createAtomicJsonWriter,
3
+ getAgentDir,
4
+ readStatus
5
+ } from "./chunk-XAC2XNAP.js";
6
+ import {
7
+ DIRS,
8
+ TEMP_ARTIFACTS_DIR,
9
+ TEMP_ROOT_DIR
10
+ } from "./chunk-UQDHXMUG.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
+ };