@xenosystem/agent-sdk 0.10.30 → 0.10.32
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.
- package/dist/artifacts/index.cjs +6 -6
- package/dist/artifacts/index.js +7 -7
- package/dist/artifacts/metafile-cjs.json +1 -1
- package/dist/artifacts/metafile-esm.json +1 -1
- package/dist/automation/index.cjs +1 -1
- package/dist/automation/index.d.cts +6 -2
- package/dist/automation/index.d.ts +6 -2
- package/dist/automation/index.js +1 -1
- package/dist/automation/metafile-cjs.json +1 -1
- package/dist/automation/metafile-esm.json +1 -1
- package/dist/control-plane/index.cjs +1 -1
- package/dist/control-plane/index.js +1 -1
- package/dist/coordination/index.cjs +2 -2
- package/dist/coordination/index.d.cts +9 -3
- package/dist/coordination/index.d.ts +9 -3
- package/dist/coordination/index.js +2 -2
- package/dist/coordination/metafile-cjs.json +1 -1
- package/dist/coordination/metafile-esm.json +1 -1
- package/dist/electron/index.cjs +222 -188
- package/dist/electron/index.d.cts +8 -2
- package/dist/electron/index.d.ts +8 -2
- package/dist/electron/index.js +222 -188
- package/dist/electron/metafile-cjs.json +1 -1
- package/dist/electron/metafile-esm.json +1 -1
- package/dist/hooks/index.cjs +4 -4
- package/dist/hooks/index.d.cts +18 -0
- package/dist/hooks/index.d.ts +18 -0
- package/dist/hooks/index.js +4 -4
- package/dist/hooks/metafile-cjs.json +1 -1
- package/dist/hooks/metafile-esm.json +1 -1
- package/dist/hosted/index.cjs +1 -1
- package/dist/hosted/index.d.cts +21 -3
- package/dist/hosted/index.d.ts +21 -3
- package/dist/hosted/index.js +1 -1
- package/dist/hosted/metafile-cjs.json +1 -1
- package/dist/hosted/metafile-esm.json +1 -1
- package/dist/index.cjs +432 -380
- package/dist/index.d.cts +283 -19
- package/dist/index.d.ts +283 -19
- package/dist/index.js +431 -379
- package/dist/intelligence/index.cjs +5 -5
- package/dist/intelligence/index.js +6 -6
- package/dist/intelligence/metafile-cjs.json +1 -1
- package/dist/intelligence/metafile-esm.json +1 -1
- package/dist/mcp/index.cjs +21 -21
- package/dist/mcp/index.d.cts +61 -6
- package/dist/mcp/index.d.ts +61 -6
- package/dist/mcp/index.js +21 -21
- package/dist/mcp/metafile-cjs.json +1 -1
- package/dist/mcp/metafile-esm.json +1 -1
- package/dist/metafile-cjs.json +1 -1
- package/dist/metafile-esm.json +1 -1
- package/dist/providers/metafile-cjs.json +1 -1
- package/dist/providers/metafile-esm.json +1 -1
- package/dist/recipes/metafile-cjs.json +1 -1
- package/dist/recipes/metafile-esm.json +1 -1
- package/dist/research/metafile-cjs.json +1 -1
- package/dist/research/metafile-esm.json +1 -1
- package/dist/session/index.cjs +24 -24
- package/dist/session/index.js +21 -21
- package/dist/session/metafile-cjs.json +1 -1
- package/dist/session/metafile-esm.json +1 -1
- package/dist/sharing/index.cjs +2 -2
- package/dist/sharing/index.js +3 -3
- package/dist/sharing/metafile-cjs.json +1 -1
- package/dist/sharing/metafile-esm.json +1 -1
- package/dist/skills/index.d.cts +5 -1
- package/dist/skills/index.d.ts +5 -1
- package/dist/utils/index.cjs +19 -18
- package/dist/utils/index.d.cts +5 -2
- package/dist/utils/index.d.ts +5 -2
- package/dist/utils/index.js +19 -18
- package/dist/utils/metafile-cjs.json +1 -1
- package/dist/utils/metafile-esm.json +1 -1
- package/package.json +2 -2
|
@@ -200,6 +200,7 @@ interface XenoHandoffRecord {
|
|
|
200
200
|
completedAt?: string;
|
|
201
201
|
failedAt?: string;
|
|
202
202
|
failureReason?: string;
|
|
203
|
+
cancelledAt?: string;
|
|
203
204
|
}
|
|
204
205
|
interface XenoExecutionOwner {
|
|
205
206
|
ownerId: string;
|
|
@@ -211,7 +212,7 @@ interface XenoExecutionOwner {
|
|
|
211
212
|
processId?: number;
|
|
212
213
|
host?: string;
|
|
213
214
|
}
|
|
214
|
-
type XenoCoordinationEventType = "goal.created" | "goal.updated" | "goal.steered" | "goal.completed" | "goal.cancelled" | "loop.started" | "loop.iteration" | "loop.paused" | "loop.waiting" | "loop.resumed" | "loop.stopped" | "loop.completed" | "loop.failed" | "handoff.created" | "handoff.claimed" | "handoff.completed" | "handoff.failed" | "ownership.acquired" | "admission.fenced" | "admission.restored" | "ownership.renewed" | "ownership.recovered" | "ownership.released";
|
|
215
|
+
type XenoCoordinationEventType = "goal.created" | "goal.updated" | "goal.steered" | "goal.completed" | "goal.cancelled" | "loop.started" | "loop.iteration" | "loop.paused" | "loop.waiting" | "loop.resumed" | "loop.stopped" | "loop.completed" | "loop.failed" | "handoff.created" | "handoff.claimed" | "handoff.completed" | "handoff.failed" | "handoff.cancelled" | "ownership.acquired" | "admission.fenced" | "admission.restored" | "ownership.renewed" | "ownership.recovered" | "ownership.released";
|
|
215
216
|
interface XenoCoordinationEvent {
|
|
216
217
|
schemaVersion: typeof XENO_COORDINATION_SCHEMA_VERSION;
|
|
217
218
|
id: string;
|
|
@@ -460,6 +461,7 @@ declare class DurableXenoCoordinationStore {
|
|
|
460
461
|
owner: XenoExecutionOwner;
|
|
461
462
|
}>;
|
|
462
463
|
completeHandoff(sessionId: string, handoffId: string, ownerId: string, leaseId: string): Promise<XenoHandoffRecord>;
|
|
464
|
+
cancelHandoff(sessionId: string, handoffId: string, ownerId: string, leaseId: string): Promise<XenoHandoffRecord>;
|
|
463
465
|
failHandoff(sessionId: string, handoffId: string, reason: string): Promise<XenoHandoffRecord>;
|
|
464
466
|
private mutateGoal;
|
|
465
467
|
private mutateLoop;
|
|
@@ -503,7 +505,7 @@ interface ExecuteXenoCoordinationActionResult {
|
|
|
503
505
|
event?: XenoCoordinationEvent;
|
|
504
506
|
}
|
|
505
507
|
declare function executeXenoCoordinationAction(store: DurableXenoCoordinationStore, input: ExecuteXenoCoordinationActionInput): Promise<ExecuteXenoCoordinationActionResult>;
|
|
506
|
-
type XenoExecutionLeaseStore = Pick<DurableXenoCoordinationStore, "acquireOwnership" | "claimHandoff" | "completeHandoff" | "renewOwnership" | "releaseOwnership" | "createHandoff"> & Partial<Pick<DurableXenoCoordinationStore, "recoverExpiredOwnership">>;
|
|
508
|
+
type XenoExecutionLeaseStore = Pick<DurableXenoCoordinationStore, "acquireOwnership" | "claimHandoff" | "completeHandoff" | "renewOwnership" | "releaseOwnership" | "createHandoff"> & Partial<Pick<DurableXenoCoordinationStore, "recoverExpiredOwnership">> & Partial<Pick<DurableXenoCoordinationStore, "cancelHandoff">>;
|
|
507
509
|
interface XenoExecutionLeaseSessionOptions {
|
|
508
510
|
store?: XenoExecutionLeaseStore;
|
|
509
511
|
sessionId: string;
|
|
@@ -557,6 +559,7 @@ declare class XenoExecutionLeaseSession {
|
|
|
557
559
|
private renewHeldLease;
|
|
558
560
|
private renewOrRecover;
|
|
559
561
|
prepareHandoff(input?: Omit<CreateXenoHandoffInput, "sessionId" | "sourceOwnerId" | "sourceLeaseId">): Promise<XenoHandoffRecord>;
|
|
562
|
+
cancelPreparedHandoff(): Promise<XenoHandoffRecord>;
|
|
560
563
|
stop(options?: {
|
|
561
564
|
release?: boolean;
|
|
562
565
|
}): Promise<void>;
|
|
@@ -620,4 +623,7 @@ declare function restoreXenoHandoffSnapshot(input: {
|
|
|
620
623
|
files: number;
|
|
621
624
|
bytes: number;
|
|
622
625
|
}>;
|
|
623
|
-
|
|
626
|
+
declare const XENO_CONTEXT_DIGEST_PATTERN: RegExp;
|
|
627
|
+
declare function isXenoContextDigest(value: unknown): value is string;
|
|
628
|
+
declare function computeXenoContextDigest(content: string | Uint8Array): string;
|
|
629
|
+
export { type ClaimXenoHandoffInput, type CreateXenoGoalInput, type CreateXenoHandoffInput, DurableXenoCoordinationStore, type ExecuteXenoCoordinationActionInput, type ExecuteXenoCoordinationActionResult, type StartXenoLoopInput, type UpdateXenoGoalInput, XENO_CONTEXT_DIGEST_PATTERN, XENO_COORDINATION_BUDGET_SESSION_SCHEMA_VERSION, XENO_COORDINATION_MANAGED_SESSION_SCHEMA_VERSION, XENO_COORDINATION_SCHEMA_VERSION, XENO_COORDINATION_TURN_SESSION_SCHEMA_VERSION, 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, computeXenoContextDigest, executeXenoCoordinationAction, isXenoContextDigest, restoreXenoHandoffSnapshot, waitForXenoHandoffStatus };
|
|
@@ -200,6 +200,7 @@ interface XenoHandoffRecord {
|
|
|
200
200
|
completedAt?: string;
|
|
201
201
|
failedAt?: string;
|
|
202
202
|
failureReason?: string;
|
|
203
|
+
cancelledAt?: string;
|
|
203
204
|
}
|
|
204
205
|
interface XenoExecutionOwner {
|
|
205
206
|
ownerId: string;
|
|
@@ -211,7 +212,7 @@ interface XenoExecutionOwner {
|
|
|
211
212
|
processId?: number;
|
|
212
213
|
host?: string;
|
|
213
214
|
}
|
|
214
|
-
type XenoCoordinationEventType = "goal.created" | "goal.updated" | "goal.steered" | "goal.completed" | "goal.cancelled" | "loop.started" | "loop.iteration" | "loop.paused" | "loop.waiting" | "loop.resumed" | "loop.stopped" | "loop.completed" | "loop.failed" | "handoff.created" | "handoff.claimed" | "handoff.completed" | "handoff.failed" | "ownership.acquired" | "admission.fenced" | "admission.restored" | "ownership.renewed" | "ownership.recovered" | "ownership.released";
|
|
215
|
+
type XenoCoordinationEventType = "goal.created" | "goal.updated" | "goal.steered" | "goal.completed" | "goal.cancelled" | "loop.started" | "loop.iteration" | "loop.paused" | "loop.waiting" | "loop.resumed" | "loop.stopped" | "loop.completed" | "loop.failed" | "handoff.created" | "handoff.claimed" | "handoff.completed" | "handoff.failed" | "handoff.cancelled" | "ownership.acquired" | "admission.fenced" | "admission.restored" | "ownership.renewed" | "ownership.recovered" | "ownership.released";
|
|
215
216
|
interface XenoCoordinationEvent {
|
|
216
217
|
schemaVersion: typeof XENO_COORDINATION_SCHEMA_VERSION;
|
|
217
218
|
id: string;
|
|
@@ -460,6 +461,7 @@ declare class DurableXenoCoordinationStore {
|
|
|
460
461
|
owner: XenoExecutionOwner;
|
|
461
462
|
}>;
|
|
462
463
|
completeHandoff(sessionId: string, handoffId: string, ownerId: string, leaseId: string): Promise<XenoHandoffRecord>;
|
|
464
|
+
cancelHandoff(sessionId: string, handoffId: string, ownerId: string, leaseId: string): Promise<XenoHandoffRecord>;
|
|
463
465
|
failHandoff(sessionId: string, handoffId: string, reason: string): Promise<XenoHandoffRecord>;
|
|
464
466
|
private mutateGoal;
|
|
465
467
|
private mutateLoop;
|
|
@@ -503,7 +505,7 @@ interface ExecuteXenoCoordinationActionResult {
|
|
|
503
505
|
event?: XenoCoordinationEvent;
|
|
504
506
|
}
|
|
505
507
|
declare function executeXenoCoordinationAction(store: DurableXenoCoordinationStore, input: ExecuteXenoCoordinationActionInput): Promise<ExecuteXenoCoordinationActionResult>;
|
|
506
|
-
type XenoExecutionLeaseStore = Pick<DurableXenoCoordinationStore, "acquireOwnership" | "claimHandoff" | "completeHandoff" | "renewOwnership" | "releaseOwnership" | "createHandoff"> & Partial<Pick<DurableXenoCoordinationStore, "recoverExpiredOwnership">>;
|
|
508
|
+
type XenoExecutionLeaseStore = Pick<DurableXenoCoordinationStore, "acquireOwnership" | "claimHandoff" | "completeHandoff" | "renewOwnership" | "releaseOwnership" | "createHandoff"> & Partial<Pick<DurableXenoCoordinationStore, "recoverExpiredOwnership">> & Partial<Pick<DurableXenoCoordinationStore, "cancelHandoff">>;
|
|
507
509
|
interface XenoExecutionLeaseSessionOptions {
|
|
508
510
|
store?: XenoExecutionLeaseStore;
|
|
509
511
|
sessionId: string;
|
|
@@ -557,6 +559,7 @@ declare class XenoExecutionLeaseSession {
|
|
|
557
559
|
private renewHeldLease;
|
|
558
560
|
private renewOrRecover;
|
|
559
561
|
prepareHandoff(input?: Omit<CreateXenoHandoffInput, "sessionId" | "sourceOwnerId" | "sourceLeaseId">): Promise<XenoHandoffRecord>;
|
|
562
|
+
cancelPreparedHandoff(): Promise<XenoHandoffRecord>;
|
|
560
563
|
stop(options?: {
|
|
561
564
|
release?: boolean;
|
|
562
565
|
}): Promise<void>;
|
|
@@ -620,4 +623,7 @@ declare function restoreXenoHandoffSnapshot(input: {
|
|
|
620
623
|
files: number;
|
|
621
624
|
bytes: number;
|
|
622
625
|
}>;
|
|
623
|
-
|
|
626
|
+
declare const XENO_CONTEXT_DIGEST_PATTERN: RegExp;
|
|
627
|
+
declare function isXenoContextDigest(value: unknown): value is string;
|
|
628
|
+
declare function computeXenoContextDigest(content: string | Uint8Array): string;
|
|
629
|
+
export { type ClaimXenoHandoffInput, type CreateXenoGoalInput, type CreateXenoHandoffInput, DurableXenoCoordinationStore, type ExecuteXenoCoordinationActionInput, type ExecuteXenoCoordinationActionResult, type StartXenoLoopInput, type UpdateXenoGoalInput, XENO_CONTEXT_DIGEST_PATTERN, XENO_COORDINATION_BUDGET_SESSION_SCHEMA_VERSION, XENO_COORDINATION_MANAGED_SESSION_SCHEMA_VERSION, XENO_COORDINATION_SCHEMA_VERSION, XENO_COORDINATION_TURN_SESSION_SCHEMA_VERSION, 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, computeXenoContextDigest, executeXenoCoordinationAction, isXenoContextDigest, restoreXenoHandoffSnapshot, waitForXenoHandoffStatus };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var v=1,G=2,x=3,R=4,u=class extends Error{constructor(o,i,t={}){super(i);this.code=o;this.details=t;this.name="XenoCoordinationError"}code;details};import{createHash as pe,randomUUID as L}from"node:crypto";import*as h from"node:fs/promises";import*as b from"node:os";import*as I from"node:path";import{homedir as Q,platform as ue,release as fe}from"node:os";import{resolve as z}from"node:path";var ke=ue();var _e=fe(),De=Q();function J(){let d=process.env.XENO_AGENT_HOME?.trim();return d?z(d):z(Q(),".xeno-agent")}var X=class extends Error{constructor(o,i){super(i);this.code=o;this.name="QuotaError"}code;retryable=!1};function W(d){if(typeof d!="string"||!d.trim()||d.length>512)throw new X("INVALID","Invalid quota identity.");return d}function V(d){let e=o=>({id:W(o?.id),generation:W(o?.generation)});if(!d||d.agent&&!d.team)throw new X("INVALID","A child quota scope requires its complete ancestry.");return{workspace:e(d.workspace),...d.team?{team:e(d.team)}:{},...d.agent?{agent:e(d.agent)}:{},...d.goal!==void 0?{goal:e(d.goal)}:{}}}function M(d){return JSON.stringify(V(d))}var he=3e4,me=3e4,ge=6e4,we=2e4,N=new Set(["EACCES","EBUSY","EPERM"]),K=[5,10,20,40,80,160,320],Ie=[5,10,20,40,80,160,320],Y=[1,2,3,4];function p(d,e,o=16384){let i=d.trim();if(!i||i.length>o)throw new u("INVALID",`${e} must be non-empty and no longer than ${o} characters`);return i}function C(d,e){return[...new Set((d??[]).map(o=>p(o,e)))]}function Z(d){if(d===void 0)return;if(!d||typeof d!="object"||Array.isArray(d))throw new u("INVALID","Goal limits must be an object when provided");let e={};for(let[o,i]of Object.entries(d)){if(o!=="maxIterations"&&o!=="maxTokens"&&o!=="maxWallClockMs")throw new u("INVALID","Unknown goal limit");if(i!==void 0){if(!Number.isSafeInteger(i)||i<=0)throw new u("INVALID",`${o} must be a positive safe integer when provided`);e[o]=i}}return e}function Ee(d){if(d){if(d.kind!=="fixed-interval"&&d.kind!=="dynamic")throw new u("INVALID","schedule.kind must be fixed-interval or dynamic");if(d.kind==="fixed-interval"&&(!Number.isSafeInteger(d.intervalMs)||(d.intervalMs??0)<=0))throw new u("INVALID","Fixed-interval schedules require a positive safe intervalMs");if(d.intervalMs!==void 0&&(!Number.isSafeInteger(d.intervalMs)||d.intervalMs<=0))throw new u("INVALID","schedule.intervalMs must be a positive safe integer when provided");for(let e of["nextRunAt","expiresAt"]){let o=d[e];if(o!==void 0&&!Number.isFinite(Date.parse(o)))throw new u("INVALID",`schedule.${e} must be an ISO timestamp when provided`)}return w(d)}}function w(d){return structuredClone(d)}function y(d){let e=Date.parse(d);return Number.isFinite(e)?e:0}function k(d){if(!Number.isInteger(d)||d<=0)return!1;try{return process.kill(d,0),!0}catch(e){return e.code==="EPERM"}}function ye(d){return{summary:"Goal created; work has not started.",completedTaskCount:0,totalTaskCount:0,outstanding:[],decisions:[],updatedAt:d}}function ve(){return{status:"pending",criteria:[],evidence:[]}}function ee(d){return pe("sha256").update(d).digest("hex")}var _=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??(o=>`${o}_${L()}`),this.ownerLeaseMs=e.ownerLeaseMs??he,this.lockTimeoutMs=e.lockTimeoutMs??me,this.lockStaleMs=e.lockStaleMs??ge,this.maximumEventsPerSession=e.maximumEventsPerSession??we}async getSessionState(e){let o=p(e,"sessionId",1024);return w(await this.readState(o))}async fenceAdmission(e,o,i){let t=p(i.authorityId,"authorityId",512),n=p(i.operationId,"operationId",512);if(!Number.isSafeInteger(o)||o<0)throw new u("INVALID","Expected session version must be a nonnegative safe integer");if(i.action!=="archive"&&i.action!=="delete")throw new u("INVALID","Unsupported admission fence action");return this.mutate(e,r=>{let s=r.admissionFence;if(s?.authorityId===t&&s.operationId===n&&s.action===i.action)return s;if(r.version!==o)throw new u("CONFLICT","Session version changed before lifecycle fencing",{expected:o,actual:r.version});if(s?.authorityId===t&&s.action==="archive"&&i.action==="archive")return s;if(s&&!(s.authorityId===t&&s.action==="archive"&&i.action==="delete"))throw new u("CONFLICT","Another lifecycle fence already owns this session");let a={schemaVersion:1,authorityId:t,operationId:n,action:i.action,createdAt:this.now()};return r.admissionFence=a,r.schemaVersion===1&&(r.schemaVersion=2),this.appendEvent(r,"admission.fenced",{data:{authorityId:t,operationId:n,action:i.action}}),a},!0)}async clearAdmissionFence(e,o,i,t){await this.mutate(e,n=>{this.assertVersion(e,n.version,o);let r=n.admissionFence;if(!r||r.authorityId!==i||r.operationId!==t)throw new u("CONFLICT","Lifecycle fence identity does not match");if(r.action==="delete")throw new u("CONFLICT","Deleted session admission cannot be restored");if(n.owner)throw new u("CONFLICT","Execution ownership must settle before restoration");n.admissionFence=void 0,this.appendEvent(n,"admission.restored",{data:{authorityId:i,operationId:t}})},!0)}async releaseDeadLifecycleOwner(e,o,i,t){await this.mutate(e,n=>{this.assertVersion(e,n.version,o);let r=n.admissionFence;if(!r||r.authorityId!==i||r.operationId!==t)throw new u("CONFLICT","Lifecycle fence identity does not match");let s=n.owner;if(s){if(s.host!==b.hostname()||!Number.isInteger(s.processId)||(s.processId??0)<=0||k(s.processId))throw new u("CONFLICT","Execution owner exit has not been proved");n.owner=void 0,this.appendEvent(n,"ownership.released",{ownerId:s.ownerId,data:{epoch:s.epoch,reason:"fenced-local-owner-exited"}})}},!0)}async listSessionStates(){let e=I.join(this.rootDirectory,"sessions"),o;try{o=await h.readdir(e)}catch(t){if(t.code==="ENOENT")return[];throw t}return(await Promise.all(o.filter(t=>t.endsWith(".json")).map(async t=>{try{let n=JSON.parse(await h.readFile(I.join(e,t),"utf8"));return!Y.includes(n.schemaVersion)||typeof n.sessionId!="string"?void 0:((!Number.isSafeInteger(n.ownershipEpoch)||n.ownershipEpoch<0)&&(n.ownershipEpoch=Math.max(n.owner?.epoch??0,...n.handoffs.map(r=>r.targetLeaseEpoch??r.sourceLeaseEpoch??0))),n)}catch{return}}))).filter(t=>t!==void 0).sort((t,n)=>y(n.updatedAt)-y(t.updatedAt)).map(t=>w(t))}async createGoal(e){let o=p(e.sessionId,"sessionId",1024),i=Z(e.limits);return this.mutate(o,t=>{let n=t.goals.find(c=>["active","paused","waiting","blocked"].includes(c.status));if(n)throw new u("CONFLICT",`Session ${o} already has active goal ${n.id}`);let r=this.now(),s=(e.successCriteria??[]).map(c=>typeof c=="string"?{id:this.idFactory("criterion"),description:p(c,"successCriteria"),required:!0}:{id:c.id?p(c.id,"successCriteria.id",512):this.idFactory("criterion"),description:p(c.description,"successCriteria.description"),required:c.required}),a={schemaVersion:1,id:this.idFactory("goal"),version:1,sessionId:o,objective:p(e.objective,"objective"),...e.why?{why:p(e.why,"why")}:{},successCriteria:s,constraints:C(e.constraints,"constraints"),...i?{limits:i}:{},metadata:w(e.metadata??{}),status:"active",milestones:[],tasks:[],progress:ye(r),verification:ve(),steering:[],createdAt:r,updatedAt:r};return t.goals.push(a),this.appendEvent(t,"goal.created",{goalId:a.id,data:{objective:a.objective}}),a})}async getGoal(e,o){let i=await this.getSessionState(e),t=o?i.goals.find(n=>n.id===o):[...i.goals].reverse().find(n=>["active","paused","waiting","blocked"].includes(n.status));return t?w(t):void 0}async updateGoal(e,o,i,t){return this.mutate(e,n=>{let r=this.requireGoal(n,o);if(this.assertVersion(r.id,r.version,i),["completed","cancelled","failed"].includes(r.status))throw new u("CONFLICT",`Goal ${r.id} is terminal (${r.status})`);let s=r.status!=="active";if(t.status==="active"&&r.status==="blocked"?r.status="active":t.status&&(r.status=t.status),t.objective!==void 0&&(r.objective=p(t.objective,"objective")),t.why!==void 0&&(r.why=p(t.why,"why")),t.constraints&&(r.constraints=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)),s&&r.status==="active")for(let a of n.loops.filter(c=>c.goalId===o&&c.kind==="goal-continuation"&&c.status==="running"))a.resumeRequested=!0,a.version+=1,a.updatedAt=this.now();return r.version+=1,r.updatedAt=this.now(),this.appendEvent(n,"goal.updated",{goalId:r.id,data:{status:r.status,version:r.version}}),r},t.status!==void 0&&["paused","cancelled","failed"].includes(t.status))}async addMilestone(e,o,i,t){return this.mutateGoal(e,o,i,(n,r)=>{let s={id:this.idFactory("milestone"),title:p(t.title,"milestone.title"),...t.description?{description:p(t.description,"milestone.description")}:{},status:n.milestones.some(a=>a.status==="active")?"pending":"active",taskIds:[],createdAt:r,updatedAt:r};n.milestones.push(s),n.progress.currentMilestoneId??=s.id,n.progress.updatedAt=r})}async addTask(e,o,i,t){return this.mutateGoal(e,o,i,(n,r)=>{let s=n.milestones.find(l=>l.id===t.milestoneId);if(!s)throw new u("NOT_FOUND",`Milestone ${t.milestoneId} was not found`);if(t.parentTaskId&&!n.tasks.some(l=>l.id===t.parentTaskId))throw new u("NOT_FOUND",`Parent task ${t.parentTaskId} was not found`);let a=[...new Set(t.dependsOn??[])];for(let l of a)if(!n.tasks.some(f=>f.id===l))throw new u("NOT_FOUND",`Task dependency ${l} was not found`);let c={id:this.idFactory("task"),milestoneId:s.id,...t.parentTaskId?{parentTaskId:t.parentTaskId}:{},title:p(t.title,"task.title"),...t.description?{description:p(t.description,"task.description")}:{},status:a.length===0?"ready":"pending",...t.assignedAgentId?{assignedAgentId:p(t.assignedAgentId,"task.assignedAgentId",512)}:{},...a.length?{dependsOn:a}:{},createdAt:r,updatedAt:r};n.tasks.push(c),s.taskIds.push(c.id),s.updatedAt=r,n.progress.totalTaskCount=n.tasks.length,n.progress.outstanding=n.tasks.filter(l=>l.status!=="completed").map(l=>l.title),n.progress.updatedAt=r})}async updateTask(e,o,i,t,n){return this.mutateGoal(e,o,t,(r,s)=>{let a=r.tasks.find(l=>l.id===i);if(!a)throw new u("NOT_FOUND",`Task ${i} was not found`);a.status=n.status,n.progress!==void 0&&(a.progress=p(n.progress,"task.progress")),n.resultEventId!==void 0&&(a.resultEventId=p(n.resultEventId,"task.resultEventId",512)),n.assignedAgentId!==void 0&&(a.assignedAgentId=p(n.assignedAgentId,"task.assignedAgentId",512)),a.updatedAt=s,a.status==="completed"&&(a.completedAt=s);let c=r.milestones.find(l=>l.id===a.milestoneId);if(c){let l=r.tasks.filter(f=>f.milestoneId===c.id);l.length>0&&l.every(f=>f.status==="completed")?(c.status="completed",c.completedAt=s):l.some(f=>f.status==="running")?c.status="active":l.some(f=>f.status==="blocked")&&(c.status="blocked"),c.updatedAt=s}for(let l of r.tasks)l.status!=="pending"||!l.dependsOn?.length||l.dependsOn.every(f=>r.tasks.find(m=>m.id===f)?.status==="completed")&&(l.status="ready",l.updatedAt=s);this.recalculateProgress(r,s)})}async steerGoal(e,o,i,t){return this.mutateGoal(e,o,i,(n,r,s)=>{let a=this.idFactory("steer");n.steering.push({id:a,instruction:p(t,"instruction"),createdAt:r}),this.appendEvent(s,"goal.steered",{goalId:o,data:{steeringId:a}})},!1)}async consumeGoalSteering(e,o,i){let t=[];return{goal:await this.mutateGoal(e,o,i,(r,s)=>{t=r.steering.filter(a=>!a.consumedAt).map(({id:a,instruction:c,createdAt:l})=>({id:a,instruction:c,createdAt:l}));for(let a of r.steering)a.consumedAt||(a.consumedAt=s)}),instructions:t}}async completeGoal(e,o,i,t){if(t.status!=="passed")throw new u("VERIFICATION_REQUIRED","Goal completion requires passed verification");return this.mutate(e,n=>{let r=this.requireGoal(n,o);this.assertVersion(r.id,r.version,i);let s=r.successCriteria.filter(l=>l.required),a=s.filter(l=>{let f=t.criteria.find(m=>m.criterionId===l.id);return!f?.satisfied||f.evidence.length===0});if(a.length>0)throw new u("VERIFICATION_REQUIRED","Required success criteria lack passing evidence",{unmetCriteria:a.map(l=>l.id)});if(s.length===0&&t.evidence.length===0)throw new u("VERIFICATION_REQUIRED","Goal completion requires at least one durable evidence reference");let c=this.now();return r.status="completed",r.verification=w(t),r.verification.verifiedAt??=c,r.completedAt=c,r.updatedAt=c,r.version+=1,this.appendEvent(n,"goal.completed",{goalId:o,data:{evidence:r.verification.evidence}}),r},!0)}async cancelGoal(e,o,i,t){return this.mutate(e,n=>{let r=this.requireGoal(n,o);if(this.assertVersion(r.id,r.version,i),["completed","cancelled","failed"].includes(r.status))return r;r.status="cancelled",r.updatedAt=this.now(),r.version+=1,this.appendEvent(n,"goal.cancelled",{goalId:o,data:{reason:p(t,"reason")}});for(let s of n.loops.filter(a=>a.goalId===o&&["running","paused","waiting"].includes(a.status)))s.status="stopped",s.resumeRequested!==void 0&&(s.resumeRequested=!1),s.stopReason=`Goal cancelled: ${t}`,s.stoppedAt=this.now(),s.updatedAt=s.stoppedAt,s.version+=1;return r},!0)}async startLoop(e){return this.mutate(e.sessionId,o=>this.createLoopRecord(o,e))}createLoopRecord(e,o){if(o.kind==="goal-continuation"&&!o.goalId)throw new u("INVALID","Goal-continuation loops require a goalId");if(o.goalId){let s=this.requireGoal(e,o.goalId);if(["completed","cancelled","failed"].includes(s.status))throw new u("CONFLICT",`Cannot start a loop for terminal goal ${s.id}`)}if(o.kind==="scheduled"&&!o.schedule)throw new u("INVALID","Scheduled loops require schedule metadata");if(o.kind!=="scheduled"&&o.schedule)throw new u("INVALID","Only scheduled loops may carry schedule metadata");let i=Ee(o.schedule),t=e.loops.find(s=>s.goalId===o.goalId&&s.kind===o.kind&&["running","paused","waiting"].includes(s.status));if(t)throw new u("CONFLICT",`Loop ${t.id} is already active`);let n=this.now(),r={schemaVersion:1,id:this.idFactory("loop"),version:1,sessionId:e.sessionId,...o.goalId?{goalId:o.goalId}:{},kind:o.kind,status:"running",...o.activity?{currentActivity:p(o.activity,"activity")}:{},iterations:[],...i?{schedule:i}:{},createdAt:n,updatedAt:n};return e.loops.push(r),this.appendEvent(e,"loop.started",{loopId:r.id,goalId:r.goalId,data:{kind:r.kind}}),r}async getLoop(e,o){let i=await this.getSessionState(e),t=o?i.loops.find(n=>n.id===o):[...i.loops].reverse().find(n=>["running","paused","waiting"].includes(n.status));return t?w(t):void 0}async beginLoopIteration(e,o,i,t,n){return this.mutateLoop(e,o,i,(r,s,a)=>{this.appendLoopIteration(a,r,s,t,n)},!1)}appendLoopIteration(e,o,i,t,n,r=!1){if(o.status!=="running")throw new u("CONFLICT",`Loop ${o.id} is ${o.status}`);if(o.goalId){let c=this.requireGoal(e,o.goalId);this.isCliGoal(c)&&this.initializeGoalTurnAccounting(e,c)}if(this.assertGoalIterationAdmission(e,o,i,r),o.iterations.some(c=>c.status==="running"))throw new u("CONFLICT",`Loop ${o.id} already has a running iteration`);let s=(o.iterations.at(-1)?.number??0)+1;o.currentActivity=p(t,"activity");let a={number:s,startedAt:i,status:"running",activity:o.currentActivity,...o.goalId&&e.goalTurnAccounting?.[o.goalId]?{goalAccountingVersion:1}:{},...n?{taskId:p(n,"taskId",512)}:{}};return o.iterations.push(a),o.resumeRequested!==void 0&&(o.resumeRequested=!1),this.appendEvent(e,"loop.iteration",{loopId:o.id,goalId:o.goalId,data:{number:s,phase:"started",activity:o.currentActivity}}),a}async admitGoalTurn(e){return this.admitGoalTurnWithOwner(e)}async admitQuotaGoalTurn(e,o,i,t){let n=V(i),r=await this.getGoal(e.sessionId,e.goalId);if(!r||r.sessionId!==e.sessionId||r.limits?.maxTokens===void 0)throw new u("BUDGET_UNAVAILABLE","The exact token-bounded goal is unavailable for quota admission");if(this.isCliGoal(r)&&r.metadata["cli.tokenQuotaVersion"]!==1)throw new u("BUDGET_UNAVAILABLE","Legacy CLI goal token spend is unknown; quota admission requires creation-time provenance");if(n.goal?.id!==r.id||n.goal.generation!==r.createdAt)throw new u("BUDGET_UNAVAILABLE","Quota scope does not identify this durable goal generation");let s=await o.policy(n);if(!s||M(s.scope)!==M(n)||s.limits.tokensLifetime===void 0||s.limits.tokensLifetime===null||s.limits.tokensLifetime>r.limits.maxTokens)throw new u("BUDGET_UNAVAILABLE","Goal quota policy is absent or wider than the goal's explicit token limit");let a=await o.remainingTokens(n);if(a===null)throw new u("BUDGET_UNAVAILABLE","Goal token accounting has no durable remaining allowance");if(a<1)throw new u("BUDGET_EXCEEDED","Goal token allowance is exhausted");return this.admitGoalTurnWithOwner(e,t,{goalId:r.id,createdAt:r.createdAt,maximum:r.limits.maxTokens})}async admitOwnedGoalTurn(e,o){if(!o||!Number.isSafeInteger(o.epoch)||o.epoch<1)throw new u("INVALID","An exact execution ownership epoch is required");return this.admitGoalTurnWithOwner(e,{...o})}async admitGoalTurnWithOwner(e,o,i){let t=p(e.requestId,"requestId",512),n=this.goalTurnHash(e.requestHash);return this.mutate(e.sessionId,r=>{if(o){let f=this.requireOwner(r,o.ownerId,o.leaseId);if(f.epoch!==o.epoch)throw new u("NOT_OWNER","Execution ownership epoch changed");if(this.ownerExpired(f,this.now()))throw new u("LEASE_EXPIRED","Execution ownership expired");if(r.handoffs.some(m=>["prepared","available"].includes(m.status)&&m.sourceLeaseEpoch===f.epoch)||r.handoffs.some(m=>m.status==="claimed"&&m.targetLeaseEpoch===f.epoch))throw new u("UNSAFE_HANDOFF","Execution handoff has not settled")}let s=this.requireGoal(r,e.goalId);if(i&&(s.id!==i.goalId||s.createdAt!==i.createdAt||s.limits?.maxTokens!==i.maximum))throw new u("BUDGET_UNAVAILABLE","Goal token limit changed after quota verification");for(let f of r.loops.filter(m=>m.goalId===s.id)){let m=f.iterations.find(E=>E.goalTurn?.requestId===t);if(m){if(m.goalTurn?.requestHash!==n)throw new u("CONFLICT","Goal turn identity was reused for different work");return{...this.goalTurnState(r,s,f,m),admitted:!1}}}if(this.assertVersion(s.id,s.version,e.expectedGoalVersion),s.status!=="active")throw new u("CONFLICT",`Goal ${s.id} is ${s.status}`);let a=[...r.loops].reverse().find(f=>f.goalId===s.id&&f.kind==="goal-continuation");if(e.expectedLoopId!==void 0){if(!a||a.id!==e.expectedLoopId)throw new u("CONFLICT","Goal continuation loop changed before admission");this.assertVersion(a.id,a.version,e.expectedLoopVersion??-1)}else if(e.expectedLoopVersion!==void 0)throw new u("INVALID","A goal turn loop version requires its exact loop ID");if(a&&a.status!=="running")throw new u("CONFLICT",`Goal loop ${a.id} is ${a.status}; resume or start it explicitly`);this.initializeGoalTurnAccounting(r,s),a??=this.createLoopRecord(r,{sessionId:r.sessionId,goalId:s.id,kind:"goal-continuation"});let c=this.now(),l=this.appendLoopIteration(r,a,c,"Interactive goal turn",void 0,i!==void 0);if(e.executionKind!==void 0&&e.executionKind!=="local-sdk"&&e.executionKind!=="external")throw new u("INVALID","Unknown goal execution lane");return l.goalTurn={requestId:t,requestHash:n,executor:e.executionKind==="local-sdk"?{kind:"local-sdk",processId:process.pid,host:b.hostname()}:{kind:"external"}},a.version+=1,a.updatedAt=c,{...this.goalTurnState(r,s,a,l),admitted:!0}},!1,r=>r.admitted)}async getGoalTurnState(e,o,i){let t=await this.getSessionState(e),n=o?t.goals.find(c=>c.id===o):[...t.goals].reverse().find(c=>["active","paused","waiting","blocked"].includes(c.status));if(!n)return;let r=t.loops.filter(c=>c.goalId===n.id),s=i?r.find(c=>c.iterations.some(l=>l.goalTurn?.requestId===i)):[...r].reverse().find(c=>c.kind==="goal-continuation"),a=i?s?.iterations.find(c=>c.goalTurn?.requestId===i):s?.iterations.at(-1);if(i&&!a)throw new u("NOT_FOUND","Goal turn was not found");return this.goalTurnState(t,n,s,a)}async finishGoalTurn(e){if(!["completed","failed","interrupted"].includes(e.status))throw new u("INVALID","Invalid goal turn outcome");let o=this.goalTurnHash(e.requestHash);return this.mutate(e.sessionId,i=>{let t=this.requireGoal(i,e.goalId),n=i.loops.find(s=>s.goalId===t.id&&s.iterations.some(a=>a.goalTurn?.requestId===e.requestId)),r=n?.iterations.find(s=>s.goalTurn?.requestId===e.requestId);if(!n||!r)throw new u("NOT_FOUND","Goal turn was not found");if(r.goalTurn?.requestHash!==o)throw new u("CONFLICT","Goal turn settlement identity does not match");return r.status==="running"&&(this.settleLoopIteration(i,n,r,this.now(),{status:t.status==="cancelled"||["stopped","failed"].includes(n.status)?"interrupted":e.status}),n.version+=1,n.updatedAt=this.now()),this.goalTurnState(i,t,n,r)},!0)}async recoverGoalTurn(e,o,i){return this.mutate(e,t=>{let n=this.requireGoal(t,o),r=t.loops.find(a=>a.goalId===o&&a.iterations.some(c=>c.goalTurn?.requestId===i)),s=r?.iterations.find(a=>a.goalTurn?.requestId===i);if(!r||!s)throw new u("NOT_FOUND","Goal turn was not found");if(s.status==="running"){if(!this.goalTurnOwnerExited(s))throw new u("NOT_OWNER","The original local goal executor has not been proved exited; external execution requires reconciliation");this.settleLoopIteration(t,r,s,this.now(),{status:"interrupted",error:"Original local SDK executor exited; inspect persisted results before retrying work"}),r.resumeRequested=n.status==="active"&&r.status==="running",r.version+=1,r.updatedAt=this.now()}return this.goalTurnState(t,n,r,s)},!0)}async finishLoopIteration(e,o,i,t){return this.mutateLoop(e,o,i,(n,r,s)=>{let a=[...n.iterations].reverse().find(c=>c.status==="running");if(!a)throw new u("CONFLICT",`Loop ${n.id} has no running iteration`);this.settleLoopIteration(s,n,a,r,t)},!1,!0)}settleLoopIteration(e,o,i,t,n){i.status=n.status,i.completedAt=t,n.verificationEventId&&(i.verificationEventId=p(n.verificationEventId,"verificationEventId",512)),n.error&&(i.error=p(n.error,"error")),o.status=["stopped","completed","failed"].includes(o.status)?o.status:e.admissionFence?"paused":n.nextStatus??(o.status==="paused"||o.status==="waiting"?o.status:"running"),this.appendEvent(e,"loop.iteration",{loopId:o.id,goalId:o.goalId,data:{number:i.number,phase:"finished",status:n.status}})}async setLoopStatus(e,o,i,t,n){return this.mutateLoop(e,o,i,(r,s,a)=>{let c=r.status;if(["stopped","completed","failed"].includes(c))throw new u("CONFLICT",`Loop ${r.id} is terminal (${c})`);let l=[...r.iterations].reverse().find(m=>m.status==="running");if(l&&t==="completed")throw new u("CONFLICT",`Loop ${r.id} cannot complete while iteration ${l.number} is running`);l&&(t==="stopped"||t==="failed")&&(l.status=t==="failed"?"failed":"interrupted",l.completedAt=s,l.error=p(n??t,"reason")),r.status=t,r.kind==="goal-continuation"&&(r.resumeRequested=t==="running"),["stopped","completed","failed"].includes(t)&&(r.stoppedAt=s,r.stopReason=p(n??t,"reason"));let f=t==="paused"?"loop.paused":t==="waiting"?"loop.waiting":t==="running"&&(c==="paused"||c==="waiting")?"loop.resumed":t==="completed"?"loop.completed":t==="failed"?"loop.failed":"loop.stopped";this.appendEvent(a,f,{loopId:o,goalId:r.goalId,data:{previous:c,status:t,...n?{reason:n}:{}}})},!1,t!=="running"&&t!=="waiting")}async acquireOwnership(e,o,i={}){return this.mutate(e,t=>{let n=this.now();if(t.owner&&!this.ownerExpired(t.owner,n)){if(t.owner.ownerId===o&&i.processId!==void 0&&t.owner.processId===i.processId&&(i.host===void 0||t.owner.host===i.host))return t.owner;throw new u("CONFLICT",`Session ${e} is owned by ${t.owner.ownerId}`,{owner:t.owner})}let r=t.owner&&this.ownerExpired(t.owner,n)?t.owner:void 0;if(r)for(let c of t.handoffs.filter(l=>l.status==="claimed"&&l.claimedBy===r.ownerId&&l.targetLeaseEpoch===r.epoch))c.status="failed",c.failureReason=`Claimed owner ${r.ownerId} lost its execution lease before completing the handoff.`,c.failedAt=n,c.updatedAt=n,c.version+=1,this.appendEvent(t,"handoff.failed",{handoffId:c.id,goalId:c.goalId,loopId:c.loopId,data:{reason:c.failureReason,expiredLeaseId:r.leaseId}});let s=t.ownershipEpoch+1;for(let c of t.handoffs.filter(l=>["prepared","available"].includes(l.status)&&l.sourceLeaseEpoch<s))c.status="failed",c.failureReason="Source ownership epoch was superseded before the handoff was claimed.",c.failedAt=n,c.updatedAt=n,c.version+=1,this.appendEvent(t,"handoff.failed",{handoffId:c.id,data:{epoch:s,reason:c.failureReason}});let a=this.newOwner(o,s,i,n);return t.owner=a,t.ownershipEpoch=s,this.appendEvent(t,"ownership.acquired",{ownerId:o,data:{epoch:s,leaseId:a.leaseId}}),a})}async renewOwnership(e,o,i,t=this.ownerLeaseMs){return this.mutate(e,n=>{let r=this.requireOwner(n,o,i);if(this.ownerExpired(r,this.now()))throw new u("LEASE_EXPIRED",`Ownership lease ${i} expired`);return r.heartbeatAt=this.now(),r.expiresAt=new Date(y(r.heartbeatAt)+t).toISOString(),this.appendEvent(n,"ownership.renewed",{ownerId:o,data:{epoch:r.epoch,leaseId:i}}),r})}async recoverExpiredOwnership(e,o,i,t,n=this.ownerLeaseMs){return this.mutate(e,r=>{let s=this.requireOwner(r,o,i);if(s.processId!==t||s.host!==b.hostname()||!k(t))throw new u("LEASE_EXPIRED",`Ownership lease ${i} expired and cannot be recovered by process ${t}`);let a=this.now(),c=Math.max(0,y(a)-y(s.expiresAt));return s.heartbeatAt=a,s.expiresAt=new Date(y(a)+n).toISOString(),this.appendEvent(r,c>0?"ownership.recovered":"ownership.renewed",{ownerId:o,data:{epoch:s.epoch,leaseId:i,...c>0?{expiredForMs:c}:{}}}),s})}async releaseOwnership(e,o,i){return this.mutate(e,t=>{let n=this.requireOwner(t,o,i);for(let r of t.handoffs.filter(s=>s.status==="claimed"&&s.claimedBy===o&&s.targetLeaseEpoch===n.epoch))r.status="failed",r.failureReason="Target released execution ownership before completing the handoff.",r.failedAt=this.now(),r.updatedAt=r.failedAt,r.version+=1,this.appendEvent(t,"handoff.failed",{handoffId:r.id,ownerId:o,data:{epoch:n.epoch,reason:r.failureReason}});return t.owner=void 0,this.appendEvent(t,"ownership.released",{ownerId:o,data:{epoch:n.epoch}}),n},!0)}async createHandoff(e){let o=!1,i=e.prepareRequestId===void 0?void 0:p(e.prepareRequestId,"prepareRequestId",512);return this.mutate(e.sessionId,t=>{let n=this.requireOwner(t,e.sourceOwnerId,e.sourceLeaseId);if(this.ownerExpired(n,this.now()))throw new u("LEASE_EXPIRED",`Ownership lease ${n.leaseId} expired`);if(i){let l=t.handoffs.find(f=>f.prepareRequestId===i);if(l){if(l.sourceOwnerId!==n.ownerId||l.sourceLeaseEpoch!==n.epoch||l.status!=="available"||l.targetOwnerId!==e.targetOwnerId||l.workspace!==e.workspace||l.goalId!==e.goalId||l.loopId!==e.loopId||l.contextDigest!==e.contextDigest||l.branch!==e.branch||l.currentMilestoneId!==e.currentMilestoneId||l.currentTaskId!==e.currentTaskId||JSON.stringify(l.agentIds)!==JSON.stringify([...new Set(e.agentIds??[])])||JSON.stringify(l.operations)!==JSON.stringify(e.operations??[]))throw new u("CONFLICT","Prepare identity was reused for different work or ownership");return o=!0,l}}let r=(e.operations??[]).filter(l=>l.status==="running"&&l.sideEffecting);if(r.length>0)throw new u("UNSAFE_HANDOFF","Running side-effecting operations must settle before execution handoff",{operationIds:r.map(l=>l.operationId)});if(e.goalId&&this.requireGoal(t,e.goalId),e.loopId&&!t.loops.some(l=>l.id===e.loopId))throw new u("NOT_FOUND",`Loop ${e.loopId} was not found`);let s=t.handoffs.find(l=>["prepared","available","claimed"].includes(l.status));if(s)throw new u("CONFLICT",`Handoff ${s.id} is already active`);let a=this.now(),c={schemaVersion:1,id:this.idFactory("handoff"),version:1,sessionId:t.sessionId,...e.goalId?{goalId:e.goalId}:{},...e.loopId?{loopId:e.loopId}:{},status:"available",sourceOwnerId:n.ownerId,...i?{prepareRequestId:i}:{},...e.targetOwnerId?{targetOwnerId:p(e.targetOwnerId,"targetOwnerId",512)}:{},sourceLeaseEpoch:n.epoch,...e.workspace?{workspace:p(e.workspace,"workspace",32768)}:{},...e.branch?{branch:p(e.branch,"branch",1024)}:{},...e.currentMilestoneId?{currentMilestoneId:e.currentMilestoneId}:{},...e.currentTaskId?{currentTaskId:e.currentTaskId}:{},agentIds:[...new Set(e.agentIds??[])],operations:w(e.operations??[]),...e.contextDigest?{contextDigest:p(e.contextDigest,"contextDigest",512)}:{},createdAt:a,updatedAt:a};return t.handoffs.push(c),this.appendEvent(t,"handoff.created",{handoffId:c.id,goalId:c.goalId,loopId:c.loopId,ownerId:n.ownerId,data:{targetOwnerId:c.targetOwnerId}}),c},!1,()=>!o)}async claimHandoff(e){let o,i=!1,t=e.claimRequestId===void 0?void 0:p(e.claimRequestId,"claimRequestId",512);return{handoff:await this.mutate(e.sessionId,r=>{let s=r.handoffs.find(l=>l.id===e.handoffId);if(!s)throw new u("NOT_FOUND",`Handoff ${e.handoffId} was not found`);if(s.status!=="available"){let l=r.owner;if(t&&s.claimRequestId===t&&["claimed","completed"].includes(s.status)&&s.claimedBy===e.targetOwnerId&&l?.ownerId===e.targetOwnerId&&l.epoch===s.targetLeaseEpoch&&l.host===e.host&&l.processId===e.processId&&!this.ownerExpired(l,this.now()))return o=l,i=!0,s;throw new u("CONFLICT",`Handoff ${s.id} is ${s.status}`,{claimedBy:s.claimedBy})}if(s.targetOwnerId&&s.targetOwnerId!==e.targetOwnerId)throw new u("CONFLICT",`Handoff ${s.id} is reserved for ${s.targetOwnerId}`);let a=r.owner;if(!a||a.ownerId!==s.sourceOwnerId||a.epoch!==s.sourceLeaseEpoch)throw new u("CONFLICT",`Handoff ${s.id} no longer matches the source ownership epoch`);let c=this.now();return o=this.newOwner(e.targetOwnerId,a.epoch+1,{processId:e.processId,host:e.host,leaseMs:e.leaseMs},c),r.owner=o,r.ownershipEpoch=o.epoch,s.status="claimed",s.claimedBy=e.targetOwnerId,t&&(s.claimRequestId=t),s.targetOwnerId=e.targetOwnerId,s.targetLeaseEpoch=o.epoch,s.claimedAt=c,s.updatedAt=c,s.version+=1,this.appendEvent(r,"handoff.claimed",{handoffId:s.id,goalId:s.goalId,loopId:s.loopId,ownerId:e.targetOwnerId,data:{sourceOwnerId:s.sourceOwnerId,epoch:o.epoch}}),s},!1,()=>!i),owner:w(o)}}async completeHandoff(e,o,i,t){let n=!1;return this.mutate(e,r=>{let s=this.requireOwner(r,i,t);if(this.ownerExpired(s,this.now()))throw new u("LEASE_EXPIRED",`Ownership lease ${t} expired`);let a=r.handoffs.find(c=>c.id===o);if(!a)throw new u("NOT_FOUND",`Handoff ${o} was not found`);if(a.claimedBy!==i||a.targetLeaseEpoch!==s.epoch||!["claimed","completed"].includes(a.status))throw new u("CONFLICT",`Handoff ${a.id} cannot be completed by ${i}`);return a.status==="completed"?(n=!0,a):(a.status="completed",a.completedAt=this.now(),a.updatedAt=a.completedAt,a.version+=1,this.appendEvent(r,"handoff.completed",{handoffId:o,goalId:a.goalId,loopId:a.loopId,ownerId:i,data:{epoch:r.owner?.epoch}}),a)},!1,()=>!n)}async failHandoff(e,o,i){return this.mutate(e,t=>{let n=t.handoffs.find(r=>r.id===o);if(!n)throw new u("NOT_FOUND",`Handoff ${o} was not found`);return["completed","cancelled","failed"].includes(n.status)||(n.status="failed",n.failureReason=p(i,"reason"),n.failedAt=this.now(),n.updatedAt=n.failedAt,n.version+=1,this.appendEvent(t,"handoff.failed",{handoffId:o,goalId:n.goalId,loopId:n.loopId,data:{reason:n.failureReason}})),n},!0)}async mutateGoal(e,o,i,t,n=!0){return this.mutate(e,r=>{let s=this.requireGoal(r,o);this.assertVersion(s.id,s.version,i);let a=this.now();return t(s,a,r),s.version+=1,s.updatedAt=a,n&&this.appendEvent(r,"goal.updated",{goalId:o,data:{status:s.status,version:s.version}}),s})}async mutateLoop(e,o,i,t,n=!0,r=!1){return this.mutate(e,s=>{let a=s.loops.find(l=>l.id===o);if(!a)throw new u("NOT_FOUND",`Loop ${o} was not found`);this.assertVersion(a.id,a.version,i);let c=this.now();return t(a,c,s),a.version+=1,a.updatedAt=c,n&&this.appendEvent(s,"loop.iteration",{loopId:o,goalId:a.goalId,data:{status:a.status,version:a.version}}),a},r)}assertGoalIterationAdmission(e,o,i,t=!1){if(!o.goalId)return;let n=this.requireGoal(e,o.goalId);if(n.status!=="active")throw new u("CONFLICT",`Goal ${n.id} is ${n.status}; no iteration was admitted`);let r=Z(n.limits);if(r?.maxTokens!==void 0&&!t)throw new u("BUDGET_UNAVAILABLE","Goal token allowance is not bound to request-level admission; no iteration was admitted",{goalId:n.id,limit:"maxTokens"});if(r?.maxWallClockMs!==void 0){let s=Date.parse(n.createdAt),a=Date.parse(i);if(!Number.isFinite(s)||!Number.isFinite(a)||a<s)throw new u("BUDGET_UNAVAILABLE","Goal wall-clock allowance cannot be verified",{goalId:n.id,limit:"maxWallClockMs"});if(a-s>=r.maxWallClockMs)throw new u("BUDGET_EXCEEDED","Goal wall-clock limit reached; no iteration was admitted",{goalId:n.id,limit:"maxWallClockMs",maximum:r.maxWallClockMs})}if(r?.maxIterations!==void 0){let s=e.goalTurnAccounting!==void 0||e.schemaVersion===4?this.resolveGoalTurnAccounting(e,n):void 0;if(s?.coverage==="partial")throw new u("BUDGET_UNAVAILABLE","Legacy goal turn accounting is incomplete");let a=this.goalIterationCount(e,n)+(s?.baseIterations??0);if(!Number.isSafeInteger(a)||a<0)throw new u("BUDGET_UNAVAILABLE","Invalid goal iteration accounting");if(a>=r.maxIterations)throw new u("BUDGET_EXCEEDED","Goal iteration limit reached; no iteration was admitted",{goalId:n.id,limit:"maxIterations",admitted:a,maximum:r.maxIterations})}}isCliGoal(e){return"cli.accountedTurns"in e.metadata||"cli.createdByCliVersion"in e.metadata}goalIterationCount(e,o){let i=0;for(let t of e.loops.filter(n=>n.goalId===o.id)){if(!Array.isArray(t.iterations))throw new u("BUDGET_UNAVAILABLE","Goal iteration history is unavailable");let n=0;for(let r of t.iterations){if(!r||!Number.isSafeInteger(r.number)||r.number<=n)throw new u("BUDGET_UNAVAILABLE","Goal iteration history is invalid");n=r.number}if(i+=n,!Number.isSafeInteger(i))throw new u("BUDGET_UNAVAILABLE","Goal iteration count exceeds its supported range")}return i}resolveGoalTurnAccounting(e,o){let i=e.goalTurnAccounting;if(i!==void 0&&(!i||typeof i!="object"||Array.isArray(i)))throw new u("BUDGET_UNAVAILABLE","Persisted goal turn accounting is invalid");if(i&&Object.hasOwn(i,o.id)){let a=i[o.id];if(!a||a.schemaVersion!==1||!Number.isSafeInteger(a.baseIterations)||a.baseIterations<0||!["complete","partial"].includes(a.coverage))throw new u("BUDGET_UNAVAILABLE","Persisted goal turn accounting is invalid");return a}if(e.loops.some(a=>a.goalId===o.id&&a.iterations.some(c=>c.goalTurn||c.goalAccountingVersion)))throw new u("BUDGET_UNAVAILABLE","Recorded goal turns are missing their protected accounting");let t=this.goalIterationCount(e,o),n=o.metadata["cli.accountedTurns"],r=typeof n=="number"&&Number.isSafeInteger(n)&&n>=0,s=this.isCliGoal(o)&&(!r||n>0&&t>0);return{schemaVersion:1,baseIterations:r&&t===0?n:0,coverage:s?"partial":"complete"}}initializeGoalTurnAccounting(e,o){let i=this.resolveGoalTurnAccounting(e,o);if(i.coverage==="partial"&&o.limits?.maxIterations!==void 0)throw new u("BUDGET_UNAVAILABLE","Legacy goal turn accounting needs reconciliation before bounded execution");e.goalTurnAccounting??={},Object.defineProperty(e.goalTurnAccounting,o.id,{value:i,writable:!0,enumerable:!0,configurable:!0})}goalTurnHash(e){let o=p(e,"requestHash",64).toLowerCase();if(!/^[0-9a-f]{64}$/.test(o))throw new u("INVALID","Goal turn requestHash must be a SHA-256 digest");return o}goalTurnState(e,o,i,t){let n=this.resolveGoalTurnAccounting(e,o),r=this.goalIterationCount(e,o)+n.baseIterations;if(!Number.isSafeInteger(r))throw new u("BUDGET_UNAVAILABLE","Goal turn count exceeds its supported range");return w({goal:o,admittedTurns:r,accountingCoverage:n.coverage,...i?{loopId:i.id,loopVersion:i.version,loopStatus:i.status,resumeRequested:i.resumeRequested===!0}:{},...t?{iterationNumber:t.number,iterationStatus:t.status,...t.goalTurn?{requestId:t.goalTurn.requestId,requestHash:t.goalTurn.requestHash}:{},canRecover:t.status==="running"&&this.goalTurnOwnerExited(t)}:{}})}goalTurnOwnerExited(e){let o=e.goalTurn?.executor;if(o?.kind!=="local-sdk"||o.host!==b.hostname()||!Number.isSafeInteger(o.processId)||o.processId<=0)return!1;try{return process.kill(o.processId,0),!1}catch(i){return i.code==="ESRCH"}}recalculateProgress(e,o){let i=e.tasks.filter(t=>t.status==="completed").length;e.progress.completedTaskCount=i,e.progress.totalTaskCount=e.tasks.length,e.progress.percent=e.tasks.length?Math.round(i/e.tasks.length*100):void 0,e.progress.outstanding=e.tasks.filter(t=>!["completed","cancelled"].includes(t.status)).map(t=>t.title),e.progress.updatedAt=o}requireGoal(e,o){let i=e.goals.find(t=>t.id===o);if(!i)throw new u("NOT_FOUND",`Goal ${o} was not found`);return i}requireOwner(e,o,i){let t=e.owner;if(!t||t.ownerId!==o||t.leaseId!==i)throw new u("NOT_OWNER",`${o} does not own session ${e.sessionId}`,{owner:t});return t}assertVersion(e,o,i){if(!Number.isInteger(i)||i<1||o!==i)throw new u("CONFLICT",`Expected ${e} version ${i}, found ${o}`,{expected:i,actual:o})}newOwner(e,o,i,t){let n=i.leaseMs??this.ownerLeaseMs;if(!Number.isSafeInteger(n)||n<1)throw new u("INVALID","leaseMs must be a positive safe integer");return{ownerId:p(e,"ownerId",512),leaseId:this.idFactory("owner"),epoch:o,acquiredAt:t,heartbeatAt:t,expiresAt:new Date(y(t)+n).toISOString(),...i.processId!==void 0?{processId:i.processId}:{},...i.host?{host:p(i.host,"host",512)}:{}}}ownerExpired(e,o){return y(e.expiresAt)<=y(o)?!0:e.processId!==void 0&&e.host===b.hostname()&&!k(e.processId)}appendEvent(e,o,i){let t={schemaVersion:1,id:this.idFactory("event"),sequence:(e.events.at(-1)?.sequence??0)+1,type:o,sessionId:e.sessionId,...i.goalId?{goalId:i.goalId}:{},...i.loopId?{loopId:i.loopId}:{},...i.handoffId?{handoffId:i.handoffId}:{},...i.ownerId?{ownerId:i.ownerId}:{},timestamp:this.now(),data:w(i.data)};e.events.push(t),e.events.length>this.maximumEventsPerSession&&e.events.splice(0,e.events.length-this.maximumEventsPerSession)}async mutate(e,o,i=!1,t=()=>!0){let n=p(e,"sessionId",1024);return this.withSessionLock(n,async()=>{let r=await this.readState(n);if(r.admissionFence&&!i)throw new u("CONFLICT","Session execution is blocked by a persisted lifecycle fence");let s=r.schemaVersion;this.promoteGoalBudgetEnvelope(r),r.schemaVersion!==s&&await this.writeState(r);let a=o(r);return t(a)&&(r.version+=1,r.updatedAt=this.now(),await this.writeState(r)),w(a)})}statePath(e){return I.join(this.rootDirectory,"sessions",`${ee(e)}.json`)}lockPath(e){return`${this.statePath(e)}.lock`}async readState(e){let o=this.statePath(e);try{let i=await h.readFile(o,"utf8"),t=JSON.parse(i);if(!Y.includes(t.schemaVersion)||t.sessionId!==e)throw new u("INVALID",`Coordination state at ${o} does not match session ${e}`);if(t.admissionFence!==void 0){let n=t.admissionFence;if(!n||n.schemaVersion!==1||typeof n.authorityId!="string"||!n.authorityId.trim()||typeof n.operationId!="string"||!n.operationId.trim()||!["archive","delete"].includes(n.action)||!Number.isFinite(Date.parse(n.createdAt)))throw new u("INVALID","Persisted lifecycle fence is corrupt; execution remains unavailable")}return(!Number.isSafeInteger(t.ownershipEpoch)||t.ownershipEpoch<0)&&(t.ownershipEpoch=Math.max(t.owner?.epoch??0,...t.handoffs.map(n=>n.targetLeaseEpoch??n.sourceLeaseEpoch??0))),t}catch(i){if(i.code!=="ENOENT")throw i;let t=this.now();return{schemaVersion:1,sessionId:e,version:0,ownershipEpoch:0,goals:[],loops:[],handoffs:[],events:[],createdAt:t,updatedAt:t}}}promoteGoalBudgetEnvelope(e){(e.goalTurnAccounting!==void 0||e.loops.some(o=>o.resumeRequested!==void 0||o.iterations.some(i=>i.goalTurn!==void 0)))&&(e.schemaVersion=4),e.schemaVersion<3&&e.goals.some(o=>o.limits!==void 0&&(!o.limits||typeof o.limits!="object"||Array.isArray(o.limits)||Object.keys(o.limits).length>0))&&(e.schemaVersion=3)}async writeState(e){this.promoteGoalBudgetEnvelope(e);let o=this.statePath(e.sessionId),i=I.dirname(o);await h.mkdir(i,{recursive:!0});let t=`${o}.${process.pid}.${L()}.tmp`,n=await h.open(t,"wx");try{await n.writeFile(`${JSON.stringify(e,null,2)}
|
|
2
|
-
`,"utf8"),await n.sync()}finally{await n.close()}try{await this.renameReplacing(t,o);try{let r=await h.open(i,"r");try{await r.sync()}finally{await r.close()}}catch{}}finally{await h.unlink(t).catch(()=>{})}}async renameReplacing(e,o){for(let i=0;;i+=1)try{await h.rename(e,o);return}catch(t){let n=t.code,r=K[i];if(process.platform!=="win32"||!n||!N.has(n)||r===void 0)throw t;await new Promise(s=>setTimeout(s,r))}}async withSessionLock(e,o){let i=this.lockPath(e),t=I.join(i,"owner.json"),n=L(),r=`${i}.candidate.${n}`,s=Date.now();await h.mkdir(I.dirname(i),{recursive:!0});let a={schemaVersion:1,token:n,pid:process.pid,host:b.hostname(),acquiredAt:this.now()};await h.mkdir(r),await h.writeFile(I.join(r,"owner.json"),JSON.stringify(a),{encoding:"utf8",flag:"wx"});for(let c=0;;c+=1)try{await h.rename(r,i);break}catch(l){let f=l.code;if(!(!!f&&new Set(["EEXIST","ENOTEMPTY","ENOTDIR","EBUSY"]).has(f)||process.platform==="win32"&&!!f&&N.has(f)))throw await h.rm(r,{recursive:!0,force:!0}).catch(()=>{}),l;let O=await this.staleLockOwner(i,t);if(O){await this.quarantineLock(i,O.token,"stale");continue}if(Date.now()-s>=this.lockTimeoutMs)throw await h.rm(r,{recursive:!0,force:!0}).catch(()=>{}),new u("CONFLICT",`Timed out waiting for coordination lock for session ${e}`);await new Promise(T=>setTimeout(T,Math.min(100,5+c*5)+Math.floor(Math.random()*10)))}try{return await o()}finally{await this.quarantineLock(i,n,"released"),await h.rm(r,{recursive:!0,force:!0}).catch(()=>{})}}async staleLockOwner(e,o){try{let[i,t]=await Promise.all([h.readFile(o,"utf8").catch(()=>""),h.stat(e)]),n=i?JSON.parse(i):void 0;return!n||n.host!==b.hostname()||k(n.pid)?void 0:Date.now()-t.mtimeMs>this.lockStaleMs?n:void 0}catch{return}}async quarantineLock(e,o,i){let t=I.join(e,"owner.json"),n=i==="stale"?`${e}.stale.${ee(o)}`:`${e}.${i}.${o}.${L()}`;for(let r=0;;r+=1){let s;try{s=JSON.parse(await h.readFile(t,"utf8"))}catch(a){if(a.code==="ENOENT")return;throw a}if(s.token!==o)return;try{await h.rename(e,n);break}catch(a){let c=a.code;if(i==="stale")try{if(JSON.parse(await h.readFile(I.join(n,"owner.json"),"utf8")).token===o)return}catch{}if(c==="ENOENT"||c==="EEXIST")return;let l=K[r];if(process.platform!=="win32"||!c||!N.has(c)||l===void 0)throw a;await new Promise(f=>setTimeout(f,l))}}if(i!=="stale")for(let r=0;;r+=1)try{await h.rm(n,{recursive:!0});return}catch(s){let a=s.code;if(a==="ENOENT")return;let c=Ie[r];if(process.platform!=="win32"||!a||!N.has(a)||c===void 0)throw s;await new Promise(l=>setTimeout(l,c))}}};function S(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 A(d,e){if(typeof d!="number"||!Number.isInteger(d))throw new Error(`${e} must be an integer`);return d}async function rt(d,e){let{action:o,sessionId:i}=e,t=e.payload??{};if(t.sessionId!==void 0&&t.sessionId!==i)throw new u("INVALID","Payload sessionId must match the routed sessionId");let n;switch(o){case"state.get":n=await d.getSessionState(i);break;case"goal.create":n=await d.createGoal({...t,sessionId:i});break;case"goal.update":n=await d.updateGoal(i,g(t.goalId,"goalId"),A(t.expectedVersion,"expectedVersion"),S(t.update,"update"));break;case"goal.complete":n=await d.completeGoal(i,g(t.goalId,"goalId"),A(t.expectedVersion,"expectedVersion"),S(t.verification,"verification"));break;case"goal.cancel":n=await d.cancelGoal(i,g(t.goalId,"goalId"),A(t.expectedVersion,"expectedVersion"),g(t.reason,"reason"));break;case"goal.steer":n=await d.steerGoal(i,g(t.goalId,"goalId"),A(t.expectedVersion,"expectedVersion"),g(t.instruction,"instruction"));break;case"loop.start":n=await d.startLoop({sessionId:i,kind:g(t.kind,"kind"),...typeof t.goalId=="string"?{goalId:t.goalId}:{},...typeof t.activity=="string"?{activity:t.activity}:{},...t.schedule?{schedule:S(t.schedule,"schedule")}:{}});break;case"loop.get":n=await d.getLoop(i,typeof t.loopId=="string"?t.loopId:void 0);break;case"loop.begin":n=await d.beginLoopIteration(i,g(t.loopId,"loopId"),A(t.expectedVersion,"expectedVersion"),g(t.activity,"activity"),typeof t.taskId=="string"?t.taskId:void 0);break;case"loop.finish":n=await d.finishLoopIteration(i,g(t.loopId,"loopId"),A(t.expectedVersion,"expectedVersion"),S(t.result,"result"));break;case"loop.set_status":n=await d.setLoopStatus(i,g(t.loopId,"loopId"),A(t.expectedVersion,"expectedVersion"),g(t.status,"status"),typeof t.reason=="string"?t.reason:void 0);break;case"ownership.acquire":n=await d.acquireOwnership(i,g(t.ownerId,"ownerId"),S(t.options??{},"options"));break;case"ownership.renew":n=await d.renewOwnership(i,g(t.ownerId,"ownerId"),g(t.leaseId,"leaseId"),typeof t.leaseMs=="number"?t.leaseMs:void 0);break;case"ownership.release":n=await d.releaseOwnership(i,g(t.ownerId,"ownerId"),g(t.leaseId,"leaseId"));break;case"handoff.create":n=await d.createHandoff({...t,sessionId:i});break;case"handoff.claim":n=await d.claimHandoff({sessionId:i,handoffId:g(t.handoffId,"handoffId"),targetOwnerId:g(t.targetOwnerId,"targetOwnerId"),...typeof t.processId=="number"?{processId:t.processId}:{},...typeof t.host=="string"?{host:t.host}:{}});break;case"handoff.complete":n=await d.completeHandoff(i,g(t.handoffId,"handoffId"),g(t.ownerId,"ownerId"),g(t.leaseId,"leaseId"));break;case"handoff.fail":n=await d.failHandoff(i,g(t.handoffId,"handoffId"),g(t.reason,"reason"));break;default:throw new u("INVALID","Unsupported coordination action")}let r=await d.getSessionState(i),s=o==="state.get"||o==="loop.get"?void 0:r.events.at(-1);return{action:o,sessionId:i,result:n,state:r,...s?{event:s}:{}}}import{randomUUID as be}from"node:crypto";import{hostname as Ae}from"node:os";var te=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 _,this.sessionId=e.sessionId,this.processId=e.processId??process.pid,this.host=e.host??Ae(),this.ownerId=e.ownerId??`runtime:${this.host}:${this.processId}:${be().slice(0,8)}`,this.leaseMs=e.leaseMs??3e4,this.heartbeatMs=e.heartbeatMs??Math.max(250,Math.floor(this.leaseMs/3)),this.heartbeatMs>=this.leaseMs)throw new Error("heartbeatMs must be shorter than leaseMs");if(this.claimHandoffId=e.claimHandoffId,this.claimRequestId=e.claimRequestId,this.onOwnershipLost=e.onOwnershipLost,this.prepareDestination=e.prepareDestination,this.destinationTimeoutMs=e.destinationTimeoutMs??Math.min(1e4,Math.floor(this.leaseMs/2)),!Number.isSafeInteger(this.destinationTimeoutMs)||this.destinationTimeoutMs<1||this.destinationTimeoutMs>=this.leaseMs)throw new Error("destinationTimeoutMs must be a positive integer shorter than leaseMs")}get currentOwner(){return this.active&&this.owner?structuredClone(this.owner):void 0}get active(){return this.ready&&!!this.owner&&!this.stopped&&this.lostError===void 0&&!this.preparingHandoff&&!this.preparedHandoffId}async start(){if(this.stopped)throw new Error("Execution lease session has already stopped");if(this.lostError!==void 0)throw this.lostError;return this.ready&&this.owner?(this.assertExecutionAllowed(),structuredClone(this.owner)):(this.starting??=this.initialize(),structuredClone(await this.starting))}async initialize(){try{if(this.claimHandoffId){let e=await this.store.claimHandoff({sessionId:this.sessionId,handoffId:this.claimHandoffId,targetOwnerId:this.ownerId,processId:this.processId,host:this.host,leaseMs:this.leaseMs,...this.claimRequestId?{claimRequestId:this.claimRequestId}:{}});if(this.owner=e.owner,this.stopped)throw new Error("Execution lease session has already stopped");if(this.prepareDestination&&await this.prepareClaimedDestination(e.handoff),this.stopped)throw new Error("Execution lease session has already stopped");await this.store.completeHandoff(this.sessionId,this.claimHandoffId,this.ownerId,this.owner.leaseId)}else this.owner=await this.store.acquireOwnership(this.sessionId,this.ownerId,{processId:this.processId,host:this.host,leaseMs:this.leaseMs});if(this.stopped)throw new Error("Execution lease session has already stopped");if(this.owner=await this.store.renewOwnership(this.sessionId,this.ownerId,this.owner.leaseId,this.leaseMs),this.stopped)throw new Error("Execution lease session has already stopped");return this.ready=!0,this.timer=setInterval(()=>{this.heartbeat()},this.heartbeatMs),this.timer.unref?.(),structuredClone(this.owner)}catch(e){throw this.ready=!1,this.markLost(e instanceof Error?e:new Error("Execution lease initialization failed",{cause:e})),this.lostError}}async prepareClaimedDestination(e){let o=this.initializationAbort.signal,i,t;try{let n=new Promise((r,s)=>{t=()=>s(o.reason??new Error("Destination preparation cancelled")),o.addEventListener("abort",t,{once:!0}),i=setTimeout(()=>this.initializationAbort.abort(new Error("Destination preparation timed out")),this.destinationTimeoutMs),o.aborted&&t()});await Promise.race([n,Promise.resolve().then(()=>(o.throwIfAborted(),this.prepareDestination({handoff:structuredClone(e),signal:o})))]),o.throwIfAborted()}finally{i&&clearTimeout(i),t&&o.removeEventListener("abort",t)}}async assertOwned(){this.assertExecutionAllowed();let e=await this.renewHeldLease();return this.assertExecutionAllowed(),e}assertExecutionAllowed(){if(this.stopped)throw new Error("Execution surface is detached");if(this.lostError)throw this.lostError;if(this.preparingHandoff)throw new Error("Execution surface is preparing a handoff and is detached from mutation");if(this.preparedHandoffId)throw new Error(`Execution surface prepared handoff ${this.preparedHandoffId} and is detached from mutation`);if(!this.ready||!this.owner)throw new Error("Execution ownership was not started")}async renewHeldLease(){if(!this.owner)throw new Error("Execution ownership was not started");try{let e=await this.renewOrRecover(this.owner.leaseId);if(this.stopped)throw new Error("Execution surface is detached");return this.owner=e,structuredClone(this.owner)}catch(e){throw this.markLost(e),e}}async renewOrRecover(e){try{return await this.store.renewOwnership(this.sessionId,this.ownerId,e,this.leaseMs)}catch(o){if(!(o instanceof Error&&"code"in o&&o.code==="LEASE_EXPIRED")||!this.store.recoverExpiredOwnership||this.preparingHandoff||this.preparedHandoffId||this.stopped)throw o;return this.store.recoverExpiredOwnership(this.sessionId,this.ownerId,e,this.processId,this.leaseMs)}}async prepareHandoff(e={}){if(this.preparedHandoffId)throw new Error(`Handoff ${this.preparedHandoffId} is already prepared`);this.assertExecutionAllowed(),this.preparingHandoff=!0;try{let o=await this.renewHeldLease();this.handoffOutcomeUncertain=!0;let i=await this.store.createHandoff({...e,sessionId:this.sessionId,sourceOwnerId:o.ownerId,sourceLeaseId:o.leaseId});return this.preparedHandoffId=i.id,this.handoffOutcomeUncertain=!1,i}catch(o){throw this.markLost(o instanceof Error?o:new Error("Handoff preparation failed",{cause:o})),o}finally{this.preparingHandoff=!1}}async stop(e={}){return this.stopping?this.stopping:(this.stopped=!0,this.ready=!1,this.initializationAbort.abort(new Error("Execution lease session has already stopped")),this.timer&&clearInterval(this.timer),this.timer=void 0,this.stopping=this.finishStop(e),this.stopping)}async finishStop(e){await this.starting?.catch(()=>{});let o=this.owner;if(this.owner=void 0,!(e.release===!1||this.preparedHandoffId||this.handoffOutcomeUncertain||!o))try{await this.store.releaseOwnership(this.sessionId,o.ownerId,o.leaseId)}catch{}}async heartbeat(){if(!(!this.ready||!this.owner||this.stopped||this.lostError!==void 0||this.heartbeatInFlight)){this.heartbeatInFlight=!0;try{await this.renewHeldLease()}catch(e){this.markLost(e)}finally{this.heartbeatInFlight=!1}}}markLost(e){this.lostError===void 0&&(this.lostError=e,this.timer&&clearInterval(this.timer),this.timer=void 0,this.onOwnershipLost?.(e))}};import{createHash as Oe}from"node:crypto";import{performance as H}from"node:perf_hooks";async function pt(d,e){let o=e.waitMs??0;if(!Number.isSafeInteger(o)||o<0||o>6e4)throw new u("INVALID","waitMs must be an integer from 0 through 60000");if(e.sinceRevision!==void 0&&!/^[a-f0-9]{64}$/.test(e.sinceRevision))throw new u("INVALID","Invalid handoff revision");if(typeof e.handoffId!="string"||!e.handoffId.trim()||e.handoffId.length>1024)throw new u("INVALID","Invalid handoff identifier");let i=H.now()+o;for(;;){e.signal?.throwIfAborted();let t=await d.getSessionState(e.sessionId);e.signal?.throwIfAborted();let n=t.handoffs.find(a=>a.id===e.handoffId);if(!n)throw new u("NOT_FOUND","Handoff not found in the authorized session");let r=Oe("sha256").update(JSON.stringify([t.sessionId,n.id,n.version,n.status,t.ownershipEpoch,t.owner?.ownerId??null,t.owner?.epoch??null])).digest("hex"),s=e.sinceRevision===void 0||r!==e.sinceRevision;if(s||H.now()>=i)return{sessionId:t.sessionId,handoffId:n.id,revision:r,changed:s,status:n.status,handoffVersion:n.version,ownershipEpoch:t.ownershipEpoch,sourceOwnerId:n.sourceOwnerId,...n.targetOwnerId?{targetOwnerId:n.targetOwnerId}:{}};await new Promise((a,c)=>{let l=e.signal,m=setTimeout(()=>{l?.removeEventListener("abort",E),a()},Math.min(100,Math.max(1,i-H.now()))),E=()=>{clearTimeout(m),l?.removeEventListener("abort",E),c(l?.reason??new Error("Handoff wait cancelled"))};l?.addEventListener("abort",E,{once:!0}),l?.aborted&&E()})}}import{randomUUID as Te}from"node:crypto";import{constants as oe}from"node:fs";import{lstat as P,mkdir as ne,open as U,realpath as B}from"node:fs/promises";import{dirname as q,isAbsolute as re,join as $,relative as xe,resolve as Re,sep as Xe}from"node:path";import{createHash as Se}from"node:crypto";function D(d){return{algorithm:"sha256",value:Se("sha256").update(d).digest("hex")}}var ie=1e4,se=8*1024*1024,ae=64*1024*1024;function de(d){if(typeof d!="string"||!d||d.length>2048||re(d)||/[\\:*?"<>|]/.test(d)||[...d].some(o=>o.charCodeAt(0)<32))throw new Error("Invalid portable snapshot path");let e=d.split("/");if(e.some(o=>!o||o==="."||o===".."||/[. ]$/.test(o)||/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(o)))throw new Error("Ambiguous portable snapshot path");if(e.some(o=>/^(?:\.git|\.ssh|\.aws|\.npmrc|\.netrc|\.xeno-handoff-ready|credentials(?:\.json)?|id_rsa|id_ed25519)$/i.test(o)||/^\.env(?:\.|$)/i.test(o)))throw new Error("Credential or repository-control path cannot be transferred");return d}function ce(d){return D(JSON.stringify([d.schemaVersion,d.sessionId,d.totalBytes,d.files.map(e=>[e.path,e.size,e.sha256,e.executable])])).value}function le(d,e){if(d.schemaVersion!==1||d.sessionId!==e||!Array.isArray(d.files)||d.files.length>ie||!Number.isSafeInteger(d.totalBytes)||d.totalBytes<0||d.totalBytes>ae)throw new Error("Invalid handoff snapshot manifest");let o=new Set,i=0;for(let t of d.files){if(de(t.path),!Number.isSafeInteger(t.size)||t.size<0||t.size>se||!/^[a-f0-9]{64}$/.test(t.sha256)||typeof t.executable!="boolean")throw new Error("Invalid handoff snapshot file");let n=t.path.toLowerCase();if(o.has(n))throw new Error("Snapshot paths collide on Windows");o.add(n),i+=t.size}for(let t of o){let n=t.split("/");for(let r=1;r<n.length;r++)if(o.has(n.slice(0,r).join("/")))throw new Error("Snapshot file conflicts with a directory")}if(i!==d.totalBytes||ce(d)!==d.digest)throw new Error("Handoff snapshot manifest integrity mismatch")}async function F(d,e){let o=d;for(let n of e.split("/"))if(o=$(o,n),(await P(o)).isSymbolicLink())throw new Error("Snapshot symlinks are not supported");let i=await B(o),t=xe(d,i);if(t===".."||t.startsWith(`..${Xe}`)||re(t))throw new Error("Snapshot path escaped its root");return o}async function bt(d){if(!d.sessionId||d.sessionId.length>1024||d.paths.length>ie)throw new Error("Invalid snapshot scope");let e=await B(d.root),o=[],i=new Map,t=0;for(let r of[...d.paths].sort()){if(d.signal?.throwIfAborted(),de(r),!await d.authorizeFile(r))throw new Error("Snapshot file transfer is not authorized");let s=await F(e,r),a=await P(s),c=await U(s,oe.O_RDONLY|(oe.O_NOFOLLOW??0));try{let l=await c.stat();if(await F(e,r),a.ino!==l.ino||a.dev!==l.dev||a.ctimeMs!==l.ctimeMs)throw new Error("Snapshot source was replaced before reading");if(!l.isFile()||l.size>se||t+l.size>ae)throw new Error("Snapshot file or total byte limit exceeded");let f=Buffer.alloc(l.size),m=0;for(;m<f.length;){d.signal?.throwIfAborted();let{bytesRead:j}=await c.read(f,m,f.length-m,m);if(!j)throw new Error("Snapshot source changed while reading");m+=j}let E=await c.stat(),O=await P(s);if(await F(e,r),l.size!==E.size||l.mtimeMs!==E.mtimeMs||l.ctimeMs!==E.ctimeMs||O.isSymbolicLink()||O.ino!==l.ino||O.dev!==l.dev)throw new Error("Snapshot source changed while reading");let T=D(f).value;o.push({path:r,size:f.length,sha256:T,executable:(l.mode&73)!==0}),i.set(T,f),t+=f.length}finally{await c.close()}}let n={schemaVersion:1,sessionId:d.sessionId,files:o,totalBytes:t,digest:""};return n.digest=ce(n),le(n,d.sessionId),{manifest:n,blobs:i}}async function At(d){let e=structuredClone(d.manifest);if(le(e,d.sessionId),!await d.authorizeManifest(structuredClone(e)))throw new Error("Snapshot restoration is not authorized");d.signal?.throwIfAborted();let o=Re(d.destination);if(await B(q(o))!==q(o))throw new Error("Snapshot destination parent must be canonical");try{throw await P(o),new Error("Snapshot destination already exists")}catch(r){if(r.code!=="ENOENT")throw r}let t=`${o}.staging-${Te()}`;await ne(t,{mode:448});for(let r of e.files){d.signal?.throwIfAborted();let s=await d.readBlob(r.sha256,r.size);if(s.byteLength!==r.size||D(s).value!==r.sha256)throw new Error("Snapshot blob integrity mismatch; staging retained");let a=$(t,...r.path.split("/"));await ne(q(a),{recursive:!0,mode:448});let c=await U(a,"wx",r.executable?448:384);try{await c.writeFile(s),await c.sync()}finally{await c.close()}}d.signal?.throwIfAborted();let n=await U($(t,".xeno-handoff-ready"),"wx",384);try{await n.writeFile(JSON.stringify({digest:e.digest,sessionId:e.sessionId})),await n.sync()}finally{await n.close()}return{directory:t,digest:e.digest,files:e.files.length,bytes:e.totalBytes}}export{_ as DurableXenoCoordinationStore,x as XENO_COORDINATION_BUDGET_SESSION_SCHEMA_VERSION,G as XENO_COORDINATION_MANAGED_SESSION_SCHEMA_VERSION,v as XENO_COORDINATION_SCHEMA_VERSION,R as XENO_COORDINATION_TURN_SESSION_SCHEMA_VERSION,u as XenoCoordinationError,te as XenoExecutionLeaseSession,bt as captureXenoHandoffSnapshot,rt as executeXenoCoordinationAction,At as restoreXenoHandoffSnapshot,pt as waitForXenoHandoffStatus};
|
|
1
|
+
var b=1,G=2,x=3,R=4,u=class extends Error{constructor(n,i,t={}){super(i);this.code=n;this.details=t;this.name="XenoCoordinationError"}code;details};import{createHash as pe,randomUUID as L}from"node:crypto";import*as h from"node:fs/promises";import*as v from"node:os";import*as I from"node:path";import{homedir as Q,platform as ue,release as fe}from"node:os";import{resolve as z}from"node:path";var Pe=ue();var De=fe(),Ge=Q();function J(){let d=process.env.XENO_AGENT_HOME?.trim();return d?z(d):z(Q(),".xeno-agent")}var X=class extends Error{constructor(n,i){super(i);this.code=n;this.name="QuotaError"}code;retryable=!1};function W(d){if(typeof d!="string"||!d.trim()||d.length>512)throw new X("INVALID","Invalid quota identity.");return d}function V(d){let e=n=>({id:W(n?.id),generation:W(n?.generation)});if(!d||d.agent&&!d.team)throw new X("INVALID","A child quota scope requires its complete ancestry.");return{workspace:e(d.workspace),...d.team?{team:e(d.team)}:{},...d.agent?{agent:e(d.agent)}:{},...d.goal!==void 0?{goal:e(d.goal)}:{}}}function M(d){return JSON.stringify(V(d))}var he=3e4,me=3e4,ge=6e4,we=2e4,N=new Set(["EACCES","EBUSY","EPERM"]),K=[5,10,20,40,80,160,320],Ie=[5,10,20,40,80,160,320],Y=[1,2,3,4];function p(d,e,n=16384){let i=d.trim();if(!i||i.length>n)throw new u("INVALID",`${e} must be non-empty and no longer than ${n} characters`);return i}function C(d,e){return[...new Set((d??[]).map(n=>p(n,e)))]}function Z(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,i]of Object.entries(d)){if(n!=="maxIterations"&&n!=="maxTokens"&&n!=="maxWallClockMs")throw new u("INVALID","Unknown goal limit");if(i!==void 0){if(!Number.isSafeInteger(i)||i<=0)throw new u("INVALID",`${n} must be a positive safe integer when provided`);e[n]=i}}return e}function Ee(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 y(d){let e=Date.parse(d);return Number.isFinite(e)?e:0}function k(d){if(!Number.isInteger(d)||d<=0)return!1;try{return process.kill(d,0),!0}catch(e){return e.code==="EPERM"}}function ye(d){return{summary:"Goal created; work has not started.",completedTaskCount:0,totalTaskCount:0,outstanding:[],decisions:[],updatedAt:d}}function be(){return{status:"pending",criteria:[],evidence:[]}}function ee(d){return pe("sha256").update(d).digest("hex")}var _=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}_${L()}`),this.ownerLeaseMs=e.ownerLeaseMs??he,this.lockTimeoutMs=e.lockTimeoutMs??me,this.lockStaleMs=e.lockStaleMs??ge,this.maximumEventsPerSession=e.maximumEventsPerSession??we}async getSessionState(e){let n=p(e,"sessionId",1024);return w(await this.readState(n))}async fenceAdmission(e,n,i){let t=p(i.authorityId,"authorityId",512),o=p(i.operationId,"operationId",512);if(!Number.isSafeInteger(n)||n<0)throw new u("INVALID","Expected session version must be a nonnegative safe integer");if(i.action!=="archive"&&i.action!=="delete")throw new u("INVALID","Unsupported admission fence action");return this.mutate(e,r=>{let s=r.admissionFence;if(s?.authorityId===t&&s.operationId===o&&s.action===i.action)return s;if(r.version!==n)throw new u("CONFLICT","Session version changed before lifecycle fencing",{expected:n,actual:r.version});if(s?.authorityId===t&&s.action==="archive"&&i.action==="archive")return s;if(s&&!(s.authorityId===t&&s.action==="archive"&&i.action==="delete"))throw new u("CONFLICT","Another lifecycle fence already owns this session");let a={schemaVersion:1,authorityId:t,operationId:o,action:i.action,createdAt:this.now()};return r.admissionFence=a,r.schemaVersion===1&&(r.schemaVersion=2),this.appendEvent(r,"admission.fenced",{data:{authorityId:t,operationId:o,action:i.action}}),a},!0)}async clearAdmissionFence(e,n,i,t){await this.mutate(e,o=>{this.assertVersion(e,o.version,n);let r=o.admissionFence;if(!r||r.authorityId!==i||r.operationId!==t)throw new 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:i,operationId:t}})},!0)}async releaseDeadLifecycleOwner(e,n,i,t){await this.mutate(e,o=>{this.assertVersion(e,o.version,n);let r=o.admissionFence;if(!r||r.authorityId!==i||r.operationId!==t)throw new u("CONFLICT","Lifecycle fence identity does not match");let s=o.owner;if(s){if(s.host!==v.hostname()||!Number.isInteger(s.processId)||(s.processId??0)<=0||k(s.processId))throw new u("CONFLICT","Execution owner exit has not been proved");o.owner=void 0,this.appendEvent(o,"ownership.released",{ownerId:s.ownerId,data:{epoch:s.epoch,reason:"fenced-local-owner-exited"}})}},!0)}async listSessionStates(){let e=I.join(this.rootDirectory,"sessions"),n;try{n=await h.readdir(e)}catch(t){if(t.code==="ENOENT")return[];throw t}return(await Promise.all(n.filter(t=>t.endsWith(".json")).map(async t=>{try{let o=JSON.parse(await h.readFile(I.join(e,t),"utf8"));return!Y.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)=>y(o.updatedAt)-y(t.updatedAt)).map(t=>w(t))}async createGoal(e){let n=p(e.sessionId,"sessionId",1024),i=Z(e.limits);return this.mutate(n,t=>{let o=t.goals.find(c=>["active","paused","waiting","blocked"].includes(c.status));if(o)throw new u("CONFLICT",`Session ${n} already has active goal ${o.id}`);let r=this.now(),s=(e.successCriteria??[]).map(c=>typeof c=="string"?{id:this.idFactory("criterion"),description:p(c,"successCriteria"),required:!0}:{id:c.id?p(c.id,"successCriteria.id",512):this.idFactory("criterion"),description:p(c.description,"successCriteria.description"),required:c.required}),a={schemaVersion:1,id:this.idFactory("goal"),version:1,sessionId:n,objective:p(e.objective,"objective"),...e.why?{why:p(e.why,"why")}:{},successCriteria:s,constraints:C(e.constraints,"constraints"),...i?{limits:i}:{},metadata:w(e.metadata??{}),status:"active",milestones:[],tasks:[],progress:ye(r),verification:be(),steering:[],createdAt:r,updatedAt:r};return t.goals.push(a),this.appendEvent(t,"goal.created",{goalId:a.id,data:{objective:a.objective}}),a})}async getGoal(e,n){let i=await this.getSessionState(e),t=n?i.goals.find(o=>o.id===n):[...i.goals].reverse().find(o=>["active","paused","waiting","blocked"].includes(o.status));return t?w(t):void 0}async updateGoal(e,n,i,t){return this.mutate(e,o=>{let r=this.requireGoal(o,n);if(this.assertVersion(r.id,r.version,i),["completed","cancelled","failed"].includes(r.status))throw new u("CONFLICT",`Goal ${r.id} is terminal (${r.status})`);let s=r.status!=="active";if(t.status==="active"&&r.status==="blocked"?r.status="active":t.status&&(r.status=t.status),t.objective!==void 0&&(r.objective=p(t.objective,"objective")),t.why!==void 0&&(r.why=p(t.why,"why")),t.constraints&&(r.constraints=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)),s&&r.status==="active")for(let a of o.loops.filter(c=>c.goalId===n&&c.kind==="goal-continuation"&&c.status==="running"))a.resumeRequested=!0,a.version+=1,a.updatedAt=this.now();return r.version+=1,r.updatedAt=this.now(),this.appendEvent(o,"goal.updated",{goalId:r.id,data:{status:r.status,version:r.version}}),r},t.status!==void 0&&["paused","cancelled","failed"].includes(t.status))}async addMilestone(e,n,i,t){return this.mutateGoal(e,n,i,(o,r)=>{let s={id:this.idFactory("milestone"),title:p(t.title,"milestone.title"),...t.description?{description:p(t.description,"milestone.description")}:{},status:o.milestones.some(a=>a.status==="active")?"pending":"active",taskIds:[],createdAt:r,updatedAt:r};o.milestones.push(s),o.progress.currentMilestoneId??=s.id,o.progress.updatedAt=r})}async addTask(e,n,i,t){return this.mutateGoal(e,n,i,(o,r)=>{let s=o.milestones.find(l=>l.id===t.milestoneId);if(!s)throw new u("NOT_FOUND",`Milestone ${t.milestoneId} was not found`);if(t.parentTaskId&&!o.tasks.some(l=>l.id===t.parentTaskId))throw new u("NOT_FOUND",`Parent task ${t.parentTaskId} was not found`);let a=[...new Set(t.dependsOn??[])];for(let l of a)if(!o.tasks.some(f=>f.id===l))throw new u("NOT_FOUND",`Task dependency ${l} was not found`);let c={id:this.idFactory("task"),milestoneId:s.id,...t.parentTaskId?{parentTaskId:t.parentTaskId}:{},title:p(t.title,"task.title"),...t.description?{description:p(t.description,"task.description")}:{},status:a.length===0?"ready":"pending",...t.assignedAgentId?{assignedAgentId:p(t.assignedAgentId,"task.assignedAgentId",512)}:{},...a.length?{dependsOn:a}:{},createdAt:r,updatedAt:r};o.tasks.push(c),s.taskIds.push(c.id),s.updatedAt=r,o.progress.totalTaskCount=o.tasks.length,o.progress.outstanding=o.tasks.filter(l=>l.status!=="completed").map(l=>l.title),o.progress.updatedAt=r})}async updateTask(e,n,i,t,o){return this.mutateGoal(e,n,t,(r,s)=>{let a=r.tasks.find(l=>l.id===i);if(!a)throw new u("NOT_FOUND",`Task ${i} was not found`);a.status=o.status,o.progress!==void 0&&(a.progress=p(o.progress,"task.progress")),o.resultEventId!==void 0&&(a.resultEventId=p(o.resultEventId,"task.resultEventId",512)),o.assignedAgentId!==void 0&&(a.assignedAgentId=p(o.assignedAgentId,"task.assignedAgentId",512)),a.updatedAt=s,a.status==="completed"&&(a.completedAt=s);let c=r.milestones.find(l=>l.id===a.milestoneId);if(c){let l=r.tasks.filter(f=>f.milestoneId===c.id);l.length>0&&l.every(f=>f.status==="completed")?(c.status="completed",c.completedAt=s):l.some(f=>f.status==="running")?c.status="active":l.some(f=>f.status==="blocked")&&(c.status="blocked"),c.updatedAt=s}for(let l of r.tasks)l.status!=="pending"||!l.dependsOn?.length||l.dependsOn.every(f=>r.tasks.find(m=>m.id===f)?.status==="completed")&&(l.status="ready",l.updatedAt=s);this.recalculateProgress(r,s)})}async steerGoal(e,n,i,t){return this.mutateGoal(e,n,i,(o,r,s)=>{let a=this.idFactory("steer");o.steering.push({id:a,instruction:p(t,"instruction"),createdAt:r}),this.appendEvent(s,"goal.steered",{goalId:n,data:{steeringId:a}})},!1)}async consumeGoalSteering(e,n,i){let t=[];return{goal:await this.mutateGoal(e,n,i,(r,s)=>{t=r.steering.filter(a=>!a.consumedAt).map(({id:a,instruction:c,createdAt:l})=>({id:a,instruction:c,createdAt:l}));for(let a of r.steering)a.consumedAt||(a.consumedAt=s)}),instructions:t}}async completeGoal(e,n,i,t){if(t.status!=="passed")throw new 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,i);let s=r.successCriteria.filter(l=>l.required),a=s.filter(l=>{let f=t.criteria.find(m=>m.criterionId===l.id);return!f?.satisfied||f.evidence.length===0});if(a.length>0)throw new u("VERIFICATION_REQUIRED","Required success criteria lack passing evidence",{unmetCriteria:a.map(l=>l.id)});if(s.length===0&&t.evidence.length===0)throw new u("VERIFICATION_REQUIRED","Goal completion requires at least one durable evidence reference");let c=this.now();return r.status="completed",r.verification=w(t),r.verification.verifiedAt??=c,r.completedAt=c,r.updatedAt=c,r.version+=1,this.appendEvent(o,"goal.completed",{goalId:n,data:{evidence:r.verification.evidence}}),r},!0)}async cancelGoal(e,n,i,t){return this.mutate(e,o=>{let r=this.requireGoal(o,n);if(this.assertVersion(r.id,r.version,i),["completed","cancelled","failed"].includes(r.status))return r;r.status="cancelled",r.updatedAt=this.now(),r.version+=1,this.appendEvent(o,"goal.cancelled",{goalId:n,data:{reason:p(t,"reason")}});for(let s of o.loops.filter(a=>a.goalId===n&&["running","paused","waiting"].includes(a.status)))s.status="stopped",s.resumeRequested!==void 0&&(s.resumeRequested=!1),s.stopReason=`Goal cancelled: ${t}`,s.stoppedAt=this.now(),s.updatedAt=s.stoppedAt,s.version+=1;return r},!0)}async startLoop(e){return this.mutate(e.sessionId,n=>this.createLoopRecord(n,e))}createLoopRecord(e,n){if(n.kind==="goal-continuation"&&!n.goalId)throw new u("INVALID","Goal-continuation loops require a goalId");if(n.goalId){let s=this.requireGoal(e,n.goalId);if(["completed","cancelled","failed"].includes(s.status))throw new u("CONFLICT",`Cannot start a loop for terminal goal ${s.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 i=Ee(n.schedule),t=e.loops.find(s=>s.goalId===n.goalId&&s.kind===n.kind&&["running","paused","waiting"].includes(s.status));if(t)throw new 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:p(n.activity,"activity")}:{},iterations:[],...i?{schedule:i}:{},createdAt:o,updatedAt:o};return e.loops.push(r),this.appendEvent(e,"loop.started",{loopId:r.id,goalId:r.goalId,data:{kind:r.kind}}),r}async getLoop(e,n){let i=await this.getSessionState(e),t=n?i.loops.find(o=>o.id===n):[...i.loops].reverse().find(o=>["running","paused","waiting"].includes(o.status));return t?w(t):void 0}async beginLoopIteration(e,n,i,t,o){return this.mutateLoop(e,n,i,(r,s,a)=>{this.appendLoopIteration(a,r,s,t,o)},!1)}appendLoopIteration(e,n,i,t,o,r=!1){if(n.status!=="running")throw new u("CONFLICT",`Loop ${n.id} is ${n.status}`);if(n.goalId){let c=this.requireGoal(e,n.goalId);this.isCliGoal(c)&&this.initializeGoalTurnAccounting(e,c)}if(this.assertGoalIterationAdmission(e,n,i,r),n.iterations.some(c=>c.status==="running"))throw new u("CONFLICT",`Loop ${n.id} already has a running iteration`);let s=(n.iterations.at(-1)?.number??0)+1;n.currentActivity=p(t,"activity");let a={number:s,startedAt:i,status:"running",activity:n.currentActivity,...n.goalId&&e.goalTurnAccounting?.[n.goalId]?{goalAccountingVersion:1}:{},...o?{taskId:p(o,"taskId",512)}:{}};return n.iterations.push(a),n.resumeRequested!==void 0&&(n.resumeRequested=!1),this.appendEvent(e,"loop.iteration",{loopId:n.id,goalId:n.goalId,data:{number:s,phase:"started",activity:n.currentActivity}}),a}async admitGoalTurn(e){return this.admitGoalTurnWithOwner(e)}async admitQuotaGoalTurn(e,n,i,t){let o=V(i),r=await this.getGoal(e.sessionId,e.goalId);if(!r||r.sessionId!==e.sessionId||r.limits?.maxTokens===void 0)throw new u("BUDGET_UNAVAILABLE","The exact token-bounded goal is unavailable for quota admission");if(this.isCliGoal(r)&&r.metadata["cli.tokenQuotaVersion"]!==1)throw new u("BUDGET_UNAVAILABLE","Legacy CLI goal token spend is unknown; quota admission requires creation-time provenance");if(o.goal?.id!==r.id||o.goal.generation!==r.createdAt)throw new u("BUDGET_UNAVAILABLE","Quota scope does not identify this durable goal generation");let s=await n.policy(o);if(!s||M(s.scope)!==M(o)||s.limits.tokensLifetime===void 0||s.limits.tokensLifetime===null||s.limits.tokensLifetime>r.limits.maxTokens)throw new u("BUDGET_UNAVAILABLE","Goal quota policy is absent or wider than the goal's explicit token limit");let a=await n.remainingTokens(o);if(a===null)throw new u("BUDGET_UNAVAILABLE","Goal token accounting has no durable remaining allowance");if(a<1)throw new u("BUDGET_EXCEEDED","Goal token allowance is exhausted");return this.admitGoalTurnWithOwner(e,t,{goalId:r.id,createdAt:r.createdAt,maximum:r.limits.maxTokens})}async admitOwnedGoalTurn(e,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,i){let t=p(e.requestId,"requestId",512),o=this.goalTurnHash(e.requestHash);return this.mutate(e.sessionId,r=>{if(n){let f=this.requireOwner(r,n.ownerId,n.leaseId);if(f.epoch!==n.epoch)throw new u("NOT_OWNER","Execution ownership epoch changed");if(this.ownerExpired(f,this.now()))throw new u("LEASE_EXPIRED","Execution ownership expired");if(r.handoffs.some(m=>["prepared","available"].includes(m.status)&&m.sourceLeaseEpoch===f.epoch)||r.handoffs.some(m=>m.status==="claimed"&&m.targetLeaseEpoch===f.epoch))throw new u("UNSAFE_HANDOFF","Execution handoff has not settled")}let s=this.requireGoal(r,e.goalId);if(i&&(s.id!==i.goalId||s.createdAt!==i.createdAt||s.limits?.maxTokens!==i.maximum))throw new u("BUDGET_UNAVAILABLE","Goal token limit changed after quota verification");for(let f of r.loops.filter(m=>m.goalId===s.id)){let m=f.iterations.find(E=>E.goalTurn?.requestId===t);if(m){if(m.goalTurn?.requestHash!==o)throw new u("CONFLICT","Goal turn identity was reused for different work");return{...this.goalTurnState(r,s,f,m),admitted:!1}}}if(this.assertVersion(s.id,s.version,e.expectedGoalVersion),s.status!=="active")throw new u("CONFLICT",`Goal ${s.id} is ${s.status}`);let a=[...r.loops].reverse().find(f=>f.goalId===s.id&&f.kind==="goal-continuation");if(e.expectedLoopId!==void 0){if(!a||a.id!==e.expectedLoopId)throw new u("CONFLICT","Goal continuation loop changed before admission");this.assertVersion(a.id,a.version,e.expectedLoopVersion??-1)}else if(e.expectedLoopVersion!==void 0)throw new u("INVALID","A goal turn loop version requires its exact loop ID");if(a&&a.status!=="running")throw new u("CONFLICT",`Goal loop ${a.id} is ${a.status}; resume or start it explicitly`);this.initializeGoalTurnAccounting(r,s),a??=this.createLoopRecord(r,{sessionId:r.sessionId,goalId:s.id,kind:"goal-continuation"});let c=this.now(),l=this.appendLoopIteration(r,a,c,"Interactive goal turn",void 0,i!==void 0);if(e.executionKind!==void 0&&e.executionKind!=="local-sdk"&&e.executionKind!=="external")throw new u("INVALID","Unknown goal execution lane");return l.goalTurn={requestId:t,requestHash:o,executor:e.executionKind==="local-sdk"?{kind:"local-sdk",processId:process.pid,host:v.hostname()}:{kind:"external"}},a.version+=1,a.updatedAt=c,{...this.goalTurnState(r,s,a,l),admitted:!0}},!1,r=>r.admitted)}async getGoalTurnState(e,n,i){let t=await this.getSessionState(e),o=n?t.goals.find(c=>c.id===n):[...t.goals].reverse().find(c=>["active","paused","waiting","blocked"].includes(c.status));if(!o)return;let r=t.loops.filter(c=>c.goalId===o.id),s=i?r.find(c=>c.iterations.some(l=>l.goalTurn?.requestId===i)):[...r].reverse().find(c=>c.kind==="goal-continuation"),a=i?s?.iterations.find(c=>c.goalTurn?.requestId===i):s?.iterations.at(-1);if(i&&!a)throw new u("NOT_FOUND","Goal turn was not found");return this.goalTurnState(t,o,s,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,i=>{let t=this.requireGoal(i,e.goalId),o=i.loops.find(s=>s.goalId===t.id&&s.iterations.some(a=>a.goalTurn?.requestId===e.requestId)),r=o?.iterations.find(s=>s.goalTurn?.requestId===e.requestId);if(!o||!r)throw new 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(i,o,r,this.now(),{status:t.status==="cancelled"||["stopped","failed"].includes(o.status)?"interrupted":e.status}),o.version+=1,o.updatedAt=this.now()),this.goalTurnState(i,t,o,r)},!0)}async recoverGoalTurn(e,n,i){return this.mutate(e,t=>{let o=this.requireGoal(t,n),r=t.loops.find(a=>a.goalId===n&&a.iterations.some(c=>c.goalTurn?.requestId===i)),s=r?.iterations.find(a=>a.goalTurn?.requestId===i);if(!r||!s)throw new u("NOT_FOUND","Goal turn was not found");if(s.status==="running"){if(!this.goalTurnOwnerExited(s))throw new u("NOT_OWNER","The original local goal executor has not been proved exited; external execution requires reconciliation");this.settleLoopIteration(t,r,s,this.now(),{status:"interrupted",error:"Original local SDK executor exited; inspect persisted results before retrying work"}),r.resumeRequested=o.status==="active"&&r.status==="running",r.version+=1,r.updatedAt=this.now()}return this.goalTurnState(t,o,r,s)},!0)}async finishLoopIteration(e,n,i,t){return this.mutateLoop(e,n,i,(o,r,s)=>{let a=[...o.iterations].reverse().find(c=>c.status==="running");if(!a)throw new u("CONFLICT",`Loop ${o.id} has no running iteration`);this.settleLoopIteration(s,o,a,r,t)},!1,!0)}settleLoopIteration(e,n,i,t,o){i.status=o.status,i.completedAt=t,o.verificationEventId&&(i.verificationEventId=p(o.verificationEventId,"verificationEventId",512)),o.error&&(i.error=p(o.error,"error")),n.status=["stopped","completed","failed"].includes(n.status)?n.status:e.admissionFence?"paused":o.nextStatus??(n.status==="paused"||n.status==="waiting"?n.status:"running"),this.appendEvent(e,"loop.iteration",{loopId:n.id,goalId:n.goalId,data:{number:i.number,phase:"finished",status:o.status}})}async setLoopStatus(e,n,i,t,o){return this.mutateLoop(e,n,i,(r,s,a)=>{let c=r.status;if(["stopped","completed","failed"].includes(c))throw new u("CONFLICT",`Loop ${r.id} is terminal (${c})`);let l=[...r.iterations].reverse().find(m=>m.status==="running");if(l&&t==="completed")throw new u("CONFLICT",`Loop ${r.id} cannot complete while iteration ${l.number} is running`);l&&(t==="stopped"||t==="failed")&&(l.status=t==="failed"?"failed":"interrupted",l.completedAt=s,l.error=p(o??t,"reason")),r.status=t,r.kind==="goal-continuation"&&(r.resumeRequested=t==="running"),["stopped","completed","failed"].includes(t)&&(r.stoppedAt=s,r.stopReason=p(o??t,"reason"));let f=t==="paused"?"loop.paused":t==="waiting"?"loop.waiting":t==="running"&&(c==="paused"||c==="waiting")?"loop.resumed":t==="completed"?"loop.completed":t==="failed"?"loop.failed":"loop.stopped";this.appendEvent(a,f,{loopId:n,goalId:r.goalId,data:{previous:c,status:t,...o?{reason:o}:{}}})},!1,t!=="running"&&t!=="waiting")}async acquireOwnership(e,n,i={}){return this.mutate(e,t=>{let o=this.now();if(t.owner&&!this.ownerExpired(t.owner,o)){if(t.owner.ownerId===n&&i.processId!==void 0&&t.owner.processId===i.processId&&(i.host===void 0||t.owner.host===i.host))return t.owner;throw new 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 c of t.handoffs.filter(l=>l.status==="claimed"&&l.claimedBy===r.ownerId&&l.targetLeaseEpoch===r.epoch))c.status="failed",c.failureReason=`Claimed owner ${r.ownerId} lost its execution lease before completing the handoff.`,c.failedAt=o,c.updatedAt=o,c.version+=1,this.appendEvent(t,"handoff.failed",{handoffId:c.id,goalId:c.goalId,loopId:c.loopId,data:{reason:c.failureReason,expiredLeaseId:r.leaseId}});let s=t.ownershipEpoch+1;for(let c of t.handoffs.filter(l=>["prepared","available"].includes(l.status)&&l.sourceLeaseEpoch<s))c.status="failed",c.failureReason="Source ownership epoch was superseded before the handoff was claimed.",c.failedAt=o,c.updatedAt=o,c.version+=1,this.appendEvent(t,"handoff.failed",{handoffId:c.id,data:{epoch:s,reason:c.failureReason}});let a=this.newOwner(n,s,i,o);return t.owner=a,t.ownershipEpoch=s,this.appendEvent(t,"ownership.acquired",{ownerId:n,data:{epoch:s,leaseId:a.leaseId}}),a})}async renewOwnership(e,n,i,t=this.ownerLeaseMs){return this.mutate(e,o=>{let r=this.requireOwner(o,n,i);if(this.ownerExpired(r,this.now()))throw new u("LEASE_EXPIRED",`Ownership lease ${i} expired`);return r.heartbeatAt=this.now(),r.expiresAt=new Date(y(r.heartbeatAt)+t).toISOString(),this.appendEvent(o,"ownership.renewed",{ownerId:n,data:{epoch:r.epoch,leaseId:i}}),r})}async recoverExpiredOwnership(e,n,i,t,o=this.ownerLeaseMs){return this.mutate(e,r=>{let s=this.requireOwner(r,n,i);if(s.processId!==t||s.host!==v.hostname()||!k(t))throw new u("LEASE_EXPIRED",`Ownership lease ${i} expired and cannot be recovered by process ${t}`);let a=this.now(),c=Math.max(0,y(a)-y(s.expiresAt));return s.heartbeatAt=a,s.expiresAt=new Date(y(a)+o).toISOString(),this.appendEvent(r,c>0?"ownership.recovered":"ownership.renewed",{ownerId:n,data:{epoch:s.epoch,leaseId:i,...c>0?{expiredForMs:c}:{}}}),s})}async releaseOwnership(e,n,i){return this.mutate(e,t=>{let o=this.requireOwner(t,n,i);for(let r of t.handoffs.filter(s=>s.status==="claimed"&&s.claimedBy===n&&s.targetLeaseEpoch===o.epoch))r.status="failed",r.failureReason="Target released execution ownership before completing the handoff.",r.failedAt=this.now(),r.updatedAt=r.failedAt,r.version+=1,this.appendEvent(t,"handoff.failed",{handoffId:r.id,ownerId:n,data:{epoch:o.epoch,reason:r.failureReason}});return t.owner=void 0,this.appendEvent(t,"ownership.released",{ownerId:n,data:{epoch:o.epoch}}),o},!0)}async createHandoff(e){let n=!1,i=e.prepareRequestId===void 0?void 0:p(e.prepareRequestId,"prepareRequestId",512);return this.mutate(e.sessionId,t=>{let o=this.requireOwner(t,e.sourceOwnerId,e.sourceLeaseId);if(this.ownerExpired(o,this.now()))throw new u("LEASE_EXPIRED",`Ownership lease ${o.leaseId} expired`);if(i){let l=t.handoffs.find(f=>f.prepareRequestId===i);if(l){if(l.sourceOwnerId!==o.ownerId||l.sourceLeaseEpoch!==o.epoch||l.status!=="available"||l.targetOwnerId!==e.targetOwnerId||l.workspace!==e.workspace||l.goalId!==e.goalId||l.loopId!==e.loopId||l.contextDigest!==e.contextDigest||l.branch!==e.branch||l.currentMilestoneId!==e.currentMilestoneId||l.currentTaskId!==e.currentTaskId||JSON.stringify(l.agentIds)!==JSON.stringify([...new Set(e.agentIds??[])])||JSON.stringify(l.operations)!==JSON.stringify(e.operations??[]))throw new u("CONFLICT","Prepare identity was reused for different work or ownership");return n=!0,l}}let r=(e.operations??[]).filter(l=>l.status==="running"&&l.sideEffecting);if(r.length>0)throw new u("UNSAFE_HANDOFF","Running side-effecting operations must settle before execution handoff",{operationIds:r.map(l=>l.operationId)});if(e.goalId&&this.requireGoal(t,e.goalId),e.loopId&&!t.loops.some(l=>l.id===e.loopId))throw new u("NOT_FOUND",`Loop ${e.loopId} was not found`);let s=t.handoffs.find(l=>["prepared","available","claimed"].includes(l.status));if(s)throw new u("CONFLICT",`Handoff ${s.id} is already active`);let a=this.now(),c={schemaVersion:1,id:this.idFactory("handoff"),version:1,sessionId:t.sessionId,...e.goalId?{goalId:e.goalId}:{},...e.loopId?{loopId:e.loopId}:{},status:"available",sourceOwnerId:o.ownerId,...i?{prepareRequestId:i}:{},...e.targetOwnerId?{targetOwnerId:p(e.targetOwnerId,"targetOwnerId",512)}:{},sourceLeaseEpoch:o.epoch,...e.workspace?{workspace:p(e.workspace,"workspace",32768)}:{},...e.branch?{branch:p(e.branch,"branch",1024)}:{},...e.currentMilestoneId?{currentMilestoneId:e.currentMilestoneId}:{},...e.currentTaskId?{currentTaskId:e.currentTaskId}:{},agentIds:[...new Set(e.agentIds??[])],operations:w(e.operations??[]),...e.contextDigest?{contextDigest:p(e.contextDigest,"contextDigest",512)}:{},createdAt:a,updatedAt:a};return t.handoffs.push(c),this.appendEvent(t,"handoff.created",{handoffId:c.id,goalId:c.goalId,loopId:c.loopId,ownerId:o.ownerId,data:{targetOwnerId:c.targetOwnerId}}),c},!1,()=>!n)}async claimHandoff(e){let n,i=!1,t=e.claimRequestId===void 0?void 0:p(e.claimRequestId,"claimRequestId",512);return{handoff:await this.mutate(e.sessionId,r=>{let s=r.handoffs.find(l=>l.id===e.handoffId);if(!s)throw new u("NOT_FOUND",`Handoff ${e.handoffId} was not found`);if(s.status!=="available"){let l=r.owner;if(t&&s.claimRequestId===t&&["claimed","completed"].includes(s.status)&&s.claimedBy===e.targetOwnerId&&l?.ownerId===e.targetOwnerId&&l.epoch===s.targetLeaseEpoch&&l.host===e.host&&l.processId===e.processId&&!this.ownerExpired(l,this.now()))return n=l,i=!0,s;throw new u("CONFLICT",`Handoff ${s.id} is ${s.status}`,{claimedBy:s.claimedBy})}if(s.targetOwnerId&&s.targetOwnerId!==e.targetOwnerId)throw new u("CONFLICT",`Handoff ${s.id} is reserved for ${s.targetOwnerId}`);let a=r.owner;if(!a||a.ownerId!==s.sourceOwnerId||a.epoch!==s.sourceLeaseEpoch)throw new u("CONFLICT",`Handoff ${s.id} no longer matches the source ownership epoch`);let c=this.now();return n=this.newOwner(e.targetOwnerId,a.epoch+1,{processId:e.processId,host:e.host,leaseMs:e.leaseMs},c),r.owner=n,r.ownershipEpoch=n.epoch,s.status="claimed",s.claimedBy=e.targetOwnerId,t&&(s.claimRequestId=t),s.targetOwnerId=e.targetOwnerId,s.targetLeaseEpoch=n.epoch,s.claimedAt=c,s.updatedAt=c,s.version+=1,this.appendEvent(r,"handoff.claimed",{handoffId:s.id,goalId:s.goalId,loopId:s.loopId,ownerId:e.targetOwnerId,data:{sourceOwnerId:s.sourceOwnerId,epoch:n.epoch}}),s},!1,()=>!i),owner:w(n)}}async completeHandoff(e,n,i,t){let o=!1;return this.mutate(e,r=>{let s=this.requireOwner(r,i,t);if(this.ownerExpired(s,this.now()))throw new u("LEASE_EXPIRED",`Ownership lease ${t} expired`);let a=r.handoffs.find(c=>c.id===n);if(!a)throw new u("NOT_FOUND",`Handoff ${n} was not found`);if(a.claimedBy!==i||a.targetLeaseEpoch!==s.epoch||!["claimed","completed"].includes(a.status))throw new u("CONFLICT",`Handoff ${a.id} cannot be completed by ${i}`);return a.status==="completed"?(o=!0,a):(a.status="completed",a.completedAt=this.now(),a.updatedAt=a.completedAt,a.version+=1,this.appendEvent(r,"handoff.completed",{handoffId:n,goalId:a.goalId,loopId:a.loopId,ownerId:i,data:{epoch:r.owner?.epoch}}),a)},!1,()=>!o)}async cancelHandoff(e,n,i,t){let o=!1;return this.mutate(e,r=>{let s=r.handoffs.find(c=>c.id===n);if(!s)throw new u("NOT_FOUND",`Handoff ${n} was not found`);if(s.sourceOwnerId!==i)throw new u("CONFLICT",`Handoff ${n} was not offered by ${i}`);if(s.status==="cancelled")return o=!0,s;if(s.status!=="available"&&s.status!=="prepared")throw new u("CONFLICT",`Handoff ${n} is ${s.status} and can no longer be cancelled`);let a=this.requireOwner(r,i,t);if(this.ownerExpired(a,this.now()))throw new u("LEASE_EXPIRED",`Ownership lease ${t} expired`);if(s.sourceLeaseEpoch!==a.epoch)throw new u("CONFLICT",`Handoff ${n} belongs to an earlier ownership epoch`);return s.status="cancelled",s.cancelledAt=this.now(),s.updatedAt=s.cancelledAt,s.version+=1,this.appendEvent(r,"handoff.cancelled",{handoffId:n,goalId:s.goalId,loopId:s.loopId,ownerId:i,data:{epoch:a.epoch}}),s},!1,()=>!o)}async failHandoff(e,n,i){return this.mutate(e,t=>{let o=t.handoffs.find(r=>r.id===n);if(!o)throw new u("NOT_FOUND",`Handoff ${n} was not found`);return["completed","cancelled","failed"].includes(o.status)||(o.status="failed",o.failureReason=p(i,"reason"),o.failedAt=this.now(),o.updatedAt=o.failedAt,o.version+=1,this.appendEvent(t,"handoff.failed",{handoffId:n,goalId:o.goalId,loopId:o.loopId,data:{reason:o.failureReason}})),o},!0)}async mutateGoal(e,n,i,t,o=!0){return this.mutate(e,r=>{let s=this.requireGoal(r,n);this.assertVersion(s.id,s.version,i);let a=this.now();return t(s,a,r),s.version+=1,s.updatedAt=a,o&&this.appendEvent(r,"goal.updated",{goalId:n,data:{status:s.status,version:s.version}}),s})}async mutateLoop(e,n,i,t,o=!0,r=!1){return this.mutate(e,s=>{let a=s.loops.find(l=>l.id===n);if(!a)throw new u("NOT_FOUND",`Loop ${n} was not found`);this.assertVersion(a.id,a.version,i);let c=this.now();return t(a,c,s),a.version+=1,a.updatedAt=c,o&&this.appendEvent(s,"loop.iteration",{loopId:n,goalId:a.goalId,data:{status:a.status,version:a.version}}),a},r)}assertGoalIterationAdmission(e,n,i,t=!1){if(!n.goalId)return;let o=this.requireGoal(e,n.goalId);if(o.status!=="active")throw new u("CONFLICT",`Goal ${o.id} is ${o.status}; no iteration was admitted`);let r=Z(o.limits);if(r?.maxTokens!==void 0&&!t)throw new u("BUDGET_UNAVAILABLE","Goal token allowance is not bound to request-level admission; no iteration was admitted",{goalId:o.id,limit:"maxTokens"});if(r?.maxWallClockMs!==void 0){let s=Date.parse(o.createdAt),a=Date.parse(i);if(!Number.isFinite(s)||!Number.isFinite(a)||a<s)throw new u("BUDGET_UNAVAILABLE","Goal wall-clock allowance cannot be verified",{goalId:o.id,limit:"maxWallClockMs"});if(a-s>=r.maxWallClockMs)throw new u("BUDGET_EXCEEDED","Goal wall-clock limit reached; no iteration was admitted",{goalId:o.id,limit:"maxWallClockMs",maximum:r.maxWallClockMs})}if(r?.maxIterations!==void 0){let s=e.goalTurnAccounting!==void 0||e.schemaVersion===4?this.resolveGoalTurnAccounting(e,o):void 0;if(s?.coverage==="partial")throw new u("BUDGET_UNAVAILABLE","Legacy goal turn accounting is incomplete");let a=this.goalIterationCount(e,o)+(s?.baseIterations??0);if(!Number.isSafeInteger(a)||a<0)throw new u("BUDGET_UNAVAILABLE","Invalid goal iteration accounting");if(a>=r.maxIterations)throw new u("BUDGET_EXCEEDED","Goal iteration limit reached; no iteration was admitted",{goalId:o.id,limit:"maxIterations",admitted:a,maximum:r.maxIterations})}}isCliGoal(e){return"cli.accountedTurns"in e.metadata||"cli.createdByCliVersion"in e.metadata}goalIterationCount(e,n){let i=0;for(let t of e.loops.filter(o=>o.goalId===n.id)){if(!Array.isArray(t.iterations))throw new 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(i+=o,!Number.isSafeInteger(i))throw new u("BUDGET_UNAVAILABLE","Goal iteration count exceeds its supported range")}return i}resolveGoalTurnAccounting(e,n){let i=e.goalTurnAccounting;if(i!==void 0&&(!i||typeof i!="object"||Array.isArray(i)))throw new u("BUDGET_UNAVAILABLE","Persisted goal turn accounting is invalid");if(i&&Object.hasOwn(i,n.id)){let a=i[n.id];if(!a||a.schemaVersion!==1||!Number.isSafeInteger(a.baseIterations)||a.baseIterations<0||!["complete","partial"].includes(a.coverage))throw new u("BUDGET_UNAVAILABLE","Persisted goal turn accounting is invalid");return a}if(e.loops.some(a=>a.goalId===n.id&&a.iterations.some(c=>c.goalTurn||c.goalAccountingVersion)))throw new 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,s=this.isCliGoal(n)&&(!r||o>0&&t>0);return{schemaVersion:1,baseIterations:r&&t===0?o:0,coverage:s?"partial":"complete"}}initializeGoalTurnAccounting(e,n){let i=this.resolveGoalTurnAccounting(e,n);if(i.coverage==="partial"&&n.limits?.maxIterations!==void 0)throw new u("BUDGET_UNAVAILABLE","Legacy goal turn accounting needs reconciliation before bounded execution");e.goalTurnAccounting??={},Object.defineProperty(e.goalTurnAccounting,n.id,{value:i,writable:!0,enumerable:!0,configurable:!0})}goalTurnHash(e){let n=p(e,"requestHash",64).toLowerCase();if(!/^[0-9a-f]{64}$/.test(n))throw new u("INVALID","Goal turn requestHash must be a SHA-256 digest");return n}goalTurnState(e,n,i,t){let o=this.resolveGoalTurnAccounting(e,n),r=this.goalIterationCount(e,n)+o.baseIterations;if(!Number.isSafeInteger(r))throw new u("BUDGET_UNAVAILABLE","Goal turn count exceeds its supported range");return w({goal:n,admittedTurns:r,accountingCoverage:o.coverage,...i?{loopId:i.id,loopVersion:i.version,loopStatus:i.status,resumeRequested:i.resumeRequested===!0}:{},...t?{iterationNumber:t.number,iterationStatus:t.status,...t.goalTurn?{requestId:t.goalTurn.requestId,requestHash:t.goalTurn.requestHash}:{},canRecover:t.status==="running"&&this.goalTurnOwnerExited(t)}:{}})}goalTurnOwnerExited(e){let n=e.goalTurn?.executor;if(n?.kind!=="local-sdk"||n.host!==v.hostname()||!Number.isSafeInteger(n.processId)||n.processId<=0)return!1;try{return process.kill(n.processId,0),!1}catch(i){return i.code==="ESRCH"}}recalculateProgress(e,n){let i=e.tasks.filter(t=>t.status==="completed").length;e.progress.completedTaskCount=i,e.progress.totalTaskCount=e.tasks.length,e.progress.percent=e.tasks.length?Math.round(i/e.tasks.length*100):void 0,e.progress.outstanding=e.tasks.filter(t=>!["completed","cancelled"].includes(t.status)).map(t=>t.title),e.progress.updatedAt=n}requireGoal(e,n){let i=e.goals.find(t=>t.id===n);if(!i)throw new u("NOT_FOUND",`Goal ${n} was not found`);return i}requireOwner(e,n,i){let t=e.owner;if(!t||t.ownerId!==n||t.leaseId!==i)throw new u("NOT_OWNER",`${n} does not own session ${e.sessionId}`,{owner:t});return t}assertVersion(e,n,i){if(!Number.isInteger(i)||i<1||n!==i)throw new u("CONFLICT",`Expected ${e} version ${i}, found ${n}`,{expected:i,actual:n})}newOwner(e,n,i,t){let o=i.leaseMs??this.ownerLeaseMs;if(!Number.isSafeInteger(o)||o<1)throw new u("INVALID","leaseMs must be a positive safe integer");return{ownerId:p(e,"ownerId",512),leaseId:this.idFactory("owner"),epoch:n,acquiredAt:t,heartbeatAt:t,expiresAt:new Date(y(t)+o).toISOString(),...i.processId!==void 0?{processId:i.processId}:{},...i.host?{host:p(i.host,"host",512)}:{}}}ownerExpired(e,n){return y(e.expiresAt)<=y(n)?!0:e.processId!==void 0&&e.host===v.hostname()&&!k(e.processId)}appendEvent(e,n,i){let t={schemaVersion:1,id:this.idFactory("event"),sequence:(e.events.at(-1)?.sequence??0)+1,type:n,sessionId:e.sessionId,...i.goalId?{goalId:i.goalId}:{},...i.loopId?{loopId:i.loopId}:{},...i.handoffId?{handoffId:i.handoffId}:{},...i.ownerId?{ownerId:i.ownerId}:{},timestamp:this.now(),data:w(i.data)};e.events.push(t),e.events.length>this.maximumEventsPerSession&&e.events.splice(0,e.events.length-this.maximumEventsPerSession)}async mutate(e,n,i=!1,t=()=>!0){let o=p(e,"sessionId",1024);return this.withSessionLock(o,async()=>{let r=await this.readState(o);if(r.admissionFence&&!i)throw new u("CONFLICT","Session execution is blocked by a persisted lifecycle fence");let s=r.schemaVersion;this.promoteGoalBudgetEnvelope(r),r.schemaVersion!==s&&await this.writeState(r);let a=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",`${ee(e)}.json`)}lockPath(e){return`${this.statePath(e)}.lock`}async readState(e){let n=this.statePath(e);try{let i=await h.readFile(n,"utf8"),t=JSON.parse(i);if(!Y.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(i){if(i.code!=="ENOENT")throw i;let t=this.now();return{schemaVersion:1,sessionId:e,version:0,ownershipEpoch:0,goals:[],loops:[],handoffs:[],events:[],createdAt:t,updatedAt:t}}}promoteGoalBudgetEnvelope(e){(e.goalTurnAccounting!==void 0||e.loops.some(n=>n.resumeRequested!==void 0||n.iterations.some(i=>i.goalTurn!==void 0)))&&(e.schemaVersion=4),e.schemaVersion<3&&e.goals.some(n=>n.limits!==void 0&&(!n.limits||typeof n.limits!="object"||Array.isArray(n.limits)||Object.keys(n.limits).length>0))&&(e.schemaVersion=3)}async writeState(e){this.promoteGoalBudgetEnvelope(e);let n=this.statePath(e.sessionId),i=I.dirname(n);await h.mkdir(i,{recursive:!0});let t=`${n}.${process.pid}.${L()}.tmp`,o=await h.open(t,"wx");try{await o.writeFile(`${JSON.stringify(e,null,2)}
|
|
2
|
+
`,"utf8"),await o.sync()}finally{await o.close()}try{await this.renameReplacing(t,n);try{let r=await h.open(i,"r");try{await r.sync()}finally{await r.close()}}catch{}}finally{await h.unlink(t).catch(()=>{})}}async renameReplacing(e,n){for(let i=0;;i+=1)try{await h.rename(e,n);return}catch(t){let o=t.code,r=K[i];if(process.platform!=="win32"||!o||!N.has(o)||r===void 0)throw t;await new Promise(s=>setTimeout(s,r))}}async withSessionLock(e,n){let i=this.lockPath(e),t=I.join(i,"owner.json"),o=L(),r=`${i}.candidate.${o}`,s=Date.now();await h.mkdir(I.dirname(i),{recursive:!0});let a={schemaVersion:1,token:o,pid:process.pid,host:v.hostname(),acquiredAt:this.now()};await h.mkdir(r),await h.writeFile(I.join(r,"owner.json"),JSON.stringify(a),{encoding:"utf8",flag:"wx"});for(let c=0;;c+=1)try{await h.rename(r,i);break}catch(l){let f=l.code;if(!(!!f&&new Set(["EEXIST","ENOTEMPTY","ENOTDIR","EBUSY"]).has(f)||process.platform==="win32"&&!!f&&N.has(f)))throw await h.rm(r,{recursive:!0,force:!0}).catch(()=>{}),l;let O=await this.staleLockOwner(i,t);if(O){await this.quarantineLock(i,O.token,"stale");continue}if(Date.now()-s>=this.lockTimeoutMs)throw await h.rm(r,{recursive:!0,force:!0}).catch(()=>{}),new u("CONFLICT",`Timed out waiting for coordination lock for session ${e}`);await new Promise(T=>setTimeout(T,Math.min(100,5+c*5)+Math.floor(Math.random()*10)))}try{return await n()}finally{await this.quarantineLock(i,o,"released"),await h.rm(r,{recursive:!0,force:!0}).catch(()=>{})}}async staleLockOwner(e,n){try{let[i,t]=await Promise.all([h.readFile(n,"utf8").catch(()=>""),h.stat(e)]),o=i?JSON.parse(i):void 0;return!o||o.host!==v.hostname()||k(o.pid)?void 0:Date.now()-t.mtimeMs>this.lockStaleMs?o:void 0}catch{return}}async quarantineLock(e,n,i){let t=I.join(e,"owner.json"),o=i==="stale"?`${e}.stale.${ee(n)}`:`${e}.${i}.${n}.${L()}`;for(let r=0;;r+=1){let s;try{s=JSON.parse(await h.readFile(t,"utf8"))}catch(a){if(a.code==="ENOENT")return;throw a}if(s.token!==n)return;try{await h.rename(e,o);break}catch(a){let c=a.code;if(i==="stale")try{if(JSON.parse(await h.readFile(I.join(o,"owner.json"),"utf8")).token===n)return}catch{}if(c==="ENOENT"||c==="EEXIST")return;let l=K[r];if(process.platform!=="win32"||!c||!N.has(c)||l===void 0)throw a;await new Promise(f=>setTimeout(f,l))}}if(i!=="stale")for(let r=0;;r+=1)try{await h.rm(o,{recursive:!0});return}catch(s){let a=s.code;if(a==="ENOENT")return;let c=Ie[r];if(process.platform!=="win32"||!a||!N.has(a)||c===void 0)throw s;await new Promise(l=>setTimeout(l,c))}}};function S(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 A(d,e){if(typeof d!="number"||!Number.isInteger(d))throw new Error(`${e} must be an integer`);return d}async function st(d,e){let{action:n,sessionId:i}=e,t=e.payload??{};if(t.sessionId!==void 0&&t.sessionId!==i)throw new u("INVALID","Payload sessionId must match the routed sessionId");let o;switch(n){case"state.get":o=await d.getSessionState(i);break;case"goal.create":o=await d.createGoal({...t,sessionId:i});break;case"goal.update":o=await d.updateGoal(i,g(t.goalId,"goalId"),A(t.expectedVersion,"expectedVersion"),S(t.update,"update"));break;case"goal.complete":o=await d.completeGoal(i,g(t.goalId,"goalId"),A(t.expectedVersion,"expectedVersion"),S(t.verification,"verification"));break;case"goal.cancel":o=await d.cancelGoal(i,g(t.goalId,"goalId"),A(t.expectedVersion,"expectedVersion"),g(t.reason,"reason"));break;case"goal.steer":o=await d.steerGoal(i,g(t.goalId,"goalId"),A(t.expectedVersion,"expectedVersion"),g(t.instruction,"instruction"));break;case"loop.start":o=await d.startLoop({sessionId:i,kind:g(t.kind,"kind"),...typeof t.goalId=="string"?{goalId:t.goalId}:{},...typeof t.activity=="string"?{activity:t.activity}:{},...t.schedule?{schedule:S(t.schedule,"schedule")}:{}});break;case"loop.get":o=await d.getLoop(i,typeof t.loopId=="string"?t.loopId:void 0);break;case"loop.begin":o=await d.beginLoopIteration(i,g(t.loopId,"loopId"),A(t.expectedVersion,"expectedVersion"),g(t.activity,"activity"),typeof t.taskId=="string"?t.taskId:void 0);break;case"loop.finish":o=await d.finishLoopIteration(i,g(t.loopId,"loopId"),A(t.expectedVersion,"expectedVersion"),S(t.result,"result"));break;case"loop.set_status":o=await d.setLoopStatus(i,g(t.loopId,"loopId"),A(t.expectedVersion,"expectedVersion"),g(t.status,"status"),typeof t.reason=="string"?t.reason:void 0);break;case"ownership.acquire":o=await d.acquireOwnership(i,g(t.ownerId,"ownerId"),S(t.options??{},"options"));break;case"ownership.renew":o=await d.renewOwnership(i,g(t.ownerId,"ownerId"),g(t.leaseId,"leaseId"),typeof t.leaseMs=="number"?t.leaseMs:void 0);break;case"ownership.release":o=await d.releaseOwnership(i,g(t.ownerId,"ownerId"),g(t.leaseId,"leaseId"));break;case"handoff.create":o=await d.createHandoff({...t,sessionId:i});break;case"handoff.claim":o=await d.claimHandoff({sessionId:i,handoffId:g(t.handoffId,"handoffId"),targetOwnerId:g(t.targetOwnerId,"targetOwnerId"),...typeof t.processId=="number"?{processId:t.processId}:{},...typeof t.host=="string"?{host:t.host}:{}});break;case"handoff.complete":o=await d.completeHandoff(i,g(t.handoffId,"handoffId"),g(t.ownerId,"ownerId"),g(t.leaseId,"leaseId"));break;case"handoff.fail":o=await d.failHandoff(i,g(t.handoffId,"handoffId"),g(t.reason,"reason"));break;default:throw new u("INVALID","Unsupported coordination action")}let r=await d.getSessionState(i),s=n==="state.get"||n==="loop.get"?void 0:r.events.at(-1);return{action:n,sessionId:i,result:o,state:r,...s?{event:s}:{}}}import{randomUUID as ve}from"node:crypto";import{hostname as Ae}from"node:os";var te=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 _,this.sessionId=e.sessionId,this.processId=e.processId??process.pid,this.host=e.host??Ae(),this.ownerId=e.ownerId??`runtime:${this.host}:${this.processId}:${ve().slice(0,8)}`,this.leaseMs=e.leaseMs??3e4,this.heartbeatMs=e.heartbeatMs??Math.max(250,Math.floor(this.leaseMs/3)),this.heartbeatMs>=this.leaseMs)throw new Error("heartbeatMs must be shorter than leaseMs");if(this.claimHandoffId=e.claimHandoffId,this.claimRequestId=e.claimRequestId,this.onOwnershipLost=e.onOwnershipLost,this.prepareDestination=e.prepareDestination,this.destinationTimeoutMs=e.destinationTimeoutMs??Math.min(1e4,Math.floor(this.leaseMs/2)),!Number.isSafeInteger(this.destinationTimeoutMs)||this.destinationTimeoutMs<1||this.destinationTimeoutMs>=this.leaseMs)throw new Error("destinationTimeoutMs must be a positive integer shorter than leaseMs")}get currentOwner(){return this.active&&this.owner?structuredClone(this.owner):void 0}get active(){return this.ready&&!!this.owner&&!this.stopped&&this.lostError===void 0&&!this.preparingHandoff&&!this.preparedHandoffId}async start(){if(this.stopped)throw new Error("Execution lease session has already stopped");if(this.lostError!==void 0)throw this.lostError;return this.ready&&this.owner?(this.assertExecutionAllowed(),structuredClone(this.owner)):(this.starting??=this.initialize(),structuredClone(await this.starting))}async initialize(){try{if(this.claimHandoffId){let e=await this.store.claimHandoff({sessionId:this.sessionId,handoffId:this.claimHandoffId,targetOwnerId:this.ownerId,processId:this.processId,host:this.host,leaseMs:this.leaseMs,...this.claimRequestId?{claimRequestId:this.claimRequestId}:{}});if(this.owner=e.owner,this.stopped)throw new Error("Execution lease session has already stopped");if(this.prepareDestination&&await this.prepareClaimedDestination(e.handoff),this.stopped)throw new Error("Execution lease session has already stopped");await this.store.completeHandoff(this.sessionId,this.claimHandoffId,this.ownerId,this.owner.leaseId)}else this.owner=await this.store.acquireOwnership(this.sessionId,this.ownerId,{processId:this.processId,host:this.host,leaseMs:this.leaseMs});if(this.stopped)throw new Error("Execution lease session has already stopped");if(this.owner=await this.store.renewOwnership(this.sessionId,this.ownerId,this.owner.leaseId,this.leaseMs),this.stopped)throw new Error("Execution lease session has already stopped");return this.ready=!0,this.timer=setInterval(()=>{this.heartbeat()},this.heartbeatMs),this.timer.unref?.(),structuredClone(this.owner)}catch(e){throw this.ready=!1,this.markLost(e instanceof Error?e:new Error("Execution lease initialization failed",{cause:e})),this.lostError}}async prepareClaimedDestination(e){let n=this.initializationAbort.signal,i,t;try{let o=new Promise((r,s)=>{t=()=>s(n.reason??new Error("Destination preparation cancelled")),n.addEventListener("abort",t,{once:!0}),i=setTimeout(()=>this.initializationAbort.abort(new Error("Destination preparation timed out")),this.destinationTimeoutMs),n.aborted&&t()});await Promise.race([o,Promise.resolve().then(()=>(n.throwIfAborted(),this.prepareDestination({handoff:structuredClone(e),signal:n})))]),n.throwIfAborted()}finally{i&&clearTimeout(i),t&&n.removeEventListener("abort",t)}}async assertOwned(){this.assertExecutionAllowed();let e=await this.renewHeldLease();return this.assertExecutionAllowed(),e}assertExecutionAllowed(){if(this.stopped)throw new Error("Execution surface is detached");if(this.lostError)throw this.lostError;if(this.preparingHandoff)throw new Error("Execution surface is preparing a handoff and is detached from mutation");if(this.preparedHandoffId)throw new Error(`Execution surface prepared handoff ${this.preparedHandoffId} and is detached from mutation`);if(!this.ready||!this.owner)throw new Error("Execution ownership was not started")}async renewHeldLease(){if(!this.owner)throw new Error("Execution ownership was not started");try{let e=await this.renewOrRecover(this.owner.leaseId);if(this.stopped)throw new Error("Execution surface is detached");return this.owner=e,structuredClone(this.owner)}catch(e){throw this.markLost(e),e}}async renewOrRecover(e){try{return await this.store.renewOwnership(this.sessionId,this.ownerId,e,this.leaseMs)}catch(n){if(!(n instanceof Error&&"code"in n&&n.code==="LEASE_EXPIRED")||!this.store.recoverExpiredOwnership||this.preparingHandoff||this.preparedHandoffId||this.stopped)throw n;return this.store.recoverExpiredOwnership(this.sessionId,this.ownerId,e,this.processId,this.leaseMs)}}async prepareHandoff(e={}){if(this.preparedHandoffId)throw new Error(`Handoff ${this.preparedHandoffId} is already prepared`);this.assertExecutionAllowed(),this.preparingHandoff=!0;try{let n=await this.renewHeldLease();this.handoffOutcomeUncertain=!0;let i=await this.store.createHandoff({...e,sessionId:this.sessionId,sourceOwnerId:n.ownerId,sourceLeaseId:n.leaseId});return this.preparedHandoffId=i.id,this.handoffOutcomeUncertain=!1,i}catch(n){throw this.markLost(n instanceof Error?n:new Error("Handoff preparation failed",{cause:n})),n}finally{this.preparingHandoff=!1}}async cancelPreparedHandoff(){let e=this.preparedHandoffId;if(!e)throw new Error("No prepared handoff to cancel");if(!this.store.cancelHandoff)throw new Error("This execution store cannot cancel a prepared handoff");if(this.stopped)throw new Error("Execution surface is detached");if(this.lostError)throw this.lostError;if(!this.owner)throw new Error("Execution ownership was not started");let n=await this.store.cancelHandoff(this.sessionId,e,this.ownerId,this.owner.leaseId);if(n.id!==e||n.status!=="cancelled")throw new Error(`Handoff ${e} was not cancelled`);return this.preparedHandoffId=void 0,await this.renewHeldLease(),n}async stop(e={}){return this.stopping?this.stopping:(this.stopped=!0,this.ready=!1,this.initializationAbort.abort(new Error("Execution lease session has already stopped")),this.timer&&clearInterval(this.timer),this.timer=void 0,this.stopping=this.finishStop(e),this.stopping)}async finishStop(e){await this.starting?.catch(()=>{});let n=this.owner;if(this.owner=void 0,!(e.release===!1||this.preparedHandoffId||this.handoffOutcomeUncertain||!n))try{await this.store.releaseOwnership(this.sessionId,n.ownerId,n.leaseId)}catch{}}async heartbeat(){if(!(!this.ready||!this.owner||this.stopped||this.lostError!==void 0||this.heartbeatInFlight)){this.heartbeatInFlight=!0;try{await this.renewHeldLease()}catch(e){this.markLost(e)}finally{this.heartbeatInFlight=!1}}}markLost(e){this.lostError===void 0&&(this.lostError=e,this.timer&&clearInterval(this.timer),this.timer=void 0,this.onOwnershipLost?.(e))}};import{createHash as Oe}from"node:crypto";import{performance as H}from"node:perf_hooks";async function mt(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 i=H.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=Oe("sha256").update(JSON.stringify([t.sessionId,o.id,o.version,o.status,t.ownershipEpoch,t.owner?.ownerId??null,t.owner?.epoch??null])).digest("hex"),s=e.sinceRevision===void 0||r!==e.sinceRevision;if(s||H.now()>=i)return{sessionId:t.sessionId,handoffId:o.id,revision:r,changed:s,status:o.status,handoffVersion:o.version,ownershipEpoch:t.ownershipEpoch,sourceOwnerId:o.sourceOwnerId,...o.targetOwnerId?{targetOwnerId:o.targetOwnerId}:{}};await new Promise((a,c)=>{let l=e.signal,m=setTimeout(()=>{l?.removeEventListener("abort",E),a()},Math.min(100,Math.max(1,i-H.now()))),E=()=>{clearTimeout(m),l?.removeEventListener("abort",E),c(l?.reason??new Error("Handoff wait cancelled"))};l?.addEventListener("abort",E,{once:!0}),l?.aborted&&E()})}}import{randomUUID as Te}from"node:crypto";import{constants as ne}from"node:fs";import{lstat as D,mkdir as oe,open as U,realpath as B}from"node:fs/promises";import{dirname as F,isAbsolute as re,join as $,relative as xe,resolve as Re,sep as Xe}from"node:path";import{createHash as Se}from"node:crypto";function P(d){return{algorithm:"sha256",value:Se("sha256").update(d).digest("hex")}}var ie=1e4,se=8*1024*1024,ae=64*1024*1024;function de(d){if(typeof d!="string"||!d||d.length>2048||re(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 ce(d){return P(JSON.stringify([d.schemaVersion,d.sessionId,d.totalBytes,d.files.map(e=>[e.path,e.size,e.sha256,e.executable])])).value}function le(d,e){if(d.schemaVersion!==1||d.sessionId!==e||!Array.isArray(d.files)||d.files.length>ie||!Number.isSafeInteger(d.totalBytes)||d.totalBytes<0||d.totalBytes>ae)throw new Error("Invalid handoff snapshot manifest");let n=new Set,i=0;for(let t of d.files){if(de(t.path),!Number.isSafeInteger(t.size)||t.size<0||t.size>se||!/^[a-f0-9]{64}$/.test(t.sha256)||typeof t.executable!="boolean")throw new Error("Invalid handoff snapshot file");let o=t.path.toLowerCase();if(n.has(o))throw new Error("Snapshot paths collide on Windows");n.add(o),i+=t.size}for(let t of n){let o=t.split("/");for(let r=1;r<o.length;r++)if(n.has(o.slice(0,r).join("/")))throw new Error("Snapshot file conflicts with a directory")}if(i!==d.totalBytes||ce(d)!==d.digest)throw new Error("Handoff snapshot manifest integrity mismatch")}async function q(d,e){let n=d;for(let o of e.split("/"))if(n=$(n,o),(await D(n)).isSymbolicLink())throw new Error("Snapshot symlinks are not supported");let i=await B(n),t=xe(d,i);if(t===".."||t.startsWith(`..${Xe}`)||re(t))throw new Error("Snapshot path escaped its root");return n}async function Ot(d){if(!d.sessionId||d.sessionId.length>1024||d.paths.length>ie)throw new Error("Invalid snapshot scope");let e=await B(d.root),n=[],i=new Map,t=0;for(let r of[...d.paths].sort()){if(d.signal?.throwIfAborted(),de(r),!await d.authorizeFile(r))throw new Error("Snapshot file transfer is not authorized");let s=await q(e,r),a=await D(s),c=await U(s,ne.O_RDONLY|(ne.O_NOFOLLOW??0));try{let l=await c.stat();if(await q(e,r),a.ino!==l.ino||a.dev!==l.dev||a.ctimeMs!==l.ctimeMs)throw new Error("Snapshot source was replaced before reading");if(!l.isFile()||l.size>se||t+l.size>ae)throw new Error("Snapshot file or total byte limit exceeded");let f=Buffer.alloc(l.size),m=0;for(;m<f.length;){d.signal?.throwIfAborted();let{bytesRead:j}=await c.read(f,m,f.length-m,m);if(!j)throw new Error("Snapshot source changed while reading");m+=j}let E=await c.stat(),O=await D(s);if(await q(e,r),l.size!==E.size||l.mtimeMs!==E.mtimeMs||l.ctimeMs!==E.ctimeMs||O.isSymbolicLink()||O.ino!==l.ino||O.dev!==l.dev)throw new Error("Snapshot source changed while reading");let T=P(f).value;n.push({path:r,size:f.length,sha256:T,executable:(l.mode&73)!==0}),i.set(T,f),t+=f.length}finally{await c.close()}}let o={schemaVersion:1,sessionId:d.sessionId,files:n,totalBytes:t,digest:""};return o.digest=ce(o),le(o,d.sessionId),{manifest:o,blobs:i}}async function St(d){let e=structuredClone(d.manifest);if(le(e,d.sessionId),!await d.authorizeManifest(structuredClone(e)))throw new Error("Snapshot restoration is not authorized");d.signal?.throwIfAborted();let n=Re(d.destination);if(await B(F(n))!==F(n))throw new Error("Snapshot destination parent must be canonical");try{throw await D(n),new Error("Snapshot destination already exists")}catch(r){if(r.code!=="ENOENT")throw r}let t=`${n}.staging-${Te()}`;await oe(t,{mode:448});for(let r of e.files){d.signal?.throwIfAborted();let s=await d.readBlob(r.sha256,r.size);if(s.byteLength!==r.size||P(s).value!==r.sha256)throw new Error("Snapshot blob integrity mismatch; staging retained");let a=$(t,...r.path.split("/"));await oe(F(a),{recursive:!0,mode:448});let c=await U(a,"wx",r.executable?448:384);try{await c.writeFile(s),await c.sync()}finally{await c.close()}}d.signal?.throwIfAborted();let o=await U($(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}}import{createHash as Le}from"node:crypto";var Ne=/^sha256:[0-9a-f]{64}$/;function Rt(d){return typeof d=="string"&&Ne.test(d)}function Xt(d){return`sha256:${Le("sha256").update(d).digest("hex")}`}export{_ as DurableXenoCoordinationStore,Ne as XENO_CONTEXT_DIGEST_PATTERN,x as XENO_COORDINATION_BUDGET_SESSION_SCHEMA_VERSION,G as XENO_COORDINATION_MANAGED_SESSION_SCHEMA_VERSION,b as XENO_COORDINATION_SCHEMA_VERSION,R as XENO_COORDINATION_TURN_SESSION_SCHEMA_VERSION,u as XenoCoordinationError,te as XenoExecutionLeaseSession,Ot as captureXenoHandoffSnapshot,Xt as computeXenoContextDigest,st as executeXenoCoordinationAction,Rt as isXenoContextDigest,St as restoreXenoHandoffSnapshot,mt as waitForXenoHandoffStatus};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"inputs":{"src/coordination/types.ts":{"bytes":
|
|
1
|
+
{"inputs":{"src/coordination/types.ts":{"bytes":9780,"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/utils/acknowledgement.ts":{"bytes":1197,"imports":[],"format":"esm"},"src/observability/telemetry.ts":{"bytes":7271,"imports":[{"path":"node:perf_hooks","kind":"import-statement","external":true}],"format":"esm"},"src/observability/index.ts":{"bytes":32,"imports":[{"path":"src/observability/telemetry.ts","kind":"import-statement","original":"./telemetry.js"}],"format":"esm"},"src/utils/context-overflow-phrases.ts":{"bytes":2266,"imports":[],"format":"esm"},"src/providers/provider-errors.ts":{"bytes":8749,"imports":[{"path":"src/observability/index.ts","kind":"import-statement","original":"../observability/index.js"},{"path":"src/utils/context-overflow-phrases.ts","kind":"import-statement","original":"../utils/context-overflow-phrases.js"}],"format":"esm"},"src/providers/quota.ts":{"bytes":9783,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"src/utils/acknowledgement.ts","kind":"import-statement","original":"../utils/acknowledgement.js"},{"path":"src/providers/provider-errors.ts","kind":"import-statement","original":"./provider-errors.js"}],"format":"esm"},"src/coordination/store.ts":{"bytes":88086,"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/providers/quota.ts","kind":"import-statement","original":"../providers/quota.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":14575,"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/context-digest.ts":{"bytes":1319,"imports":[{"path":"node:crypto","kind":"import-statement","external":true}],"format":"esm"},"src/coordination/index.ts":{"bytes":227,"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"},{"path":"src/coordination/context-digest.ts","kind":"import-statement","original":"./context-digest.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},{"path":"node:crypto","kind":"require-call","external":true}],"exports":[],"entryPoint":"src/coordination/index.ts","inputs":{"src/coordination/index.ts":{"bytesInOutput":567},"src/coordination/types.ts":{"bytesInOutput":148},"src/coordination/store.ts":{"bytesInOutput":42171},"src/utils/platform.ts":{"bytesInOutput":240},"src/observability/index.ts":{"bytesInOutput":0},"src/providers/quota.ts":{"bytesInOutput":570},"src/coordination/runtime.ts":{"bytesInOutput":3142},"src/coordination/lease.ts":{"bytesInOutput":7089},"src/coordination/handoff-status.ts":{"bytesInOutput":1502},"src/coordination/handoff-snapshot.ts":{"bytesInOutput":4716},"src/artifacts/hash.ts":{"bytesInOutput":129},"src/coordination/context-digest.ts":{"bytesInOutput":195}},"bytes":61509}}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"inputs":{"src/coordination/types.ts":{"bytes":
|
|
1
|
+
{"inputs":{"src/coordination/types.ts":{"bytes":9780,"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/utils/acknowledgement.ts":{"bytes":1197,"imports":[],"format":"esm"},"src/observability/telemetry.ts":{"bytes":7271,"imports":[{"path":"node:perf_hooks","kind":"import-statement","external":true}],"format":"esm"},"src/observability/index.ts":{"bytes":32,"imports":[{"path":"src/observability/telemetry.ts","kind":"import-statement","original":"./telemetry.js"}],"format":"esm"},"src/utils/context-overflow-phrases.ts":{"bytes":2266,"imports":[],"format":"esm"},"src/providers/provider-errors.ts":{"bytes":8749,"imports":[{"path":"src/observability/index.ts","kind":"import-statement","original":"../observability/index.js"},{"path":"src/utils/context-overflow-phrases.ts","kind":"import-statement","original":"../utils/context-overflow-phrases.js"}],"format":"esm"},"src/providers/quota.ts":{"bytes":9783,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"src/utils/acknowledgement.ts","kind":"import-statement","original":"../utils/acknowledgement.js"},{"path":"src/providers/provider-errors.ts","kind":"import-statement","original":"./provider-errors.js"}],"format":"esm"},"src/coordination/store.ts":{"bytes":88086,"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/providers/quota.ts","kind":"import-statement","original":"../providers/quota.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":14575,"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/context-digest.ts":{"bytes":1319,"imports":[{"path":"node:crypto","kind":"import-statement","external":true}],"format":"esm"},"src/coordination/index.ts":{"bytes":227,"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"},{"path":"src/coordination/context-digest.ts","kind":"import-statement","original":"./context-digest.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},{"path":"node:crypto","kind":"import-statement","external":true}],"exports":["DurableXenoCoordinationStore","XENO_CONTEXT_DIGEST_PATTERN","XENO_COORDINATION_BUDGET_SESSION_SCHEMA_VERSION","XENO_COORDINATION_MANAGED_SESSION_SCHEMA_VERSION","XENO_COORDINATION_SCHEMA_VERSION","XENO_COORDINATION_TURN_SESSION_SCHEMA_VERSION","XenoCoordinationError","XenoExecutionLeaseSession","captureXenoHandoffSnapshot","computeXenoContextDigest","executeXenoCoordinationAction","isXenoContextDigest","restoreXenoHandoffSnapshot","waitForXenoHandoffStatus"],"entryPoint":"src/coordination/index.ts","inputs":{"src/coordination/types.ts":{"bytesInOutput":148},"src/coordination/index.ts":{"bytesInOutput":0},"src/coordination/store.ts":{"bytesInOutput":42121},"src/utils/platform.ts":{"bytesInOutput":220},"src/observability/index.ts":{"bytesInOutput":0},"src/providers/quota.ts":{"bytesInOutput":570},"src/coordination/runtime.ts":{"bytesInOutput":3142},"src/coordination/lease.ts":{"bytesInOutput":7088},"src/coordination/handoff-status.ts":{"bytesInOutput":1480},"src/coordination/handoff-snapshot.ts":{"bytesInOutput":4608},"src/artifacts/hash.ts":{"bytesInOutput":126},"src/coordination/context-digest.ts":{"bytesInOutput":196}},"bytes":60221}}}
|