pi-fabric 0.129.2 → 0.130.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 (195) hide show
  1. package/dist/actors/binding-store.d.ts.map +1 -1
  2. package/dist/actors/registry-store.d.ts.map +1 -1
  3. package/dist/agents/manager.d.ts +9 -0
  4. package/dist/agents/manager.d.ts.map +1 -1
  5. package/dist/agents/request.d.ts.map +1 -1
  6. package/dist/agents/types.d.ts +2 -0
  7. package/dist/agents/types.d.ts.map +1 -1
  8. package/dist/agents/worker-recovery.d.ts +75 -0
  9. package/dist/agents/worker-recovery.d.ts.map +1 -0
  10. package/dist/agents.js +1 -1
  11. package/dist/audit/details.d.ts +31 -0
  12. package/dist/audit/details.d.ts.map +1 -1
  13. package/dist/audit/projection.d.ts.map +1 -1
  14. package/dist/chunks/{chunk-N3SSXCEC.js → chunk-3MOY6WIB.js} +4 -4
  15. package/dist/chunks/chunk-3MOY6WIB.js.map +7 -0
  16. package/dist/chunks/{chunk-X7GHEK6O.js → chunk-4BYS4ZLY.js} +4 -4
  17. package/dist/chunks/{chunk-GW25FXU4.js → chunk-6C2DMTQC.js} +768 -314
  18. package/dist/chunks/chunk-6C2DMTQC.js.map +7 -0
  19. package/dist/chunks/{chunk-BUJOFUEB.js → chunk-6O6UWMBO.js} +2 -2
  20. package/dist/chunks/chunk-6OGYPHNQ.js +62 -0
  21. package/dist/chunks/chunk-6OGYPHNQ.js.map +7 -0
  22. package/dist/chunks/{chunk-NUU6IUJU.js → chunk-7YNE4NB2.js} +2 -2
  23. package/dist/chunks/{chunk-NTC2MCB6.js → chunk-B5L3X3ID.js} +1 -1
  24. package/dist/chunks/{chunk-NTC2MCB6.js.map → chunk-B5L3X3ID.js.map} +1 -1
  25. package/dist/chunks/{chunk-GJ43CMF4.js → chunk-CH2QMORW.js} +2 -2
  26. package/dist/chunks/{chunk-52NENK4H.js → chunk-CXYJJ3HZ.js} +3 -3
  27. package/dist/chunks/{chunk-4I7SW4F7.js → chunk-D5224P2R.js} +2 -1
  28. package/dist/chunks/chunk-D5224P2R.js.map +7 -0
  29. package/dist/chunks/{chunk-IOPDT6GA.js → chunk-EYHTTMSM.js} +141 -89
  30. package/dist/chunks/chunk-EYHTTMSM.js.map +7 -0
  31. package/dist/chunks/{chunk-N2J2TCYZ.js → chunk-F4HL6KJR.js} +24 -11
  32. package/dist/chunks/chunk-F4HL6KJR.js.map +7 -0
  33. package/dist/chunks/chunk-F6A6MQ6G.js +609 -0
  34. package/dist/chunks/chunk-F6A6MQ6G.js.map +7 -0
  35. package/dist/chunks/{chunk-E4D5FUHX.js → chunk-FCLVPCPN.js} +137 -26
  36. package/dist/chunks/chunk-FCLVPCPN.js.map +7 -0
  37. package/dist/chunks/{chunk-C6C4ER5J.js → chunk-HSEZPCL5.js} +7 -1
  38. package/dist/chunks/chunk-HSEZPCL5.js.map +7 -0
  39. package/dist/chunks/{chunk-DIAXZTLV.js → chunk-JJXUOXI5.js} +28 -5
  40. package/dist/chunks/chunk-JJXUOXI5.js.map +7 -0
  41. package/dist/chunks/{chunk-OI43UUG5.js → chunk-K3ZWBUUL.js} +10 -7
  42. package/dist/chunks/chunk-K3ZWBUUL.js.map +7 -0
  43. package/dist/chunks/{chunk-L3OOZ5TJ.js → chunk-MSDL7U6Q.js} +3 -3
  44. package/dist/chunks/chunk-N7ZAK2PB.js +132 -0
  45. package/dist/chunks/chunk-N7ZAK2PB.js.map +7 -0
  46. package/dist/chunks/{chunk-EB7JMNJY.js → chunk-NF6W327N.js} +7 -1
  47. package/dist/chunks/{chunk-EB7JMNJY.js.map → chunk-NF6W327N.js.map} +2 -2
  48. package/dist/chunks/{chunk-2EJDNTAU.js → chunk-NQ7IWEIF.js} +2 -2
  49. package/dist/chunks/{chunk-IXOPBWQ5.js → chunk-ROPY7LYT.js} +6 -4
  50. package/dist/chunks/{chunk-IXOPBWQ5.js.map → chunk-ROPY7LYT.js.map} +2 -2
  51. package/dist/chunks/{chunk-63NMKXIG.js → chunk-SBAROA4Y.js} +17 -1
  52. package/dist/chunks/chunk-SBAROA4Y.js.map +7 -0
  53. package/dist/chunks/{chunk-7CLTT7FD.js → chunk-TJZYM2SP.js} +66 -99
  54. package/dist/chunks/chunk-TJZYM2SP.js.map +7 -0
  55. package/dist/chunks/chunk-WKFRGICG.js +101 -0
  56. package/dist/chunks/chunk-WKFRGICG.js.map +7 -0
  57. package/dist/chunks/{chunk-OP6CWP4N.js → chunk-WQFG7ZVC.js} +18 -2
  58. package/dist/chunks/chunk-WQFG7ZVC.js.map +7 -0
  59. package/dist/chunks/{chunk-3UFN4LKG.js → chunk-WTIF3MIM.js} +12 -10
  60. package/dist/chunks/chunk-WTIF3MIM.js.map +7 -0
  61. package/dist/chunks/{chunk-36GLBMUN.js → chunk-YTYLKL3Z.js} +6 -6
  62. package/dist/cli/decisions.js +2 -2
  63. package/dist/cli/mesh.js +3 -3
  64. package/dist/commands/fabric-handler.js +2 -2
  65. package/dist/compaction/claim-events.js +2 -2
  66. package/dist/components/configuration.js +3 -3
  67. package/dist/config.d.ts +14 -0
  68. package/dist/config.d.ts.map +1 -1
  69. package/dist/core/action-policy-hooks.d.ts +69 -0
  70. package/dist/core/action-policy-hooks.d.ts.map +1 -0
  71. package/dist/core/action-registry.d.ts +3 -1
  72. package/dist/core/action-registry.d.ts.map +1 -1
  73. package/dist/core/action-registry.js +5 -4
  74. package/dist/core/approval-controller.d.ts +18 -4
  75. package/dist/core/approval-controller.d.ts.map +1 -1
  76. package/dist/core/atomic-write.d.ts +143 -2
  77. package/dist/core/atomic-write.d.ts.map +1 -1
  78. package/dist/core/child-tool-allowlist.d.ts +11 -0
  79. package/dist/core/child-tool-allowlist.d.ts.map +1 -1
  80. package/dist/core/file-lock.d.ts.map +1 -1
  81. package/dist/core/provider-operations.js +4 -4
  82. package/dist/durable/agent.d.ts.map +1 -1
  83. package/dist/durable/session.d.ts.map +1 -1
  84. package/dist/durable/worker-host.d.ts.map +1 -1
  85. package/dist/durable/worker-host.js +16 -3
  86. package/dist/durable/worker-host.js.map +2 -2
  87. package/dist/durable/worker-options.d.ts +1 -0
  88. package/dist/durable/worker-options.d.ts.map +1 -1
  89. package/dist/durable/worker.js +4 -1
  90. package/dist/durable/worker.js.map +2 -2
  91. package/dist/entropy/index.js +6 -5
  92. package/dist/execution-service.d.ts +3 -0
  93. package/dist/execution-service.d.ts.map +1 -1
  94. package/dist/extension-bootstrap.d.ts.map +1 -1
  95. package/dist/extension-bootstrap.js +11 -9
  96. package/dist/extension-bootstrap.js.map +1 -1
  97. package/dist/extension.d.ts.map +1 -1
  98. package/dist/fabric-exec-tool.d.ts.map +1 -1
  99. package/dist/fabric-runtime-state.d.ts +2 -0
  100. package/dist/fabric-runtime-state.d.ts.map +1 -1
  101. package/dist/fabric-runtime-state.js +125 -42
  102. package/dist/fabric-runtime-state.js.map +2 -2
  103. package/dist/fabric-state.d.ts +3 -0
  104. package/dist/fabric-state.d.ts.map +1 -1
  105. package/dist/index.js +18 -12
  106. package/dist/index.js.map +1 -1
  107. package/dist/jev/manager.d.ts +3 -0
  108. package/dist/jev/manager.d.ts.map +1 -1
  109. package/dist/jev.js +3 -3
  110. package/dist/mesh/grants.d.ts +3 -3
  111. package/dist/mesh/grants.d.ts.map +1 -1
  112. package/dist/mesh/store.d.ts +8 -0
  113. package/dist/mesh/store.d.ts.map +1 -1
  114. package/dist/programs/host.js +2 -2
  115. package/dist/protocol.d.ts +23 -0
  116. package/dist/protocol.d.ts.map +1 -1
  117. package/dist/protocol.js +5 -1
  118. package/dist/providers/agents-actions.d.ts.map +1 -1
  119. package/dist/providers/agents-provider.d.ts.map +1 -1
  120. package/dist/providers/captured-tools-provider.d.ts +5 -0
  121. package/dist/providers/captured-tools-provider.d.ts.map +1 -1
  122. package/dist/providers/jev-provider.js +3 -3
  123. package/dist/providers/pi-tools-provider.d.ts +5 -0
  124. package/dist/providers/pi-tools-provider.d.ts.map +1 -1
  125. package/dist/residency/actor-client.js +3 -3
  126. package/dist/residency/client.d.ts.map +1 -1
  127. package/dist/residency/host.d.ts.map +1 -1
  128. package/dist/residency/host.js +9 -9
  129. package/dist/residency/launcher.js +1 -1
  130. package/dist/residency/pi-entry.js +9 -9
  131. package/dist/residency/protocol.d.ts +2 -0
  132. package/dist/residency/protocol.d.ts.map +1 -1
  133. package/dist/runtime/core-override-guest-types.js +2 -2
  134. package/dist/runtime/guest-types.d.ts +1 -1
  135. package/dist/runtime/guest-types.d.ts.map +1 -1
  136. package/dist/runtime/guest-types.js +1 -1
  137. package/dist/runtime/monty-runtime.js +2 -2
  138. package/dist/runtime/node-process-runtime.js +3 -3
  139. package/dist/runtime/quickjs-runtime.d.ts.map +1 -1
  140. package/dist/runtime/quickjs-runtime.js +1 -1
  141. package/dist/runtime/typescript-kernel.js +5 -5
  142. package/dist/topology/participant-directory.d.ts +15 -1
  143. package/dist/topology/participant-directory.d.ts.map +1 -1
  144. package/dist/topology/session-label.d.ts +2 -1
  145. package/dist/topology/session-label.d.ts.map +1 -1
  146. package/dist/topology/types.d.ts +27 -0
  147. package/dist/topology/types.d.ts.map +1 -1
  148. package/dist/type-error-guidance.js +1 -1
  149. package/dist/ui/conversation-native-reader.js +2 -2
  150. package/dist/ui/dashboard.js +1 -1
  151. package/dist/ui/fabric-render.d.ts +5 -0
  152. package/dist/ui/fabric-render.d.ts.map +1 -1
  153. package/dist/ui/settings-sections-lifecycle.d.ts.map +1 -1
  154. package/dist/ui/settings-values.d.ts +1 -0
  155. package/dist/ui/settings-values.d.ts.map +1 -1
  156. package/dist/ui/settings.js +7 -2
  157. package/dist/ui/settings.js.map +2 -2
  158. package/dist/ui/widget.d.ts.map +1 -1
  159. package/dist/worker.js +21 -0
  160. package/dist/worker.js.map +2 -2
  161. package/docs/agents.md +7 -1
  162. package/docs/configuration.md +65 -1
  163. package/docs/decisions.md +1 -0
  164. package/docs/durable-pi.md +76 -5
  165. package/docs/short-lock-protocol.md +90 -0
  166. package/docs/speculation.md +6 -0
  167. package/package.json +1 -1
  168. package/skillsets/typescript/fabric-exec/references/agents.md +1 -0
  169. package/dist/chunks/chunk-3UFN4LKG.js.map +0 -7
  170. package/dist/chunks/chunk-4I7SW4F7.js.map +0 -7
  171. package/dist/chunks/chunk-63NMKXIG.js.map +0 -7
  172. package/dist/chunks/chunk-7CLTT7FD.js.map +0 -7
  173. package/dist/chunks/chunk-C6C4ER5J.js.map +0 -7
  174. package/dist/chunks/chunk-DIAXZTLV.js.map +0 -7
  175. package/dist/chunks/chunk-E4D5FUHX.js.map +0 -7
  176. package/dist/chunks/chunk-ESGPDDLC.js +0 -244
  177. package/dist/chunks/chunk-ESGPDDLC.js.map +0 -7
  178. package/dist/chunks/chunk-GW25FXU4.js.map +0 -7
  179. package/dist/chunks/chunk-IOPDT6GA.js.map +0 -7
  180. package/dist/chunks/chunk-IZIBLVU2.js +0 -297
  181. package/dist/chunks/chunk-IZIBLVU2.js.map +0 -7
  182. package/dist/chunks/chunk-N2J2TCYZ.js.map +0 -7
  183. package/dist/chunks/chunk-N3SSXCEC.js.map +0 -7
  184. package/dist/chunks/chunk-OI43UUG5.js.map +0 -7
  185. package/dist/chunks/chunk-OP6CWP4N.js.map +0 -7
  186. package/dist/chunks/chunk-WJNGSG4M.js +0 -27
  187. package/dist/chunks/chunk-WJNGSG4M.js.map +0 -7
  188. /package/dist/chunks/{chunk-X7GHEK6O.js.map → chunk-4BYS4ZLY.js.map} +0 -0
  189. /package/dist/chunks/{chunk-BUJOFUEB.js.map → chunk-6O6UWMBO.js.map} +0 -0
  190. /package/dist/chunks/{chunk-NUU6IUJU.js.map → chunk-7YNE4NB2.js.map} +0 -0
  191. /package/dist/chunks/{chunk-GJ43CMF4.js.map → chunk-CH2QMORW.js.map} +0 -0
  192. /package/dist/chunks/{chunk-52NENK4H.js.map → chunk-CXYJJ3HZ.js.map} +0 -0
  193. /package/dist/chunks/{chunk-L3OOZ5TJ.js.map → chunk-MSDL7U6Q.js.map} +0 -0
  194. /package/dist/chunks/{chunk-2EJDNTAU.js.map → chunk-NQ7IWEIF.js.map} +0 -0
  195. /package/dist/chunks/{chunk-36GLBMUN.js.map → chunk-YTYLKL3Z.js.map} +0 -0
@@ -42,13 +42,10 @@ import {
42
42
  senderStamp,
43
43
  senderTrusted
44
44
  } from "./chunk-JKQARSWR.js";
45
- import {
46
- readChildToolAllowlist
47
- } from "./chunk-WJNGSG4M.js";
48
45
  import {
49
46
  ownedStat,
50
47
  processAlive
51
- } from "./chunk-NUU6IUJU.js";
48
+ } from "./chunk-7YNE4NB2.js";
52
49
  import {
53
50
  resolveAgentDir
54
51
  } from "./chunk-PBDDXBHY.js";
@@ -56,25 +53,28 @@ import {
56
53
  DEFAULT_FABRIC_CONFIG,
57
54
  MAX_AGENT_TIMEOUT_MS,
58
55
  MIN_AGENT_TIMEOUT_MS
59
- } from "./chunk-DIAXZTLV.js";
56
+ } from "./chunk-JJXUOXI5.js";
60
57
  import {
61
58
  readJsonlPage
62
59
  } from "./chunk-CGPK5WHX.js";
63
60
  import {
64
- SHORT_LOCK_MAX_HOLD_MS,
65
- encodeOwnerIdentityLine,
66
- lockOwnerLiveness,
67
- lockOwnerProvablyDead,
61
+ formatShortLockOwner,
68
62
  ownerHeartbeatFields,
69
63
  ownerIdentityFields,
70
64
  ownerLiveness,
71
- reapLockByRenameClaim,
65
+ reapStaleShortLock,
72
66
  recordOwnerLiveness,
67
+ releaseShortLock,
68
+ tryAcquireShortLock,
73
69
  writeJsonAtomic
74
- } from "./chunk-IZIBLVU2.js";
70
+ } from "./chunk-F6A6MQ6G.js";
75
71
  import {
76
72
  FABRIC_PEER_LABEL_SEQUENCE
77
- } from "./chunk-63NMKXIG.js";
73
+ } from "./chunk-SBAROA4Y.js";
74
+ import {
75
+ constrainChildToolSelection,
76
+ readChildToolAllowlist
77
+ } from "./chunk-6OGYPHNQ.js";
78
78
  import {
79
79
  AgentAdmission,
80
80
  FABRIC_LIFECYCLE_SUBSCRIPTION_PREFIX,
@@ -297,9 +297,9 @@ function appendBudgetLedger(file, entry) {
297
297
 
298
298
  // src/agents/manager.ts
299
299
  import { randomUUID as randomUUID4 } from "node:crypto";
300
- import fs11 from "node:fs";
300
+ import fs12 from "node:fs";
301
301
  import os3 from "node:os";
302
- import path12 from "node:path";
302
+ import path13 from "node:path";
303
303
  import { fileURLToPath } from "node:url";
304
304
 
305
305
  // src/agents/hosted-run.ts
@@ -784,6 +784,185 @@ var removeTree = async (target, rm = defaultRemove) => {
784
784
  }
785
785
  };
786
786
 
787
+ // src/agents/worker-recovery.ts
788
+ import { execFileSync } from "node:child_process";
789
+ import fs4 from "node:fs";
790
+ import path4 from "node:path";
791
+ import { isDeepStrictEqual } from "node:util";
792
+ var WORKER_RECOVERY_FILE = "worker-recovery.json";
793
+ var WORKER_RECOVERY_FORMAT = 1;
794
+ var MAX_ARGUMENTS = 4096;
795
+ var MAX_STRING = 1048576;
796
+ var WORKER_RECOVERY_MAX_BYTES = 8 * 1048576;
797
+ var boundedString = (value) => typeof value === "string" && value.length > 0 && value.length <= MAX_STRING;
798
+ var workerRecoveryPath = (runDirectory) => path4.join(runDirectory, WORKER_RECOVERY_FILE);
799
+ var writeWorkerRecovery = (runDirectory, record) => {
800
+ writeJsonAtomic(workerRecoveryPath(runDirectory), record, { mode: 384 });
801
+ };
802
+ var workerRecoveryAuthorityRoot = (runRoot) => `${path4.resolve(runRoot)}.worker-launch-authority`;
803
+ var authorityPath = (runDirectory) => path4.join(workerRecoveryAuthorityRoot(path4.dirname(runDirectory)), `${path4.basename(runDirectory)}.json`);
804
+ var authorizeWorkerRecovery = (runDirectory, recovery, policy) => {
805
+ fs4.mkdirSync(path4.dirname(authorityPath(runDirectory)), { recursive: true, mode: 448 });
806
+ writeJsonAtomic(authorityPath(runDirectory), { recovery, policy }, { mode: 384 });
807
+ };
808
+ var readWorkerRecoveryAuthority = (runDirectory, policy) => {
809
+ const content = readBounded(authorityPath(runDirectory));
810
+ if (!content) return void 0;
811
+ try {
812
+ const receipt = JSON.parse(content);
813
+ if (policy !== void 0 && receipt.policy !== policy) return void 0;
814
+ return parseWorkerRecovery(JSON.stringify(receipt.recovery), runDirectory);
815
+ } catch {
816
+ return void 0;
817
+ }
818
+ };
819
+ var removeWorkerRecovery = (runDirectory) => {
820
+ fs4.rmSync(workerRecoveryPath(runDirectory), { force: true });
821
+ fs4.rmSync(authorityPath(runDirectory), { force: true });
822
+ try {
823
+ fs4.rmdirSync(workerRecoveryAuthorityRoot(path4.dirname(runDirectory)));
824
+ } catch {
825
+ }
826
+ };
827
+ var hasWorkerRecovery = (runDirectory) => fs4.existsSync(workerRecoveryPath(runDirectory));
828
+ var readBounded = (file) => {
829
+ let descriptor;
830
+ try {
831
+ descriptor = fs4.openSync(file, fs4.constants.O_RDONLY | (fs4.constants.O_NOFOLLOW ?? 0) | (fs4.constants.O_NONBLOCK ?? 0));
832
+ const stat = fs4.fstatSync(descriptor);
833
+ if (!stat.isFile() || stat.size > WORKER_RECOVERY_MAX_BYTES) return void 0;
834
+ const buffer = Buffer.alloc(stat.size);
835
+ const bytes = fs4.readSync(descriptor, buffer, 0, buffer.length, 0);
836
+ return buffer.subarray(0, bytes).toString("utf8");
837
+ } catch {
838
+ return void 0;
839
+ } finally {
840
+ if (descriptor !== void 0) fs4.closeSync(descriptor);
841
+ }
842
+ };
843
+ var readWorkerRecovery = (runDirectory) => {
844
+ const content = readBounded(workerRecoveryPath(runDirectory));
845
+ if (content === void 0) return void 0;
846
+ return parseWorkerRecovery(content, runDirectory);
847
+ };
848
+ var parseWorkerRecovery = (content, runDirectory) => {
849
+ let raw;
850
+ try {
851
+ raw = JSON.parse(content);
852
+ } catch {
853
+ return void 0;
854
+ }
855
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return void 0;
856
+ const value = raw;
857
+ const launch = value.launch;
858
+ if (value.format !== WORKER_RECOVERY_FORMAT || !boundedString(value.id) || value.id !== path4.basename(runDirectory) || value.runner !== "pi-durable" || typeof value.deadlineAt !== "number" || !Number.isFinite(value.deadlineAt) || typeof value.pid !== "number" || !Number.isSafeInteger(value.pid) || value.pid <= 0 || typeof value.writtenAt !== "number" || !Number.isFinite(value.writtenAt) || typeof launch !== "object" || launch === null || Array.isArray(launch) || launch.id !== value.id || !boundedString(launch.name) || !boundedString(launch.cwd) || !boundedString(launch.workerPath) || !Array.isArray(launch.workerArguments) || launch.workerArguments.length > MAX_ARGUMENTS || launch.workerArguments.some((argument) => typeof argument !== "string" || argument.length > MAX_STRING)) {
859
+ return void 0;
860
+ }
861
+ return {
862
+ format: WORKER_RECOVERY_FORMAT,
863
+ id: value.id,
864
+ runner: "pi-durable",
865
+ deadlineAt: value.deadlineAt,
866
+ pid: value.pid,
867
+ writtenAt: value.writtenAt,
868
+ launch: {
869
+ id: value.id,
870
+ name: launch.name,
871
+ cwd: launch.cwd,
872
+ workerPath: launch.workerPath,
873
+ workerArguments: [...launch.workerArguments]
874
+ }
875
+ };
876
+ };
877
+ var workerArgumentMap = (args) => {
878
+ if (args.length % 2 !== 0) return void 0;
879
+ const result = /* @__PURE__ */ new Map();
880
+ for (let index = 0; index < args.length; index += 2) {
881
+ const key = args[index];
882
+ if (!key.startsWith("--")) return void 0;
883
+ result.set(key.slice(2), args[index + 1]);
884
+ }
885
+ return result;
886
+ };
887
+ var insideDirectory = (directory, file) => {
888
+ if (!path4.isAbsolute(file)) return false;
889
+ const relative = path4.relative(path4.resolve(directory), path4.resolve(file));
890
+ return relative !== "" && !relative.startsWith("..") && !path4.isAbsolute(relative);
891
+ };
892
+ var workerRecoveryMismatch = (recovery, expected) => {
893
+ const authority = readWorkerRecoveryAuthority(expected.runDirectory, expected.policy);
894
+ if (!authority || !isDeepStrictEqual(authority, recovery)) return "host launch receipt";
895
+ const { launch } = recovery;
896
+ if (path4.basename(expected.runDirectory) !== recovery.id || launch.id !== recovery.id) return "run id";
897
+ if (path4.resolve(launch.workerPath) !== path4.resolve(expected.workerPath)) return "worker path";
898
+ const args = workerArgumentMap(launch.workerArguments);
899
+ if (!args) return "worker arguments";
900
+ if (args.get("id") !== recovery.id) return "--id";
901
+ if (!path4.isAbsolute(launch.cwd) || launch.cwd !== expected.cwd || args.get("cwd") !== launch.cwd) return "working directory";
902
+ const pinned = [
903
+ ["status-file", path4.join(expected.runDirectory, "status.json")],
904
+ ["lifecycle-file", path4.join(expected.runDirectory, "lifecycle.jsonl")],
905
+ ["task-file", void 0],
906
+ ["log-file", void 0]
907
+ ];
908
+ for (const [name, exact] of pinned) {
909
+ const value = args.get(name);
910
+ if (value === void 0 || !insideDirectory(expected.runDirectory, value)) return `--${name}`;
911
+ if (exact !== void 0 && path4.resolve(value) !== path4.resolve(exact)) return `--${name}`;
912
+ }
913
+ return void 0;
914
+ };
915
+ var signalProbe = (pid) => {
916
+ try {
917
+ process.kill(pid, 0);
918
+ return "exists";
919
+ } catch (error) {
920
+ const code = error?.code;
921
+ if (code === "ESRCH") return "missing";
922
+ return "unknown";
923
+ }
924
+ };
925
+ var commandLineProbe = (pid) => {
926
+ try {
927
+ if (process.platform === "linux") {
928
+ return fs4.readFileSync(`/proc/${pid}/cmdline`, "utf8").split("\0").join(" ");
929
+ }
930
+ return execFileSync("ps", ["-ww", "-o", "command=", "-p", String(pid)], {
931
+ encoding: "utf8",
932
+ timeout: 2e3,
933
+ stdio: ["ignore", "pipe", "ignore"]
934
+ });
935
+ } catch {
936
+ return void 0;
937
+ }
938
+ };
939
+ var probeWorker = (pid, id, probes = {}) => {
940
+ if (!Number.isSafeInteger(pid) || pid <= 0) return "dead";
941
+ const signal = (probes.signal ?? signalProbe)(pid);
942
+ if (signal === "missing") return "dead";
943
+ if (signal === "unknown") return "unknown";
944
+ const commandLine = (probes.commandLine ?? commandLineProbe)(pid);
945
+ if (commandLine === void 0) return "unknown";
946
+ const tokens = commandLine.trim().split(/\s+/);
947
+ for (let index = 0; index < tokens.length - 1; index += 1) {
948
+ if (tokens[index] === "--id" && tokens[index + 1] === id) return "alive";
949
+ }
950
+ return "dead";
951
+ };
952
+ var adoptedWorkerHandle = (pid, id, probes = {}) => ({
953
+ kind: "process",
954
+ sessionId: String(pid),
955
+ livenessPollIntervalMs: 1e3,
956
+ isAlive: async () => probeWorker(pid, id, probes) !== "dead",
957
+ stop: async () => {
958
+ if (probeWorker(pid, id, probes) !== "alive") return;
959
+ try {
960
+ process.kill(process.platform === "win32" ? pid : -pid, "SIGTERM");
961
+ } catch {
962
+ }
963
+ }
964
+ });
965
+
787
966
  // src/agents/constants.ts
788
967
  var AGENT_STATUS_POLL_INTERVAL_MS = 250;
789
968
  var EXTERNAL_TRANSPORT_LIVENESS_POLL_INTERVAL_MS = 2e3;
@@ -1014,16 +1193,16 @@ var TmuxTransport = class {
1014
1193
  };
1015
1194
 
1016
1195
  // src/agents/worktree-manager.ts
1017
- import fs7 from "node:fs";
1018
- import path7 from "node:path";
1196
+ import fs8 from "node:fs";
1197
+ import path8 from "node:path";
1019
1198
 
1020
1199
  // src/agents/clone-first-worktree.ts
1021
- import fs6 from "node:fs";
1022
- import path6 from "node:path";
1200
+ import fs7 from "node:fs";
1201
+ import path7 from "node:path";
1023
1202
 
1024
1203
  // src/agents/cow-clone.ts
1025
- import fs4 from "node:fs";
1026
- import path4 from "node:path";
1204
+ import fs5 from "node:fs";
1205
+ import path5 from "node:path";
1027
1206
  var CLONE_SKIP_PREFIXES = [".git", ".pi/fabric/worktrees"];
1028
1207
  var CowUnavailableError = class extends Error {
1029
1208
  constructor(message2, options) {
@@ -1039,11 +1218,11 @@ var isCowUnavailable = (error) => {
1039
1218
  };
1040
1219
  var cloneEntry = async (from, to) => {
1041
1220
  try {
1042
- await fs4.promises.cp(from, to, {
1221
+ await fs5.promises.cp(from, to, {
1043
1222
  recursive: true,
1044
1223
  verbatimSymlinks: true,
1045
1224
  force: false,
1046
- mode: fs4.constants.COPYFILE_FICLONE_FORCE
1225
+ mode: fs5.constants.COPYFILE_FICLONE_FORCE
1047
1226
  });
1048
1227
  } catch (error) {
1049
1228
  if (isCowUnavailable(error)) {
@@ -1063,13 +1242,13 @@ var hasNestedSkip = (rel, prefixes) => {
1063
1242
  return prefixes.some((prefix) => prefix.startsWith(`${value}/`));
1064
1243
  };
1065
1244
  var cloneLevel = async (source, dest, relBase, prefixes) => {
1066
- await fs4.promises.mkdir(dest, { recursive: true });
1067
- const entries = await fs4.promises.readdir(source, { withFileTypes: true });
1245
+ await fs5.promises.mkdir(dest, { recursive: true });
1246
+ const entries = await fs5.promises.readdir(source, { withFileTypes: true });
1068
1247
  for (const entry of entries) {
1069
1248
  const rel = relBase ? `${relBase}/${entry.name}` : entry.name;
1070
1249
  if (skipped(rel, prefixes)) continue;
1071
- const from = path4.join(source, entry.name);
1072
- const to = path4.join(dest, entry.name);
1250
+ const from = path5.join(source, entry.name);
1251
+ const to = path5.join(dest, entry.name);
1073
1252
  if (entry.isDirectory() && !entry.isSymbolicLink() && hasNestedSkip(rel, prefixes)) {
1074
1253
  await cloneLevel(from, to, rel, prefixes);
1075
1254
  continue;
@@ -1083,11 +1262,11 @@ var cloneTree = async (source, dest, prefixes = CLONE_SKIP_PREFIXES) => {
1083
1262
  };
1084
1263
 
1085
1264
  // src/agents/worktree-paths.ts
1086
- import fs5 from "node:fs";
1087
- import path5 from "node:path";
1265
+ import fs6 from "node:fs";
1266
+ import path6 from "node:path";
1088
1267
  var FABRIC_WORKTREE_SEGMENTS = [".pi", "fabric", "worktrees"];
1089
1268
  var FABRIC_WORKTREE_EXCLUDE = ".pi/fabric/worktrees/";
1090
- var fabricWorktreePath = (gitRoot, id) => path5.join(gitRoot, ...FABRIC_WORKTREE_SEGMENTS, id);
1269
+ var fabricWorktreePath = (gitRoot, id) => path6.join(gitRoot, ...FABRIC_WORKTREE_SEGMENTS, id);
1091
1270
  var isFabricWorktreePath = (worktree, id) => {
1092
1271
  const parts = worktree.split(/[\\/]/).filter(Boolean);
1093
1272
  return parts.length >= 4 && parts.at(-1) === id && parts.at(-2) === "worktrees" && parts.at(-3) === "fabric" && parts.at(-4) === ".pi";
@@ -1097,11 +1276,11 @@ var ensureWorktreeExclude = async (gitRoot) => {
1097
1276
  cwd: gitRoot,
1098
1277
  timeoutMs: 1e4
1099
1278
  });
1100
- const excludePath = path5.resolve(gitRoot, located.stdout.trim());
1101
- fs5.mkdirSync(path5.dirname(excludePath), { recursive: true });
1279
+ const excludePath = path6.resolve(gitRoot, located.stdout.trim());
1280
+ fs6.mkdirSync(path6.dirname(excludePath), { recursive: true });
1102
1281
  let current = "";
1103
1282
  try {
1104
- current = fs5.readFileSync(excludePath, "utf8");
1283
+ current = fs6.readFileSync(excludePath, "utf8");
1105
1284
  } catch (error) {
1106
1285
  const code = error instanceof Error && "code" in error ? error.code : void 0;
1107
1286
  if (code !== "ENOENT") throw error;
@@ -1109,17 +1288,17 @@ var ensureWorktreeExclude = async (gitRoot) => {
1109
1288
  const lines = current.split(/\r?\n/);
1110
1289
  if (lines.some((line) => line.trim() === FABRIC_WORKTREE_EXCLUDE)) return;
1111
1290
  const prefix = current.length === 0 || current.endsWith("\n") ? "" : "\n";
1112
- fs5.appendFileSync(excludePath, `${prefix}${FABRIC_WORKTREE_EXCLUDE}
1291
+ fs6.appendFileSync(excludePath, `${prefix}${FABRIC_WORKTREE_EXCLUDE}
1113
1292
  `);
1114
1293
  };
1115
1294
 
1116
1295
  // src/agents/clone-first-worktree.ts
1117
1296
  var addCloneFirstWorktree = async (options) => {
1118
1297
  const dest = options.dest;
1119
- if (isFabricWorktreePath(dest, path6.basename(dest))) {
1298
+ if (isFabricWorktreePath(dest, path7.basename(dest))) {
1120
1299
  await ensureWorktreeExclude(options.gitRoot);
1121
1300
  }
1122
- fs6.mkdirSync(path6.dirname(dest), { recursive: true });
1301
+ fs7.mkdirSync(path7.dirname(dest), { recursive: true });
1123
1302
  const args = ["worktree", "add", "--no-checkout"];
1124
1303
  if (options.quiet) args.push("-q");
1125
1304
  if (options.detach) args.push("--detach");
@@ -1148,9 +1327,9 @@ var SETUP_TIMEOUT_MS = 10 * 6e4;
1148
1327
  var SETUP_OUTPUT_TAIL_CHARS = 2e3;
1149
1328
  var countLines = (file) => {
1150
1329
  try {
1151
- const stat = fs7.statSync(file);
1330
+ const stat = fs8.statSync(file);
1152
1331
  if (!stat.isFile() || stat.size > MAX_COUNTED_BYTES) return 0;
1153
- const content = fs7.readFileSync(file);
1332
+ const content = fs8.readFileSync(file);
1154
1333
  if (content.length === 0 || content.includes(0)) return 0;
1155
1334
  let lines = 0;
1156
1335
  for (const byte of content) if (byte === 10) lines++;
@@ -1161,8 +1340,8 @@ var countLines = (file) => {
1161
1340
  };
1162
1341
  var safeLabel = (value) => value.toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 30) || "agent";
1163
1342
  var isInside2 = (root, target) => {
1164
- const relative = path7.relative(root, target);
1165
- return relative === "" || relative !== ".." && !relative.startsWith(`..${path7.sep}`) && !path7.isAbsolute(relative);
1343
+ const relative = path8.relative(root, target);
1344
+ return relative === "" || relative !== ".." && !relative.startsWith(`..${path8.sep}`) && !path8.isAbsolute(relative);
1166
1345
  };
1167
1346
  var worktreePrefixParts = (prefix) => {
1168
1347
  const parts = prefix.split(/[\\/]+/).filter(Boolean);
@@ -1180,7 +1359,7 @@ var WorktreeManager = class {
1180
1359
  ]);
1181
1360
  const output = root.stdout.trim();
1182
1361
  if (!output) throw new Error("Git did not return a worktree root");
1183
- gitRoot = fs7.realpathSync(output);
1362
+ gitRoot = fs8.realpathSync(output);
1184
1363
  sourcePrefix = prefix2.stdout.trim();
1185
1364
  } catch {
1186
1365
  throw new Error("Worktree isolation requires a Git repository");
@@ -1193,15 +1372,15 @@ var WorktreeManager = class {
1193
1372
  branch: { flag: "-b", name: branch },
1194
1373
  startPoint: "HEAD"
1195
1374
  });
1196
- const canonicalWorktreePath = fs7.realpathSync(worktreePath);
1375
+ const canonicalWorktreePath = fs8.realpathSync(worktreePath);
1197
1376
  const baseRef = await executeFile("git", ["rev-parse", "HEAD"], { cwd: worktreePath, timeoutMs: GIT_SUMMARY_TIMEOUT_MS }).then((result) => result.stdout.trim() || void 0, () => void 0);
1198
1377
  const prefix = preserveSourceSubdirectory ? worktreePrefixParts(sourcePrefix) : void 0;
1199
1378
  let effectiveCwd = canonicalWorktreePath;
1200
1379
  if (prefix && prefix.length > 0) {
1201
- const candidate = path7.resolve(canonicalWorktreePath, ...prefix);
1380
+ const candidate = path8.resolve(canonicalWorktreePath, ...prefix);
1202
1381
  try {
1203
- const canonicalCandidate = fs7.realpathSync(candidate);
1204
- if (fs7.statSync(canonicalCandidate).isDirectory() && isInside2(canonicalWorktreePath, canonicalCandidate)) {
1382
+ const canonicalCandidate = fs8.realpathSync(candidate);
1383
+ if (fs8.statSync(canonicalCandidate).isDirectory() && isInside2(canonicalWorktreePath, canonicalCandidate)) {
1205
1384
  effectiveCwd = canonicalCandidate;
1206
1385
  }
1207
1386
  } catch {
@@ -1240,7 +1419,7 @@ ${tail}` : ""}`);
1240
1419
  ...lease.baseRef ? { baseRef: lease.baseRef } : {},
1241
1420
  changedFiles: [],
1242
1421
  diffstat: { files: 0, insertions: 0, deletions: 0 },
1243
- kept: fs7.existsSync(lease.path)
1422
+ kept: fs8.existsSync(lease.path)
1244
1423
  };
1245
1424
  if (!result.kept) return result;
1246
1425
  try {
@@ -1260,7 +1439,7 @@ ${tail}` : ""}`);
1260
1439
  for (const file of untracked.stdout.split("\n")) {
1261
1440
  if (!file || files.has(file)) continue;
1262
1441
  files.add(file);
1263
- if (files.size <= MAX_CHANGED_FILES) result.diffstat.insertions += countLines(path7.join(lease.path, file));
1442
+ if (files.size <= MAX_CHANGED_FILES) result.diffstat.insertions += countLines(path8.join(lease.path, file));
1264
1443
  }
1265
1444
  result.diffstat.files = files.size;
1266
1445
  result.changedFiles = [...files].sort().slice(0, MAX_CHANGED_FILES);
@@ -1289,8 +1468,8 @@ ${tail}` : ""}`);
1289
1468
 
1290
1469
  // src/agents/handoff.ts
1291
1470
  import { randomUUID as randomUUID3 } from "node:crypto";
1292
- import fs8 from "node:fs";
1293
- import path8 from "node:path";
1471
+ import fs9 from "node:fs";
1472
+ import path9 from "node:path";
1294
1473
 
1295
1474
  // src/core/host-sdk-runtime.ts
1296
1475
  var PiCodingAgent = await loadHostSdk();
@@ -1489,7 +1668,7 @@ var materializeBranch = (seed, cwd, directory) => {
1489
1668
  throw new Error("In-memory trajectory handoff is missing its source branch");
1490
1669
  }
1491
1670
  const id = randomUUID3();
1492
- const sessionFile = path8.join(directory, `handoff-${id}.jsonl`);
1671
+ const sessionFile = path9.join(directory, `handoff-${id}.jsonl`);
1493
1672
  const header = {
1494
1673
  type: "session",
1495
1674
  version: PiCodingAgent.CURRENT_SESSION_VERSION,
@@ -1498,7 +1677,7 @@ var materializeBranch = (seed, cwd, directory) => {
1498
1677
  cwd,
1499
1678
  ...seed.sourceSessionFile ? { parentSession: seed.sourceSessionFile } : {}
1500
1679
  };
1501
- fs8.writeFileSync(
1680
+ fs9.writeFileSync(
1502
1681
  sessionFile,
1503
1682
  `${[header, ...seed.sourceBranch].map((entry) => JSON.stringify(entry)).join("\n")}
1504
1683
  `,
@@ -1542,7 +1721,7 @@ var synchronizeSourceSettings = (session, seed) => {
1542
1721
  }
1543
1722
  };
1544
1723
  var writeHandoffSession = (seed, cwd, directory, transfer, compaction, compactionBudget) => {
1545
- fs8.mkdirSync(directory, { recursive: true, mode: 448 });
1724
+ fs9.mkdirSync(directory, { recursive: true, mode: 448 });
1546
1725
  const policy = transfer ? thinkingTransferPolicy(transfer) : "preserved";
1547
1726
  let session;
1548
1727
  let report;
@@ -1616,11 +1795,11 @@ var writeHandoffSession = (seed, cwd, directory, transfer, compaction, compactio
1616
1795
  });
1617
1796
  const sessionFile = session.getSessionFile();
1618
1797
  if (!sessionFile) throw new Error("Trajectory handoff did not produce a Pi session file");
1619
- fs8.chmodSync(sessionFile, 384);
1798
+ fs9.chmodSync(sessionFile, 384);
1620
1799
  return sessionFile;
1621
1800
  };
1622
1801
  var writeForkSession = (seed, cwd, directory, transfer) => {
1623
- fs8.mkdirSync(directory, { recursive: true, mode: 448 });
1802
+ fs9.mkdirSync(directory, { recursive: true, mode: 448 });
1624
1803
  const policy = transfer ? thinkingTransferPolicy(transfer) : "preserved";
1625
1804
  const raw = structuredClone(seed.sourceBranch);
1626
1805
  const digest = policy === "stripped" && transfer ? buildThinkingDigest(raw, transfer) : void 0;
@@ -1643,13 +1822,13 @@ var writeForkSession = (seed, cwd, directory, transfer) => {
1643
1822
  });
1644
1823
  const sessionFile = session.getSessionFile();
1645
1824
  if (!sessionFile) throw new Error("Branch seed did not produce a Pi session file");
1646
- fs8.chmodSync(sessionFile, 384);
1825
+ fs9.chmodSync(sessionFile, 384);
1647
1826
  return sessionFile;
1648
1827
  };
1649
1828
 
1650
1829
  // src/agents/child-env.ts
1651
- import fs9 from "node:fs";
1652
- import path9 from "node:path";
1830
+ import fs10 from "node:fs";
1831
+ import path10 from "node:path";
1653
1832
  var MAX_WRITABLE_ROOTS = 32;
1654
1833
  var MAX_ROOT_CHARS = 4096;
1655
1834
  var readAgentLineage = (raw = process.env.PI_FABRIC_LINEAGE) => {
@@ -1680,12 +1859,12 @@ var checkWritePolicyRequest = (request) => {
1680
1859
  };
1681
1860
  var nearestExisting = (target) => {
1682
1861
  let current = target;
1683
- while (!fs9.existsSync(current)) {
1684
- const parent = path9.dirname(current);
1862
+ while (!fs10.existsSync(current)) {
1863
+ const parent = path10.dirname(current);
1685
1864
  if (parent === current) break;
1686
1865
  current = parent;
1687
1866
  }
1688
- return path9.join(fs9.realpathSync(current), path9.relative(current, target));
1867
+ return path10.join(fs10.realpathSync(current), path10.relative(current, target));
1689
1868
  };
1690
1869
  var resolveChildWritePolicy = (request, parent, cwd) => {
1691
1870
  if (!requestsWritePolicy(request)) return parent;
@@ -1698,21 +1877,21 @@ var resolveChildWritePolicy = (request, parent, cwd) => {
1698
1877
  throw new Error('A shell-confined agent cannot launch a child with shell: "unconfined"');
1699
1878
  }
1700
1879
  if (readOnly) return { readOnly, writableRoots: [], shell };
1701
- const realCwd = fs9.realpathSync(cwd);
1880
+ const realCwd = fs10.realpathSync(cwd);
1702
1881
  const within = (target) => !parent || parent.writableRoots.some((root) => isInside(root, target));
1703
1882
  const roots = request.writableRoots ?? (parent ? parent.writableRoots : [cwd]);
1704
1883
  const resolved = /* @__PURE__ */ new Set();
1705
1884
  for (const root of roots) {
1706
- const absolute = path9.resolve(cwd, root);
1707
- if (!fs9.existsSync(absolute)) {
1885
+ const absolute = path10.resolve(cwd, root);
1886
+ if (!fs10.existsSync(absolute)) {
1708
1887
  const target = nearestExisting(absolute);
1709
1888
  if (!isInside(cwd, absolute) || !isInside(realCwd, target) || !within(target)) {
1710
1889
  throw new Error(`Writable root must exist or be creatable inside the agent cwd: ${root}`);
1711
1890
  }
1712
- fs9.mkdirSync(absolute, { recursive: true });
1891
+ fs10.mkdirSync(absolute, { recursive: true });
1713
1892
  }
1714
- const real = fs9.realpathSync(absolute);
1715
- if (!fs9.statSync(real).isDirectory()) throw new Error(`Writable root is not a directory: ${root}`);
1893
+ const real = fs10.realpathSync(absolute);
1894
+ if (!fs10.statSync(real).isDirectory()) throw new Error(`Writable root is not a directory: ${root}`);
1716
1895
  if (!within(real)) throw new Error(`Writable root is outside the caller's writable roots: ${root}`);
1717
1896
  resolved.add(real);
1718
1897
  }
@@ -1753,17 +1932,17 @@ var budgetAdmits = (spent, limit) => {
1753
1932
  };
1754
1933
 
1755
1934
  // src/storage/retention.ts
1756
- import fs10 from "node:fs";
1757
- import path10 from "node:path";
1935
+ import fs11 from "node:fs";
1936
+ import path11 from "node:path";
1758
1937
  var RUN_ROOT_OWNER_FILE = ".fabric-owner.json";
1759
1938
  var TERMINAL_STATUSES = /* @__PURE__ */ new Set(["completed", "failed", "stopped", "timed_out"]);
1760
1939
  var RUN_ROOT_HEARTBEAT_TTL_MS = 45 * 60 * 1e3;
1761
- var ownerPath = (root) => path10.join(root, RUN_ROOT_OWNER_FILE);
1940
+ var ownerPath = (root) => path11.join(root, RUN_ROOT_OWNER_FILE);
1762
1941
  var readJson = (file) => {
1763
1942
  try {
1764
1943
  const stat = ownedStat(file);
1765
1944
  if (!stat?.isFile() || stat.size > 1024 * 1024) return;
1766
- return JSON.parse(fs10.readFileSync(file, "utf8"));
1945
+ return JSON.parse(fs11.readFileSync(file, "utf8"));
1767
1946
  } catch {
1768
1947
  return;
1769
1948
  }
@@ -1771,9 +1950,9 @@ var readJson = (file) => {
1771
1950
  var time = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0;
1772
1951
  var validOwner = (owner) => !!owner && Number.isSafeInteger(owner.pid) && owner.pid > 0 && time(owner.startedAt) && time(owner.heartbeatAt) && (owner.closedAt === void 0 || time(owner.closedAt)) && (owner.orphanedAt === void 0 || time(owner.orphanedAt)) && (owner.childrenStopped === void 0 || typeof owner.childrenStopped === "boolean");
1773
1952
  var writeOwner = (root, owner) => {
1774
- if (fs10.existsSync(root) && !ownedStat(root)?.isDirectory()) throw new Error("Unsafe Fabric run root");
1953
+ if (fs11.existsSync(root) && !ownedStat(root)?.isDirectory()) throw new Error("Unsafe Fabric run root");
1775
1954
  const file = ownerPath(root);
1776
- if (fs10.existsSync(file)) {
1955
+ if (fs11.existsSync(file)) {
1777
1956
  const existing = readJson(file);
1778
1957
  if (!validOwner(existing) || existing.pid !== owner.pid) throw new Error("Unsafe Fabric run owner marker");
1779
1958
  }
@@ -1819,37 +1998,37 @@ var OVERSIZED_EVENT_FILE = "oversized-event-prefix.txt";
1819
1998
  var DURABLE_KEY = /^(?:initial|[0-9a-f]{64})$/;
1820
1999
  var DURABLE_LEASE_FILES = /* @__PURE__ */ new Set(["lease.sqlite", "lease.sqlite-journal"]);
1821
2000
  var DURABLE_STORE_FILE = /^(?:main|(?:doc|task)-(?:0|[1-9]\d*))\.jsonl(?:\.reclaim)?$/;
1822
- var onlyOwnedFiles = (directory, allowed) => fs10.readdirSync(directory).every((name) => allowed(name) && ownedStat(path10.join(directory, name))?.isFile() === true);
1823
- var safeDurableTree = (directory) => fs10.readdirSync(directory).every((key) => {
1824
- const conversation = path10.join(directory, key);
2001
+ var onlyOwnedFiles = (directory, allowed) => fs11.readdirSync(directory).every((name) => allowed(name) && ownedStat(path11.join(directory, name))?.isFile() === true);
2002
+ var safeDurableTree = (directory) => fs11.readdirSync(directory).every((key) => {
2003
+ const conversation = path11.join(directory, key);
1825
2004
  if (!DURABLE_KEY.test(key) || !ownedStat(conversation)?.isDirectory()) return false;
1826
- return fs10.readdirSync(conversation).every((name) => {
1827
- const file = path10.join(conversation, name);
2005
+ return fs11.readdirSync(conversation).every((name) => {
2006
+ const file = path11.join(conversation, name);
1828
2007
  if (name === "store") return ownedStat(file)?.isDirectory() === true && onlyOwnedFiles(file, (child) => DURABLE_STORE_FILE.test(child));
1829
2008
  return DURABLE_LEASE_FILES.has(name) && ownedStat(file)?.isFile() === true;
1830
2009
  });
1831
2010
  });
1832
2011
  var ownedTree = (directory, depth) => {
1833
2012
  if (depth > 32) return false;
1834
- return fs10.readdirSync(directory).every((name) => {
1835
- const stat = ownedStat(path10.join(directory, name));
2013
+ return fs11.readdirSync(directory).every((name) => {
2014
+ const stat = ownedStat(path11.join(directory, name));
1836
2015
  if (!stat || name.startsWith("hosted.json")) return false;
1837
- return stat.isFile() || stat.isDirectory() && ownedTree(path10.join(directory, name), depth + 1);
2016
+ return stat.isFile() || stat.isDirectory() && ownedTree(path11.join(directory, name), depth + 1);
1838
2017
  });
1839
2018
  };
1840
2019
  var safeRunTree = (root, childrenStopped, owner, depth = 0, anyContents = false) => {
1841
2020
  if (depth > 32 || !ownedStat(root)?.isDirectory()) return false;
1842
- const record = readJson(path10.join(root, "status.json"));
2021
+ const record = readJson(path11.join(root, "status.json"));
1843
2022
  const pid = record?.transport === "process" && typeof record.sessionId === "string" && /^\d+$/.test(record.sessionId) ? Number(record.sessionId) : void 0;
1844
2023
  if (pid !== void 0 && childAlive(owner, pid)) return false;
1845
2024
  const terminal = !!record?.status && TERMINAL_STATUSES.has(record.status);
1846
2025
  if (!terminal) {
1847
2026
  if (!childrenStopped && pid === void 0) return false;
1848
- if (!ownedStat(path10.join(root, "task.txt"))?.isFile()) return false;
2027
+ if (!ownedStat(path11.join(root, "task.txt"))?.isFile()) return false;
1849
2028
  }
1850
2029
  try {
1851
- for (const name of fs10.readdirSync(root)) {
1852
- const file = path10.join(root, name);
2030
+ for (const name of fs11.readdirSync(root)) {
2031
+ const file = path11.join(root, name);
1853
2032
  const stat = ownedStat(file);
1854
2033
  if (!stat) return false;
1855
2034
  if (stat.isFile() && (runFiles.has(name) || name === OVERSIZED_EVENT_FILE || STATUS_TEMP_FILE.test(name))) continue;
@@ -1862,7 +2041,7 @@ var safeRunTree = (root, childrenStopped, owner, depth = 0, anyContents = false)
1862
2041
  continue;
1863
2042
  }
1864
2043
  if (stat.isDirectory() && name === "handoff-session") {
1865
- if (fs10.readdirSync(file).some((child) => !child.endsWith(".jsonl") || !ownedStat(path10.join(file, child))?.isFile())) return false;
2044
+ if (fs11.readdirSync(file).some((child) => !child.endsWith(".jsonl") || !ownedStat(path11.join(file, child))?.isFile())) return false;
1866
2045
  continue;
1867
2046
  }
1868
2047
  if (stat.isDirectory() && name === "durable") {
@@ -1870,7 +2049,7 @@ var safeRunTree = (root, childrenStopped, owner, depth = 0, anyContents = false)
1870
2049
  continue;
1871
2050
  }
1872
2051
  if (stat.isDirectory() && name === "nested") {
1873
- for (const child of fs10.readdirSync(file)) if (!safeRunTree(path10.join(file, child), false, owner, depth + 1, anyContents)) return false;
2052
+ for (const child of fs11.readdirSync(file)) if (!safeRunTree(path11.join(file, child), false, owner, depth + 1, anyContents)) return false;
1874
2053
  continue;
1875
2054
  }
1876
2055
  return false;
@@ -1882,7 +2061,7 @@ var safeRunTree = (root, childrenStopped, owner, depth = 0, anyContents = false)
1882
2061
  };
1883
2062
  var safeRootContents = (root, childrenStopped, owner, anyContents = false) => {
1884
2063
  try {
1885
- return fs10.readdirSync(root).every((name) => name === RUN_ROOT_OWNER_FILE || safeRunTree(path10.join(root, name), childrenStopped, owner, 0, anyContents));
2064
+ return fs11.readdirSync(root).every((name) => name === RUN_ROOT_OWNER_FILE || safeRunTree(path11.join(root, name), childrenStopped, owner, 0, anyContents));
1886
2065
  } catch {
1887
2066
  return false;
1888
2067
  }
@@ -1895,8 +2074,8 @@ var canRemoveManagedRunRoot = (root) => {
1895
2074
  var removeEmptyRunRoot = (root) => {
1896
2075
  try {
1897
2076
  if (!ownedStat(root)?.isDirectory() || !validOwner(readJson(ownerPath(root)))) return false;
1898
- if (fs10.readdirSync(root).some((name) => name !== RUN_ROOT_OWNER_FILE)) return false;
1899
- fs10.rmSync(root, { recursive: true, force: true });
2077
+ if (fs11.readdirSync(root).some((name) => name !== RUN_ROOT_OWNER_FILE)) return false;
2078
+ fs11.rmSync(root, { recursive: true, force: true });
1900
2079
  return true;
1901
2080
  } catch {
1902
2081
  return false;
@@ -1906,21 +2085,21 @@ var pruneClosedRunRoot = (root, owner, orphanMs, oneShotMs, now) => {
1906
2085
  const removed = [];
1907
2086
  let entries;
1908
2087
  try {
1909
- entries = fs10.readdirSync(root, { withFileTypes: true });
2088
+ entries = fs11.readdirSync(root, { withFileTypes: true });
1910
2089
  } catch {
1911
2090
  return removed;
1912
2091
  }
1913
2092
  for (const entry of entries) {
1914
2093
  if (!entry.isDirectory()) continue;
1915
- const directory = path10.join(root, entry.name);
2094
+ const directory = path11.join(root, entry.name);
1916
2095
  if (!safeRunTree(directory, owner.childrenStopped === true, owner)) continue;
1917
- const record = readJson(path10.join(directory, "status.json"));
2096
+ const record = readJson(path11.join(directory, "status.json"));
1918
2097
  const terminal = !!record?.status && TERMINAL_STATUSES.has(record.status);
1919
2098
  const reference = terminal ? recordAgeReference(record, ownedStat(directory)?.mtimeMs ?? now) : owner.closedAt;
1920
2099
  const retention = terminal && !record?.actorId ? oneShotMs : orphanMs;
1921
2100
  if (now - reference < retention) continue;
1922
2101
  try {
1923
- fs10.rmSync(directory, { recursive: true, force: true });
2102
+ fs11.rmSync(directory, { recursive: true, force: true });
1924
2103
  removed.push(directory);
1925
2104
  } catch {
1926
2105
  }
@@ -1932,14 +2111,14 @@ var sweepTempRunRoots = (options) => {
1932
2111
  const result = { removedRoots: [], removedRuns: [] };
1933
2112
  let entries;
1934
2113
  try {
1935
- entries = fs10.readdirSync(options.tempRoot, { withFileTypes: true });
2114
+ entries = fs11.readdirSync(options.tempRoot, { withFileTypes: true });
1936
2115
  } catch {
1937
2116
  return result;
1938
2117
  }
1939
2118
  for (const entry of entries) {
1940
2119
  if (!entry.isDirectory() || !/^pi-fabric-runs-[A-Za-z0-9_-]+$/.test(entry.name)) continue;
1941
- const root = path10.join(options.tempRoot, entry.name);
1942
- if (options.currentRoot && path10.resolve(root) === path10.resolve(options.currentRoot)) continue;
2120
+ const root = path11.join(options.tempRoot, entry.name);
2121
+ if (options.currentRoot && path11.resolve(root) === path11.resolve(options.currentRoot)) continue;
1943
2122
  if (!ownedStat(root)?.isDirectory()) continue;
1944
2123
  const owner = readJson(ownerPath(root));
1945
2124
  if (!validOwner(owner)) continue;
@@ -1958,7 +2137,7 @@ var sweepTempRunRoots = (options) => {
1958
2137
  }
1959
2138
  if (now - owner.orphanedAt < options.orphanedTempRunRetentionMs || !safeRootContents(root, false, owner, true)) continue;
1960
2139
  try {
1961
- fs10.rmSync(root, { recursive: true, force: true });
2140
+ fs11.rmSync(root, { recursive: true, force: true });
1962
2141
  result.removedRoots.push(root);
1963
2142
  } catch {
1964
2143
  }
@@ -1971,18 +2150,18 @@ var pruneActorRunArchives = (options) => {
1971
2150
  if (!ownedStat(options.runsDirectory)?.isDirectory()) return removed;
1972
2151
  let entries;
1973
2152
  try {
1974
- entries = fs10.readdirSync(options.runsDirectory, { withFileTypes: true });
2153
+ entries = fs11.readdirSync(options.runsDirectory, { withFileTypes: true });
1975
2154
  } catch {
1976
2155
  return removed;
1977
2156
  }
1978
2157
  for (const entry of entries) {
1979
2158
  if (!entry.isDirectory() || entry.name === options.latestRunId) continue;
1980
- const directory = path10.join(options.runsDirectory, entry.name);
1981
- const record = readJson(path10.join(directory, "status.json"));
2159
+ const directory = path11.join(options.runsDirectory, entry.name);
2160
+ const record = readJson(path11.join(directory, "status.json"));
1982
2161
  if (!record?.status || !TERMINAL_STATUSES.has(record.status) || !safeRunTree(directory, false)) continue;
1983
2162
  if (now - recordAgeReference(record, ownedStat(directory)?.mtimeMs ?? now) < options.retentionMs) continue;
1984
2163
  try {
1985
- fs10.rmSync(directory, { recursive: true, force: true });
2164
+ fs11.rmSync(directory, { recursive: true, force: true });
1986
2165
  removed.push(directory);
1987
2166
  } catch {
1988
2167
  }
@@ -1992,21 +2171,21 @@ var pruneActorRunArchives = (options) => {
1992
2171
 
1993
2172
  // src/agents/session-export.ts
1994
2173
  import os2 from "node:os";
1995
- import path11 from "node:path";
2174
+ import path12 from "node:path";
1996
2175
  var SESSION_EXPORT_ENV = "PI_FABRIC_AGENT_DIR";
1997
- var expandHome = (value) => value === "~" ? os2.homedir() : value.startsWith("~/") || value.startsWith(`~${path11.win32.sep}`) ? path11.join(os2.homedir(), value.slice(2)) : value;
2176
+ var expandHome = (value) => value === "~" ? os2.homedir() : value.startsWith("~/") || value.startsWith(`~${path12.win32.sep}`) ? path12.join(os2.homedir(), value.slice(2)) : value;
1998
2177
  var encodeSessionExportCwd = (cwd) => {
1999
- const absolute = path11.isAbsolute(cwd) || path11.win32.isAbsolute(cwd) ? cwd : path11.resolve(cwd);
2178
+ const absolute = path12.isAbsolute(cwd) || path12.win32.isAbsolute(cwd) ? cwd : path12.resolve(cwd);
2000
2179
  return `--${absolute.replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}--`;
2001
2180
  };
2002
2181
  var resolveSessionExportDir = (config) => {
2003
2182
  if (!config.sessionExport) return void 0;
2004
- const raw = process.env[SESSION_EXPORT_ENV]?.trim() || config.sessionExportDir.trim() || path11.join(os2.homedir(), ".pi", "agent");
2183
+ const raw = process.env[SESSION_EXPORT_ENV]?.trim() || config.sessionExportDir.trim() || path12.join(os2.homedir(), ".pi", "agent");
2005
2184
  return expandHome(raw);
2006
2185
  };
2007
2186
  var sessionExportFileFor = (root, cwd, runId, at) => {
2008
2187
  const fileTimestamp = at.toISOString().replace(/[:.]/g, "-");
2009
- return path11.join(
2188
+ return path12.join(
2010
2189
  root,
2011
2190
  "sessions",
2012
2191
  ".fabric",
@@ -2047,11 +2226,11 @@ var resolveAgentCwd = (parentCwd, requestedCwd) => {
2047
2226
  if (typeof requested !== "string" || requested.trim().length === 0) {
2048
2227
  throw new Error(`Invalid Fabric agent cwd ${JSON.stringify(requested)}: path must not be empty`);
2049
2228
  }
2050
- const candidate = path12.isAbsolute(requested) ? requested : path12.resolve(parentCwd, requested);
2229
+ const candidate = path13.isAbsolute(requested) ? requested : path13.resolve(parentCwd, requested);
2051
2230
  try {
2052
- const canonical = fs11.realpathSync(candidate);
2053
- fs11.accessSync(canonical, fs11.constants.R_OK | fs11.constants.X_OK);
2054
- if (!fs11.statSync(canonical).isDirectory()) {
2231
+ const canonical = fs12.realpathSync(candidate);
2232
+ fs12.accessSync(canonical, fs12.constants.R_OK | fs12.constants.X_OK);
2233
+ if (!fs12.statSync(canonical).isDirectory()) {
2055
2234
  throw new Error("path is not a directory");
2056
2235
  }
2057
2236
  return canonical;
@@ -2061,6 +2240,13 @@ var resolveAgentCwd = (parentCwd, requestedCwd) => {
2061
2240
  }
2062
2241
  };
2063
2242
  var terminalStatuses = terminalAgentStatuses;
2243
+ var fileSize = (filePath) => {
2244
+ try {
2245
+ return fs12.statSync(filePath).size;
2246
+ } catch {
2247
+ return 0;
2248
+ }
2249
+ };
2064
2250
  var HOSTED_TRANSPORT = {
2065
2251
  kind: "process",
2066
2252
  available: async () => false,
@@ -2107,7 +2293,7 @@ var runName = (request) => safeName(request.name ?? request.task.split("\n", 1)[
2107
2293
  var safeName = (value) => value.replace(/[\r\n\t]+/g, " ").trim().slice(0, MAX_NAME_LENGTH) || "Fabric agent";
2108
2294
  var readRecord = (filePath) => {
2109
2295
  try {
2110
- const parsed = JSON.parse(fs11.readFileSync(filePath, "utf8"));
2296
+ const parsed = JSON.parse(fs12.readFileSync(filePath, "utf8"));
2111
2297
  if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return void 0;
2112
2298
  const record = parsed;
2113
2299
  return { ...record, runner: isFabricRunnerId(record.runner) ? record.runner : "pi" };
@@ -2159,24 +2345,24 @@ var reconcileNestedAgents = (records, owner) => records.map((record) => {
2159
2345
  });
2160
2346
  var readNestedAgents = (runDirectory, depth = 0) => {
2161
2347
  if (depth >= 8) return [];
2162
- const nestedRoot = path12.join(runDirectory, "nested");
2348
+ const nestedRoot = path13.join(runDirectory, "nested");
2163
2349
  let entries;
2164
2350
  try {
2165
- entries = fs11.readdirSync(nestedRoot);
2351
+ entries = fs12.readdirSync(nestedRoot);
2166
2352
  } catch {
2167
2353
  return [];
2168
2354
  }
2169
2355
  const agents = [];
2170
2356
  for (const entry of entries.slice(0, 200)) {
2171
- const runDirectory2 = path12.join(nestedRoot, entry);
2172
- const record = readRecord(path12.join(runDirectory2, "status.json"));
2357
+ const runDirectory2 = path13.join(nestedRoot, entry);
2358
+ const record = readRecord(path13.join(runDirectory2, "status.json"));
2173
2359
  if (!record) continue;
2174
2360
  const nestedAgents = readNestedAgents(runDirectory2, depth + 1);
2175
2361
  const { logFile: _logFile, nestedAgents: _nestedAgents, ...safeRecord } = record;
2176
2362
  agents.push(
2177
2363
  compactUiRecord({
2178
2364
  ...safeRecord,
2179
- logFile: path12.join(runDirectory2, "events.jsonl"),
2365
+ logFile: path13.join(runDirectory2, "events.jsonl"),
2180
2366
  ...nestedAgents.length > 0 ? { nestedAgents } : {}
2181
2367
  })
2182
2368
  );
@@ -2184,7 +2370,7 @@ var readNestedAgents = (runDirectory, depth = 0) => {
2184
2370
  return agents;
2185
2371
  };
2186
2372
  var summarizeRunLog = (runDirectory, lines) => {
2187
- const page = readJsonlPage(path12.join(runDirectory, "events.jsonl"), lines);
2373
+ const page = readJsonlPage(path13.join(runDirectory, "events.jsonl"), lines);
2188
2374
  const summary = [];
2189
2375
  for (const entry of page.lines) {
2190
2376
  const parsed = entry.parsed;
@@ -2237,8 +2423,8 @@ var AgentManager = class {
2237
2423
  this.config = config;
2238
2424
  this.#semaphore = new AgentAdmission(config.maxConcurrent, Infinity, config.maxDepth);
2239
2425
  this.#managedTempRoot = options.runRoot === void 0 && process.env.PI_FABRIC_RUN_ROOT === void 0;
2240
- this.#runRoot = options.runRoot ?? process.env.PI_FABRIC_RUN_ROOT ?? fs11.mkdtempSync(path12.join(os3.tmpdir(), "pi-fabric-runs-"));
2241
- this.#parentOwnedRunRoot = options.runRoot === void 0 && this.#parentLineage?.worker === true && this.#parentLineage.depth > 0 && path12.basename(this.#runRoot) === "nested" && path12.basename(path12.dirname(this.#runRoot)) === this.#parentLineage.runId;
2426
+ this.#runRoot = options.runRoot ?? process.env.PI_FABRIC_RUN_ROOT ?? fs12.mkdtempSync(path13.join(os3.tmpdir(), "pi-fabric-runs-"));
2427
+ this.#parentOwnedRunRoot = options.runRoot === void 0 && this.#parentLineage?.worker === true && this.#parentLineage.depth > 0 && path13.basename(this.#runRoot) === "nested" && path13.basename(path13.dirname(this.#runRoot)) === this.#parentLineage.runId;
2242
2428
  this.#retention = options.retention ?? DEFAULT_FABRIC_CONFIG.retention;
2243
2429
  this.#workerPath = options.workerPath ?? fileURLToPath(new URL("../worker.js", import.meta.url));
2244
2430
  this.#fabricExtensionPath = options.fabricExtensionPath ?? fileURLToPath(new URL("../index.js", import.meta.url));
@@ -2550,25 +2736,25 @@ var AgentManager = class {
2550
2736
  }
2551
2737
  const id = randomUUID4().replaceAll("-", "");
2552
2738
  const name = runName(request);
2553
- const runDirectory = path12.join(this.#runRoot, id);
2554
- const taskFile = path12.join(runDirectory, "task.txt");
2555
- const statusFile = path12.join(runDirectory, "status.json");
2556
- const lifecycleFile = path12.join(runDirectory, "lifecycle.jsonl");
2557
- const logFile = path12.join(runDirectory, "events.jsonl");
2558
- const steerFile = path12.join(runDirectory, "steer.jsonl");
2559
- const schemaFile = request.schema ? path12.join(runDirectory, "schema.json") : void 0;
2560
- const imagesFile = request.images && request.images.length > 0 ? path12.join(runDirectory, "images.json") : void 0;
2739
+ const runDirectory = path13.join(this.#runRoot, id);
2740
+ const taskFile = path13.join(runDirectory, "task.txt");
2741
+ const statusFile = path13.join(runDirectory, "status.json");
2742
+ const lifecycleFile = path13.join(runDirectory, "lifecycle.jsonl");
2743
+ const logFile = path13.join(runDirectory, "events.jsonl");
2744
+ const steerFile = path13.join(runDirectory, "steer.jsonl");
2745
+ const schemaFile = request.schema ? path13.join(runDirectory, "schema.json") : void 0;
2746
+ const imagesFile = request.images && request.images.length > 0 ? path13.join(runDirectory, "images.json") : void 0;
2561
2747
  try {
2562
- fs11.mkdirSync(runDirectory, { recursive: true });
2563
- fs11.writeFileSync(taskFile, request.task, { encoding: "utf8", mode: 384 });
2748
+ fs12.mkdirSync(runDirectory, { recursive: true });
2749
+ fs12.writeFileSync(taskFile, request.task, { encoding: "utf8", mode: 384 });
2564
2750
  if (imagesFile) {
2565
- fs11.writeFileSync(imagesFile, JSON.stringify(request.images), {
2751
+ fs12.writeFileSync(imagesFile, JSON.stringify(request.images), {
2566
2752
  encoding: "utf8",
2567
2753
  mode: 384
2568
2754
  });
2569
2755
  }
2570
2756
  if (schemaFile) {
2571
- fs11.writeFileSync(schemaFile, JSON.stringify(request.schema, null, 2), {
2757
+ fs12.writeFileSync(schemaFile, JSON.stringify(request.schema, null, 2), {
2572
2758
  encoding: "utf8",
2573
2759
  mode: 384
2574
2760
  });
@@ -2611,10 +2797,10 @@ var AgentManager = class {
2611
2797
  childIndex: this.#childIndex++,
2612
2798
  worker: true
2613
2799
  };
2614
- const sessionFile = request.forkSeed ? writeForkSession(request.forkSeed, agentCwd, path12.join(runDirectory, "fork-session"), request.thinkingTransfer) : request.sessionSeed ? writeHandoffSession(
2800
+ const sessionFile = request.forkSeed ? writeForkSession(request.forkSeed, agentCwd, path13.join(runDirectory, "fork-session"), request.thinkingTransfer) : request.sessionSeed ? writeHandoffSession(
2615
2801
  request.sessionSeed,
2616
2802
  agentCwd,
2617
- path12.join(runDirectory, "handoff-session"),
2803
+ path13.join(runDirectory, "handoff-session"),
2618
2804
  request.thinkingTransfer,
2619
2805
  request.handoffCompact,
2620
2806
  request.handoffCompact ? await this.#resolveHandoffCompactionBudget?.(model, agentCwd) : void 0
@@ -2744,7 +2930,7 @@ var AgentManager = class {
2744
2930
  ...this.#identityId ? ["--owner-identity-id", this.#identityId] : [],
2745
2931
  ...request.runnerSessionId ? ["--runner-session-id", request.runnerSessionId] : [],
2746
2932
  "--run-root",
2747
- path12.join(runDirectory, "nested"),
2933
+ path13.join(runDirectory, "nested"),
2748
2934
  "--steer-file",
2749
2935
  steerFile,
2750
2936
  ...this.config.childQuestions === "route" && capabilities2.questions ? [
@@ -2785,6 +2971,7 @@ var AgentManager = class {
2785
2971
  workerArguments: [...runnerLaunch.workerArguments]
2786
2972
  };
2787
2973
  if (this.#closing) throw new Error("Fabric agent manager is closing");
2974
+ const recoveryPolicy = this.config.durableWorkerRecovery === true && residency === "durable" && runner === "pi-durable" && adapter.kind === "process" && process.platform !== "win32" ? this.#workerRecoveryPolicy() : void 0;
2788
2975
  const transport = await this.#launchTransport(adapter, launch);
2789
2976
  const lifecycle = createAgentLifecycle(release);
2790
2977
  if (signal?.aborted || this.#closing) {
@@ -2844,6 +3031,10 @@ var AgentManager = class {
2844
3031
  }
2845
3032
  this.#runs.set(id, managed);
2846
3033
  this.#unregisteredTransports.delete(transport);
3034
+ if (recoveryPolicy !== void 0) {
3035
+ managed.workerRecovery = { deadlineAt: Date.now() + timeoutMs, policy: recoveryPolicy };
3036
+ this.#persistWorkerRecovery(managed);
3037
+ }
2847
3038
  this.#invalidateUiList();
2848
3039
  void this.#monitor(managed, timeoutMs);
2849
3040
  return this.#handleInfo(managed, "running");
@@ -2882,7 +3073,7 @@ var AgentManager = class {
2882
3073
  const hosted = await HostedRun.prepare(
2883
3074
  adapter,
2884
3075
  { ...context, idempotencyKey: context.id },
2885
- { ...launch.files, stateFile: path12.join(context.runDirectory, HOSTED_STATE_FILE) },
3076
+ { ...launch.files, stateFile: path13.join(context.runDirectory, HOSTED_STATE_FILE) },
2886
3077
  record,
2887
3078
  this.#hostedHooks(() => managed, launch.request.holdQuestions === true)
2888
3079
  );
@@ -2969,17 +3160,17 @@ var AgentManager = class {
2969
3160
  async recoverHostedRuns() {
2970
3161
  let entries;
2971
3162
  try {
2972
- entries = fs11.readdirSync(this.#runRoot);
3163
+ entries = fs12.readdirSync(this.#runRoot);
2973
3164
  } catch {
2974
3165
  return [];
2975
3166
  }
2976
3167
  const recovered = [];
2977
3168
  for (const entry of entries) {
2978
3169
  if (this.#closing || this.#runs.has(entry) || !/^[0-9a-f]{32}$/.test(entry)) continue;
2979
- const runDirectory = path12.join(this.#runRoot, entry);
2980
- const statusFile = path12.join(runDirectory, "status.json");
3170
+ const runDirectory = path13.join(this.#runRoot, entry);
3171
+ const statusFile = path13.join(runDirectory, "status.json");
2981
3172
  const record = readRecord(statusFile);
2982
- const state = readHostedRunState(path12.join(runDirectory, HOSTED_STATE_FILE));
3173
+ const state = readHostedRunState(path13.join(runDirectory, HOSTED_STATE_FILE));
2983
3174
  if (!record?.hosted || !state || record.id !== entry || state.context.id !== entry || terminalStatuses.has(record.status)) {
2984
3175
  continue;
2985
3176
  }
@@ -3011,9 +3202,9 @@ var AgentManager = class {
3011
3202
  state,
3012
3203
  {
3013
3204
  statusFile,
3014
- lifecycleFile: path12.join(runDirectory, "lifecycle.jsonl"),
3015
- logFile: path12.join(runDirectory, "events.jsonl"),
3016
- stateFile: path12.join(runDirectory, HOSTED_STATE_FILE)
3205
+ lifecycleFile: path13.join(runDirectory, "lifecycle.jsonl"),
3206
+ logFile: path13.join(runDirectory, "events.jsonl"),
3207
+ stateFile: path13.join(runDirectory, HOSTED_STATE_FILE)
3017
3208
  },
3018
3209
  record,
3019
3210
  this.#hostedHooks(() => managed, state.holdQuestions === true)
@@ -3026,6 +3217,241 @@ var AgentManager = class {
3026
3217
  }
3027
3218
  return recovered;
3028
3219
  }
3220
+ #workerRecoveryPolicy() {
3221
+ return JSON.stringify({
3222
+ config: this.config,
3223
+ worker: this.#workerPath,
3224
+ pi: this.#piBinary,
3225
+ claude: this.#claudeBinary,
3226
+ veda: this.#vedaBinary,
3227
+ extension: this.#fabricExtensionPath,
3228
+ project: this.#projectRoot,
3229
+ mesh: this.#meshRoot,
3230
+ host: this.#hostId,
3231
+ identity: this.#identityId,
3232
+ depth: this.#currentDepth,
3233
+ fullCodeMode: this.#fullCodeMode,
3234
+ writePolicy: this.#parentWritePolicy,
3235
+ lineage: this.#parentLineage,
3236
+ thinkingBounds: this.#thinkingBounds?.(),
3237
+ kernel: this.#kernel(),
3238
+ pythonRuntime: this.#pythonRuntime(),
3239
+ executor: this.#executorRuntime?.(),
3240
+ inheritedTools: this.#inheritedToolAllowlist?.entries,
3241
+ // Exact fabric_exec authority is stored outside entries; pin both so
3242
+ // revoking recursion cannot reuse an otherwise identical launch receipt.
3243
+ inheritedFabricExec: this.#inheritedToolAllowlist?.fabricExec
3244
+ });
3245
+ }
3246
+ #persistWorkerRecovery(managed) {
3247
+ if (!managed.workerRecovery) return;
3248
+ if (managed.stopRequested || managed.settled) {
3249
+ removeWorkerRecovery(managed.runDirectory);
3250
+ return;
3251
+ }
3252
+ const pid = Number(managed.transport.sessionId);
3253
+ if (!Number.isSafeInteger(pid) || pid <= 0) {
3254
+ delete managed.workerRecovery;
3255
+ removeWorkerRecovery(managed.runDirectory);
3256
+ return;
3257
+ }
3258
+ const recovery = {
3259
+ format: WORKER_RECOVERY_FORMAT,
3260
+ id: managed.id,
3261
+ runner: "pi-durable",
3262
+ deadlineAt: managed.workerRecovery.deadlineAt,
3263
+ pid,
3264
+ launch: {
3265
+ id: managed.launch.id,
3266
+ name: managed.launch.name,
3267
+ cwd: managed.launch.cwd,
3268
+ workerPath: managed.launch.workerPath,
3269
+ workerArguments: [...managed.launch.workerArguments]
3270
+ },
3271
+ writtenAt: Date.now()
3272
+ };
3273
+ authorizeWorkerRecovery(managed.runDirectory, recovery, managed.workerRecovery.policy);
3274
+ writeWorkerRecovery(managed.runDirectory, recovery);
3275
+ }
3276
+ /**
3277
+ * Re-attach opted-in pi-durable worker runs (agents.durableWorkerRecovery)
3278
+ * left unfinished under this run root by an earlier host. A verified live
3279
+ * worker is adopted; a dead one is relaunched on its own durable journal
3280
+ * with its progress carried over; a run whose deadline passed, or whose
3281
+ * worker Fabric cannot verify either way, settles failed with outcome
3282
+ * "indeterminate" instead of being guessed at.
3283
+ */
3284
+ async recoverWorkerRuns() {
3285
+ let entries;
3286
+ try {
3287
+ entries = fs12.readdirSync(this.#runRoot);
3288
+ } catch {
3289
+ return [];
3290
+ }
3291
+ const recovered = [];
3292
+ for (const entry of entries) {
3293
+ if (this.#closing || this.#runs.has(entry) || !/^[0-9a-f]{32}$/.test(entry)) continue;
3294
+ const runDirectory = path13.join(this.#runRoot, entry);
3295
+ const recovery = readWorkerRecovery(runDirectory);
3296
+ const statusFile = path13.join(runDirectory, "status.json");
3297
+ const record = readRecord(statusFile);
3298
+ if (!recovery || recovery.id !== entry) {
3299
+ if (!hasWorkerRecovery(runDirectory)) continue;
3300
+ removeWorkerRecovery(runDirectory);
3301
+ if (record?.id === entry && !record.hosted && (!terminalStatuses.has(record.status) || record.status === "stopped")) {
3302
+ const { currentTool: _tool, blockedOn: _blocked, sleeping: _sleeping, ...rest } = record;
3303
+ const now2 = Date.now();
3304
+ writeRecord(statusFile, {
3305
+ ...rest,
3306
+ status: "failed",
3307
+ outcome: "indeterminate",
3308
+ error: "Invalid durable worker recovery marker; the run outcome is indeterminate",
3309
+ updatedAt: now2,
3310
+ finishedAt: now2
3311
+ });
3312
+ }
3313
+ continue;
3314
+ }
3315
+ if (!record || record.id !== entry) {
3316
+ const now2 = Date.now();
3317
+ removeWorkerRecovery(runDirectory);
3318
+ writeRecord(statusFile, {
3319
+ id: entry,
3320
+ name: recovery.launch.name,
3321
+ task: "",
3322
+ runner: "pi-durable",
3323
+ cwd: recovery.launch.cwd,
3324
+ residency: "durable",
3325
+ transport: "process",
3326
+ status: "failed",
3327
+ outcome: "indeterminate",
3328
+ error: "Durable worker recovery has no valid initial status; the run outcome is indeterminate",
3329
+ startedAt: recovery.writtenAt,
3330
+ updatedAt: now2,
3331
+ finishedAt: now2,
3332
+ turns: 0,
3333
+ toolCalls: 0,
3334
+ text: "",
3335
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 }
3336
+ });
3337
+ continue;
3338
+ }
3339
+ if (record.hosted) continue;
3340
+ if (terminalStatuses.has(record.status) && record.status !== "stopped") {
3341
+ removeWorkerRecovery(runDirectory);
3342
+ continue;
3343
+ }
3344
+ const now = Date.now();
3345
+ const indeterminate = (reason) => {
3346
+ const { currentTool: _tool, blockedOn: _blocked, sleeping: _sleeping, ...rest } = record;
3347
+ removeWorkerRecovery(runDirectory);
3348
+ writeRecord(statusFile, {
3349
+ ...rest,
3350
+ status: "failed",
3351
+ error: `${reason}; the run outcome is indeterminate`,
3352
+ outcome: "indeterminate",
3353
+ finishedAt: now,
3354
+ updatedAt: now
3355
+ });
3356
+ };
3357
+ const runnerAdapter = getAgentRunner("pi-durable");
3358
+ if (runnerAdapter?.kind !== "worker") {
3359
+ indeterminate("The pi-durable runner is not registered in this process");
3360
+ continue;
3361
+ }
3362
+ const policy = this.#workerRecoveryPolicy();
3363
+ const authority = readWorkerRecoveryAuthority(runDirectory, policy);
3364
+ if (!authority || workerRecoveryMismatch(recovery, { runDirectory, workerPath: this.#workerPath, cwd: record.cwd, policy })) {
3365
+ indeterminate("The recovery file does not match this host");
3366
+ continue;
3367
+ }
3368
+ if (authority.deadlineAt <= now) {
3369
+ indeterminate("The durable worker run passed its deadline while no resident host owned it");
3370
+ continue;
3371
+ }
3372
+ let liveness = probeWorker(authority.pid, entry);
3373
+ if (record.status === "stopped" && liveness === "alive") {
3374
+ liveness = await this.#waitForWorkerExit(authority.pid, entry);
3375
+ if (liveness === "alive") {
3376
+ indeterminate(`Worker process ${recovery.pid} recorded a stop but did not exit`);
3377
+ continue;
3378
+ }
3379
+ }
3380
+ if (liveness === "unknown") {
3381
+ indeterminate(`Fabric cannot verify whether worker process ${recovery.pid} is still running`);
3382
+ continue;
3383
+ }
3384
+ if (liveness === "dead" && !fs12.existsSync(authority.launch.workerPath)) {
3385
+ indeterminate(`The worker entry ${recovery.launch.workerPath} no longer exists`);
3386
+ continue;
3387
+ }
3388
+ const argument = (name) => {
3389
+ const index = authority.launch.workerArguments.indexOf(`--${name}`);
3390
+ return index < 0 ? void 0 : authority.launch.workerArguments[index + 1];
3391
+ };
3392
+ const kernel = argument("kernel");
3393
+ const model = argument("model");
3394
+ const thinking = argument("thinking");
3395
+ const branch = argument("branch");
3396
+ const worktree = argument("worktree");
3397
+ const adapter = await this.#resolveTransport("process");
3398
+ const managed = {
3399
+ id: entry,
3400
+ name: record.name,
3401
+ task: record.task,
3402
+ runner: "pi-durable",
3403
+ runnerAdapter,
3404
+ ...kernel === "typescript" || kernel === "python" ? { kernel } : {},
3405
+ recursive: JSON.parse(argument("granted-risks") ?? "[]").includes("agent"),
3406
+ residency: "durable",
3407
+ cwd: record.cwd,
3408
+ statusFile,
3409
+ lifecycleFile: path13.join(runDirectory, "lifecycle.jsonl"),
3410
+ // Events before this point reached the previous host's ledger.
3411
+ lifecycleOffset: fileSize(path13.join(runDirectory, "lifecycle.jsonl")),
3412
+ lifecycleRemainder: Buffer.alloc(0),
3413
+ runDirectory,
3414
+ transport: adoptedWorkerHandle(authority.pid, entry),
3415
+ adapter,
3416
+ launch: authority.launch,
3417
+ startupAttempts: 1,
3418
+ ...createAgentLifecycle(() => {
3419
+ }),
3420
+ abortSignal: void 0,
3421
+ abortHandler: void 0,
3422
+ ...model ? { model } : {},
3423
+ ...thinking ? { thinking } : {},
3424
+ ...branch ? { branch } : {},
3425
+ ...worktree ? { worktree } : {},
3426
+ workerRecovery: { deadlineAt: authority.deadlineAt, policy },
3427
+ settled: false,
3428
+ background: true,
3429
+ lastLivenessCheckAt: 0,
3430
+ resumeAttempts: 0,
3431
+ stopRequested: false,
3432
+ observedProgress: { turns: record.turns, toolCalls: record.toolCalls, usage: { ...record.usage } },
3433
+ usageEmitted: { ...record.usage }
3434
+ };
3435
+ this.#runs.set(entry, managed);
3436
+ this.#invalidateUiList();
3437
+ if (liveness === "dead") {
3438
+ managed.resumeAttempts += 1;
3439
+ const { turns, toolCalls, usage } = managed.observedProgress;
3440
+ const relaunched = await this.#relaunch(managed, record, {
3441
+ task: managed.task,
3442
+ carryOver: { turns, toolCalls, usage: { ...usage } }
3443
+ });
3444
+ if (!relaunched) {
3445
+ const failed = readRecord(statusFile) ?? record;
3446
+ this.#settle(managed, this.#withTransportMetadata(failed, managed));
3447
+ continue;
3448
+ }
3449
+ }
3450
+ void this.#monitor(managed, Math.max(0, recovery.deadlineAt - Date.now()));
3451
+ recovered.push(entry);
3452
+ }
3453
+ return recovered;
3454
+ }
3029
3455
  /** Park or resume a hosted run whose runner declares `sleep`. */
3030
3456
  async sleep(id) {
3031
3457
  await this.#requireHosted(id, "sleep").park("sleep");
@@ -3193,6 +3619,7 @@ var AgentManager = class {
3193
3619
  async stop(id) {
3194
3620
  const managed = this.#requireRun(id);
3195
3621
  managed.stopRequested = true;
3622
+ if (managed.workerRecovery) removeWorkerRecovery(managed.runDirectory);
3196
3623
  if (managed.settled) return this.wait(id);
3197
3624
  managed.background = false;
3198
3625
  const existing = readRecord(managed.statusFile);
@@ -3223,15 +3650,15 @@ var AgentManager = class {
3223
3650
  this.#runs.delete(id);
3224
3651
  this.#pruneRetainedUiRecords();
3225
3652
  this.#invalidateUiList();
3226
- return { cleaned: cleaned || !fs11.existsSync(managed.runDirectory) };
3653
+ return { cleaned: cleaned || !fs12.existsSync(managed.runDirectory) };
3227
3654
  }
3228
3655
  readLog(id, opts = {}) {
3229
3656
  const managed = this.#requireRun(id);
3230
3657
  const runDirectory = managed.runDirectory;
3231
- const logFile = path12.join(runDirectory, "events.jsonl");
3658
+ const logFile = path13.join(runDirectory, "events.jsonl");
3232
3659
  const lines = Math.max(1, Math.min(opts.lines ?? 200, 5e3));
3233
3660
  const page = readJsonlPage(logFile, lines, opts.before);
3234
- const statusRecord = readRecord(path12.join(runDirectory, "status.json"));
3661
+ const statusRecord = readRecord(path13.join(runDirectory, "status.json"));
3235
3662
  return {
3236
3663
  id,
3237
3664
  runDirectory,
@@ -3306,10 +3733,10 @@ var AgentManager = class {
3306
3733
  `Fabric agent ${id} already finished (${record.status}); steering has no target`
3307
3734
  );
3308
3735
  }
3309
- const steerFile = path12.join(managed.runDirectory, "steer.jsonl");
3736
+ const steerFile = path13.join(managed.runDirectory, "steer.jsonl");
3310
3737
  const messageId = randomUUID4();
3311
3738
  const line = JSON.stringify({ ...entry, id: messageId, ts: Date.now() }) + "\n";
3312
- fs11.appendFileSync(steerFile, line, { encoding: "utf8", mode: 384 });
3739
+ fs12.appendFileSync(steerFile, line, { encoding: "utf8", mode: 384 });
3313
3740
  return { queued: true, messageId };
3314
3741
  }
3315
3742
  close() {
@@ -3330,13 +3757,21 @@ var AgentManager = class {
3330
3757
  managed.questions?.abort(new Error("Fabric resident host detached the run"));
3331
3758
  }
3332
3759
  await Promise.allSettled(detached.flatMap((managed) => [...managed.asks ?? []]));
3760
+ for (const managed of this.#runs.values()) {
3761
+ if (!managed.settled && !managed.stopRequested && managed.workerRecovery && managed.residency === "durable") {
3762
+ managed.workerDetached = true;
3763
+ detached.push(managed);
3764
+ }
3765
+ }
3333
3766
  const running = [...this.#runs.values()].filter((managed) => !managed.settled && !detached.includes(managed));
3334
3767
  for (const managed of running) managed.hosted?.markShutdown();
3335
3768
  await Promise.allSettled(running.map((managed) => this.stop(managed.id)));
3336
3769
  await Promise.allSettled([...this.#spawns]);
3337
3770
  await Promise.allSettled([...this.#launches]);
3338
3771
  const all = [...this.#runs.values()];
3339
- await Promise.allSettled(all.map((managed) => this.#waitForTransportExit(managed)));
3772
+ await Promise.allSettled(
3773
+ all.filter((managed) => !managed.workerDetached).map((managed) => this.#waitForTransportExit(managed))
3774
+ );
3340
3775
  const transports2 = [...all.map((managed) => managed.transport), ...this.#unregisteredTransports];
3341
3776
  const alive = await Promise.all(transports2.map((transport) => transport.isAlive().catch(() => true)));
3342
3777
  if (detached.length === 0 && !alive.some(Boolean)) {
@@ -3354,7 +3789,7 @@ var AgentManager = class {
3354
3789
  removeEmptyRunRoot(this.#runRoot);
3355
3790
  }
3356
3791
  if (storageSafe && this.#budgetOwned && this.#budget) {
3357
- await removeTree(path12.dirname(this.#budget.file)).catch(() => void 0);
3792
+ await removeTree(path13.dirname(this.#budget.file)).catch(() => void 0);
3358
3793
  }
3359
3794
  }
3360
3795
  if (this.#budgetOwned) clearOwnedBudgetEnv();
@@ -3396,7 +3831,7 @@ var AgentManager = class {
3396
3831
  });
3397
3832
  for (const managed of expired) {
3398
3833
  await removeTree(managed.runDirectory).catch(() => void 0);
3399
- if (!fs11.existsSync(managed.runDirectory)) this.#runs.delete(managed.id);
3834
+ if (!fs12.existsSync(managed.runDirectory)) this.#runs.delete(managed.id);
3400
3835
  }
3401
3836
  if (expired.length > 0) {
3402
3837
  this.#pruneRetainedUiRecords();
@@ -3409,6 +3844,16 @@ var AgentManager = class {
3409
3844
  if (runner.kind !== "worker" || !runner.stop) return;
3410
3845
  await Promise.resolve().then(() => runner.stop({ id: managed.id, runDirectory: managed.runDirectory })).catch(() => void 0);
3411
3846
  }
3847
+ /** Bounded like #waitForTransportExit; returns the last liveness seen. */
3848
+ async #waitForWorkerExit(pid, id) {
3849
+ const deadline = Date.now() + TRANSPORT_EXIT_GRACE_MS * 7;
3850
+ let liveness = probeWorker(pid, id);
3851
+ while (liveness === "alive" && Date.now() < deadline && !this.#closing) {
3852
+ await delay(AGENT_STATUS_POLL_INTERVAL_MS);
3853
+ liveness = probeWorker(pid, id);
3854
+ }
3855
+ return liveness;
3856
+ }
3412
3857
  async #waitForTransportExit(managed) {
3413
3858
  const deadline = Date.now() + TRANSPORT_EXIT_GRACE_MS * 7;
3414
3859
  const pollIntervalMs = managed.transport.livenessPollIntervalMs ?? AGENT_STATUS_POLL_INTERVAL_MS;
@@ -3479,8 +3924,15 @@ var AgentManager = class {
3479
3924
  delete managed.model;
3480
3925
  }
3481
3926
  }
3927
+ if (managed.workerRecovery) {
3928
+ setWorkerArgument(
3929
+ managed.launch.workerArguments,
3930
+ "timeout-ms",
3931
+ String(Math.max(1, managed.workerRecovery.deadlineAt - Date.now()))
3932
+ );
3933
+ }
3482
3934
  if (resume) {
3483
- fs11.writeFileSync(path12.join(managed.runDirectory, "task.txt"), resume.task, {
3935
+ fs12.writeFileSync(path13.join(managed.runDirectory, "task.txt"), resume.task, {
3484
3936
  encoding: "utf8",
3485
3937
  mode: 384
3486
3938
  });
@@ -3503,12 +3955,13 @@ var AgentManager = class {
3503
3955
  }
3504
3956
  this.#drainLifecycle(managed);
3505
3957
  if (managed.settled || this.#closing || managed.stopRequested) return false;
3506
- fs11.rmSync(managed.statusFile, { force: true });
3958
+ fs12.rmSync(managed.statusFile, { force: true });
3507
3959
  managed.lifecycleOffset = 0;
3508
3960
  managed.lifecycleRemainder = Buffer.alloc(0);
3509
- fs11.rmSync(managed.lifecycleFile, { force: true });
3961
+ fs12.rmSync(managed.lifecycleFile, { force: true });
3510
3962
  managed.transport = await this.#launchTransport(managed.adapter, managed.launch);
3511
3963
  this.#unregisteredTransports.delete(managed.transport);
3964
+ if (managed.workerRecovery) this.#persistWorkerRecovery(managed);
3512
3965
  if (managed.settled || this.#closing || managed.stopRequested) {
3513
3966
  await managed.transport.stop().catch(() => void 0);
3514
3967
  return false;
@@ -3569,6 +4022,7 @@ var AgentManager = class {
3569
4022
  let firstObservedDeadAt;
3570
4023
  while (!managed.settled) {
3571
4024
  if (managed.hosted?.detached) return;
4025
+ if (managed.workerDetached) return;
3572
4026
  this.#drainLifecycle(managed);
3573
4027
  const record = readRecord(managed.statusFile);
3574
4028
  if (record) {
@@ -3674,6 +4128,7 @@ var AgentManager = class {
3674
4128
  }
3675
4129
  #settle(managed, result) {
3676
4130
  if (managed.settled) return;
4131
+ if (managed.workerRecovery) removeWorkerRecovery(managed.runDirectory);
3677
4132
  if (managed.worktreeResult) result.worktreeResult = managed.worktreeResult;
3678
4133
  const nested = this.#nestedAgents(managed, true);
3679
4134
  if (nested.length > 0) result.nestedAgents = reconcileNestedAgents(nested, result);
@@ -3682,7 +4137,7 @@ var AgentManager = class {
3682
4137
  managed.questions?.abort(new Error("Agent run settled"));
3683
4138
  managed.hosted?.close();
3684
4139
  try {
3685
- fs11.rmSync(path12.join(managed.runDirectory, "images.json"), { force: true });
4140
+ fs12.rmSync(path13.join(managed.runDirectory, "images.json"), { force: true });
3686
4141
  } catch {
3687
4142
  }
3688
4143
  this.#emitLifecycle(managed, `run.${result.status}`, result.finishedAt ?? Date.now(), {
@@ -3717,7 +4172,7 @@ var AgentManager = class {
3717
4172
  #drainLifecycle(managed) {
3718
4173
  let content;
3719
4174
  try {
3720
- content = fs11.readFileSync(managed.lifecycleFile);
4175
+ content = fs12.readFileSync(managed.lifecycleFile);
3721
4176
  } catch {
3722
4177
  return;
3723
4178
  }
@@ -3770,8 +4225,8 @@ var AgentManager = class {
3770
4225
  const requestId = question.requestId;
3771
4226
  const steer = (command) => {
3772
4227
  try {
3773
- fs11.appendFileSync(
3774
- path12.join(managed.runDirectory, "steer.jsonl"),
4228
+ fs12.appendFileSync(
4229
+ path13.join(managed.runDirectory, "steer.jsonl"),
3775
4230
  `${JSON.stringify({ ...command, id: randomUUID4(), ts: Date.now() })}
3776
4231
  `,
3777
4232
  { encoding: "utf8", mode: 384 }
@@ -3880,7 +4335,8 @@ var AgentManager = class {
3880
4335
  #inheritedToolAllowlist = readChildToolAllowlist();
3881
4336
  #childTools(request, runner, requiresFabricKernel = false) {
3882
4337
  const requested = request.tools ?? this.config.defaultTools;
3883
- const tools = requested.filter(
4338
+ const nativePi = runner.id === "pi" || runner.id === "pi-durable";
4339
+ const tools = nativePi ? constrainChildToolSelection(requested, this.#inheritedToolAllowlist) : requested.filter(
3884
4340
  (tool) => tool !== "fabric_exec" && (this.#inheritedToolAllowlist === void 0 || this.#inheritedToolAllowlist.has(tool))
3885
4341
  );
3886
4342
  const extensions = request.recursive === true ? true : request.extensions ?? this.config.extensions;
@@ -3889,8 +4345,8 @@ var AgentManager = class {
3889
4345
  if (this.#inheritedToolAllowlist === void 0 || this.#inheritedToolAllowlist.has(tool)) tools.push(tool);
3890
4346
  }
3891
4347
  }
3892
- if (runner.capabilities.recursiveFabric && (request.recursive || (this.#fullCodeMode || requiresFabricKernel) && extensions)) {
3893
- tools.push("fabric_exec");
4348
+ if (request.recursiveToolAuthority === void 0 && !requested.includes("-fabric_exec") && (this.#inheritedToolAllowlist === void 0 || this.#inheritedToolAllowlist.fabricExec) && runner.capabilities.recursiveFabric && (request.recursive || (this.#fullCodeMode || requiresFabricKernel) && extensions)) {
4349
+ tools.push(nativePi && tools.some((tool) => tool.startsWith("+") || tool.startsWith("-")) ? "+fabric_exec" : "fabric_exec");
3894
4350
  }
3895
4351
  return [...new Set(tools)];
3896
4352
  }
@@ -3983,7 +4439,7 @@ var AgentManager = class {
3983
4439
  // directories. Terminal-owner reconciliation prevents cached active ghosts.
3984
4440
  #nestedAgents(managed, force = false) {
3985
4441
  const now = Date.now();
3986
- const needsInitialDiscovery = managed.nestedSnapshot === void 0 && fs11.existsSync(path12.join(managed.runDirectory, "nested"));
4442
+ const needsInitialDiscovery = managed.nestedSnapshot === void 0 && fs12.existsSync(path13.join(managed.runDirectory, "nested"));
3987
4443
  if (!force && !needsInitialDiscovery && managed.nestedSnapshotAt !== void 0 && now - managed.nestedSnapshotAt < NESTED_SNAPSHOT_POLL_MS) {
3988
4444
  return managed.nestedSnapshot ? structuredClone(managed.nestedSnapshot) : [];
3989
4445
  }
@@ -4011,7 +4467,7 @@ var AgentManager = class {
4011
4467
  runner: managed.runner,
4012
4468
  ...managed.kernel ? { kernel: managed.kernel } : {},
4013
4469
  ...managed.residency === "durable" ? { residency: "durable" } : {},
4014
- logFile: path12.join(managed.runDirectory, "events.jsonl"),
4470
+ logFile: path13.join(managed.runDirectory, "events.jsonl"),
4015
4471
  ...nestedAgents.length > 0 ? { nestedAgents } : {},
4016
4472
  ...budget ? { budget } : {},
4017
4473
  ...model ? { model } : {},
@@ -4067,15 +4523,15 @@ var actorDeliveryNotice = (delivery, triggerTurn) => {
4067
4523
  };
4068
4524
 
4069
4525
  // src/actors/directory.ts
4070
- import fs18 from "node:fs";
4526
+ import fs19 from "node:fs";
4071
4527
 
4072
4528
  // src/actors/manager.ts
4073
4529
  import { randomUUID as randomUUID7 } from "node:crypto";
4074
- import fs17 from "node:fs";
4530
+ import fs18 from "node:fs";
4075
4531
 
4076
4532
  // src/actors/mesh-monitor.ts
4077
- import fs12 from "node:fs";
4078
- import path13 from "node:path";
4533
+ import fs13 from "node:fs";
4534
+ import path14 from "node:path";
4079
4535
  var MESH_WATCH_RECONCILE_MS = 2e3;
4080
4536
  var ActorMeshMonitor = class {
4081
4537
  constructor(mesh, config, callbacks) {
@@ -4102,8 +4558,8 @@ var ActorMeshMonitor = class {
4102
4558
  return;
4103
4559
  }
4104
4560
  try {
4105
- const watcher = fs12.watch(this.mesh.root, { persistent: false }, (_event, filename) => {
4106
- const name = filename == null ? void 0 : path13.basename(filename.toString());
4561
+ const watcher = fs13.watch(this.mesh.root, { persistent: false }, (_event, filename) => {
4562
+ const name = filename == null ? void 0 : path14.basename(filename.toString());
4107
4563
  if (name !== void 0 && name !== "events.jsonl" && name !== "schedules.json") return;
4108
4564
  this.schedule();
4109
4565
  });
@@ -4192,7 +4648,7 @@ var ActorMeshMonitor = class {
4192
4648
  #readCursor() {
4193
4649
  if (!this.callbacks.cursorPath) return void 0;
4194
4650
  try {
4195
- const value = JSON.parse(fs12.readFileSync(this.callbacks.cursorPath, "utf8"));
4651
+ const value = JSON.parse(fs13.readFileSync(this.callbacks.cursorPath, "utf8"));
4196
4652
  return value.format === 1 && typeof value.cursor === "number" && value.cursor >= 0 ? value.cursor : void 0;
4197
4653
  } catch {
4198
4654
  return void 0;
@@ -4209,11 +4665,11 @@ var ActorMeshMonitor = class {
4209
4665
 
4210
4666
  // src/actors/manager.ts
4211
4667
  import os4 from "node:os";
4212
- import path17 from "node:path";
4668
+ import path18 from "node:path";
4213
4669
 
4214
4670
  // src/actors/log-store.ts
4215
- import fs13 from "node:fs";
4216
- import path14 from "node:path";
4671
+ import fs14 from "node:fs";
4672
+ import path15 from "node:path";
4217
4673
  var ACTOR_MESSAGE_HISTORY_LIMIT = 100;
4218
4674
  var ACTOR_MESSAGE_ENVELOPE_BYTES = 4096;
4219
4675
  var ACTOR_TRUNCATION_SUFFIX = "\n[actor message truncated]";
@@ -4271,17 +4727,17 @@ var ActorLogStore = class {
4271
4727
  this.retention = retention;
4272
4728
  }
4273
4729
  async retainRun(actor, runId, runDirectory) {
4274
- if (!runDirectory || !fs13.existsSync(runDirectory)) return;
4275
- const dest = path14.join(path14.dirname(actor.sessionFile), "runs", runId);
4276
- fs13.mkdirSync(dest, { recursive: true, mode: 448 });
4730
+ if (!runDirectory || !fs14.existsSync(runDirectory)) return;
4731
+ const dest = path15.join(path15.dirname(actor.sessionFile), "runs", runId);
4732
+ fs14.mkdirSync(dest, { recursive: true, mode: 448 });
4277
4733
  for (const file of ["events.jsonl", "status.json", "task.txt"]) {
4278
- const src = path14.join(runDirectory, file);
4279
- if (fs13.existsSync(src)) fs13.copyFileSync(src, path14.join(dest, file));
4734
+ const src = path15.join(runDirectory, file);
4735
+ if (fs14.existsSync(src)) fs14.copyFileSync(src, path15.join(dest, file));
4280
4736
  }
4281
- const nested = path14.join(runDirectory, "nested");
4282
- if (fs13.existsSync(nested)) {
4737
+ const nested = path15.join(runDirectory, "nested");
4738
+ if (fs14.existsSync(nested)) {
4283
4739
  try {
4284
- fs13.cpSync(nested, path14.join(dest, "nested"), { recursive: true });
4740
+ fs14.cpSync(nested, path15.join(dest, "nested"), { recursive: true });
4285
4741
  } catch {
4286
4742
  }
4287
4743
  }
@@ -4289,16 +4745,16 @@ var ActorLogStore = class {
4289
4745
  }
4290
4746
  pruneRuns(actor, now = Date.now()) {
4291
4747
  pruneActorRunArchives({
4292
- runsDirectory: path14.join(path14.dirname(actor.sessionFile), "runs"),
4748
+ runsDirectory: path15.join(path15.dirname(actor.sessionFile), "runs"),
4293
4749
  ...actor.lastRunId ? { latestRunId: actor.lastRunId } : {},
4294
4750
  retentionMs: this.retention.actorRunArchiveMs,
4295
4751
  now
4296
4752
  });
4297
4753
  }
4298
4754
  retainedRunIds(actor) {
4299
- const runsDir = path14.join(path14.dirname(actor.sessionFile), "runs");
4755
+ const runsDir = path15.join(path15.dirname(actor.sessionFile), "runs");
4300
4756
  try {
4301
- return fs13.readdirSync(runsDir).sort();
4757
+ return fs14.readdirSync(runsDir).sort();
4302
4758
  } catch {
4303
4759
  return [];
4304
4760
  }
@@ -4420,11 +4876,11 @@ var evaluateActorValidWhile = async (source, facts) => {
4420
4876
 
4421
4877
  // src/actors/binding-store.ts
4422
4878
  import { createHash, randomUUID as randomUUID5 } from "node:crypto";
4423
- import fs15 from "node:fs";
4424
- import path15 from "node:path";
4879
+ import fs16 from "node:fs";
4880
+ import path16 from "node:path";
4425
4881
 
4426
4882
  // src/actors/store-read.ts
4427
- import fs14 from "node:fs";
4883
+ import fs15 from "node:fs";
4428
4884
  var ActorStoreReadError = class extends Error {
4429
4885
  filePath;
4430
4886
  constructor(filePath, detail, options) {
@@ -4436,7 +4892,7 @@ var ActorStoreReadError = class extends Error {
4436
4892
  var readStoreJson = (filePath) => {
4437
4893
  let text;
4438
4894
  try {
4439
- text = fs14.readFileSync(filePath, "utf8");
4895
+ text = fs15.readFileSync(filePath, "utf8");
4440
4896
  } catch (error) {
4441
4897
  if (error?.code === "ENOENT") return void 0;
4442
4898
  throw new ActorStoreReadError(
@@ -4461,12 +4917,11 @@ var BINDING_LOCK_TIMEOUT_MS = 5e3;
4461
4917
  var BINDING_STALE_LOCK_MS = 3e4;
4462
4918
  var bindingFileName = (sessionId) => `${createHash("sha256").update(sessionId).digest("hex")}.json`;
4463
4919
  var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4464
- var errorCode = (error) => error instanceof Error && "code" in error ? String(error.code) : void 0;
4465
4920
  var delay2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
4466
4921
  var ActorBindingStore = class {
4467
4922
  constructor(sessionId, root) {
4468
4923
  this.sessionId = sessionId;
4469
- this.filePath = root ? path15.join(root, "bindings", bindingFileName(sessionId)) : void 0;
4924
+ this.filePath = root ? path16.join(root, "bindings", bindingFileName(sessionId)) : void 0;
4470
4925
  this.#sync(true);
4471
4926
  }
4472
4927
  #bindings = /* @__PURE__ */ new Map();
@@ -4599,7 +5054,7 @@ var ActorBindingStore = class {
4599
5054
  #currentFingerprint() {
4600
5055
  if (!this.filePath) return void 0;
4601
5056
  try {
4602
- const stat = fs15.statSync(this.filePath);
5057
+ const stat = fs16.statSync(this.filePath);
4603
5058
  return `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeMs}`;
4604
5059
  } catch {
4605
5060
  return void 0;
@@ -4608,7 +5063,6 @@ var ActorBindingStore = class {
4608
5063
  async #withLock(operation) {
4609
5064
  if (!this.filePath) return operation();
4610
5065
  const lockPath = `${this.filePath}.lock`;
4611
- const ownerPath2 = path15.join(lockPath, "owner");
4612
5066
  const deadline = Date.now() + BINDING_LOCK_TIMEOUT_MS;
4613
5067
  const token = randomUUID5();
4614
5068
  const processAlive2 = (pid) => {
@@ -4620,72 +5074,29 @@ var ActorBindingStore = class {
4620
5074
  return false;
4621
5075
  }
4622
5076
  };
4623
- fs15.mkdirSync(path15.dirname(this.filePath), { recursive: true, mode: 448 });
4624
- while (true) {
4625
- try {
4626
- fs15.mkdirSync(lockPath, { mode: 448 });
4627
- fs15.writeFileSync(ownerPath2, `${token}
4628
- ${process.pid}
4629
- ${Date.now()}
4630
- ${encodeOwnerIdentityLine()}
4631
- `, {
4632
- encoding: "utf8",
4633
- mode: 384
4634
- });
4635
- break;
4636
- } catch (error) {
4637
- if (errorCode(error) !== "EEXIST") throw error;
4638
- try {
4639
- const firstOwner = fs15.readFileSync(ownerPath2, "utf8");
4640
- const [, pidText, createdText, identityLine] = firstOwner.trim().split("\n");
4641
- const stale = Date.now() - Number(createdText) > BINDING_STALE_LOCK_MS;
4642
- const dead = stale ? lockOwnerLiveness(Number(pidText), Number(createdText), identityLine, {
4643
- legacyAlive: processAlive2,
4644
- maxHoldMs: Math.max(SHORT_LOCK_MAX_HOLD_MS, BINDING_STALE_LOCK_MS)
4645
- }) === "dead" : lockOwnerProvablyDead(Number(pidText), identityLine);
4646
- if (dead) {
4647
- const secondOwner = fs15.readFileSync(ownerPath2, "utf8");
4648
- if (secondOwner === firstOwner && reapLockByRenameClaim(lockPath, (claimed) => {
4649
- try {
4650
- return fs15.readFileSync(path15.join(claimed, "owner"), "utf8") === firstOwner;
4651
- } catch {
4652
- return false;
4653
- }
4654
- })) {
4655
- continue;
4656
- }
4657
- }
4658
- } catch {
4659
- }
4660
- if (Date.now() >= deadline) {
4661
- throw new Error("Timed out waiting for the Fabric actor binding lock");
4662
- }
4663
- await delay2(10);
5077
+ fs16.mkdirSync(path16.dirname(this.filePath), { recursive: true, mode: 448 });
5078
+ while (!tryAcquireShortLock(lockPath, formatShortLockOwner(token))) {
5079
+ if (reapStaleShortLock(lockPath, { staleMs: BINDING_STALE_LOCK_MS, legacyAlive: processAlive2 })) continue;
5080
+ if (Date.now() >= deadline) {
5081
+ throw new Error("Timed out waiting for the Fabric actor binding lock");
4664
5082
  }
5083
+ await delay2(10);
4665
5084
  }
4666
5085
  try {
4667
5086
  return operation();
4668
5087
  } finally {
4669
- try {
4670
- const owner = fs15.readFileSync(ownerPath2, "utf8");
4671
- if (owner.startsWith(`${token}
4672
- `)) {
4673
- fs15.rmSync(lockPath, { recursive: true, force: true });
4674
- }
4675
- } catch {
4676
- }
5088
+ releaseShortLock(lockPath, token);
4677
5089
  }
4678
5090
  }
4679
5091
  };
4680
5092
 
4681
5093
  // src/actors/registry-store.ts
4682
5094
  import { randomUUID as randomUUID6 } from "node:crypto";
4683
- import fs16 from "node:fs";
4684
- import path16 from "node:path";
5095
+ import fs17 from "node:fs";
5096
+ import path17 from "node:path";
4685
5097
  var ACTOR_REGISTRY_LOCK_TIMEOUT_MS = 5e3;
4686
5098
  var ACTOR_REGISTRY_STALE_LOCK_MS = 3e4;
4687
5099
  var delay3 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
4688
- var errorCode2 = (error) => error instanceof Error && "code" in error ? String(error.code) : void 0;
4689
5100
  var isObject2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4690
5101
  var isActorRegistryRecord = (entry) => isObject2(entry) && typeof entry.id === "string";
4691
5102
  var ActorRegistryStore = class {
@@ -4693,7 +5104,7 @@ var ActorRegistryStore = class {
4693
5104
  #actorRoot;
4694
5105
  constructor(actorRoot) {
4695
5106
  this.#actorRoot = actorRoot;
4696
- this.#registryPath = path16.join(actorRoot, "actors.json");
5107
+ this.#registryPath = path17.join(actorRoot, "actors.json");
4697
5108
  }
4698
5109
  /**
4699
5110
  * Every entry in actors.json, including entries without a valid identity, so
@@ -4716,7 +5127,6 @@ var ActorRegistryStore = class {
4716
5127
  /** The callback must be synchronous: release precedes promise assimilation. */
4717
5128
  async withLock(operation) {
4718
5129
  const lockPath = `${this.#registryPath}.lock`;
4719
- const ownerPath2 = path16.join(lockPath, "owner");
4720
5130
  const deadline = Date.now() + ACTOR_REGISTRY_LOCK_TIMEOUT_MS;
4721
5131
  const token = randomUUID6();
4722
5132
  const processAlive2 = (pid) => {
@@ -4728,72 +5138,30 @@ var ActorRegistryStore = class {
4728
5138
  return false;
4729
5139
  }
4730
5140
  };
4731
- fs16.mkdirSync(this.#actorRoot, { recursive: true, mode: 448 });
4732
- while (true) {
4733
- try {
4734
- fs16.mkdirSync(lockPath, { mode: 448 });
4735
- fs16.writeFileSync(ownerPath2, `${token}
4736
- ${process.pid}
4737
- ${Date.now()}
4738
- ${encodeOwnerIdentityLine()}
4739
- `, {
4740
- encoding: "utf8",
4741
- mode: 384
4742
- });
4743
- break;
4744
- } catch (error) {
4745
- if (errorCode2(error) !== "EEXIST") throw error;
4746
- try {
4747
- const firstOwner = fs16.readFileSync(ownerPath2, "utf8");
4748
- const [, pidText, createdText, identityLine] = firstOwner.trim().split("\n");
4749
- const stale = Date.now() - Number(createdText) > ACTOR_REGISTRY_STALE_LOCK_MS;
4750
- const dead = stale ? lockOwnerLiveness(Number(pidText), Number(createdText), identityLine, {
4751
- legacyAlive: processAlive2,
4752
- maxHoldMs: Math.max(SHORT_LOCK_MAX_HOLD_MS, ACTOR_REGISTRY_STALE_LOCK_MS)
4753
- }) === "dead" : lockOwnerProvablyDead(Number(pidText), identityLine);
4754
- if (dead) {
4755
- const secondOwner = fs16.readFileSync(ownerPath2, "utf8");
4756
- if (secondOwner === firstOwner && reapLockByRenameClaim(lockPath, (claimed) => {
4757
- try {
4758
- return fs16.readFileSync(path16.join(claimed, "owner"), "utf8") === firstOwner;
4759
- } catch {
4760
- return false;
4761
- }
4762
- })) {
4763
- continue;
4764
- }
4765
- }
4766
- } catch {
4767
- }
4768
- if (Date.now() >= deadline) {
4769
- throw new Error("Timed out waiting for the Fabric actor registry lock");
4770
- }
4771
- await delay3(10);
5141
+ fs17.mkdirSync(this.#actorRoot, { recursive: true, mode: 448 });
5142
+ while (!tryAcquireShortLock(lockPath, formatShortLockOwner(token))) {
5143
+ if (reapStaleShortLock(lockPath, { staleMs: ACTOR_REGISTRY_STALE_LOCK_MS, legacyAlive: processAlive2 })) continue;
5144
+ if (Date.now() >= deadline) {
5145
+ throw new Error("Timed out waiting for the Fabric actor registry lock");
4772
5146
  }
5147
+ await delay3(10);
4773
5148
  }
4774
5149
  try {
4775
5150
  return operation();
4776
5151
  } finally {
4777
- try {
4778
- const owner = fs16.readFileSync(ownerPath2, "utf8");
4779
- if (owner.startsWith(`${token}
4780
- `)) {
4781
- fs16.rmSync(lockPath, { recursive: true, force: true });
4782
- }
4783
- } catch {
4784
- }
5152
+ releaseShortLock(lockPath, token);
4785
5153
  }
4786
5154
  }
4787
5155
  fingerprint() {
4788
5156
  try {
4789
- const stat = fs16.statSync(this.#registryPath);
5157
+ const stat = fs17.statSync(this.#registryPath);
4790
5158
  return `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeMs}`;
4791
5159
  } catch {
4792
5160
  return void 0;
4793
5161
  }
4794
5162
  }
4795
5163
  read() {
4796
- return JSON.parse(fs16.readFileSync(this.#registryPath, "utf8"));
5164
+ return JSON.parse(fs17.readFileSync(this.#registryPath, "utf8"));
4797
5165
  }
4798
5166
  /** Call within withLock for read-modify-write operations. */
4799
5167
  write(actors) {
@@ -4831,7 +5199,7 @@ var normalizeCapabilityRequirements = (requirements = []) => {
4831
5199
  };
4832
5200
  var readRunRecord = (filePath) => {
4833
5201
  try {
4834
- const parsed = JSON.parse(fs17.readFileSync(filePath, "utf8"));
5202
+ const parsed = JSON.parse(fs18.readFileSync(filePath, "utf8"));
4835
5203
  if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return void 0;
4836
5204
  return parsed;
4837
5205
  } catch {
@@ -4881,7 +5249,7 @@ var ActorManager = class {
4881
5249
  this.meshConfig = meshConfig;
4882
5250
  this.agents = agents;
4883
5251
  this.onDeliver = onDeliver;
4884
- this.#actorRoot = options.actorRoot ?? fs17.mkdtempSync(path17.join(os4.tmpdir(), "pi-fabric-actors-"));
5252
+ this.#actorRoot = options.actorRoot ?? fs18.mkdtempSync(path18.join(os4.tmpdir(), "pi-fabric-actors-"));
4885
5253
  this.#actorScope = options.actorScope ?? meshConfig.actorScope;
4886
5254
  this.#persistent = options.persistent ?? false;
4887
5255
  this.#mainAgent = options.mainAgent;
@@ -5034,8 +5402,8 @@ var ActorManager = class {
5034
5402
  }
5035
5403
  const principalScope = launchScope(void 0, request.principalScope);
5036
5404
  const id = randomUUID7().replaceAll("-", "");
5037
- const actorDirectory = path17.join(this.#actorRoot, id);
5038
- fs17.mkdirSync(actorDirectory, { recursive: true, mode: 448 });
5405
+ const actorDirectory = path18.join(this.#actorRoot, id);
5406
+ fs18.mkdirSync(actorDirectory, { recursive: true, mode: 448 });
5039
5407
  const actor = {
5040
5408
  id,
5041
5409
  name,
@@ -5062,7 +5430,7 @@ var ActorManager = class {
5062
5430
  ...request.validWhile ? { validWhile: structuredClone(request.validWhile) } : {},
5063
5431
  ...principalScope ? { principalScope } : {},
5064
5432
  latestActivationSequence: 0,
5065
- sessionFile: path17.join(actorDirectory, "session.jsonl"),
5433
+ sessionFile: path18.join(actorDirectory, "session.jsonl"),
5066
5434
  queue: [],
5067
5435
  draining: false,
5068
5436
  messages: [],
@@ -5397,17 +5765,17 @@ var ActorManager = class {
5397
5765
  const type = opts.type ?? "session";
5398
5766
  const lines = Math.max(1, Math.min(opts.lines ?? 200, 5e3));
5399
5767
  const sessionFile = actor.sessionFile;
5400
- const logDir = path17.join(path17.dirname(sessionFile), "runs");
5768
+ const logDir = path18.join(path18.dirname(sessionFile), "runs");
5401
5769
  const sessionPage = type === "run" ? { lines: [], hasMore: false } : readJsonlPage(sessionFile, lines, opts.before);
5402
5770
  const session = sessionPage.lines;
5403
5771
  let run;
5404
5772
  if (type !== "session") {
5405
5773
  const targetRunId = opts.runId ?? actor.lastRunId;
5406
5774
  if (targetRunId) {
5407
- const runPath = path17.join(logDir, targetRunId);
5408
- if (fs17.existsSync(runPath)) {
5409
- const statusRecord = readRunRecord(path17.join(runPath, "status.json"));
5410
- const eventsFile = path17.join(runPath, "events.jsonl");
5775
+ const runPath = path18.join(logDir, targetRunId);
5776
+ if (fs18.existsSync(runPath)) {
5777
+ const statusRecord = readRunRecord(path18.join(runPath, "status.json"));
5778
+ const eventsFile = path18.join(runPath, "events.jsonl");
5411
5779
  const page = readJsonlPage(eventsFile, lines, opts.before);
5412
5780
  run = {
5413
5781
  runId: targetRunId,
@@ -5609,7 +5977,7 @@ var ActorManager = class {
5609
5977
  await this.#bindings.delete(actor.id);
5610
5978
  this.#actors.delete(actor.id);
5611
5979
  this.#emitChange();
5612
- fs17.rmSync(path17.dirname(actor.sessionFile), { recursive: true, force: true });
5980
+ fs18.rmSync(path18.dirname(actor.sessionFile), { recursive: true, force: true });
5613
5981
  await this.#saveActors(/* @__PURE__ */ new Set([actor.id]));
5614
5982
  await this.mesh.delete({ key: this.#presenceKey(actor.id) }).catch(() => ({ deleted: false }));
5615
5983
  if (retainedRunId) await this.agents.cleanup(retainedRunId).catch(() => ({ cleaned: false }));
@@ -5649,7 +6017,7 @@ var ActorManager = class {
5649
6017
  await Promise.allSettled(
5650
6018
  [...this.#actors.values()].map((actor) => actor.drain ?? Promise.resolve())
5651
6019
  );
5652
- fs17.rmSync(this.#actorRoot, { recursive: true, force: true });
6020
+ fs18.rmSync(this.#actorRoot, { recursive: true, force: true });
5653
6021
  }
5654
6022
  #enqueue(actor, source, payload, options = {}) {
5655
6023
  const canManage = options.ownershipChecked ? this.#canManageCached(actor.id) : this.#canManage(actor.id);
@@ -6320,7 +6688,7 @@ var ActorManager = class {
6320
6688
  ...record.validWhile?.version === 1 && typeof record.validWhile.source === "string" ? { validWhile: record.validWhile } : {},
6321
6689
  ...principalScope ? { principalScope } : {},
6322
6690
  latestActivationSequence: 0,
6323
- sessionFile: path17.join(this.#actorRoot, record.id, "session.jsonl"),
6691
+ sessionFile: path18.join(this.#actorRoot, record.id, "session.jsonl"),
6324
6692
  queue: [],
6325
6693
  draining: false,
6326
6694
  messages: [],
@@ -6415,7 +6783,7 @@ var ActorManager = class {
6415
6783
  ...actor.lastRunId ? { lastRunId: actor.lastRunId } : {},
6416
6784
  ...actor.lastError ? { lastError: actor.lastError } : {},
6417
6785
  sessionFile: actor.sessionFile,
6418
- logDir: path17.join(path17.dirname(actor.sessionFile), "runs")
6786
+ logDir: path18.join(path18.dirname(actor.sessionFile), "runs")
6419
6787
  };
6420
6788
  }
6421
6789
  validateDirectMessage(message2, data) {
@@ -6586,10 +6954,10 @@ var ActorDirectory = class extends ActorManager {
6586
6954
  delete options.actorRoot;
6587
6955
  delete options.meshCursorPath;
6588
6956
  const cursorPaths = meshCursorPath ? { project: `${meshCursorPath}.project`, session: `${meshCursorPath}.session` } : void 0;
6589
- if (meshCursorPath && fs18.existsSync(meshCursorPath)) {
6957
+ if (meshCursorPath && fs19.existsSync(meshCursorPath)) {
6590
6958
  for (const cursorPath of Object.values(cursorPaths)) {
6591
6959
  try {
6592
- if (!fs18.existsSync(cursorPath)) fs18.copyFileSync(meshCursorPath, cursorPath);
6960
+ if (!fs19.existsSync(cursorPath)) fs19.copyFileSync(meshCursorPath, cursorPath);
6593
6961
  } catch {
6594
6962
  }
6595
6963
  }
@@ -7484,6 +7852,9 @@ var LEGACY_SESSION_PREFIX = "sessions/";
7484
7852
  var LEGACY_ACTOR_PREFIX = "actors/";
7485
7853
  var PARTICIPANT_HEARTBEAT_MS = 5e3;
7486
7854
  var PARTICIPANT_LEASE_MS = 15e3;
7855
+ var TOMBSTONE_PREFIX = "topology/tombstones/";
7856
+ var DEPARTED_LIMIT = 32;
7857
+ var DEPARTED_RETENTION_MS = 7 * 24 * 60 * 60 * 1e3;
7487
7858
  var keyFor = (prefix, id) => prefix + createHash3("sha256").update(id).digest("hex");
7488
7859
  var isObject4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
7489
7860
  var participantKind = (value) => value === "root" || value === "agent" || value === "actor" || value === "provider" ? value : void 0;
@@ -7527,6 +7898,31 @@ var hostFromEntry = (entry) => {
7527
7898
  }
7528
7899
  return value;
7529
7900
  };
7901
+ var optionalString = (value) => value === void 0 || typeof value === "string";
7902
+ var tombstoneFromEntry = (entry) => {
7903
+ if (!isObject4(entry.value) || entry.value.format !== 1) return void 0;
7904
+ const value = entry.value;
7905
+ if (value.kind !== "root" || value.status !== "stopped" || typeof value.id !== "string" || entry.key !== keyFor(TOMBSTONE_PREFIX, value.id) || typeof value.rootId !== "string" || typeof value.ownerHostId !== "string" || typeof value.ownerIdentityId !== "string" || entry.updatedBy.id !== value.ownerIdentityId || typeof value.name !== "string" || !optionalString(value.ownerIncarnation) || !optionalString(value.label) || !optionalString(value.cwd) || !optionalString(value.sessionId) || typeof value.startedAt !== "number" || typeof value.lastSeenAt !== "number") {
7906
+ return void 0;
7907
+ }
7908
+ return value;
7909
+ };
7910
+ var departedFromRoot = (participant, status, lastSeenAt) => ({
7911
+ format: 1,
7912
+ id: participant.id,
7913
+ kind: "root",
7914
+ rootId: participant.rootId,
7915
+ ownerHostId: participant.ownerHostId,
7916
+ ownerIdentityId: participant.ownerIdentityId,
7917
+ ...participant.ownerIncarnation ? { ownerIncarnation: participant.ownerIncarnation } : {},
7918
+ name: participant.name,
7919
+ ...participant.label ? { label: participant.label } : {},
7920
+ ...participant.cwd ? { cwd: participant.cwd } : {},
7921
+ ...participant.sessionId ? { sessionId: participant.sessionId } : {},
7922
+ status,
7923
+ startedAt: participant.startedAt,
7924
+ lastSeenAt
7925
+ });
7530
7926
  var peerFromParticipant = (participant) => {
7531
7927
  if (participant.kind !== "root" || !participant.cwd || !participant.sessionId || participant.status !== "idle" && participant.status !== "running") {
7532
7928
  return void 0;
@@ -7623,11 +8019,15 @@ var ParticipantDirectory = class {
7623
8019
  this.options = options;
7624
8020
  this.#heartbeatMs = Math.max(100, options.heartbeatMs ?? PARTICIPANT_HEARTBEAT_MS);
7625
8021
  this.#leaseMs = Math.max(this.#heartbeatMs * 2, options.leaseMs ?? PARTICIPANT_LEASE_MS);
8022
+ this.#departedLimit = Math.max(0, Math.floor(options.departedLimit ?? DEPARTED_LIMIT));
8023
+ this.#departedRetentionMs = Math.max(0, options.departedRetentionMs ?? DEPARTED_RETENTION_MS);
7626
8024
  }
7627
8025
  #sources = /* @__PURE__ */ new Set();
7628
8026
  #startedAt = Date.now();
7629
8027
  #heartbeatMs;
7630
8028
  #leaseMs;
8029
+ #departedLimit;
8030
+ #departedRetentionMs;
7631
8031
  #localRecords = /* @__PURE__ */ new Map();
7632
8032
  #timer;
7633
8033
  #closed = false;
@@ -7801,6 +8201,38 @@ var ParticipantDirectory = class {
7801
8201
  return peer ? [peer] : [];
7802
8202
  });
7803
8203
  }
8204
+ /**
8205
+ * Root sessions that are no longer live, newest first: `stopped` from the
8206
+ * tombstone a clean close wrote, `lost` from a root record whose owner
8207
+ * lease expired without one. Explicit opt-in only; live queries never read
8208
+ * tombstones. Pure read: never writes or prunes.
8209
+ */
8210
+ departed(options = {}, now = Date.now()) {
8211
+ if (!this.options.enabled) return [];
8212
+ const hosts = this.#hosts();
8213
+ const live = /* @__PURE__ */ new Set([this.options.rootId]);
8214
+ const byId = /* @__PURE__ */ new Map();
8215
+ for (const entry of this.mesh.listAll(PARTICIPANT_PREFIX)) {
8216
+ const participant = participantFromEntry(entry);
8217
+ if (participant?.kind !== "root") continue;
8218
+ if (liveOwner(participant, hosts, now)) {
8219
+ live.add(participant.id);
8220
+ continue;
8221
+ }
8222
+ const owner = hosts.get(participant.ownerHostId);
8223
+ const heartbeat = owner?.identity.id === participant.ownerIdentityId ? owner.updatedAt : 0;
8224
+ byId.set(participant.id, departedFromRoot(participant, "lost", Math.max(participant.updatedAt, heartbeat)));
8225
+ }
8226
+ for (const entry of this.mesh.listAll(TOMBSTONE_PREFIX)) {
8227
+ const tombstone = tombstoneFromEntry(entry);
8228
+ if (!tombstone) continue;
8229
+ const lost = byId.get(tombstone.id);
8230
+ if (!lost || tombstone.lastSeenAt >= lost.lastSeenAt) byId.set(tombstone.id, tombstone);
8231
+ }
8232
+ const cutoff = now - this.#departedRetentionMs;
8233
+ const limit = Math.max(0, Math.floor(options.limit ?? (this.#departedLimit || DEPARTED_LIMIT)));
8234
+ return [...byId.values()].filter((participant) => !live.has(participant.id) && participant.lastSeenAt >= cutoff).sort((left, right) => right.lastSeenAt - left.lastSeenAt || left.id.localeCompare(right.id)).slice(0, limit);
8235
+ }
7804
8236
  root(main) {
7805
8237
  return {
7806
8238
  format: 1,
@@ -7837,8 +8269,12 @@ var ParticipantDirectory = class {
7837
8269
  this.#timer = void 0;
7838
8270
  await this.#refreshing?.catch(() => void 0);
7839
8271
  if (!this.options.enabled) return;
7840
- const owned = this.mesh.listAll(PARTICIPANT_PREFIX).filter((entry) => participantFromEntry(entry)?.ownerHostId === this.options.hostId);
7841
- await Promise.allSettled(owned.map((entry) => this.mesh.delete({ key: entry.key, ifVersion: entry.version })));
8272
+ const owned = this.mesh.listAll(PARTICIPANT_PREFIX).flatMap((entry) => {
8273
+ const participant = participantFromEntry(entry);
8274
+ return participant?.ownerHostId === this.options.hostId ? [{ entry, participant }] : [];
8275
+ });
8276
+ await this.#writeTombstones(owned.map((item) => item.participant)).catch(() => void 0);
8277
+ await Promise.allSettled(owned.map(({ entry }) => this.mesh.delete({ key: entry.key, ifVersion: entry.version })));
7842
8278
  const legacySessionKey = this.#legacySessionKey();
7843
8279
  if (legacySessionKey) {
7844
8280
  const legacy = this.mesh.get(legacySessionKey);
@@ -7849,6 +8285,23 @@ var ParticipantDirectory = class {
7849
8285
  const hostEntry = this.mesh.get(keyFor(HOST_PREFIX, this.options.hostId));
7850
8286
  if (hostEntry) await this.mesh.delete({ key: hostEntry.key, ifVersion: hostEntry.version }).catch(() => void 0);
7851
8287
  }
8288
+ /** Replace this host's root records with stopped tombstones, then prune by age and count. */
8289
+ async #writeTombstones(owned) {
8290
+ if (this.#departedLimit === 0) return;
8291
+ const now = Date.now();
8292
+ for (const participant of owned) {
8293
+ if (participant.kind !== "root") continue;
8294
+ await this.mesh.put({
8295
+ key: keyFor(TOMBSTONE_PREFIX, participant.id),
8296
+ value: departedFromRoot(participant, "stopped", now),
8297
+ identity: this.options.identity
8298
+ }).catch(() => void 0);
8299
+ }
8300
+ const cutoff = now - this.#departedRetentionMs;
8301
+ const kept = this.mesh.listAll(TOMBSTONE_PREFIX).map((entry) => ({ entry, tombstone: tombstoneFromEntry(entry) })).sort((left, right) => (right.tombstone?.lastSeenAt ?? 0) - (left.tombstone?.lastSeenAt ?? 0));
8302
+ const prune = kept.filter(({ tombstone }, index) => !tombstone || tombstone.lastSeenAt < cutoff || index >= this.#departedLimit);
8303
+ await Promise.allSettled(prune.map(({ entry }) => this.mesh.delete({ key: entry.key, ifVersion: entry.version })));
8304
+ }
7852
8305
  async #refresh() {
7853
8306
  const now = Date.now();
7854
8307
  const desired = /* @__PURE__ */ new Map();
@@ -8130,6 +8583,7 @@ export {
8130
8583
  resolvePiBinary,
8131
8584
  resolveInheritedSessionPins,
8132
8585
  withInheritedSessionPins,
8586
+ hasWorkerRecovery,
8133
8587
  isFabricWorktreePath,
8134
8588
  addCloneFirstWorktree,
8135
8589
  PiCodingAgent,
@@ -8154,4 +8608,4 @@ export {
8154
8608
  agentParticipantRecords,
8155
8609
  actorParticipantRecord
8156
8610
  };
8157
- //# sourceMappingURL=chunk-GW25FXU4.js.map
8611
+ //# sourceMappingURL=chunk-6C2DMTQC.js.map