@xenosystem/agent-sdk 0.10.29 → 0.10.31

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 (65) hide show
  1. package/dist/artifacts/index.cjs +6 -6
  2. package/dist/artifacts/index.js +7 -7
  3. package/dist/artifacts/metafile-cjs.json +1 -1
  4. package/dist/artifacts/metafile-esm.json +1 -1
  5. package/dist/automation/index.cjs +1 -1
  6. package/dist/automation/index.d.cts +6 -2
  7. package/dist/automation/index.d.ts +6 -2
  8. package/dist/automation/index.js +1 -1
  9. package/dist/automation/metafile-cjs.json +1 -1
  10. package/dist/automation/metafile-esm.json +1 -1
  11. package/dist/control-plane/index.cjs +1 -1
  12. package/dist/control-plane/index.js +1 -1
  13. package/dist/coordination/index.cjs +2 -2
  14. package/dist/coordination/index.d.cts +9 -3
  15. package/dist/coordination/index.d.ts +9 -3
  16. package/dist/coordination/index.js +2 -2
  17. package/dist/coordination/metafile-cjs.json +1 -1
  18. package/dist/coordination/metafile-esm.json +1 -1
  19. package/dist/electron/index.cjs +199 -178
  20. package/dist/electron/index.d.cts +20 -2
  21. package/dist/electron/index.d.ts +20 -2
  22. package/dist/electron/index.js +199 -178
  23. package/dist/electron/metafile-cjs.json +1 -1
  24. package/dist/electron/metafile-esm.json +1 -1
  25. package/dist/hosted/index.cjs +1 -1
  26. package/dist/hosted/index.js +1 -1
  27. package/dist/hosted/metafile-cjs.json +1 -1
  28. package/dist/hosted/metafile-esm.json +1 -1
  29. package/dist/index.cjs +374 -353
  30. package/dist/index.d.cts +93 -13
  31. package/dist/index.d.ts +93 -13
  32. package/dist/index.js +375 -354
  33. package/dist/intelligence/index.cjs +5 -5
  34. package/dist/intelligence/index.js +6 -6
  35. package/dist/intelligence/metafile-cjs.json +1 -1
  36. package/dist/intelligence/metafile-esm.json +1 -1
  37. package/dist/mcp/index.d.cts +6 -2
  38. package/dist/mcp/index.d.ts +6 -2
  39. package/dist/metafile-cjs.json +1 -1
  40. package/dist/metafile-esm.json +1 -1
  41. package/dist/providers/metafile-cjs.json +1 -1
  42. package/dist/providers/metafile-esm.json +1 -1
  43. package/dist/recipes/metafile-cjs.json +1 -1
  44. package/dist/recipes/metafile-esm.json +1 -1
  45. package/dist/research/metafile-cjs.json +1 -1
  46. package/dist/research/metafile-esm.json +1 -1
  47. package/dist/session/index.cjs +22 -22
  48. package/dist/session/index.d.cts +15 -0
  49. package/dist/session/index.d.ts +15 -0
  50. package/dist/session/index.js +22 -22
  51. package/dist/session/metafile-cjs.json +1 -1
  52. package/dist/session/metafile-esm.json +1 -1
  53. package/dist/sharing/index.cjs +2 -2
  54. package/dist/sharing/index.js +3 -3
  55. package/dist/sharing/metafile-cjs.json +1 -1
  56. package/dist/sharing/metafile-esm.json +1 -1
  57. package/dist/skills/index.d.cts +5 -1
  58. package/dist/skills/index.d.ts +5 -1
  59. package/dist/utils/index.cjs +19 -18
  60. package/dist/utils/index.d.cts +5 -2
  61. package/dist/utils/index.d.ts +5 -2
  62. package/dist/utils/index.js +19 -18
  63. package/dist/utils/metafile-cjs.json +1 -1
  64. package/dist/utils/metafile-esm.json +1 -1
  65. package/package.json +1 -1
@@ -1 +1 @@
1
- {"inputs":{"src/automation/types.ts":{"bytes":7431,"imports":[],"format":"esm"},"src/automation/operations.ts":{"bytes":3367,"imports":[],"format":"esm"},"src/automation/errors.ts":{"bytes":899,"imports":[],"format":"esm"},"src/security/path-policy.ts":{"bytes":5541,"imports":[{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true}],"format":"esm"},"src/security/windows-process-containment.ts":{"bytes":51557,"imports":[{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:child_process","kind":"import-statement","external":true},{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true}],"format":"esm"},"src/security/linux-process-containment.ts":{"bytes":5665,"imports":[{"path":"node:child_process","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true}],"format":"esm"},"src/security/containment-certification.ts":{"bytes":13312,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true}],"format":"esm"},"src/security/environment-policy.ts":{"bytes":1195,"imports":[],"format":"esm"},"src/security/mxc-containment.ts":{"bytes":28272,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"node:child_process","kind":"import-statement","external":true},{"path":"node:url","kind":"import-statement","external":true},{"path":"src/security/environment-policy.ts","kind":"import-statement","original":"./environment-policy.js"},{"path":"src/security/path-policy.ts","kind":"import-statement","original":"./path-policy.js"}],"format":"esm"},"src/security/process-containment.ts":{"bytes":17360,"imports":[{"path":"src/security/windows-process-containment.ts","kind":"import-statement","original":"./windows-process-containment.js"},{"path":"src/security/linux-process-containment.ts","kind":"import-statement","original":"./linux-process-containment.js"},{"path":"src/security/path-policy.ts","kind":"import-statement","original":"./path-policy.js"},{"path":"src/security/containment-certification.ts","kind":"import-statement","original":"./containment-certification.js"},{"path":"src/security/mxc-containment.ts","kind":"import-statement","original":"./mxc-containment.js"}],"format":"esm"},"src/security/secure-execution-contract.ts":{"bytes":24510,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true},{"path":"src/security/path-policy.ts","kind":"import-statement","original":"./path-policy.js"},{"path":"src/security/process-containment.ts","kind":"import-statement","original":"./process-containment.js"}],"format":"esm"},"src/automation/policy.ts":{"bytes":15653,"imports":[{"path":"src/security/secure-execution-contract.ts","kind":"import-statement","original":"../security/secure-execution-contract.js"},{"path":"src/automation/errors.ts","kind":"import-statement","original":"./errors.js"},{"path":"src/automation/operations.ts","kind":"import-statement","original":"./operations.js"},{"path":"src/automation/types.ts","kind":"import-statement","original":"./types.js"}],"format":"esm"},"src/artifacts/types.ts":{"bytes":11227,"imports":[],"format":"esm"},"src/artifacts/hash.ts":{"bytes":1489,"imports":[{"path":"node:crypto","kind":"import-statement","external":true}],"format":"esm"},"src/utils/custom-names.ts":{"bytes":2210,"imports":[],"format":"esm"},"src/artifacts/validation.ts":{"bytes":25271,"imports":[{"path":"src/artifacts/types.ts","kind":"import-statement","original":"./types.js"},{"path":"node:buffer","kind":"import-statement","external":true},{"path":"src/artifacts/hash.ts","kind":"import-statement","original":"./hash.js"},{"path":"src/utils/custom-names.ts","kind":"import-statement","original":"../utils/custom-names.js"},{"path":"src/artifacts/types.ts","kind":"import-statement","original":"./types.js"}],"format":"esm"},"src/artifacts/repository.ts":{"bytes":29289,"imports":[{"path":"src/artifacts/types.ts","kind":"import-statement","original":"./types.js"},{"path":"src/artifacts/validation.ts","kind":"import-statement","original":"./validation.js"}],"format":"esm"},"src/automation/evidence.ts":{"bytes":8618,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"src/artifacts/repository.ts","kind":"import-statement","original":"../artifacts/repository.js"},{"path":"src/artifacts/hash.ts","kind":"import-statement","original":"../artifacts/hash.js"},{"path":"src/artifacts/types.ts","kind":"import-statement","original":"../artifacts/types.js"},{"path":"src/automation/errors.ts","kind":"import-statement","original":"./errors.js"}],"format":"esm"},"src/automation/durable-execution.ts":{"bytes":4647,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"src/automation/evidence.ts","kind":"import-statement","original":"./evidence.js"},{"path":"src/automation/errors.ts","kind":"import-statement","original":"./errors.js"}],"format":"esm"},"src/automation/executor.ts":{"bytes":16288,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"src/automation/errors.ts","kind":"import-statement","original":"./errors.js"},{"path":"src/automation/durable-execution.ts","kind":"import-statement","original":"./durable-execution.js"},{"path":"src/automation/evidence.ts","kind":"import-statement","original":"./evidence.js"},{"path":"src/automation/operations.ts","kind":"import-statement","original":"./operations.js"},{"path":"src/automation/policy.ts","kind":"import-statement","original":"./policy.js"}],"format":"esm"},"src/automation/execution-journal.ts":{"bytes":7254,"imports":[{"path":"node:path","kind":"import-statement","external":true},{"path":"src/automation/errors.ts","kind":"import-statement","original":"./errors.js"},{"path":"node:sqlite","kind":"dynamic-import","external":true}],"format":"esm"},"src/automation/conformance.ts":{"bytes":4331,"imports":[{"path":"src/automation/errors.ts","kind":"import-statement","original":"./errors.js"},{"path":"src/automation/policy.ts","kind":"import-statement","original":"./policy.js"},{"path":"src/automation/types.ts","kind":"import-statement","original":"./types.js"}],"format":"esm"},"src/automation/http-adapter.ts":{"bytes":8862,"imports":[{"path":"src/automation/errors.ts","kind":"import-statement","original":"./errors.js"}],"format":"esm"},"src/automation/browser-control-plane-adapter.ts":{"bytes":17420,"imports":[{"path":"node:crypto","kind":"import-statement","external":true}],"format":"esm"},"src/utils/fs.ts":{"bytes":11685,"imports":[{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:fs/promises","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true}],"format":"esm"},"src/control-plane/lock.ts":{"bytes":2496,"imports":[{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true}],"format":"esm"},"src/version.ts":{"bytes":195,"imports":[],"format":"esm"},"src/artifacts/file-repository.ts":{"bytes":16401,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:fs/promises","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"src/utils/fs.ts","kind":"import-statement","original":"../utils/fs.js"},{"path":"src/control-plane/lock.ts","kind":"import-statement","original":"../control-plane/lock.js"},{"path":"src/version.ts","kind":"import-statement","original":"../version.js"},{"path":"src/artifacts/hash.ts","kind":"import-statement","original":"./hash.js"},{"path":"src/artifacts/repository.ts","kind":"import-statement","original":"./repository.js"},{"path":"src/artifacts/types.ts","kind":"import-statement","original":"./types.js"}],"format":"esm"},"src/utils/yaml.ts":{"bytes":5506,"imports":[],"format":"esm"},"src/utils/platform.ts":{"bytes":5600,"imports":[{"path":"node:os","kind":"import-statement","external":true},{"path":"node:child_process","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true}],"format":"esm"},"src/agents/definitions.ts":{"bytes":23563,"imports":[{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"src/utils/yaml.ts","kind":"import-statement","original":"../utils/yaml.js"},{"path":"src/utils/platform.ts","kind":"import-statement","original":"../utils/platform.js"}],"format":"esm"},"src/agents/profiles.ts":{"bytes":33625,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"src/agents/definitions.ts","kind":"import-statement","original":"./definitions.js"}],"format":"esm"},"src/security/capability-lease.ts":{"bytes":29318,"imports":[{"path":"src/agents/profiles.ts","kind":"import-statement","original":"../agents/profiles.js"},{"path":"src/utils/custom-names.ts","kind":"import-statement","original":"../utils/custom-names.js"}],"format":"esm"},"src/automation/tool-pack.ts":{"bytes":19206,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"src/automation/operations.ts","kind":"import-statement","original":"./operations.js"}],"format":"esm"},"src/automation/host-runtime.ts":{"bytes":30630,"imports":[{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"src/artifacts/file-repository.ts","kind":"import-statement","original":"../artifacts/file-repository.js"},{"path":"src/security/capability-lease.ts","kind":"import-statement","original":"../security/capability-lease.js"},{"path":"src/security/secure-execution-contract.ts","kind":"import-statement","original":"../security/secure-execution-contract.js"},{"path":"src/automation/types.ts","kind":"import-statement","original":"./types.js"},{"path":"src/automation/executor.ts","kind":"import-statement","original":"./executor.js"},{"path":"src/automation/operations.ts","kind":"import-statement","original":"./operations.js"},{"path":"src/automation/tool-pack.ts","kind":"import-statement","original":"./tool-pack.js"},{"path":"src/automation/browser-control-plane-adapter.ts","kind":"import-statement","original":"./browser-control-plane-adapter.js"}],"format":"esm"},"src/automation/index.ts":{"bytes":449,"imports":[{"path":"src/automation/types.ts","kind":"import-statement","original":"./types.js"},{"path":"src/automation/operations.ts","kind":"import-statement","original":"./operations.js"},{"path":"src/automation/errors.ts","kind":"import-statement","original":"./errors.js"},{"path":"src/automation/policy.ts","kind":"import-statement","original":"./policy.js"},{"path":"src/automation/evidence.ts","kind":"import-statement","original":"./evidence.js"},{"path":"src/automation/executor.ts","kind":"import-statement","original":"./executor.js"},{"path":"src/automation/execution-journal.ts","kind":"import-statement","original":"./execution-journal.js"},{"path":"src/automation/durable-execution.ts","kind":"import-statement","original":"./durable-execution.js"},{"path":"src/automation/conformance.ts","kind":"import-statement","original":"./conformance.js"},{"path":"src/automation/http-adapter.ts","kind":"import-statement","original":"./http-adapter.js"},{"path":"src/automation/browser-control-plane-adapter.ts","kind":"import-statement","original":"./browser-control-plane-adapter.js"},{"path":"src/automation/host-runtime.ts","kind":"import-statement","original":"./host-runtime.js"},{"path":"src/automation/tool-pack.ts","kind":"import-statement","original":"./tool-pack.js"}],"format":"esm"}},"outputs":{"dist/automation/index.js":{"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"node:child_process","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"node:child_process","kind":"import-statement","external":true},{"path":"node:url","kind":"import-statement","external":true},{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:buffer","kind":"import-statement","external":true},{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"node:sqlite","kind":"dynamic-import","external":true},{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:fs/promises","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"node:fs/promises","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true},{"path":"node:crypto","kind":"import-statement","external":true}],"exports":["CliGovernedAutomationRuntime","SqliteAutomationExecutionJournal","XENO_AUTOMATION_OPERATIONS","XENO_AUTOMATION_PROTOCOL_VERSION","XENO_BROWSER_CONTROL_PLANE_OPERATIONS","XenoAutomationError","XenoBrowserControlPlaneAdapter","XenoGovernedAutomationExecutor","XenoHostGovernedAutomationRuntime","XenoLoopbackAutomationAdapter","assertRequiredXenoAutomationEvidence","assertValidXenoAutomationAdapterManifest","assertValidXenoAutomationRequest","assertXenoAutomationAdapterConformant","assertXenoAutomationAuthority","buildXenoAutomationCapabilityUse","createCliAutomationAuditSink","createCliGovernedAutomationRuntime","createXenoAutomationConformanceReport","createXenoGovernedAutomationTools","createXenoHostAutomationAuditSink","createXenoHostGovernedAutomationRuntime","describeXenoAutomationOperation","inspectCliAutomationStatus","inspectXenoHostAutomationStatus","isXenoAutomationOperation","materializeXenoAutomationEvidence","openSqliteAutomationExecutionJournal","pending","persistXenoAutomationEvidence","readCliAutomationEnvironment","readXenoHostAutomationEnvironment","renderCliAutomationStatus","renderXenoHostAutomationStatus","resolveXenoAutomationEvidencePolicy","runDurableAutomation"],"entryPoint":"src/automation/index.ts","inputs":{"src/automation/types.ts":{"bytesInOutput":8},"src/automation/index.ts":{"bytesInOutput":0},"src/automation/operations.ts":{"bytesInOutput":1656},"src/automation/errors.ts":{"bytesInOutput":129},"src/security/secure-execution-contract.ts":{"bytesInOutput":10453},"src/security/path-policy.ts":{"bytesInOutput":2570},"src/security/windows-process-containment.ts":{"bytesInOutput":47621},"src/security/linux-process-containment.ts":{"bytesInOutput":1948},"src/security/containment-certification.ts":{"bytesInOutput":6156},"src/security/mxc-containment.ts":{"bytesInOutput":6366},"src/security/process-containment.ts":{"bytesInOutput":6520},"src/automation/policy.ts":{"bytesInOutput":7893},"src/automation/evidence.ts":{"bytesInOutput":4449},"src/artifacts/types.ts":{"bytesInOutput":825},"src/artifacts/validation.ts":{"bytesInOutput":13370},"src/artifacts/hash.ts":{"bytesInOutput":126},"src/utils/custom-names.ts":{"bytesInOutput":125},"src/artifacts/repository.ts":{"bytesInOutput":13753},"src/automation/executor.ts":{"bytesInOutput":7132},"src/automation/durable-execution.ts":{"bytesInOutput":2222},"src/automation/execution-journal.ts":{"bytesInOutput":4236},"src/automation/conformance.ts":{"bytesInOutput":2199},"src/automation/http-adapter.ts":{"bytesInOutput":4320},"src/automation/browser-control-plane-adapter.ts":{"bytesInOutput":9666},"src/automation/host-runtime.ts":{"bytesInOutput":12795},"src/artifacts/file-repository.ts":{"bytesInOutput":6720},"src/utils/fs.ts":{"bytesInOutput":314},"src/control-plane/lock.ts":{"bytesInOutput":1054},"src/version.ts":{"bytesInOutput":17},"src/utils/platform.ts":{"bytesInOutput":96},"src/agents/definitions.ts":{"bytesInOutput":20},"src/agents/profiles.ts":{"bytesInOutput":8624},"src/security/capability-lease.ts":{"bytesInOutput":14560},"src/automation/tool-pack.ts":{"bytesInOutput":10038}},"bytes":209333}}}
1
+ {"inputs":{"src/automation/types.ts":{"bytes":7431,"imports":[],"format":"esm"},"src/automation/operations.ts":{"bytes":3367,"imports":[],"format":"esm"},"src/automation/errors.ts":{"bytes":899,"imports":[],"format":"esm"},"src/security/path-policy.ts":{"bytes":5541,"imports":[{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true}],"format":"esm"},"src/security/windows-process-containment.ts":{"bytes":51557,"imports":[{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:child_process","kind":"import-statement","external":true},{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true}],"format":"esm"},"src/security/linux-process-containment.ts":{"bytes":5665,"imports":[{"path":"node:child_process","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true}],"format":"esm"},"src/security/containment-certification.ts":{"bytes":13312,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true}],"format":"esm"},"src/security/environment-policy.ts":{"bytes":1195,"imports":[],"format":"esm"},"src/security/mxc-containment.ts":{"bytes":28272,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"node:child_process","kind":"import-statement","external":true},{"path":"node:url","kind":"import-statement","external":true},{"path":"src/security/environment-policy.ts","kind":"import-statement","original":"./environment-policy.js"},{"path":"src/security/path-policy.ts","kind":"import-statement","original":"./path-policy.js"}],"format":"esm"},"src/security/process-containment.ts":{"bytes":17360,"imports":[{"path":"src/security/windows-process-containment.ts","kind":"import-statement","original":"./windows-process-containment.js"},{"path":"src/security/linux-process-containment.ts","kind":"import-statement","original":"./linux-process-containment.js"},{"path":"src/security/path-policy.ts","kind":"import-statement","original":"./path-policy.js"},{"path":"src/security/containment-certification.ts","kind":"import-statement","original":"./containment-certification.js"},{"path":"src/security/mxc-containment.ts","kind":"import-statement","original":"./mxc-containment.js"}],"format":"esm"},"src/security/secure-execution-contract.ts":{"bytes":24510,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true},{"path":"src/security/path-policy.ts","kind":"import-statement","original":"./path-policy.js"},{"path":"src/security/process-containment.ts","kind":"import-statement","original":"./process-containment.js"}],"format":"esm"},"src/automation/policy.ts":{"bytes":15653,"imports":[{"path":"src/security/secure-execution-contract.ts","kind":"import-statement","original":"../security/secure-execution-contract.js"},{"path":"src/automation/errors.ts","kind":"import-statement","original":"./errors.js"},{"path":"src/automation/operations.ts","kind":"import-statement","original":"./operations.js"},{"path":"src/automation/types.ts","kind":"import-statement","original":"./types.js"}],"format":"esm"},"src/artifacts/types.ts":{"bytes":11227,"imports":[],"format":"esm"},"src/artifacts/hash.ts":{"bytes":1489,"imports":[{"path":"node:crypto","kind":"import-statement","external":true}],"format":"esm"},"src/utils/custom-names.ts":{"bytes":2210,"imports":[],"format":"esm"},"src/artifacts/validation.ts":{"bytes":25271,"imports":[{"path":"src/artifacts/types.ts","kind":"import-statement","original":"./types.js"},{"path":"node:buffer","kind":"import-statement","external":true},{"path":"src/artifacts/hash.ts","kind":"import-statement","original":"./hash.js"},{"path":"src/utils/custom-names.ts","kind":"import-statement","original":"../utils/custom-names.js"},{"path":"src/artifacts/types.ts","kind":"import-statement","original":"./types.js"}],"format":"esm"},"src/artifacts/repository.ts":{"bytes":29289,"imports":[{"path":"src/artifacts/types.ts","kind":"import-statement","original":"./types.js"},{"path":"src/artifacts/validation.ts","kind":"import-statement","original":"./validation.js"}],"format":"esm"},"src/automation/evidence.ts":{"bytes":8618,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"src/artifacts/repository.ts","kind":"import-statement","original":"../artifacts/repository.js"},{"path":"src/artifacts/hash.ts","kind":"import-statement","original":"../artifacts/hash.js"},{"path":"src/artifacts/types.ts","kind":"import-statement","original":"../artifacts/types.js"},{"path":"src/automation/errors.ts","kind":"import-statement","original":"./errors.js"}],"format":"esm"},"src/automation/durable-execution.ts":{"bytes":4647,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"src/automation/evidence.ts","kind":"import-statement","original":"./evidence.js"},{"path":"src/automation/errors.ts","kind":"import-statement","original":"./errors.js"}],"format":"esm"},"src/automation/executor.ts":{"bytes":16288,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"src/automation/errors.ts","kind":"import-statement","original":"./errors.js"},{"path":"src/automation/durable-execution.ts","kind":"import-statement","original":"./durable-execution.js"},{"path":"src/automation/evidence.ts","kind":"import-statement","original":"./evidence.js"},{"path":"src/automation/operations.ts","kind":"import-statement","original":"./operations.js"},{"path":"src/automation/policy.ts","kind":"import-statement","original":"./policy.js"}],"format":"esm"},"src/automation/execution-journal.ts":{"bytes":7254,"imports":[{"path":"node:path","kind":"import-statement","external":true},{"path":"src/automation/errors.ts","kind":"import-statement","original":"./errors.js"},{"path":"node:sqlite","kind":"dynamic-import","external":true}],"format":"esm"},"src/automation/conformance.ts":{"bytes":4331,"imports":[{"path":"src/automation/errors.ts","kind":"import-statement","original":"./errors.js"},{"path":"src/automation/policy.ts","kind":"import-statement","original":"./policy.js"},{"path":"src/automation/types.ts","kind":"import-statement","original":"./types.js"}],"format":"esm"},"src/automation/http-adapter.ts":{"bytes":8862,"imports":[{"path":"src/automation/errors.ts","kind":"import-statement","original":"./errors.js"}],"format":"esm"},"src/automation/browser-control-plane-adapter.ts":{"bytes":17420,"imports":[{"path":"node:crypto","kind":"import-statement","external":true}],"format":"esm"},"src/utils/fs.ts":{"bytes":13355,"imports":[{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:fs/promises","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true}],"format":"esm"},"src/control-plane/lock.ts":{"bytes":2496,"imports":[{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true}],"format":"esm"},"src/version.ts":{"bytes":195,"imports":[],"format":"esm"},"src/artifacts/file-repository.ts":{"bytes":16401,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:fs/promises","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"src/utils/fs.ts","kind":"import-statement","original":"../utils/fs.js"},{"path":"src/control-plane/lock.ts","kind":"import-statement","original":"../control-plane/lock.js"},{"path":"src/version.ts","kind":"import-statement","original":"../version.js"},{"path":"src/artifacts/hash.ts","kind":"import-statement","original":"./hash.js"},{"path":"src/artifacts/repository.ts","kind":"import-statement","original":"./repository.js"},{"path":"src/artifacts/types.ts","kind":"import-statement","original":"./types.js"}],"format":"esm"},"src/utils/yaml.ts":{"bytes":5506,"imports":[],"format":"esm"},"src/utils/platform.ts":{"bytes":5600,"imports":[{"path":"node:os","kind":"import-statement","external":true},{"path":"node:child_process","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true}],"format":"esm"},"src/agents/definitions.ts":{"bytes":23563,"imports":[{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"src/utils/yaml.ts","kind":"import-statement","original":"../utils/yaml.js"},{"path":"src/utils/platform.ts","kind":"import-statement","original":"../utils/platform.js"}],"format":"esm"},"src/agents/profiles.ts":{"bytes":33625,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"src/agents/definitions.ts","kind":"import-statement","original":"./definitions.js"}],"format":"esm"},"src/security/capability-lease.ts":{"bytes":29318,"imports":[{"path":"src/agents/profiles.ts","kind":"import-statement","original":"../agents/profiles.js"},{"path":"src/utils/custom-names.ts","kind":"import-statement","original":"../utils/custom-names.js"}],"format":"esm"},"src/automation/tool-pack.ts":{"bytes":19206,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"src/automation/operations.ts","kind":"import-statement","original":"./operations.js"}],"format":"esm"},"src/automation/host-runtime.ts":{"bytes":30630,"imports":[{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"src/artifacts/file-repository.ts","kind":"import-statement","original":"../artifacts/file-repository.js"},{"path":"src/security/capability-lease.ts","kind":"import-statement","original":"../security/capability-lease.js"},{"path":"src/security/secure-execution-contract.ts","kind":"import-statement","original":"../security/secure-execution-contract.js"},{"path":"src/automation/types.ts","kind":"import-statement","original":"./types.js"},{"path":"src/automation/executor.ts","kind":"import-statement","original":"./executor.js"},{"path":"src/automation/operations.ts","kind":"import-statement","original":"./operations.js"},{"path":"src/automation/tool-pack.ts","kind":"import-statement","original":"./tool-pack.js"},{"path":"src/automation/browser-control-plane-adapter.ts","kind":"import-statement","original":"./browser-control-plane-adapter.js"}],"format":"esm"},"src/automation/index.ts":{"bytes":449,"imports":[{"path":"src/automation/types.ts","kind":"import-statement","original":"./types.js"},{"path":"src/automation/operations.ts","kind":"import-statement","original":"./operations.js"},{"path":"src/automation/errors.ts","kind":"import-statement","original":"./errors.js"},{"path":"src/automation/policy.ts","kind":"import-statement","original":"./policy.js"},{"path":"src/automation/evidence.ts","kind":"import-statement","original":"./evidence.js"},{"path":"src/automation/executor.ts","kind":"import-statement","original":"./executor.js"},{"path":"src/automation/execution-journal.ts","kind":"import-statement","original":"./execution-journal.js"},{"path":"src/automation/durable-execution.ts","kind":"import-statement","original":"./durable-execution.js"},{"path":"src/automation/conformance.ts","kind":"import-statement","original":"./conformance.js"},{"path":"src/automation/http-adapter.ts","kind":"import-statement","original":"./http-adapter.js"},{"path":"src/automation/browser-control-plane-adapter.ts","kind":"import-statement","original":"./browser-control-plane-adapter.js"},{"path":"src/automation/host-runtime.ts","kind":"import-statement","original":"./host-runtime.js"},{"path":"src/automation/tool-pack.ts","kind":"import-statement","original":"./tool-pack.js"}],"format":"esm"}},"outputs":{"dist/automation/index.js":{"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"node:child_process","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"node:child_process","kind":"import-statement","external":true},{"path":"node:url","kind":"import-statement","external":true},{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:buffer","kind":"import-statement","external":true},{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"node:sqlite","kind":"dynamic-import","external":true},{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:fs/promises","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"node:fs/promises","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true},{"path":"node:crypto","kind":"import-statement","external":true}],"exports":["CliGovernedAutomationRuntime","SqliteAutomationExecutionJournal","XENO_AUTOMATION_OPERATIONS","XENO_AUTOMATION_PROTOCOL_VERSION","XENO_BROWSER_CONTROL_PLANE_OPERATIONS","XenoAutomationError","XenoBrowserControlPlaneAdapter","XenoGovernedAutomationExecutor","XenoHostGovernedAutomationRuntime","XenoLoopbackAutomationAdapter","assertRequiredXenoAutomationEvidence","assertValidXenoAutomationAdapterManifest","assertValidXenoAutomationRequest","assertXenoAutomationAdapterConformant","assertXenoAutomationAuthority","buildXenoAutomationCapabilityUse","createCliAutomationAuditSink","createCliGovernedAutomationRuntime","createXenoAutomationConformanceReport","createXenoGovernedAutomationTools","createXenoHostAutomationAuditSink","createXenoHostGovernedAutomationRuntime","describeXenoAutomationOperation","inspectCliAutomationStatus","inspectXenoHostAutomationStatus","isXenoAutomationOperation","materializeXenoAutomationEvidence","openSqliteAutomationExecutionJournal","pending","persistXenoAutomationEvidence","readCliAutomationEnvironment","readXenoHostAutomationEnvironment","renderCliAutomationStatus","renderXenoHostAutomationStatus","resolveXenoAutomationEvidencePolicy","runDurableAutomation"],"entryPoint":"src/automation/index.ts","inputs":{"src/automation/types.ts":{"bytesInOutput":8},"src/automation/index.ts":{"bytesInOutput":0},"src/automation/operations.ts":{"bytesInOutput":1656},"src/automation/errors.ts":{"bytesInOutput":129},"src/security/secure-execution-contract.ts":{"bytesInOutput":10453},"src/security/path-policy.ts":{"bytesInOutput":2570},"src/security/windows-process-containment.ts":{"bytesInOutput":47621},"src/security/linux-process-containment.ts":{"bytesInOutput":1948},"src/security/containment-certification.ts":{"bytesInOutput":6156},"src/security/mxc-containment.ts":{"bytesInOutput":6366},"src/security/process-containment.ts":{"bytesInOutput":6520},"src/automation/policy.ts":{"bytesInOutput":7893},"src/automation/evidence.ts":{"bytesInOutput":4449},"src/artifacts/types.ts":{"bytesInOutput":825},"src/artifacts/validation.ts":{"bytesInOutput":13370},"src/artifacts/hash.ts":{"bytesInOutput":126},"src/utils/custom-names.ts":{"bytesInOutput":125},"src/artifacts/repository.ts":{"bytesInOutput":13753},"src/automation/executor.ts":{"bytesInOutput":7132},"src/automation/durable-execution.ts":{"bytesInOutput":2222},"src/automation/execution-journal.ts":{"bytesInOutput":4236},"src/automation/conformance.ts":{"bytesInOutput":2199},"src/automation/http-adapter.ts":{"bytesInOutput":4320},"src/automation/browser-control-plane-adapter.ts":{"bytesInOutput":9666},"src/automation/host-runtime.ts":{"bytesInOutput":12795},"src/artifacts/file-repository.ts":{"bytesInOutput":6720},"src/utils/fs.ts":{"bytesInOutput":314},"src/control-plane/lock.ts":{"bytesInOutput":1054},"src/version.ts":{"bytesInOutput":17},"src/utils/platform.ts":{"bytesInOutput":96},"src/agents/definitions.ts":{"bytesInOutput":20},"src/agents/profiles.ts":{"bytesInOutput":8624},"src/security/capability-lease.ts":{"bytesInOutput":14560},"src/automation/tool-pack.ts":{"bytesInOutput":10038}},"bytes":209333}}}
@@ -1,4 +1,4 @@
1
- "use strict";var ne=Object.defineProperty;var qe=Object.getOwnPropertyDescriptor;var Fe=Object.getOwnPropertyNames;var je=Object.prototype.hasOwnProperty;var He=(s,e)=>{for(var t in e)ne(s,t,{get:e[t],enumerable:!0})},Je=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Fe(e))!je.call(s,n)&&n!==t&&ne(s,n,{get:()=>e[n],enumerable:!(r=qe(e,n))||r.enumerable});return s};var Ke=s=>Je(ne({},"__esModule",{value:!0}),s);var vt={};He(vt,{AGENT_DAEMON_PROTOCOL_VERSION:()=>O,AgentDaemonClient:()=>le,AgentDaemonServer:()=>de,AgentEventStore:()=>W,AgentRunController:()=>ce,AgentRunStore:()=>L,MonitorManager:()=>fe,MonitorStopTool:()=>we,MonitorTool:()=>he,OtelExporter:()=>Re,PEER_MESSAGE_DEFAULT_TTL_MS:()=>Ue,PEER_PRESENCE_TTL_MS:()=>Ne,PEER_SCHEMA_VERSION:()=>P,PEER_TASK_TERMINAL_STATUSES:()=>Ve,PeerMessagingStore:()=>ve,UsageAccumulator:()=>Q,UsageLedger:()=>ke,WorkflowPlanner:()=>$,WorkflowRuntime:()=>me,WorkflowStore:()=>B,acquireControlPlaneLock:()=>M,createAgentRunId:()=>Te,defaultPeerDirectory:()=>Le,getAgentRunDir:()=>dt,getAgentRunStoreDir:()=>ct,isPeerTaskTerminal:()=>j,movesTrustUpward:()=>We,peerShortId:()=>ye,renderPeerLabel:()=>ee,resolvePeerTarget:()=>ht,toPeerPosture:()=>ft});module.exports=Ke(vt);var De=require("node:crypto"),f=require("node:fs"),m=require("node:path");var V="0.10.29";var A=require("node:fs"),se=require("node:os"),Ae=require("node:path");function ze(){return new Date().toISOString()}function Be(){return new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString()}function Se(s){try{return JSON.parse((0,A.readFileSync)(s,"utf8"))}catch{return null}}function Qe(s){if(!s||s<=0)return!1;try{return process.kill(s,0),!0}catch{return!1}}function Ge(s){return s.hostname!==(0,se.hostname)()?!0:Qe(s.pid)}function Pe(s,e){(0,A.mkdirSync)((0,Ae.dirname)(s),{recursive:!0}),(0,A.writeFileSync)(s,JSON.stringify(e,null,2)+`
1
+ "use strict";var ne=Object.defineProperty;var qe=Object.getOwnPropertyDescriptor;var Fe=Object.getOwnPropertyNames;var je=Object.prototype.hasOwnProperty;var He=(s,e)=>{for(var t in e)ne(s,t,{get:e[t],enumerable:!0})},Je=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Fe(e))!je.call(s,n)&&n!==t&&ne(s,n,{get:()=>e[n],enumerable:!(r=qe(e,n))||r.enumerable});return s};var Ke=s=>Je(ne({},"__esModule",{value:!0}),s);var vt={};He(vt,{AGENT_DAEMON_PROTOCOL_VERSION:()=>O,AgentDaemonClient:()=>le,AgentDaemonServer:()=>de,AgentEventStore:()=>W,AgentRunController:()=>ce,AgentRunStore:()=>L,MonitorManager:()=>fe,MonitorStopTool:()=>we,MonitorTool:()=>he,OtelExporter:()=>Re,PEER_MESSAGE_DEFAULT_TTL_MS:()=>Ue,PEER_PRESENCE_TTL_MS:()=>Ne,PEER_SCHEMA_VERSION:()=>P,PEER_TASK_TERMINAL_STATUSES:()=>Ve,PeerMessagingStore:()=>ve,UsageAccumulator:()=>Q,UsageLedger:()=>ke,WorkflowPlanner:()=>$,WorkflowRuntime:()=>me,WorkflowStore:()=>B,acquireControlPlaneLock:()=>M,createAgentRunId:()=>Te,defaultPeerDirectory:()=>Le,getAgentRunDir:()=>dt,getAgentRunStoreDir:()=>ct,isPeerTaskTerminal:()=>j,movesTrustUpward:()=>We,peerShortId:()=>ye,renderPeerLabel:()=>ee,resolvePeerTarget:()=>ht,toPeerPosture:()=>ft});module.exports=Ke(vt);var De=require("node:crypto"),f=require("node:fs"),m=require("node:path");var V="0.10.31";var A=require("node:fs"),se=require("node:os"),Ae=require("node:path");function ze(){return new Date().toISOString()}function Be(){return new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString()}function Se(s){try{return JSON.parse((0,A.readFileSync)(s,"utf8"))}catch{return null}}function Qe(s){if(!s||s<=0)return!1;try{return process.kill(s,0),!0}catch{return!1}}function Ge(s){return s.hostname!==(0,se.hostname)()?!0:Qe(s.pid)}function Pe(s,e){(0,A.mkdirSync)((0,Ae.dirname)(s),{recursive:!0}),(0,A.writeFileSync)(s,JSON.stringify(e,null,2)+`
2
2
  `,{encoding:"utf8",flag:"wx"})}function Xe(s,e){let t=Se(s);t?.pid!==e.pid||t.hostname!==e.hostname||(0,A.rmSync)(s,{force:!0})}function M(s,e,t){let r=ze(),n={schemaVersion:1,name:e,pid:process.pid,hostname:(0,se.hostname)(),processStartedAt:Be(),version:t,acquiredAt:r,updatedAt:r};try{Pe(s,n)}catch(o){if(o.code!=="EEXIST")throw o;let a=Se(s);if(a&&Ge(a))throw new Error(`${e} is already locked by PID ${a.pid} on ${a.hostname}.`);(0,A.rmSync)(s,{force:!0}),Pe(s,n)}return{record:n,release:()=>{Xe(s,n)}}}var Ee=require("node:crypto"),S=require("node:fs"),C=require("node:path");function xe(s){return(0,C.basename)(s).replace(/[^A-Za-z0-9_.-]/g,"_").slice(0,96)}function Ie(s){return(0,S.existsSync)(s)?(0,S.readFileSync)(s,"utf8").split(/\r?\n/).map(e=>e.trim()).filter(Boolean).map(e=>{try{return JSON.parse(e)}catch{return null}}).filter(e=>e!==null):[]}var W=class{constructor(e){this.runsDir=e;(0,S.mkdirSync)(this.runsDir,{recursive:!0})}runsDir;pathFor(e){return(0,C.join)(this.runsDir,xe(e),"events.jsonl")}append(e,t,r={},n=new Date().toISOString()){let o=this.pathFor(e);(0,S.mkdirSync)((0,C.dirname)(o),{recursive:!0});let i=M(`${o}.lock`,`events:${xe(e)}`,V);try{let a=Ie(o).reduce((x,p,d)=>Math.max(x,p.sequence??d),-1)+1,c={schemaVersion:1,eventId:`event_${(0,Ee.randomUUID)()}`,sequence:a,runId:e,type:t,timestamp:n,payload:r};return(0,S.appendFileSync)(o,`${JSON.stringify(c)}
3
3
  `,"utf8"),c}finally{i.release()}}read(e){return Ie(this.pathFor(e))}tail(e,t=100){let r=Math.max(0,Math.min(1e4,Math.trunc(t)));return r===0?[]:this.read(e).slice(-r)}};var _=require("node:os");var oe=require("node:path"),Et=(0,_.platform)();var bt=(0,_.release)(),Dt=(0,_.homedir)();function I(){let s=process.env.XENO_AGENT_HOME?.trim();return s?(0,oe.resolve)(s):(0,oe.resolve)((0,_.homedir)(),".xeno-agent")}var Ze=1,Ye=(0,m.join)(I(),"daemon"),ae=(0,m.join)(Ye,"runs");function k(){return new Date().toISOString()}function et(s=new Date){return s.toISOString().replace(/[^0-9]/g,"").slice(0,14)}function ie(s){return s.replace(/[^A-Za-z0-9_.-]/g,"_").slice(0,80)}function ue(s){return(0,m.resolve)(s)}function J(s){return ue(s).toLowerCase()}function be(s,e){let t=J(s),r=J(e);return t===r||t.startsWith(`${r}\\`)||t.startsWith(`${r}/`)}function tt(s,e){return!!(J(s.cwd)===J(e)||s.git?.root&&be(e,s.git.root)||s.git?.worktree&&be(e,s.git.worktree))}function rt(s){return ie(Buffer.from(ue(s)).toString("base64url"))}function nt(){return{input:0,output:0,total:0}}function H(s){try{return JSON.parse((0,f.readFileSync)(s,"utf8"))}catch{return null}}function st(s){return s instanceof Error&&/\balready locked by PID\b/.test(s.message)}function ot(s,e){(0,f.mkdirSync)((0,m.dirname)(s),{recursive:!0});let t=`${s}.${process.pid}.${Date.now()}.tmp`;(0,f.writeFileSync)(t,JSON.stringify(e,null,2)+`
4
4
  `,"utf8"),(0,f.renameSync)(t,s)}function it(s){if(!s||s<=0)return!1;try{return process.kill(s,0),!0}catch{return!1}}function at(s){return s==="completed"||s==="failed"||s==="cancelled"||s==="interrupted"}function ut(s,e){return s.pinned!==e.pinned?s.pinned?-1:1:Date.parse(e.updatedAt)-Date.parse(s.updatedAt)}function ct(){return ae}function dt(s){return(0,m.join)(ae,s)}function Te(s=new Date){return`run_${et(s)}_${(0,De.randomUUID)().slice(0,8)}`}var L=class{constructor(e=ae){this.runsDir=e;(0,f.mkdirSync)(this.runsDir,{recursive:!0}),this.eventStore=new W(this.runsDir)}runsDir;eventStore;create(e){let t=Te(),r=(0,m.join)(this.runsDir,t);(0,f.mkdirSync)(r,{recursive:!0});let n=k(),o=(0,m.join)(r,"events.jsonl"),i={schemaVersion:Ze,runId:t,sessionId:t,rootRunId:t,cwd:ue(e.cwd),workspaceId:rt(e.cwd),prompt:e.prompt,...e.title?{title:e.title}:{},status:"starting",model:e.model,...e.effort?{effort:e.effort}:{},...e.agent?{agent:e.agent}:{},...e.git?{git:e.git}:{},permissionMode:e.permissionMode,...e.cliVersion?{createdByCliVersion:e.cliVersion}:{},createdBySdkVersion:e.sdkVersion??V,createdAt:n,updatedAt:n,lastActivityAt:n,pinned:!!e.pinned,attachedClients:0,...e.cliVersion?{cliVersion:e.cliVersion}:{},...e.sdkVersion?{sdkVersion:e.sdkVersion}:{},stdoutPath:(0,m.join)(r,"stdout.log"),stderrPath:(0,m.join)(r,"stderr.log"),eventsPath:o,usage:nt(),children:[],tags:[]};return(0,f.writeFileSync)(i.stdoutPath,"","utf8"),(0,f.writeFileSync)(i.stderrPath,"","utf8"),(0,f.writeFileSync)(i.eventsPath,"","utf8"),this.write(i),this.appendEvent(t,"run_created",{cwd:i.cwd,model:i.model,...i.agent?{agent:i.agent}:{},...i.git?{git:i.git}:{},permissionMode:i.permissionMode,pinned:i.pinned}),i}get(e){let t=H(this.recordPath(e));return t?this.refreshRecordStatus(t):null}list(e={}){if(!(0,f.existsSync)(this.runsDir))return[];let t=(0,f.readdirSync)(this.runsDir,{withFileTypes:!0}).filter(r=>r.isDirectory()).map(r=>{try{return this.get(r.name)}catch(n){if(st(n))return H(this.recordPath(r.name));throw n}}).filter(r=>r!==null).filter(r=>e.all||!e.cwd||tt(r,e.cwd)).filter(r=>!e.status||e.status.includes(r.status)).sort(ut);return typeof e.limit=="number"&&e.limit>0?t.slice(0,e.limit):t}markSpawned(e,t,r){return this.update(e,n=>({...n,status:"running",workerPid:t,...r?{workerVersion:r}:{},startedAt:n.startedAt??k(),lastActivityAt:k()}))}markStarted(e,t){return this.update(e,r=>({...r,status:"running",workerPid:t.pid,...t.workerVersion?{workerVersion:t.workerVersion}:{},...t.model?{model:t.model}:{},...t.effort?{effort:t.effort}:{},startedAt:r.startedAt??k(),lastActivityAt:k()}))}markCompleted(e,t){return this.update(e,r=>({...r,status:t.status,...t.statusReason?{statusReason:t.statusReason}:{},exitCode:t.exitCode??null,usage:t.usage??r.usage,endedAt:k(),lastActivityAt:k()}))}markCancelled(e,t){return this.update(e,r=>({...r,status:"cancelled",statusReason:t,endedAt:k(),lastActivityAt:k()}))}markPaused(e,t="Paused by user."){let r=this.update(e,n=>({...n,status:"paused",statusReason:t,lastActivityAt:k()}));return r&&this.appendEvent(e,"run_paused",{reason:t}),r}markResumed(e,t="Resumed by user."){let r=this.update(e,n=>{let o={...n,status:"running",statusReason:t,lastActivityAt:k()};return delete o.endedAt,delete o.exitCode,o});return r&&this.appendEvent(e,"run_resumed",{reason:t}),r}setPinned(e,t){let r=this.update(e,n=>({...n,pinned:t,lastActivityAt:k()}));return r&&this.appendEvent(e,t?"run_pinned":"run_unpinned",{pinned:t}),r}appendEvent(e,t,r={}){let n=H(this.recordPath(e)),o=this.eventStore.append(e,t,r);n&&this.update(e,i=>({...i,lastActivityAt:o.timestamp}))}readEvents(e){return this.get(e)?this.eventStore.read(e):[]}delete(e){(0,f.rmSync)((0,m.join)(this.runsDir,e),{recursive:!0,force:!0})}refreshRecordStatus(e){if(at(e.status))return e;if(e.workerPid&&!it(e.workerPid)){let t={...e,status:"failed",statusReason:"Worker process is no longer running and did not record a terminal status.",endedAt:e.endedAt??k(),updatedAt:k()};return this.write(t),t}return e}update(e,t){let r=H(this.recordPath(e));if(!r)return null;let n=t(r);return n.updatedAt=k(),this.write(n),n}write(e){let t=M((0,m.join)(this.runDir(e.runId),"run.lock"),`run:${e.runId}`,V);try{ot(this.recordPath(e.runId),e)}finally{t.release()}}recordPath(e){return(0,m.join)(this.runsDir,ie((0,m.basename)(e)),"run.json")}runDir(e){return(0,m.join)(this.runsDir,ie((0,m.basename)(e)))}};function Me(s){return s==="completed"||s==="failed"||s==="cancelled"||s==="interrupted"}var ce=class{constructor(e={}){this.options=e;this.store=e.store??new L}options;store;create(e){return this.store.create(e)}async start(e){let t=this.create(e);if(!this.options.spawn)return t;try{let r=await this.options.spawn(t),n=this.store.markSpawned(t.runId,r.pid,r.workerVersion);if(!n)throw new Error(`Run disappeared during spawn: ${t.runId}`);return this.store.appendEvent(t.runId,"run_started",{pid:r.pid}),n}catch(r){let n=r instanceof Error?r.message:String(r);throw this.store.markCompleted(t.runId,{status:"failed",statusReason:n,exitCode:null}),this.store.appendEvent(t.runId,"run_start_failed",{reason:n}),r}}get(e){return this.store.get(e)}list(e={}){return this.store.list(e)}events(e,t){let r=this.store.readEvents(e);return t===void 0?r:r.slice(-Math.max(0,Math.trunc(t)))}async stop(e,t="Stopped by user."){let r=this.store.get(e);if(!r||Me(r.status))return r;await this.options.stop?.(r,t);let n=this.store.markCancelled(e,t);return n&&this.store.appendEvent(e,"run_cancelled",{reason:t}),n}async pause(e,t="Paused by user."){let r=this.store.get(e);return!r||Me(r.status)||r.status==="paused"?r:(await this.options.pause?.(r,t),this.store.markPaused(e,t))}async resume(e,t="Resumed by user."){let r=this.store.get(e);return!r||r.status!=="paused"?r:(await this.options.resume?.(r,t),this.store.markResumed(e,t))}complete(e,t,r={}){let n=this.store.markCompleted(e,{status:t,...r.reason?{statusReason:r.reason}:{},...r.exitCode!==void 0?{exitCode:r.exitCode}:{},...r.usage?{usage:r.usage}:{}});return n&&this.store.appendEvent(e,`run_${t}`,{...r.reason?{reason:r.reason}:{}}),n}};var K=require("node:crypto"),O=1;function lt(s,e){if(!s)return!1;let t=Buffer.from(s),r=Buffer.from(e);return t.length===r.length&&(0,K.timingSafeEqual)(t,r)}var de=class{constructor(e={}){this.options=e}options;handlers=new Map;register(e,t){let r=e.trim();if(!r)throw new Error("Daemon method name cannot be empty.");if(this.handlers.has(r))throw new Error(`Daemon method already registered: ${r}`);return this.handlers.set(r,t),this}registerController(e){return this.register("runs.start",t=>e.start(t)).register("runs.get",t=>e.get(t.runId)).register("runs.list",t=>e.list(t??{})).register("runs.events",t=>{let r=t;return e.events(r.runId,r.limit)}).register("runs.stop",t=>{let r=t;return e.stop(r.runId,r.reason)}).register("runs.pause",t=>{let r=t;return e.pause(r.runId,r.reason)}).register("runs.resume",t=>{let r=t;return e.resume(r.runId,r.reason)})}async handle(e){if(e.protocolVersion!==O)return this.error(e.id,"PROTOCOL_MISMATCH",`Unsupported protocol version: ${e.protocolVersion}`);if(this.options.authToken&&!lt(e.authToken,this.options.authToken))return this.error(e.id,"UNAUTHORIZED","Daemon authentication failed.");let t=this.handlers.get(e.method);if(!t)return this.error(e.id,"METHOD_NOT_FOUND",`Unknown daemon method: ${e.method}`);try{return{protocolVersion:O,id:e.id,result:await t(e.params,e)}}catch(r){return this.error(e.id,"INTERNAL_ERROR",r instanceof Error?r.message:String(r))}}error(e,t,r){return{protocolVersion:O,id:e,error:{code:t,message:r}}}},le=class{constructor(e,t={}){this.transport=e;this.options=t}transport;options;async request(e,t){let r={protocolVersion:O,id:`request_${(0,K.randomUUID)()}`,method:e,params:t,...this.options.authToken?{authToken:this.options.authToken}:{}},n=await this.transport(r);if(n.protocolVersion!==O||n.id!==r.id)throw new Error("Invalid daemon response identity.");if("error"in n){let o=new Error(n.error.message);throw o.code=n.error.code,o}return n.result}};var pe=require("node:crypto"),h=require("node:fs"),v=require("node:path");function z(s){return(0,v.basename)(s).replace(/[^A-Za-z0-9_.-]/g,"_").slice(0,96)}function ge(s){try{return JSON.parse((0,h.readFileSync)(s,"utf8"))}catch{return null}}function _e(s,e){(0,h.mkdirSync)((0,v.dirname)(s),{recursive:!0});let t=`${s}.${process.pid}.${Date.now()}.tmp`;(0,h.writeFileSync)(t,`${JSON.stringify(e,null,2)}
@@ -1,4 +1,4 @@
1
- import{randomUUID as Qe}from"node:crypto";import{existsSync as Ge,mkdirSync as B,readFileSync as Xe,readdirSync as Ze,renameSync as Ye,rmSync as et,writeFileSync as N}from"node:fs";import{basename as ge,dirname as tt,join as w,resolve as rt}from"node:path";var b="0.10.29";import{mkdirSync as Me,readFileSync as _e,rmSync as se,writeFileSync as Ce}from"node:fs";import{hostname as oe}from"node:os";import{dirname as Oe}from"node:path";function $e(){return new Date().toISOString()}function Ne(){return new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString()}function ie(s){try{return JSON.parse(_e(s,"utf8"))}catch{return null}}function Ue(s){if(!s||s<=0)return!1;try{return process.kill(s,0),!0}catch{return!1}}function Ve(s){return s.hostname!==oe()?!0:Ue(s.pid)}function ne(s,e){Me(Oe(s),{recursive:!0}),Ce(s,JSON.stringify(e,null,2)+`
1
+ import{randomUUID as Qe}from"node:crypto";import{existsSync as Ge,mkdirSync as B,readFileSync as Xe,readdirSync as Ze,renameSync as Ye,rmSync as et,writeFileSync as N}from"node:fs";import{basename as ge,dirname as tt,join as w,resolve as rt}from"node:path";var b="0.10.31";import{mkdirSync as Me,readFileSync as _e,rmSync as se,writeFileSync as Ce}from"node:fs";import{hostname as oe}from"node:os";import{dirname as Oe}from"node:path";function $e(){return new Date().toISOString()}function Ne(){return new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString()}function ie(s){try{return JSON.parse(_e(s,"utf8"))}catch{return null}}function Ue(s){if(!s||s<=0)return!1;try{return process.kill(s,0),!0}catch{return!1}}function Ve(s){return s.hostname!==oe()?!0:Ue(s.pid)}function ne(s,e){Me(Oe(s),{recursive:!0}),Ce(s,JSON.stringify(e,null,2)+`
2
2
  `,{encoding:"utf8",flag:"wx"})}function We(s,e){let t=ie(s);t?.pid!==e.pid||t.hostname!==e.hostname||se(s,{force:!0})}function x(s,e,t){let r=$e(),n={schemaVersion:1,name:e,pid:process.pid,hostname:oe(),processStartedAt:Ne(),version:t,acquiredAt:r,updatedAt:r};try{ne(s,n)}catch(o){if(o.code!=="EEXIST")throw o;let a=ie(s);if(a&&Ve(a))throw new Error(`${e} is already locked by PID ${a.pid} on ${a.hostname}.`);se(s,{force:!0}),ne(s,n)}return{record:n,release:()=>{We(s,n)}}}import{randomUUID as Le}from"node:crypto";import{appendFileSync as qe,existsSync as Fe,mkdirSync as ae,readFileSync as je}from"node:fs";import{basename as He,dirname as Je,join as Ke}from"node:path";function ue(s){return He(s).replace(/[^A-Za-z0-9_.-]/g,"_").slice(0,96)}function ce(s){return Fe(s)?je(s,"utf8").split(/\r?\n/).map(e=>e.trim()).filter(Boolean).map(e=>{try{return JSON.parse(e)}catch{return null}}).filter(e=>e!==null):[]}var O=class{constructor(e){this.runsDir=e;ae(this.runsDir,{recursive:!0})}runsDir;pathFor(e){return Ke(this.runsDir,ue(e),"events.jsonl")}append(e,t,r={},n=new Date().toISOString()){let o=this.pathFor(e);ae(Je(o),{recursive:!0});let i=x(`${o}.lock`,`events:${ue(e)}`,b);try{let a=ce(o).reduce((R,g,c)=>Math.max(R,g.sequence??c),-1)+1,u={schemaVersion:1,eventId:`event_${Le()}`,sequence:a,runId:e,type:t,timestamp:n,payload:r};return qe(o,`${JSON.stringify(u)}
3
3
  `,"utf8"),u}finally{i.release()}}read(e){return ce(this.pathFor(e))}tail(e,t=100){let r=Math.max(0,Math.min(1e4,Math.trunc(t)));return r===0?[]:this.read(e).slice(-r)}};import{homedir as le,platform as ze,release as Be}from"node:os";import{resolve as de}from"node:path";var ur=ze();var cr=Be(),dr=le();function v(){let s=process.env.XENO_AGENT_HOME?.trim();return s?de(s):de(le(),".xeno-agent")}var nt=1,st=w(v(),"daemon"),G=w(st,"runs");function m(){return new Date().toISOString()}function ot(s=new Date){return s.toISOString().replace(/[^0-9]/g,"").slice(0,14)}function Q(s){return s.replace(/[^A-Za-z0-9_.-]/g,"_").slice(0,80)}function X(s){return rt(s)}function U(s){return X(s).toLowerCase()}function pe(s,e){let t=U(s),r=U(e);return t===r||t.startsWith(`${r}\\`)||t.startsWith(`${r}/`)}function it(s,e){return!!(U(s.cwd)===U(e)||s.git?.root&&pe(e,s.git.root)||s.git?.worktree&&pe(e,s.git.worktree))}function at(s){return Q(Buffer.from(X(s)).toString("base64url"))}function ut(){return{input:0,output:0,total:0}}function $(s){try{return JSON.parse(Xe(s,"utf8"))}catch{return null}}function ct(s){return s instanceof Error&&/\balready locked by PID\b/.test(s.message)}function dt(s,e){B(tt(s),{recursive:!0});let t=`${s}.${process.pid}.${Date.now()}.tmp`;N(t,JSON.stringify(e,null,2)+`
4
4
  `,"utf8"),Ye(t,s)}function lt(s){if(!s||s<=0)return!1;try{return process.kill(s,0),!0}catch{return!1}}function gt(s){return s==="completed"||s==="failed"||s==="cancelled"||s==="interrupted"}function pt(s,e){return s.pinned!==e.pinned?s.pinned?-1:1:Date.parse(e.updatedAt)-Date.parse(s.updatedAt)}function Rr(){return G}function vr(s){return w(G,s)}function mt(s=new Date){return`run_${ot(s)}_${Qe().slice(0,8)}`}var V=class{constructor(e=G){this.runsDir=e;B(this.runsDir,{recursive:!0}),this.eventStore=new O(this.runsDir)}runsDir;eventStore;create(e){let t=mt(),r=w(this.runsDir,t);B(r,{recursive:!0});let n=m(),o=w(r,"events.jsonl"),i={schemaVersion:nt,runId:t,sessionId:t,rootRunId:t,cwd:X(e.cwd),workspaceId:at(e.cwd),prompt:e.prompt,...e.title?{title:e.title}:{},status:"starting",model:e.model,...e.effort?{effort:e.effort}:{},...e.agent?{agent:e.agent}:{},...e.git?{git:e.git}:{},permissionMode:e.permissionMode,...e.cliVersion?{createdByCliVersion:e.cliVersion}:{},createdBySdkVersion:e.sdkVersion??b,createdAt:n,updatedAt:n,lastActivityAt:n,pinned:!!e.pinned,attachedClients:0,...e.cliVersion?{cliVersion:e.cliVersion}:{},...e.sdkVersion?{sdkVersion:e.sdkVersion}:{},stdoutPath:w(r,"stdout.log"),stderrPath:w(r,"stderr.log"),eventsPath:o,usage:ut(),children:[],tags:[]};return N(i.stdoutPath,"","utf8"),N(i.stderrPath,"","utf8"),N(i.eventsPath,"","utf8"),this.write(i),this.appendEvent(t,"run_created",{cwd:i.cwd,model:i.model,...i.agent?{agent:i.agent}:{},...i.git?{git:i.git}:{},permissionMode:i.permissionMode,pinned:i.pinned}),i}get(e){let t=$(this.recordPath(e));return t?this.refreshRecordStatus(t):null}list(e={}){if(!Ge(this.runsDir))return[];let t=Ze(this.runsDir,{withFileTypes:!0}).filter(r=>r.isDirectory()).map(r=>{try{return this.get(r.name)}catch(n){if(ct(n))return $(this.recordPath(r.name));throw n}}).filter(r=>r!==null).filter(r=>e.all||!e.cwd||it(r,e.cwd)).filter(r=>!e.status||e.status.includes(r.status)).sort(pt);return typeof e.limit=="number"&&e.limit>0?t.slice(0,e.limit):t}markSpawned(e,t,r){return this.update(e,n=>({...n,status:"running",workerPid:t,...r?{workerVersion:r}:{},startedAt:n.startedAt??m(),lastActivityAt:m()}))}markStarted(e,t){return this.update(e,r=>({...r,status:"running",workerPid:t.pid,...t.workerVersion?{workerVersion:t.workerVersion}:{},...t.model?{model:t.model}:{},...t.effort?{effort:t.effort}:{},startedAt:r.startedAt??m(),lastActivityAt:m()}))}markCompleted(e,t){return this.update(e,r=>({...r,status:t.status,...t.statusReason?{statusReason:t.statusReason}:{},exitCode:t.exitCode??null,usage:t.usage??r.usage,endedAt:m(),lastActivityAt:m()}))}markCancelled(e,t){return this.update(e,r=>({...r,status:"cancelled",statusReason:t,endedAt:m(),lastActivityAt:m()}))}markPaused(e,t="Paused by user."){let r=this.update(e,n=>({...n,status:"paused",statusReason:t,lastActivityAt:m()}));return r&&this.appendEvent(e,"run_paused",{reason:t}),r}markResumed(e,t="Resumed by user."){let r=this.update(e,n=>{let o={...n,status:"running",statusReason:t,lastActivityAt:m()};return delete o.endedAt,delete o.exitCode,o});return r&&this.appendEvent(e,"run_resumed",{reason:t}),r}setPinned(e,t){let r=this.update(e,n=>({...n,pinned:t,lastActivityAt:m()}));return r&&this.appendEvent(e,t?"run_pinned":"run_unpinned",{pinned:t}),r}appendEvent(e,t,r={}){let n=$(this.recordPath(e)),o=this.eventStore.append(e,t,r);n&&this.update(e,i=>({...i,lastActivityAt:o.timestamp}))}readEvents(e){return this.get(e)?this.eventStore.read(e):[]}delete(e){et(w(this.runsDir,e),{recursive:!0,force:!0})}refreshRecordStatus(e){if(gt(e.status))return e;if(e.workerPid&&!lt(e.workerPid)){let t={...e,status:"failed",statusReason:"Worker process is no longer running and did not record a terminal status.",endedAt:e.endedAt??m(),updatedAt:m()};return this.write(t),t}return e}update(e,t){let r=$(this.recordPath(e));if(!r)return null;let n=t(r);return n.updatedAt=m(),this.write(n),n}write(e){let t=x(w(this.runDir(e.runId),"run.lock"),`run:${e.runId}`,b);try{dt(this.recordPath(e.runId),e)}finally{t.release()}}recordPath(e){return w(this.runsDir,Q(ge(e)),"run.json")}runDir(e){return w(this.runsDir,Q(ge(e)))}};function me(s){return s==="completed"||s==="failed"||s==="cancelled"||s==="interrupted"}var fe=class{constructor(e={}){this.options=e;this.store=e.store??new V}options;store;create(e){return this.store.create(e)}async start(e){let t=this.create(e);if(!this.options.spawn)return t;try{let r=await this.options.spawn(t),n=this.store.markSpawned(t.runId,r.pid,r.workerVersion);if(!n)throw new Error(`Run disappeared during spawn: ${t.runId}`);return this.store.appendEvent(t.runId,"run_started",{pid:r.pid}),n}catch(r){let n=r instanceof Error?r.message:String(r);throw this.store.markCompleted(t.runId,{status:"failed",statusReason:n,exitCode:null}),this.store.appendEvent(t.runId,"run_start_failed",{reason:n}),r}}get(e){return this.store.get(e)}list(e={}){return this.store.list(e)}events(e,t){let r=this.store.readEvents(e);return t===void 0?r:r.slice(-Math.max(0,Math.trunc(t)))}async stop(e,t="Stopped by user."){let r=this.store.get(e);if(!r||me(r.status))return r;await this.options.stop?.(r,t);let n=this.store.markCancelled(e,t);return n&&this.store.appendEvent(e,"run_cancelled",{reason:t}),n}async pause(e,t="Paused by user."){let r=this.store.get(e);return!r||me(r.status)||r.status==="paused"?r:(await this.options.pause?.(r,t),this.store.markPaused(e,t))}async resume(e,t="Resumed by user."){let r=this.store.get(e);return!r||r.status!=="paused"?r:(await this.options.resume?.(r,t),this.store.markResumed(e,t))}complete(e,t,r={}){let n=this.store.markCompleted(e,{status:t,...r.reason?{statusReason:r.reason}:{},...r.exitCode!==void 0?{exitCode:r.exitCode}:{},...r.usage?{usage:r.usage}:{}});return n&&this.store.appendEvent(e,`run_${t}`,{...r.reason?{reason:r.reason}:{}}),n}};import{randomUUID as ft,timingSafeEqual as ht}from"node:crypto";var D=1;function wt(s,e){if(!s)return!1;let t=Buffer.from(s),r=Buffer.from(e);return t.length===r.length&&ht(t,r)}var he=class{constructor(e={}){this.options=e}options;handlers=new Map;register(e,t){let r=e.trim();if(!r)throw new Error("Daemon method name cannot be empty.");if(this.handlers.has(r))throw new Error(`Daemon method already registered: ${r}`);return this.handlers.set(r,t),this}registerController(e){return this.register("runs.start",t=>e.start(t)).register("runs.get",t=>e.get(t.runId)).register("runs.list",t=>e.list(t??{})).register("runs.events",t=>{let r=t;return e.events(r.runId,r.limit)}).register("runs.stop",t=>{let r=t;return e.stop(r.runId,r.reason)}).register("runs.pause",t=>{let r=t;return e.pause(r.runId,r.reason)}).register("runs.resume",t=>{let r=t;return e.resume(r.runId,r.reason)})}async handle(e){if(e.protocolVersion!==D)return this.error(e.id,"PROTOCOL_MISMATCH",`Unsupported protocol version: ${e.protocolVersion}`);if(this.options.authToken&&!wt(e.authToken,this.options.authToken))return this.error(e.id,"UNAUTHORIZED","Daemon authentication failed.");let t=this.handlers.get(e.method);if(!t)return this.error(e.id,"METHOD_NOT_FOUND",`Unknown daemon method: ${e.method}`);try{return{protocolVersion:D,id:e.id,result:await t(e.params,e)}}catch(r){return this.error(e.id,"INTERNAL_ERROR",r instanceof Error?r.message:String(r))}}error(e,t,r){return{protocolVersion:D,id:e,error:{code:t,message:r}}}},we=class{constructor(e,t={}){this.transport=e;this.options=t}transport;options;async request(e,t){let r={protocolVersion:D,id:`request_${ft()}`,method:e,params:t,...this.options.authToken?{authToken:this.options.authToken}:{}},n=await this.transport(r);if(n.protocolVersion!==D||n.id!==r.id)throw new Error("Invalid daemon response identity.");if("error"in n){let o=new Error(n.error.message);throw o.code=n.error.code,o}return n.result}};import{randomUUID as ke}from"node:crypto";import{appendFileSync as kt,existsSync as Rt,mkdirSync as L,readFileSync as ye,readdirSync as vt,renameSync as yt,writeFileSync as Pt}from"node:fs";import{basename as At,dirname as Pe,join as y}from"node:path";function W(s){return At(s).replace(/[^A-Za-z0-9_.-]/g,"_").slice(0,96)}function Z(s){try{return JSON.parse(ye(s,"utf8"))}catch{return null}}function Re(s,e){L(Pe(s),{recursive:!0});let t=`${s}.${process.pid}.${Date.now()}.tmp`;Pt(t,`${JSON.stringify(e,null,2)}
@@ -1,2 +1,2 @@
1
- "use strict";var he=Object.create;var C=Object.defineProperty;var me=Object.getOwnPropertyDescriptor;var ge=Object.getOwnPropertyNames;var we=Object.getPrototypeOf,Ie=Object.prototype.hasOwnProperty;var Ee=(d,e)=>{for(var o in e)C(d,o,{get:e[o],enumerable:!0})},W=(d,e,o,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of ge(e))!Ie.call(d,t)&&t!==o&&C(d,t,{get:()=>e[t],enumerable:!(i=me(e,t))||i.enumerable});return d};var q=(d,e,o)=>(o=d!=null?he(we(d)):{},W(e||!d||!d.__esModule?C(o,"default",{value:d,enumerable:!0}):o,d)),ye=d=>W(C({},"__esModule",{value:!0}),d);var ke={};Ee(ke,{DurableXenoCoordinationStore:()=>X,XENO_COORDINATION_BUDGET_SESSION_SCHEMA_VERSION:()=>k,XENO_COORDINATION_MANAGED_SESSION_SCHEMA_VERSION:()=>F,XENO_COORDINATION_SCHEMA_VERSION:()=>A,XENO_COORDINATION_TURN_SESSION_SCHEMA_VERSION:()=>_,XenoCoordinationError:()=>u,XenoExecutionLeaseSession:()=>j,captureXenoHandoffSnapshot:()=>Ne,executeXenoCoordinationAction:()=>Xe,restoreXenoHandoffSnapshot:()=>Ce,waitForXenoHandoffStatus:()=>Le});module.exports=ye(ke);var A=1,F=2,k=3,_=4,u=class extends Error{constructor(o,i,t={}){super(i);this.code=o;this.details=t;this.name="XenoCoordinationError"}code;details};var T=require("node:crypto"),h=q(require("node:fs/promises"),1),O=q(require("node:os"),1),y=q(require("node:path"),1);var S=require("node:os");var U=require("node:path"),Pe=(0,S.platform)();var Ge=(0,S.release)(),Ve=(0,S.homedir)();function K(){let d=process.env.XENO_AGENT_HOME?.trim();return d?(0,U.resolve)(d):(0,U.resolve)((0,S.homedir)(),".xeno-agent")}var D=class extends Error{constructor(o,i){super(i);this.code=o;this.name="QuotaError"}code;retryable=!1};function Y(d){if(typeof d!="string"||!d.trim()||d.length>512)throw new D("INVALID","Invalid quota identity.");return d}function $(d){let e=o=>({id:Y(o?.id),generation:Y(o?.generation)});if(!d||d.agent&&!d.team)throw new D("INVALID","A child quota scope requires its complete ancestry.");return{workspace:e(d.workspace),...d.team?{team:e(d.team)}:{},...d.agent?{agent:e(d.agent)}:{},...d.goal!==void 0?{goal:e(d.goal)}:{}}}function B(d){return JSON.stringify($(d))}var ve=3e4,be=3e4,Ae=6e4,Oe=2e4,P=new Set(["EACCES","EBUSY","EPERM"]),Z=[5,10,20,40,80,160,320],Se=[5,10,20,40,80,160,320],ee=[1,2,3,4];function p(d,e,o=16384){let i=d.trim();if(!i||i.length>o)throw new u("INVALID",`${e} must be non-empty and no longer than ${o} characters`);return i}function G(d,e){return[...new Set((d??[]).map(o=>p(o,e)))]}function te(d){if(d===void 0)return;if(!d||typeof d!="object"||Array.isArray(d))throw new u("INVALID","Goal limits must be an object when provided");let e={};for(let[o,i]of Object.entries(d)){if(o!=="maxIterations"&&o!=="maxTokens"&&o!=="maxWallClockMs")throw new u("INVALID","Unknown goal limit");if(i!==void 0){if(!Number.isSafeInteger(i)||i<=0)throw new u("INVALID",`${o} must be a positive safe integer when provided`);e[o]=i}}return e}function Te(d){if(d){if(d.kind!=="fixed-interval"&&d.kind!=="dynamic")throw new u("INVALID","schedule.kind must be fixed-interval or dynamic");if(d.kind==="fixed-interval"&&(!Number.isSafeInteger(d.intervalMs)||(d.intervalMs??0)<=0))throw new u("INVALID","Fixed-interval schedules require a positive safe intervalMs");if(d.intervalMs!==void 0&&(!Number.isSafeInteger(d.intervalMs)||d.intervalMs<=0))throw new u("INVALID","schedule.intervalMs must be a positive safe integer when provided");for(let e of["nextRunAt","expiresAt"]){let o=d[e];if(o!==void 0&&!Number.isFinite(Date.parse(o)))throw new u("INVALID",`schedule.${e} must be an ISO timestamp when provided`)}return w(d)}}function w(d){return structuredClone(d)}function b(d){let e=Date.parse(d);return Number.isFinite(e)?e:0}function V(d){if(!Number.isInteger(d)||d<=0)return!1;try{return process.kill(d,0),!0}catch(e){return e.code==="EPERM"}}function xe(d){return{summary:"Goal created; work has not started.",completedTaskCount:0,totalTaskCount:0,outstanding:[],decisions:[],updatedAt:d}}function Re(){return{status:"pending",criteria:[],evidence:[]}}function oe(d){return(0,T.createHash)("sha256").update(d).digest("hex")}var X=class{get goalTurnAdmissionVersion(){return 1}rootDirectory;now;idFactory;ownerLeaseMs;lockTimeoutMs;lockStaleMs;maximumEventsPerSession;constructor(e={}){this.rootDirectory=e.rootDirectory??y.join(K(),"coordination"),this.now=e.now??(()=>new Date().toISOString()),this.idFactory=e.idFactory??(o=>`${o}_${(0,T.randomUUID)()}`),this.ownerLeaseMs=e.ownerLeaseMs??ve,this.lockTimeoutMs=e.lockTimeoutMs??be,this.lockStaleMs=e.lockStaleMs??Ae,this.maximumEventsPerSession=e.maximumEventsPerSession??Oe}async getSessionState(e){let o=p(e,"sessionId",1024);return w(await this.readState(o))}async fenceAdmission(e,o,i){let t=p(i.authorityId,"authorityId",512),n=p(i.operationId,"operationId",512);if(!Number.isSafeInteger(o)||o<0)throw new u("INVALID","Expected session version must be a nonnegative safe integer");if(i.action!=="archive"&&i.action!=="delete")throw new u("INVALID","Unsupported admission fence action");return this.mutate(e,r=>{let s=r.admissionFence;if(s?.authorityId===t&&s.operationId===n&&s.action===i.action)return s;if(r.version!==o)throw new u("CONFLICT","Session version changed before lifecycle fencing",{expected:o,actual:r.version});if(s?.authorityId===t&&s.action==="archive"&&i.action==="archive")return s;if(s&&!(s.authorityId===t&&s.action==="archive"&&i.action==="delete"))throw new u("CONFLICT","Another lifecycle fence already owns this session");let a={schemaVersion:1,authorityId:t,operationId:n,action:i.action,createdAt:this.now()};return r.admissionFence=a,r.schemaVersion===1&&(r.schemaVersion=2),this.appendEvent(r,"admission.fenced",{data:{authorityId:t,operationId:n,action:i.action}}),a},!0)}async clearAdmissionFence(e,o,i,t){await this.mutate(e,n=>{this.assertVersion(e,n.version,o);let r=n.admissionFence;if(!r||r.authorityId!==i||r.operationId!==t)throw new u("CONFLICT","Lifecycle fence identity does not match");if(r.action==="delete")throw new u("CONFLICT","Deleted session admission cannot be restored");if(n.owner)throw new u("CONFLICT","Execution ownership must settle before restoration");n.admissionFence=void 0,this.appendEvent(n,"admission.restored",{data:{authorityId:i,operationId:t}})},!0)}async releaseDeadLifecycleOwner(e,o,i,t){await this.mutate(e,n=>{this.assertVersion(e,n.version,o);let r=n.admissionFence;if(!r||r.authorityId!==i||r.operationId!==t)throw new u("CONFLICT","Lifecycle fence identity does not match");let s=n.owner;if(s){if(s.host!==O.hostname()||!Number.isInteger(s.processId)||(s.processId??0)<=0||V(s.processId))throw new u("CONFLICT","Execution owner exit has not been proved");n.owner=void 0,this.appendEvent(n,"ownership.released",{ownerId:s.ownerId,data:{epoch:s.epoch,reason:"fenced-local-owner-exited"}})}},!0)}async listSessionStates(){let e=y.join(this.rootDirectory,"sessions"),o;try{o=await h.readdir(e)}catch(t){if(t.code==="ENOENT")return[];throw t}return(await Promise.all(o.filter(t=>t.endsWith(".json")).map(async t=>{try{let n=JSON.parse(await h.readFile(y.join(e,t),"utf8"));return!ee.includes(n.schemaVersion)||typeof n.sessionId!="string"?void 0:((!Number.isSafeInteger(n.ownershipEpoch)||n.ownershipEpoch<0)&&(n.ownershipEpoch=Math.max(n.owner?.epoch??0,...n.handoffs.map(r=>r.targetLeaseEpoch??r.sourceLeaseEpoch??0))),n)}catch{return}}))).filter(t=>t!==void 0).sort((t,n)=>b(n.updatedAt)-b(t.updatedAt)).map(t=>w(t))}async createGoal(e){let o=p(e.sessionId,"sessionId",1024),i=te(e.limits);return this.mutate(o,t=>{let n=t.goals.find(c=>["active","paused","waiting","blocked"].includes(c.status));if(n)throw new u("CONFLICT",`Session ${o} already has active goal ${n.id}`);let r=this.now(),s=(e.successCriteria??[]).map(c=>typeof c=="string"?{id:this.idFactory("criterion"),description:p(c,"successCriteria"),required:!0}:{id:c.id?p(c.id,"successCriteria.id",512):this.idFactory("criterion"),description:p(c.description,"successCriteria.description"),required:c.required}),a={schemaVersion:1,id:this.idFactory("goal"),version:1,sessionId:o,objective:p(e.objective,"objective"),...e.why?{why:p(e.why,"why")}:{},successCriteria:s,constraints:G(e.constraints,"constraints"),...i?{limits:i}:{},metadata:w(e.metadata??{}),status:"active",milestones:[],tasks:[],progress:xe(r),verification:Re(),steering:[],createdAt:r,updatedAt:r};return t.goals.push(a),this.appendEvent(t,"goal.created",{goalId:a.id,data:{objective:a.objective}}),a})}async getGoal(e,o){let i=await this.getSessionState(e),t=o?i.goals.find(n=>n.id===o):[...i.goals].reverse().find(n=>["active","paused","waiting","blocked"].includes(n.status));return t?w(t):void 0}async updateGoal(e,o,i,t){return this.mutate(e,n=>{let r=this.requireGoal(n,o);if(this.assertVersion(r.id,r.version,i),["completed","cancelled","failed"].includes(r.status))throw new u("CONFLICT",`Goal ${r.id} is terminal (${r.status})`);let s=r.status!=="active";if(t.status==="active"&&r.status==="blocked"?r.status="active":t.status&&(r.status=t.status),t.objective!==void 0&&(r.objective=p(t.objective,"objective")),t.why!==void 0&&(r.why=p(t.why,"why")),t.constraints&&(r.constraints=G(t.constraints,"constraints")),t.successCriteria&&(r.successCriteria=w(t.successCriteria)),t.progress&&(r.progress={...r.progress,...w(t.progress),outstanding:G(t.progress.outstanding??r.progress.outstanding,"progress.outstanding"),decisions:G(t.progress.decisions??r.progress.decisions,"progress.decisions"),updatedAt:this.now()}),t.verification&&(r.verification=w(t.verification)),t.metadata&&(r.metadata=w(t.metadata)),s&&r.status==="active")for(let a of n.loops.filter(c=>c.goalId===o&&c.kind==="goal-continuation"&&c.status==="running"))a.resumeRequested=!0,a.version+=1,a.updatedAt=this.now();return r.version+=1,r.updatedAt=this.now(),this.appendEvent(n,"goal.updated",{goalId:r.id,data:{status:r.status,version:r.version}}),r},t.status!==void 0&&["paused","cancelled","failed"].includes(t.status))}async addMilestone(e,o,i,t){return this.mutateGoal(e,o,i,(n,r)=>{let s={id:this.idFactory("milestone"),title:p(t.title,"milestone.title"),...t.description?{description:p(t.description,"milestone.description")}:{},status:n.milestones.some(a=>a.status==="active")?"pending":"active",taskIds:[],createdAt:r,updatedAt:r};n.milestones.push(s),n.progress.currentMilestoneId??=s.id,n.progress.updatedAt=r})}async addTask(e,o,i,t){return this.mutateGoal(e,o,i,(n,r)=>{let s=n.milestones.find(l=>l.id===t.milestoneId);if(!s)throw new u("NOT_FOUND",`Milestone ${t.milestoneId} was not found`);if(t.parentTaskId&&!n.tasks.some(l=>l.id===t.parentTaskId))throw new u("NOT_FOUND",`Parent task ${t.parentTaskId} was not found`);let a=[...new Set(t.dependsOn??[])];for(let l of a)if(!n.tasks.some(f=>f.id===l))throw new u("NOT_FOUND",`Task dependency ${l} was not found`);let c={id:this.idFactory("task"),milestoneId:s.id,...t.parentTaskId?{parentTaskId:t.parentTaskId}:{},title:p(t.title,"task.title"),...t.description?{description:p(t.description,"task.description")}:{},status:a.length===0?"ready":"pending",...t.assignedAgentId?{assignedAgentId:p(t.assignedAgentId,"task.assignedAgentId",512)}:{},...a.length?{dependsOn:a}:{},createdAt:r,updatedAt:r};n.tasks.push(c),s.taskIds.push(c.id),s.updatedAt=r,n.progress.totalTaskCount=n.tasks.length,n.progress.outstanding=n.tasks.filter(l=>l.status!=="completed").map(l=>l.title),n.progress.updatedAt=r})}async updateTask(e,o,i,t,n){return this.mutateGoal(e,o,t,(r,s)=>{let a=r.tasks.find(l=>l.id===i);if(!a)throw new u("NOT_FOUND",`Task ${i} was not found`);a.status=n.status,n.progress!==void 0&&(a.progress=p(n.progress,"task.progress")),n.resultEventId!==void 0&&(a.resultEventId=p(n.resultEventId,"task.resultEventId",512)),n.assignedAgentId!==void 0&&(a.assignedAgentId=p(n.assignedAgentId,"task.assignedAgentId",512)),a.updatedAt=s,a.status==="completed"&&(a.completedAt=s);let c=r.milestones.find(l=>l.id===a.milestoneId);if(c){let l=r.tasks.filter(f=>f.milestoneId===c.id);l.length>0&&l.every(f=>f.status==="completed")?(c.status="completed",c.completedAt=s):l.some(f=>f.status==="running")?c.status="active":l.some(f=>f.status==="blocked")&&(c.status="blocked"),c.updatedAt=s}for(let l of r.tasks)l.status!=="pending"||!l.dependsOn?.length||l.dependsOn.every(f=>r.tasks.find(m=>m.id===f)?.status==="completed")&&(l.status="ready",l.updatedAt=s);this.recalculateProgress(r,s)})}async steerGoal(e,o,i,t){return this.mutateGoal(e,o,i,(n,r,s)=>{let a=this.idFactory("steer");n.steering.push({id:a,instruction:p(t,"instruction"),createdAt:r}),this.appendEvent(s,"goal.steered",{goalId:o,data:{steeringId:a}})},!1)}async consumeGoalSteering(e,o,i){let t=[];return{goal:await this.mutateGoal(e,o,i,(r,s)=>{t=r.steering.filter(a=>!a.consumedAt).map(({id:a,instruction:c,createdAt:l})=>({id:a,instruction:c,createdAt:l}));for(let a of r.steering)a.consumedAt||(a.consumedAt=s)}),instructions:t}}async completeGoal(e,o,i,t){if(t.status!=="passed")throw new u("VERIFICATION_REQUIRED","Goal completion requires passed verification");return this.mutate(e,n=>{let r=this.requireGoal(n,o);this.assertVersion(r.id,r.version,i);let s=r.successCriteria.filter(l=>l.required),a=s.filter(l=>{let f=t.criteria.find(m=>m.criterionId===l.id);return!f?.satisfied||f.evidence.length===0});if(a.length>0)throw new u("VERIFICATION_REQUIRED","Required success criteria lack passing evidence",{unmetCriteria:a.map(l=>l.id)});if(s.length===0&&t.evidence.length===0)throw new u("VERIFICATION_REQUIRED","Goal completion requires at least one durable evidence reference");let c=this.now();return r.status="completed",r.verification=w(t),r.verification.verifiedAt??=c,r.completedAt=c,r.updatedAt=c,r.version+=1,this.appendEvent(n,"goal.completed",{goalId:o,data:{evidence:r.verification.evidence}}),r},!0)}async cancelGoal(e,o,i,t){return this.mutate(e,n=>{let r=this.requireGoal(n,o);if(this.assertVersion(r.id,r.version,i),["completed","cancelled","failed"].includes(r.status))return r;r.status="cancelled",r.updatedAt=this.now(),r.version+=1,this.appendEvent(n,"goal.cancelled",{goalId:o,data:{reason:p(t,"reason")}});for(let s of n.loops.filter(a=>a.goalId===o&&["running","paused","waiting"].includes(a.status)))s.status="stopped",s.resumeRequested!==void 0&&(s.resumeRequested=!1),s.stopReason=`Goal cancelled: ${t}`,s.stoppedAt=this.now(),s.updatedAt=s.stoppedAt,s.version+=1;return r},!0)}async startLoop(e){return this.mutate(e.sessionId,o=>this.createLoopRecord(o,e))}createLoopRecord(e,o){if(o.kind==="goal-continuation"&&!o.goalId)throw new u("INVALID","Goal-continuation loops require a goalId");if(o.goalId){let s=this.requireGoal(e,o.goalId);if(["completed","cancelled","failed"].includes(s.status))throw new u("CONFLICT",`Cannot start a loop for terminal goal ${s.id}`)}if(o.kind==="scheduled"&&!o.schedule)throw new u("INVALID","Scheduled loops require schedule metadata");if(o.kind!=="scheduled"&&o.schedule)throw new u("INVALID","Only scheduled loops may carry schedule metadata");let i=Te(o.schedule),t=e.loops.find(s=>s.goalId===o.goalId&&s.kind===o.kind&&["running","paused","waiting"].includes(s.status));if(t)throw new u("CONFLICT",`Loop ${t.id} is already active`);let n=this.now(),r={schemaVersion:1,id:this.idFactory("loop"),version:1,sessionId:e.sessionId,...o.goalId?{goalId:o.goalId}:{},kind:o.kind,status:"running",...o.activity?{currentActivity:p(o.activity,"activity")}:{},iterations:[],...i?{schedule:i}:{},createdAt:n,updatedAt:n};return e.loops.push(r),this.appendEvent(e,"loop.started",{loopId:r.id,goalId:r.goalId,data:{kind:r.kind}}),r}async getLoop(e,o){let i=await this.getSessionState(e),t=o?i.loops.find(n=>n.id===o):[...i.loops].reverse().find(n=>["running","paused","waiting"].includes(n.status));return t?w(t):void 0}async beginLoopIteration(e,o,i,t,n){return this.mutateLoop(e,o,i,(r,s,a)=>{this.appendLoopIteration(a,r,s,t,n)},!1)}appendLoopIteration(e,o,i,t,n,r=!1){if(o.status!=="running")throw new u("CONFLICT",`Loop ${o.id} is ${o.status}`);if(o.goalId){let c=this.requireGoal(e,o.goalId);this.isCliGoal(c)&&this.initializeGoalTurnAccounting(e,c)}if(this.assertGoalIterationAdmission(e,o,i,r),o.iterations.some(c=>c.status==="running"))throw new u("CONFLICT",`Loop ${o.id} already has a running iteration`);let s=(o.iterations.at(-1)?.number??0)+1;o.currentActivity=p(t,"activity");let a={number:s,startedAt:i,status:"running",activity:o.currentActivity,...o.goalId&&e.goalTurnAccounting?.[o.goalId]?{goalAccountingVersion:1}:{},...n?{taskId:p(n,"taskId",512)}:{}};return o.iterations.push(a),o.resumeRequested!==void 0&&(o.resumeRequested=!1),this.appendEvent(e,"loop.iteration",{loopId:o.id,goalId:o.goalId,data:{number:s,phase:"started",activity:o.currentActivity}}),a}async admitGoalTurn(e){return this.admitGoalTurnWithOwner(e)}async admitQuotaGoalTurn(e,o,i,t){let n=$(i),r=await this.getGoal(e.sessionId,e.goalId);if(!r||r.sessionId!==e.sessionId||r.limits?.maxTokens===void 0)throw new u("BUDGET_UNAVAILABLE","The exact token-bounded goal is unavailable for quota admission");if(this.isCliGoal(r)&&r.metadata["cli.tokenQuotaVersion"]!==1)throw new u("BUDGET_UNAVAILABLE","Legacy CLI goal token spend is unknown; quota admission requires creation-time provenance");if(n.goal?.id!==r.id||n.goal.generation!==r.createdAt)throw new u("BUDGET_UNAVAILABLE","Quota scope does not identify this durable goal generation");let s=await o.policy(n);if(!s||B(s.scope)!==B(n)||s.limits.tokensLifetime===void 0||s.limits.tokensLifetime===null||s.limits.tokensLifetime>r.limits.maxTokens)throw new u("BUDGET_UNAVAILABLE","Goal quota policy is absent or wider than the goal's explicit token limit");let a=await o.remainingTokens(n);if(a===null)throw new u("BUDGET_UNAVAILABLE","Goal token accounting has no durable remaining allowance");if(a<1)throw new u("BUDGET_EXCEEDED","Goal token allowance is exhausted");return this.admitGoalTurnWithOwner(e,t,{goalId:r.id,createdAt:r.createdAt,maximum:r.limits.maxTokens})}async admitOwnedGoalTurn(e,o){if(!o||!Number.isSafeInteger(o.epoch)||o.epoch<1)throw new u("INVALID","An exact execution ownership epoch is required");return this.admitGoalTurnWithOwner(e,{...o})}async admitGoalTurnWithOwner(e,o,i){let t=p(e.requestId,"requestId",512),n=this.goalTurnHash(e.requestHash);return this.mutate(e.sessionId,r=>{if(o){let f=this.requireOwner(r,o.ownerId,o.leaseId);if(f.epoch!==o.epoch)throw new u("NOT_OWNER","Execution ownership epoch changed");if(this.ownerExpired(f,this.now()))throw new u("LEASE_EXPIRED","Execution ownership expired");if(r.handoffs.some(m=>["prepared","available"].includes(m.status)&&m.sourceLeaseEpoch===f.epoch)||r.handoffs.some(m=>m.status==="claimed"&&m.targetLeaseEpoch===f.epoch))throw new u("UNSAFE_HANDOFF","Execution handoff has not settled")}let s=this.requireGoal(r,e.goalId);if(i&&(s.id!==i.goalId||s.createdAt!==i.createdAt||s.limits?.maxTokens!==i.maximum))throw new u("BUDGET_UNAVAILABLE","Goal token limit changed after quota verification");for(let f of r.loops.filter(m=>m.goalId===s.id)){let m=f.iterations.find(v=>v.goalTurn?.requestId===t);if(m){if(m.goalTurn?.requestHash!==n)throw new u("CONFLICT","Goal turn identity was reused for different work");return{...this.goalTurnState(r,s,f,m),admitted:!1}}}if(this.assertVersion(s.id,s.version,e.expectedGoalVersion),s.status!=="active")throw new u("CONFLICT",`Goal ${s.id} is ${s.status}`);let a=[...r.loops].reverse().find(f=>f.goalId===s.id&&f.kind==="goal-continuation");if(e.expectedLoopId!==void 0){if(!a||a.id!==e.expectedLoopId)throw new u("CONFLICT","Goal continuation loop changed before admission");this.assertVersion(a.id,a.version,e.expectedLoopVersion??-1)}else if(e.expectedLoopVersion!==void 0)throw new u("INVALID","A goal turn loop version requires its exact loop ID");if(a&&a.status!=="running")throw new u("CONFLICT",`Goal loop ${a.id} is ${a.status}; resume or start it explicitly`);this.initializeGoalTurnAccounting(r,s),a??=this.createLoopRecord(r,{sessionId:r.sessionId,goalId:s.id,kind:"goal-continuation"});let c=this.now(),l=this.appendLoopIteration(r,a,c,"Interactive goal turn",void 0,i!==void 0);if(e.executionKind!==void 0&&e.executionKind!=="local-sdk"&&e.executionKind!=="external")throw new u("INVALID","Unknown goal execution lane");return l.goalTurn={requestId:t,requestHash:n,executor:e.executionKind==="local-sdk"?{kind:"local-sdk",processId:process.pid,host:O.hostname()}:{kind:"external"}},a.version+=1,a.updatedAt=c,{...this.goalTurnState(r,s,a,l),admitted:!0}},!1,r=>r.admitted)}async getGoalTurnState(e,o,i){let t=await this.getSessionState(e),n=o?t.goals.find(c=>c.id===o):[...t.goals].reverse().find(c=>["active","paused","waiting","blocked"].includes(c.status));if(!n)return;let r=t.loops.filter(c=>c.goalId===n.id),s=i?r.find(c=>c.iterations.some(l=>l.goalTurn?.requestId===i)):[...r].reverse().find(c=>c.kind==="goal-continuation"),a=i?s?.iterations.find(c=>c.goalTurn?.requestId===i):s?.iterations.at(-1);if(i&&!a)throw new u("NOT_FOUND","Goal turn was not found");return this.goalTurnState(t,n,s,a)}async finishGoalTurn(e){if(!["completed","failed","interrupted"].includes(e.status))throw new u("INVALID","Invalid goal turn outcome");let o=this.goalTurnHash(e.requestHash);return this.mutate(e.sessionId,i=>{let t=this.requireGoal(i,e.goalId),n=i.loops.find(s=>s.goalId===t.id&&s.iterations.some(a=>a.goalTurn?.requestId===e.requestId)),r=n?.iterations.find(s=>s.goalTurn?.requestId===e.requestId);if(!n||!r)throw new u("NOT_FOUND","Goal turn was not found");if(r.goalTurn?.requestHash!==o)throw new u("CONFLICT","Goal turn settlement identity does not match");return r.status==="running"&&(this.settleLoopIteration(i,n,r,this.now(),{status:t.status==="cancelled"||["stopped","failed"].includes(n.status)?"interrupted":e.status}),n.version+=1,n.updatedAt=this.now()),this.goalTurnState(i,t,n,r)},!0)}async recoverGoalTurn(e,o,i){return this.mutate(e,t=>{let n=this.requireGoal(t,o),r=t.loops.find(a=>a.goalId===o&&a.iterations.some(c=>c.goalTurn?.requestId===i)),s=r?.iterations.find(a=>a.goalTurn?.requestId===i);if(!r||!s)throw new u("NOT_FOUND","Goal turn was not found");if(s.status==="running"){if(!this.goalTurnOwnerExited(s))throw new u("NOT_OWNER","The original local goal executor has not been proved exited; external execution requires reconciliation");this.settleLoopIteration(t,r,s,this.now(),{status:"interrupted",error:"Original local SDK executor exited; inspect persisted results before retrying work"}),r.resumeRequested=n.status==="active"&&r.status==="running",r.version+=1,r.updatedAt=this.now()}return this.goalTurnState(t,n,r,s)},!0)}async finishLoopIteration(e,o,i,t){return this.mutateLoop(e,o,i,(n,r,s)=>{let a=[...n.iterations].reverse().find(c=>c.status==="running");if(!a)throw new u("CONFLICT",`Loop ${n.id} has no running iteration`);this.settleLoopIteration(s,n,a,r,t)},!1,!0)}settleLoopIteration(e,o,i,t,n){i.status=n.status,i.completedAt=t,n.verificationEventId&&(i.verificationEventId=p(n.verificationEventId,"verificationEventId",512)),n.error&&(i.error=p(n.error,"error")),o.status=["stopped","completed","failed"].includes(o.status)?o.status:e.admissionFence?"paused":n.nextStatus??(o.status==="paused"||o.status==="waiting"?o.status:"running"),this.appendEvent(e,"loop.iteration",{loopId:o.id,goalId:o.goalId,data:{number:i.number,phase:"finished",status:n.status}})}async setLoopStatus(e,o,i,t,n){return this.mutateLoop(e,o,i,(r,s,a)=>{let c=r.status;if(["stopped","completed","failed"].includes(c))throw new u("CONFLICT",`Loop ${r.id} is terminal (${c})`);let l=[...r.iterations].reverse().find(m=>m.status==="running");if(l&&t==="completed")throw new u("CONFLICT",`Loop ${r.id} cannot complete while iteration ${l.number} is running`);l&&(t==="stopped"||t==="failed")&&(l.status=t==="failed"?"failed":"interrupted",l.completedAt=s,l.error=p(n??t,"reason")),r.status=t,r.kind==="goal-continuation"&&(r.resumeRequested=t==="running"),["stopped","completed","failed"].includes(t)&&(r.stoppedAt=s,r.stopReason=p(n??t,"reason"));let f=t==="paused"?"loop.paused":t==="waiting"?"loop.waiting":t==="running"&&(c==="paused"||c==="waiting")?"loop.resumed":t==="completed"?"loop.completed":t==="failed"?"loop.failed":"loop.stopped";this.appendEvent(a,f,{loopId:o,goalId:r.goalId,data:{previous:c,status:t,...n?{reason:n}:{}}})},!1,t!=="running"&&t!=="waiting")}async acquireOwnership(e,o,i={}){return this.mutate(e,t=>{let n=this.now();if(t.owner&&!this.ownerExpired(t.owner,n)){if(t.owner.ownerId===o&&i.processId!==void 0&&t.owner.processId===i.processId&&(i.host===void 0||t.owner.host===i.host))return t.owner;throw new u("CONFLICT",`Session ${e} is owned by ${t.owner.ownerId}`,{owner:t.owner})}let r=t.owner&&this.ownerExpired(t.owner,n)?t.owner:void 0;if(r)for(let c of t.handoffs.filter(l=>l.status==="claimed"&&l.claimedBy===r.ownerId&&l.targetLeaseEpoch===r.epoch))c.status="failed",c.failureReason=`Claimed owner ${r.ownerId} lost its execution lease before completing the handoff.`,c.failedAt=n,c.updatedAt=n,c.version+=1,this.appendEvent(t,"handoff.failed",{handoffId:c.id,goalId:c.goalId,loopId:c.loopId,data:{reason:c.failureReason,expiredLeaseId:r.leaseId}});let s=t.ownershipEpoch+1;for(let c of t.handoffs.filter(l=>["prepared","available"].includes(l.status)&&l.sourceLeaseEpoch<s))c.status="failed",c.failureReason="Source ownership epoch was superseded before the handoff was claimed.",c.failedAt=n,c.updatedAt=n,c.version+=1,this.appendEvent(t,"handoff.failed",{handoffId:c.id,data:{epoch:s,reason:c.failureReason}});let a=this.newOwner(o,s,i,n);return t.owner=a,t.ownershipEpoch=s,this.appendEvent(t,"ownership.acquired",{ownerId:o,data:{epoch:s,leaseId:a.leaseId}}),a})}async renewOwnership(e,o,i,t=this.ownerLeaseMs){return this.mutate(e,n=>{let r=this.requireOwner(n,o,i);if(this.ownerExpired(r,this.now()))throw new u("LEASE_EXPIRED",`Ownership lease ${i} expired`);return r.heartbeatAt=this.now(),r.expiresAt=new Date(b(r.heartbeatAt)+t).toISOString(),this.appendEvent(n,"ownership.renewed",{ownerId:o,data:{epoch:r.epoch,leaseId:i}}),r})}async recoverExpiredOwnership(e,o,i,t,n=this.ownerLeaseMs){return this.mutate(e,r=>{let s=this.requireOwner(r,o,i);if(s.processId!==t||s.host!==O.hostname()||!V(t))throw new u("LEASE_EXPIRED",`Ownership lease ${i} expired and cannot be recovered by process ${t}`);let a=this.now(),c=Math.max(0,b(a)-b(s.expiresAt));return s.heartbeatAt=a,s.expiresAt=new Date(b(a)+n).toISOString(),this.appendEvent(r,c>0?"ownership.recovered":"ownership.renewed",{ownerId:o,data:{epoch:s.epoch,leaseId:i,...c>0?{expiredForMs:c}:{}}}),s})}async releaseOwnership(e,o,i){return this.mutate(e,t=>{let n=this.requireOwner(t,o,i);for(let r of t.handoffs.filter(s=>s.status==="claimed"&&s.claimedBy===o&&s.targetLeaseEpoch===n.epoch))r.status="failed",r.failureReason="Target released execution ownership before completing the handoff.",r.failedAt=this.now(),r.updatedAt=r.failedAt,r.version+=1,this.appendEvent(t,"handoff.failed",{handoffId:r.id,ownerId:o,data:{epoch:n.epoch,reason:r.failureReason}});return t.owner=void 0,this.appendEvent(t,"ownership.released",{ownerId:o,data:{epoch:n.epoch}}),n},!0)}async createHandoff(e){let o=!1,i=e.prepareRequestId===void 0?void 0:p(e.prepareRequestId,"prepareRequestId",512);return this.mutate(e.sessionId,t=>{let n=this.requireOwner(t,e.sourceOwnerId,e.sourceLeaseId);if(this.ownerExpired(n,this.now()))throw new u("LEASE_EXPIRED",`Ownership lease ${n.leaseId} expired`);if(i){let l=t.handoffs.find(f=>f.prepareRequestId===i);if(l){if(l.sourceOwnerId!==n.ownerId||l.sourceLeaseEpoch!==n.epoch||l.status!=="available"||l.targetOwnerId!==e.targetOwnerId||l.workspace!==e.workspace||l.goalId!==e.goalId||l.loopId!==e.loopId||l.contextDigest!==e.contextDigest||l.branch!==e.branch||l.currentMilestoneId!==e.currentMilestoneId||l.currentTaskId!==e.currentTaskId||JSON.stringify(l.agentIds)!==JSON.stringify([...new Set(e.agentIds??[])])||JSON.stringify(l.operations)!==JSON.stringify(e.operations??[]))throw new u("CONFLICT","Prepare identity was reused for different work or ownership");return o=!0,l}}let r=(e.operations??[]).filter(l=>l.status==="running"&&l.sideEffecting);if(r.length>0)throw new u("UNSAFE_HANDOFF","Running side-effecting operations must settle before execution handoff",{operationIds:r.map(l=>l.operationId)});if(e.goalId&&this.requireGoal(t,e.goalId),e.loopId&&!t.loops.some(l=>l.id===e.loopId))throw new u("NOT_FOUND",`Loop ${e.loopId} was not found`);let s=t.handoffs.find(l=>["prepared","available","claimed"].includes(l.status));if(s)throw new u("CONFLICT",`Handoff ${s.id} is already active`);let a=this.now(),c={schemaVersion:1,id:this.idFactory("handoff"),version:1,sessionId:t.sessionId,...e.goalId?{goalId:e.goalId}:{},...e.loopId?{loopId:e.loopId}:{},status:"available",sourceOwnerId:n.ownerId,...i?{prepareRequestId:i}:{},...e.targetOwnerId?{targetOwnerId:p(e.targetOwnerId,"targetOwnerId",512)}:{},sourceLeaseEpoch:n.epoch,...e.workspace?{workspace:p(e.workspace,"workspace",32768)}:{},...e.branch?{branch:p(e.branch,"branch",1024)}:{},...e.currentMilestoneId?{currentMilestoneId:e.currentMilestoneId}:{},...e.currentTaskId?{currentTaskId:e.currentTaskId}:{},agentIds:[...new Set(e.agentIds??[])],operations:w(e.operations??[]),...e.contextDigest?{contextDigest:p(e.contextDigest,"contextDigest",512)}:{},createdAt:a,updatedAt:a};return t.handoffs.push(c),this.appendEvent(t,"handoff.created",{handoffId:c.id,goalId:c.goalId,loopId:c.loopId,ownerId:n.ownerId,data:{targetOwnerId:c.targetOwnerId}}),c},!1,()=>!o)}async claimHandoff(e){let o,i=!1,t=e.claimRequestId===void 0?void 0:p(e.claimRequestId,"claimRequestId",512);return{handoff:await this.mutate(e.sessionId,r=>{let s=r.handoffs.find(l=>l.id===e.handoffId);if(!s)throw new u("NOT_FOUND",`Handoff ${e.handoffId} was not found`);if(s.status!=="available"){let l=r.owner;if(t&&s.claimRequestId===t&&["claimed","completed"].includes(s.status)&&s.claimedBy===e.targetOwnerId&&l?.ownerId===e.targetOwnerId&&l.epoch===s.targetLeaseEpoch&&l.host===e.host&&l.processId===e.processId&&!this.ownerExpired(l,this.now()))return o=l,i=!0,s;throw new u("CONFLICT",`Handoff ${s.id} is ${s.status}`,{claimedBy:s.claimedBy})}if(s.targetOwnerId&&s.targetOwnerId!==e.targetOwnerId)throw new u("CONFLICT",`Handoff ${s.id} is reserved for ${s.targetOwnerId}`);let a=r.owner;if(!a||a.ownerId!==s.sourceOwnerId||a.epoch!==s.sourceLeaseEpoch)throw new u("CONFLICT",`Handoff ${s.id} no longer matches the source ownership epoch`);let c=this.now();return o=this.newOwner(e.targetOwnerId,a.epoch+1,{processId:e.processId,host:e.host,leaseMs:e.leaseMs},c),r.owner=o,r.ownershipEpoch=o.epoch,s.status="claimed",s.claimedBy=e.targetOwnerId,t&&(s.claimRequestId=t),s.targetOwnerId=e.targetOwnerId,s.targetLeaseEpoch=o.epoch,s.claimedAt=c,s.updatedAt=c,s.version+=1,this.appendEvent(r,"handoff.claimed",{handoffId:s.id,goalId:s.goalId,loopId:s.loopId,ownerId:e.targetOwnerId,data:{sourceOwnerId:s.sourceOwnerId,epoch:o.epoch}}),s},!1,()=>!i),owner:w(o)}}async completeHandoff(e,o,i,t){let n=!1;return this.mutate(e,r=>{let s=this.requireOwner(r,i,t);if(this.ownerExpired(s,this.now()))throw new u("LEASE_EXPIRED",`Ownership lease ${t} expired`);let a=r.handoffs.find(c=>c.id===o);if(!a)throw new u("NOT_FOUND",`Handoff ${o} was not found`);if(a.claimedBy!==i||a.targetLeaseEpoch!==s.epoch||!["claimed","completed"].includes(a.status))throw new u("CONFLICT",`Handoff ${a.id} cannot be completed by ${i}`);return a.status==="completed"?(n=!0,a):(a.status="completed",a.completedAt=this.now(),a.updatedAt=a.completedAt,a.version+=1,this.appendEvent(r,"handoff.completed",{handoffId:o,goalId:a.goalId,loopId:a.loopId,ownerId:i,data:{epoch:r.owner?.epoch}}),a)},!1,()=>!n)}async failHandoff(e,o,i){return this.mutate(e,t=>{let n=t.handoffs.find(r=>r.id===o);if(!n)throw new u("NOT_FOUND",`Handoff ${o} was not found`);return["completed","cancelled","failed"].includes(n.status)||(n.status="failed",n.failureReason=p(i,"reason"),n.failedAt=this.now(),n.updatedAt=n.failedAt,n.version+=1,this.appendEvent(t,"handoff.failed",{handoffId:o,goalId:n.goalId,loopId:n.loopId,data:{reason:n.failureReason}})),n},!0)}async mutateGoal(e,o,i,t,n=!0){return this.mutate(e,r=>{let s=this.requireGoal(r,o);this.assertVersion(s.id,s.version,i);let a=this.now();return t(s,a,r),s.version+=1,s.updatedAt=a,n&&this.appendEvent(r,"goal.updated",{goalId:o,data:{status:s.status,version:s.version}}),s})}async mutateLoop(e,o,i,t,n=!0,r=!1){return this.mutate(e,s=>{let a=s.loops.find(l=>l.id===o);if(!a)throw new u("NOT_FOUND",`Loop ${o} was not found`);this.assertVersion(a.id,a.version,i);let c=this.now();return t(a,c,s),a.version+=1,a.updatedAt=c,n&&this.appendEvent(s,"loop.iteration",{loopId:o,goalId:a.goalId,data:{status:a.status,version:a.version}}),a},r)}assertGoalIterationAdmission(e,o,i,t=!1){if(!o.goalId)return;let n=this.requireGoal(e,o.goalId);if(n.status!=="active")throw new u("CONFLICT",`Goal ${n.id} is ${n.status}; no iteration was admitted`);let r=te(n.limits);if(r?.maxTokens!==void 0&&!t)throw new u("BUDGET_UNAVAILABLE","Goal token allowance is not bound to request-level admission; no iteration was admitted",{goalId:n.id,limit:"maxTokens"});if(r?.maxWallClockMs!==void 0){let s=Date.parse(n.createdAt),a=Date.parse(i);if(!Number.isFinite(s)||!Number.isFinite(a)||a<s)throw new u("BUDGET_UNAVAILABLE","Goal wall-clock allowance cannot be verified",{goalId:n.id,limit:"maxWallClockMs"});if(a-s>=r.maxWallClockMs)throw new u("BUDGET_EXCEEDED","Goal wall-clock limit reached; no iteration was admitted",{goalId:n.id,limit:"maxWallClockMs",maximum:r.maxWallClockMs})}if(r?.maxIterations!==void 0){let s=e.goalTurnAccounting!==void 0||e.schemaVersion===4?this.resolveGoalTurnAccounting(e,n):void 0;if(s?.coverage==="partial")throw new u("BUDGET_UNAVAILABLE","Legacy goal turn accounting is incomplete");let a=this.goalIterationCount(e,n)+(s?.baseIterations??0);if(!Number.isSafeInteger(a)||a<0)throw new u("BUDGET_UNAVAILABLE","Invalid goal iteration accounting");if(a>=r.maxIterations)throw new u("BUDGET_EXCEEDED","Goal iteration limit reached; no iteration was admitted",{goalId:n.id,limit:"maxIterations",admitted:a,maximum:r.maxIterations})}}isCliGoal(e){return"cli.accountedTurns"in e.metadata||"cli.createdByCliVersion"in e.metadata}goalIterationCount(e,o){let i=0;for(let t of e.loops.filter(n=>n.goalId===o.id)){if(!Array.isArray(t.iterations))throw new u("BUDGET_UNAVAILABLE","Goal iteration history is unavailable");let n=0;for(let r of t.iterations){if(!r||!Number.isSafeInteger(r.number)||r.number<=n)throw new u("BUDGET_UNAVAILABLE","Goal iteration history is invalid");n=r.number}if(i+=n,!Number.isSafeInteger(i))throw new u("BUDGET_UNAVAILABLE","Goal iteration count exceeds its supported range")}return i}resolveGoalTurnAccounting(e,o){let i=e.goalTurnAccounting;if(i!==void 0&&(!i||typeof i!="object"||Array.isArray(i)))throw new u("BUDGET_UNAVAILABLE","Persisted goal turn accounting is invalid");if(i&&Object.hasOwn(i,o.id)){let a=i[o.id];if(!a||a.schemaVersion!==1||!Number.isSafeInteger(a.baseIterations)||a.baseIterations<0||!["complete","partial"].includes(a.coverage))throw new u("BUDGET_UNAVAILABLE","Persisted goal turn accounting is invalid");return a}if(e.loops.some(a=>a.goalId===o.id&&a.iterations.some(c=>c.goalTurn||c.goalAccountingVersion)))throw new u("BUDGET_UNAVAILABLE","Recorded goal turns are missing their protected accounting");let t=this.goalIterationCount(e,o),n=o.metadata["cli.accountedTurns"],r=typeof n=="number"&&Number.isSafeInteger(n)&&n>=0,s=this.isCliGoal(o)&&(!r||n>0&&t>0);return{schemaVersion:1,baseIterations:r&&t===0?n:0,coverage:s?"partial":"complete"}}initializeGoalTurnAccounting(e,o){let i=this.resolveGoalTurnAccounting(e,o);if(i.coverage==="partial"&&o.limits?.maxIterations!==void 0)throw new u("BUDGET_UNAVAILABLE","Legacy goal turn accounting needs reconciliation before bounded execution");e.goalTurnAccounting??={},Object.defineProperty(e.goalTurnAccounting,o.id,{value:i,writable:!0,enumerable:!0,configurable:!0})}goalTurnHash(e){let o=p(e,"requestHash",64).toLowerCase();if(!/^[0-9a-f]{64}$/.test(o))throw new u("INVALID","Goal turn requestHash must be a SHA-256 digest");return o}goalTurnState(e,o,i,t){let n=this.resolveGoalTurnAccounting(e,o),r=this.goalIterationCount(e,o)+n.baseIterations;if(!Number.isSafeInteger(r))throw new u("BUDGET_UNAVAILABLE","Goal turn count exceeds its supported range");return w({goal:o,admittedTurns:r,accountingCoverage:n.coverage,...i?{loopId:i.id,loopVersion:i.version,loopStatus:i.status,resumeRequested:i.resumeRequested===!0}:{},...t?{iterationNumber:t.number,iterationStatus:t.status,...t.goalTurn?{requestId:t.goalTurn.requestId,requestHash:t.goalTurn.requestHash}:{},canRecover:t.status==="running"&&this.goalTurnOwnerExited(t)}:{}})}goalTurnOwnerExited(e){let o=e.goalTurn?.executor;if(o?.kind!=="local-sdk"||o.host!==O.hostname()||!Number.isSafeInteger(o.processId)||o.processId<=0)return!1;try{return process.kill(o.processId,0),!1}catch(i){return i.code==="ESRCH"}}recalculateProgress(e,o){let i=e.tasks.filter(t=>t.status==="completed").length;e.progress.completedTaskCount=i,e.progress.totalTaskCount=e.tasks.length,e.progress.percent=e.tasks.length?Math.round(i/e.tasks.length*100):void 0,e.progress.outstanding=e.tasks.filter(t=>!["completed","cancelled"].includes(t.status)).map(t=>t.title),e.progress.updatedAt=o}requireGoal(e,o){let i=e.goals.find(t=>t.id===o);if(!i)throw new u("NOT_FOUND",`Goal ${o} was not found`);return i}requireOwner(e,o,i){let t=e.owner;if(!t||t.ownerId!==o||t.leaseId!==i)throw new u("NOT_OWNER",`${o} does not own session ${e.sessionId}`,{owner:t});return t}assertVersion(e,o,i){if(!Number.isInteger(i)||i<1||o!==i)throw new u("CONFLICT",`Expected ${e} version ${i}, found ${o}`,{expected:i,actual:o})}newOwner(e,o,i,t){let n=i.leaseMs??this.ownerLeaseMs;if(!Number.isSafeInteger(n)||n<1)throw new u("INVALID","leaseMs must be a positive safe integer");return{ownerId:p(e,"ownerId",512),leaseId:this.idFactory("owner"),epoch:o,acquiredAt:t,heartbeatAt:t,expiresAt:new Date(b(t)+n).toISOString(),...i.processId!==void 0?{processId:i.processId}:{},...i.host?{host:p(i.host,"host",512)}:{}}}ownerExpired(e,o){return b(e.expiresAt)<=b(o)?!0:e.processId!==void 0&&e.host===O.hostname()&&!V(e.processId)}appendEvent(e,o,i){let t={schemaVersion:1,id:this.idFactory("event"),sequence:(e.events.at(-1)?.sequence??0)+1,type:o,sessionId:e.sessionId,...i.goalId?{goalId:i.goalId}:{},...i.loopId?{loopId:i.loopId}:{},...i.handoffId?{handoffId:i.handoffId}:{},...i.ownerId?{ownerId:i.ownerId}:{},timestamp:this.now(),data:w(i.data)};e.events.push(t),e.events.length>this.maximumEventsPerSession&&e.events.splice(0,e.events.length-this.maximumEventsPerSession)}async mutate(e,o,i=!1,t=()=>!0){let n=p(e,"sessionId",1024);return this.withSessionLock(n,async()=>{let r=await this.readState(n);if(r.admissionFence&&!i)throw new u("CONFLICT","Session execution is blocked by a persisted lifecycle fence");let s=r.schemaVersion;this.promoteGoalBudgetEnvelope(r),r.schemaVersion!==s&&await this.writeState(r);let a=o(r);return t(a)&&(r.version+=1,r.updatedAt=this.now(),await this.writeState(r)),w(a)})}statePath(e){return y.join(this.rootDirectory,"sessions",`${oe(e)}.json`)}lockPath(e){return`${this.statePath(e)}.lock`}async readState(e){let o=this.statePath(e);try{let i=await h.readFile(o,"utf8"),t=JSON.parse(i);if(!ee.includes(t.schemaVersion)||t.sessionId!==e)throw new u("INVALID",`Coordination state at ${o} does not match session ${e}`);if(t.admissionFence!==void 0){let n=t.admissionFence;if(!n||n.schemaVersion!==1||typeof n.authorityId!="string"||!n.authorityId.trim()||typeof n.operationId!="string"||!n.operationId.trim()||!["archive","delete"].includes(n.action)||!Number.isFinite(Date.parse(n.createdAt)))throw new u("INVALID","Persisted lifecycle fence is corrupt; execution remains unavailable")}return(!Number.isSafeInteger(t.ownershipEpoch)||t.ownershipEpoch<0)&&(t.ownershipEpoch=Math.max(t.owner?.epoch??0,...t.handoffs.map(n=>n.targetLeaseEpoch??n.sourceLeaseEpoch??0))),t}catch(i){if(i.code!=="ENOENT")throw i;let t=this.now();return{schemaVersion:1,sessionId:e,version:0,ownershipEpoch:0,goals:[],loops:[],handoffs:[],events:[],createdAt:t,updatedAt:t}}}promoteGoalBudgetEnvelope(e){(e.goalTurnAccounting!==void 0||e.loops.some(o=>o.resumeRequested!==void 0||o.iterations.some(i=>i.goalTurn!==void 0)))&&(e.schemaVersion=4),e.schemaVersion<3&&e.goals.some(o=>o.limits!==void 0&&(!o.limits||typeof o.limits!="object"||Array.isArray(o.limits)||Object.keys(o.limits).length>0))&&(e.schemaVersion=3)}async writeState(e){this.promoteGoalBudgetEnvelope(e);let o=this.statePath(e.sessionId),i=y.dirname(o);await h.mkdir(i,{recursive:!0});let t=`${o}.${process.pid}.${(0,T.randomUUID)()}.tmp`,n=await h.open(t,"wx");try{await n.writeFile(`${JSON.stringify(e,null,2)}
2
- `,"utf8"),await n.sync()}finally{await n.close()}try{await this.renameReplacing(t,o);try{let r=await h.open(i,"r");try{await r.sync()}finally{await r.close()}}catch{}}finally{await h.unlink(t).catch(()=>{})}}async renameReplacing(e,o){for(let i=0;;i+=1)try{await h.rename(e,o);return}catch(t){let n=t.code,r=Z[i];if(process.platform!=="win32"||!n||!P.has(n)||r===void 0)throw t;await new Promise(s=>setTimeout(s,r))}}async withSessionLock(e,o){let i=this.lockPath(e),t=y.join(i,"owner.json"),n=(0,T.randomUUID)(),r=`${i}.candidate.${n}`,s=Date.now();await h.mkdir(y.dirname(i),{recursive:!0});let a={schemaVersion:1,token:n,pid:process.pid,host:O.hostname(),acquiredAt:this.now()};await h.mkdir(r),await h.writeFile(y.join(r,"owner.json"),JSON.stringify(a),{encoding:"utf8",flag:"wx"});for(let c=0;;c+=1)try{await h.rename(r,i);break}catch(l){let f=l.code;if(!(!!f&&new Set(["EEXIST","ENOTEMPTY","ENOTDIR","EBUSY"]).has(f)||process.platform==="win32"&&!!f&&P.has(f)))throw await h.rm(r,{recursive:!0,force:!0}).catch(()=>{}),l;let R=await this.staleLockOwner(i,t);if(R){await this.quarantineLock(i,R.token,"stale");continue}if(Date.now()-s>=this.lockTimeoutMs)throw await h.rm(r,{recursive:!0,force:!0}).catch(()=>{}),new u("CONFLICT",`Timed out waiting for coordination lock for session ${e}`);await new Promise(N=>setTimeout(N,Math.min(100,5+c*5)+Math.floor(Math.random()*10)))}try{return await o()}finally{await this.quarantineLock(i,n,"released"),await h.rm(r,{recursive:!0,force:!0}).catch(()=>{})}}async staleLockOwner(e,o){try{let[i,t]=await Promise.all([h.readFile(o,"utf8").catch(()=>""),h.stat(e)]),n=i?JSON.parse(i):void 0;return!n||n.host!==O.hostname()||V(n.pid)?void 0:Date.now()-t.mtimeMs>this.lockStaleMs?n:void 0}catch{return}}async quarantineLock(e,o,i){let t=y.join(e,"owner.json"),n=i==="stale"?`${e}.stale.${oe(o)}`:`${e}.${i}.${o}.${(0,T.randomUUID)()}`;for(let r=0;;r+=1){let s;try{s=JSON.parse(await h.readFile(t,"utf8"))}catch(a){if(a.code==="ENOENT")return;throw a}if(s.token!==o)return;try{await h.rename(e,n);break}catch(a){let c=a.code;if(i==="stale")try{if(JSON.parse(await h.readFile(y.join(n,"owner.json"),"utf8")).token===o)return}catch{}if(c==="ENOENT"||c==="EEXIST")return;let l=Z[r];if(process.platform!=="win32"||!c||!P.has(c)||l===void 0)throw a;await new Promise(f=>setTimeout(f,l))}}if(i!=="stale")for(let r=0;;r+=1)try{await h.rm(n,{recursive:!0});return}catch(s){let a=s.code;if(a==="ENOENT")return;let c=Se[r];if(process.platform!=="win32"||!a||!P.has(a)||c===void 0)throw s;await new Promise(l=>setTimeout(l,c))}}};function L(d,e){if(!d||typeof d!="object"||Array.isArray(d))throw new Error(`${e} must be an object`);return d}function g(d,e){if(typeof d!="string"||!d.trim())throw new Error(`${e} must be a non-empty string`);return d}function x(d,e){if(typeof d!="number"||!Number.isInteger(d))throw new Error(`${e} must be an integer`);return d}async function Xe(d,e){let{action:o,sessionId:i}=e,t=e.payload??{};if(t.sessionId!==void 0&&t.sessionId!==i)throw new u("INVALID","Payload sessionId must match the routed sessionId");let n;switch(o){case"state.get":n=await d.getSessionState(i);break;case"goal.create":n=await d.createGoal({...t,sessionId:i});break;case"goal.update":n=await d.updateGoal(i,g(t.goalId,"goalId"),x(t.expectedVersion,"expectedVersion"),L(t.update,"update"));break;case"goal.complete":n=await d.completeGoal(i,g(t.goalId,"goalId"),x(t.expectedVersion,"expectedVersion"),L(t.verification,"verification"));break;case"goal.cancel":n=await d.cancelGoal(i,g(t.goalId,"goalId"),x(t.expectedVersion,"expectedVersion"),g(t.reason,"reason"));break;case"goal.steer":n=await d.steerGoal(i,g(t.goalId,"goalId"),x(t.expectedVersion,"expectedVersion"),g(t.instruction,"instruction"));break;case"loop.start":n=await d.startLoop({sessionId:i,kind:g(t.kind,"kind"),...typeof t.goalId=="string"?{goalId:t.goalId}:{},...typeof t.activity=="string"?{activity:t.activity}:{},...t.schedule?{schedule:L(t.schedule,"schedule")}:{}});break;case"loop.get":n=await d.getLoop(i,typeof t.loopId=="string"?t.loopId:void 0);break;case"loop.begin":n=await d.beginLoopIteration(i,g(t.loopId,"loopId"),x(t.expectedVersion,"expectedVersion"),g(t.activity,"activity"),typeof t.taskId=="string"?t.taskId:void 0);break;case"loop.finish":n=await d.finishLoopIteration(i,g(t.loopId,"loopId"),x(t.expectedVersion,"expectedVersion"),L(t.result,"result"));break;case"loop.set_status":n=await d.setLoopStatus(i,g(t.loopId,"loopId"),x(t.expectedVersion,"expectedVersion"),g(t.status,"status"),typeof t.reason=="string"?t.reason:void 0);break;case"ownership.acquire":n=await d.acquireOwnership(i,g(t.ownerId,"ownerId"),L(t.options??{},"options"));break;case"ownership.renew":n=await d.renewOwnership(i,g(t.ownerId,"ownerId"),g(t.leaseId,"leaseId"),typeof t.leaseMs=="number"?t.leaseMs:void 0);break;case"ownership.release":n=await d.releaseOwnership(i,g(t.ownerId,"ownerId"),g(t.leaseId,"leaseId"));break;case"handoff.create":n=await d.createHandoff({...t,sessionId:i});break;case"handoff.claim":n=await d.claimHandoff({sessionId:i,handoffId:g(t.handoffId,"handoffId"),targetOwnerId:g(t.targetOwnerId,"targetOwnerId"),...typeof t.processId=="number"?{processId:t.processId}:{},...typeof t.host=="string"?{host:t.host}:{}});break;case"handoff.complete":n=await d.completeHandoff(i,g(t.handoffId,"handoffId"),g(t.ownerId,"ownerId"),g(t.leaseId,"leaseId"));break;case"handoff.fail":n=await d.failHandoff(i,g(t.handoffId,"handoffId"),g(t.reason,"reason"));break;default:throw new u("INVALID","Unsupported coordination action")}let r=await d.getSessionState(i),s=o==="state.get"||o==="loop.get"?void 0:r.events.at(-1);return{action:o,sessionId:i,result:n,state:r,...s?{event:s}:{}}}var ne=require("node:crypto"),re=require("node:os");var j=class{sessionId;ownerId;store;processId;host;leaseMs;heartbeatMs;claimHandoffId;claimRequestId;onOwnershipLost;prepareDestination;destinationTimeoutMs;initializationAbort=new AbortController;timer;heartbeatInFlight=!1;owner;ready=!1;starting;stopping;stopped=!1;lostError;preparedHandoffId;preparingHandoff=!1;handoffOutcomeUncertain=!1;constructor(e){if(this.store=e.store??new X,this.sessionId=e.sessionId,this.processId=e.processId??process.pid,this.host=e.host??(0,re.hostname)(),this.ownerId=e.ownerId??`runtime:${this.host}:${this.processId}:${(0,ne.randomUUID)().slice(0,8)}`,this.leaseMs=e.leaseMs??3e4,this.heartbeatMs=e.heartbeatMs??Math.max(250,Math.floor(this.leaseMs/3)),this.heartbeatMs>=this.leaseMs)throw new Error("heartbeatMs must be shorter than leaseMs");if(this.claimHandoffId=e.claimHandoffId,this.claimRequestId=e.claimRequestId,this.onOwnershipLost=e.onOwnershipLost,this.prepareDestination=e.prepareDestination,this.destinationTimeoutMs=e.destinationTimeoutMs??Math.min(1e4,Math.floor(this.leaseMs/2)),!Number.isSafeInteger(this.destinationTimeoutMs)||this.destinationTimeoutMs<1||this.destinationTimeoutMs>=this.leaseMs)throw new Error("destinationTimeoutMs must be a positive integer shorter than leaseMs")}get currentOwner(){return this.active&&this.owner?structuredClone(this.owner):void 0}get active(){return this.ready&&!!this.owner&&!this.stopped&&this.lostError===void 0&&!this.preparingHandoff&&!this.preparedHandoffId}async start(){if(this.stopped)throw new Error("Execution lease session has already stopped");if(this.lostError!==void 0)throw this.lostError;return this.ready&&this.owner?(this.assertExecutionAllowed(),structuredClone(this.owner)):(this.starting??=this.initialize(),structuredClone(await this.starting))}async initialize(){try{if(this.claimHandoffId){let e=await this.store.claimHandoff({sessionId:this.sessionId,handoffId:this.claimHandoffId,targetOwnerId:this.ownerId,processId:this.processId,host:this.host,leaseMs:this.leaseMs,...this.claimRequestId?{claimRequestId:this.claimRequestId}:{}});if(this.owner=e.owner,this.stopped)throw new Error("Execution lease session has already stopped");if(this.prepareDestination&&await this.prepareClaimedDestination(e.handoff),this.stopped)throw new Error("Execution lease session has already stopped");await this.store.completeHandoff(this.sessionId,this.claimHandoffId,this.ownerId,this.owner.leaseId)}else this.owner=await this.store.acquireOwnership(this.sessionId,this.ownerId,{processId:this.processId,host:this.host,leaseMs:this.leaseMs});if(this.stopped)throw new Error("Execution lease session has already stopped");if(this.owner=await this.store.renewOwnership(this.sessionId,this.ownerId,this.owner.leaseId,this.leaseMs),this.stopped)throw new Error("Execution lease session has already stopped");return this.ready=!0,this.timer=setInterval(()=>{this.heartbeat()},this.heartbeatMs),this.timer.unref?.(),structuredClone(this.owner)}catch(e){throw this.ready=!1,this.markLost(e instanceof Error?e:new Error("Execution lease initialization failed",{cause:e})),this.lostError}}async prepareClaimedDestination(e){let o=this.initializationAbort.signal,i,t;try{let n=new Promise((r,s)=>{t=()=>s(o.reason??new Error("Destination preparation cancelled")),o.addEventListener("abort",t,{once:!0}),i=setTimeout(()=>this.initializationAbort.abort(new Error("Destination preparation timed out")),this.destinationTimeoutMs),o.aborted&&t()});await Promise.race([n,Promise.resolve().then(()=>(o.throwIfAborted(),this.prepareDestination({handoff:structuredClone(e),signal:o})))]),o.throwIfAborted()}finally{i&&clearTimeout(i),t&&o.removeEventListener("abort",t)}}async assertOwned(){this.assertExecutionAllowed();let e=await this.renewHeldLease();return this.assertExecutionAllowed(),e}assertExecutionAllowed(){if(this.stopped)throw new Error("Execution surface is detached");if(this.lostError)throw this.lostError;if(this.preparingHandoff)throw new Error("Execution surface is preparing a handoff and is detached from mutation");if(this.preparedHandoffId)throw new Error(`Execution surface prepared handoff ${this.preparedHandoffId} and is detached from mutation`);if(!this.ready||!this.owner)throw new Error("Execution ownership was not started")}async renewHeldLease(){if(!this.owner)throw new Error("Execution ownership was not started");try{let e=await this.renewOrRecover(this.owner.leaseId);if(this.stopped)throw new Error("Execution surface is detached");return this.owner=e,structuredClone(this.owner)}catch(e){throw this.markLost(e),e}}async renewOrRecover(e){try{return await this.store.renewOwnership(this.sessionId,this.ownerId,e,this.leaseMs)}catch(o){if(!(o instanceof Error&&"code"in o&&o.code==="LEASE_EXPIRED")||!this.store.recoverExpiredOwnership||this.preparingHandoff||this.preparedHandoffId||this.stopped)throw o;return this.store.recoverExpiredOwnership(this.sessionId,this.ownerId,e,this.processId,this.leaseMs)}}async prepareHandoff(e={}){if(this.preparedHandoffId)throw new Error(`Handoff ${this.preparedHandoffId} is already prepared`);this.assertExecutionAllowed(),this.preparingHandoff=!0;try{let o=await this.renewHeldLease();this.handoffOutcomeUncertain=!0;let i=await this.store.createHandoff({...e,sessionId:this.sessionId,sourceOwnerId:o.ownerId,sourceLeaseId:o.leaseId});return this.preparedHandoffId=i.id,this.handoffOutcomeUncertain=!1,i}catch(o){throw this.markLost(o instanceof Error?o:new Error("Handoff preparation failed",{cause:o})),o}finally{this.preparingHandoff=!1}}async stop(e={}){return this.stopping?this.stopping:(this.stopped=!0,this.ready=!1,this.initializationAbort.abort(new Error("Execution lease session has already stopped")),this.timer&&clearInterval(this.timer),this.timer=void 0,this.stopping=this.finishStop(e),this.stopping)}async finishStop(e){await this.starting?.catch(()=>{});let o=this.owner;if(this.owner=void 0,!(e.release===!1||this.preparedHandoffId||this.handoffOutcomeUncertain||!o))try{await this.store.releaseOwnership(this.sessionId,o.ownerId,o.leaseId)}catch{}}async heartbeat(){if(!(!this.ready||!this.owner||this.stopped||this.lostError!==void 0||this.heartbeatInFlight)){this.heartbeatInFlight=!0;try{await this.renewHeldLease()}catch(e){this.markLost(e)}finally{this.heartbeatInFlight=!1}}}markLost(e){this.lostError===void 0&&(this.lostError=e,this.timer&&clearInterval(this.timer),this.timer=void 0,this.onOwnershipLost?.(e))}};var ie=require("node:crypto"),M=require("node:perf_hooks");async function Le(d,e){let o=e.waitMs??0;if(!Number.isSafeInteger(o)||o<0||o>6e4)throw new u("INVALID","waitMs must be an integer from 0 through 60000");if(e.sinceRevision!==void 0&&!/^[a-f0-9]{64}$/.test(e.sinceRevision))throw new u("INVALID","Invalid handoff revision");if(typeof e.handoffId!="string"||!e.handoffId.trim()||e.handoffId.length>1024)throw new u("INVALID","Invalid handoff identifier");let i=M.performance.now()+o;for(;;){e.signal?.throwIfAborted();let t=await d.getSessionState(e.sessionId);e.signal?.throwIfAborted();let n=t.handoffs.find(a=>a.id===e.handoffId);if(!n)throw new u("NOT_FOUND","Handoff not found in the authorized session");let r=(0,ie.createHash)("sha256").update(JSON.stringify([t.sessionId,n.id,n.version,n.status,t.ownershipEpoch,t.owner?.ownerId??null,t.owner?.epoch??null])).digest("hex"),s=e.sinceRevision===void 0||r!==e.sinceRevision;if(s||M.performance.now()>=i)return{sessionId:t.sessionId,handoffId:n.id,revision:r,changed:s,status:n.status,handoffVersion:n.version,ownershipEpoch:t.ownershipEpoch,sourceOwnerId:n.sourceOwnerId,...n.targetOwnerId?{targetOwnerId:n.targetOwnerId}:{}};await new Promise((a,c)=>{let l=e.signal,m=setTimeout(()=>{l?.removeEventListener("abort",v),a()},Math.min(100,Math.max(1,i-M.performance.now()))),v=()=>{clearTimeout(m),l?.removeEventListener("abort",v),c(l?.reason??new Error("Handoff wait cancelled"))};l?.addEventListener("abort",v,{once:!0}),l?.aborted&&v()})}}var ae=require("node:crypto"),Q=require("node:fs"),E=require("node:fs/promises"),I=require("node:path");var se=require("node:crypto");function H(d){return{algorithm:"sha256",value:(0,se.createHash)("sha256").update(d).digest("hex")}}var de=1e4,ce=8*1024*1024,le=64*1024*1024;function ue(d){if(typeof d!="string"||!d||d.length>2048||(0,I.isAbsolute)(d)||/[\\:*?"<>|]/.test(d)||[...d].some(o=>o.charCodeAt(0)<32))throw new Error("Invalid portable snapshot path");let e=d.split("/");if(e.some(o=>!o||o==="."||o===".."||/[. ]$/.test(o)||/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(o)))throw new Error("Ambiguous portable snapshot path");if(e.some(o=>/^(?:\.git|\.ssh|\.aws|\.npmrc|\.netrc|\.xeno-handoff-ready|credentials(?:\.json)?|id_rsa|id_ed25519)$/i.test(o)||/^\.env(?:\.|$)/i.test(o)))throw new Error("Credential or repository-control path cannot be transferred");return d}function fe(d){return H(JSON.stringify([d.schemaVersion,d.sessionId,d.totalBytes,d.files.map(e=>[e.path,e.size,e.sha256,e.executable])])).value}function pe(d,e){if(d.schemaVersion!==1||d.sessionId!==e||!Array.isArray(d.files)||d.files.length>de||!Number.isSafeInteger(d.totalBytes)||d.totalBytes<0||d.totalBytes>le)throw new Error("Invalid handoff snapshot manifest");let o=new Set,i=0;for(let t of d.files){if(ue(t.path),!Number.isSafeInteger(t.size)||t.size<0||t.size>ce||!/^[a-f0-9]{64}$/.test(t.sha256)||typeof t.executable!="boolean")throw new Error("Invalid handoff snapshot file");let n=t.path.toLowerCase();if(o.has(n))throw new Error("Snapshot paths collide on Windows");o.add(n),i+=t.size}for(let t of o){let n=t.split("/");for(let r=1;r<n.length;r++)if(o.has(n.slice(0,r).join("/")))throw new Error("Snapshot file conflicts with a directory")}if(i!==d.totalBytes||fe(d)!==d.digest)throw new Error("Handoff snapshot manifest integrity mismatch")}async function z(d,e){let o=d;for(let n of e.split("/"))if(o=(0,I.join)(o,n),(await(0,E.lstat)(o)).isSymbolicLink())throw new Error("Snapshot symlinks are not supported");let i=await(0,E.realpath)(o),t=(0,I.relative)(d,i);if(t===".."||t.startsWith(`..${I.sep}`)||(0,I.isAbsolute)(t))throw new Error("Snapshot path escaped its root");return o}async function Ne(d){if(!d.sessionId||d.sessionId.length>1024||d.paths.length>de)throw new Error("Invalid snapshot scope");let e=await(0,E.realpath)(d.root),o=[],i=new Map,t=0;for(let r of[...d.paths].sort()){if(d.signal?.throwIfAborted(),ue(r),!await d.authorizeFile(r))throw new Error("Snapshot file transfer is not authorized");let s=await z(e,r),a=await(0,E.lstat)(s),c=await(0,E.open)(s,Q.constants.O_RDONLY|(Q.constants.O_NOFOLLOW??0));try{let l=await c.stat();if(await z(e,r),a.ino!==l.ino||a.dev!==l.dev||a.ctimeMs!==l.ctimeMs)throw new Error("Snapshot source was replaced before reading");if(!l.isFile()||l.size>ce||t+l.size>le)throw new Error("Snapshot file or total byte limit exceeded");let f=Buffer.alloc(l.size),m=0;for(;m<f.length;){d.signal?.throwIfAborted();let{bytesRead:J}=await c.read(f,m,f.length-m,m);if(!J)throw new Error("Snapshot source changed while reading");m+=J}let v=await c.stat(),R=await(0,E.lstat)(s);if(await z(e,r),l.size!==v.size||l.mtimeMs!==v.mtimeMs||l.ctimeMs!==v.ctimeMs||R.isSymbolicLink()||R.ino!==l.ino||R.dev!==l.dev)throw new Error("Snapshot source changed while reading");let N=H(f).value;o.push({path:r,size:f.length,sha256:N,executable:(l.mode&73)!==0}),i.set(N,f),t+=f.length}finally{await c.close()}}let n={schemaVersion:1,sessionId:d.sessionId,files:o,totalBytes:t,digest:""};return n.digest=fe(n),pe(n,d.sessionId),{manifest:n,blobs:i}}async function Ce(d){let e=structuredClone(d.manifest);if(pe(e,d.sessionId),!await d.authorizeManifest(structuredClone(e)))throw new Error("Snapshot restoration is not authorized");d.signal?.throwIfAborted();let o=(0,I.resolve)(d.destination);if(await(0,E.realpath)((0,I.dirname)(o))!==(0,I.dirname)(o))throw new Error("Snapshot destination parent must be canonical");try{throw await(0,E.lstat)(o),new Error("Snapshot destination already exists")}catch(r){if(r.code!=="ENOENT")throw r}let t=`${o}.staging-${(0,ae.randomUUID)()}`;await(0,E.mkdir)(t,{mode:448});for(let r of e.files){d.signal?.throwIfAborted();let s=await d.readBlob(r.sha256,r.size);if(s.byteLength!==r.size||H(s).value!==r.sha256)throw new Error("Snapshot blob integrity mismatch; staging retained");let a=(0,I.join)(t,...r.path.split("/"));await(0,E.mkdir)((0,I.dirname)(a),{recursive:!0,mode:448});let c=await(0,E.open)(a,"wx",r.executable?448:384);try{await c.writeFile(s),await c.sync()}finally{await c.close()}}d.signal?.throwIfAborted();let n=await(0,E.open)((0,I.join)(t,".xeno-handoff-ready"),"wx",384);try{await n.writeFile(JSON.stringify({digest:e.digest,sessionId:e.sessionId})),await n.sync()}finally{await n.close()}return{directory:t,digest:e.digest,files:e.files.length,bytes:e.totalBytes}}0&&(module.exports={DurableXenoCoordinationStore,XENO_COORDINATION_BUDGET_SESSION_SCHEMA_VERSION,XENO_COORDINATION_MANAGED_SESSION_SCHEMA_VERSION,XENO_COORDINATION_SCHEMA_VERSION,XENO_COORDINATION_TURN_SESSION_SCHEMA_VERSION,XenoCoordinationError,XenoExecutionLeaseSession,captureXenoHandoffSnapshot,executeXenoCoordinationAction,restoreXenoHandoffSnapshot,waitForXenoHandoffStatus});
1
+ "use strict";var ge=Object.create;var C=Object.defineProperty;var we=Object.getOwnPropertyDescriptor;var Ie=Object.getOwnPropertyNames;var Ee=Object.getPrototypeOf,ye=Object.prototype.hasOwnProperty;var be=(d,e)=>{for(var n in e)C(d,n,{get:e[n],enumerable:!0})},W=(d,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of Ie(e))!ye.call(d,t)&&t!==n&&C(d,t,{get:()=>e[t],enumerable:!(i=we(e,t))||i.enumerable});return d};var F=(d,e,n)=>(n=d!=null?ge(Ee(d)):{},W(e||!d||!d.__esModule?C(n,"default",{value:d,enumerable:!0}):n,d)),ve=d=>W(C({},"__esModule",{value:!0}),d);var Ge={};be(Ge,{DurableXenoCoordinationStore:()=>X,XENO_CONTEXT_DIGEST_PATTERN:()=>me,XENO_COORDINATION_BUDGET_SESSION_SCHEMA_VERSION:()=>k,XENO_COORDINATION_MANAGED_SESSION_SCHEMA_VERSION:()=>q,XENO_COORDINATION_SCHEMA_VERSION:()=>A,XENO_COORDINATION_TURN_SESSION_SCHEMA_VERSION:()=>_,XenoCoordinationError:()=>l,XenoExecutionLeaseSession:()=>j,captureXenoHandoffSnapshot:()=>ke,computeXenoContextDigest:()=>De,executeXenoCoordinationAction:()=>Ne,isXenoContextDigest:()=>Pe,restoreXenoHandoffSnapshot:()=>_e,waitForXenoHandoffStatus:()=>Ce});module.exports=ve(Ge);var A=1,q=2,k=3,_=4,l=class extends Error{constructor(n,i,t={}){super(i);this.code=n;this.details=t;this.name="XenoCoordinationError"}code;details};var T=require("node:crypto"),h=F(require("node:fs/promises"),1),O=F(require("node:os"),1),y=F(require("node:path"),1);var S=require("node:os");var U=require("node:path"),He=(0,S.platform)();var Fe=(0,S.release)(),qe=(0,S.homedir)();function K(){let d=process.env.XENO_AGENT_HOME?.trim();return d?(0,U.resolve)(d):(0,U.resolve)((0,S.homedir)(),".xeno-agent")}var P=class extends Error{constructor(n,i){super(i);this.code=n;this.name="QuotaError"}code;retryable=!1};function Y(d){if(typeof d!="string"||!d.trim()||d.length>512)throw new P("INVALID","Invalid quota identity.");return d}function $(d){let e=n=>({id:Y(n?.id),generation:Y(n?.generation)});if(!d||d.agent&&!d.team)throw new P("INVALID","A child quota scope requires its complete ancestry.");return{workspace:e(d.workspace),...d.team?{team:e(d.team)}:{},...d.agent?{agent:e(d.agent)}:{},...d.goal!==void 0?{goal:e(d.goal)}:{}}}function B(d){return JSON.stringify($(d))}var Ae=3e4,Oe=3e4,Se=6e4,Te=2e4,D=new Set(["EACCES","EBUSY","EPERM"]),Z=[5,10,20,40,80,160,320],xe=[5,10,20,40,80,160,320],ee=[1,2,3,4];function p(d,e,n=16384){let i=d.trim();if(!i||i.length>n)throw new l("INVALID",`${e} must be non-empty and no longer than ${n} characters`);return i}function G(d,e){return[...new Set((d??[]).map(n=>p(n,e)))]}function te(d){if(d===void 0)return;if(!d||typeof d!="object"||Array.isArray(d))throw new l("INVALID","Goal limits must be an object when provided");let e={};for(let[n,i]of Object.entries(d)){if(n!=="maxIterations"&&n!=="maxTokens"&&n!=="maxWallClockMs")throw new l("INVALID","Unknown goal limit");if(i!==void 0){if(!Number.isSafeInteger(i)||i<=0)throw new l("INVALID",`${n} must be a positive safe integer when provided`);e[n]=i}}return e}function Re(d){if(d){if(d.kind!=="fixed-interval"&&d.kind!=="dynamic")throw new l("INVALID","schedule.kind must be fixed-interval or dynamic");if(d.kind==="fixed-interval"&&(!Number.isSafeInteger(d.intervalMs)||(d.intervalMs??0)<=0))throw new l("INVALID","Fixed-interval schedules require a positive safe intervalMs");if(d.intervalMs!==void 0&&(!Number.isSafeInteger(d.intervalMs)||d.intervalMs<=0))throw new l("INVALID","schedule.intervalMs must be a positive safe integer when provided");for(let e of["nextRunAt","expiresAt"]){let n=d[e];if(n!==void 0&&!Number.isFinite(Date.parse(n)))throw new l("INVALID",`schedule.${e} must be an ISO timestamp when provided`)}return w(d)}}function w(d){return structuredClone(d)}function v(d){let e=Date.parse(d);return Number.isFinite(e)?e:0}function V(d){if(!Number.isInteger(d)||d<=0)return!1;try{return process.kill(d,0),!0}catch(e){return e.code==="EPERM"}}function Xe(d){return{summary:"Goal created; work has not started.",completedTaskCount:0,totalTaskCount:0,outstanding:[],decisions:[],updatedAt:d}}function Le(){return{status:"pending",criteria:[],evidence:[]}}function ne(d){return(0,T.createHash)("sha256").update(d).digest("hex")}var X=class{get goalTurnAdmissionVersion(){return 1}rootDirectory;now;idFactory;ownerLeaseMs;lockTimeoutMs;lockStaleMs;maximumEventsPerSession;constructor(e={}){this.rootDirectory=e.rootDirectory??y.join(K(),"coordination"),this.now=e.now??(()=>new Date().toISOString()),this.idFactory=e.idFactory??(n=>`${n}_${(0,T.randomUUID)()}`),this.ownerLeaseMs=e.ownerLeaseMs??Ae,this.lockTimeoutMs=e.lockTimeoutMs??Oe,this.lockStaleMs=e.lockStaleMs??Se,this.maximumEventsPerSession=e.maximumEventsPerSession??Te}async getSessionState(e){let n=p(e,"sessionId",1024);return w(await this.readState(n))}async fenceAdmission(e,n,i){let t=p(i.authorityId,"authorityId",512),o=p(i.operationId,"operationId",512);if(!Number.isSafeInteger(n)||n<0)throw new l("INVALID","Expected session version must be a nonnegative safe integer");if(i.action!=="archive"&&i.action!=="delete")throw new l("INVALID","Unsupported admission fence action");return this.mutate(e,r=>{let s=r.admissionFence;if(s?.authorityId===t&&s.operationId===o&&s.action===i.action)return s;if(r.version!==n)throw new l("CONFLICT","Session version changed before lifecycle fencing",{expected:n,actual:r.version});if(s?.authorityId===t&&s.action==="archive"&&i.action==="archive")return s;if(s&&!(s.authorityId===t&&s.action==="archive"&&i.action==="delete"))throw new l("CONFLICT","Another lifecycle fence already owns this session");let a={schemaVersion:1,authorityId:t,operationId:o,action:i.action,createdAt:this.now()};return r.admissionFence=a,r.schemaVersion===1&&(r.schemaVersion=2),this.appendEvent(r,"admission.fenced",{data:{authorityId:t,operationId:o,action:i.action}}),a},!0)}async clearAdmissionFence(e,n,i,t){await this.mutate(e,o=>{this.assertVersion(e,o.version,n);let r=o.admissionFence;if(!r||r.authorityId!==i||r.operationId!==t)throw new l("CONFLICT","Lifecycle fence identity does not match");if(r.action==="delete")throw new l("CONFLICT","Deleted session admission cannot be restored");if(o.owner)throw new l("CONFLICT","Execution ownership must settle before restoration");o.admissionFence=void 0,this.appendEvent(o,"admission.restored",{data:{authorityId:i,operationId:t}})},!0)}async releaseDeadLifecycleOwner(e,n,i,t){await this.mutate(e,o=>{this.assertVersion(e,o.version,n);let r=o.admissionFence;if(!r||r.authorityId!==i||r.operationId!==t)throw new l("CONFLICT","Lifecycle fence identity does not match");let s=o.owner;if(s){if(s.host!==O.hostname()||!Number.isInteger(s.processId)||(s.processId??0)<=0||V(s.processId))throw new l("CONFLICT","Execution owner exit has not been proved");o.owner=void 0,this.appendEvent(o,"ownership.released",{ownerId:s.ownerId,data:{epoch:s.epoch,reason:"fenced-local-owner-exited"}})}},!0)}async listSessionStates(){let e=y.join(this.rootDirectory,"sessions"),n;try{n=await h.readdir(e)}catch(t){if(t.code==="ENOENT")return[];throw t}return(await Promise.all(n.filter(t=>t.endsWith(".json")).map(async t=>{try{let o=JSON.parse(await h.readFile(y.join(e,t),"utf8"));return!ee.includes(o.schemaVersion)||typeof o.sessionId!="string"?void 0:((!Number.isSafeInteger(o.ownershipEpoch)||o.ownershipEpoch<0)&&(o.ownershipEpoch=Math.max(o.owner?.epoch??0,...o.handoffs.map(r=>r.targetLeaseEpoch??r.sourceLeaseEpoch??0))),o)}catch{return}}))).filter(t=>t!==void 0).sort((t,o)=>v(o.updatedAt)-v(t.updatedAt)).map(t=>w(t))}async createGoal(e){let n=p(e.sessionId,"sessionId",1024),i=te(e.limits);return this.mutate(n,t=>{let o=t.goals.find(c=>["active","paused","waiting","blocked"].includes(c.status));if(o)throw new l("CONFLICT",`Session ${n} already has active goal ${o.id}`);let r=this.now(),s=(e.successCriteria??[]).map(c=>typeof c=="string"?{id:this.idFactory("criterion"),description:p(c,"successCriteria"),required:!0}:{id:c.id?p(c.id,"successCriteria.id",512):this.idFactory("criterion"),description:p(c.description,"successCriteria.description"),required:c.required}),a={schemaVersion:1,id:this.idFactory("goal"),version:1,sessionId:n,objective:p(e.objective,"objective"),...e.why?{why:p(e.why,"why")}:{},successCriteria:s,constraints:G(e.constraints,"constraints"),...i?{limits:i}:{},metadata:w(e.metadata??{}),status:"active",milestones:[],tasks:[],progress:Xe(r),verification:Le(),steering:[],createdAt:r,updatedAt:r};return t.goals.push(a),this.appendEvent(t,"goal.created",{goalId:a.id,data:{objective:a.objective}}),a})}async getGoal(e,n){let i=await this.getSessionState(e),t=n?i.goals.find(o=>o.id===n):[...i.goals].reverse().find(o=>["active","paused","waiting","blocked"].includes(o.status));return t?w(t):void 0}async updateGoal(e,n,i,t){return this.mutate(e,o=>{let r=this.requireGoal(o,n);if(this.assertVersion(r.id,r.version,i),["completed","cancelled","failed"].includes(r.status))throw new l("CONFLICT",`Goal ${r.id} is terminal (${r.status})`);let s=r.status!=="active";if(t.status==="active"&&r.status==="blocked"?r.status="active":t.status&&(r.status=t.status),t.objective!==void 0&&(r.objective=p(t.objective,"objective")),t.why!==void 0&&(r.why=p(t.why,"why")),t.constraints&&(r.constraints=G(t.constraints,"constraints")),t.successCriteria&&(r.successCriteria=w(t.successCriteria)),t.progress&&(r.progress={...r.progress,...w(t.progress),outstanding:G(t.progress.outstanding??r.progress.outstanding,"progress.outstanding"),decisions:G(t.progress.decisions??r.progress.decisions,"progress.decisions"),updatedAt:this.now()}),t.verification&&(r.verification=w(t.verification)),t.metadata&&(r.metadata=w(t.metadata)),s&&r.status==="active")for(let a of o.loops.filter(c=>c.goalId===n&&c.kind==="goal-continuation"&&c.status==="running"))a.resumeRequested=!0,a.version+=1,a.updatedAt=this.now();return r.version+=1,r.updatedAt=this.now(),this.appendEvent(o,"goal.updated",{goalId:r.id,data:{status:r.status,version:r.version}}),r},t.status!==void 0&&["paused","cancelled","failed"].includes(t.status))}async addMilestone(e,n,i,t){return this.mutateGoal(e,n,i,(o,r)=>{let s={id:this.idFactory("milestone"),title:p(t.title,"milestone.title"),...t.description?{description:p(t.description,"milestone.description")}:{},status:o.milestones.some(a=>a.status==="active")?"pending":"active",taskIds:[],createdAt:r,updatedAt:r};o.milestones.push(s),o.progress.currentMilestoneId??=s.id,o.progress.updatedAt=r})}async addTask(e,n,i,t){return this.mutateGoal(e,n,i,(o,r)=>{let s=o.milestones.find(u=>u.id===t.milestoneId);if(!s)throw new l("NOT_FOUND",`Milestone ${t.milestoneId} was not found`);if(t.parentTaskId&&!o.tasks.some(u=>u.id===t.parentTaskId))throw new l("NOT_FOUND",`Parent task ${t.parentTaskId} was not found`);let a=[...new Set(t.dependsOn??[])];for(let u of a)if(!o.tasks.some(f=>f.id===u))throw new l("NOT_FOUND",`Task dependency ${u} was not found`);let c={id:this.idFactory("task"),milestoneId:s.id,...t.parentTaskId?{parentTaskId:t.parentTaskId}:{},title:p(t.title,"task.title"),...t.description?{description:p(t.description,"task.description")}:{},status:a.length===0?"ready":"pending",...t.assignedAgentId?{assignedAgentId:p(t.assignedAgentId,"task.assignedAgentId",512)}:{},...a.length?{dependsOn:a}:{},createdAt:r,updatedAt:r};o.tasks.push(c),s.taskIds.push(c.id),s.updatedAt=r,o.progress.totalTaskCount=o.tasks.length,o.progress.outstanding=o.tasks.filter(u=>u.status!=="completed").map(u=>u.title),o.progress.updatedAt=r})}async updateTask(e,n,i,t,o){return this.mutateGoal(e,n,t,(r,s)=>{let a=r.tasks.find(u=>u.id===i);if(!a)throw new l("NOT_FOUND",`Task ${i} was not found`);a.status=o.status,o.progress!==void 0&&(a.progress=p(o.progress,"task.progress")),o.resultEventId!==void 0&&(a.resultEventId=p(o.resultEventId,"task.resultEventId",512)),o.assignedAgentId!==void 0&&(a.assignedAgentId=p(o.assignedAgentId,"task.assignedAgentId",512)),a.updatedAt=s,a.status==="completed"&&(a.completedAt=s);let c=r.milestones.find(u=>u.id===a.milestoneId);if(c){let u=r.tasks.filter(f=>f.milestoneId===c.id);u.length>0&&u.every(f=>f.status==="completed")?(c.status="completed",c.completedAt=s):u.some(f=>f.status==="running")?c.status="active":u.some(f=>f.status==="blocked")&&(c.status="blocked"),c.updatedAt=s}for(let u of r.tasks)u.status!=="pending"||!u.dependsOn?.length||u.dependsOn.every(f=>r.tasks.find(m=>m.id===f)?.status==="completed")&&(u.status="ready",u.updatedAt=s);this.recalculateProgress(r,s)})}async steerGoal(e,n,i,t){return this.mutateGoal(e,n,i,(o,r,s)=>{let a=this.idFactory("steer");o.steering.push({id:a,instruction:p(t,"instruction"),createdAt:r}),this.appendEvent(s,"goal.steered",{goalId:n,data:{steeringId:a}})},!1)}async consumeGoalSteering(e,n,i){let t=[];return{goal:await this.mutateGoal(e,n,i,(r,s)=>{t=r.steering.filter(a=>!a.consumedAt).map(({id:a,instruction:c,createdAt:u})=>({id:a,instruction:c,createdAt:u}));for(let a of r.steering)a.consumedAt||(a.consumedAt=s)}),instructions:t}}async completeGoal(e,n,i,t){if(t.status!=="passed")throw new l("VERIFICATION_REQUIRED","Goal completion requires passed verification");return this.mutate(e,o=>{let r=this.requireGoal(o,n);this.assertVersion(r.id,r.version,i);let s=r.successCriteria.filter(u=>u.required),a=s.filter(u=>{let f=t.criteria.find(m=>m.criterionId===u.id);return!f?.satisfied||f.evidence.length===0});if(a.length>0)throw new l("VERIFICATION_REQUIRED","Required success criteria lack passing evidence",{unmetCriteria:a.map(u=>u.id)});if(s.length===0&&t.evidence.length===0)throw new l("VERIFICATION_REQUIRED","Goal completion requires at least one durable evidence reference");let c=this.now();return r.status="completed",r.verification=w(t),r.verification.verifiedAt??=c,r.completedAt=c,r.updatedAt=c,r.version+=1,this.appendEvent(o,"goal.completed",{goalId:n,data:{evidence:r.verification.evidence}}),r},!0)}async cancelGoal(e,n,i,t){return this.mutate(e,o=>{let r=this.requireGoal(o,n);if(this.assertVersion(r.id,r.version,i),["completed","cancelled","failed"].includes(r.status))return r;r.status="cancelled",r.updatedAt=this.now(),r.version+=1,this.appendEvent(o,"goal.cancelled",{goalId:n,data:{reason:p(t,"reason")}});for(let s of o.loops.filter(a=>a.goalId===n&&["running","paused","waiting"].includes(a.status)))s.status="stopped",s.resumeRequested!==void 0&&(s.resumeRequested=!1),s.stopReason=`Goal cancelled: ${t}`,s.stoppedAt=this.now(),s.updatedAt=s.stoppedAt,s.version+=1;return r},!0)}async startLoop(e){return this.mutate(e.sessionId,n=>this.createLoopRecord(n,e))}createLoopRecord(e,n){if(n.kind==="goal-continuation"&&!n.goalId)throw new l("INVALID","Goal-continuation loops require a goalId");if(n.goalId){let s=this.requireGoal(e,n.goalId);if(["completed","cancelled","failed"].includes(s.status))throw new l("CONFLICT",`Cannot start a loop for terminal goal ${s.id}`)}if(n.kind==="scheduled"&&!n.schedule)throw new l("INVALID","Scheduled loops require schedule metadata");if(n.kind!=="scheduled"&&n.schedule)throw new l("INVALID","Only scheduled loops may carry schedule metadata");let i=Re(n.schedule),t=e.loops.find(s=>s.goalId===n.goalId&&s.kind===n.kind&&["running","paused","waiting"].includes(s.status));if(t)throw new l("CONFLICT",`Loop ${t.id} is already active`);let o=this.now(),r={schemaVersion:1,id:this.idFactory("loop"),version:1,sessionId:e.sessionId,...n.goalId?{goalId:n.goalId}:{},kind:n.kind,status:"running",...n.activity?{currentActivity:p(n.activity,"activity")}:{},iterations:[],...i?{schedule:i}:{},createdAt:o,updatedAt:o};return e.loops.push(r),this.appendEvent(e,"loop.started",{loopId:r.id,goalId:r.goalId,data:{kind:r.kind}}),r}async getLoop(e,n){let i=await this.getSessionState(e),t=n?i.loops.find(o=>o.id===n):[...i.loops].reverse().find(o=>["running","paused","waiting"].includes(o.status));return t?w(t):void 0}async beginLoopIteration(e,n,i,t,o){return this.mutateLoop(e,n,i,(r,s,a)=>{this.appendLoopIteration(a,r,s,t,o)},!1)}appendLoopIteration(e,n,i,t,o,r=!1){if(n.status!=="running")throw new l("CONFLICT",`Loop ${n.id} is ${n.status}`);if(n.goalId){let c=this.requireGoal(e,n.goalId);this.isCliGoal(c)&&this.initializeGoalTurnAccounting(e,c)}if(this.assertGoalIterationAdmission(e,n,i,r),n.iterations.some(c=>c.status==="running"))throw new l("CONFLICT",`Loop ${n.id} already has a running iteration`);let s=(n.iterations.at(-1)?.number??0)+1;n.currentActivity=p(t,"activity");let a={number:s,startedAt:i,status:"running",activity:n.currentActivity,...n.goalId&&e.goalTurnAccounting?.[n.goalId]?{goalAccountingVersion:1}:{},...o?{taskId:p(o,"taskId",512)}:{}};return n.iterations.push(a),n.resumeRequested!==void 0&&(n.resumeRequested=!1),this.appendEvent(e,"loop.iteration",{loopId:n.id,goalId:n.goalId,data:{number:s,phase:"started",activity:n.currentActivity}}),a}async admitGoalTurn(e){return this.admitGoalTurnWithOwner(e)}async admitQuotaGoalTurn(e,n,i,t){let o=$(i),r=await this.getGoal(e.sessionId,e.goalId);if(!r||r.sessionId!==e.sessionId||r.limits?.maxTokens===void 0)throw new l("BUDGET_UNAVAILABLE","The exact token-bounded goal is unavailable for quota admission");if(this.isCliGoal(r)&&r.metadata["cli.tokenQuotaVersion"]!==1)throw new l("BUDGET_UNAVAILABLE","Legacy CLI goal token spend is unknown; quota admission requires creation-time provenance");if(o.goal?.id!==r.id||o.goal.generation!==r.createdAt)throw new l("BUDGET_UNAVAILABLE","Quota scope does not identify this durable goal generation");let s=await n.policy(o);if(!s||B(s.scope)!==B(o)||s.limits.tokensLifetime===void 0||s.limits.tokensLifetime===null||s.limits.tokensLifetime>r.limits.maxTokens)throw new l("BUDGET_UNAVAILABLE","Goal quota policy is absent or wider than the goal's explicit token limit");let a=await n.remainingTokens(o);if(a===null)throw new l("BUDGET_UNAVAILABLE","Goal token accounting has no durable remaining allowance");if(a<1)throw new l("BUDGET_EXCEEDED","Goal token allowance is exhausted");return this.admitGoalTurnWithOwner(e,t,{goalId:r.id,createdAt:r.createdAt,maximum:r.limits.maxTokens})}async admitOwnedGoalTurn(e,n){if(!n||!Number.isSafeInteger(n.epoch)||n.epoch<1)throw new l("INVALID","An exact execution ownership epoch is required");return this.admitGoalTurnWithOwner(e,{...n})}async admitGoalTurnWithOwner(e,n,i){let t=p(e.requestId,"requestId",512),o=this.goalTurnHash(e.requestHash);return this.mutate(e.sessionId,r=>{if(n){let f=this.requireOwner(r,n.ownerId,n.leaseId);if(f.epoch!==n.epoch)throw new l("NOT_OWNER","Execution ownership epoch changed");if(this.ownerExpired(f,this.now()))throw new l("LEASE_EXPIRED","Execution ownership expired");if(r.handoffs.some(m=>["prepared","available"].includes(m.status)&&m.sourceLeaseEpoch===f.epoch)||r.handoffs.some(m=>m.status==="claimed"&&m.targetLeaseEpoch===f.epoch))throw new l("UNSAFE_HANDOFF","Execution handoff has not settled")}let s=this.requireGoal(r,e.goalId);if(i&&(s.id!==i.goalId||s.createdAt!==i.createdAt||s.limits?.maxTokens!==i.maximum))throw new l("BUDGET_UNAVAILABLE","Goal token limit changed after quota verification");for(let f of r.loops.filter(m=>m.goalId===s.id)){let m=f.iterations.find(b=>b.goalTurn?.requestId===t);if(m){if(m.goalTurn?.requestHash!==o)throw new l("CONFLICT","Goal turn identity was reused for different work");return{...this.goalTurnState(r,s,f,m),admitted:!1}}}if(this.assertVersion(s.id,s.version,e.expectedGoalVersion),s.status!=="active")throw new l("CONFLICT",`Goal ${s.id} is ${s.status}`);let a=[...r.loops].reverse().find(f=>f.goalId===s.id&&f.kind==="goal-continuation");if(e.expectedLoopId!==void 0){if(!a||a.id!==e.expectedLoopId)throw new l("CONFLICT","Goal continuation loop changed before admission");this.assertVersion(a.id,a.version,e.expectedLoopVersion??-1)}else if(e.expectedLoopVersion!==void 0)throw new l("INVALID","A goal turn loop version requires its exact loop ID");if(a&&a.status!=="running")throw new l("CONFLICT",`Goal loop ${a.id} is ${a.status}; resume or start it explicitly`);this.initializeGoalTurnAccounting(r,s),a??=this.createLoopRecord(r,{sessionId:r.sessionId,goalId:s.id,kind:"goal-continuation"});let c=this.now(),u=this.appendLoopIteration(r,a,c,"Interactive goal turn",void 0,i!==void 0);if(e.executionKind!==void 0&&e.executionKind!=="local-sdk"&&e.executionKind!=="external")throw new l("INVALID","Unknown goal execution lane");return u.goalTurn={requestId:t,requestHash:o,executor:e.executionKind==="local-sdk"?{kind:"local-sdk",processId:process.pid,host:O.hostname()}:{kind:"external"}},a.version+=1,a.updatedAt=c,{...this.goalTurnState(r,s,a,u),admitted:!0}},!1,r=>r.admitted)}async getGoalTurnState(e,n,i){let t=await this.getSessionState(e),o=n?t.goals.find(c=>c.id===n):[...t.goals].reverse().find(c=>["active","paused","waiting","blocked"].includes(c.status));if(!o)return;let r=t.loops.filter(c=>c.goalId===o.id),s=i?r.find(c=>c.iterations.some(u=>u.goalTurn?.requestId===i)):[...r].reverse().find(c=>c.kind==="goal-continuation"),a=i?s?.iterations.find(c=>c.goalTurn?.requestId===i):s?.iterations.at(-1);if(i&&!a)throw new l("NOT_FOUND","Goal turn was not found");return this.goalTurnState(t,o,s,a)}async finishGoalTurn(e){if(!["completed","failed","interrupted"].includes(e.status))throw new l("INVALID","Invalid goal turn outcome");let n=this.goalTurnHash(e.requestHash);return this.mutate(e.sessionId,i=>{let t=this.requireGoal(i,e.goalId),o=i.loops.find(s=>s.goalId===t.id&&s.iterations.some(a=>a.goalTurn?.requestId===e.requestId)),r=o?.iterations.find(s=>s.goalTurn?.requestId===e.requestId);if(!o||!r)throw new l("NOT_FOUND","Goal turn was not found");if(r.goalTurn?.requestHash!==n)throw new l("CONFLICT","Goal turn settlement identity does not match");return r.status==="running"&&(this.settleLoopIteration(i,o,r,this.now(),{status:t.status==="cancelled"||["stopped","failed"].includes(o.status)?"interrupted":e.status}),o.version+=1,o.updatedAt=this.now()),this.goalTurnState(i,t,o,r)},!0)}async recoverGoalTurn(e,n,i){return this.mutate(e,t=>{let o=this.requireGoal(t,n),r=t.loops.find(a=>a.goalId===n&&a.iterations.some(c=>c.goalTurn?.requestId===i)),s=r?.iterations.find(a=>a.goalTurn?.requestId===i);if(!r||!s)throw new l("NOT_FOUND","Goal turn was not found");if(s.status==="running"){if(!this.goalTurnOwnerExited(s))throw new l("NOT_OWNER","The original local goal executor has not been proved exited; external execution requires reconciliation");this.settleLoopIteration(t,r,s,this.now(),{status:"interrupted",error:"Original local SDK executor exited; inspect persisted results before retrying work"}),r.resumeRequested=o.status==="active"&&r.status==="running",r.version+=1,r.updatedAt=this.now()}return this.goalTurnState(t,o,r,s)},!0)}async finishLoopIteration(e,n,i,t){return this.mutateLoop(e,n,i,(o,r,s)=>{let a=[...o.iterations].reverse().find(c=>c.status==="running");if(!a)throw new l("CONFLICT",`Loop ${o.id} has no running iteration`);this.settleLoopIteration(s,o,a,r,t)},!1,!0)}settleLoopIteration(e,n,i,t,o){i.status=o.status,i.completedAt=t,o.verificationEventId&&(i.verificationEventId=p(o.verificationEventId,"verificationEventId",512)),o.error&&(i.error=p(o.error,"error")),n.status=["stopped","completed","failed"].includes(n.status)?n.status:e.admissionFence?"paused":o.nextStatus??(n.status==="paused"||n.status==="waiting"?n.status:"running"),this.appendEvent(e,"loop.iteration",{loopId:n.id,goalId:n.goalId,data:{number:i.number,phase:"finished",status:o.status}})}async setLoopStatus(e,n,i,t,o){return this.mutateLoop(e,n,i,(r,s,a)=>{let c=r.status;if(["stopped","completed","failed"].includes(c))throw new l("CONFLICT",`Loop ${r.id} is terminal (${c})`);let u=[...r.iterations].reverse().find(m=>m.status==="running");if(u&&t==="completed")throw new l("CONFLICT",`Loop ${r.id} cannot complete while iteration ${u.number} is running`);u&&(t==="stopped"||t==="failed")&&(u.status=t==="failed"?"failed":"interrupted",u.completedAt=s,u.error=p(o??t,"reason")),r.status=t,r.kind==="goal-continuation"&&(r.resumeRequested=t==="running"),["stopped","completed","failed"].includes(t)&&(r.stoppedAt=s,r.stopReason=p(o??t,"reason"));let f=t==="paused"?"loop.paused":t==="waiting"?"loop.waiting":t==="running"&&(c==="paused"||c==="waiting")?"loop.resumed":t==="completed"?"loop.completed":t==="failed"?"loop.failed":"loop.stopped";this.appendEvent(a,f,{loopId:n,goalId:r.goalId,data:{previous:c,status:t,...o?{reason:o}:{}}})},!1,t!=="running"&&t!=="waiting")}async acquireOwnership(e,n,i={}){return this.mutate(e,t=>{let o=this.now();if(t.owner&&!this.ownerExpired(t.owner,o)){if(t.owner.ownerId===n&&i.processId!==void 0&&t.owner.processId===i.processId&&(i.host===void 0||t.owner.host===i.host))return t.owner;throw new l("CONFLICT",`Session ${e} is owned by ${t.owner.ownerId}`,{owner:t.owner})}let r=t.owner&&this.ownerExpired(t.owner,o)?t.owner:void 0;if(r)for(let c of t.handoffs.filter(u=>u.status==="claimed"&&u.claimedBy===r.ownerId&&u.targetLeaseEpoch===r.epoch))c.status="failed",c.failureReason=`Claimed owner ${r.ownerId} lost its execution lease before completing the handoff.`,c.failedAt=o,c.updatedAt=o,c.version+=1,this.appendEvent(t,"handoff.failed",{handoffId:c.id,goalId:c.goalId,loopId:c.loopId,data:{reason:c.failureReason,expiredLeaseId:r.leaseId}});let s=t.ownershipEpoch+1;for(let c of t.handoffs.filter(u=>["prepared","available"].includes(u.status)&&u.sourceLeaseEpoch<s))c.status="failed",c.failureReason="Source ownership epoch was superseded before the handoff was claimed.",c.failedAt=o,c.updatedAt=o,c.version+=1,this.appendEvent(t,"handoff.failed",{handoffId:c.id,data:{epoch:s,reason:c.failureReason}});let a=this.newOwner(n,s,i,o);return t.owner=a,t.ownershipEpoch=s,this.appendEvent(t,"ownership.acquired",{ownerId:n,data:{epoch:s,leaseId:a.leaseId}}),a})}async renewOwnership(e,n,i,t=this.ownerLeaseMs){return this.mutate(e,o=>{let r=this.requireOwner(o,n,i);if(this.ownerExpired(r,this.now()))throw new l("LEASE_EXPIRED",`Ownership lease ${i} expired`);return r.heartbeatAt=this.now(),r.expiresAt=new Date(v(r.heartbeatAt)+t).toISOString(),this.appendEvent(o,"ownership.renewed",{ownerId:n,data:{epoch:r.epoch,leaseId:i}}),r})}async recoverExpiredOwnership(e,n,i,t,o=this.ownerLeaseMs){return this.mutate(e,r=>{let s=this.requireOwner(r,n,i);if(s.processId!==t||s.host!==O.hostname()||!V(t))throw new l("LEASE_EXPIRED",`Ownership lease ${i} expired and cannot be recovered by process ${t}`);let a=this.now(),c=Math.max(0,v(a)-v(s.expiresAt));return s.heartbeatAt=a,s.expiresAt=new Date(v(a)+o).toISOString(),this.appendEvent(r,c>0?"ownership.recovered":"ownership.renewed",{ownerId:n,data:{epoch:s.epoch,leaseId:i,...c>0?{expiredForMs:c}:{}}}),s})}async releaseOwnership(e,n,i){return this.mutate(e,t=>{let o=this.requireOwner(t,n,i);for(let r of t.handoffs.filter(s=>s.status==="claimed"&&s.claimedBy===n&&s.targetLeaseEpoch===o.epoch))r.status="failed",r.failureReason="Target released execution ownership before completing the handoff.",r.failedAt=this.now(),r.updatedAt=r.failedAt,r.version+=1,this.appendEvent(t,"handoff.failed",{handoffId:r.id,ownerId:n,data:{epoch:o.epoch,reason:r.failureReason}});return t.owner=void 0,this.appendEvent(t,"ownership.released",{ownerId:n,data:{epoch:o.epoch}}),o},!0)}async createHandoff(e){let n=!1,i=e.prepareRequestId===void 0?void 0:p(e.prepareRequestId,"prepareRequestId",512);return this.mutate(e.sessionId,t=>{let o=this.requireOwner(t,e.sourceOwnerId,e.sourceLeaseId);if(this.ownerExpired(o,this.now()))throw new l("LEASE_EXPIRED",`Ownership lease ${o.leaseId} expired`);if(i){let u=t.handoffs.find(f=>f.prepareRequestId===i);if(u){if(u.sourceOwnerId!==o.ownerId||u.sourceLeaseEpoch!==o.epoch||u.status!=="available"||u.targetOwnerId!==e.targetOwnerId||u.workspace!==e.workspace||u.goalId!==e.goalId||u.loopId!==e.loopId||u.contextDigest!==e.contextDigest||u.branch!==e.branch||u.currentMilestoneId!==e.currentMilestoneId||u.currentTaskId!==e.currentTaskId||JSON.stringify(u.agentIds)!==JSON.stringify([...new Set(e.agentIds??[])])||JSON.stringify(u.operations)!==JSON.stringify(e.operations??[]))throw new l("CONFLICT","Prepare identity was reused for different work or ownership");return n=!0,u}}let r=(e.operations??[]).filter(u=>u.status==="running"&&u.sideEffecting);if(r.length>0)throw new l("UNSAFE_HANDOFF","Running side-effecting operations must settle before execution handoff",{operationIds:r.map(u=>u.operationId)});if(e.goalId&&this.requireGoal(t,e.goalId),e.loopId&&!t.loops.some(u=>u.id===e.loopId))throw new l("NOT_FOUND",`Loop ${e.loopId} was not found`);let s=t.handoffs.find(u=>["prepared","available","claimed"].includes(u.status));if(s)throw new l("CONFLICT",`Handoff ${s.id} is already active`);let a=this.now(),c={schemaVersion:1,id:this.idFactory("handoff"),version:1,sessionId:t.sessionId,...e.goalId?{goalId:e.goalId}:{},...e.loopId?{loopId:e.loopId}:{},status:"available",sourceOwnerId:o.ownerId,...i?{prepareRequestId:i}:{},...e.targetOwnerId?{targetOwnerId:p(e.targetOwnerId,"targetOwnerId",512)}:{},sourceLeaseEpoch:o.epoch,...e.workspace?{workspace:p(e.workspace,"workspace",32768)}:{},...e.branch?{branch:p(e.branch,"branch",1024)}:{},...e.currentMilestoneId?{currentMilestoneId:e.currentMilestoneId}:{},...e.currentTaskId?{currentTaskId:e.currentTaskId}:{},agentIds:[...new Set(e.agentIds??[])],operations:w(e.operations??[]),...e.contextDigest?{contextDigest:p(e.contextDigest,"contextDigest",512)}:{},createdAt:a,updatedAt:a};return t.handoffs.push(c),this.appendEvent(t,"handoff.created",{handoffId:c.id,goalId:c.goalId,loopId:c.loopId,ownerId:o.ownerId,data:{targetOwnerId:c.targetOwnerId}}),c},!1,()=>!n)}async claimHandoff(e){let n,i=!1,t=e.claimRequestId===void 0?void 0:p(e.claimRequestId,"claimRequestId",512);return{handoff:await this.mutate(e.sessionId,r=>{let s=r.handoffs.find(u=>u.id===e.handoffId);if(!s)throw new l("NOT_FOUND",`Handoff ${e.handoffId} was not found`);if(s.status!=="available"){let u=r.owner;if(t&&s.claimRequestId===t&&["claimed","completed"].includes(s.status)&&s.claimedBy===e.targetOwnerId&&u?.ownerId===e.targetOwnerId&&u.epoch===s.targetLeaseEpoch&&u.host===e.host&&u.processId===e.processId&&!this.ownerExpired(u,this.now()))return n=u,i=!0,s;throw new l("CONFLICT",`Handoff ${s.id} is ${s.status}`,{claimedBy:s.claimedBy})}if(s.targetOwnerId&&s.targetOwnerId!==e.targetOwnerId)throw new l("CONFLICT",`Handoff ${s.id} is reserved for ${s.targetOwnerId}`);let a=r.owner;if(!a||a.ownerId!==s.sourceOwnerId||a.epoch!==s.sourceLeaseEpoch)throw new l("CONFLICT",`Handoff ${s.id} no longer matches the source ownership epoch`);let c=this.now();return n=this.newOwner(e.targetOwnerId,a.epoch+1,{processId:e.processId,host:e.host,leaseMs:e.leaseMs},c),r.owner=n,r.ownershipEpoch=n.epoch,s.status="claimed",s.claimedBy=e.targetOwnerId,t&&(s.claimRequestId=t),s.targetOwnerId=e.targetOwnerId,s.targetLeaseEpoch=n.epoch,s.claimedAt=c,s.updatedAt=c,s.version+=1,this.appendEvent(r,"handoff.claimed",{handoffId:s.id,goalId:s.goalId,loopId:s.loopId,ownerId:e.targetOwnerId,data:{sourceOwnerId:s.sourceOwnerId,epoch:n.epoch}}),s},!1,()=>!i),owner:w(n)}}async completeHandoff(e,n,i,t){let o=!1;return this.mutate(e,r=>{let s=this.requireOwner(r,i,t);if(this.ownerExpired(s,this.now()))throw new l("LEASE_EXPIRED",`Ownership lease ${t} expired`);let a=r.handoffs.find(c=>c.id===n);if(!a)throw new l("NOT_FOUND",`Handoff ${n} was not found`);if(a.claimedBy!==i||a.targetLeaseEpoch!==s.epoch||!["claimed","completed"].includes(a.status))throw new l("CONFLICT",`Handoff ${a.id} cannot be completed by ${i}`);return a.status==="completed"?(o=!0,a):(a.status="completed",a.completedAt=this.now(),a.updatedAt=a.completedAt,a.version+=1,this.appendEvent(r,"handoff.completed",{handoffId:n,goalId:a.goalId,loopId:a.loopId,ownerId:i,data:{epoch:r.owner?.epoch}}),a)},!1,()=>!o)}async cancelHandoff(e,n,i,t){let o=!1;return this.mutate(e,r=>{let s=r.handoffs.find(c=>c.id===n);if(!s)throw new l("NOT_FOUND",`Handoff ${n} was not found`);if(s.sourceOwnerId!==i)throw new l("CONFLICT",`Handoff ${n} was not offered by ${i}`);if(s.status==="cancelled")return o=!0,s;if(s.status!=="available"&&s.status!=="prepared")throw new l("CONFLICT",`Handoff ${n} is ${s.status} and can no longer be cancelled`);let a=this.requireOwner(r,i,t);if(this.ownerExpired(a,this.now()))throw new l("LEASE_EXPIRED",`Ownership lease ${t} expired`);if(s.sourceLeaseEpoch!==a.epoch)throw new l("CONFLICT",`Handoff ${n} belongs to an earlier ownership epoch`);return s.status="cancelled",s.cancelledAt=this.now(),s.updatedAt=s.cancelledAt,s.version+=1,this.appendEvent(r,"handoff.cancelled",{handoffId:n,goalId:s.goalId,loopId:s.loopId,ownerId:i,data:{epoch:a.epoch}}),s},!1,()=>!o)}async failHandoff(e,n,i){return this.mutate(e,t=>{let o=t.handoffs.find(r=>r.id===n);if(!o)throw new l("NOT_FOUND",`Handoff ${n} was not found`);return["completed","cancelled","failed"].includes(o.status)||(o.status="failed",o.failureReason=p(i,"reason"),o.failedAt=this.now(),o.updatedAt=o.failedAt,o.version+=1,this.appendEvent(t,"handoff.failed",{handoffId:n,goalId:o.goalId,loopId:o.loopId,data:{reason:o.failureReason}})),o},!0)}async mutateGoal(e,n,i,t,o=!0){return this.mutate(e,r=>{let s=this.requireGoal(r,n);this.assertVersion(s.id,s.version,i);let a=this.now();return t(s,a,r),s.version+=1,s.updatedAt=a,o&&this.appendEvent(r,"goal.updated",{goalId:n,data:{status:s.status,version:s.version}}),s})}async mutateLoop(e,n,i,t,o=!0,r=!1){return this.mutate(e,s=>{let a=s.loops.find(u=>u.id===n);if(!a)throw new l("NOT_FOUND",`Loop ${n} was not found`);this.assertVersion(a.id,a.version,i);let c=this.now();return t(a,c,s),a.version+=1,a.updatedAt=c,o&&this.appendEvent(s,"loop.iteration",{loopId:n,goalId:a.goalId,data:{status:a.status,version:a.version}}),a},r)}assertGoalIterationAdmission(e,n,i,t=!1){if(!n.goalId)return;let o=this.requireGoal(e,n.goalId);if(o.status!=="active")throw new l("CONFLICT",`Goal ${o.id} is ${o.status}; no iteration was admitted`);let r=te(o.limits);if(r?.maxTokens!==void 0&&!t)throw new l("BUDGET_UNAVAILABLE","Goal token allowance is not bound to request-level admission; no iteration was admitted",{goalId:o.id,limit:"maxTokens"});if(r?.maxWallClockMs!==void 0){let s=Date.parse(o.createdAt),a=Date.parse(i);if(!Number.isFinite(s)||!Number.isFinite(a)||a<s)throw new l("BUDGET_UNAVAILABLE","Goal wall-clock allowance cannot be verified",{goalId:o.id,limit:"maxWallClockMs"});if(a-s>=r.maxWallClockMs)throw new l("BUDGET_EXCEEDED","Goal wall-clock limit reached; no iteration was admitted",{goalId:o.id,limit:"maxWallClockMs",maximum:r.maxWallClockMs})}if(r?.maxIterations!==void 0){let s=e.goalTurnAccounting!==void 0||e.schemaVersion===4?this.resolveGoalTurnAccounting(e,o):void 0;if(s?.coverage==="partial")throw new l("BUDGET_UNAVAILABLE","Legacy goal turn accounting is incomplete");let a=this.goalIterationCount(e,o)+(s?.baseIterations??0);if(!Number.isSafeInteger(a)||a<0)throw new l("BUDGET_UNAVAILABLE","Invalid goal iteration accounting");if(a>=r.maxIterations)throw new l("BUDGET_EXCEEDED","Goal iteration limit reached; no iteration was admitted",{goalId:o.id,limit:"maxIterations",admitted:a,maximum:r.maxIterations})}}isCliGoal(e){return"cli.accountedTurns"in e.metadata||"cli.createdByCliVersion"in e.metadata}goalIterationCount(e,n){let i=0;for(let t of e.loops.filter(o=>o.goalId===n.id)){if(!Array.isArray(t.iterations))throw new l("BUDGET_UNAVAILABLE","Goal iteration history is unavailable");let o=0;for(let r of t.iterations){if(!r||!Number.isSafeInteger(r.number)||r.number<=o)throw new l("BUDGET_UNAVAILABLE","Goal iteration history is invalid");o=r.number}if(i+=o,!Number.isSafeInteger(i))throw new l("BUDGET_UNAVAILABLE","Goal iteration count exceeds its supported range")}return i}resolveGoalTurnAccounting(e,n){let i=e.goalTurnAccounting;if(i!==void 0&&(!i||typeof i!="object"||Array.isArray(i)))throw new l("BUDGET_UNAVAILABLE","Persisted goal turn accounting is invalid");if(i&&Object.hasOwn(i,n.id)){let a=i[n.id];if(!a||a.schemaVersion!==1||!Number.isSafeInteger(a.baseIterations)||a.baseIterations<0||!["complete","partial"].includes(a.coverage))throw new l("BUDGET_UNAVAILABLE","Persisted goal turn accounting is invalid");return a}if(e.loops.some(a=>a.goalId===n.id&&a.iterations.some(c=>c.goalTurn||c.goalAccountingVersion)))throw new l("BUDGET_UNAVAILABLE","Recorded goal turns are missing their protected accounting");let t=this.goalIterationCount(e,n),o=n.metadata["cli.accountedTurns"],r=typeof o=="number"&&Number.isSafeInteger(o)&&o>=0,s=this.isCliGoal(n)&&(!r||o>0&&t>0);return{schemaVersion:1,baseIterations:r&&t===0?o:0,coverage:s?"partial":"complete"}}initializeGoalTurnAccounting(e,n){let i=this.resolveGoalTurnAccounting(e,n);if(i.coverage==="partial"&&n.limits?.maxIterations!==void 0)throw new l("BUDGET_UNAVAILABLE","Legacy goal turn accounting needs reconciliation before bounded execution");e.goalTurnAccounting??={},Object.defineProperty(e.goalTurnAccounting,n.id,{value:i,writable:!0,enumerable:!0,configurable:!0})}goalTurnHash(e){let n=p(e,"requestHash",64).toLowerCase();if(!/^[0-9a-f]{64}$/.test(n))throw new l("INVALID","Goal turn requestHash must be a SHA-256 digest");return n}goalTurnState(e,n,i,t){let o=this.resolveGoalTurnAccounting(e,n),r=this.goalIterationCount(e,n)+o.baseIterations;if(!Number.isSafeInteger(r))throw new l("BUDGET_UNAVAILABLE","Goal turn count exceeds its supported range");return w({goal:n,admittedTurns:r,accountingCoverage:o.coverage,...i?{loopId:i.id,loopVersion:i.version,loopStatus:i.status,resumeRequested:i.resumeRequested===!0}:{},...t?{iterationNumber:t.number,iterationStatus:t.status,...t.goalTurn?{requestId:t.goalTurn.requestId,requestHash:t.goalTurn.requestHash}:{},canRecover:t.status==="running"&&this.goalTurnOwnerExited(t)}:{}})}goalTurnOwnerExited(e){let n=e.goalTurn?.executor;if(n?.kind!=="local-sdk"||n.host!==O.hostname()||!Number.isSafeInteger(n.processId)||n.processId<=0)return!1;try{return process.kill(n.processId,0),!1}catch(i){return i.code==="ESRCH"}}recalculateProgress(e,n){let i=e.tasks.filter(t=>t.status==="completed").length;e.progress.completedTaskCount=i,e.progress.totalTaskCount=e.tasks.length,e.progress.percent=e.tasks.length?Math.round(i/e.tasks.length*100):void 0,e.progress.outstanding=e.tasks.filter(t=>!["completed","cancelled"].includes(t.status)).map(t=>t.title),e.progress.updatedAt=n}requireGoal(e,n){let i=e.goals.find(t=>t.id===n);if(!i)throw new l("NOT_FOUND",`Goal ${n} was not found`);return i}requireOwner(e,n,i){let t=e.owner;if(!t||t.ownerId!==n||t.leaseId!==i)throw new l("NOT_OWNER",`${n} does not own session ${e.sessionId}`,{owner:t});return t}assertVersion(e,n,i){if(!Number.isInteger(i)||i<1||n!==i)throw new l("CONFLICT",`Expected ${e} version ${i}, found ${n}`,{expected:i,actual:n})}newOwner(e,n,i,t){let o=i.leaseMs??this.ownerLeaseMs;if(!Number.isSafeInteger(o)||o<1)throw new l("INVALID","leaseMs must be a positive safe integer");return{ownerId:p(e,"ownerId",512),leaseId:this.idFactory("owner"),epoch:n,acquiredAt:t,heartbeatAt:t,expiresAt:new Date(v(t)+o).toISOString(),...i.processId!==void 0?{processId:i.processId}:{},...i.host?{host:p(i.host,"host",512)}:{}}}ownerExpired(e,n){return v(e.expiresAt)<=v(n)?!0:e.processId!==void 0&&e.host===O.hostname()&&!V(e.processId)}appendEvent(e,n,i){let t={schemaVersion:1,id:this.idFactory("event"),sequence:(e.events.at(-1)?.sequence??0)+1,type:n,sessionId:e.sessionId,...i.goalId?{goalId:i.goalId}:{},...i.loopId?{loopId:i.loopId}:{},...i.handoffId?{handoffId:i.handoffId}:{},...i.ownerId?{ownerId:i.ownerId}:{},timestamp:this.now(),data:w(i.data)};e.events.push(t),e.events.length>this.maximumEventsPerSession&&e.events.splice(0,e.events.length-this.maximumEventsPerSession)}async mutate(e,n,i=!1,t=()=>!0){let o=p(e,"sessionId",1024);return this.withSessionLock(o,async()=>{let r=await this.readState(o);if(r.admissionFence&&!i)throw new l("CONFLICT","Session execution is blocked by a persisted lifecycle fence");let s=r.schemaVersion;this.promoteGoalBudgetEnvelope(r),r.schemaVersion!==s&&await this.writeState(r);let a=n(r);return t(a)&&(r.version+=1,r.updatedAt=this.now(),await this.writeState(r)),w(a)})}statePath(e){return y.join(this.rootDirectory,"sessions",`${ne(e)}.json`)}lockPath(e){return`${this.statePath(e)}.lock`}async readState(e){let n=this.statePath(e);try{let i=await h.readFile(n,"utf8"),t=JSON.parse(i);if(!ee.includes(t.schemaVersion)||t.sessionId!==e)throw new l("INVALID",`Coordination state at ${n} does not match session ${e}`);if(t.admissionFence!==void 0){let o=t.admissionFence;if(!o||o.schemaVersion!==1||typeof o.authorityId!="string"||!o.authorityId.trim()||typeof o.operationId!="string"||!o.operationId.trim()||!["archive","delete"].includes(o.action)||!Number.isFinite(Date.parse(o.createdAt)))throw new l("INVALID","Persisted lifecycle fence is corrupt; execution remains unavailable")}return(!Number.isSafeInteger(t.ownershipEpoch)||t.ownershipEpoch<0)&&(t.ownershipEpoch=Math.max(t.owner?.epoch??0,...t.handoffs.map(o=>o.targetLeaseEpoch??o.sourceLeaseEpoch??0))),t}catch(i){if(i.code!=="ENOENT")throw i;let t=this.now();return{schemaVersion:1,sessionId:e,version:0,ownershipEpoch:0,goals:[],loops:[],handoffs:[],events:[],createdAt:t,updatedAt:t}}}promoteGoalBudgetEnvelope(e){(e.goalTurnAccounting!==void 0||e.loops.some(n=>n.resumeRequested!==void 0||n.iterations.some(i=>i.goalTurn!==void 0)))&&(e.schemaVersion=4),e.schemaVersion<3&&e.goals.some(n=>n.limits!==void 0&&(!n.limits||typeof n.limits!="object"||Array.isArray(n.limits)||Object.keys(n.limits).length>0))&&(e.schemaVersion=3)}async writeState(e){this.promoteGoalBudgetEnvelope(e);let n=this.statePath(e.sessionId),i=y.dirname(n);await h.mkdir(i,{recursive:!0});let t=`${n}.${process.pid}.${(0,T.randomUUID)()}.tmp`,o=await h.open(t,"wx");try{await o.writeFile(`${JSON.stringify(e,null,2)}
2
+ `,"utf8"),await o.sync()}finally{await o.close()}try{await this.renameReplacing(t,n);try{let r=await h.open(i,"r");try{await r.sync()}finally{await r.close()}}catch{}}finally{await h.unlink(t).catch(()=>{})}}async renameReplacing(e,n){for(let i=0;;i+=1)try{await h.rename(e,n);return}catch(t){let o=t.code,r=Z[i];if(process.platform!=="win32"||!o||!D.has(o)||r===void 0)throw t;await new Promise(s=>setTimeout(s,r))}}async withSessionLock(e,n){let i=this.lockPath(e),t=y.join(i,"owner.json"),o=(0,T.randomUUID)(),r=`${i}.candidate.${o}`,s=Date.now();await h.mkdir(y.dirname(i),{recursive:!0});let a={schemaVersion:1,token:o,pid:process.pid,host:O.hostname(),acquiredAt:this.now()};await h.mkdir(r),await h.writeFile(y.join(r,"owner.json"),JSON.stringify(a),{encoding:"utf8",flag:"wx"});for(let c=0;;c+=1)try{await h.rename(r,i);break}catch(u){let f=u.code;if(!(!!f&&new Set(["EEXIST","ENOTEMPTY","ENOTDIR","EBUSY"]).has(f)||process.platform==="win32"&&!!f&&D.has(f)))throw await h.rm(r,{recursive:!0,force:!0}).catch(()=>{}),u;let R=await this.staleLockOwner(i,t);if(R){await this.quarantineLock(i,R.token,"stale");continue}if(Date.now()-s>=this.lockTimeoutMs)throw await h.rm(r,{recursive:!0,force:!0}).catch(()=>{}),new l("CONFLICT",`Timed out waiting for coordination lock for session ${e}`);await new Promise(N=>setTimeout(N,Math.min(100,5+c*5)+Math.floor(Math.random()*10)))}try{return await n()}finally{await this.quarantineLock(i,o,"released"),await h.rm(r,{recursive:!0,force:!0}).catch(()=>{})}}async staleLockOwner(e,n){try{let[i,t]=await Promise.all([h.readFile(n,"utf8").catch(()=>""),h.stat(e)]),o=i?JSON.parse(i):void 0;return!o||o.host!==O.hostname()||V(o.pid)?void 0:Date.now()-t.mtimeMs>this.lockStaleMs?o:void 0}catch{return}}async quarantineLock(e,n,i){let t=y.join(e,"owner.json"),o=i==="stale"?`${e}.stale.${ne(n)}`:`${e}.${i}.${n}.${(0,T.randomUUID)()}`;for(let r=0;;r+=1){let s;try{s=JSON.parse(await h.readFile(t,"utf8"))}catch(a){if(a.code==="ENOENT")return;throw a}if(s.token!==n)return;try{await h.rename(e,o);break}catch(a){let c=a.code;if(i==="stale")try{if(JSON.parse(await h.readFile(y.join(o,"owner.json"),"utf8")).token===n)return}catch{}if(c==="ENOENT"||c==="EEXIST")return;let u=Z[r];if(process.platform!=="win32"||!c||!D.has(c)||u===void 0)throw a;await new Promise(f=>setTimeout(f,u))}}if(i!=="stale")for(let r=0;;r+=1)try{await h.rm(o,{recursive:!0});return}catch(s){let a=s.code;if(a==="ENOENT")return;let c=xe[r];if(process.platform!=="win32"||!a||!D.has(a)||c===void 0)throw s;await new Promise(u=>setTimeout(u,c))}}};function L(d,e){if(!d||typeof d!="object"||Array.isArray(d))throw new Error(`${e} must be an object`);return d}function g(d,e){if(typeof d!="string"||!d.trim())throw new Error(`${e} must be a non-empty string`);return d}function x(d,e){if(typeof d!="number"||!Number.isInteger(d))throw new Error(`${e} must be an integer`);return d}async function Ne(d,e){let{action:n,sessionId:i}=e,t=e.payload??{};if(t.sessionId!==void 0&&t.sessionId!==i)throw new l("INVALID","Payload sessionId must match the routed sessionId");let o;switch(n){case"state.get":o=await d.getSessionState(i);break;case"goal.create":o=await d.createGoal({...t,sessionId:i});break;case"goal.update":o=await d.updateGoal(i,g(t.goalId,"goalId"),x(t.expectedVersion,"expectedVersion"),L(t.update,"update"));break;case"goal.complete":o=await d.completeGoal(i,g(t.goalId,"goalId"),x(t.expectedVersion,"expectedVersion"),L(t.verification,"verification"));break;case"goal.cancel":o=await d.cancelGoal(i,g(t.goalId,"goalId"),x(t.expectedVersion,"expectedVersion"),g(t.reason,"reason"));break;case"goal.steer":o=await d.steerGoal(i,g(t.goalId,"goalId"),x(t.expectedVersion,"expectedVersion"),g(t.instruction,"instruction"));break;case"loop.start":o=await d.startLoop({sessionId:i,kind:g(t.kind,"kind"),...typeof t.goalId=="string"?{goalId:t.goalId}:{},...typeof t.activity=="string"?{activity:t.activity}:{},...t.schedule?{schedule:L(t.schedule,"schedule")}:{}});break;case"loop.get":o=await d.getLoop(i,typeof t.loopId=="string"?t.loopId:void 0);break;case"loop.begin":o=await d.beginLoopIteration(i,g(t.loopId,"loopId"),x(t.expectedVersion,"expectedVersion"),g(t.activity,"activity"),typeof t.taskId=="string"?t.taskId:void 0);break;case"loop.finish":o=await d.finishLoopIteration(i,g(t.loopId,"loopId"),x(t.expectedVersion,"expectedVersion"),L(t.result,"result"));break;case"loop.set_status":o=await d.setLoopStatus(i,g(t.loopId,"loopId"),x(t.expectedVersion,"expectedVersion"),g(t.status,"status"),typeof t.reason=="string"?t.reason:void 0);break;case"ownership.acquire":o=await d.acquireOwnership(i,g(t.ownerId,"ownerId"),L(t.options??{},"options"));break;case"ownership.renew":o=await d.renewOwnership(i,g(t.ownerId,"ownerId"),g(t.leaseId,"leaseId"),typeof t.leaseMs=="number"?t.leaseMs:void 0);break;case"ownership.release":o=await d.releaseOwnership(i,g(t.ownerId,"ownerId"),g(t.leaseId,"leaseId"));break;case"handoff.create":o=await d.createHandoff({...t,sessionId:i});break;case"handoff.claim":o=await d.claimHandoff({sessionId:i,handoffId:g(t.handoffId,"handoffId"),targetOwnerId:g(t.targetOwnerId,"targetOwnerId"),...typeof t.processId=="number"?{processId:t.processId}:{},...typeof t.host=="string"?{host:t.host}:{}});break;case"handoff.complete":o=await d.completeHandoff(i,g(t.handoffId,"handoffId"),g(t.ownerId,"ownerId"),g(t.leaseId,"leaseId"));break;case"handoff.fail":o=await d.failHandoff(i,g(t.handoffId,"handoffId"),g(t.reason,"reason"));break;default:throw new l("INVALID","Unsupported coordination action")}let r=await d.getSessionState(i),s=n==="state.get"||n==="loop.get"?void 0:r.events.at(-1);return{action:n,sessionId:i,result:o,state:r,...s?{event:s}:{}}}var oe=require("node:crypto"),re=require("node:os");var j=class{sessionId;ownerId;store;processId;host;leaseMs;heartbeatMs;claimHandoffId;claimRequestId;onOwnershipLost;prepareDestination;destinationTimeoutMs;initializationAbort=new AbortController;timer;heartbeatInFlight=!1;owner;ready=!1;starting;stopping;stopped=!1;lostError;preparedHandoffId;preparingHandoff=!1;handoffOutcomeUncertain=!1;constructor(e){if(this.store=e.store??new X,this.sessionId=e.sessionId,this.processId=e.processId??process.pid,this.host=e.host??(0,re.hostname)(),this.ownerId=e.ownerId??`runtime:${this.host}:${this.processId}:${(0,oe.randomUUID)().slice(0,8)}`,this.leaseMs=e.leaseMs??3e4,this.heartbeatMs=e.heartbeatMs??Math.max(250,Math.floor(this.leaseMs/3)),this.heartbeatMs>=this.leaseMs)throw new Error("heartbeatMs must be shorter than leaseMs");if(this.claimHandoffId=e.claimHandoffId,this.claimRequestId=e.claimRequestId,this.onOwnershipLost=e.onOwnershipLost,this.prepareDestination=e.prepareDestination,this.destinationTimeoutMs=e.destinationTimeoutMs??Math.min(1e4,Math.floor(this.leaseMs/2)),!Number.isSafeInteger(this.destinationTimeoutMs)||this.destinationTimeoutMs<1||this.destinationTimeoutMs>=this.leaseMs)throw new Error("destinationTimeoutMs must be a positive integer shorter than leaseMs")}get currentOwner(){return this.active&&this.owner?structuredClone(this.owner):void 0}get active(){return this.ready&&!!this.owner&&!this.stopped&&this.lostError===void 0&&!this.preparingHandoff&&!this.preparedHandoffId}async start(){if(this.stopped)throw new Error("Execution lease session has already stopped");if(this.lostError!==void 0)throw this.lostError;return this.ready&&this.owner?(this.assertExecutionAllowed(),structuredClone(this.owner)):(this.starting??=this.initialize(),structuredClone(await this.starting))}async initialize(){try{if(this.claimHandoffId){let e=await this.store.claimHandoff({sessionId:this.sessionId,handoffId:this.claimHandoffId,targetOwnerId:this.ownerId,processId:this.processId,host:this.host,leaseMs:this.leaseMs,...this.claimRequestId?{claimRequestId:this.claimRequestId}:{}});if(this.owner=e.owner,this.stopped)throw new Error("Execution lease session has already stopped");if(this.prepareDestination&&await this.prepareClaimedDestination(e.handoff),this.stopped)throw new Error("Execution lease session has already stopped");await this.store.completeHandoff(this.sessionId,this.claimHandoffId,this.ownerId,this.owner.leaseId)}else this.owner=await this.store.acquireOwnership(this.sessionId,this.ownerId,{processId:this.processId,host:this.host,leaseMs:this.leaseMs});if(this.stopped)throw new Error("Execution lease session has already stopped");if(this.owner=await this.store.renewOwnership(this.sessionId,this.ownerId,this.owner.leaseId,this.leaseMs),this.stopped)throw new Error("Execution lease session has already stopped");return this.ready=!0,this.timer=setInterval(()=>{this.heartbeat()},this.heartbeatMs),this.timer.unref?.(),structuredClone(this.owner)}catch(e){throw this.ready=!1,this.markLost(e instanceof Error?e:new Error("Execution lease initialization failed",{cause:e})),this.lostError}}async prepareClaimedDestination(e){let n=this.initializationAbort.signal,i,t;try{let o=new Promise((r,s)=>{t=()=>s(n.reason??new Error("Destination preparation cancelled")),n.addEventListener("abort",t,{once:!0}),i=setTimeout(()=>this.initializationAbort.abort(new Error("Destination preparation timed out")),this.destinationTimeoutMs),n.aborted&&t()});await Promise.race([o,Promise.resolve().then(()=>(n.throwIfAborted(),this.prepareDestination({handoff:structuredClone(e),signal:n})))]),n.throwIfAborted()}finally{i&&clearTimeout(i),t&&n.removeEventListener("abort",t)}}async assertOwned(){this.assertExecutionAllowed();let e=await this.renewHeldLease();return this.assertExecutionAllowed(),e}assertExecutionAllowed(){if(this.stopped)throw new Error("Execution surface is detached");if(this.lostError)throw this.lostError;if(this.preparingHandoff)throw new Error("Execution surface is preparing a handoff and is detached from mutation");if(this.preparedHandoffId)throw new Error(`Execution surface prepared handoff ${this.preparedHandoffId} and is detached from mutation`);if(!this.ready||!this.owner)throw new Error("Execution ownership was not started")}async renewHeldLease(){if(!this.owner)throw new Error("Execution ownership was not started");try{let e=await this.renewOrRecover(this.owner.leaseId);if(this.stopped)throw new Error("Execution surface is detached");return this.owner=e,structuredClone(this.owner)}catch(e){throw this.markLost(e),e}}async renewOrRecover(e){try{return await this.store.renewOwnership(this.sessionId,this.ownerId,e,this.leaseMs)}catch(n){if(!(n instanceof Error&&"code"in n&&n.code==="LEASE_EXPIRED")||!this.store.recoverExpiredOwnership||this.preparingHandoff||this.preparedHandoffId||this.stopped)throw n;return this.store.recoverExpiredOwnership(this.sessionId,this.ownerId,e,this.processId,this.leaseMs)}}async prepareHandoff(e={}){if(this.preparedHandoffId)throw new Error(`Handoff ${this.preparedHandoffId} is already prepared`);this.assertExecutionAllowed(),this.preparingHandoff=!0;try{let n=await this.renewHeldLease();this.handoffOutcomeUncertain=!0;let i=await this.store.createHandoff({...e,sessionId:this.sessionId,sourceOwnerId:n.ownerId,sourceLeaseId:n.leaseId});return this.preparedHandoffId=i.id,this.handoffOutcomeUncertain=!1,i}catch(n){throw this.markLost(n instanceof Error?n:new Error("Handoff preparation failed",{cause:n})),n}finally{this.preparingHandoff=!1}}async cancelPreparedHandoff(){let e=this.preparedHandoffId;if(!e)throw new Error("No prepared handoff to cancel");if(!this.store.cancelHandoff)throw new Error("This execution store cannot cancel a prepared handoff");if(this.stopped)throw new Error("Execution surface is detached");if(this.lostError)throw this.lostError;if(!this.owner)throw new Error("Execution ownership was not started");let n=await this.store.cancelHandoff(this.sessionId,e,this.ownerId,this.owner.leaseId);if(n.id!==e||n.status!=="cancelled")throw new Error(`Handoff ${e} was not cancelled`);return this.preparedHandoffId=void 0,await this.renewHeldLease(),n}async stop(e={}){return this.stopping?this.stopping:(this.stopped=!0,this.ready=!1,this.initializationAbort.abort(new Error("Execution lease session has already stopped")),this.timer&&clearInterval(this.timer),this.timer=void 0,this.stopping=this.finishStop(e),this.stopping)}async finishStop(e){await this.starting?.catch(()=>{});let n=this.owner;if(this.owner=void 0,!(e.release===!1||this.preparedHandoffId||this.handoffOutcomeUncertain||!n))try{await this.store.releaseOwnership(this.sessionId,n.ownerId,n.leaseId)}catch{}}async heartbeat(){if(!(!this.ready||!this.owner||this.stopped||this.lostError!==void 0||this.heartbeatInFlight)){this.heartbeatInFlight=!0;try{await this.renewHeldLease()}catch(e){this.markLost(e)}finally{this.heartbeatInFlight=!1}}}markLost(e){this.lostError===void 0&&(this.lostError=e,this.timer&&clearInterval(this.timer),this.timer=void 0,this.onOwnershipLost?.(e))}};var ie=require("node:crypto"),M=require("node:perf_hooks");async function Ce(d,e){let n=e.waitMs??0;if(!Number.isSafeInteger(n)||n<0||n>6e4)throw new l("INVALID","waitMs must be an integer from 0 through 60000");if(e.sinceRevision!==void 0&&!/^[a-f0-9]{64}$/.test(e.sinceRevision))throw new l("INVALID","Invalid handoff revision");if(typeof e.handoffId!="string"||!e.handoffId.trim()||e.handoffId.length>1024)throw new l("INVALID","Invalid handoff identifier");let i=M.performance.now()+n;for(;;){e.signal?.throwIfAborted();let t=await d.getSessionState(e.sessionId);e.signal?.throwIfAborted();let o=t.handoffs.find(a=>a.id===e.handoffId);if(!o)throw new l("NOT_FOUND","Handoff not found in the authorized session");let r=(0,ie.createHash)("sha256").update(JSON.stringify([t.sessionId,o.id,o.version,o.status,t.ownershipEpoch,t.owner?.ownerId??null,t.owner?.epoch??null])).digest("hex"),s=e.sinceRevision===void 0||r!==e.sinceRevision;if(s||M.performance.now()>=i)return{sessionId:t.sessionId,handoffId:o.id,revision:r,changed:s,status:o.status,handoffVersion:o.version,ownershipEpoch:t.ownershipEpoch,sourceOwnerId:o.sourceOwnerId,...o.targetOwnerId?{targetOwnerId:o.targetOwnerId}:{}};await new Promise((a,c)=>{let u=e.signal,m=setTimeout(()=>{u?.removeEventListener("abort",b),a()},Math.min(100,Math.max(1,i-M.performance.now()))),b=()=>{clearTimeout(m),u?.removeEventListener("abort",b),c(u?.reason??new Error("Handoff wait cancelled"))};u?.addEventListener("abort",b,{once:!0}),u?.aborted&&b()})}}var ae=require("node:crypto"),Q=require("node:fs"),E=require("node:fs/promises"),I=require("node:path");var se=require("node:crypto");function H(d){return{algorithm:"sha256",value:(0,se.createHash)("sha256").update(d).digest("hex")}}var de=1e4,ce=8*1024*1024,le=64*1024*1024;function ue(d){if(typeof d!="string"||!d||d.length>2048||(0,I.isAbsolute)(d)||/[\\:*?"<>|]/.test(d)||[...d].some(n=>n.charCodeAt(0)<32))throw new Error("Invalid portable snapshot path");let e=d.split("/");if(e.some(n=>!n||n==="."||n===".."||/[. ]$/.test(n)||/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(n)))throw new Error("Ambiguous portable snapshot path");if(e.some(n=>/^(?:\.git|\.ssh|\.aws|\.npmrc|\.netrc|\.xeno-handoff-ready|credentials(?:\.json)?|id_rsa|id_ed25519)$/i.test(n)||/^\.env(?:\.|$)/i.test(n)))throw new Error("Credential or repository-control path cannot be transferred");return d}function fe(d){return H(JSON.stringify([d.schemaVersion,d.sessionId,d.totalBytes,d.files.map(e=>[e.path,e.size,e.sha256,e.executable])])).value}function pe(d,e){if(d.schemaVersion!==1||d.sessionId!==e||!Array.isArray(d.files)||d.files.length>de||!Number.isSafeInteger(d.totalBytes)||d.totalBytes<0||d.totalBytes>le)throw new Error("Invalid handoff snapshot manifest");let n=new Set,i=0;for(let t of d.files){if(ue(t.path),!Number.isSafeInteger(t.size)||t.size<0||t.size>ce||!/^[a-f0-9]{64}$/.test(t.sha256)||typeof t.executable!="boolean")throw new Error("Invalid handoff snapshot file");let o=t.path.toLowerCase();if(n.has(o))throw new Error("Snapshot paths collide on Windows");n.add(o),i+=t.size}for(let t of n){let o=t.split("/");for(let r=1;r<o.length;r++)if(n.has(o.slice(0,r).join("/")))throw new Error("Snapshot file conflicts with a directory")}if(i!==d.totalBytes||fe(d)!==d.digest)throw new Error("Handoff snapshot manifest integrity mismatch")}async function z(d,e){let n=d;for(let o of e.split("/"))if(n=(0,I.join)(n,o),(await(0,E.lstat)(n)).isSymbolicLink())throw new Error("Snapshot symlinks are not supported");let i=await(0,E.realpath)(n),t=(0,I.relative)(d,i);if(t===".."||t.startsWith(`..${I.sep}`)||(0,I.isAbsolute)(t))throw new Error("Snapshot path escaped its root");return n}async function ke(d){if(!d.sessionId||d.sessionId.length>1024||d.paths.length>de)throw new Error("Invalid snapshot scope");let e=await(0,E.realpath)(d.root),n=[],i=new Map,t=0;for(let r of[...d.paths].sort()){if(d.signal?.throwIfAborted(),ue(r),!await d.authorizeFile(r))throw new Error("Snapshot file transfer is not authorized");let s=await z(e,r),a=await(0,E.lstat)(s),c=await(0,E.open)(s,Q.constants.O_RDONLY|(Q.constants.O_NOFOLLOW??0));try{let u=await c.stat();if(await z(e,r),a.ino!==u.ino||a.dev!==u.dev||a.ctimeMs!==u.ctimeMs)throw new Error("Snapshot source was replaced before reading");if(!u.isFile()||u.size>ce||t+u.size>le)throw new Error("Snapshot file or total byte limit exceeded");let f=Buffer.alloc(u.size),m=0;for(;m<f.length;){d.signal?.throwIfAborted();let{bytesRead:J}=await c.read(f,m,f.length-m,m);if(!J)throw new Error("Snapshot source changed while reading");m+=J}let b=await c.stat(),R=await(0,E.lstat)(s);if(await z(e,r),u.size!==b.size||u.mtimeMs!==b.mtimeMs||u.ctimeMs!==b.ctimeMs||R.isSymbolicLink()||R.ino!==u.ino||R.dev!==u.dev)throw new Error("Snapshot source changed while reading");let N=H(f).value;n.push({path:r,size:f.length,sha256:N,executable:(u.mode&73)!==0}),i.set(N,f),t+=f.length}finally{await c.close()}}let o={schemaVersion:1,sessionId:d.sessionId,files:n,totalBytes:t,digest:""};return o.digest=fe(o),pe(o,d.sessionId),{manifest:o,blobs:i}}async function _e(d){let e=structuredClone(d.manifest);if(pe(e,d.sessionId),!await d.authorizeManifest(structuredClone(e)))throw new Error("Snapshot restoration is not authorized");d.signal?.throwIfAborted();let n=(0,I.resolve)(d.destination);if(await(0,E.realpath)((0,I.dirname)(n))!==(0,I.dirname)(n))throw new Error("Snapshot destination parent must be canonical");try{throw await(0,E.lstat)(n),new Error("Snapshot destination already exists")}catch(r){if(r.code!=="ENOENT")throw r}let t=`${n}.staging-${(0,ae.randomUUID)()}`;await(0,E.mkdir)(t,{mode:448});for(let r of e.files){d.signal?.throwIfAborted();let s=await d.readBlob(r.sha256,r.size);if(s.byteLength!==r.size||H(s).value!==r.sha256)throw new Error("Snapshot blob integrity mismatch; staging retained");let a=(0,I.join)(t,...r.path.split("/"));await(0,E.mkdir)((0,I.dirname)(a),{recursive:!0,mode:448});let c=await(0,E.open)(a,"wx",r.executable?448:384);try{await c.writeFile(s),await c.sync()}finally{await c.close()}}d.signal?.throwIfAborted();let o=await(0,E.open)((0,I.join)(t,".xeno-handoff-ready"),"wx",384);try{await o.writeFile(JSON.stringify({digest:e.digest,sessionId:e.sessionId})),await o.sync()}finally{await o.close()}return{directory:t,digest:e.digest,files:e.files.length,bytes:e.totalBytes}}var he=require("node:crypto"),me=/^sha256:[0-9a-f]{64}$/;function Pe(d){return typeof d=="string"&&me.test(d)}function De(d){return`sha256:${(0,he.createHash)("sha256").update(d).digest("hex")}`}0&&(module.exports={DurableXenoCoordinationStore,XENO_CONTEXT_DIGEST_PATTERN,XENO_COORDINATION_BUDGET_SESSION_SCHEMA_VERSION,XENO_COORDINATION_MANAGED_SESSION_SCHEMA_VERSION,XENO_COORDINATION_SCHEMA_VERSION,XENO_COORDINATION_TURN_SESSION_SCHEMA_VERSION,XenoCoordinationError,XenoExecutionLeaseSession,captureXenoHandoffSnapshot,computeXenoContextDigest,executeXenoCoordinationAction,isXenoContextDigest,restoreXenoHandoffSnapshot,waitForXenoHandoffStatus});