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