@xenosystem/agent-sdk 0.9.38 → 0.9.39

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 (66) hide show
  1. package/dist/artifacts/browser.cjs +1 -1
  2. package/dist/artifacts/browser.d.cts +2 -2
  3. package/dist/artifacts/browser.d.ts +2 -2
  4. package/dist/artifacts/browser.js +1 -1
  5. package/dist/artifacts/{diff-artifact-CmhmeSu5.d.cts → diff-artifact--7QTtOxh.d.cts} +2 -1
  6. package/dist/artifacts/{diff-artifact-CmhmeSu5.d.ts → diff-artifact--7QTtOxh.d.ts} +2 -1
  7. package/dist/artifacts/index.cjs +10 -9
  8. package/dist/artifacts/index.d.cts +94 -3
  9. package/dist/artifacts/index.d.ts +94 -3
  10. package/dist/artifacts/index.js +10 -9
  11. package/dist/artifacts/metafile-cjs.json +1 -1
  12. package/dist/artifacts/metafile-esm.json +1 -1
  13. package/dist/automation/index.cjs +2 -2
  14. package/dist/automation/index.d.cts +2 -1
  15. package/dist/automation/index.d.ts +2 -1
  16. package/dist/automation/index.js +2 -2
  17. package/dist/automation/metafile-cjs.json +1 -1
  18. package/dist/automation/metafile-esm.json +1 -1
  19. package/dist/control-plane/index.cjs +8 -7
  20. package/dist/control-plane/index.d.cts +171 -1
  21. package/dist/control-plane/index.d.ts +171 -1
  22. package/dist/control-plane/index.js +8 -7
  23. package/dist/control-plane/metafile-cjs.json +1 -1
  24. package/dist/control-plane/metafile-esm.json +1 -1
  25. package/dist/coordination/index.cjs +2 -2
  26. package/dist/coordination/index.d.cts +85 -2
  27. package/dist/coordination/index.d.ts +85 -2
  28. package/dist/coordination/index.js +2 -2
  29. package/dist/coordination/metafile-cjs.json +1 -1
  30. package/dist/coordination/metafile-esm.json +1 -1
  31. package/dist/electron/index.cjs +48 -48
  32. package/dist/electron/index.d.cts +7 -1
  33. package/dist/electron/index.d.ts +7 -1
  34. package/dist/electron/index.js +48 -48
  35. package/dist/electron/metafile-cjs.json +1 -1
  36. package/dist/electron/metafile-esm.json +1 -1
  37. package/dist/index.cjs +343 -341
  38. package/dist/index.d.cts +443 -5
  39. package/dist/index.d.ts +443 -5
  40. package/dist/index.js +343 -341
  41. package/dist/metafile-cjs.json +1 -1
  42. package/dist/metafile-esm.json +1 -1
  43. package/dist/oracle/index.cjs +1 -1
  44. package/dist/oracle/index.d.cts +2 -1
  45. package/dist/oracle/index.d.ts +2 -1
  46. package/dist/oracle/index.js +1 -1
  47. package/dist/oracle/metafile-cjs.json +1 -1
  48. package/dist/oracle/metafile-esm.json +1 -1
  49. package/dist/recipes/index.cjs +2 -2
  50. package/dist/recipes/index.js +2 -2
  51. package/dist/recipes/metafile-cjs.json +1 -1
  52. package/dist/recipes/metafile-esm.json +1 -1
  53. package/dist/research/index.cjs +3 -3
  54. package/dist/research/index.d.cts +2 -1
  55. package/dist/research/index.d.ts +2 -1
  56. package/dist/research/index.js +3 -3
  57. package/dist/research/metafile-cjs.json +1 -1
  58. package/dist/research/metafile-esm.json +1 -1
  59. package/dist/session/index.cjs +12 -12
  60. package/dist/session/index.d.cts +7 -1
  61. package/dist/session/index.d.ts +7 -1
  62. package/dist/session/index.js +9 -9
  63. package/dist/session/metafile-cjs.json +1 -1
  64. package/dist/session/metafile-esm.json +1 -1
  65. package/ownership/audit.mjs +6 -0
  66. package/package.json +1 -1
@@ -183,6 +183,8 @@ interface XenoHandoffRecord {
183
183
  sourceOwnerId: string;
184
184
  targetOwnerId?: string;
185
185
  claimedBy?: string;
186
+ claimRequestId?: string;
187
+ prepareRequestId?: string;
186
188
  sourceLeaseEpoch: number;
187
189
  targetLeaseEpoch?: number;
188
190
  workspace?: string;
@@ -273,6 +275,7 @@ interface CreateXenoHandoffInput {
273
275
  sessionId: string;
274
276
  sourceOwnerId: string;
275
277
  sourceLeaseId: string;
278
+ prepareRequestId?: string;
276
279
  goalId?: string;
277
280
  loopId?: string;
278
281
  targetOwnerId?: string;
@@ -312,6 +315,8 @@ interface ClaimXenoHandoffInput {
312
315
  targetOwnerId: string;
313
316
  processId?: number;
314
317
  host?: string;
318
+ leaseMs?: number;
319
+ claimRequestId?: string;
315
320
  }
316
321
  declare class DurableXenoCoordinationStore {
317
322
  get goalTurnAdmissionVersion(): 1;
@@ -361,6 +366,8 @@ declare class DurableXenoCoordinationStore {
361
366
  beginLoopIteration(sessionId: string, loopId: string, expectedVersion: number, activity: string, taskId?: string): Promise<XenoLoopRecord>;
362
367
  private appendLoopIteration;
363
368
  admitGoalTurn(input: XenoGoalTurnRequest): Promise<XenoGoalTurnAdmission>;
369
+ admitOwnedGoalTurn(input: XenoGoalTurnRequest, authority: Pick<XenoExecutionOwner, "ownerId" | "leaseId" | "epoch">): Promise<XenoGoalTurnAdmission>;
370
+ private admitGoalTurnWithOwner;
364
371
  getGoalTurnState(sessionId: string, goalId?: string, requestId?: string): Promise<XenoGoalTurnState | undefined>;
365
372
  finishGoalTurn(input: Omit<XenoGoalTurnRequest, "expectedGoalVersion"> & {
366
373
  status: "completed" | "failed" | "interrupted";
@@ -430,8 +437,9 @@ interface ExecuteXenoCoordinationActionResult {
430
437
  event?: XenoCoordinationEvent;
431
438
  }
432
439
  declare function executeXenoCoordinationAction(store: DurableXenoCoordinationStore, input: ExecuteXenoCoordinationActionInput): Promise<ExecuteXenoCoordinationActionResult>;
440
+ type XenoExecutionLeaseStore = Pick<DurableXenoCoordinationStore, "acquireOwnership" | "claimHandoff" | "completeHandoff" | "renewOwnership" | "releaseOwnership" | "createHandoff">;
433
441
  interface XenoExecutionLeaseSessionOptions {
434
- store?: DurableXenoCoordinationStore;
442
+ store?: XenoExecutionLeaseStore;
435
443
  sessionId: string;
436
444
  ownerId?: string;
437
445
  processId?: number;
@@ -439,6 +447,12 @@ interface XenoExecutionLeaseSessionOptions {
439
447
  leaseMs?: number;
440
448
  heartbeatMs?: number;
441
449
  claimHandoffId?: string;
450
+ claimRequestId?: string;
451
+ prepareDestination?: (input: {
452
+ handoff: XenoHandoffRecord;
453
+ signal: AbortSignal;
454
+ }) => Promise<void>;
455
+ destinationTimeoutMs?: number;
442
456
  onOwnershipLost?: (error: unknown) => void;
443
457
  }
444
458
  declare class XenoExecutionLeaseSession {
@@ -450,24 +464,93 @@ declare class XenoExecutionLeaseSession {
450
464
  private readonly leaseMs;
451
465
  private readonly heartbeatMs;
452
466
  private readonly claimHandoffId?;
467
+ private readonly claimRequestId?;
453
468
  private readonly onOwnershipLost?;
469
+ private readonly prepareDestination?;
470
+ private readonly destinationTimeoutMs;
471
+ private readonly initializationAbort;
454
472
  private timer?;
455
473
  private heartbeatInFlight;
456
474
  private owner?;
475
+ private ready;
476
+ private starting?;
477
+ private stopping?;
457
478
  private stopped;
458
479
  private lostError?;
459
480
  private preparedHandoffId?;
481
+ private preparingHandoff;
482
+ private handoffOutcomeUncertain;
460
483
  constructor(options: XenoExecutionLeaseSessionOptions);
461
484
  get currentOwner(): XenoExecutionOwner | undefined;
462
485
  get active(): boolean;
463
486
  start(): Promise<XenoExecutionOwner>;
487
+ private initialize;
488
+ private prepareClaimedDestination;
464
489
  assertOwned(): Promise<XenoExecutionOwner>;
490
+ private assertExecutionAllowed;
465
491
  private renewHeldLease;
466
492
  prepareHandoff(input?: Omit<CreateXenoHandoffInput, "sessionId" | "sourceOwnerId" | "sourceLeaseId">): Promise<XenoHandoffRecord>;
467
493
  stop(options?: {
468
494
  release?: boolean;
469
495
  }): Promise<void>;
496
+ private finishStop;
470
497
  private heartbeat;
471
498
  private markLost;
472
499
  }
473
- export { type ClaimXenoHandoffInput, type CreateXenoGoalInput, type CreateXenoHandoffInput, DurableXenoCoordinationStore, type ExecuteXenoCoordinationActionInput, type ExecuteXenoCoordinationActionResult, type StartXenoLoopInput, type UpdateXenoGoalInput, XENO_COORDINATION_BUDGET_SESSION_SCHEMA_VERSION, XENO_COORDINATION_MANAGED_SESSION_SCHEMA_VERSION, XENO_COORDINATION_SCHEMA_VERSION, XENO_COORDINATION_TURN_SESSION_SCHEMA_VERSION, type XenoCoordinationAction, type XenoCoordinationAdmissionFence, XenoCoordinationError, type XenoCoordinationEvent, type XenoCoordinationEventType, type XenoCoordinationSessionState, type XenoCoordinationStoreOptions, XenoExecutionLeaseSession, type XenoExecutionLeaseSessionOptions, type XenoExecutionOwner, type XenoGoalCriterion, type XenoGoalCriterionResult, type XenoGoalMilestone, type XenoGoalProgress, type XenoGoalRecord, type XenoGoalStatus, type XenoGoalTask, type XenoGoalTaskStatus, type XenoGoalTurnAdmission, type XenoGoalTurnRequest, type XenoGoalTurnState, type XenoGoalVerification, type XenoHandoffOperation, type XenoHandoffRecord, type XenoHandoffStatus, type XenoLoopIteration, type XenoLoopKind, type XenoLoopRecord, type XenoLoopSchedule, type XenoLoopStatus, executeXenoCoordinationAction };
500
+ interface XenoHandoffStatusInput {
501
+ sessionId: string;
502
+ handoffId: string;
503
+ sinceRevision?: string;
504
+ waitMs?: number;
505
+ signal?: AbortSignal;
506
+ }
507
+ interface XenoHandoffStatusReceipt {
508
+ sessionId: string;
509
+ handoffId: string;
510
+ revision: string;
511
+ changed: boolean;
512
+ status: XenoHandoffRecord["status"];
513
+ handoffVersion: number;
514
+ ownershipEpoch: number;
515
+ sourceOwnerId: string;
516
+ targetOwnerId?: string;
517
+ }
518
+ declare function waitForXenoHandoffStatus(store: Pick<DurableXenoCoordinationStore, "getSessionState">, input: XenoHandoffStatusInput): Promise<XenoHandoffStatusReceipt>;
519
+ interface XenoHandoffSnapshotFile {
520
+ path: string;
521
+ size: number;
522
+ sha256: string;
523
+ executable: boolean;
524
+ }
525
+ interface XenoHandoffSnapshotManifest {
526
+ schemaVersion: 1;
527
+ sessionId: string;
528
+ files: XenoHandoffSnapshotFile[];
529
+ totalBytes: number;
530
+ digest: string;
531
+ }
532
+ interface XenoHandoffSnapshot {
533
+ manifest: XenoHandoffSnapshotManifest;
534
+ blobs: ReadonlyMap<string, Uint8Array>;
535
+ }
536
+ declare function captureXenoHandoffSnapshot(input: {
537
+ root: string;
538
+ sessionId: string;
539
+ paths: readonly string[];
540
+ authorizeFile(path: string): boolean | Promise<boolean>;
541
+ signal?: AbortSignal;
542
+ }): Promise<XenoHandoffSnapshot>;
543
+ declare function restoreXenoHandoffSnapshot(input: {
544
+ destination: string;
545
+ sessionId: string;
546
+ manifest: XenoHandoffSnapshotManifest;
547
+ authorizeManifest(manifest: XenoHandoffSnapshotManifest): boolean | Promise<boolean>;
548
+ readBlob(sha256: string, expectedBytes: number): Promise<Uint8Array>;
549
+ signal?: AbortSignal;
550
+ }): Promise<{
551
+ directory: string;
552
+ digest: string;
553
+ files: number;
554
+ bytes: number;
555
+ }>;
556
+ export { type ClaimXenoHandoffInput, type CreateXenoGoalInput, type CreateXenoHandoffInput, DurableXenoCoordinationStore, type ExecuteXenoCoordinationActionInput, type ExecuteXenoCoordinationActionResult, type StartXenoLoopInput, type UpdateXenoGoalInput, XENO_COORDINATION_BUDGET_SESSION_SCHEMA_VERSION, XENO_COORDINATION_MANAGED_SESSION_SCHEMA_VERSION, XENO_COORDINATION_SCHEMA_VERSION, XENO_COORDINATION_TURN_SESSION_SCHEMA_VERSION, type XenoCoordinationAction, type XenoCoordinationAdmissionFence, XenoCoordinationError, type XenoCoordinationEvent, type XenoCoordinationEventType, type XenoCoordinationSessionState, type XenoCoordinationStoreOptions, XenoExecutionLeaseSession, type XenoExecutionLeaseSessionOptions, type XenoExecutionLeaseStore, type XenoExecutionOwner, type XenoGoalCriterion, type XenoGoalCriterionResult, type XenoGoalMilestone, type XenoGoalProgress, type XenoGoalRecord, type XenoGoalStatus, type XenoGoalTask, type XenoGoalTaskStatus, type XenoGoalTurnAdmission, type XenoGoalTurnRequest, type XenoGoalTurnState, type XenoGoalVerification, type XenoHandoffOperation, type XenoHandoffRecord, type XenoHandoffSnapshot, type XenoHandoffSnapshotFile, type XenoHandoffSnapshotManifest, type XenoHandoffStatus, type XenoHandoffStatusInput, type XenoHandoffStatusReceipt, type XenoLoopIteration, type XenoLoopKind, type XenoLoopRecord, type XenoLoopSchedule, type XenoLoopStatus, captureXenoHandoffSnapshot, executeXenoCoordinationAction, restoreXenoHandoffSnapshot, waitForXenoHandoffStatus };
@@ -1,2 +1,2 @@
1
- var w=1,L=2,S=3,X=4,d=class extends Error{constructor(o,i,e={}){super(i);this.code=o;this.details=e;this.name="XenoCoordinationError"}code;details};import{createHash as $,randomUUID as N}from"node:crypto";import*as f from"node:fs/promises";import*as v from"node:os";import*as I from"node:path";import{homedir as R,platform as P,release as q}from"node:os";import{resolve as G}from"node:path";var ie=P();var se=q(),ae=R();function _(){let l=process.env.XENO_AGENT_HOME?.trim();return l?G(l):G(R(),".xeno-agent")}var U=3e4,B=3e4,j=6e4,W=2e4,b=new Set(["EACCES","EBUSY","EPERM"]),D=[5,10,20,40,80,160,320],J=[5,10,20,40,80,160,320],V=[1,2,3,4];function p(l,t,o=16384){let i=l.trim();if(!i||i.length>o)throw new d("INVALID",`${t} must be non-empty and no longer than ${o} characters`);return i}function C(l,t){return[...new Set((l??[]).map(o=>p(o,t)))]}function F(l){if(l===void 0)return;if(!l||typeof l!="object"||Array.isArray(l))throw new d("INVALID","Goal limits must be an object when provided");let t={};for(let[o,i]of Object.entries(l)){if(o!=="maxIterations"&&o!=="maxTokens"&&o!=="maxWallClockMs")throw new d("INVALID","Unknown goal limit");if(i!==void 0){if(!Number.isSafeInteger(i)||i<=0)throw new d("INVALID",`${o} must be a positive safe integer when provided`);t[o]=i}}return t}function K(l){if(l){if(l.kind!=="fixed-interval"&&l.kind!=="dynamic")throw new d("INVALID","schedule.kind must be fixed-interval or dynamic");if(l.kind==="fixed-interval"&&(!Number.isSafeInteger(l.intervalMs)||(l.intervalMs??0)<=0))throw new d("INVALID","Fixed-interval schedules require a positive safe intervalMs");if(l.intervalMs!==void 0&&(!Number.isSafeInteger(l.intervalMs)||l.intervalMs<=0))throw new d("INVALID","schedule.intervalMs must be a positive safe integer when provided");for(let t of["nextRunAt","expiresAt"]){let o=l[t];if(o!==void 0&&!Number.isFinite(Date.parse(o)))throw new d("INVALID",`schedule.${t} must be an ISO timestamp when provided`)}return m(l)}}function m(l){return structuredClone(l)}function y(l){let t=Date.parse(l);return Number.isFinite(t)?t:0}function x(l){if(!Number.isInteger(l)||l<=0)return!1;try{return process.kill(l,0),!0}catch(t){return t.code==="EPERM"}}function Y(l){return{summary:"Goal created; work has not started.",completedTaskCount:0,totalTaskCount:0,outstanding:[],decisions:[],updatedAt:l}}function z(){return{status:"pending",criteria:[],evidence:[]}}function Q(l){return $("sha256").update(l).digest("hex")}var T=class{get goalTurnAdmissionVersion(){return 1}rootDirectory;now;idFactory;ownerLeaseMs;lockTimeoutMs;lockStaleMs;maximumEventsPerSession;constructor(t={}){this.rootDirectory=t.rootDirectory??I.join(_(),"coordination"),this.now=t.now??(()=>new Date().toISOString()),this.idFactory=t.idFactory??(o=>`${o}_${N()}`),this.ownerLeaseMs=t.ownerLeaseMs??U,this.lockTimeoutMs=t.lockTimeoutMs??B,this.lockStaleMs=t.lockStaleMs??j,this.maximumEventsPerSession=t.maximumEventsPerSession??W}async getSessionState(t){let o=p(t,"sessionId",1024);return m(await this.readState(o))}async fenceAdmission(t,o,i){let e=p(i.authorityId,"authorityId",512),n=p(i.operationId,"operationId",512);if(!Number.isSafeInteger(o)||o<0)throw new d("INVALID","Expected session version must be a nonnegative safe integer");if(i.action!=="archive"&&i.action!=="delete")throw new d("INVALID","Unsupported admission fence action");return this.mutate(t,r=>{let s=r.admissionFence;if(s?.authorityId===e&&s.operationId===n&&s.action===i.action)return s;if(r.version!==o)throw new d("CONFLICT","Session version changed before lifecycle fencing",{expected:o,actual:r.version});if(s?.authorityId===e&&s.action==="archive"&&i.action==="archive")return s;if(s&&!(s.authorityId===e&&s.action==="archive"&&i.action==="delete"))throw new d("CONFLICT","Another lifecycle fence already owns this session");let a={schemaVersion:1,authorityId:e,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:e,operationId:n,action:i.action}}),a},!0)}async clearAdmissionFence(t,o,i,e){await this.mutate(t,n=>{this.assertVersion(t,n.version,o);let r=n.admissionFence;if(!r||r.authorityId!==i||r.operationId!==e)throw new d("CONFLICT","Lifecycle fence identity does not match");if(r.action==="delete")throw new d("CONFLICT","Deleted session admission cannot be restored");if(n.owner)throw new d("CONFLICT","Execution ownership must settle before restoration");n.admissionFence=void 0,this.appendEvent(n,"admission.restored",{data:{authorityId:i,operationId:e}})},!0)}async releaseDeadLifecycleOwner(t,o,i,e){await this.mutate(t,n=>{this.assertVersion(t,n.version,o);let r=n.admissionFence;if(!r||r.authorityId!==i||r.operationId!==e)throw new d("CONFLICT","Lifecycle fence identity does not match");let s=n.owner;if(s){if(s.host!==v.hostname()||!Number.isInteger(s.processId)||(s.processId??0)<=0||x(s.processId))throw new d("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 t=I.join(this.rootDirectory,"sessions"),o;try{o=await f.readdir(t)}catch(e){if(e.code==="ENOENT")return[];throw e}return(await Promise.all(o.filter(e=>e.endsWith(".json")).map(async e=>{try{let n=JSON.parse(await f.readFile(I.join(t,e),"utf8"));return!V.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(e=>e!==void 0).sort((e,n)=>y(n.updatedAt)-y(e.updatedAt)).map(e=>m(e))}async createGoal(t){let o=p(t.sessionId,"sessionId",1024),i=F(t.limits);return this.mutate(o,e=>{let n=e.goals.find(c=>["active","paused","waiting","blocked"].includes(c.status));if(n)throw new d("CONFLICT",`Session ${o} already has active goal ${n.id}`);let r=this.now(),s=(t.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(t.objective,"objective"),...t.why?{why:p(t.why,"why")}:{},successCriteria:s,constraints:C(t.constraints,"constraints"),...i?{limits:i}:{},metadata:m(t.metadata??{}),status:"active",milestones:[],tasks:[],progress:Y(r),verification:z(),steering:[],createdAt:r,updatedAt:r};return e.goals.push(a),this.appendEvent(e,"goal.created",{goalId:a.id,data:{objective:a.objective}}),a})}async getGoal(t,o){let i=await this.getSessionState(t),e=o?i.goals.find(n=>n.id===o):[...i.goals].reverse().find(n=>["active","paused","waiting","blocked"].includes(n.status));return e?m(e):void 0}async updateGoal(t,o,i,e){return this.mutate(t,n=>{let r=this.requireGoal(n,o);if(this.assertVersion(r.id,r.version,i),["completed","cancelled","failed"].includes(r.status))throw new d("CONFLICT",`Goal ${r.id} is terminal (${r.status})`);let s=r.status!=="active";if(e.status==="active"&&r.status==="blocked"?r.status="active":e.status&&(r.status=e.status),e.objective!==void 0&&(r.objective=p(e.objective,"objective")),e.why!==void 0&&(r.why=p(e.why,"why")),e.constraints&&(r.constraints=C(e.constraints,"constraints")),e.successCriteria&&(r.successCriteria=m(e.successCriteria)),e.progress&&(r.progress={...r.progress,...m(e.progress),outstanding:C(e.progress.outstanding??r.progress.outstanding,"progress.outstanding"),decisions:C(e.progress.decisions??r.progress.decisions,"progress.decisions"),updatedAt:this.now()}),e.verification&&(r.verification=m(e.verification)),e.metadata&&(r.metadata=m(e.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},e.status!==void 0&&["paused","cancelled","failed"].includes(e.status))}async addMilestone(t,o,i,e){return this.mutateGoal(t,o,i,(n,r)=>{let s={id:this.idFactory("milestone"),title:p(e.title,"milestone.title"),...e.description?{description:p(e.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(t,o,i,e){return this.mutateGoal(t,o,i,(n,r)=>{let s=n.milestones.find(u=>u.id===e.milestoneId);if(!s)throw new d("NOT_FOUND",`Milestone ${e.milestoneId} was not found`);if(e.parentTaskId&&!n.tasks.some(u=>u.id===e.parentTaskId))throw new d("NOT_FOUND",`Parent task ${e.parentTaskId} was not found`);let a=[...new Set(e.dependsOn??[])];for(let u of a)if(!n.tasks.some(h=>h.id===u))throw new d("NOT_FOUND",`Task dependency ${u} was not found`);let c={id:this.idFactory("task"),milestoneId:s.id,...e.parentTaskId?{parentTaskId:e.parentTaskId}:{},title:p(e.title,"task.title"),...e.description?{description:p(e.description,"task.description")}:{},status:a.length===0?"ready":"pending",...e.assignedAgentId?{assignedAgentId:p(e.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(u=>u.status!=="completed").map(u=>u.title),n.progress.updatedAt=r})}async updateTask(t,o,i,e,n){return this.mutateGoal(t,o,e,(r,s)=>{let a=r.tasks.find(u=>u.id===i);if(!a)throw new d("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(u=>u.id===a.milestoneId);if(c){let u=r.tasks.filter(h=>h.milestoneId===c.id);u.length>0&&u.every(h=>h.status==="completed")?(c.status="completed",c.completedAt=s):u.some(h=>h.status==="running")?c.status="active":u.some(h=>h.status==="blocked")&&(c.status="blocked"),c.updatedAt=s}for(let u of r.tasks)u.status!=="pending"||!u.dependsOn?.length||u.dependsOn.every(h=>r.tasks.find(O=>O.id===h)?.status==="completed")&&(u.status="ready",u.updatedAt=s);this.recalculateProgress(r,s)})}async steerGoal(t,o,i,e){return this.mutateGoal(t,o,i,(n,r,s)=>{let a=this.idFactory("steer");n.steering.push({id:a,instruction:p(e,"instruction"),createdAt:r}),this.appendEvent(s,"goal.steered",{goalId:o,data:{steeringId:a}})},!1)}async consumeGoalSteering(t,o,i){let e=[];return{goal:await this.mutateGoal(t,o,i,(r,s)=>{e=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:e}}async completeGoal(t,o,i,e){if(e.status!=="passed")throw new d("VERIFICATION_REQUIRED","Goal completion requires passed verification");return this.mutate(t,n=>{let r=this.requireGoal(n,o);this.assertVersion(r.id,r.version,i);let s=r.successCriteria.filter(u=>u.required),a=s.filter(u=>{let h=e.criteria.find(O=>O.criterionId===u.id);return!h?.satisfied||h.evidence.length===0});if(a.length>0)throw new d("VERIFICATION_REQUIRED","Required success criteria lack passing evidence",{unmetCriteria:a.map(u=>u.id)});if(s.length===0&&e.evidence.length===0)throw new d("VERIFICATION_REQUIRED","Goal completion requires at least one durable evidence reference");let c=this.now();return r.status="completed",r.verification=m(e),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(t,o,i,e){return this.mutate(t,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(e,"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: ${e}`,s.stoppedAt=this.now(),s.updatedAt=s.stoppedAt,s.version+=1;return r},!0)}async startLoop(t){return this.mutate(t.sessionId,o=>this.createLoopRecord(o,t))}createLoopRecord(t,o){if(o.kind==="goal-continuation"&&!o.goalId)throw new d("INVALID","Goal-continuation loops require a goalId");if(o.goalId){let s=this.requireGoal(t,o.goalId);if(["completed","cancelled","failed"].includes(s.status))throw new d("CONFLICT",`Cannot start a loop for terminal goal ${s.id}`)}if(o.kind==="scheduled"&&!o.schedule)throw new d("INVALID","Scheduled loops require schedule metadata");if(o.kind!=="scheduled"&&o.schedule)throw new d("INVALID","Only scheduled loops may carry schedule metadata");let i=K(o.schedule),e=t.loops.find(s=>s.goalId===o.goalId&&s.kind===o.kind&&["running","paused","waiting"].includes(s.status));if(e)throw new d("CONFLICT",`Loop ${e.id} is already active`);let n=this.now(),r={schemaVersion:1,id:this.idFactory("loop"),version:1,sessionId:t.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 t.loops.push(r),this.appendEvent(t,"loop.started",{loopId:r.id,goalId:r.goalId,data:{kind:r.kind}}),r}async getLoop(t,o){let i=await this.getSessionState(t),e=o?i.loops.find(n=>n.id===o):[...i.loops].reverse().find(n=>["running","paused","waiting"].includes(n.status));return e?m(e):void 0}async beginLoopIteration(t,o,i,e,n){return this.mutateLoop(t,o,i,(r,s,a)=>{this.appendLoopIteration(a,r,s,e,n)},!1)}appendLoopIteration(t,o,i,e,n){if(o.status!=="running")throw new d("CONFLICT",`Loop ${o.id} is ${o.status}`);if(o.goalId){let a=this.requireGoal(t,o.goalId);this.isCliGoal(a)&&this.initializeGoalTurnAccounting(t,a)}if(this.assertGoalIterationAdmission(t,o,i),o.iterations.some(a=>a.status==="running"))throw new d("CONFLICT",`Loop ${o.id} already has a running iteration`);let r=(o.iterations.at(-1)?.number??0)+1;o.currentActivity=p(e,"activity");let s={number:r,startedAt:i,status:"running",activity:o.currentActivity,...o.goalId&&t.goalTurnAccounting?.[o.goalId]?{goalAccountingVersion:1}:{},...n?{taskId:p(n,"taskId",512)}:{}};return o.iterations.push(s),o.resumeRequested!==void 0&&(o.resumeRequested=!1),this.appendEvent(t,"loop.iteration",{loopId:o.id,goalId:o.goalId,data:{number:r,phase:"started",activity:o.currentActivity}}),s}async admitGoalTurn(t){let o=p(t.requestId,"requestId",512),i=this.goalTurnHash(t.requestHash);return this.mutate(t.sessionId,e=>{let n=this.requireGoal(e,t.goalId);for(let c of e.loops.filter(u=>u.goalId===n.id)){let u=c.iterations.find(h=>h.goalTurn?.requestId===o);if(u){if(u.goalTurn?.requestHash!==i)throw new d("CONFLICT","Goal turn identity was reused for different work");return{...this.goalTurnState(e,n,c,u),admitted:!1}}}if(this.assertVersion(n.id,n.version,t.expectedGoalVersion),n.status!=="active")throw new d("CONFLICT",`Goal ${n.id} is ${n.status}`);let r=[...e.loops].reverse().find(c=>c.goalId===n.id&&c.kind==="goal-continuation");if(t.expectedLoopId!==void 0){if(!r||r.id!==t.expectedLoopId)throw new d("CONFLICT","Goal continuation loop changed before admission");this.assertVersion(r.id,r.version,t.expectedLoopVersion??-1)}else if(t.expectedLoopVersion!==void 0)throw new d("INVALID","A goal turn loop version requires its exact loop ID");if(r&&r.status!=="running")throw new d("CONFLICT",`Goal loop ${r.id} is ${r.status}; resume or start it explicitly`);this.initializeGoalTurnAccounting(e,n),r??=this.createLoopRecord(e,{sessionId:e.sessionId,goalId:n.id,kind:"goal-continuation"});let s=this.now(),a=this.appendLoopIteration(e,r,s,"Interactive goal turn");if(t.executionKind!==void 0&&t.executionKind!=="local-sdk"&&t.executionKind!=="external")throw new d("INVALID","Unknown goal execution lane");return a.goalTurn={requestId:o,requestHash:i,executor:t.executionKind==="local-sdk"?{kind:"local-sdk",processId:process.pid,host:v.hostname()}:{kind:"external"}},r.version+=1,r.updatedAt=s,{...this.goalTurnState(e,n,r,a),admitted:!0}},!1,e=>e.admitted)}async getGoalTurnState(t,o,i){let e=await this.getSessionState(t),n=o?e.goals.find(c=>c.id===o):[...e.goals].reverse().find(c=>["active","paused","waiting","blocked"].includes(c.status));if(!n)return;let r=e.loops.filter(c=>c.goalId===n.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 d("NOT_FOUND","Goal turn was not found");return this.goalTurnState(e,n,s,a)}async finishGoalTurn(t){if(!["completed","failed","interrupted"].includes(t.status))throw new d("INVALID","Invalid goal turn outcome");let o=this.goalTurnHash(t.requestHash);return this.mutate(t.sessionId,i=>{let e=this.requireGoal(i,t.goalId),n=i.loops.find(s=>s.goalId===e.id&&s.iterations.some(a=>a.goalTurn?.requestId===t.requestId)),r=n?.iterations.find(s=>s.goalTurn?.requestId===t.requestId);if(!n||!r)throw new d("NOT_FOUND","Goal turn was not found");if(r.goalTurn?.requestHash!==o)throw new d("CONFLICT","Goal turn settlement identity does not match");return r.status==="running"&&(this.settleLoopIteration(i,n,r,this.now(),{status:e.status==="cancelled"||["stopped","failed"].includes(n.status)?"interrupted":t.status}),n.version+=1,n.updatedAt=this.now()),this.goalTurnState(i,e,n,r)},!0)}async recoverGoalTurn(t,o,i){return this.mutate(t,e=>{let n=this.requireGoal(e,o),r=e.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 d("NOT_FOUND","Goal turn was not found");if(s.status==="running"){if(!this.goalTurnOwnerExited(s))throw new d("NOT_OWNER","The original local goal executor has not been proved exited; external execution requires reconciliation");this.settleLoopIteration(e,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(e,n,r,s)},!0)}async finishLoopIteration(t,o,i,e){return this.mutateLoop(t,o,i,(n,r,s)=>{let a=[...n.iterations].reverse().find(c=>c.status==="running");if(!a)throw new d("CONFLICT",`Loop ${n.id} has no running iteration`);this.settleLoopIteration(s,n,a,r,e)},!1,!0)}settleLoopIteration(t,o,i,e,n){i.status=n.status,i.completedAt=e,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:t.admissionFence?"paused":n.nextStatus??(o.status==="paused"||o.status==="waiting"?o.status:"running"),this.appendEvent(t,"loop.iteration",{loopId:o.id,goalId:o.goalId,data:{number:i.number,phase:"finished",status:n.status}})}async setLoopStatus(t,o,i,e,n){return this.mutateLoop(t,o,i,(r,s,a)=>{let c=r.status;if(["stopped","completed","failed"].includes(c))throw new d("CONFLICT",`Loop ${r.id} is terminal (${c})`);let u=[...r.iterations].reverse().find(O=>O.status==="running");if(u&&e==="completed")throw new d("CONFLICT",`Loop ${r.id} cannot complete while iteration ${u.number} is running`);u&&(e==="stopped"||e==="failed")&&(u.status=e==="failed"?"failed":"interrupted",u.completedAt=s,u.error=p(n??e,"reason")),r.status=e,r.kind==="goal-continuation"&&(r.resumeRequested=e==="running"),["stopped","completed","failed"].includes(e)&&(r.stoppedAt=s,r.stopReason=p(n??e,"reason"));let h=e==="paused"?"loop.paused":e==="waiting"?"loop.waiting":e==="running"&&(c==="paused"||c==="waiting")?"loop.resumed":e==="completed"?"loop.completed":e==="failed"?"loop.failed":"loop.stopped";this.appendEvent(a,h,{loopId:o,goalId:r.goalId,data:{previous:c,status:e,...n?{reason:n}:{}}})},!1,e!=="running"&&e!=="waiting")}async acquireOwnership(t,o,i={}){return this.mutate(t,e=>{let n=this.now();if(e.owner&&!this.ownerExpired(e.owner,n)){if(e.owner.ownerId===o&&i.processId!==void 0&&e.owner.processId===i.processId&&(i.host===void 0||e.owner.host===i.host))return e.owner;throw new d("CONFLICT",`Session ${t} is owned by ${e.owner.ownerId}`,{owner:e.owner})}let r=e.owner&&this.ownerExpired(e.owner,n)?e.owner:void 0;if(r&&r.ownerId!==o)for(let c of e.handoffs.filter(u=>u.status==="claimed"&&u.claimedBy===r.ownerId))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(e,"handoff.failed",{handoffId:c.id,goalId:c.goalId,loopId:c.loopId,data:{reason:c.failureReason,expiredLeaseId:r.leaseId}});let s=e.ownershipEpoch+1,a=this.newOwner(o,s,i,n);return e.owner=a,e.ownershipEpoch=s,this.appendEvent(e,"ownership.acquired",{ownerId:o,data:{epoch:s,leaseId:a.leaseId}}),a})}async renewOwnership(t,o,i,e=this.ownerLeaseMs){return this.mutate(t,n=>{let r=this.requireOwner(n,o,i);if(this.ownerExpired(r,this.now()))throw new d("LEASE_EXPIRED",`Ownership lease ${i} expired`);return r.heartbeatAt=this.now(),r.expiresAt=new Date(y(r.heartbeatAt)+e).toISOString(),this.appendEvent(n,"ownership.renewed",{ownerId:o,data:{epoch:r.epoch,leaseId:i}}),r})}async releaseOwnership(t,o,i){return this.mutate(t,e=>{let n=this.requireOwner(e,o,i);return e.owner=void 0,this.appendEvent(e,"ownership.released",{ownerId:o,data:{epoch:n.epoch}}),n},!0)}async createHandoff(t){return this.mutate(t.sessionId,o=>{let i=this.requireOwner(o,t.sourceOwnerId,t.sourceLeaseId);if(this.ownerExpired(i,this.now()))throw new d("LEASE_EXPIRED",`Ownership lease ${i.leaseId} expired`);let e=(t.operations??[]).filter(a=>a.status==="running"&&a.sideEffecting&&a.recovery==="retry");if(e.length>0)throw new d("UNSAFE_HANDOFF","Running side-effecting operations cannot be transferred with automatic retry",{operationIds:e.map(a=>a.operationId)});if(t.goalId&&this.requireGoal(o,t.goalId),t.loopId&&!o.loops.some(a=>a.id===t.loopId))throw new d("NOT_FOUND",`Loop ${t.loopId} was not found`);let n=o.handoffs.find(a=>["prepared","available","claimed"].includes(a.status));if(n)throw new d("CONFLICT",`Handoff ${n.id} is already active`);let r=this.now(),s={schemaVersion:1,id:this.idFactory("handoff"),version:1,sessionId:o.sessionId,...t.goalId?{goalId:t.goalId}:{},...t.loopId?{loopId:t.loopId}:{},status:"available",sourceOwnerId:i.ownerId,...t.targetOwnerId?{targetOwnerId:p(t.targetOwnerId,"targetOwnerId",512)}:{},sourceLeaseEpoch:i.epoch,...t.workspace?{workspace:p(t.workspace,"workspace",32768)}:{},...t.branch?{branch:p(t.branch,"branch",1024)}:{},...t.currentMilestoneId?{currentMilestoneId:t.currentMilestoneId}:{},...t.currentTaskId?{currentTaskId:t.currentTaskId}:{},agentIds:[...new Set(t.agentIds??[])],operations:m(t.operations??[]),...t.contextDigest?{contextDigest:p(t.contextDigest,"contextDigest",512)}:{},createdAt:r,updatedAt:r};return o.handoffs.push(s),this.appendEvent(o,"handoff.created",{handoffId:s.id,goalId:s.goalId,loopId:s.loopId,ownerId:i.ownerId,data:{targetOwnerId:s.targetOwnerId}}),s})}async claimHandoff(t){let o;return{handoff:await this.mutate(t.sessionId,e=>{let n=e.handoffs.find(a=>a.id===t.handoffId);if(!n)throw new d("NOT_FOUND",`Handoff ${t.handoffId} was not found`);if(n.status!=="available")throw new d("CONFLICT",`Handoff ${n.id} is ${n.status}`,{claimedBy:n.claimedBy});if(n.targetOwnerId&&n.targetOwnerId!==t.targetOwnerId)throw new d("CONFLICT",`Handoff ${n.id} is reserved for ${n.targetOwnerId}`);let r=e.owner;if(!r||r.ownerId!==n.sourceOwnerId||r.epoch!==n.sourceLeaseEpoch)throw new d("CONFLICT",`Handoff ${n.id} no longer matches the source ownership epoch`);let s=this.now();return o=this.newOwner(t.targetOwnerId,r.epoch+1,{processId:t.processId,host:t.host},s),e.owner=o,e.ownershipEpoch=o.epoch,n.status="claimed",n.claimedBy=t.targetOwnerId,n.targetOwnerId=t.targetOwnerId,n.targetLeaseEpoch=o.epoch,n.claimedAt=s,n.updatedAt=s,n.version+=1,this.appendEvent(e,"handoff.claimed",{handoffId:n.id,goalId:n.goalId,loopId:n.loopId,ownerId:t.targetOwnerId,data:{sourceOwnerId:n.sourceOwnerId,epoch:o.epoch}}),n}),owner:m(o)}}async completeHandoff(t,o,i,e){return this.mutate(t,n=>{this.requireOwner(n,i,e);let r=n.handoffs.find(s=>s.id===o);if(!r)throw new d("NOT_FOUND",`Handoff ${o} was not found`);if(r.status!=="claimed"||r.claimedBy!==i)throw new d("CONFLICT",`Handoff ${r.id} cannot be completed by ${i}`);return r.status="completed",r.completedAt=this.now(),r.updatedAt=r.completedAt,r.version+=1,this.appendEvent(n,"handoff.completed",{handoffId:o,goalId:r.goalId,loopId:r.loopId,ownerId:i,data:{epoch:n.owner?.epoch}}),r})}async failHandoff(t,o,i){return this.mutate(t,e=>{let n=e.handoffs.find(r=>r.id===o);if(!n)throw new d("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(e,"handoff.failed",{handoffId:o,goalId:n.goalId,loopId:n.loopId,data:{reason:n.failureReason}})),n},!0)}async mutateGoal(t,o,i,e,n=!0){return this.mutate(t,r=>{let s=this.requireGoal(r,o);this.assertVersion(s.id,s.version,i);let a=this.now();return e(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(t,o,i,e,n=!0,r=!1){return this.mutate(t,s=>{let a=s.loops.find(u=>u.id===o);if(!a)throw new d("NOT_FOUND",`Loop ${o} was not found`);this.assertVersion(a.id,a.version,i);let c=this.now();return e(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(t,o,i){if(!o.goalId)return;let e=this.requireGoal(t,o.goalId);if(e.status!=="active")throw new d("CONFLICT",`Goal ${e.id} is ${e.status}; no iteration was admitted`);let n=F(e.limits);if(n?.maxTokens!==void 0)throw new d("BUDGET_UNAVAILABLE","Goal token allowance is not bound to request-level admission; no iteration was admitted",{goalId:e.id,limit:"maxTokens"});if(n?.maxWallClockMs!==void 0){let r=Date.parse(e.createdAt),s=Date.parse(i);if(!Number.isFinite(r)||!Number.isFinite(s)||s<r)throw new d("BUDGET_UNAVAILABLE","Goal wall-clock allowance cannot be verified",{goalId:e.id,limit:"maxWallClockMs"});if(s-r>=n.maxWallClockMs)throw new d("BUDGET_EXCEEDED","Goal wall-clock limit reached; no iteration was admitted",{goalId:e.id,limit:"maxWallClockMs",maximum:n.maxWallClockMs})}if(n?.maxIterations!==void 0){let r=t.goalTurnAccounting!==void 0||t.schemaVersion===4?this.resolveGoalTurnAccounting(t,e):void 0;if(r?.coverage==="partial")throw new d("BUDGET_UNAVAILABLE","Legacy goal turn accounting is incomplete");let s=this.goalIterationCount(t,e)+(r?.baseIterations??0);if(!Number.isSafeInteger(s)||s<0)throw new d("BUDGET_UNAVAILABLE","Invalid goal iteration accounting");if(s>=n.maxIterations)throw new d("BUDGET_EXCEEDED","Goal iteration limit reached; no iteration was admitted",{goalId:e.id,limit:"maxIterations",admitted:s,maximum:n.maxIterations})}}isCliGoal(t){return"cli.accountedTurns"in t.metadata||"cli.createdByCliVersion"in t.metadata}goalIterationCount(t,o){let i=0;for(let e of t.loops.filter(n=>n.goalId===o.id)){if(!Array.isArray(e.iterations))throw new d("BUDGET_UNAVAILABLE","Goal iteration history is unavailable");let n=0;for(let r of e.iterations){if(!r||!Number.isSafeInteger(r.number)||r.number<=n)throw new d("BUDGET_UNAVAILABLE","Goal iteration history is invalid");n=r.number}if(i+=n,!Number.isSafeInteger(i))throw new d("BUDGET_UNAVAILABLE","Goal iteration count exceeds its supported range")}return i}resolveGoalTurnAccounting(t,o){let i=t.goalTurnAccounting;if(i!==void 0&&(!i||typeof i!="object"||Array.isArray(i)))throw new d("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 d("BUDGET_UNAVAILABLE","Persisted goal turn accounting is invalid");return a}if(t.loops.some(a=>a.goalId===o.id&&a.iterations.some(c=>c.goalTurn||c.goalAccountingVersion)))throw new d("BUDGET_UNAVAILABLE","Recorded goal turns are missing their protected accounting");let e=this.goalIterationCount(t,o),n=o.metadata["cli.accountedTurns"],r=typeof n=="number"&&Number.isSafeInteger(n)&&n>=0,s=this.isCliGoal(o)&&(!r||n>0&&e>0);return{schemaVersion:1,baseIterations:r&&e===0?n:0,coverage:s?"partial":"complete"}}initializeGoalTurnAccounting(t,o){let i=this.resolveGoalTurnAccounting(t,o);if(i.coverage==="partial"&&o.limits?.maxIterations!==void 0)throw new d("BUDGET_UNAVAILABLE","Legacy goal turn accounting needs reconciliation before bounded execution");t.goalTurnAccounting??={},Object.defineProperty(t.goalTurnAccounting,o.id,{value:i,writable:!0,enumerable:!0,configurable:!0})}goalTurnHash(t){let o=p(t,"requestHash",64).toLowerCase();if(!/^[0-9a-f]{64}$/.test(o))throw new d("INVALID","Goal turn requestHash must be a SHA-256 digest");return o}goalTurnState(t,o,i,e){let n=this.resolveGoalTurnAccounting(t,o),r=this.goalIterationCount(t,o)+n.baseIterations;if(!Number.isSafeInteger(r))throw new d("BUDGET_UNAVAILABLE","Goal turn count exceeds its supported range");return m({goal:o,admittedTurns:r,accountingCoverage:n.coverage,...i?{loopId:i.id,loopVersion:i.version,loopStatus:i.status,resumeRequested:i.resumeRequested===!0}:{},...e?{iterationNumber:e.number,iterationStatus:e.status,...e.goalTurn?{requestId:e.goalTurn.requestId,requestHash:e.goalTurn.requestHash}:{},canRecover:e.status==="running"&&this.goalTurnOwnerExited(e)}:{}})}goalTurnOwnerExited(t){let o=t.goalTurn?.executor;if(o?.kind!=="local-sdk"||o.host!==v.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(t,o){let i=t.tasks.filter(e=>e.status==="completed").length;t.progress.completedTaskCount=i,t.progress.totalTaskCount=t.tasks.length,t.progress.percent=t.tasks.length?Math.round(i/t.tasks.length*100):void 0,t.progress.outstanding=t.tasks.filter(e=>!["completed","cancelled"].includes(e.status)).map(e=>e.title),t.progress.updatedAt=o}requireGoal(t,o){let i=t.goals.find(e=>e.id===o);if(!i)throw new d("NOT_FOUND",`Goal ${o} was not found`);return i}requireOwner(t,o,i){let e=t.owner;if(!e||e.ownerId!==o||e.leaseId!==i)throw new d("NOT_OWNER",`${o} does not own session ${t.sessionId}`,{owner:e});return e}assertVersion(t,o,i){if(!Number.isInteger(i)||i<1||o!==i)throw new d("CONFLICT",`Expected ${t} version ${i}, found ${o}`,{expected:i,actual:o})}newOwner(t,o,i,e){let n=i.leaseMs??this.ownerLeaseMs;if(!Number.isSafeInteger(n)||n<1)throw new d("INVALID","leaseMs must be a positive safe integer");return{ownerId:p(t,"ownerId",512),leaseId:this.idFactory("owner"),epoch:o,acquiredAt:e,heartbeatAt:e,expiresAt:new Date(y(e)+n).toISOString(),...i.processId!==void 0?{processId:i.processId}:{},...i.host?{host:p(i.host,"host",512)}:{}}}ownerExpired(t,o){return y(t.expiresAt)<=y(o)?!0:t.processId!==void 0&&t.host===v.hostname()&&!x(t.processId)}appendEvent(t,o,i){let e={schemaVersion:1,id:this.idFactory("event"),sequence:(t.events.at(-1)?.sequence??0)+1,type:o,sessionId:t.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:m(i.data)};t.events.push(e),t.events.length>this.maximumEventsPerSession&&t.events.splice(0,t.events.length-this.maximumEventsPerSession)}async mutate(t,o,i=!1,e=()=>!0){let n=p(t,"sessionId",1024);return this.withSessionLock(n,async()=>{let r=await this.readState(n);if(r.admissionFence&&!i)throw new d("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 e(a)&&(r.version+=1,r.updatedAt=this.now(),await this.writeState(r)),m(a)})}statePath(t){return I.join(this.rootDirectory,"sessions",`${Q(t)}.json`)}lockPath(t){return`${this.statePath(t)}.lock`}async readState(t){let o=this.statePath(t);try{let i=await f.readFile(o,"utf8"),e=JSON.parse(i);if(!V.includes(e.schemaVersion)||e.sessionId!==t)throw new d("INVALID",`Coordination state at ${o} does not match session ${t}`);if(e.admissionFence!==void 0){let n=e.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 d("INVALID","Persisted lifecycle fence is corrupt; execution remains unavailable")}return(!Number.isSafeInteger(e.ownershipEpoch)||e.ownershipEpoch<0)&&(e.ownershipEpoch=Math.max(e.owner?.epoch??0,...e.handoffs.map(n=>n.targetLeaseEpoch??n.sourceLeaseEpoch??0))),e}catch(i){if(i.code!=="ENOENT")throw i;let e=this.now();return{schemaVersion:1,sessionId:t,version:0,ownershipEpoch:0,goals:[],loops:[],handoffs:[],events:[],createdAt:e,updatedAt:e}}}promoteGoalBudgetEnvelope(t){(t.goalTurnAccounting!==void 0||t.loops.some(o=>o.resumeRequested!==void 0||o.iterations.some(i=>i.goalTurn!==void 0)))&&(t.schemaVersion=4),t.schemaVersion<3&&t.goals.some(o=>o.limits!==void 0&&(!o.limits||typeof o.limits!="object"||Array.isArray(o.limits)||Object.keys(o.limits).length>0))&&(t.schemaVersion=3)}async writeState(t){this.promoteGoalBudgetEnvelope(t);let o=this.statePath(t.sessionId),i=I.dirname(o);await f.mkdir(i,{recursive:!0});let e=`${o}.${process.pid}.${N()}.tmp`,n=await f.open(e,"wx");try{await n.writeFile(`${JSON.stringify(t,null,2)}
2
- `,"utf8"),await n.sync()}finally{await n.close()}try{await this.renameReplacing(e,o);try{let r=await f.open(i,"r");try{await r.sync()}finally{await r.close()}}catch{}}finally{await f.unlink(e).catch(()=>{})}}async renameReplacing(t,o){for(let i=0;;i+=1)try{await f.rename(t,o);return}catch(e){let n=e.code,r=D[i];if(process.platform!=="win32"||!n||!b.has(n)||r===void 0)throw e;await new Promise(s=>setTimeout(s,r))}}async withSessionLock(t,o){let i=this.lockPath(t),e=I.join(i,"owner.json"),n=N(),r=`${i}.candidate.${n}`,s=Date.now();await f.mkdir(I.dirname(i),{recursive:!0});let a={schemaVersion:1,token:n,pid:process.pid,host:v.hostname(),acquiredAt:this.now()};await f.mkdir(r),await f.writeFile(I.join(r,"owner.json"),JSON.stringify(a),{encoding:"utf8",flag:"wx"});for(let c=0;;c+=1)try{await f.rename(r,i);break}catch(u){let h=u.code;if(!(!!h&&new Set(["EEXIST","ENOTEMPTY","ENOTDIR","EBUSY"]).has(h)||process.platform==="win32"&&!!h&&b.has(h)))throw await f.rm(r,{recursive:!0,force:!0}).catch(()=>{}),u;let k=await this.staleLockOwner(i,e);if(k){await this.quarantineLock(i,k.token,"stale");continue}if(Date.now()-s>=this.lockTimeoutMs)throw await f.rm(r,{recursive:!0,force:!0}).catch(()=>{}),new d("CONFLICT",`Timed out waiting for coordination lock for session ${t}`);await new Promise(H=>setTimeout(H,Math.min(100,5+c*5)+Math.floor(Math.random()*10)))}try{return await o()}finally{await this.quarantineLock(i,n,"released"),await f.rm(r,{recursive:!0,force:!0}).catch(()=>{})}}async staleLockOwner(t,o){try{let[i,e]=await Promise.all([f.readFile(o,"utf8").catch(()=>""),f.stat(t)]),n=i?JSON.parse(i):void 0;return!n||n.host===v.hostname()&&x(n.pid)?void 0:Date.now()-e.mtimeMs>this.lockStaleMs?n:void 0}catch{return}}async quarantineLock(t,o,i){let e=I.join(t,"owner.json"),n=`${t}.${i}.${o}.${N()}`;for(let r=0;;r+=1){let s;try{s=JSON.parse(await f.readFile(e,"utf8"))}catch(a){if(a.code==="ENOENT")return;throw a}if(s.token!==o)return;try{await f.rename(t,n);break}catch(a){let c=a.code;if(c==="ENOENT"||c==="EEXIST")return;let u=D[r];if(process.platform!=="win32"||!c||!b.has(c)||u===void 0)throw a;await new Promise(h=>setTimeout(h,u))}}for(let r=0;;r+=1)try{await f.rm(n,{recursive:!0});return}catch(s){let a=s.code;if(a==="ENOENT")return;let c=J[r];if(process.platform!=="win32"||!a||!b.has(a)||c===void 0)throw s;await new Promise(u=>setTimeout(u,c))}}};function A(l,t){if(!l||typeof l!="object"||Array.isArray(l))throw new Error(`${t} must be an object`);return l}function g(l,t){if(typeof l!="string"||!l.trim())throw new Error(`${t} must be a non-empty string`);return l}function E(l,t){if(typeof l!="number"||!Number.isInteger(l))throw new Error(`${t} must be an integer`);return l}async function he(l,t){let{action:o,sessionId:i}=t,e=t.payload??{};if(e.sessionId!==void 0&&e.sessionId!==i)throw new d("INVALID","Payload sessionId must match the routed sessionId");let n;switch(o){case"state.get":n=await l.getSessionState(i);break;case"goal.create":n=await l.createGoal({...e,sessionId:i});break;case"goal.update":n=await l.updateGoal(i,g(e.goalId,"goalId"),E(e.expectedVersion,"expectedVersion"),A(e.update,"update"));break;case"goal.complete":n=await l.completeGoal(i,g(e.goalId,"goalId"),E(e.expectedVersion,"expectedVersion"),A(e.verification,"verification"));break;case"goal.cancel":n=await l.cancelGoal(i,g(e.goalId,"goalId"),E(e.expectedVersion,"expectedVersion"),g(e.reason,"reason"));break;case"goal.steer":n=await l.steerGoal(i,g(e.goalId,"goalId"),E(e.expectedVersion,"expectedVersion"),g(e.instruction,"instruction"));break;case"loop.start":n=await l.startLoop({sessionId:i,kind:g(e.kind,"kind"),...typeof e.goalId=="string"?{goalId:e.goalId}:{},...typeof e.activity=="string"?{activity:e.activity}:{},...e.schedule?{schedule:A(e.schedule,"schedule")}:{}});break;case"loop.get":n=await l.getLoop(i,typeof e.loopId=="string"?e.loopId:void 0);break;case"loop.begin":n=await l.beginLoopIteration(i,g(e.loopId,"loopId"),E(e.expectedVersion,"expectedVersion"),g(e.activity,"activity"),typeof e.taskId=="string"?e.taskId:void 0);break;case"loop.finish":n=await l.finishLoopIteration(i,g(e.loopId,"loopId"),E(e.expectedVersion,"expectedVersion"),A(e.result,"result"));break;case"loop.set_status":n=await l.setLoopStatus(i,g(e.loopId,"loopId"),E(e.expectedVersion,"expectedVersion"),g(e.status,"status"),typeof e.reason=="string"?e.reason:void 0);break;case"ownership.acquire":n=await l.acquireOwnership(i,g(e.ownerId,"ownerId"),A(e.options??{},"options"));break;case"ownership.renew":n=await l.renewOwnership(i,g(e.ownerId,"ownerId"),g(e.leaseId,"leaseId"),typeof e.leaseMs=="number"?e.leaseMs:void 0);break;case"ownership.release":n=await l.releaseOwnership(i,g(e.ownerId,"ownerId"),g(e.leaseId,"leaseId"));break;case"handoff.create":n=await l.createHandoff({...e,sessionId:i});break;case"handoff.claim":n=await l.claimHandoff({sessionId:i,handoffId:g(e.handoffId,"handoffId"),targetOwnerId:g(e.targetOwnerId,"targetOwnerId"),...typeof e.processId=="number"?{processId:e.processId}:{},...typeof e.host=="string"?{host:e.host}:{}});break;case"handoff.complete":n=await l.completeHandoff(i,g(e.handoffId,"handoffId"),g(e.ownerId,"ownerId"),g(e.leaseId,"leaseId"));break;case"handoff.fail":n=await l.failHandoff(i,g(e.handoffId,"handoffId"),g(e.reason,"reason"));break;default:throw new d("INVALID","Unsupported coordination action")}let r=await l.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}:{}}}import{randomUUID as Z}from"node:crypto";import{hostname as ee}from"node:os";var M=class{sessionId;ownerId;store;processId;host;leaseMs;heartbeatMs;claimHandoffId;onOwnershipLost;timer;heartbeatInFlight=!1;owner;stopped=!1;lostError;preparedHandoffId;constructor(t){if(this.store=t.store??new T,this.sessionId=t.sessionId,this.processId=t.processId??process.pid,this.host=t.host??ee(),this.ownerId=t.ownerId??`runtime:${this.host}:${this.processId}:${Z().slice(0,8)}`,this.leaseMs=t.leaseMs??3e4,this.heartbeatMs=t.heartbeatMs??Math.max(250,Math.floor(this.leaseMs/3)),this.heartbeatMs>=this.leaseMs)throw new Error("heartbeatMs must be shorter than leaseMs");this.claimHandoffId=t.claimHandoffId,this.onOwnershipLost=t.onOwnershipLost}get currentOwner(){return this.owner?structuredClone(this.owner):void 0}get active(){return!!this.owner&&!this.stopped&&this.lostError===void 0}async start(){if(this.owner)return structuredClone(this.owner);if(this.stopped)throw new Error("Execution lease session has already stopped");if(this.claimHandoffId){let t=await this.store.claimHandoff({sessionId:this.sessionId,handoffId:this.claimHandoffId,targetOwnerId:this.ownerId,processId:this.processId,host:this.host});this.owner=t.owner,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});return this.timer=setInterval(()=>{this.heartbeat()},this.heartbeatMs),this.timer.unref?.(),structuredClone(this.owner)}async assertOwned(){if(this.stopped)throw new Error("Execution surface is detached");if(this.lostError)throw this.lostError;if(this.preparedHandoffId)throw new Error(`Execution surface prepared handoff ${this.preparedHandoffId} and is detached from mutation`);if(!this.owner)throw new Error("Execution ownership was not started");return this.renewHeldLease()}async renewHeldLease(){if(!this.owner)throw new Error("Execution ownership was not started");try{return this.owner=await this.store.renewOwnership(this.sessionId,this.ownerId,this.owner.leaseId,this.leaseMs),structuredClone(this.owner)}catch(t){throw this.markLost(t),t}}async prepareHandoff(t={}){if(this.preparedHandoffId)throw new Error(`Handoff ${this.preparedHandoffId} is already prepared`);let o=await this.assertOwned(),i=await this.store.createHandoff({...t,sessionId:this.sessionId,sourceOwnerId:o.ownerId,sourceLeaseId:o.leaseId});return this.preparedHandoffId=i.id,i}async stop(t={}){if(this.stopped)return;this.stopped=!0,this.timer&&clearInterval(this.timer),this.timer=void 0;let o=this.owner;if(this.owner=void 0,!(t.release===!1||this.preparedHandoffId||!o||this.lostError))try{await this.store.releaseOwnership(this.sessionId,o.ownerId,o.leaseId)}catch{}}async heartbeat(){if(!(!this.active||this.heartbeatInFlight)){this.heartbeatInFlight=!0;try{await this.renewHeldLease()}catch(t){this.markLost(t)}finally{this.heartbeatInFlight=!1}}}markLost(t){this.lostError===void 0&&(this.lostError=t,this.timer&&clearInterval(this.timer),this.timer=void 0,this.onOwnershipLost?.(t))}};export{T as DurableXenoCoordinationStore,S as XENO_COORDINATION_BUDGET_SESSION_SCHEMA_VERSION,L as XENO_COORDINATION_MANAGED_SESSION_SCHEMA_VERSION,w as XENO_COORDINATION_SCHEMA_VERSION,X as XENO_COORDINATION_TURN_SESSION_SCHEMA_VERSION,d as XenoCoordinationError,M as XenoExecutionLeaseSession,he as executeXenoCoordinationAction};
1
+ var y=1,_=2,N=3,x=4,u=class extends Error{constructor(n,s,t={}){super(s);this.code=n;this.details=t;this.name="XenoCoordinationError"}code;details};import{createHash as ce,randomUUID as T}from"node:crypto";import*as p from"node:fs/promises";import*as v from"node:os";import*as I from"node:path";import{homedir as B,platform as ae,release as de}from"node:os";import{resolve as U}from"node:path";var Te=ae();var Le=de(),Ce=B();function j(){let d=process.env.XENO_AGENT_HOME?.trim();return d?U(d):U(B(),".xeno-agent")}var le=3e4,ue=3e4,fe=6e4,he=2e4,L=new Set(["EACCES","EBUSY","EPERM"]),J=[5,10,20,40,80,160,320],pe=[5,10,20,40,80,160,320],z=[1,2,3,4];function h(d,e,n=16384){let s=d.trim();if(!s||s.length>n)throw new u("INVALID",`${e} must be non-empty and no longer than ${n} characters`);return s}function C(d,e){return[...new Set((d??[]).map(n=>h(n,e)))]}function W(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[n,s]of Object.entries(d)){if(n!=="maxIterations"&&n!=="maxTokens"&&n!=="maxWallClockMs")throw new u("INVALID","Unknown goal limit");if(s!==void 0){if(!Number.isSafeInteger(s)||s<=0)throw new u("INVALID",`${n} must be a positive safe integer when provided`);e[n]=s}}return e}function ge(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 n=d[e];if(n!==void 0&&!Number.isFinite(Date.parse(n)))throw new u("INVALID",`schedule.${e} must be an ISO timestamp when provided`)}return w(d)}}function w(d){return structuredClone(d)}function A(d){let e=Date.parse(d);return Number.isFinite(e)?e:0}function D(d){if(!Number.isInteger(d)||d<=0)return!1;try{return process.kill(d,0),!0}catch(e){return e.code==="EPERM"}}function we(d){return{summary:"Goal created; work has not started.",completedTaskCount:0,totalTaskCount:0,outstanding:[],decisions:[],updatedAt:d}}function me(){return{status:"pending",criteria:[],evidence:[]}}function K(d){return ce("sha256").update(d).digest("hex")}var k=class{get goalTurnAdmissionVersion(){return 1}rootDirectory;now;idFactory;ownerLeaseMs;lockTimeoutMs;lockStaleMs;maximumEventsPerSession;constructor(e={}){this.rootDirectory=e.rootDirectory??I.join(j(),"coordination"),this.now=e.now??(()=>new Date().toISOString()),this.idFactory=e.idFactory??(n=>`${n}_${T()}`),this.ownerLeaseMs=e.ownerLeaseMs??le,this.lockTimeoutMs=e.lockTimeoutMs??ue,this.lockStaleMs=e.lockStaleMs??fe,this.maximumEventsPerSession=e.maximumEventsPerSession??he}async getSessionState(e){let n=h(e,"sessionId",1024);return w(await this.readState(n))}async fenceAdmission(e,n,s){let t=h(s.authorityId,"authorityId",512),o=h(s.operationId,"operationId",512);if(!Number.isSafeInteger(n)||n<0)throw new u("INVALID","Expected session version must be a nonnegative safe integer");if(s.action!=="archive"&&s.action!=="delete")throw new u("INVALID","Unsupported admission fence action");return this.mutate(e,r=>{let i=r.admissionFence;if(i?.authorityId===t&&i.operationId===o&&i.action===s.action)return i;if(r.version!==n)throw new u("CONFLICT","Session version changed before lifecycle fencing",{expected:n,actual:r.version});if(i?.authorityId===t&&i.action==="archive"&&s.action==="archive")return i;if(i&&!(i.authorityId===t&&i.action==="archive"&&s.action==="delete"))throw new u("CONFLICT","Another lifecycle fence already owns this session");let a={schemaVersion:1,authorityId:t,operationId:o,action:s.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:s.action}}),a},!0)}async clearAdmissionFence(e,n,s,t){await this.mutate(e,o=>{this.assertVersion(e,o.version,n);let r=o.admissionFence;if(!r||r.authorityId!==s||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(o.owner)throw new u("CONFLICT","Execution ownership must settle before restoration");o.admissionFence=void 0,this.appendEvent(o,"admission.restored",{data:{authorityId:s,operationId:t}})},!0)}async releaseDeadLifecycleOwner(e,n,s,t){await this.mutate(e,o=>{this.assertVersion(e,o.version,n);let r=o.admissionFence;if(!r||r.authorityId!==s||r.operationId!==t)throw new u("CONFLICT","Lifecycle fence identity does not match");let i=o.owner;if(i){if(i.host!==v.hostname()||!Number.isInteger(i.processId)||(i.processId??0)<=0||D(i.processId))throw new u("CONFLICT","Execution owner exit has not been proved");o.owner=void 0,this.appendEvent(o,"ownership.released",{ownerId:i.ownerId,data:{epoch:i.epoch,reason:"fenced-local-owner-exited"}})}},!0)}async listSessionStates(){let e=I.join(this.rootDirectory,"sessions"),n;try{n=await p.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 p.readFile(I.join(e,t),"utf8"));return!z.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)=>A(o.updatedAt)-A(t.updatedAt)).map(t=>w(t))}async createGoal(e){let n=h(e.sessionId,"sessionId",1024),s=W(e.limits);return this.mutate(n,t=>{let o=t.goals.find(l=>["active","paused","waiting","blocked"].includes(l.status));if(o)throw new u("CONFLICT",`Session ${n} already has active goal ${o.id}`);let r=this.now(),i=(e.successCriteria??[]).map(l=>typeof l=="string"?{id:this.idFactory("criterion"),description:h(l,"successCriteria"),required:!0}:{id:l.id?h(l.id,"successCriteria.id",512):this.idFactory("criterion"),description:h(l.description,"successCriteria.description"),required:l.required}),a={schemaVersion:1,id:this.idFactory("goal"),version:1,sessionId:n,objective:h(e.objective,"objective"),...e.why?{why:h(e.why,"why")}:{},successCriteria:i,constraints:C(e.constraints,"constraints"),...s?{limits:s}:{},metadata:w(e.metadata??{}),status:"active",milestones:[],tasks:[],progress:we(r),verification:me(),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 s=await this.getSessionState(e),t=n?s.goals.find(o=>o.id===n):[...s.goals].reverse().find(o=>["active","paused","waiting","blocked"].includes(o.status));return t?w(t):void 0}async updateGoal(e,n,s,t){return this.mutate(e,o=>{let r=this.requireGoal(o,n);if(this.assertVersion(r.id,r.version,s),["completed","cancelled","failed"].includes(r.status))throw new u("CONFLICT",`Goal ${r.id} is terminal (${r.status})`);let i=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=h(t.objective,"objective")),t.why!==void 0&&(r.why=h(t.why,"why")),t.constraints&&(r.constraints=C(t.constraints,"constraints")),t.successCriteria&&(r.successCriteria=w(t.successCriteria)),t.progress&&(r.progress={...r.progress,...w(t.progress),outstanding:C(t.progress.outstanding??r.progress.outstanding,"progress.outstanding"),decisions:C(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)),i&&r.status==="active")for(let a of o.loops.filter(l=>l.goalId===n&&l.kind==="goal-continuation"&&l.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,s,t){return this.mutateGoal(e,n,s,(o,r)=>{let i={id:this.idFactory("milestone"),title:h(t.title,"milestone.title"),...t.description?{description:h(t.description,"milestone.description")}:{},status:o.milestones.some(a=>a.status==="active")?"pending":"active",taskIds:[],createdAt:r,updatedAt:r};o.milestones.push(i),o.progress.currentMilestoneId??=i.id,o.progress.updatedAt=r})}async addTask(e,n,s,t){return this.mutateGoal(e,n,s,(o,r)=>{let i=o.milestones.find(c=>c.id===t.milestoneId);if(!i)throw new u("NOT_FOUND",`Milestone ${t.milestoneId} was not found`);if(t.parentTaskId&&!o.tasks.some(c=>c.id===t.parentTaskId))throw new u("NOT_FOUND",`Parent task ${t.parentTaskId} was not found`);let a=[...new Set(t.dependsOn??[])];for(let c of a)if(!o.tasks.some(f=>f.id===c))throw new u("NOT_FOUND",`Task dependency ${c} was not found`);let l={id:this.idFactory("task"),milestoneId:i.id,...t.parentTaskId?{parentTaskId:t.parentTaskId}:{},title:h(t.title,"task.title"),...t.description?{description:h(t.description,"task.description")}:{},status:a.length===0?"ready":"pending",...t.assignedAgentId?{assignedAgentId:h(t.assignedAgentId,"task.assignedAgentId",512)}:{},...a.length?{dependsOn:a}:{},createdAt:r,updatedAt:r};o.tasks.push(l),i.taskIds.push(l.id),i.updatedAt=r,o.progress.totalTaskCount=o.tasks.length,o.progress.outstanding=o.tasks.filter(c=>c.status!=="completed").map(c=>c.title),o.progress.updatedAt=r})}async updateTask(e,n,s,t,o){return this.mutateGoal(e,n,t,(r,i)=>{let a=r.tasks.find(c=>c.id===s);if(!a)throw new u("NOT_FOUND",`Task ${s} was not found`);a.status=o.status,o.progress!==void 0&&(a.progress=h(o.progress,"task.progress")),o.resultEventId!==void 0&&(a.resultEventId=h(o.resultEventId,"task.resultEventId",512)),o.assignedAgentId!==void 0&&(a.assignedAgentId=h(o.assignedAgentId,"task.assignedAgentId",512)),a.updatedAt=i,a.status==="completed"&&(a.completedAt=i);let l=r.milestones.find(c=>c.id===a.milestoneId);if(l){let c=r.tasks.filter(f=>f.milestoneId===l.id);c.length>0&&c.every(f=>f.status==="completed")?(l.status="completed",l.completedAt=i):c.some(f=>f.status==="running")?l.status="active":c.some(f=>f.status==="blocked")&&(l.status="blocked"),l.updatedAt=i}for(let c of r.tasks)c.status!=="pending"||!c.dependsOn?.length||c.dependsOn.every(f=>r.tasks.find(m=>m.id===f)?.status==="completed")&&(c.status="ready",c.updatedAt=i);this.recalculateProgress(r,i)})}async steerGoal(e,n,s,t){return this.mutateGoal(e,n,s,(o,r,i)=>{let a=this.idFactory("steer");o.steering.push({id:a,instruction:h(t,"instruction"),createdAt:r}),this.appendEvent(i,"goal.steered",{goalId:n,data:{steeringId:a}})},!1)}async consumeGoalSteering(e,n,s){let t=[];return{goal:await this.mutateGoal(e,n,s,(r,i)=>{t=r.steering.filter(a=>!a.consumedAt).map(({id:a,instruction:l,createdAt:c})=>({id:a,instruction:l,createdAt:c}));for(let a of r.steering)a.consumedAt||(a.consumedAt=i)}),instructions:t}}async completeGoal(e,n,s,t){if(t.status!=="passed")throw new u("VERIFICATION_REQUIRED","Goal completion requires passed verification");return this.mutate(e,o=>{let r=this.requireGoal(o,n);this.assertVersion(r.id,r.version,s);let i=r.successCriteria.filter(c=>c.required),a=i.filter(c=>{let f=t.criteria.find(m=>m.criterionId===c.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(c=>c.id)});if(i.length===0&&t.evidence.length===0)throw new u("VERIFICATION_REQUIRED","Goal completion requires at least one durable evidence reference");let l=this.now();return r.status="completed",r.verification=w(t),r.verification.verifiedAt??=l,r.completedAt=l,r.updatedAt=l,r.version+=1,this.appendEvent(o,"goal.completed",{goalId:n,data:{evidence:r.verification.evidence}}),r},!0)}async cancelGoal(e,n,s,t){return this.mutate(e,o=>{let r=this.requireGoal(o,n);if(this.assertVersion(r.id,r.version,s),["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:h(t,"reason")}});for(let i of o.loops.filter(a=>a.goalId===n&&["running","paused","waiting"].includes(a.status)))i.status="stopped",i.resumeRequested!==void 0&&(i.resumeRequested=!1),i.stopReason=`Goal cancelled: ${t}`,i.stoppedAt=this.now(),i.updatedAt=i.stoppedAt,i.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 u("INVALID","Goal-continuation loops require a goalId");if(n.goalId){let i=this.requireGoal(e,n.goalId);if(["completed","cancelled","failed"].includes(i.status))throw new u("CONFLICT",`Cannot start a loop for terminal goal ${i.id}`)}if(n.kind==="scheduled"&&!n.schedule)throw new u("INVALID","Scheduled loops require schedule metadata");if(n.kind!=="scheduled"&&n.schedule)throw new u("INVALID","Only scheduled loops may carry schedule metadata");let s=ge(n.schedule),t=e.loops.find(i=>i.goalId===n.goalId&&i.kind===n.kind&&["running","paused","waiting"].includes(i.status));if(t)throw new u("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:h(n.activity,"activity")}:{},iterations:[],...s?{schedule:s}:{},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 s=await this.getSessionState(e),t=n?s.loops.find(o=>o.id===n):[...s.loops].reverse().find(o=>["running","paused","waiting"].includes(o.status));return t?w(t):void 0}async beginLoopIteration(e,n,s,t,o){return this.mutateLoop(e,n,s,(r,i,a)=>{this.appendLoopIteration(a,r,i,t,o)},!1)}appendLoopIteration(e,n,s,t,o){if(n.status!=="running")throw new u("CONFLICT",`Loop ${n.id} is ${n.status}`);if(n.goalId){let a=this.requireGoal(e,n.goalId);this.isCliGoal(a)&&this.initializeGoalTurnAccounting(e,a)}if(this.assertGoalIterationAdmission(e,n,s),n.iterations.some(a=>a.status==="running"))throw new u("CONFLICT",`Loop ${n.id} already has a running iteration`);let r=(n.iterations.at(-1)?.number??0)+1;n.currentActivity=h(t,"activity");let i={number:r,startedAt:s,status:"running",activity:n.currentActivity,...n.goalId&&e.goalTurnAccounting?.[n.goalId]?{goalAccountingVersion:1}:{},...o?{taskId:h(o,"taskId",512)}:{}};return n.iterations.push(i),n.resumeRequested!==void 0&&(n.resumeRequested=!1),this.appendEvent(e,"loop.iteration",{loopId:n.id,goalId:n.goalId,data:{number:r,phase:"started",activity:n.currentActivity}}),i}async admitGoalTurn(e){return this.admitGoalTurnWithOwner(e)}async admitOwnedGoalTurn(e,n){if(!n||!Number.isSafeInteger(n.epoch)||n.epoch<1)throw new u("INVALID","An exact execution ownership epoch is required");return this.admitGoalTurnWithOwner(e,{...n})}async admitGoalTurnWithOwner(e,n){let s=h(e.requestId,"requestId",512),t=this.goalTurnHash(e.requestHash);return this.mutate(e.sessionId,o=>{if(n){let c=this.requireOwner(o,n.ownerId,n.leaseId);if(c.epoch!==n.epoch)throw new u("NOT_OWNER","Execution ownership epoch changed");if(this.ownerExpired(c,this.now()))throw new u("LEASE_EXPIRED","Execution ownership expired");if(o.handoffs.some(f=>["prepared","available"].includes(f.status)&&f.sourceLeaseEpoch===c.epoch)||o.handoffs.some(f=>f.status==="claimed"&&f.targetLeaseEpoch===c.epoch))throw new u("UNSAFE_HANDOFF","Execution handoff has not settled")}let r=this.requireGoal(o,e.goalId);for(let c of o.loops.filter(f=>f.goalId===r.id)){let f=c.iterations.find(m=>m.goalTurn?.requestId===s);if(f){if(f.goalTurn?.requestHash!==t)throw new u("CONFLICT","Goal turn identity was reused for different work");return{...this.goalTurnState(o,r,c,f),admitted:!1}}}if(this.assertVersion(r.id,r.version,e.expectedGoalVersion),r.status!=="active")throw new u("CONFLICT",`Goal ${r.id} is ${r.status}`);let i=[...o.loops].reverse().find(c=>c.goalId===r.id&&c.kind==="goal-continuation");if(e.expectedLoopId!==void 0){if(!i||i.id!==e.expectedLoopId)throw new u("CONFLICT","Goal continuation loop changed before admission");this.assertVersion(i.id,i.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(i&&i.status!=="running")throw new u("CONFLICT",`Goal loop ${i.id} is ${i.status}; resume or start it explicitly`);this.initializeGoalTurnAccounting(o,r),i??=this.createLoopRecord(o,{sessionId:o.sessionId,goalId:r.id,kind:"goal-continuation"});let a=this.now(),l=this.appendLoopIteration(o,i,a,"Interactive goal turn");if(e.executionKind!==void 0&&e.executionKind!=="local-sdk"&&e.executionKind!=="external")throw new u("INVALID","Unknown goal execution lane");return l.goalTurn={requestId:s,requestHash:t,executor:e.executionKind==="local-sdk"?{kind:"local-sdk",processId:process.pid,host:v.hostname()}:{kind:"external"}},i.version+=1,i.updatedAt=a,{...this.goalTurnState(o,r,i,l),admitted:!0}},!1,o=>o.admitted)}async getGoalTurnState(e,n,s){let t=await this.getSessionState(e),o=n?t.goals.find(l=>l.id===n):[...t.goals].reverse().find(l=>["active","paused","waiting","blocked"].includes(l.status));if(!o)return;let r=t.loops.filter(l=>l.goalId===o.id),i=s?r.find(l=>l.iterations.some(c=>c.goalTurn?.requestId===s)):[...r].reverse().find(l=>l.kind==="goal-continuation"),a=s?i?.iterations.find(l=>l.goalTurn?.requestId===s):i?.iterations.at(-1);if(s&&!a)throw new u("NOT_FOUND","Goal turn was not found");return this.goalTurnState(t,o,i,a)}async finishGoalTurn(e){if(!["completed","failed","interrupted"].includes(e.status))throw new u("INVALID","Invalid goal turn outcome");let n=this.goalTurnHash(e.requestHash);return this.mutate(e.sessionId,s=>{let t=this.requireGoal(s,e.goalId),o=s.loops.find(i=>i.goalId===t.id&&i.iterations.some(a=>a.goalTurn?.requestId===e.requestId)),r=o?.iterations.find(i=>i.goalTurn?.requestId===e.requestId);if(!o||!r)throw new u("NOT_FOUND","Goal turn was not found");if(r.goalTurn?.requestHash!==n)throw new u("CONFLICT","Goal turn settlement identity does not match");return r.status==="running"&&(this.settleLoopIteration(s,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(s,t,o,r)},!0)}async recoverGoalTurn(e,n,s){return this.mutate(e,t=>{let o=this.requireGoal(t,n),r=t.loops.find(a=>a.goalId===n&&a.iterations.some(l=>l.goalTurn?.requestId===s)),i=r?.iterations.find(a=>a.goalTurn?.requestId===s);if(!r||!i)throw new u("NOT_FOUND","Goal turn was not found");if(i.status==="running"){if(!this.goalTurnOwnerExited(i))throw new u("NOT_OWNER","The original local goal executor has not been proved exited; external execution requires reconciliation");this.settleLoopIteration(t,r,i,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,i)},!0)}async finishLoopIteration(e,n,s,t){return this.mutateLoop(e,n,s,(o,r,i)=>{let a=[...o.iterations].reverse().find(l=>l.status==="running");if(!a)throw new u("CONFLICT",`Loop ${o.id} has no running iteration`);this.settleLoopIteration(i,o,a,r,t)},!1,!0)}settleLoopIteration(e,n,s,t,o){s.status=o.status,s.completedAt=t,o.verificationEventId&&(s.verificationEventId=h(o.verificationEventId,"verificationEventId",512)),o.error&&(s.error=h(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:s.number,phase:"finished",status:o.status}})}async setLoopStatus(e,n,s,t,o){return this.mutateLoop(e,n,s,(r,i,a)=>{let l=r.status;if(["stopped","completed","failed"].includes(l))throw new u("CONFLICT",`Loop ${r.id} is terminal (${l})`);let c=[...r.iterations].reverse().find(m=>m.status==="running");if(c&&t==="completed")throw new u("CONFLICT",`Loop ${r.id} cannot complete while iteration ${c.number} is running`);c&&(t==="stopped"||t==="failed")&&(c.status=t==="failed"?"failed":"interrupted",c.completedAt=i,c.error=h(o??t,"reason")),r.status=t,r.kind==="goal-continuation"&&(r.resumeRequested=t==="running"),["stopped","completed","failed"].includes(t)&&(r.stoppedAt=i,r.stopReason=h(o??t,"reason"));let f=t==="paused"?"loop.paused":t==="waiting"?"loop.waiting":t==="running"&&(l==="paused"||l==="waiting")?"loop.resumed":t==="completed"?"loop.completed":t==="failed"?"loop.failed":"loop.stopped";this.appendEvent(a,f,{loopId:n,goalId:r.goalId,data:{previous:l,status:t,...o?{reason:o}:{}}})},!1,t!=="running"&&t!=="waiting")}async acquireOwnership(e,n,s={}){return this.mutate(e,t=>{let o=this.now();if(t.owner&&!this.ownerExpired(t.owner,o)){if(t.owner.ownerId===n&&s.processId!==void 0&&t.owner.processId===s.processId&&(s.host===void 0||t.owner.host===s.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,o)?t.owner:void 0;if(r)for(let l of t.handoffs.filter(c=>c.status==="claimed"&&c.claimedBy===r.ownerId&&c.targetLeaseEpoch===r.epoch))l.status="failed",l.failureReason=`Claimed owner ${r.ownerId} lost its execution lease before completing the handoff.`,l.failedAt=o,l.updatedAt=o,l.version+=1,this.appendEvent(t,"handoff.failed",{handoffId:l.id,goalId:l.goalId,loopId:l.loopId,data:{reason:l.failureReason,expiredLeaseId:r.leaseId}});let i=t.ownershipEpoch+1;for(let l of t.handoffs.filter(c=>["prepared","available"].includes(c.status)&&c.sourceLeaseEpoch<i))l.status="failed",l.failureReason="Source ownership epoch was superseded before the handoff was claimed.",l.failedAt=o,l.updatedAt=o,l.version+=1,this.appendEvent(t,"handoff.failed",{handoffId:l.id,data:{epoch:i,reason:l.failureReason}});let a=this.newOwner(n,i,s,o);return t.owner=a,t.ownershipEpoch=i,this.appendEvent(t,"ownership.acquired",{ownerId:n,data:{epoch:i,leaseId:a.leaseId}}),a})}async renewOwnership(e,n,s,t=this.ownerLeaseMs){return this.mutate(e,o=>{let r=this.requireOwner(o,n,s);if(this.ownerExpired(r,this.now()))throw new u("LEASE_EXPIRED",`Ownership lease ${s} expired`);return r.heartbeatAt=this.now(),r.expiresAt=new Date(A(r.heartbeatAt)+t).toISOString(),this.appendEvent(o,"ownership.renewed",{ownerId:n,data:{epoch:r.epoch,leaseId:s}}),r})}async releaseOwnership(e,n,s){return this.mutate(e,t=>{let o=this.requireOwner(t,n,s);for(let r of t.handoffs.filter(i=>i.status==="claimed"&&i.claimedBy===n&&i.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,s=e.prepareRequestId===void 0?void 0:h(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 u("LEASE_EXPIRED",`Ownership lease ${o.leaseId} expired`);if(s){let c=t.handoffs.find(f=>f.prepareRequestId===s);if(c){if(c.sourceOwnerId!==o.ownerId||c.sourceLeaseEpoch!==o.epoch||c.status!=="available"||c.targetOwnerId!==e.targetOwnerId||c.workspace!==e.workspace||c.goalId!==e.goalId||c.loopId!==e.loopId||c.contextDigest!==e.contextDigest||c.branch!==e.branch||c.currentMilestoneId!==e.currentMilestoneId||c.currentTaskId!==e.currentTaskId||JSON.stringify(c.agentIds)!==JSON.stringify([...new Set(e.agentIds??[])])||JSON.stringify(c.operations)!==JSON.stringify(e.operations??[]))throw new u("CONFLICT","Prepare identity was reused for different work or ownership");return n=!0,c}}let r=(e.operations??[]).filter(c=>c.status==="running"&&c.sideEffecting);if(r.length>0)throw new u("UNSAFE_HANDOFF","Running side-effecting operations must settle before execution handoff",{operationIds:r.map(c=>c.operationId)});if(e.goalId&&this.requireGoal(t,e.goalId),e.loopId&&!t.loops.some(c=>c.id===e.loopId))throw new u("NOT_FOUND",`Loop ${e.loopId} was not found`);let i=t.handoffs.find(c=>["prepared","available","claimed"].includes(c.status));if(i)throw new u("CONFLICT",`Handoff ${i.id} is already active`);let a=this.now(),l={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,...s?{prepareRequestId:s}:{},...e.targetOwnerId?{targetOwnerId:h(e.targetOwnerId,"targetOwnerId",512)}:{},sourceLeaseEpoch:o.epoch,...e.workspace?{workspace:h(e.workspace,"workspace",32768)}:{},...e.branch?{branch:h(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:h(e.contextDigest,"contextDigest",512)}:{},createdAt:a,updatedAt:a};return t.handoffs.push(l),this.appendEvent(t,"handoff.created",{handoffId:l.id,goalId:l.goalId,loopId:l.loopId,ownerId:o.ownerId,data:{targetOwnerId:l.targetOwnerId}}),l},!1,()=>!n)}async claimHandoff(e){let n,s=!1,t=e.claimRequestId===void 0?void 0:h(e.claimRequestId,"claimRequestId",512);return{handoff:await this.mutate(e.sessionId,r=>{let i=r.handoffs.find(c=>c.id===e.handoffId);if(!i)throw new u("NOT_FOUND",`Handoff ${e.handoffId} was not found`);if(i.status!=="available"){let c=r.owner;if(t&&i.claimRequestId===t&&["claimed","completed"].includes(i.status)&&i.claimedBy===e.targetOwnerId&&c?.ownerId===e.targetOwnerId&&c.epoch===i.targetLeaseEpoch&&c.host===e.host&&c.processId===e.processId&&!this.ownerExpired(c,this.now()))return n=c,s=!0,i;throw new u("CONFLICT",`Handoff ${i.id} is ${i.status}`,{claimedBy:i.claimedBy})}if(i.targetOwnerId&&i.targetOwnerId!==e.targetOwnerId)throw new u("CONFLICT",`Handoff ${i.id} is reserved for ${i.targetOwnerId}`);let a=r.owner;if(!a||a.ownerId!==i.sourceOwnerId||a.epoch!==i.sourceLeaseEpoch)throw new u("CONFLICT",`Handoff ${i.id} no longer matches the source ownership epoch`);let l=this.now();return n=this.newOwner(e.targetOwnerId,a.epoch+1,{processId:e.processId,host:e.host,leaseMs:e.leaseMs},l),r.owner=n,r.ownershipEpoch=n.epoch,i.status="claimed",i.claimedBy=e.targetOwnerId,t&&(i.claimRequestId=t),i.targetOwnerId=e.targetOwnerId,i.targetLeaseEpoch=n.epoch,i.claimedAt=l,i.updatedAt=l,i.version+=1,this.appendEvent(r,"handoff.claimed",{handoffId:i.id,goalId:i.goalId,loopId:i.loopId,ownerId:e.targetOwnerId,data:{sourceOwnerId:i.sourceOwnerId,epoch:n.epoch}}),i},!1,()=>!s),owner:w(n)}}async completeHandoff(e,n,s,t){let o=!1;return this.mutate(e,r=>{let i=this.requireOwner(r,s,t);if(this.ownerExpired(i,this.now()))throw new u("LEASE_EXPIRED",`Ownership lease ${t} expired`);let a=r.handoffs.find(l=>l.id===n);if(!a)throw new u("NOT_FOUND",`Handoff ${n} was not found`);if(a.claimedBy!==s||a.targetLeaseEpoch!==i.epoch||!["claimed","completed"].includes(a.status))throw new u("CONFLICT",`Handoff ${a.id} cannot be completed by ${s}`);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:s,data:{epoch:r.owner?.epoch}}),a)},!1,()=>!o)}async failHandoff(e,n,s){return this.mutate(e,t=>{let o=t.handoffs.find(r=>r.id===n);if(!o)throw new u("NOT_FOUND",`Handoff ${n} was not found`);return["completed","cancelled","failed"].includes(o.status)||(o.status="failed",o.failureReason=h(s,"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,s,t,o=!0){return this.mutate(e,r=>{let i=this.requireGoal(r,n);this.assertVersion(i.id,i.version,s);let a=this.now();return t(i,a,r),i.version+=1,i.updatedAt=a,o&&this.appendEvent(r,"goal.updated",{goalId:n,data:{status:i.status,version:i.version}}),i})}async mutateLoop(e,n,s,t,o=!0,r=!1){return this.mutate(e,i=>{let a=i.loops.find(c=>c.id===n);if(!a)throw new u("NOT_FOUND",`Loop ${n} was not found`);this.assertVersion(a.id,a.version,s);let l=this.now();return t(a,l,i),a.version+=1,a.updatedAt=l,o&&this.appendEvent(i,"loop.iteration",{loopId:n,goalId:a.goalId,data:{status:a.status,version:a.version}}),a},r)}assertGoalIterationAdmission(e,n,s){if(!n.goalId)return;let t=this.requireGoal(e,n.goalId);if(t.status!=="active")throw new u("CONFLICT",`Goal ${t.id} is ${t.status}; no iteration was admitted`);let o=W(t.limits);if(o?.maxTokens!==void 0)throw new u("BUDGET_UNAVAILABLE","Goal token allowance is not bound to request-level admission; no iteration was admitted",{goalId:t.id,limit:"maxTokens"});if(o?.maxWallClockMs!==void 0){let r=Date.parse(t.createdAt),i=Date.parse(s);if(!Number.isFinite(r)||!Number.isFinite(i)||i<r)throw new u("BUDGET_UNAVAILABLE","Goal wall-clock allowance cannot be verified",{goalId:t.id,limit:"maxWallClockMs"});if(i-r>=o.maxWallClockMs)throw new u("BUDGET_EXCEEDED","Goal wall-clock limit reached; no iteration was admitted",{goalId:t.id,limit:"maxWallClockMs",maximum:o.maxWallClockMs})}if(o?.maxIterations!==void 0){let r=e.goalTurnAccounting!==void 0||e.schemaVersion===4?this.resolveGoalTurnAccounting(e,t):void 0;if(r?.coverage==="partial")throw new u("BUDGET_UNAVAILABLE","Legacy goal turn accounting is incomplete");let i=this.goalIterationCount(e,t)+(r?.baseIterations??0);if(!Number.isSafeInteger(i)||i<0)throw new u("BUDGET_UNAVAILABLE","Invalid goal iteration accounting");if(i>=o.maxIterations)throw new u("BUDGET_EXCEEDED","Goal iteration limit reached; no iteration was admitted",{goalId:t.id,limit:"maxIterations",admitted:i,maximum:o.maxIterations})}}isCliGoal(e){return"cli.accountedTurns"in e.metadata||"cli.createdByCliVersion"in e.metadata}goalIterationCount(e,n){let s=0;for(let t of e.loops.filter(o=>o.goalId===n.id)){if(!Array.isArray(t.iterations))throw new u("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 u("BUDGET_UNAVAILABLE","Goal iteration history is invalid");o=r.number}if(s+=o,!Number.isSafeInteger(s))throw new u("BUDGET_UNAVAILABLE","Goal iteration count exceeds its supported range")}return s}resolveGoalTurnAccounting(e,n){let s=e.goalTurnAccounting;if(s!==void 0&&(!s||typeof s!="object"||Array.isArray(s)))throw new u("BUDGET_UNAVAILABLE","Persisted goal turn accounting is invalid");if(s&&Object.hasOwn(s,n.id)){let a=s[n.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===n.id&&a.iterations.some(l=>l.goalTurn||l.goalAccountingVersion)))throw new u("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,i=this.isCliGoal(n)&&(!r||o>0&&t>0);return{schemaVersion:1,baseIterations:r&&t===0?o:0,coverage:i?"partial":"complete"}}initializeGoalTurnAccounting(e,n){let s=this.resolveGoalTurnAccounting(e,n);if(s.coverage==="partial"&&n.limits?.maxIterations!==void 0)throw new u("BUDGET_UNAVAILABLE","Legacy goal turn accounting needs reconciliation before bounded execution");e.goalTurnAccounting??={},Object.defineProperty(e.goalTurnAccounting,n.id,{value:s,writable:!0,enumerable:!0,configurable:!0})}goalTurnHash(e){let n=h(e,"requestHash",64).toLowerCase();if(!/^[0-9a-f]{64}$/.test(n))throw new u("INVALID","Goal turn requestHash must be a SHA-256 digest");return n}goalTurnState(e,n,s,t){let o=this.resolveGoalTurnAccounting(e,n),r=this.goalIterationCount(e,n)+o.baseIterations;if(!Number.isSafeInteger(r))throw new u("BUDGET_UNAVAILABLE","Goal turn count exceeds its supported range");return w({goal:n,admittedTurns:r,accountingCoverage:o.coverage,...s?{loopId:s.id,loopVersion:s.version,loopStatus:s.status,resumeRequested:s.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!==v.hostname()||!Number.isSafeInteger(n.processId)||n.processId<=0)return!1;try{return process.kill(n.processId,0),!1}catch(s){return s.code==="ESRCH"}}recalculateProgress(e,n){let s=e.tasks.filter(t=>t.status==="completed").length;e.progress.completedTaskCount=s,e.progress.totalTaskCount=e.tasks.length,e.progress.percent=e.tasks.length?Math.round(s/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 s=e.goals.find(t=>t.id===n);if(!s)throw new u("NOT_FOUND",`Goal ${n} was not found`);return s}requireOwner(e,n,s){let t=e.owner;if(!t||t.ownerId!==n||t.leaseId!==s)throw new u("NOT_OWNER",`${n} does not own session ${e.sessionId}`,{owner:t});return t}assertVersion(e,n,s){if(!Number.isInteger(s)||s<1||n!==s)throw new u("CONFLICT",`Expected ${e} version ${s}, found ${n}`,{expected:s,actual:n})}newOwner(e,n,s,t){let o=s.leaseMs??this.ownerLeaseMs;if(!Number.isSafeInteger(o)||o<1)throw new u("INVALID","leaseMs must be a positive safe integer");return{ownerId:h(e,"ownerId",512),leaseId:this.idFactory("owner"),epoch:n,acquiredAt:t,heartbeatAt:t,expiresAt:new Date(A(t)+o).toISOString(),...s.processId!==void 0?{processId:s.processId}:{},...s.host?{host:h(s.host,"host",512)}:{}}}ownerExpired(e,n){return A(e.expiresAt)<=A(n)?!0:e.processId!==void 0&&e.host===v.hostname()&&!D(e.processId)}appendEvent(e,n,s){let t={schemaVersion:1,id:this.idFactory("event"),sequence:(e.events.at(-1)?.sequence??0)+1,type:n,sessionId:e.sessionId,...s.goalId?{goalId:s.goalId}:{},...s.loopId?{loopId:s.loopId}:{},...s.handoffId?{handoffId:s.handoffId}:{},...s.ownerId?{ownerId:s.ownerId}:{},timestamp:this.now(),data:w(s.data)};e.events.push(t),e.events.length>this.maximumEventsPerSession&&e.events.splice(0,e.events.length-this.maximumEventsPerSession)}async mutate(e,n,s=!1,t=()=>!0){let o=h(e,"sessionId",1024);return this.withSessionLock(o,async()=>{let r=await this.readState(o);if(r.admissionFence&&!s)throw new u("CONFLICT","Session execution is blocked by a persisted lifecycle fence");let i=r.schemaVersion;this.promoteGoalBudgetEnvelope(r),r.schemaVersion!==i&&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 I.join(this.rootDirectory,"sessions",`${K(e)}.json`)}lockPath(e){return`${this.statePath(e)}.lock`}async readState(e){let n=this.statePath(e);try{let s=await p.readFile(n,"utf8"),t=JSON.parse(s);if(!z.includes(t.schemaVersion)||t.sessionId!==e)throw new u("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 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(o=>o.targetLeaseEpoch??o.sourceLeaseEpoch??0))),t}catch(s){if(s.code!=="ENOENT")throw s;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(s=>s.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),s=I.dirname(n);await p.mkdir(s,{recursive:!0});let t=`${n}.${process.pid}.${T()}.tmp`,o=await p.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 p.open(s,"r");try{await r.sync()}finally{await r.close()}}catch{}}finally{await p.unlink(t).catch(()=>{})}}async renameReplacing(e,n){for(let s=0;;s+=1)try{await p.rename(e,n);return}catch(t){let o=t.code,r=J[s];if(process.platform!=="win32"||!o||!L.has(o)||r===void 0)throw t;await new Promise(i=>setTimeout(i,r))}}async withSessionLock(e,n){let s=this.lockPath(e),t=I.join(s,"owner.json"),o=T(),r=`${s}.candidate.${o}`,i=Date.now();await p.mkdir(I.dirname(s),{recursive:!0});let a={schemaVersion:1,token:o,pid:process.pid,host:v.hostname(),acquiredAt:this.now()};await p.mkdir(r),await p.writeFile(I.join(r,"owner.json"),JSON.stringify(a),{encoding:"utf8",flag:"wx"});for(let l=0;;l+=1)try{await p.rename(r,s);break}catch(c){let f=c.code;if(!(!!f&&new Set(["EEXIST","ENOTEMPTY","ENOTDIR","EBUSY"]).has(f)||process.platform==="win32"&&!!f&&L.has(f)))throw await p.rm(r,{recursive:!0,force:!0}).catch(()=>{}),c;let S=await this.staleLockOwner(s,t);if(S){await this.quarantineLock(s,S.token,"stale");continue}if(Date.now()-i>=this.lockTimeoutMs)throw await p.rm(r,{recursive:!0,force:!0}).catch(()=>{}),new u("CONFLICT",`Timed out waiting for coordination lock for session ${e}`);await new Promise(X=>setTimeout(X,Math.min(100,5+l*5)+Math.floor(Math.random()*10)))}try{return await n()}finally{await this.quarantineLock(s,o,"released"),await p.rm(r,{recursive:!0,force:!0}).catch(()=>{})}}async staleLockOwner(e,n){try{let[s,t]=await Promise.all([p.readFile(n,"utf8").catch(()=>""),p.stat(e)]),o=s?JSON.parse(s):void 0;return!o||o.host!==v.hostname()||D(o.pid)?void 0:Date.now()-t.mtimeMs>this.lockStaleMs?o:void 0}catch{return}}async quarantineLock(e,n,s){let t=I.join(e,"owner.json"),o=s==="stale"?`${e}.stale.${K(n)}`:`${e}.${s}.${n}.${T()}`;for(let r=0;;r+=1){let i;try{i=JSON.parse(await p.readFile(t,"utf8"))}catch(a){if(a.code==="ENOENT")return;throw a}if(i.token!==n)return;try{await p.rename(e,o);break}catch(a){let l=a.code;if(s==="stale")try{if(JSON.parse(await p.readFile(I.join(o,"owner.json"),"utf8")).token===n)return}catch{}if(l==="ENOENT"||l==="EEXIST")return;let c=J[r];if(process.platform!=="win32"||!l||!L.has(l)||c===void 0)throw a;await new Promise(f=>setTimeout(f,c))}}if(s!=="stale")for(let r=0;;r+=1)try{await p.rm(o,{recursive:!0});return}catch(i){let a=i.code;if(a==="ENOENT")return;let l=pe[r];if(process.platform!=="win32"||!a||!L.has(a)||l===void 0)throw i;await new Promise(c=>setTimeout(c,l))}}};function b(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 O(d,e){if(typeof d!="number"||!Number.isInteger(d))throw new Error(`${e} must be an integer`);return d}async function He(d,e){let{action:n,sessionId:s}=e,t=e.payload??{};if(t.sessionId!==void 0&&t.sessionId!==s)throw new u("INVALID","Payload sessionId must match the routed sessionId");let o;switch(n){case"state.get":o=await d.getSessionState(s);break;case"goal.create":o=await d.createGoal({...t,sessionId:s});break;case"goal.update":o=await d.updateGoal(s,g(t.goalId,"goalId"),O(t.expectedVersion,"expectedVersion"),b(t.update,"update"));break;case"goal.complete":o=await d.completeGoal(s,g(t.goalId,"goalId"),O(t.expectedVersion,"expectedVersion"),b(t.verification,"verification"));break;case"goal.cancel":o=await d.cancelGoal(s,g(t.goalId,"goalId"),O(t.expectedVersion,"expectedVersion"),g(t.reason,"reason"));break;case"goal.steer":o=await d.steerGoal(s,g(t.goalId,"goalId"),O(t.expectedVersion,"expectedVersion"),g(t.instruction,"instruction"));break;case"loop.start":o=await d.startLoop({sessionId:s,kind:g(t.kind,"kind"),...typeof t.goalId=="string"?{goalId:t.goalId}:{},...typeof t.activity=="string"?{activity:t.activity}:{},...t.schedule?{schedule:b(t.schedule,"schedule")}:{}});break;case"loop.get":o=await d.getLoop(s,typeof t.loopId=="string"?t.loopId:void 0);break;case"loop.begin":o=await d.beginLoopIteration(s,g(t.loopId,"loopId"),O(t.expectedVersion,"expectedVersion"),g(t.activity,"activity"),typeof t.taskId=="string"?t.taskId:void 0);break;case"loop.finish":o=await d.finishLoopIteration(s,g(t.loopId,"loopId"),O(t.expectedVersion,"expectedVersion"),b(t.result,"result"));break;case"loop.set_status":o=await d.setLoopStatus(s,g(t.loopId,"loopId"),O(t.expectedVersion,"expectedVersion"),g(t.status,"status"),typeof t.reason=="string"?t.reason:void 0);break;case"ownership.acquire":o=await d.acquireOwnership(s,g(t.ownerId,"ownerId"),b(t.options??{},"options"));break;case"ownership.renew":o=await d.renewOwnership(s,g(t.ownerId,"ownerId"),g(t.leaseId,"leaseId"),typeof t.leaseMs=="number"?t.leaseMs:void 0);break;case"ownership.release":o=await d.releaseOwnership(s,g(t.ownerId,"ownerId"),g(t.leaseId,"leaseId"));break;case"handoff.create":o=await d.createHandoff({...t,sessionId:s});break;case"handoff.claim":o=await d.claimHandoff({sessionId:s,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(s,g(t.handoffId,"handoffId"),g(t.ownerId,"ownerId"),g(t.leaseId,"leaseId"));break;case"handoff.fail":o=await d.failHandoff(s,g(t.handoffId,"handoffId"),g(t.reason,"reason"));break;default:throw new u("INVALID","Unsupported coordination action")}let r=await d.getSessionState(s),i=n==="state.get"||n==="loop.get"?void 0:r.events.at(-1);return{action:n,sessionId:s,result:o,state:r,...i?{event:i}:{}}}import{randomUUID as Ie}from"node:crypto";import{hostname as Ee}from"node:os";var Y=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 k,this.sessionId=e.sessionId,this.processId=e.processId??process.pid,this.host=e.host??Ee(),this.ownerId=e.ownerId??`runtime:${this.host}:${this.processId}:${Ie().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,s,t;try{let o=new Promise((r,i)=>{t=()=>i(n.reason??new Error("Destination preparation cancelled")),n.addEventListener("abort",t,{once:!0}),s=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{s&&clearTimeout(s),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.store.renewOwnership(this.sessionId,this.ownerId,this.owner.leaseId,this.leaseMs);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 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 s=await this.store.createHandoff({...e,sessionId:this.sessionId,sourceOwnerId:n.ownerId,sourceLeaseId:n.leaseId});return this.preparedHandoffId=s.id,this.handoffOutcomeUncertain=!1,s}catch(n){throw this.markLost(n instanceof Error?n:new Error("Handoff preparation failed",{cause:n})),n}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 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))}};import{createHash as ye}from"node:crypto";import{performance as M}from"node:perf_hooks";async function Je(d,e){let n=e.waitMs??0;if(!Number.isSafeInteger(n)||n<0||n>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 s=M.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 u("NOT_FOUND","Handoff not found in the authorized session");let r=ye("sha256").update(JSON.stringify([t.sessionId,o.id,o.version,o.status,t.ownershipEpoch,t.owner?.ownerId??null,t.owner?.epoch??null])).digest("hex"),i=e.sinceRevision===void 0||r!==e.sinceRevision;if(i||M.now()>=s)return{sessionId:t.sessionId,handoffId:o.id,revision:r,changed:i,status:o.status,handoffVersion:o.version,ownershipEpoch:t.ownershipEpoch,sourceOwnerId:o.sourceOwnerId,...o.targetOwnerId?{targetOwnerId:o.targetOwnerId}:{}};await new Promise((a,l)=>{let c=e.signal,m=setTimeout(()=>{c?.removeEventListener("abort",E),a()},Math.min(100,Math.max(1,s-M.now()))),E=()=>{clearTimeout(m),c?.removeEventListener("abort",E),l(c?.reason??new Error("Handoff wait cancelled"))};c?.addEventListener("abort",E,{once:!0}),c?.aborted&&E()})}}import{randomUUID as Oe}from"node:crypto";import{constants as Q}from"node:fs";import{lstat as G,mkdir as Z,open as F,realpath as q}from"node:fs/promises";import{dirname as H,isAbsolute as ee,join as P,relative as Se,resolve as Ae,sep as be}from"node:path";import{createHash as ve}from"node:crypto";function R(d){return{algorithm:"sha256",value:ve("sha256").update(d).digest("hex")}}var te=1e4,ne=8*1024*1024,oe=64*1024*1024;function re(d){if(typeof d!="string"||!d||d.length>2048||ee(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 se(d){return R(JSON.stringify([d.schemaVersion,d.sessionId,d.totalBytes,d.files.map(e=>[e.path,e.size,e.sha256,e.executable])])).value}function ie(d,e){if(d.schemaVersion!==1||d.sessionId!==e||!Array.isArray(d.files)||d.files.length>te||!Number.isSafeInteger(d.totalBytes)||d.totalBytes<0||d.totalBytes>oe)throw new Error("Invalid handoff snapshot manifest");let n=new Set,s=0;for(let t of d.files){if(re(t.path),!Number.isSafeInteger(t.size)||t.size<0||t.size>ne||!/^[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),s+=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(s!==d.totalBytes||se(d)!==d.digest)throw new Error("Handoff snapshot manifest integrity mismatch")}async function V(d,e){let n=d;for(let o of e.split("/"))if(n=P(n,o),(await G(n)).isSymbolicLink())throw new Error("Snapshot symlinks are not supported");let s=await q(n),t=Se(d,s);if(t===".."||t.startsWith(`..${be}`)||ee(t))throw new Error("Snapshot path escaped its root");return n}async function nt(d){if(!d.sessionId||d.sessionId.length>1024||d.paths.length>te)throw new Error("Invalid snapshot scope");let e=await q(d.root),n=[],s=new Map,t=0;for(let r of[...d.paths].sort()){if(d.signal?.throwIfAborted(),re(r),!await d.authorizeFile(r))throw new Error("Snapshot file transfer is not authorized");let i=await V(e,r),a=await G(i),l=await F(i,Q.O_RDONLY|(Q.O_NOFOLLOW??0));try{let c=await l.stat();if(await V(e,r),a.ino!==c.ino||a.dev!==c.dev||a.ctimeMs!==c.ctimeMs)throw new Error("Snapshot source was replaced before reading");if(!c.isFile()||c.size>ne||t+c.size>oe)throw new Error("Snapshot file or total byte limit exceeded");let f=Buffer.alloc(c.size),m=0;for(;m<f.length;){d.signal?.throwIfAborted();let{bytesRead:$}=await l.read(f,m,f.length-m,m);if(!$)throw new Error("Snapshot source changed while reading");m+=$}let E=await l.stat(),S=await G(i);if(await V(e,r),c.size!==E.size||c.mtimeMs!==E.mtimeMs||c.ctimeMs!==E.ctimeMs||S.isSymbolicLink()||S.ino!==c.ino||S.dev!==c.dev)throw new Error("Snapshot source changed while reading");let X=R(f).value;n.push({path:r,size:f.length,sha256:X,executable:(c.mode&73)!==0}),s.set(X,f),t+=f.length}finally{await l.close()}}let o={schemaVersion:1,sessionId:d.sessionId,files:n,totalBytes:t,digest:""};return o.digest=se(o),ie(o,d.sessionId),{manifest:o,blobs:s}}async function ot(d){let e=structuredClone(d.manifest);if(ie(e,d.sessionId),!await d.authorizeManifest(structuredClone(e)))throw new Error("Snapshot restoration is not authorized");d.signal?.throwIfAborted();let n=Ae(d.destination);if(await q(H(n))!==H(n))throw new Error("Snapshot destination parent must be canonical");try{throw await G(n),new Error("Snapshot destination already exists")}catch(r){if(r.code!=="ENOENT")throw r}let t=`${n}.staging-${Oe()}`;await Z(t,{mode:448});for(let r of e.files){d.signal?.throwIfAborted();let i=await d.readBlob(r.sha256,r.size);if(i.byteLength!==r.size||R(i).value!==r.sha256)throw new Error("Snapshot blob integrity mismatch; staging retained");let a=P(t,...r.path.split("/"));await Z(H(a),{recursive:!0,mode:448});let l=await F(a,"wx",r.executable?448:384);try{await l.writeFile(i),await l.sync()}finally{await l.close()}}d.signal?.throwIfAborted();let o=await F(P(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}}export{k as DurableXenoCoordinationStore,N as XENO_COORDINATION_BUDGET_SESSION_SCHEMA_VERSION,_ as XENO_COORDINATION_MANAGED_SESSION_SCHEMA_VERSION,y as XENO_COORDINATION_SCHEMA_VERSION,x as XENO_COORDINATION_TURN_SESSION_SCHEMA_VERSION,u as XenoCoordinationError,Y as XenoExecutionLeaseSession,nt as captureXenoHandoffSnapshot,He as executeXenoCoordinationAction,ot as restoreXenoHandoffSnapshot,Je as waitForXenoHandoffStatus};
@@ -1 +1 @@
1
- {"inputs":{"src/coordination/types.ts":{"bytes":9451,"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/coordination/store.ts":{"bytes":74862,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:fs/promises","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"src/utils/platform.ts","kind":"import-statement","original":"../utils/platform.js"},{"path":"src/coordination/types.ts","kind":"import-statement","original":"./types.js"}],"format":"esm"},"src/coordination/runtime.ts":{"bytes":6499,"imports":[{"path":"./store.js","kind":"import-statement","external":true},{"path":"src/coordination/types.ts","kind":"import-statement","original":"./types.js"}],"format":"esm"},"src/coordination/lease.ts":{"bytes":5947,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true},{"path":"src/coordination/store.ts","kind":"import-statement","original":"./store.js"}],"format":"esm"},"src/coordination/index.ts":{"bytes":114,"imports":[{"path":"src/coordination/types.ts","kind":"import-statement","original":"./types.js"},{"path":"src/coordination/store.ts","kind":"import-statement","original":"./store.js"},{"path":"src/coordination/runtime.ts","kind":"import-statement","original":"./runtime.js"},{"path":"src/coordination/lease.ts","kind":"import-statement","original":"./lease.js"}],"format":"esm"}},"outputs":{"dist/coordination/index.cjs":{"imports":[{"path":"node:crypto","kind":"require-call","external":true},{"path":"node:fs/promises","kind":"require-call","external":true},{"path":"node:os","kind":"require-call","external":true},{"path":"node:path","kind":"require-call","external":true},{"path":"node:os","kind":"require-call","external":true},{"path":"node:path","kind":"require-call","external":true},{"path":"node:crypto","kind":"require-call","external":true},{"path":"node:os","kind":"require-call","external":true}],"exports":[],"entryPoint":"src/coordination/index.ts","inputs":{"src/coordination/index.ts":{"bytesInOutput":371},"src/coordination/types.ts":{"bytesInOutput":148},"src/coordination/store.ts":{"bytesInOutput":36429},"src/utils/platform.ts":{"bytesInOutput":240},"src/coordination/runtime.ts":{"bytesInOutput":3142},"src/coordination/lease.ts":{"bytesInOutput":3143}},"bytes":44349}}}
1
+ {"inputs":{"src/coordination/types.ts":{"bytes":9630,"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/coordination/store.ts":{"bytes":81307,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:fs/promises","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"src/utils/platform.ts","kind":"import-statement","original":"../utils/platform.js"},{"path":"src/coordination/types.ts","kind":"import-statement","original":"./types.js"}],"format":"esm"},"src/coordination/runtime.ts":{"bytes":6499,"imports":[{"path":"./store.js","kind":"import-statement","external":true},{"path":"src/coordination/types.ts","kind":"import-statement","original":"./types.js"}],"format":"esm"},"src/coordination/lease.ts":{"bytes":12085,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true},{"path":"src/coordination/store.ts","kind":"import-statement","original":"./store.js"}],"format":"esm"},"src/coordination/handoff-status.ts":{"bytes":3331,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:perf_hooks","kind":"import-statement","external":true},{"path":"src/coordination/types.ts","kind":"import-statement","original":"./types.js"}],"format":"esm"},"src/artifacts/hash.ts":{"bytes":1489,"imports":[{"path":"node:crypto","kind":"import-statement","external":true}],"format":"esm"},"src/coordination/handoff-snapshot.ts":{"bytes":9170,"imports":[{"path":"node:crypto","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},{"path":"src/artifacts/hash.ts","kind":"import-statement","original":"../artifacts/hash.js"}],"format":"esm"},"src/coordination/index.ts":{"bytes":190,"imports":[{"path":"src/coordination/types.ts","kind":"import-statement","original":"./types.js"},{"path":"src/coordination/store.ts","kind":"import-statement","original":"./store.js"},{"path":"src/coordination/runtime.ts","kind":"import-statement","original":"./runtime.js"},{"path":"src/coordination/lease.ts","kind":"import-statement","original":"./lease.js"},{"path":"src/coordination/handoff-status.ts","kind":"import-statement","original":"./handoff-status.js"},{"path":"src/coordination/handoff-snapshot.ts","kind":"import-statement","original":"./handoff-snapshot.js"}],"format":"esm"}},"outputs":{"dist/coordination/index.cjs":{"imports":[{"path":"node:crypto","kind":"require-call","external":true},{"path":"node:fs/promises","kind":"require-call","external":true},{"path":"node:os","kind":"require-call","external":true},{"path":"node:path","kind":"require-call","external":true},{"path":"node:os","kind":"require-call","external":true},{"path":"node:path","kind":"require-call","external":true},{"path":"node:crypto","kind":"require-call","external":true},{"path":"node:os","kind":"require-call","external":true},{"path":"node:crypto","kind":"require-call","external":true},{"path":"node:perf_hooks","kind":"require-call","external":true},{"path":"node:crypto","kind":"require-call","external":true},{"path":"node:fs","kind":"require-call","external":true},{"path":"node:fs/promises","kind":"require-call","external":true},{"path":"node:path","kind":"require-call","external":true},{"path":"node:crypto","kind":"require-call","external":true}],"exports":[],"entryPoint":"src/coordination/index.ts","inputs":{"src/coordination/index.ts":{"bytesInOutput":473},"src/coordination/types.ts":{"bytesInOutput":148},"src/coordination/store.ts":{"bytesInOutput":39387},"src/utils/platform.ts":{"bytesInOutput":240},"src/coordination/runtime.ts":{"bytesInOutput":3142},"src/coordination/lease.ts":{"bytesInOutput":6113},"src/coordination/handoff-status.ts":{"bytesInOutput":1502},"src/coordination/handoff-snapshot.ts":{"bytesInOutput":4716},"src/artifacts/hash.ts":{"bytesInOutput":129}},"bytes":56817}}}
@@ -1 +1 @@
1
- {"inputs":{"src/coordination/types.ts":{"bytes":9451,"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/coordination/store.ts":{"bytes":74862,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:fs/promises","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"src/utils/platform.ts","kind":"import-statement","original":"../utils/platform.js"},{"path":"src/coordination/types.ts","kind":"import-statement","original":"./types.js"}],"format":"esm"},"src/coordination/runtime.ts":{"bytes":6499,"imports":[{"path":"./store.js","kind":"import-statement","external":true},{"path":"src/coordination/types.ts","kind":"import-statement","original":"./types.js"}],"format":"esm"},"src/coordination/lease.ts":{"bytes":5947,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true},{"path":"src/coordination/store.ts","kind":"import-statement","original":"./store.js"}],"format":"esm"},"src/coordination/index.ts":{"bytes":114,"imports":[{"path":"src/coordination/types.ts","kind":"import-statement","original":"./types.js"},{"path":"src/coordination/store.ts","kind":"import-statement","original":"./store.js"},{"path":"src/coordination/runtime.ts","kind":"import-statement","original":"./runtime.js"},{"path":"src/coordination/lease.ts","kind":"import-statement","original":"./lease.js"}],"format":"esm"}},"outputs":{"dist/coordination/index.js":{"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:fs/promises","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:path","kind":"import-statement","external":true},{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true}],"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","executeXenoCoordinationAction"],"entryPoint":"src/coordination/index.ts","inputs":{"src/coordination/types.ts":{"bytesInOutput":148},"src/coordination/index.ts":{"bytesInOutput":0},"src/coordination/store.ts":{"bytesInOutput":36367},"src/utils/platform.ts":{"bytesInOutput":216},"src/coordination/runtime.ts":{"bytesInOutput":3142},"src/coordination/lease.ts":{"bytesInOutput":3143}},"bytes":43349}}}
1
+ {"inputs":{"src/coordination/types.ts":{"bytes":9630,"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/coordination/store.ts":{"bytes":81307,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:fs/promises","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"src/utils/platform.ts","kind":"import-statement","original":"../utils/platform.js"},{"path":"src/coordination/types.ts","kind":"import-statement","original":"./types.js"}],"format":"esm"},"src/coordination/runtime.ts":{"bytes":6499,"imports":[{"path":"./store.js","kind":"import-statement","external":true},{"path":"src/coordination/types.ts","kind":"import-statement","original":"./types.js"}],"format":"esm"},"src/coordination/lease.ts":{"bytes":12085,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true},{"path":"src/coordination/store.ts","kind":"import-statement","original":"./store.js"}],"format":"esm"},"src/coordination/handoff-status.ts":{"bytes":3331,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:perf_hooks","kind":"import-statement","external":true},{"path":"src/coordination/types.ts","kind":"import-statement","original":"./types.js"}],"format":"esm"},"src/artifacts/hash.ts":{"bytes":1489,"imports":[{"path":"node:crypto","kind":"import-statement","external":true}],"format":"esm"},"src/coordination/handoff-snapshot.ts":{"bytes":9170,"imports":[{"path":"node:crypto","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},{"path":"src/artifacts/hash.ts","kind":"import-statement","original":"../artifacts/hash.js"}],"format":"esm"},"src/coordination/index.ts":{"bytes":190,"imports":[{"path":"src/coordination/types.ts","kind":"import-statement","original":"./types.js"},{"path":"src/coordination/store.ts","kind":"import-statement","original":"./store.js"},{"path":"src/coordination/runtime.ts","kind":"import-statement","original":"./runtime.js"},{"path":"src/coordination/lease.ts","kind":"import-statement","original":"./lease.js"},{"path":"src/coordination/handoff-status.ts","kind":"import-statement","original":"./handoff-status.js"},{"path":"src/coordination/handoff-snapshot.ts","kind":"import-statement","original":"./handoff-snapshot.js"}],"format":"esm"}},"outputs":{"dist/coordination/index.js":{"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:fs/promises","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:path","kind":"import-statement","external":true},{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true},{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:perf_hooks","kind":"import-statement","external":true},{"path":"node:crypto","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},{"path":"node:crypto","kind":"import-statement","external":true}],"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"],"entryPoint":"src/coordination/index.ts","inputs":{"src/coordination/types.ts":{"bytesInOutput":148},"src/coordination/index.ts":{"bytesInOutput":0},"src/coordination/store.ts":{"bytesInOutput":39343},"src/utils/platform.ts":{"bytesInOutput":220},"src/coordination/runtime.ts":{"bytesInOutput":3142},"src/coordination/lease.ts":{"bytesInOutput":6113},"src/coordination/handoff-status.ts":{"bytesInOutput":1480},"src/coordination/handoff-snapshot.ts":{"bytesInOutput":4602},"src/artifacts/hash.ts":{"bytesInOutput":126}},"bytes":55604}}}