@xenosystem/agent-sdk 0.10.35 → 0.10.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/README.md +1 -1
  2. package/dist/agents/index.cjs +9 -9
  3. package/dist/agents/index.d.cts +4 -1
  4. package/dist/agents/index.d.ts +4 -1
  5. package/dist/agents/index.js +16 -16
  6. package/dist/agents/metafile-cjs.json +1 -1
  7. package/dist/agents/metafile-esm.json +1 -1
  8. package/dist/artifacts/index.cjs +1 -1
  9. package/dist/artifacts/index.js +1 -1
  10. package/dist/artifacts/metafile-cjs.json +1 -1
  11. package/dist/artifacts/metafile-esm.json +1 -1
  12. package/dist/automation/index.cjs +35 -24
  13. package/dist/automation/index.d.cts +194 -12
  14. package/dist/automation/index.d.ts +194 -12
  15. package/dist/automation/index.js +35 -24
  16. package/dist/automation/metafile-cjs.json +1 -1
  17. package/dist/automation/metafile-esm.json +1 -1
  18. package/dist/control-plane/index.cjs +8 -8
  19. package/dist/control-plane/index.js +8 -8
  20. package/dist/control-plane/metafile-cjs.json +1 -1
  21. package/dist/control-plane/metafile-esm.json +1 -1
  22. package/dist/coordination/index.cjs +2 -2
  23. package/dist/coordination/index.js +2 -2
  24. package/dist/coordination/metafile-cjs.json +1 -1
  25. package/dist/coordination/metafile-esm.json +1 -1
  26. package/dist/electron/index.cjs +243 -223
  27. package/dist/electron/index.d.cts +198 -1
  28. package/dist/electron/index.d.ts +198 -1
  29. package/dist/electron/index.js +243 -223
  30. package/dist/electron/metafile-cjs.json +1 -1
  31. package/dist/electron/metafile-esm.json +1 -1
  32. package/dist/hosted/metafile-cjs.json +1 -1
  33. package/dist/hosted/metafile-esm.json +1 -1
  34. package/dist/index.cjs +406 -395
  35. package/dist/index.d.cts +325 -172
  36. package/dist/index.d.ts +325 -172
  37. package/dist/index.js +406 -395
  38. package/dist/intelligence/index.cjs +4 -4
  39. package/dist/intelligence/index.js +4 -4
  40. package/dist/intelligence/metafile-cjs.json +1 -1
  41. package/dist/intelligence/metafile-esm.json +1 -1
  42. package/dist/mcp/index.cjs +20 -20
  43. package/dist/mcp/index.d.cts +146 -0
  44. package/dist/mcp/index.d.ts +146 -0
  45. package/dist/mcp/index.js +17 -17
  46. package/dist/mcp/metafile-cjs.json +1 -1
  47. package/dist/mcp/metafile-esm.json +1 -1
  48. package/dist/metafile-cjs.json +1 -1
  49. package/dist/metafile-esm.json +1 -1
  50. package/dist/providers/index.cjs +10 -10
  51. package/dist/providers/index.d.cts +49 -5
  52. package/dist/providers/index.d.ts +49 -5
  53. package/dist/providers/index.js +10 -10
  54. package/dist/providers/metafile-cjs.json +1 -1
  55. package/dist/providers/metafile-esm.json +1 -1
  56. package/dist/recipes/metafile-cjs.json +1 -1
  57. package/dist/recipes/metafile-esm.json +1 -1
  58. package/dist/research/metafile-cjs.json +1 -1
  59. package/dist/research/metafile-esm.json +1 -1
  60. package/dist/session/index.cjs +24 -24
  61. package/dist/session/index.js +16 -16
  62. package/dist/session/metafile-cjs.json +1 -1
  63. package/dist/session/metafile-esm.json +1 -1
  64. package/dist/sharing/index.cjs +1 -1
  65. package/dist/sharing/index.js +3 -3
  66. package/dist/sharing/metafile-cjs.json +1 -1
  67. package/dist/sharing/metafile-esm.json +1 -1
  68. package/dist/skills/index.d.cts +6 -0
  69. package/dist/skills/index.d.ts +6 -0
  70. package/dist/utils/index.cjs +24 -24
  71. package/dist/utils/index.d.cts +14 -2
  72. package/dist/utils/index.d.ts +14 -2
  73. package/dist/utils/index.js +24 -24
  74. package/dist/utils/metafile-cjs.json +1 -1
  75. package/dist/utils/metafile-esm.json +1 -1
  76. package/ownership/evidence/PROPRIETARY-PTY-1/implementation-record.md +1 -1
  77. package/ownership/ownership-policy.json +14 -3
  78. package/package.json +1 -1
@@ -1,2 +1,2 @@
1
- "use strict";var we=Object.create;var L=Object.defineProperty;var Ie=Object.getOwnPropertyDescriptor;var Ee=Object.getOwnPropertyNames;var ye=Object.getPrototypeOf,ve=Object.prototype.hasOwnProperty;var be=(d,e)=>{for(var n in e)L(d,n,{get:e[n],enumerable:!0})},K=(d,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of Ee(e))!ve.call(d,t)&&t!==n&&L(d,t,{get:()=>e[t],enumerable:!(i=Ie(e,t))||i.enumerable});return d};var F=(d,e,n)=>(n=d!=null?we(ye(d)):{},K(e||!d||!d.__esModule?L(n,"default",{value:d,enumerable:!0}):n,d)),Ae=d=>K(L({},"__esModule",{value:!0}),d);var Me={};be(Me,{DurableXenoCoordinationStore:()=>C,XENO_CONTEXT_DIGEST_PATTERN:()=>me,XENO_COORDINATION_BUDGET_SESSION_SCHEMA_VERSION:()=>X,XENO_COORDINATION_MANAGED_SESSION_SCHEMA_VERSION:()=>$,XENO_COORDINATION_SCHEMA_VERSION:()=>A,XENO_COORDINATION_TURN_SESSION_SCHEMA_VERSION:()=>P,XenoCoordinationError:()=>l,XenoExecutionLeaseSession:()=>j,captureXenoHandoffSnapshot:()=>Xe,computeXenoContextDigest:()=>Ge,executeXenoCoordinationAction:()=>_e,isXenoContextDigest:()=>De,restoreXenoHandoffSnapshot:()=>Pe,waitForXenoHandoffStatus:()=>Le});module.exports=Ae(Me);var A=1,$=2,X=3,P=4,l=class extends Error{constructor(n,i,t={}){super(i);this.code=n;this.details=t;this.name="XenoCoordinationError"}code;details};var x=require("node:crypto"),h=F(require("node:fs/promises"),1),O=F(require("node:os"),1),y=F(require("node:path"),1);var S=require("node:os");var U=require("node:path"),qe=(0,S.platform)();var Fe=(0,S.release)(),$e=(0,S.homedir)();function Y(){let d=process.env.XENO_AGENT_HOME?.trim();return d?(0,U.resolve)(d):(0,U.resolve)((0,S.homedir)(),".xeno-agent")}var T="[redacted]";var We=[[/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g,"[redacted:private-key]"],[/((?:^|[\s{,;"'(\[])["']?(?:cookie|set-cookie)["']?\s*[:=]\s*["']?)(?!\[redacted)[^\s"',;]+(?:;\s*[^\s"',;=]+=[^\s"',;]*)*/gi,`$1${T}`],[/((?:^|[\s{,;"'(\[])["']?(?:authorization|proxy-authorization|x-api-key|x-goog-api-key|x-xeno-api-key|api[-_]?key|apikey|dpop)["']?\s*[:=]\s*["']?)(?:(?:Bearer|Basic|Token|DPoP)\s+)?(?!\[redacted)[^\s"',;]+/gi,`$1${T}`],[/\b(Bearer|Basic|Token|DPoP)\s+[A-Za-z0-9._~+/=-]{6,}/gi,`$1 ${T}`],[/\b(?:sk-(?:ant-|proj-)?[A-Za-z0-9_-]{16,}|xeno-[A-Za-z0-9]{24,}|xrun_[A-Za-z0-9_-]{8,}|AIza[0-9A-Za-z_-]{30,}|gh[pousr]_[A-Za-z0-9_]{20,}|github_pat_[A-Za-z0-9_]{20,}|npm_[A-Za-z0-9]{30,}|xox[baprs]-[A-Za-z0-9-]{16,}|AKIA[0-9A-Z]{16})\b/g,T],[/\beyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}/g,T],[/([?&#;](?:access_token|refresh_token|id_token|token|key|api[_-]?key|secret|client_secret|password|signature|sig)=)[^&#\s"'<>]+/gi,`$1${T}`],[/(\b[a-z][a-z0-9+.-]*:\/\/)[^/\s:@"']+:[^/\s@"']+@/gi,`$1${T}@`]];var D=class extends Error{constructor(n,i){super(i);this.code=n;this.name="QuotaError"}code;retryable=!1};function Z(d){if(typeof d!="string"||!d.trim()||d.length>512)throw new D("INVALID","Invalid quota identity.");return d}function B(d){let e=n=>({id:Z(n?.id),generation:Z(n?.generation)});if(!d||d.agent&&!d.team)throw new D("INVALID","A child quota scope requires its complete ancestry.");return{workspace:e(d.workspace),...d.team?{team:e(d.team)}:{},...d.agent?{agent:e(d.agent)}:{},...d.goal!==void 0?{goal:e(d.goal)}:{}}}function z(d){return JSON.stringify(B(d))}var Oe=3e4,Se=3e4,Te=6e4,xe=2e4,G=new Set(["EACCES","EBUSY","EPERM"]),ee=[5,10,20,40,80,160,320],Re=[5,10,20,40,80,160,320],te=[1,2,3,4];function p(d,e,n=16384){let i=d.trim();if(!i||i.length>n)throw new l("INVALID",`${e} must be non-empty and no longer than ${n} characters`);return i}function M(d,e){return[...new Set((d??[]).map(n=>p(n,e)))]}function ne(d){if(d===void 0)return;if(!d||typeof d!="object"||Array.isArray(d))throw new l("INVALID","Goal limits must be an object when provided");let e={};for(let[n,i]of Object.entries(d)){if(n!=="maxIterations"&&n!=="maxTokens"&&n!=="maxWallClockMs")throw new l("INVALID","Unknown goal limit");if(i!==void 0){if(!Number.isSafeInteger(i)||i<=0)throw new l("INVALID",`${n} must be a positive safe integer when provided`);e[n]=i}}return e}function ke(d){if(d){if(d.kind!=="fixed-interval"&&d.kind!=="dynamic")throw new l("INVALID","schedule.kind must be fixed-interval or dynamic");if(d.kind==="fixed-interval"&&(!Number.isSafeInteger(d.intervalMs)||(d.intervalMs??0)<=0))throw new l("INVALID","Fixed-interval schedules require a positive safe intervalMs");if(d.intervalMs!==void 0&&(!Number.isSafeInteger(d.intervalMs)||d.intervalMs<=0))throw new l("INVALID","schedule.intervalMs must be a positive safe integer when provided");for(let e of["nextRunAt","expiresAt"]){let n=d[e];if(n!==void 0&&!Number.isFinite(Date.parse(n)))throw new l("INVALID",`schedule.${e} must be an ISO timestamp when provided`)}return w(d)}}function w(d){return structuredClone(d)}function b(d){let e=Date.parse(d);return Number.isFinite(e)?e:0}function V(d){if(!Number.isInteger(d)||d<=0)return!1;try{return process.kill(d,0),!0}catch(e){return e.code==="EPERM"}}function Ce(d){return{summary:"Goal created; work has not started.",completedTaskCount:0,totalTaskCount:0,outstanding:[],decisions:[],updatedAt:d}}function Ne(){return{status:"pending",criteria:[],evidence:[]}}function oe(d){return(0,x.createHash)("sha256").update(d).digest("hex")}var C=class{get goalTurnAdmissionVersion(){return 1}rootDirectory;now;idFactory;ownerLeaseMs;lockTimeoutMs;lockStaleMs;maximumEventsPerSession;constructor(e={}){this.rootDirectory=e.rootDirectory??y.join(Y(),"coordination"),this.now=e.now??(()=>new Date().toISOString()),this.idFactory=e.idFactory??(n=>`${n}_${(0,x.randomUUID)()}`),this.ownerLeaseMs=e.ownerLeaseMs??Oe,this.lockTimeoutMs=e.lockTimeoutMs??Se,this.lockStaleMs=e.lockStaleMs??Te,this.maximumEventsPerSession=e.maximumEventsPerSession??xe}async getSessionState(e){let n=p(e,"sessionId",1024);return w(await this.readState(n))}async fenceAdmission(e,n,i){let t=p(i.authorityId,"authorityId",512),o=p(i.operationId,"operationId",512);if(!Number.isSafeInteger(n)||n<0)throw new l("INVALID","Expected session version must be a nonnegative safe integer");if(i.action!=="archive"&&i.action!=="delete")throw new l("INVALID","Unsupported admission fence action");return this.mutate(e,r=>{let s=r.admissionFence;if(s?.authorityId===t&&s.operationId===o&&s.action===i.action)return s;if(r.version!==n)throw new l("CONFLICT","Session version changed before lifecycle fencing",{expected:n,actual:r.version});if(s?.authorityId===t&&s.action==="archive"&&i.action==="archive")return s;if(s&&!(s.authorityId===t&&s.action==="archive"&&i.action==="delete"))throw new l("CONFLICT","Another lifecycle fence already owns this session");let a={schemaVersion:1,authorityId:t,operationId:o,action:i.action,createdAt:this.now()};return r.admissionFence=a,r.schemaVersion===1&&(r.schemaVersion=2),this.appendEvent(r,"admission.fenced",{data:{authorityId:t,operationId:o,action:i.action}}),a},!0)}async clearAdmissionFence(e,n,i,t){await this.mutate(e,o=>{this.assertVersion(e,o.version,n);let r=o.admissionFence;if(!r||r.authorityId!==i||r.operationId!==t)throw new l("CONFLICT","Lifecycle fence identity does not match");if(r.action==="delete")throw new l("CONFLICT","Deleted session admission cannot be restored");if(o.owner)throw new l("CONFLICT","Execution ownership must settle before restoration");o.admissionFence=void 0,this.appendEvent(o,"admission.restored",{data:{authorityId:i,operationId:t}})},!0)}async releaseDeadLifecycleOwner(e,n,i,t){await this.mutate(e,o=>{this.assertVersion(e,o.version,n);let r=o.admissionFence;if(!r||r.authorityId!==i||r.operationId!==t)throw new l("CONFLICT","Lifecycle fence identity does not match");let s=o.owner;if(s){if(s.host!==O.hostname()||!Number.isInteger(s.processId)||(s.processId??0)<=0||V(s.processId))throw new l("CONFLICT","Execution owner exit has not been proved");o.owner=void 0,this.appendEvent(o,"ownership.released",{ownerId:s.ownerId,data:{epoch:s.epoch,reason:"fenced-local-owner-exited"}})}},!0)}async listSessionStates(){let e=y.join(this.rootDirectory,"sessions"),n;try{n=await h.readdir(e)}catch(t){if(t.code==="ENOENT")return[];throw t}return(await Promise.all(n.filter(t=>t.endsWith(".json")).map(async t=>{try{let o=JSON.parse(await h.readFile(y.join(e,t),"utf8"));return!te.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)=>b(o.updatedAt)-b(t.updatedAt)).map(t=>w(t))}async createGoal(e){let n=p(e.sessionId,"sessionId",1024),i=ne(e.limits);return this.mutate(n,t=>{let o=t.goals.find(c=>["active","paused","waiting","blocked"].includes(c.status));if(o)throw new l("CONFLICT",`Session ${n} already has active goal ${o.id}`);let r=this.now(),s=(e.successCriteria??[]).map(c=>typeof c=="string"?{id:this.idFactory("criterion"),description:p(c,"successCriteria"),required:!0}:{id:c.id?p(c.id,"successCriteria.id",512):this.idFactory("criterion"),description:p(c.description,"successCriteria.description"),required:c.required}),a={schemaVersion:1,id:this.idFactory("goal"),version:1,sessionId:n,objective:p(e.objective,"objective"),...e.why?{why:p(e.why,"why")}:{},successCriteria:s,constraints:M(e.constraints,"constraints"),...i?{limits:i}:{},metadata:w(e.metadata??{}),status:"active",milestones:[],tasks:[],progress:Ce(r),verification:Ne(),steering:[],createdAt:r,updatedAt:r};return t.goals.push(a),this.appendEvent(t,"goal.created",{goalId:a.id,data:{objective:a.objective}}),a})}async getGoal(e,n){let i=await this.getSessionState(e),t=n?i.goals.find(o=>o.id===n):[...i.goals].reverse().find(o=>["active","paused","waiting","blocked"].includes(o.status));return t?w(t):void 0}async updateGoal(e,n,i,t){return this.mutate(e,o=>{let r=this.requireGoal(o,n);if(this.assertVersion(r.id,r.version,i),["completed","cancelled","failed"].includes(r.status))throw new l("CONFLICT",`Goal ${r.id} is terminal (${r.status})`);let s=r.status!=="active";if(t.status==="active"&&r.status==="blocked"?r.status="active":t.status&&(r.status=t.status),t.objective!==void 0&&(r.objective=p(t.objective,"objective")),t.why!==void 0&&(r.why=p(t.why,"why")),t.constraints&&(r.constraints=M(t.constraints,"constraints")),t.successCriteria&&(r.successCriteria=w(t.successCriteria)),t.progress&&(r.progress={...r.progress,...w(t.progress),outstanding:M(t.progress.outstanding??r.progress.outstanding,"progress.outstanding"),decisions:M(t.progress.decisions??r.progress.decisions,"progress.decisions"),updatedAt:this.now()}),t.verification&&(r.verification=w(t.verification)),t.metadata&&(r.metadata=w(t.metadata)),s&&r.status==="active")for(let a of o.loops.filter(c=>c.goalId===n&&c.kind==="goal-continuation"&&c.status==="running"))a.resumeRequested=!0,a.version+=1,a.updatedAt=this.now();return r.version+=1,r.updatedAt=this.now(),this.appendEvent(o,"goal.updated",{goalId:r.id,data:{status:r.status,version:r.version}}),r},t.status!==void 0&&["paused","cancelled","failed"].includes(t.status))}async addMilestone(e,n,i,t){return this.mutateGoal(e,n,i,(o,r)=>{let s={id:this.idFactory("milestone"),title:p(t.title,"milestone.title"),...t.description?{description:p(t.description,"milestone.description")}:{},status:o.milestones.some(a=>a.status==="active")?"pending":"active",taskIds:[],createdAt:r,updatedAt:r};o.milestones.push(s),o.progress.currentMilestoneId??=s.id,o.progress.updatedAt=r})}async addTask(e,n,i,t){return this.mutateGoal(e,n,i,(o,r)=>{let s=o.milestones.find(u=>u.id===t.milestoneId);if(!s)throw new l("NOT_FOUND",`Milestone ${t.milestoneId} was not found`);if(t.parentTaskId&&!o.tasks.some(u=>u.id===t.parentTaskId))throw new l("NOT_FOUND",`Parent task ${t.parentTaskId} was not found`);let a=[...new Set(t.dependsOn??[])];for(let u of a)if(!o.tasks.some(f=>f.id===u))throw new l("NOT_FOUND",`Task dependency ${u} was not found`);let c={id:this.idFactory("task"),milestoneId:s.id,...t.parentTaskId?{parentTaskId:t.parentTaskId}:{},title:p(t.title,"task.title"),...t.description?{description:p(t.description,"task.description")}:{},status:a.length===0?"ready":"pending",...t.assignedAgentId?{assignedAgentId:p(t.assignedAgentId,"task.assignedAgentId",512)}:{},...a.length?{dependsOn:a}:{},createdAt:r,updatedAt:r};o.tasks.push(c),s.taskIds.push(c.id),s.updatedAt=r,o.progress.totalTaskCount=o.tasks.length,o.progress.outstanding=o.tasks.filter(u=>u.status!=="completed").map(u=>u.title),o.progress.updatedAt=r})}async updateTask(e,n,i,t,o){return this.mutateGoal(e,n,t,(r,s)=>{let a=r.tasks.find(u=>u.id===i);if(!a)throw new l("NOT_FOUND",`Task ${i} was not found`);a.status=o.status,o.progress!==void 0&&(a.progress=p(o.progress,"task.progress")),o.resultEventId!==void 0&&(a.resultEventId=p(o.resultEventId,"task.resultEventId",512)),o.assignedAgentId!==void 0&&(a.assignedAgentId=p(o.assignedAgentId,"task.assignedAgentId",512)),a.updatedAt=s,a.status==="completed"&&(a.completedAt=s);let c=r.milestones.find(u=>u.id===a.milestoneId);if(c){let u=r.tasks.filter(f=>f.milestoneId===c.id);u.length>0&&u.every(f=>f.status==="completed")?(c.status="completed",c.completedAt=s):u.some(f=>f.status==="running")?c.status="active":u.some(f=>f.status==="blocked")&&(c.status="blocked"),c.updatedAt=s}for(let u of r.tasks)u.status!=="pending"||!u.dependsOn?.length||u.dependsOn.every(f=>r.tasks.find(g=>g.id===f)?.status==="completed")&&(u.status="ready",u.updatedAt=s);this.recalculateProgress(r,s)})}async steerGoal(e,n,i,t){return this.mutateGoal(e,n,i,(o,r,s)=>{let a=this.idFactory("steer");o.steering.push({id:a,instruction:p(t,"instruction"),createdAt:r}),this.appendEvent(s,"goal.steered",{goalId:n,data:{steeringId:a}})},!1)}async consumeGoalSteering(e,n,i){let t=[];return{goal:await this.mutateGoal(e,n,i,(r,s)=>{t=r.steering.filter(a=>!a.consumedAt).map(({id:a,instruction:c,createdAt:u})=>({id:a,instruction:c,createdAt:u}));for(let a of r.steering)a.consumedAt||(a.consumedAt=s)}),instructions:t}}async completeGoal(e,n,i,t){if(t.status!=="passed")throw new l("VERIFICATION_REQUIRED","Goal completion requires passed verification");return this.mutate(e,o=>{let r=this.requireGoal(o,n);this.assertVersion(r.id,r.version,i);let s=r.successCriteria.filter(u=>u.required),a=s.filter(u=>{let f=t.criteria.find(g=>g.criterionId===u.id);return!f?.satisfied||f.evidence.length===0});if(a.length>0)throw new l("VERIFICATION_REQUIRED","Required success criteria lack passing evidence",{unmetCriteria:a.map(u=>u.id)});if(s.length===0&&t.evidence.length===0)throw new l("VERIFICATION_REQUIRED","Goal completion requires at least one durable evidence reference");let c=this.now();return r.status="completed",r.verification=w(t),r.verification.verifiedAt??=c,r.completedAt=c,r.updatedAt=c,r.version+=1,this.appendEvent(o,"goal.completed",{goalId:n,data:{evidence:r.verification.evidence}}),r},!0)}async cancelGoal(e,n,i,t){return this.mutate(e,o=>{let r=this.requireGoal(o,n);if(this.assertVersion(r.id,r.version,i),["completed","cancelled","failed"].includes(r.status))return r;r.status="cancelled",r.updatedAt=this.now(),r.version+=1,this.appendEvent(o,"goal.cancelled",{goalId:n,data:{reason:p(t,"reason")}});for(let s of o.loops.filter(a=>a.goalId===n&&["running","paused","waiting"].includes(a.status)))s.status="stopped",s.resumeRequested!==void 0&&(s.resumeRequested=!1),s.stopReason=`Goal cancelled: ${t}`,s.stoppedAt=this.now(),s.updatedAt=s.stoppedAt,s.version+=1;return r},!0)}async startLoop(e){return this.mutate(e.sessionId,n=>this.createLoopRecord(n,e))}createLoopRecord(e,n){if(n.kind==="goal-continuation"&&!n.goalId)throw new l("INVALID","Goal-continuation loops require a goalId");if(n.goalId){let s=this.requireGoal(e,n.goalId);if(["completed","cancelled","failed"].includes(s.status))throw new l("CONFLICT",`Cannot start a loop for terminal goal ${s.id}`)}if(n.kind==="scheduled"&&!n.schedule)throw new l("INVALID","Scheduled loops require schedule metadata");if(n.kind!=="scheduled"&&n.schedule)throw new l("INVALID","Only scheduled loops may carry schedule metadata");let i=ke(n.schedule),t=e.loops.find(s=>s.goalId===n.goalId&&s.kind===n.kind&&["running","paused","waiting"].includes(s.status));if(t)throw new l("CONFLICT",`Loop ${t.id} is already active`);let o=this.now(),r={schemaVersion:1,id:this.idFactory("loop"),version:1,sessionId:e.sessionId,...n.goalId?{goalId:n.goalId}:{},kind:n.kind,status:"running",...n.activity?{currentActivity:p(n.activity,"activity")}:{},iterations:[],...i?{schedule:i}:{},createdAt:o,updatedAt:o};return e.loops.push(r),this.appendEvent(e,"loop.started",{loopId:r.id,goalId:r.goalId,data:{kind:r.kind}}),r}async getLoop(e,n){let i=await this.getSessionState(e),t=n?i.loops.find(o=>o.id===n):[...i.loops].reverse().find(o=>["running","paused","waiting"].includes(o.status));return t?w(t):void 0}async beginLoopIteration(e,n,i,t,o){return this.mutateLoop(e,n,i,(r,s,a)=>{this.appendLoopIteration(a,r,s,t,o)},!1)}appendLoopIteration(e,n,i,t,o,r=!1){if(n.status!=="running")throw new l("CONFLICT",`Loop ${n.id} is ${n.status}`);if(n.goalId){let c=this.requireGoal(e,n.goalId);this.isCliGoal(c)&&this.initializeGoalTurnAccounting(e,c)}if(this.assertGoalIterationAdmission(e,n,i,r),n.iterations.some(c=>c.status==="running"))throw new l("CONFLICT",`Loop ${n.id} already has a running iteration`);let s=(n.iterations.at(-1)?.number??0)+1;n.currentActivity=p(t,"activity");let a={number:s,startedAt:i,status:"running",activity:n.currentActivity,...n.goalId&&e.goalTurnAccounting?.[n.goalId]?{goalAccountingVersion:1}:{},...o?{taskId:p(o,"taskId",512)}:{}};return n.iterations.push(a),n.resumeRequested!==void 0&&(n.resumeRequested=!1),this.appendEvent(e,"loop.iteration",{loopId:n.id,goalId:n.goalId,data:{number:s,phase:"started",activity:n.currentActivity}}),a}async admitGoalTurn(e){return this.admitGoalTurnWithOwner(e)}async admitQuotaGoalTurn(e,n,i,t){let o=B(i),r=await this.getGoal(e.sessionId,e.goalId);if(!r||r.sessionId!==e.sessionId||r.limits?.maxTokens===void 0)throw new l("BUDGET_UNAVAILABLE","The exact token-bounded goal is unavailable for quota admission");if(this.isCliGoal(r)&&r.metadata["cli.tokenQuotaVersion"]!==1)throw new l("BUDGET_UNAVAILABLE","Legacy CLI goal token spend is unknown; quota admission requires creation-time provenance");if(o.goal?.id!==r.id||o.goal.generation!==r.createdAt)throw new l("BUDGET_UNAVAILABLE","Quota scope does not identify this durable goal generation");let s=await n.policy(o);if(!s||z(s.scope)!==z(o)||s.limits.tokensLifetime===void 0||s.limits.tokensLifetime===null||s.limits.tokensLifetime>r.limits.maxTokens)throw new l("BUDGET_UNAVAILABLE","Goal quota policy is absent or wider than the goal's explicit token limit");let a=await n.remainingTokens(o);if(a===null)throw new l("BUDGET_UNAVAILABLE","Goal token accounting has no durable remaining allowance");if(a<1)throw new l("BUDGET_EXCEEDED","Goal token allowance is exhausted");return this.admitGoalTurnWithOwner(e,t,{goalId:r.id,createdAt:r.createdAt,maximum:r.limits.maxTokens})}async admitOwnedGoalTurn(e,n){if(!n||!Number.isSafeInteger(n.epoch)||n.epoch<1)throw new l("INVALID","An exact execution ownership epoch is required");return this.admitGoalTurnWithOwner(e,{...n})}async admitGoalTurnWithOwner(e,n,i){let t=p(e.requestId,"requestId",512),o=this.goalTurnHash(e.requestHash);return this.mutate(e.sessionId,r=>{if(n){let f=this.requireOwner(r,n.ownerId,n.leaseId);if(f.epoch!==n.epoch)throw new l("NOT_OWNER","Execution ownership epoch changed");if(this.ownerExpired(f,this.now()))throw new l("LEASE_EXPIRED","Execution ownership expired");if(r.handoffs.some(g=>["prepared","available"].includes(g.status)&&g.sourceLeaseEpoch===f.epoch)||r.handoffs.some(g=>g.status==="claimed"&&g.targetLeaseEpoch===f.epoch))throw new l("UNSAFE_HANDOFF","Execution handoff has not settled")}let s=this.requireGoal(r,e.goalId);if(i&&(s.id!==i.goalId||s.createdAt!==i.createdAt||s.limits?.maxTokens!==i.maximum))throw new l("BUDGET_UNAVAILABLE","Goal token limit changed after quota verification");for(let f of r.loops.filter(g=>g.goalId===s.id)){let g=f.iterations.find(v=>v.goalTurn?.requestId===t);if(g){if(g.goalTurn?.requestHash!==o)throw new l("CONFLICT","Goal turn identity was reused for different work");return{...this.goalTurnState(r,s,f,g),admitted:!1}}}if(this.assertVersion(s.id,s.version,e.expectedGoalVersion),s.status!=="active")throw new l("CONFLICT",`Goal ${s.id} is ${s.status}`);let a=[...r.loops].reverse().find(f=>f.goalId===s.id&&f.kind==="goal-continuation");if(e.expectedLoopId!==void 0){if(!a||a.id!==e.expectedLoopId)throw new l("CONFLICT","Goal continuation loop changed before admission");this.assertVersion(a.id,a.version,e.expectedLoopVersion??-1)}else if(e.expectedLoopVersion!==void 0)throw new l("INVALID","A goal turn loop version requires its exact loop ID");if(a&&a.status!=="running")throw new l("CONFLICT",`Goal loop ${a.id} is ${a.status}; resume or start it explicitly`);this.initializeGoalTurnAccounting(r,s),a??=this.createLoopRecord(r,{sessionId:r.sessionId,goalId:s.id,kind:"goal-continuation"});let c=this.now(),u=this.appendLoopIteration(r,a,c,"Interactive goal turn",void 0,i!==void 0);if(e.executionKind!==void 0&&e.executionKind!=="local-sdk"&&e.executionKind!=="external")throw new l("INVALID","Unknown goal execution lane");return u.goalTurn={requestId:t,requestHash:o,executor:e.executionKind==="local-sdk"?{kind:"local-sdk",processId:process.pid,host:O.hostname()}:{kind:"external"}},a.version+=1,a.updatedAt=c,{...this.goalTurnState(r,s,a,u),admitted:!0}},!1,r=>r.admitted)}async getGoalTurnState(e,n,i){let t=await this.getSessionState(e),o=n?t.goals.find(c=>c.id===n):[...t.goals].reverse().find(c=>["active","paused","waiting","blocked"].includes(c.status));if(!o)return;let r=t.loops.filter(c=>c.goalId===o.id),s=i?r.find(c=>c.iterations.some(u=>u.goalTurn?.requestId===i)):[...r].reverse().find(c=>c.kind==="goal-continuation"),a=i?s?.iterations.find(c=>c.goalTurn?.requestId===i):s?.iterations.at(-1);if(i&&!a)throw new l("NOT_FOUND","Goal turn was not found");return this.goalTurnState(t,o,s,a)}async finishGoalTurn(e){if(!["completed","failed","interrupted"].includes(e.status))throw new l("INVALID","Invalid goal turn outcome");let n=this.goalTurnHash(e.requestHash);return this.mutate(e.sessionId,i=>{let t=this.requireGoal(i,e.goalId),o=i.loops.find(s=>s.goalId===t.id&&s.iterations.some(a=>a.goalTurn?.requestId===e.requestId)),r=o?.iterations.find(s=>s.goalTurn?.requestId===e.requestId);if(!o||!r)throw new l("NOT_FOUND","Goal turn was not found");if(r.goalTurn?.requestHash!==n)throw new l("CONFLICT","Goal turn settlement identity does not match");return r.status==="running"&&(this.settleLoopIteration(i,o,r,this.now(),{status:t.status==="cancelled"||["stopped","failed"].includes(o.status)?"interrupted":e.status}),o.version+=1,o.updatedAt=this.now()),this.goalTurnState(i,t,o,r)},!0)}async recoverGoalTurn(e,n,i){return this.mutate(e,t=>{let o=this.requireGoal(t,n),r=t.loops.find(a=>a.goalId===n&&a.iterations.some(c=>c.goalTurn?.requestId===i)),s=r?.iterations.find(a=>a.goalTurn?.requestId===i);if(!r||!s)throw new l("NOT_FOUND","Goal turn was not found");if(s.status==="running"){if(!this.goalTurnOwnerExited(s))throw new l("NOT_OWNER","The original local goal executor has not been proved exited; external execution requires reconciliation");this.settleLoopIteration(t,r,s,this.now(),{status:"interrupted",error:"Original local SDK executor exited; inspect persisted results before retrying work"}),r.resumeRequested=o.status==="active"&&r.status==="running",r.version+=1,r.updatedAt=this.now()}return this.goalTurnState(t,o,r,s)},!0)}async finishLoopIteration(e,n,i,t){return this.mutateLoop(e,n,i,(o,r,s)=>{let a=[...o.iterations].reverse().find(c=>c.status==="running");if(!a)throw new l("CONFLICT",`Loop ${o.id} has no running iteration`);this.settleLoopIteration(s,o,a,r,t)},!1,!0)}settleLoopIteration(e,n,i,t,o){i.status=o.status,i.completedAt=t,o.verificationEventId&&(i.verificationEventId=p(o.verificationEventId,"verificationEventId",512)),o.error&&(i.error=p(o.error,"error")),n.status=["stopped","completed","failed"].includes(n.status)?n.status:e.admissionFence?"paused":o.nextStatus??(n.status==="paused"||n.status==="waiting"?n.status:"running"),this.appendEvent(e,"loop.iteration",{loopId:n.id,goalId:n.goalId,data:{number:i.number,phase:"finished",status:o.status}})}async setLoopStatus(e,n,i,t,o){return this.mutateLoop(e,n,i,(r,s,a)=>{let c=r.status;if(["stopped","completed","failed"].includes(c))throw new l("CONFLICT",`Loop ${r.id} is terminal (${c})`);let u=[...r.iterations].reverse().find(g=>g.status==="running");if(u&&t==="completed")throw new l("CONFLICT",`Loop ${r.id} cannot complete while iteration ${u.number} is running`);u&&(t==="stopped"||t==="failed")&&(u.status=t==="failed"?"failed":"interrupted",u.completedAt=s,u.error=p(o??t,"reason")),r.status=t,r.kind==="goal-continuation"&&(r.resumeRequested=t==="running"),["stopped","completed","failed"].includes(t)&&(r.stoppedAt=s,r.stopReason=p(o??t,"reason"));let f=t==="paused"?"loop.paused":t==="waiting"?"loop.waiting":t==="running"&&(c==="paused"||c==="waiting")?"loop.resumed":t==="completed"?"loop.completed":t==="failed"?"loop.failed":"loop.stopped";this.appendEvent(a,f,{loopId:n,goalId:r.goalId,data:{previous:c,status:t,...o?{reason:o}:{}}})},!1,t!=="running"&&t!=="waiting")}async acquireOwnership(e,n,i={}){return this.mutate(e,t=>{let o=this.now();if(t.owner&&!this.ownerExpired(t.owner,o)){if(t.owner.ownerId===n&&i.processId!==void 0&&t.owner.processId===i.processId&&(i.host===void 0||t.owner.host===i.host))return t.owner;throw new l("CONFLICT",`Session ${e} is owned by ${t.owner.ownerId}`,{owner:t.owner})}let r=t.owner&&this.ownerExpired(t.owner,o)?t.owner:void 0;if(r)for(let c of t.handoffs.filter(u=>u.status==="claimed"&&u.claimedBy===r.ownerId&&u.targetLeaseEpoch===r.epoch))c.status="failed",c.failureReason=`Claimed owner ${r.ownerId} lost its execution lease before completing the handoff.`,c.failedAt=o,c.updatedAt=o,c.version+=1,this.appendEvent(t,"handoff.failed",{handoffId:c.id,goalId:c.goalId,loopId:c.loopId,data:{reason:c.failureReason,expiredLeaseId:r.leaseId}});let s=t.ownershipEpoch+1;for(let c of t.handoffs.filter(u=>["prepared","available"].includes(u.status)&&u.sourceLeaseEpoch<s))c.status="failed",c.failureReason="Source ownership epoch was superseded before the handoff was claimed.",c.failedAt=o,c.updatedAt=o,c.version+=1,this.appendEvent(t,"handoff.failed",{handoffId:c.id,data:{epoch:s,reason:c.failureReason}});let a=this.newOwner(n,s,i,o);return t.owner=a,t.ownershipEpoch=s,this.appendEvent(t,"ownership.acquired",{ownerId:n,data:{epoch:s,leaseId:a.leaseId}}),a})}async renewOwnership(e,n,i,t=this.ownerLeaseMs){return this.mutate(e,o=>{let r=this.requireOwner(o,n,i);if(this.ownerExpired(r,this.now()))throw new l("LEASE_EXPIRED",`Ownership lease ${i} expired`);return r.heartbeatAt=this.now(),r.expiresAt=new Date(b(r.heartbeatAt)+t).toISOString(),this.appendEvent(o,"ownership.renewed",{ownerId:n,data:{epoch:r.epoch,leaseId:i}}),r})}async recoverExpiredOwnership(e,n,i,t,o=this.ownerLeaseMs){return this.mutate(e,r=>{let s=this.requireOwner(r,n,i);if(s.processId!==t||s.host!==O.hostname()||!V(t))throw new l("LEASE_EXPIRED",`Ownership lease ${i} expired and cannot be recovered by process ${t}`);let a=this.now(),c=Math.max(0,b(a)-b(s.expiresAt));return s.heartbeatAt=a,s.expiresAt=new Date(b(a)+o).toISOString(),this.appendEvent(r,c>0?"ownership.recovered":"ownership.renewed",{ownerId:n,data:{epoch:s.epoch,leaseId:i,...c>0?{expiredForMs:c}:{}}}),s})}async releaseOwnership(e,n,i){return this.mutate(e,t=>{let o=this.requireOwner(t,n,i);for(let r of t.handoffs.filter(s=>s.status==="claimed"&&s.claimedBy===n&&s.targetLeaseEpoch===o.epoch))r.status="failed",r.failureReason="Target released execution ownership before completing the handoff.",r.failedAt=this.now(),r.updatedAt=r.failedAt,r.version+=1,this.appendEvent(t,"handoff.failed",{handoffId:r.id,ownerId:n,data:{epoch:o.epoch,reason:r.failureReason}});return t.owner=void 0,this.appendEvent(t,"ownership.released",{ownerId:n,data:{epoch:o.epoch}}),o},!0)}async createHandoff(e){let n=!1,i=e.prepareRequestId===void 0?void 0:p(e.prepareRequestId,"prepareRequestId",512);return this.mutate(e.sessionId,t=>{let o=this.requireOwner(t,e.sourceOwnerId,e.sourceLeaseId);if(this.ownerExpired(o,this.now()))throw new l("LEASE_EXPIRED",`Ownership lease ${o.leaseId} expired`);if(i){let u=t.handoffs.find(f=>f.prepareRequestId===i);if(u){if(u.sourceOwnerId!==o.ownerId||u.sourceLeaseEpoch!==o.epoch||u.status!=="available"||u.targetOwnerId!==e.targetOwnerId||u.workspace!==e.workspace||u.goalId!==e.goalId||u.loopId!==e.loopId||u.contextDigest!==e.contextDigest||u.branch!==e.branch||u.currentMilestoneId!==e.currentMilestoneId||u.currentTaskId!==e.currentTaskId||JSON.stringify(u.agentIds)!==JSON.stringify([...new Set(e.agentIds??[])])||JSON.stringify(u.operations)!==JSON.stringify(e.operations??[]))throw new l("CONFLICT","Prepare identity was reused for different work or ownership");return n=!0,u}}let r=(e.operations??[]).filter(u=>u.status==="running"&&u.sideEffecting);if(r.length>0)throw new l("UNSAFE_HANDOFF","Running side-effecting operations must settle before execution handoff",{operationIds:r.map(u=>u.operationId)});if(e.goalId&&this.requireGoal(t,e.goalId),e.loopId&&!t.loops.some(u=>u.id===e.loopId))throw new l("NOT_FOUND",`Loop ${e.loopId} was not found`);let s=t.handoffs.find(u=>["prepared","available","claimed"].includes(u.status));if(s)throw new l("CONFLICT",`Handoff ${s.id} is already active`);let a=this.now(),c={schemaVersion:1,id:this.idFactory("handoff"),version:1,sessionId:t.sessionId,...e.goalId?{goalId:e.goalId}:{},...e.loopId?{loopId:e.loopId}:{},status:"available",sourceOwnerId:o.ownerId,...i?{prepareRequestId:i}:{},...e.targetOwnerId?{targetOwnerId:p(e.targetOwnerId,"targetOwnerId",512)}:{},sourceLeaseEpoch:o.epoch,...e.workspace?{workspace:p(e.workspace,"workspace",32768)}:{},...e.branch?{branch:p(e.branch,"branch",1024)}:{},...e.currentMilestoneId?{currentMilestoneId:e.currentMilestoneId}:{},...e.currentTaskId?{currentTaskId:e.currentTaskId}:{},agentIds:[...new Set(e.agentIds??[])],operations:w(e.operations??[]),...e.contextDigest?{contextDigest:p(e.contextDigest,"contextDigest",512)}:{},createdAt:a,updatedAt:a};return t.handoffs.push(c),this.appendEvent(t,"handoff.created",{handoffId:c.id,goalId:c.goalId,loopId:c.loopId,ownerId:o.ownerId,data:{targetOwnerId:c.targetOwnerId}}),c},!1,()=>!n)}async claimHandoff(e){let n,i=!1,t=e.claimRequestId===void 0?void 0:p(e.claimRequestId,"claimRequestId",512);return{handoff:await this.mutate(e.sessionId,r=>{let s=r.handoffs.find(u=>u.id===e.handoffId);if(!s)throw new l("NOT_FOUND",`Handoff ${e.handoffId} was not found`);if(s.status!=="available"){let u=r.owner;if(t&&s.claimRequestId===t&&["claimed","completed"].includes(s.status)&&s.claimedBy===e.targetOwnerId&&u?.ownerId===e.targetOwnerId&&u.epoch===s.targetLeaseEpoch&&u.host===e.host&&u.processId===e.processId&&!this.ownerExpired(u,this.now()))return n=u,i=!0,s;throw new l("CONFLICT",`Handoff ${s.id} is ${s.status}`,{claimedBy:s.claimedBy})}if(s.targetOwnerId&&s.targetOwnerId!==e.targetOwnerId)throw new l("CONFLICT",`Handoff ${s.id} is reserved for ${s.targetOwnerId}`);let a=r.owner;if(!a||a.ownerId!==s.sourceOwnerId||a.epoch!==s.sourceLeaseEpoch)throw new l("CONFLICT",`Handoff ${s.id} no longer matches the source ownership epoch`);let c=this.now();return n=this.newOwner(e.targetOwnerId,a.epoch+1,{processId:e.processId,host:e.host,leaseMs:e.leaseMs},c),r.owner=n,r.ownershipEpoch=n.epoch,s.status="claimed",s.claimedBy=e.targetOwnerId,t&&(s.claimRequestId=t),s.targetOwnerId=e.targetOwnerId,s.targetLeaseEpoch=n.epoch,s.claimedAt=c,s.updatedAt=c,s.version+=1,this.appendEvent(r,"handoff.claimed",{handoffId:s.id,goalId:s.goalId,loopId:s.loopId,ownerId:e.targetOwnerId,data:{sourceOwnerId:s.sourceOwnerId,epoch:n.epoch}}),s},!1,()=>!i),owner:w(n)}}async completeHandoff(e,n,i,t){let o=!1;return this.mutate(e,r=>{let s=this.requireOwner(r,i,t);if(this.ownerExpired(s,this.now()))throw new l("LEASE_EXPIRED",`Ownership lease ${t} expired`);let a=r.handoffs.find(c=>c.id===n);if(!a)throw new l("NOT_FOUND",`Handoff ${n} was not found`);if(a.claimedBy!==i||a.targetLeaseEpoch!==s.epoch||!["claimed","completed"].includes(a.status))throw new l("CONFLICT",`Handoff ${a.id} cannot be completed by ${i}`);return a.status==="completed"?(o=!0,a):(a.status="completed",a.completedAt=this.now(),a.updatedAt=a.completedAt,a.version+=1,this.appendEvent(r,"handoff.completed",{handoffId:n,goalId:a.goalId,loopId:a.loopId,ownerId:i,data:{epoch:r.owner?.epoch}}),a)},!1,()=>!o)}async cancelHandoff(e,n,i,t){let o=!1;return this.mutate(e,r=>{let s=r.handoffs.find(c=>c.id===n);if(!s)throw new l("NOT_FOUND",`Handoff ${n} was not found`);if(s.sourceOwnerId!==i)throw new l("CONFLICT",`Handoff ${n} was not offered by ${i}`);if(s.status==="cancelled")return o=!0,s;if(s.status!=="available"&&s.status!=="prepared")throw new l("CONFLICT",`Handoff ${n} is ${s.status} and can no longer be cancelled`);let a=this.requireOwner(r,i,t);if(this.ownerExpired(a,this.now()))throw new l("LEASE_EXPIRED",`Ownership lease ${t} expired`);if(s.sourceLeaseEpoch!==a.epoch)throw new l("CONFLICT",`Handoff ${n} belongs to an earlier ownership epoch`);return s.status="cancelled",s.cancelledAt=this.now(),s.updatedAt=s.cancelledAt,s.version+=1,this.appendEvent(r,"handoff.cancelled",{handoffId:n,goalId:s.goalId,loopId:s.loopId,ownerId:i,data:{epoch:a.epoch}}),s},!1,()=>!o)}async failHandoff(e,n,i){return this.mutate(e,t=>{let o=t.handoffs.find(r=>r.id===n);if(!o)throw new l("NOT_FOUND",`Handoff ${n} was not found`);return["completed","cancelled","failed"].includes(o.status)||(o.status="failed",o.failureReason=p(i,"reason"),o.failedAt=this.now(),o.updatedAt=o.failedAt,o.version+=1,this.appendEvent(t,"handoff.failed",{handoffId:n,goalId:o.goalId,loopId:o.loopId,data:{reason:o.failureReason}})),o},!0)}async mutateGoal(e,n,i,t,o=!0){return this.mutate(e,r=>{let s=this.requireGoal(r,n);this.assertVersion(s.id,s.version,i);let a=this.now();return t(s,a,r),s.version+=1,s.updatedAt=a,o&&this.appendEvent(r,"goal.updated",{goalId:n,data:{status:s.status,version:s.version}}),s})}async mutateLoop(e,n,i,t,o=!0,r=!1){return this.mutate(e,s=>{let a=s.loops.find(u=>u.id===n);if(!a)throw new l("NOT_FOUND",`Loop ${n} was not found`);this.assertVersion(a.id,a.version,i);let c=this.now();return t(a,c,s),a.version+=1,a.updatedAt=c,o&&this.appendEvent(s,"loop.iteration",{loopId:n,goalId:a.goalId,data:{status:a.status,version:a.version}}),a},r)}assertGoalIterationAdmission(e,n,i,t=!1){if(!n.goalId)return;let o=this.requireGoal(e,n.goalId);if(o.status!=="active")throw new l("CONFLICT",`Goal ${o.id} is ${o.status}; no iteration was admitted`);let r=ne(o.limits);if(r?.maxTokens!==void 0&&!t)throw new l("BUDGET_UNAVAILABLE","Goal token allowance is not bound to request-level admission; no iteration was admitted",{goalId:o.id,limit:"maxTokens"});if(r?.maxWallClockMs!==void 0){let s=Date.parse(o.createdAt),a=Date.parse(i);if(!Number.isFinite(s)||!Number.isFinite(a)||a<s)throw new l("BUDGET_UNAVAILABLE","Goal wall-clock allowance cannot be verified",{goalId:o.id,limit:"maxWallClockMs"});if(a-s>=r.maxWallClockMs)throw new l("BUDGET_EXCEEDED","Goal wall-clock limit reached; no iteration was admitted",{goalId:o.id,limit:"maxWallClockMs",maximum:r.maxWallClockMs})}if(r?.maxIterations!==void 0){let s=e.goalTurnAccounting!==void 0||e.schemaVersion===4?this.resolveGoalTurnAccounting(e,o):void 0;if(s?.coverage==="partial")throw new l("BUDGET_UNAVAILABLE","Legacy goal turn accounting is incomplete");let a=this.goalIterationCount(e,o)+(s?.baseIterations??0);if(!Number.isSafeInteger(a)||a<0)throw new l("BUDGET_UNAVAILABLE","Invalid goal iteration accounting");if(a>=r.maxIterations)throw new l("BUDGET_EXCEEDED","Goal iteration limit reached; no iteration was admitted",{goalId:o.id,limit:"maxIterations",admitted:a,maximum:r.maxIterations})}}isCliGoal(e){return"cli.accountedTurns"in e.metadata||"cli.createdByCliVersion"in e.metadata}goalIterationCount(e,n){let i=0;for(let t of e.loops.filter(o=>o.goalId===n.id)){if(!Array.isArray(t.iterations))throw new l("BUDGET_UNAVAILABLE","Goal iteration history is unavailable");let o=0;for(let r of t.iterations){if(!r||!Number.isSafeInteger(r.number)||r.number<=o)throw new l("BUDGET_UNAVAILABLE","Goal iteration history is invalid");o=r.number}if(i+=o,!Number.isSafeInteger(i))throw new l("BUDGET_UNAVAILABLE","Goal iteration count exceeds its supported range")}return i}resolveGoalTurnAccounting(e,n){let i=e.goalTurnAccounting;if(i!==void 0&&(!i||typeof i!="object"||Array.isArray(i)))throw new l("BUDGET_UNAVAILABLE","Persisted goal turn accounting is invalid");if(i&&Object.hasOwn(i,n.id)){let a=i[n.id];if(!a||a.schemaVersion!==1||!Number.isSafeInteger(a.baseIterations)||a.baseIterations<0||!["complete","partial"].includes(a.coverage))throw new l("BUDGET_UNAVAILABLE","Persisted goal turn accounting is invalid");return a}if(e.loops.some(a=>a.goalId===n.id&&a.iterations.some(c=>c.goalTurn||c.goalAccountingVersion)))throw new l("BUDGET_UNAVAILABLE","Recorded goal turns are missing their protected accounting");let t=this.goalIterationCount(e,n),o=n.metadata["cli.accountedTurns"],r=typeof o=="number"&&Number.isSafeInteger(o)&&o>=0,s=this.isCliGoal(n)&&(!r||o>0&&t>0);return{schemaVersion:1,baseIterations:r&&t===0?o:0,coverage:s?"partial":"complete"}}initializeGoalTurnAccounting(e,n){let i=this.resolveGoalTurnAccounting(e,n);if(i.coverage==="partial"&&n.limits?.maxIterations!==void 0)throw new l("BUDGET_UNAVAILABLE","Legacy goal turn accounting needs reconciliation before bounded execution");e.goalTurnAccounting??={},Object.defineProperty(e.goalTurnAccounting,n.id,{value:i,writable:!0,enumerable:!0,configurable:!0})}goalTurnHash(e){let n=p(e,"requestHash",64).toLowerCase();if(!/^[0-9a-f]{64}$/.test(n))throw new l("INVALID","Goal turn requestHash must be a SHA-256 digest");return n}goalTurnState(e,n,i,t){let o=this.resolveGoalTurnAccounting(e,n),r=this.goalIterationCount(e,n)+o.baseIterations;if(!Number.isSafeInteger(r))throw new l("BUDGET_UNAVAILABLE","Goal turn count exceeds its supported range");return w({goal:n,admittedTurns:r,accountingCoverage:o.coverage,...i?{loopId:i.id,loopVersion:i.version,loopStatus:i.status,resumeRequested:i.resumeRequested===!0}:{},...t?{iterationNumber:t.number,iterationStatus:t.status,...t.goalTurn?{requestId:t.goalTurn.requestId,requestHash:t.goalTurn.requestHash}:{},canRecover:t.status==="running"&&this.goalTurnOwnerExited(t)}:{}})}goalTurnOwnerExited(e){let n=e.goalTurn?.executor;if(n?.kind!=="local-sdk"||n.host!==O.hostname()||!Number.isSafeInteger(n.processId)||n.processId<=0)return!1;try{return process.kill(n.processId,0),!1}catch(i){return i.code==="ESRCH"}}recalculateProgress(e,n){let i=e.tasks.filter(t=>t.status==="completed").length;e.progress.completedTaskCount=i,e.progress.totalTaskCount=e.tasks.length,e.progress.percent=e.tasks.length?Math.round(i/e.tasks.length*100):void 0,e.progress.outstanding=e.tasks.filter(t=>!["completed","cancelled"].includes(t.status)).map(t=>t.title),e.progress.updatedAt=n}requireGoal(e,n){let i=e.goals.find(t=>t.id===n);if(!i)throw new l("NOT_FOUND",`Goal ${n} was not found`);return i}requireOwner(e,n,i){let t=e.owner;if(!t||t.ownerId!==n||t.leaseId!==i)throw new l("NOT_OWNER",`${n} does not own session ${e.sessionId}`,{owner:t});return t}assertVersion(e,n,i){if(!Number.isInteger(i)||i<1||n!==i)throw new l("CONFLICT",`Expected ${e} version ${i}, found ${n}`,{expected:i,actual:n})}newOwner(e,n,i,t){let o=i.leaseMs??this.ownerLeaseMs;if(!Number.isSafeInteger(o)||o<1)throw new l("INVALID","leaseMs must be a positive safe integer");return{ownerId:p(e,"ownerId",512),leaseId:this.idFactory("owner"),epoch:n,acquiredAt:t,heartbeatAt:t,expiresAt:new Date(b(t)+o).toISOString(),...i.processId!==void 0?{processId:i.processId}:{},...i.host?{host:p(i.host,"host",512)}:{}}}ownerExpired(e,n){return b(e.expiresAt)<=b(n)?!0:e.processId!==void 0&&e.host===O.hostname()&&!V(e.processId)}appendEvent(e,n,i){let t={schemaVersion:1,id:this.idFactory("event"),sequence:(e.events.at(-1)?.sequence??0)+1,type:n,sessionId:e.sessionId,...i.goalId?{goalId:i.goalId}:{},...i.loopId?{loopId:i.loopId}:{},...i.handoffId?{handoffId:i.handoffId}:{},...i.ownerId?{ownerId:i.ownerId}:{},timestamp:this.now(),data:w(i.data)};e.events.push(t),e.events.length>this.maximumEventsPerSession&&e.events.splice(0,e.events.length-this.maximumEventsPerSession)}async mutate(e,n,i=!1,t=()=>!0){let o=p(e,"sessionId",1024);return this.withSessionLock(o,async()=>{let r=await this.readState(o);if(r.admissionFence&&!i)throw new l("CONFLICT","Session execution is blocked by a persisted lifecycle fence");let s=r.schemaVersion;this.promoteGoalBudgetEnvelope(r),r.schemaVersion!==s&&await this.writeState(r);let a=n(r);return t(a)&&(r.version+=1,r.updatedAt=this.now(),await this.writeState(r)),w(a)})}statePath(e){return y.join(this.rootDirectory,"sessions",`${oe(e)}.json`)}lockPath(e){return`${this.statePath(e)}.lock`}async readState(e){let n=this.statePath(e);try{let i=await h.readFile(n,"utf8"),t=JSON.parse(i);if(!te.includes(t.schemaVersion)||t.sessionId!==e)throw new l("INVALID",`Coordination state at ${n} does not match session ${e}`);if(t.admissionFence!==void 0){let o=t.admissionFence;if(!o||o.schemaVersion!==1||typeof o.authorityId!="string"||!o.authorityId.trim()||typeof o.operationId!="string"||!o.operationId.trim()||!["archive","delete"].includes(o.action)||!Number.isFinite(Date.parse(o.createdAt)))throw new l("INVALID","Persisted lifecycle fence is corrupt; execution remains unavailable")}return(!Number.isSafeInteger(t.ownershipEpoch)||t.ownershipEpoch<0)&&(t.ownershipEpoch=Math.max(t.owner?.epoch??0,...t.handoffs.map(o=>o.targetLeaseEpoch??o.sourceLeaseEpoch??0))),t}catch(i){if(i.code!=="ENOENT")throw i;let t=this.now();return{schemaVersion:1,sessionId:e,version:0,ownershipEpoch:0,goals:[],loops:[],handoffs:[],events:[],createdAt:t,updatedAt:t}}}promoteGoalBudgetEnvelope(e){(e.goalTurnAccounting!==void 0||e.loops.some(n=>n.resumeRequested!==void 0||n.iterations.some(i=>i.goalTurn!==void 0)))&&(e.schemaVersion=4),e.schemaVersion<3&&e.goals.some(n=>n.limits!==void 0&&(!n.limits||typeof n.limits!="object"||Array.isArray(n.limits)||Object.keys(n.limits).length>0))&&(e.schemaVersion=3)}async writeState(e){this.promoteGoalBudgetEnvelope(e);let n=this.statePath(e.sessionId),i=y.dirname(n);await h.mkdir(i,{recursive:!0});let t=`${n}.${process.pid}.${(0,x.randomUUID)()}.tmp`,o=await h.open(t,"wx");try{await o.writeFile(`${JSON.stringify(e,null,2)}
2
- `,"utf8"),await o.sync()}finally{await o.close()}try{await this.renameReplacing(t,n);try{let r=await h.open(i,"r");try{await r.sync()}finally{await r.close()}}catch{}}finally{await h.unlink(t).catch(()=>{})}}async renameReplacing(e,n){for(let i=0;;i+=1)try{await h.rename(e,n);return}catch(t){let o=t.code,r=ee[i];if(process.platform!=="win32"||!o||!G.has(o)||r===void 0)throw t;await new Promise(s=>setTimeout(s,r))}}async withSessionLock(e,n){let i=this.lockPath(e),t=y.join(i,"owner.json"),o=(0,x.randomUUID)(),r=`${i}.candidate.${o}`,s=Date.now();await h.mkdir(y.dirname(i),{recursive:!0});let a={schemaVersion:1,token:o,pid:process.pid,host:O.hostname(),acquiredAt:this.now()};await h.mkdir(r),await h.writeFile(y.join(r,"owner.json"),JSON.stringify(a),{encoding:"utf8",flag:"wx"});for(let c=0;;c+=1)try{await h.rename(r,i);break}catch(u){let f=u.code;if(!(!!f&&new Set(["EEXIST","ENOTEMPTY","ENOTDIR","EBUSY"]).has(f)||process.platform==="win32"&&!!f&&G.has(f)))throw await h.rm(r,{recursive:!0,force:!0}).catch(()=>{}),u;let k=await this.staleLockOwner(i,t);if(k){await this.quarantineLock(i,k.token,"stale");continue}if(Date.now()-s>=this.lockTimeoutMs)throw await h.rm(r,{recursive:!0,force:!0}).catch(()=>{}),new l("CONFLICT",`Timed out waiting for coordination lock for session ${e}`);await new Promise(_=>setTimeout(_,Math.min(100,5+c*5)+Math.floor(Math.random()*10)))}try{return await n()}finally{await this.quarantineLock(i,o,"released"),await h.rm(r,{recursive:!0,force:!0}).catch(()=>{})}}async staleLockOwner(e,n){try{let[i,t]=await Promise.all([h.readFile(n,"utf8").catch(()=>""),h.stat(e)]),o=i?JSON.parse(i):void 0;return!o||o.host!==O.hostname()||V(o.pid)?void 0:Date.now()-t.mtimeMs>this.lockStaleMs?o:void 0}catch{return}}async quarantineLock(e,n,i){let t=y.join(e,"owner.json"),o=i==="stale"?`${e}.stale.${oe(n)}`:`${e}.${i}.${n}.${(0,x.randomUUID)()}`;for(let r=0;;r+=1){let s;try{s=JSON.parse(await h.readFile(t,"utf8"))}catch(a){if(a.code==="ENOENT")return;throw a}if(s.token!==n)return;try{await h.rename(e,o);break}catch(a){let c=a.code;if(i==="stale")try{if(JSON.parse(await h.readFile(y.join(o,"owner.json"),"utf8")).token===n)return}catch{}if(c==="ENOENT"||c==="EEXIST")return;let u=ee[r];if(process.platform!=="win32"||!c||!G.has(c)||u===void 0)throw a;await new Promise(f=>setTimeout(f,u))}}if(i!=="stale")for(let r=0;;r+=1)try{await h.rm(o,{recursive:!0});return}catch(s){let a=s.code;if(a==="ENOENT")return;let c=Re[r];if(process.platform!=="win32"||!a||!G.has(a)||c===void 0)throw s;await new Promise(u=>setTimeout(u,c))}}};function N(d,e){if(!d||typeof d!="object"||Array.isArray(d))throw new Error(`${e} must be an object`);return d}function m(d,e){if(typeof d!="string"||!d.trim())throw new Error(`${e} must be a non-empty string`);return d}function R(d,e){if(typeof d!="number"||!Number.isInteger(d))throw new Error(`${e} must be an integer`);return d}async function _e(d,e){let{action:n,sessionId:i}=e,t=e.payload??{};if(t.sessionId!==void 0&&t.sessionId!==i)throw new l("INVALID","Payload sessionId must match the routed sessionId");let o;switch(n){case"state.get":o=await d.getSessionState(i);break;case"goal.create":o=await d.createGoal({...t,sessionId:i});break;case"goal.update":o=await d.updateGoal(i,m(t.goalId,"goalId"),R(t.expectedVersion,"expectedVersion"),N(t.update,"update"));break;case"goal.complete":o=await d.completeGoal(i,m(t.goalId,"goalId"),R(t.expectedVersion,"expectedVersion"),N(t.verification,"verification"));break;case"goal.cancel":o=await d.cancelGoal(i,m(t.goalId,"goalId"),R(t.expectedVersion,"expectedVersion"),m(t.reason,"reason"));break;case"goal.steer":o=await d.steerGoal(i,m(t.goalId,"goalId"),R(t.expectedVersion,"expectedVersion"),m(t.instruction,"instruction"));break;case"loop.start":o=await d.startLoop({sessionId:i,kind:m(t.kind,"kind"),...typeof t.goalId=="string"?{goalId:t.goalId}:{},...typeof t.activity=="string"?{activity:t.activity}:{},...t.schedule?{schedule:N(t.schedule,"schedule")}:{}});break;case"loop.get":o=await d.getLoop(i,typeof t.loopId=="string"?t.loopId:void 0);break;case"loop.begin":o=await d.beginLoopIteration(i,m(t.loopId,"loopId"),R(t.expectedVersion,"expectedVersion"),m(t.activity,"activity"),typeof t.taskId=="string"?t.taskId:void 0);break;case"loop.finish":o=await d.finishLoopIteration(i,m(t.loopId,"loopId"),R(t.expectedVersion,"expectedVersion"),N(t.result,"result"));break;case"loop.set_status":o=await d.setLoopStatus(i,m(t.loopId,"loopId"),R(t.expectedVersion,"expectedVersion"),m(t.status,"status"),typeof t.reason=="string"?t.reason:void 0);break;case"ownership.acquire":o=await d.acquireOwnership(i,m(t.ownerId,"ownerId"),N(t.options??{},"options"));break;case"ownership.renew":o=await d.renewOwnership(i,m(t.ownerId,"ownerId"),m(t.leaseId,"leaseId"),typeof t.leaseMs=="number"?t.leaseMs:void 0);break;case"ownership.release":o=await d.releaseOwnership(i,m(t.ownerId,"ownerId"),m(t.leaseId,"leaseId"));break;case"handoff.create":o=await d.createHandoff({...t,sessionId:i});break;case"handoff.claim":o=await d.claimHandoff({sessionId:i,handoffId:m(t.handoffId,"handoffId"),targetOwnerId:m(t.targetOwnerId,"targetOwnerId"),...typeof t.processId=="number"?{processId:t.processId}:{},...typeof t.host=="string"?{host:t.host}:{}});break;case"handoff.complete":o=await d.completeHandoff(i,m(t.handoffId,"handoffId"),m(t.ownerId,"ownerId"),m(t.leaseId,"leaseId"));break;case"handoff.fail":o=await d.failHandoff(i,m(t.handoffId,"handoffId"),m(t.reason,"reason"));break;default:throw new l("INVALID","Unsupported coordination action")}let r=await d.getSessionState(i),s=n==="state.get"||n==="loop.get"?void 0:r.events.at(-1);return{action:n,sessionId:i,result:o,state:r,...s?{event:s}:{}}}var re=require("node:crypto"),ie=require("node:os");var j=class{sessionId;ownerId;store;processId;host;leaseMs;heartbeatMs;claimHandoffId;claimRequestId;onOwnershipLost;prepareDestination;destinationTimeoutMs;initializationAbort=new AbortController;timer;heartbeatInFlight=!1;owner;ready=!1;starting;stopping;stopped=!1;lostError;preparedHandoffId;preparingHandoff=!1;handoffOutcomeUncertain=!1;constructor(e){if(this.store=e.store??new C,this.sessionId=e.sessionId,this.processId=e.processId??process.pid,this.host=e.host??(0,ie.hostname)(),this.ownerId=e.ownerId??`runtime:${this.host}:${this.processId}:${(0,re.randomUUID)().slice(0,8)}`,this.leaseMs=e.leaseMs??3e4,this.heartbeatMs=e.heartbeatMs??Math.max(250,Math.floor(this.leaseMs/3)),this.heartbeatMs>=this.leaseMs)throw new Error("heartbeatMs must be shorter than leaseMs");if(this.claimHandoffId=e.claimHandoffId,this.claimRequestId=e.claimRequestId,this.onOwnershipLost=e.onOwnershipLost,this.prepareDestination=e.prepareDestination,this.destinationTimeoutMs=e.destinationTimeoutMs??Math.min(1e4,Math.floor(this.leaseMs/2)),!Number.isSafeInteger(this.destinationTimeoutMs)||this.destinationTimeoutMs<1||this.destinationTimeoutMs>=this.leaseMs)throw new Error("destinationTimeoutMs must be a positive integer shorter than leaseMs")}get currentOwner(){return this.active&&this.owner?structuredClone(this.owner):void 0}get active(){return this.ready&&!!this.owner&&!this.stopped&&this.lostError===void 0&&!this.preparingHandoff&&!this.preparedHandoffId}async start(){if(this.stopped)throw new Error("Execution lease session has already stopped");if(this.lostError!==void 0)throw this.lostError;return this.ready&&this.owner?(this.assertExecutionAllowed(),structuredClone(this.owner)):(this.starting??=this.initialize(),structuredClone(await this.starting))}async initialize(){try{if(this.claimHandoffId){let e=await this.store.claimHandoff({sessionId:this.sessionId,handoffId:this.claimHandoffId,targetOwnerId:this.ownerId,processId:this.processId,host:this.host,leaseMs:this.leaseMs,...this.claimRequestId?{claimRequestId:this.claimRequestId}:{}});if(this.owner=e.owner,this.stopped)throw new Error("Execution lease session has already stopped");if(this.prepareDestination&&await this.prepareClaimedDestination(e.handoff),this.stopped)throw new Error("Execution lease session has already stopped");await this.store.completeHandoff(this.sessionId,this.claimHandoffId,this.ownerId,this.owner.leaseId)}else this.owner=await this.store.acquireOwnership(this.sessionId,this.ownerId,{processId:this.processId,host:this.host,leaseMs:this.leaseMs});if(this.stopped)throw new Error("Execution lease session has already stopped");if(this.owner=await this.store.renewOwnership(this.sessionId,this.ownerId,this.owner.leaseId,this.leaseMs),this.stopped)throw new Error("Execution lease session has already stopped");return this.ready=!0,this.timer=setInterval(()=>{this.heartbeat()},this.heartbeatMs),this.timer.unref?.(),structuredClone(this.owner)}catch(e){throw this.ready=!1,this.markLost(e instanceof Error?e:new Error("Execution lease initialization failed",{cause:e})),this.lostError}}async prepareClaimedDestination(e){let n=this.initializationAbort.signal,i,t;try{let o=new Promise((r,s)=>{t=()=>s(n.reason??new Error("Destination preparation cancelled")),n.addEventListener("abort",t,{once:!0}),i=setTimeout(()=>this.initializationAbort.abort(new Error("Destination preparation timed out")),this.destinationTimeoutMs),n.aborted&&t()});await Promise.race([o,Promise.resolve().then(()=>(n.throwIfAborted(),this.prepareDestination({handoff:structuredClone(e),signal:n})))]),n.throwIfAborted()}finally{i&&clearTimeout(i),t&&n.removeEventListener("abort",t)}}async assertOwned(){this.assertExecutionAllowed();let e=await this.renewHeldLease();return this.assertExecutionAllowed(),e}assertExecutionAllowed(){if(this.stopped)throw new Error("Execution surface is detached");if(this.lostError)throw this.lostError;if(this.preparingHandoff)throw new Error("Execution surface is preparing a handoff and is detached from mutation");if(this.preparedHandoffId)throw new Error(`Execution surface prepared handoff ${this.preparedHandoffId} and is detached from mutation`);if(!this.ready||!this.owner)throw new Error("Execution ownership was not started")}async renewHeldLease(){if(!this.owner)throw new Error("Execution ownership was not started");try{let e=await this.renewOrRecover(this.owner.leaseId);if(this.stopped)throw new Error("Execution surface is detached");return this.owner=e,structuredClone(this.owner)}catch(e){throw this.markLost(e),e}}async renewOrRecover(e){try{return await this.store.renewOwnership(this.sessionId,this.ownerId,e,this.leaseMs)}catch(n){if(!(n instanceof Error&&"code"in n&&n.code==="LEASE_EXPIRED")||!this.store.recoverExpiredOwnership||this.preparingHandoff||this.preparedHandoffId||this.stopped)throw n;return this.store.recoverExpiredOwnership(this.sessionId,this.ownerId,e,this.processId,this.leaseMs)}}async prepareHandoff(e={}){if(this.preparedHandoffId)throw new Error(`Handoff ${this.preparedHandoffId} is already prepared`);this.assertExecutionAllowed(),this.preparingHandoff=!0;try{let n=await this.renewHeldLease();this.handoffOutcomeUncertain=!0;let i=await this.store.createHandoff({...e,sessionId:this.sessionId,sourceOwnerId:n.ownerId,sourceLeaseId:n.leaseId});return this.preparedHandoffId=i.id,this.handoffOutcomeUncertain=!1,i}catch(n){throw this.markLost(n instanceof Error?n:new Error("Handoff preparation failed",{cause:n})),n}finally{this.preparingHandoff=!1}}async cancelPreparedHandoff(){let e=this.preparedHandoffId;if(!e)throw new Error("No prepared handoff to cancel");if(!this.store.cancelHandoff)throw new Error("This execution store cannot cancel a prepared handoff");if(this.stopped)throw new Error("Execution surface is detached");if(this.lostError)throw this.lostError;if(!this.owner)throw new Error("Execution ownership was not started");let n=await this.store.cancelHandoff(this.sessionId,e,this.ownerId,this.owner.leaseId);if(n.id!==e||n.status!=="cancelled")throw new Error(`Handoff ${e} was not cancelled`);return this.preparedHandoffId=void 0,await this.renewHeldLease(),n}async stop(e={}){return this.stopping?this.stopping:(this.stopped=!0,this.ready=!1,this.initializationAbort.abort(new Error("Execution lease session has already stopped")),this.timer&&clearInterval(this.timer),this.timer=void 0,this.stopping=this.finishStop(e),this.stopping)}async finishStop(e){await this.starting?.catch(()=>{});let n=this.owner;if(this.owner=void 0,!(e.release===!1||this.preparedHandoffId||this.handoffOutcomeUncertain||!n))try{await this.store.releaseOwnership(this.sessionId,n.ownerId,n.leaseId)}catch{}}async heartbeat(){if(!(!this.ready||!this.owner||this.stopped||this.lostError!==void 0||this.heartbeatInFlight)){this.heartbeatInFlight=!0;try{await this.renewHeldLease()}catch(e){this.markLost(e)}finally{this.heartbeatInFlight=!1}}}markLost(e){this.lostError===void 0&&(this.lostError=e,this.timer&&clearInterval(this.timer),this.timer=void 0,this.onOwnershipLost?.(e))}};var se=require("node:crypto"),H=require("node:perf_hooks");async function Le(d,e){let n=e.waitMs??0;if(!Number.isSafeInteger(n)||n<0||n>6e4)throw new l("INVALID","waitMs must be an integer from 0 through 60000");if(e.sinceRevision!==void 0&&!/^[a-f0-9]{64}$/.test(e.sinceRevision))throw new l("INVALID","Invalid handoff revision");if(typeof e.handoffId!="string"||!e.handoffId.trim()||e.handoffId.length>1024)throw new l("INVALID","Invalid handoff identifier");let i=H.performance.now()+n;for(;;){e.signal?.throwIfAborted();let t=await d.getSessionState(e.sessionId);e.signal?.throwIfAborted();let o=t.handoffs.find(a=>a.id===e.handoffId);if(!o)throw new l("NOT_FOUND","Handoff not found in the authorized session");let r=(0,se.createHash)("sha256").update(JSON.stringify([t.sessionId,o.id,o.version,o.status,t.ownershipEpoch,t.owner?.ownerId??null,t.owner?.epoch??null])).digest("hex"),s=e.sinceRevision===void 0||r!==e.sinceRevision;if(s||H.performance.now()>=i)return{sessionId:t.sessionId,handoffId:o.id,revision:r,changed:s,status:o.status,handoffVersion:o.version,ownershipEpoch:t.ownershipEpoch,sourceOwnerId:o.sourceOwnerId,...o.targetOwnerId?{targetOwnerId:o.targetOwnerId}:{}};await new Promise((a,c)=>{let u=e.signal,g=setTimeout(()=>{u?.removeEventListener("abort",v),a()},Math.min(100,Math.max(1,i-H.performance.now()))),v=()=>{clearTimeout(g),u?.removeEventListener("abort",v),c(u?.reason??new Error("Handoff wait cancelled"))};u?.addEventListener("abort",v,{once:!0}),u?.aborted&&v()})}}var de=require("node:crypto"),J=require("node:fs"),E=require("node:fs/promises"),I=require("node:path");var ae=require("node:crypto");function q(d){return{algorithm:"sha256",value:(0,ae.createHash)("sha256").update(d).digest("hex")}}var ce=1e4,le=8*1024*1024,ue=64*1024*1024;function fe(d){if(typeof d!="string"||!d||d.length>2048||(0,I.isAbsolute)(d)||/[\\:*?"<>|]/.test(d)||[...d].some(n=>n.charCodeAt(0)<32))throw new Error("Invalid portable snapshot path");let e=d.split("/");if(e.some(n=>!n||n==="."||n===".."||/[. ]$/.test(n)||/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(n)))throw new Error("Ambiguous portable snapshot path");if(e.some(n=>/^(?:\.git|\.ssh|\.aws|\.npmrc|\.netrc|\.xeno-handoff-ready|credentials(?:\.json)?|id_rsa|id_ed25519)$/i.test(n)||/^\.env(?:\.|$)/i.test(n)))throw new Error("Credential or repository-control path cannot be transferred");return d}function pe(d){return q(JSON.stringify([d.schemaVersion,d.sessionId,d.totalBytes,d.files.map(e=>[e.path,e.size,e.sha256,e.executable])])).value}function he(d,e){if(d.schemaVersion!==1||d.sessionId!==e||!Array.isArray(d.files)||d.files.length>ce||!Number.isSafeInteger(d.totalBytes)||d.totalBytes<0||d.totalBytes>ue)throw new Error("Invalid handoff snapshot manifest");let n=new Set,i=0;for(let t of d.files){if(fe(t.path),!Number.isSafeInteger(t.size)||t.size<0||t.size>le||!/^[a-f0-9]{64}$/.test(t.sha256)||typeof t.executable!="boolean")throw new Error("Invalid handoff snapshot file");let o=t.path.toLowerCase();if(n.has(o))throw new Error("Snapshot paths collide on Windows");n.add(o),i+=t.size}for(let t of n){let o=t.split("/");for(let r=1;r<o.length;r++)if(n.has(o.slice(0,r).join("/")))throw new Error("Snapshot file conflicts with a directory")}if(i!==d.totalBytes||pe(d)!==d.digest)throw new Error("Handoff snapshot manifest integrity mismatch")}async function Q(d,e){let n=d;for(let o of e.split("/"))if(n=(0,I.join)(n,o),(await(0,E.lstat)(n)).isSymbolicLink())throw new Error("Snapshot symlinks are not supported");let i=await(0,E.realpath)(n),t=(0,I.relative)(d,i);if(t===".."||t.startsWith(`..${I.sep}`)||(0,I.isAbsolute)(t))throw new Error("Snapshot path escaped its root");return n}async function Xe(d){if(!d.sessionId||d.sessionId.length>1024||d.paths.length>ce)throw new Error("Invalid snapshot scope");let e=await(0,E.realpath)(d.root),n=[],i=new Map,t=0;for(let r of[...d.paths].sort()){if(d.signal?.throwIfAborted(),fe(r),!await d.authorizeFile(r))throw new Error("Snapshot file transfer is not authorized");let s=await Q(e,r),a=await(0,E.lstat)(s),c=await(0,E.open)(s,J.constants.O_RDONLY|(J.constants.O_NOFOLLOW??0));try{let u=await c.stat();if(await Q(e,r),a.ino!==u.ino||a.dev!==u.dev||a.ctimeMs!==u.ctimeMs)throw new Error("Snapshot source was replaced before reading");if(!u.isFile()||u.size>le||t+u.size>ue)throw new Error("Snapshot file or total byte limit exceeded");let f=Buffer.alloc(u.size),g=0;for(;g<f.length;){d.signal?.throwIfAborted();let{bytesRead:W}=await c.read(f,g,f.length-g,g);if(!W)throw new Error("Snapshot source changed while reading");g+=W}let v=await c.stat(),k=await(0,E.lstat)(s);if(await Q(e,r),u.size!==v.size||u.mtimeMs!==v.mtimeMs||u.ctimeMs!==v.ctimeMs||k.isSymbolicLink()||k.ino!==u.ino||k.dev!==u.dev)throw new Error("Snapshot source changed while reading");let _=q(f).value;n.push({path:r,size:f.length,sha256:_,executable:(u.mode&73)!==0}),i.set(_,f),t+=f.length}finally{await c.close()}}let o={schemaVersion:1,sessionId:d.sessionId,files:n,totalBytes:t,digest:""};return o.digest=pe(o),he(o,d.sessionId),{manifest:o,blobs:i}}async function Pe(d){let e=structuredClone(d.manifest);if(he(e,d.sessionId),!await d.authorizeManifest(structuredClone(e)))throw new Error("Snapshot restoration is not authorized");d.signal?.throwIfAborted();let n=(0,I.resolve)(d.destination);if(await(0,E.realpath)((0,I.dirname)(n))!==(0,I.dirname)(n))throw new Error("Snapshot destination parent must be canonical");try{throw await(0,E.lstat)(n),new Error("Snapshot destination already exists")}catch(r){if(r.code!=="ENOENT")throw r}let t=`${n}.staging-${(0,de.randomUUID)()}`;await(0,E.mkdir)(t,{mode:448});for(let r of e.files){d.signal?.throwIfAborted();let s=await d.readBlob(r.sha256,r.size);if(s.byteLength!==r.size||q(s).value!==r.sha256)throw new Error("Snapshot blob integrity mismatch; staging retained");let a=(0,I.join)(t,...r.path.split("/"));await(0,E.mkdir)((0,I.dirname)(a),{recursive:!0,mode:448});let c=await(0,E.open)(a,"wx",r.executable?448:384);try{await c.writeFile(s),await c.sync()}finally{await c.close()}}d.signal?.throwIfAborted();let o=await(0,E.open)((0,I.join)(t,".xeno-handoff-ready"),"wx",384);try{await o.writeFile(JSON.stringify({digest:e.digest,sessionId:e.sessionId})),await o.sync()}finally{await o.close()}return{directory:t,digest:e.digest,files:e.files.length,bytes:e.totalBytes}}var ge=require("node:crypto"),me=/^sha256:[0-9a-f]{64}$/;function De(d){return typeof d=="string"&&me.test(d)}function Ge(d){return`sha256:${(0,ge.createHash)("sha256").update(d).digest("hex")}`}0&&(module.exports={DurableXenoCoordinationStore,XENO_CONTEXT_DIGEST_PATTERN,XENO_COORDINATION_BUDGET_SESSION_SCHEMA_VERSION,XENO_COORDINATION_MANAGED_SESSION_SCHEMA_VERSION,XENO_COORDINATION_SCHEMA_VERSION,XENO_COORDINATION_TURN_SESSION_SCHEMA_VERSION,XenoCoordinationError,XenoExecutionLeaseSession,captureXenoHandoffSnapshot,computeXenoContextDigest,executeXenoCoordinationAction,isXenoContextDigest,restoreXenoHandoffSnapshot,waitForXenoHandoffStatus});
1
+ "use strict";var we=Object.create;var N=Object.defineProperty;var Ie=Object.getOwnPropertyDescriptor;var ye=Object.getOwnPropertyNames;var Ee=Object.getPrototypeOf,ve=Object.prototype.hasOwnProperty;var be=(d,e)=>{for(var r in e)N(d,r,{get:e[r],enumerable:!0})},W=(d,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of ye(e))!ve.call(d,t)&&t!==r&&N(d,t,{get:()=>e[t],enumerable:!(i=Ie(e,t))||i.enumerable});return d};var $=(d,e,r)=>(r=d!=null?we(Ee(d)):{},W(e||!d||!d.__esModule?N(r,"default",{value:d,enumerable:!0}):r,d)),Ae=d=>W(N({},"__esModule",{value:!0}),d);var Me={};be(Me,{DurableXenoCoordinationStore:()=>C,XENO_CONTEXT_DIGEST_PATTERN:()=>me,XENO_COORDINATION_BUDGET_SESSION_SCHEMA_VERSION:()=>P,XENO_COORDINATION_MANAGED_SESSION_SCHEMA_VERSION:()=>U,XENO_COORDINATION_SCHEMA_VERSION:()=>A,XENO_COORDINATION_TURN_SESSION_SCHEMA_VERSION:()=>D,XenoCoordinationError:()=>l,XenoExecutionLeaseSession:()=>j,captureXenoHandoffSnapshot:()=>Ne,computeXenoContextDigest:()=>Ge,executeXenoCoordinationAction:()=>Le,isXenoContextDigest:()=>De,restoreXenoHandoffSnapshot:()=>Pe,waitForXenoHandoffStatus:()=>_e});module.exports=Ae(Me);var A=1,U=2,P=3,D=4,l=class extends Error{constructor(r,i,t={}){super(i);this.code=r;this.details=t;this.name="XenoCoordinationError"}code;details};var x=require("node:crypto"),h=$(require("node:fs/promises"),1),O=$(require("node:os"),1),E=$(require("node:path"),1);var T=require("node:os");var X=require("node:path");var Ue=(0,T.platform)();var Be=(0,T.release)(),ze=(0,T.homedir)();function Y(){let d=process.env.XENO_AGENT_HOME?.trim();return d?(0,X.resolve)(d):(0,X.resolve)((0,T.homedir)(),".xeno-agent")}var S="[redacted]";var Ze=[[/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g,"[redacted:private-key]"],[/((?:^|[\s{,;"'(\[])["']?(?:cookie|set-cookie)["']?\s*[:=]\s*["']?)(?!\[redacted)[^\s"',;]+(?:;\s*[^\s"',;=]+=[^\s"',;]*)*/gi,`$1${S}`],[/((?:^|[\s{,;"'(\[])["']?(?:authorization|proxy-authorization|x-api-key|x-goog-api-key|x-xeno-api-key|api[-_]?key|apikey|dpop)["']?\s*[:=]\s*["']?)(?:(?:Bearer|Basic|Token|DPoP)\s+)?(?!\[redacted)[^\s"',;]+/gi,`$1${S}`],[/\b(Bearer|Basic|Token|DPoP)\s+[A-Za-z0-9._~+/=-]{6,}/gi,`$1 ${S}`],[/\b(?:sk-(?:ant-|proj-)?[A-Za-z0-9_-]{16,}|xeno-[A-Za-z0-9]{24,}|xrun_[A-Za-z0-9_-]{8,}|AIza[0-9A-Za-z_-]{30,}|gh[pousr]_[A-Za-z0-9_]{20,}|github_pat_[A-Za-z0-9_]{20,}|npm_[A-Za-z0-9]{30,}|xox[baprs]-[A-Za-z0-9-]{16,}|AKIA[0-9A-Z]{16})\b/g,S],[/\beyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}/g,S],[/([?&#;](?:access_token|refresh_token|id_token|token|key|api[_-]?key|secret|client_secret|password|signature|sig)=)[^&#\s"'<>]+/gi,`$1${S}`],[/(\b[a-z][a-z0-9+.-]*:\/\/)[^/\s:@"']+:[^/\s@"']+@/gi,`$1${S}@`]];var G=class extends Error{constructor(r,i){super(i);this.code=r;this.name="QuotaError"}code;retryable=!1};function Z(d){if(typeof d!="string"||!d.trim()||d.length>512)throw new G("INVALID","Invalid quota identity.");return d}function B(d){let e=r=>({id:Z(r?.id),generation:Z(r?.generation)});if(!d||d.agent&&!d.team)throw new G("INVALID","A child quota scope requires its complete ancestry.");return{workspace:e(d.workspace),...d.team?{team:e(d.team)}:{},...d.agent?{agent:e(d.agent)}:{},...d.goal!==void 0?{goal:e(d.goal)}:{}}}function z(d){return JSON.stringify(B(d))}var Oe=3e4,Te=3e4,Se=6e4,xe=2e4,M=new Set(["EACCES","EBUSY","EPERM"]),ee=[5,10,20,40,80,160,320],Re=[5,10,20,40,80,160,320],te=[1,2,3,4];function p(d,e,r=16384){let i=d.trim();if(!i||i.length>r)throw new l("INVALID",`${e} must be non-empty and no longer than ${r} characters`);return i}function V(d,e){return[...new Set((d??[]).map(r=>p(r,e)))]}function re(d){if(d===void 0)return;if(!d||typeof d!="object"||Array.isArray(d))throw new l("INVALID","Goal limits must be an object when provided");let e={};for(let[r,i]of Object.entries(d)){if(r!=="maxIterations"&&r!=="maxTokens"&&r!=="maxWallClockMs")throw new l("INVALID","Unknown goal limit");if(i!==void 0){if(!Number.isSafeInteger(i)||i<=0)throw new l("INVALID",`${r} must be a positive safe integer when provided`);e[r]=i}}return e}function ke(d){if(d){if(d.kind!=="fixed-interval"&&d.kind!=="dynamic")throw new l("INVALID","schedule.kind must be fixed-interval or dynamic");if(d.kind==="fixed-interval"&&(!Number.isSafeInteger(d.intervalMs)||(d.intervalMs??0)<=0))throw new l("INVALID","Fixed-interval schedules require a positive safe intervalMs");if(d.intervalMs!==void 0&&(!Number.isSafeInteger(d.intervalMs)||d.intervalMs<=0))throw new l("INVALID","schedule.intervalMs must be a positive safe integer when provided");for(let e of["nextRunAt","expiresAt"]){let r=d[e];if(r!==void 0&&!Number.isFinite(Date.parse(r)))throw new l("INVALID",`schedule.${e} must be an ISO timestamp when provided`)}return w(d)}}function w(d){return structuredClone(d)}function b(d){let e=Date.parse(d);return Number.isFinite(e)?e:0}function H(d){if(!Number.isInteger(d)||d<=0)return!1;try{return process.kill(d,0),!0}catch(e){return e.code==="EPERM"}}function Xe(d){return{summary:"Goal created; work has not started.",completedTaskCount:0,totalTaskCount:0,outstanding:[],decisions:[],updatedAt:d}}function Ce(){return{status:"pending",criteria:[],evidence:[]}}function oe(d){return(0,x.createHash)("sha256").update(d).digest("hex")}var C=class{get goalTurnAdmissionVersion(){return 1}rootDirectory;now;idFactory;ownerLeaseMs;lockTimeoutMs;lockStaleMs;maximumEventsPerSession;constructor(e={}){this.rootDirectory=e.rootDirectory??E.join(Y(),"coordination"),this.now=e.now??(()=>new Date().toISOString()),this.idFactory=e.idFactory??(r=>`${r}_${(0,x.randomUUID)()}`),this.ownerLeaseMs=e.ownerLeaseMs??Oe,this.lockTimeoutMs=e.lockTimeoutMs??Te,this.lockStaleMs=e.lockStaleMs??Se,this.maximumEventsPerSession=e.maximumEventsPerSession??xe}async getSessionState(e){let r=p(e,"sessionId",1024);return w(await this.readState(r))}async fenceAdmission(e,r,i){let t=p(i.authorityId,"authorityId",512),o=p(i.operationId,"operationId",512);if(!Number.isSafeInteger(r)||r<0)throw new l("INVALID","Expected session version must be a nonnegative safe integer");if(i.action!=="archive"&&i.action!=="delete")throw new l("INVALID","Unsupported admission fence action");return this.mutate(e,n=>{let s=n.admissionFence;if(s?.authorityId===t&&s.operationId===o&&s.action===i.action)return s;if(n.version!==r)throw new l("CONFLICT","Session version changed before lifecycle fencing",{expected:r,actual:n.version});if(s?.authorityId===t&&s.action==="archive"&&i.action==="archive")return s;if(s&&!(s.authorityId===t&&s.action==="archive"&&i.action==="delete"))throw new l("CONFLICT","Another lifecycle fence already owns this session");let a={schemaVersion:1,authorityId:t,operationId:o,action:i.action,createdAt:this.now()};return n.admissionFence=a,n.schemaVersion===1&&(n.schemaVersion=2),this.appendEvent(n,"admission.fenced",{data:{authorityId:t,operationId:o,action:i.action}}),a},!0)}async clearAdmissionFence(e,r,i,t){await this.mutate(e,o=>{this.assertVersion(e,o.version,r);let n=o.admissionFence;if(!n||n.authorityId!==i||n.operationId!==t)throw new l("CONFLICT","Lifecycle fence identity does not match");if(n.action==="delete")throw new l("CONFLICT","Deleted session admission cannot be restored");if(o.owner)throw new l("CONFLICT","Execution ownership must settle before restoration");o.admissionFence=void 0,this.appendEvent(o,"admission.restored",{data:{authorityId:i,operationId:t}})},!0)}async releaseDeadLifecycleOwner(e,r,i,t){await this.mutate(e,o=>{this.assertVersion(e,o.version,r);let n=o.admissionFence;if(!n||n.authorityId!==i||n.operationId!==t)throw new l("CONFLICT","Lifecycle fence identity does not match");let s=o.owner;if(s){if(s.host!==O.hostname()||!Number.isInteger(s.processId)||(s.processId??0)<=0||H(s.processId))throw new l("CONFLICT","Execution owner exit has not been proved");o.owner=void 0,this.appendEvent(o,"ownership.released",{ownerId:s.ownerId,data:{epoch:s.epoch,reason:"fenced-local-owner-exited"}})}},!0)}async listSessionStates(){let e=E.join(this.rootDirectory,"sessions"),r;try{r=await h.readdir(e)}catch(t){if(t.code==="ENOENT")return[];throw t}return(await Promise.all(r.filter(t=>t.endsWith(".json")).map(async t=>{try{let o=JSON.parse(await h.readFile(E.join(e,t),"utf8"));return!te.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(n=>n.targetLeaseEpoch??n.sourceLeaseEpoch??0))),o)}catch{return}}))).filter(t=>t!==void 0).sort((t,o)=>b(o.updatedAt)-b(t.updatedAt)).map(t=>w(t))}async createGoal(e){let r=p(e.sessionId,"sessionId",1024),i=re(e.limits);return this.mutate(r,t=>{let o=t.goals.find(c=>["active","paused","waiting","blocked"].includes(c.status));if(o)throw new l("CONFLICT",`Session ${r} already has active goal ${o.id}`);let n=this.now(),s=(e.successCriteria??[]).map(c=>typeof c=="string"?{id:this.idFactory("criterion"),description:p(c,"successCriteria"),required:!0}:{id:c.id?p(c.id,"successCriteria.id",512):this.idFactory("criterion"),description:p(c.description,"successCriteria.description"),required:c.required}),a={schemaVersion:1,id:this.idFactory("goal"),version:1,sessionId:r,objective:p(e.objective,"objective"),...e.why?{why:p(e.why,"why")}:{},successCriteria:s,constraints:V(e.constraints,"constraints"),...i?{limits:i}:{},metadata:w(e.metadata??{}),status:"active",milestones:[],tasks:[],progress:Xe(n),verification:Ce(),steering:[],createdAt:n,updatedAt:n};return t.goals.push(a),this.appendEvent(t,"goal.created",{goalId:a.id,data:{objective:a.objective}}),a})}async getGoal(e,r){let i=await this.getSessionState(e),t=r?i.goals.find(o=>o.id===r):[...i.goals].reverse().find(o=>["active","paused","waiting","blocked"].includes(o.status));return t?w(t):void 0}async updateGoal(e,r,i,t){return this.mutate(e,o=>{let n=this.requireGoal(o,r);if(this.assertVersion(n.id,n.version,i),["completed","cancelled","failed"].includes(n.status))throw new l("CONFLICT",`Goal ${n.id} is terminal (${n.status})`);let s=n.status!=="active";if(t.status==="active"&&n.status==="blocked"?n.status="active":t.status&&(n.status=t.status),t.objective!==void 0&&(n.objective=p(t.objective,"objective")),t.why!==void 0&&(n.why=p(t.why,"why")),t.constraints&&(n.constraints=V(t.constraints,"constraints")),t.successCriteria&&(n.successCriteria=w(t.successCriteria)),t.progress&&(n.progress={...n.progress,...w(t.progress),outstanding:V(t.progress.outstanding??n.progress.outstanding,"progress.outstanding"),decisions:V(t.progress.decisions??n.progress.decisions,"progress.decisions"),updatedAt:this.now()}),t.verification&&(n.verification=w(t.verification)),t.metadata&&(n.metadata=w(t.metadata)),s&&n.status==="active")for(let a of o.loops.filter(c=>c.goalId===r&&c.kind==="goal-continuation"&&c.status==="running"))a.resumeRequested=!0,a.version+=1,a.updatedAt=this.now();return n.version+=1,n.updatedAt=this.now(),this.appendEvent(o,"goal.updated",{goalId:n.id,data:{status:n.status,version:n.version}}),n},t.status!==void 0&&["paused","cancelled","failed"].includes(t.status))}async addMilestone(e,r,i,t){return this.mutateGoal(e,r,i,(o,n)=>{let s={id:this.idFactory("milestone"),title:p(t.title,"milestone.title"),...t.description?{description:p(t.description,"milestone.description")}:{},status:o.milestones.some(a=>a.status==="active")?"pending":"active",taskIds:[],createdAt:n,updatedAt:n};o.milestones.push(s),o.progress.currentMilestoneId??=s.id,o.progress.updatedAt=n})}async addTask(e,r,i,t){return this.mutateGoal(e,r,i,(o,n)=>{let s=o.milestones.find(u=>u.id===t.milestoneId);if(!s)throw new l("NOT_FOUND",`Milestone ${t.milestoneId} was not found`);if(t.parentTaskId&&!o.tasks.some(u=>u.id===t.parentTaskId))throw new l("NOT_FOUND",`Parent task ${t.parentTaskId} was not found`);let a=[...new Set(t.dependsOn??[])];for(let u of a)if(!o.tasks.some(f=>f.id===u))throw new l("NOT_FOUND",`Task dependency ${u} was not found`);let c={id:this.idFactory("task"),milestoneId:s.id,...t.parentTaskId?{parentTaskId:t.parentTaskId}:{},title:p(t.title,"task.title"),...t.description?{description:p(t.description,"task.description")}:{},status:a.length===0?"ready":"pending",...t.assignedAgentId?{assignedAgentId:p(t.assignedAgentId,"task.assignedAgentId",512)}:{},...a.length?{dependsOn:a}:{},createdAt:n,updatedAt:n};o.tasks.push(c),s.taskIds.push(c.id),s.updatedAt=n,o.progress.totalTaskCount=o.tasks.length,o.progress.outstanding=o.tasks.filter(u=>u.status!=="completed").map(u=>u.title),o.progress.updatedAt=n})}async updateTask(e,r,i,t,o){return this.mutateGoal(e,r,t,(n,s)=>{let a=n.tasks.find(u=>u.id===i);if(!a)throw new l("NOT_FOUND",`Task ${i} was not found`);a.status=o.status,o.progress!==void 0&&(a.progress=p(o.progress,"task.progress")),o.resultEventId!==void 0&&(a.resultEventId=p(o.resultEventId,"task.resultEventId",512)),o.assignedAgentId!==void 0&&(a.assignedAgentId=p(o.assignedAgentId,"task.assignedAgentId",512)),a.updatedAt=s,a.status==="completed"&&(a.completedAt=s);let c=n.milestones.find(u=>u.id===a.milestoneId);if(c){let u=n.tasks.filter(f=>f.milestoneId===c.id);u.length>0&&u.every(f=>f.status==="completed")?(c.status="completed",c.completedAt=s):u.some(f=>f.status==="running")?c.status="active":u.some(f=>f.status==="blocked")&&(c.status="blocked"),c.updatedAt=s}for(let u of n.tasks)u.status!=="pending"||!u.dependsOn?.length||u.dependsOn.every(f=>n.tasks.find(g=>g.id===f)?.status==="completed")&&(u.status="ready",u.updatedAt=s);this.recalculateProgress(n,s)})}async steerGoal(e,r,i,t){return this.mutateGoal(e,r,i,(o,n,s)=>{let a=this.idFactory("steer");o.steering.push({id:a,instruction:p(t,"instruction"),createdAt:n}),this.appendEvent(s,"goal.steered",{goalId:r,data:{steeringId:a}})},!1)}async consumeGoalSteering(e,r,i){let t=[];return{goal:await this.mutateGoal(e,r,i,(n,s)=>{t=n.steering.filter(a=>!a.consumedAt).map(({id:a,instruction:c,createdAt:u})=>({id:a,instruction:c,createdAt:u}));for(let a of n.steering)a.consumedAt||(a.consumedAt=s)}),instructions:t}}async completeGoal(e,r,i,t){if(t.status!=="passed")throw new l("VERIFICATION_REQUIRED","Goal completion requires passed verification");return this.mutate(e,o=>{let n=this.requireGoal(o,r);this.assertVersion(n.id,n.version,i);let s=n.successCriteria.filter(u=>u.required),a=s.filter(u=>{let f=t.criteria.find(g=>g.criterionId===u.id);return!f?.satisfied||f.evidence.length===0});if(a.length>0)throw new l("VERIFICATION_REQUIRED","Required success criteria lack passing evidence",{unmetCriteria:a.map(u=>u.id)});if(s.length===0&&t.evidence.length===0)throw new l("VERIFICATION_REQUIRED","Goal completion requires at least one durable evidence reference");let c=this.now();return n.status="completed",n.verification=w(t),n.verification.verifiedAt??=c,n.completedAt=c,n.updatedAt=c,n.version+=1,this.appendEvent(o,"goal.completed",{goalId:r,data:{evidence:n.verification.evidence}}),n},!0)}async cancelGoal(e,r,i,t){return this.mutate(e,o=>{let n=this.requireGoal(o,r);if(this.assertVersion(n.id,n.version,i),["completed","cancelled","failed"].includes(n.status))return n;n.status="cancelled",n.updatedAt=this.now(),n.version+=1,this.appendEvent(o,"goal.cancelled",{goalId:r,data:{reason:p(t,"reason")}});for(let s of o.loops.filter(a=>a.goalId===r&&["running","paused","waiting"].includes(a.status)))s.status="stopped",s.resumeRequested!==void 0&&(s.resumeRequested=!1),s.stopReason=`Goal cancelled: ${t}`,s.stoppedAt=this.now(),s.updatedAt=s.stoppedAt,s.version+=1;return n},!0)}async startLoop(e){return this.mutate(e.sessionId,r=>this.createLoopRecord(r,e))}createLoopRecord(e,r){if(r.kind==="goal-continuation"&&!r.goalId)throw new l("INVALID","Goal-continuation loops require a goalId");if(r.goalId){let s=this.requireGoal(e,r.goalId);if(["completed","cancelled","failed"].includes(s.status))throw new l("CONFLICT",`Cannot start a loop for terminal goal ${s.id}`)}if(r.kind==="scheduled"&&!r.schedule)throw new l("INVALID","Scheduled loops require schedule metadata");if(r.kind!=="scheduled"&&r.schedule)throw new l("INVALID","Only scheduled loops may carry schedule metadata");let i=ke(r.schedule),t=e.loops.find(s=>s.goalId===r.goalId&&s.kind===r.kind&&["running","paused","waiting"].includes(s.status));if(t)throw new l("CONFLICT",`Loop ${t.id} is already active`);let o=this.now(),n={schemaVersion:1,id:this.idFactory("loop"),version:1,sessionId:e.sessionId,...r.goalId?{goalId:r.goalId}:{},kind:r.kind,status:"running",...r.activity?{currentActivity:p(r.activity,"activity")}:{},iterations:[],...i?{schedule:i}:{},createdAt:o,updatedAt:o};return e.loops.push(n),this.appendEvent(e,"loop.started",{loopId:n.id,goalId:n.goalId,data:{kind:n.kind}}),n}async getLoop(e,r){let i=await this.getSessionState(e),t=r?i.loops.find(o=>o.id===r):[...i.loops].reverse().find(o=>["running","paused","waiting"].includes(o.status));return t?w(t):void 0}async beginLoopIteration(e,r,i,t,o){return this.mutateLoop(e,r,i,(n,s,a)=>{this.appendLoopIteration(a,n,s,t,o)},!1)}appendLoopIteration(e,r,i,t,o,n=!1){if(r.status!=="running")throw new l("CONFLICT",`Loop ${r.id} is ${r.status}`);if(r.goalId){let c=this.requireGoal(e,r.goalId);this.isCliGoal(c)&&this.initializeGoalTurnAccounting(e,c)}if(this.assertGoalIterationAdmission(e,r,i,n),r.iterations.some(c=>c.status==="running"))throw new l("CONFLICT",`Loop ${r.id} already has a running iteration`);let s=(r.iterations.at(-1)?.number??0)+1;r.currentActivity=p(t,"activity");let a={number:s,startedAt:i,status:"running",activity:r.currentActivity,...r.goalId&&e.goalTurnAccounting?.[r.goalId]?{goalAccountingVersion:1}:{},...o?{taskId:p(o,"taskId",512)}:{}};return r.iterations.push(a),r.resumeRequested!==void 0&&(r.resumeRequested=!1),this.appendEvent(e,"loop.iteration",{loopId:r.id,goalId:r.goalId,data:{number:s,phase:"started",activity:r.currentActivity}}),a}async admitGoalTurn(e){return this.admitGoalTurnWithOwner(e)}async admitQuotaGoalTurn(e,r,i,t){let o=B(i),n=await this.getGoal(e.sessionId,e.goalId);if(!n||n.sessionId!==e.sessionId||n.limits?.maxTokens===void 0)throw new l("BUDGET_UNAVAILABLE","The exact token-bounded goal is unavailable for quota admission");if(this.isCliGoal(n)&&n.metadata["cli.tokenQuotaVersion"]!==1)throw new l("BUDGET_UNAVAILABLE","Legacy CLI goal token spend is unknown; quota admission requires creation-time provenance");if(o.goal?.id!==n.id||o.goal.generation!==n.createdAt)throw new l("BUDGET_UNAVAILABLE","Quota scope does not identify this durable goal generation");let s=await r.policy(o);if(!s||z(s.scope)!==z(o)||s.limits.tokensLifetime===void 0||s.limits.tokensLifetime===null||s.limits.tokensLifetime>n.limits.maxTokens)throw new l("BUDGET_UNAVAILABLE","Goal quota policy is absent or wider than the goal's explicit token limit");let a=await r.remainingTokens(o);if(a===null)throw new l("BUDGET_UNAVAILABLE","Goal token accounting has no durable remaining allowance");if(a<1)throw new l("BUDGET_EXCEEDED","Goal token allowance is exhausted");return this.admitGoalTurnWithOwner(e,t,{goalId:n.id,createdAt:n.createdAt,maximum:n.limits.maxTokens})}async admitOwnedGoalTurn(e,r){if(!r||!Number.isSafeInteger(r.epoch)||r.epoch<1)throw new l("INVALID","An exact execution ownership epoch is required");return this.admitGoalTurnWithOwner(e,{...r})}async admitGoalTurnWithOwner(e,r,i){let t=p(e.requestId,"requestId",512),o=this.goalTurnHash(e.requestHash);return this.mutate(e.sessionId,n=>{if(r){let f=this.requireOwner(n,r.ownerId,r.leaseId);if(f.epoch!==r.epoch)throw new l("NOT_OWNER","Execution ownership epoch changed");if(this.ownerExpired(f,this.now()))throw new l("LEASE_EXPIRED","Execution ownership expired");if(n.handoffs.some(g=>["prepared","available"].includes(g.status)&&g.sourceLeaseEpoch===f.epoch)||n.handoffs.some(g=>g.status==="claimed"&&g.targetLeaseEpoch===f.epoch))throw new l("UNSAFE_HANDOFF","Execution handoff has not settled")}let s=this.requireGoal(n,e.goalId);if(i&&(s.id!==i.goalId||s.createdAt!==i.createdAt||s.limits?.maxTokens!==i.maximum))throw new l("BUDGET_UNAVAILABLE","Goal token limit changed after quota verification");for(let f of n.loops.filter(g=>g.goalId===s.id)){let g=f.iterations.find(v=>v.goalTurn?.requestId===t);if(g){if(g.goalTurn?.requestHash!==o)throw new l("CONFLICT","Goal turn identity was reused for different work");return{...this.goalTurnState(n,s,f,g),admitted:!1}}}if(this.assertVersion(s.id,s.version,e.expectedGoalVersion),s.status!=="active")throw new l("CONFLICT",`Goal ${s.id} is ${s.status}`);let a=[...n.loops].reverse().find(f=>f.goalId===s.id&&f.kind==="goal-continuation");if(e.expectedLoopId!==void 0){if(!a||a.id!==e.expectedLoopId)throw new l("CONFLICT","Goal continuation loop changed before admission");this.assertVersion(a.id,a.version,e.expectedLoopVersion??-1)}else if(e.expectedLoopVersion!==void 0)throw new l("INVALID","A goal turn loop version requires its exact loop ID");if(a&&a.status!=="running")throw new l("CONFLICT",`Goal loop ${a.id} is ${a.status}; resume or start it explicitly`);this.initializeGoalTurnAccounting(n,s),a??=this.createLoopRecord(n,{sessionId:n.sessionId,goalId:s.id,kind:"goal-continuation"});let c=this.now(),u=this.appendLoopIteration(n,a,c,"Interactive goal turn",void 0,i!==void 0);if(e.executionKind!==void 0&&e.executionKind!=="local-sdk"&&e.executionKind!=="external")throw new l("INVALID","Unknown goal execution lane");return u.goalTurn={requestId:t,requestHash:o,executor:e.executionKind==="local-sdk"?{kind:"local-sdk",processId:process.pid,host:O.hostname()}:{kind:"external"}},a.version+=1,a.updatedAt=c,{...this.goalTurnState(n,s,a,u),admitted:!0}},!1,n=>n.admitted)}async getGoalTurnState(e,r,i){let t=await this.getSessionState(e),o=r?t.goals.find(c=>c.id===r):[...t.goals].reverse().find(c=>["active","paused","waiting","blocked"].includes(c.status));if(!o)return;let n=t.loops.filter(c=>c.goalId===o.id),s=i?n.find(c=>c.iterations.some(u=>u.goalTurn?.requestId===i)):[...n].reverse().find(c=>c.kind==="goal-continuation"),a=i?s?.iterations.find(c=>c.goalTurn?.requestId===i):s?.iterations.at(-1);if(i&&!a)throw new l("NOT_FOUND","Goal turn was not found");return this.goalTurnState(t,o,s,a)}async finishGoalTurn(e){if(!["completed","failed","interrupted"].includes(e.status))throw new l("INVALID","Invalid goal turn outcome");let r=this.goalTurnHash(e.requestHash);return this.mutate(e.sessionId,i=>{let t=this.requireGoal(i,e.goalId),o=i.loops.find(s=>s.goalId===t.id&&s.iterations.some(a=>a.goalTurn?.requestId===e.requestId)),n=o?.iterations.find(s=>s.goalTurn?.requestId===e.requestId);if(!o||!n)throw new l("NOT_FOUND","Goal turn was not found");if(n.goalTurn?.requestHash!==r)throw new l("CONFLICT","Goal turn settlement identity does not match");return n.status==="running"&&(this.settleLoopIteration(i,o,n,this.now(),{status:t.status==="cancelled"||["stopped","failed"].includes(o.status)?"interrupted":e.status}),o.version+=1,o.updatedAt=this.now()),this.goalTurnState(i,t,o,n)},!0)}async recoverGoalTurn(e,r,i){return this.mutate(e,t=>{let o=this.requireGoal(t,r),n=t.loops.find(a=>a.goalId===r&&a.iterations.some(c=>c.goalTurn?.requestId===i)),s=n?.iterations.find(a=>a.goalTurn?.requestId===i);if(!n||!s)throw new l("NOT_FOUND","Goal turn was not found");if(s.status==="running"){if(!this.goalTurnOwnerExited(s))throw new l("NOT_OWNER","The original local goal executor has not been proved exited; external execution requires reconciliation");this.settleLoopIteration(t,n,s,this.now(),{status:"interrupted",error:"Original local SDK executor exited; inspect persisted results before retrying work"}),n.resumeRequested=o.status==="active"&&n.status==="running",n.version+=1,n.updatedAt=this.now()}return this.goalTurnState(t,o,n,s)},!0)}async finishLoopIteration(e,r,i,t){return this.mutateLoop(e,r,i,(o,n,s)=>{let a=[...o.iterations].reverse().find(c=>c.status==="running");if(!a)throw new l("CONFLICT",`Loop ${o.id} has no running iteration`);this.settleLoopIteration(s,o,a,n,t)},!1,!0)}settleLoopIteration(e,r,i,t,o){i.status=o.status,i.completedAt=t,o.verificationEventId&&(i.verificationEventId=p(o.verificationEventId,"verificationEventId",512)),o.error&&(i.error=p(o.error,"error")),r.status=["stopped","completed","failed"].includes(r.status)?r.status:e.admissionFence?"paused":o.nextStatus??(r.status==="paused"||r.status==="waiting"?r.status:"running"),this.appendEvent(e,"loop.iteration",{loopId:r.id,goalId:r.goalId,data:{number:i.number,phase:"finished",status:o.status}})}async setLoopStatus(e,r,i,t,o){return this.mutateLoop(e,r,i,(n,s,a)=>{let c=n.status;if(["stopped","completed","failed"].includes(c))throw new l("CONFLICT",`Loop ${n.id} is terminal (${c})`);let u=[...n.iterations].reverse().find(g=>g.status==="running");if(u&&t==="completed")throw new l("CONFLICT",`Loop ${n.id} cannot complete while iteration ${u.number} is running`);u&&(t==="stopped"||t==="failed")&&(u.status=t==="failed"?"failed":"interrupted",u.completedAt=s,u.error=p(o??t,"reason")),n.status=t,n.kind==="goal-continuation"&&(n.resumeRequested=t==="running"),["stopped","completed","failed"].includes(t)&&(n.stoppedAt=s,n.stopReason=p(o??t,"reason"));let f=t==="paused"?"loop.paused":t==="waiting"?"loop.waiting":t==="running"&&(c==="paused"||c==="waiting")?"loop.resumed":t==="completed"?"loop.completed":t==="failed"?"loop.failed":"loop.stopped";this.appendEvent(a,f,{loopId:r,goalId:n.goalId,data:{previous:c,status:t,...o?{reason:o}:{}}})},!1,t!=="running"&&t!=="waiting")}async acquireOwnership(e,r,i={}){return this.mutate(e,t=>{let o=this.now();if(t.owner&&!this.ownerExpired(t.owner,o)){if(t.owner.ownerId===r&&i.processId!==void 0&&t.owner.processId===i.processId&&(i.host===void 0||t.owner.host===i.host))return t.owner;throw new l("CONFLICT",`Session ${e} is owned by ${t.owner.ownerId}`,{owner:t.owner})}let n=t.owner&&this.ownerExpired(t.owner,o)?t.owner:void 0;if(n)for(let c of t.handoffs.filter(u=>u.status==="claimed"&&u.claimedBy===n.ownerId&&u.targetLeaseEpoch===n.epoch))c.status="failed",c.failureReason=`Claimed owner ${n.ownerId} lost its execution lease before completing the handoff.`,c.failedAt=o,c.updatedAt=o,c.version+=1,this.appendEvent(t,"handoff.failed",{handoffId:c.id,goalId:c.goalId,loopId:c.loopId,data:{reason:c.failureReason,expiredLeaseId:n.leaseId}});let s=t.ownershipEpoch+1;for(let c of t.handoffs.filter(u=>["prepared","available"].includes(u.status)&&u.sourceLeaseEpoch<s))c.status="failed",c.failureReason="Source ownership epoch was superseded before the handoff was claimed.",c.failedAt=o,c.updatedAt=o,c.version+=1,this.appendEvent(t,"handoff.failed",{handoffId:c.id,data:{epoch:s,reason:c.failureReason}});let a=this.newOwner(r,s,i,o);return t.owner=a,t.ownershipEpoch=s,this.appendEvent(t,"ownership.acquired",{ownerId:r,data:{epoch:s,leaseId:a.leaseId}}),a})}async renewOwnership(e,r,i,t=this.ownerLeaseMs){return this.mutate(e,o=>{let n=this.requireOwner(o,r,i);if(this.ownerExpired(n,this.now()))throw new l("LEASE_EXPIRED",`Ownership lease ${i} expired`);return n.heartbeatAt=this.now(),n.expiresAt=new Date(b(n.heartbeatAt)+t).toISOString(),this.appendEvent(o,"ownership.renewed",{ownerId:r,data:{epoch:n.epoch,leaseId:i}}),n})}async recoverExpiredOwnership(e,r,i,t,o=this.ownerLeaseMs){return this.mutate(e,n=>{let s=this.requireOwner(n,r,i);if(s.processId!==t||s.host!==O.hostname()||!H(t))throw new l("LEASE_EXPIRED",`Ownership lease ${i} expired and cannot be recovered by process ${t}`);let a=this.now(),c=Math.max(0,b(a)-b(s.expiresAt));return s.heartbeatAt=a,s.expiresAt=new Date(b(a)+o).toISOString(),this.appendEvent(n,c>0?"ownership.recovered":"ownership.renewed",{ownerId:r,data:{epoch:s.epoch,leaseId:i,...c>0?{expiredForMs:c}:{}}}),s})}async releaseOwnership(e,r,i){return this.mutate(e,t=>{let o=this.requireOwner(t,r,i);for(let n of t.handoffs.filter(s=>s.status==="claimed"&&s.claimedBy===r&&s.targetLeaseEpoch===o.epoch))n.status="failed",n.failureReason="Target released execution ownership before completing the handoff.",n.failedAt=this.now(),n.updatedAt=n.failedAt,n.version+=1,this.appendEvent(t,"handoff.failed",{handoffId:n.id,ownerId:r,data:{epoch:o.epoch,reason:n.failureReason}});return t.owner=void 0,this.appendEvent(t,"ownership.released",{ownerId:r,data:{epoch:o.epoch}}),o},!0)}async createHandoff(e){let r=!1,i=e.prepareRequestId===void 0?void 0:p(e.prepareRequestId,"prepareRequestId",512);return this.mutate(e.sessionId,t=>{let o=this.requireOwner(t,e.sourceOwnerId,e.sourceLeaseId);if(this.ownerExpired(o,this.now()))throw new l("LEASE_EXPIRED",`Ownership lease ${o.leaseId} expired`);if(i){let u=t.handoffs.find(f=>f.prepareRequestId===i);if(u){if(u.sourceOwnerId!==o.ownerId||u.sourceLeaseEpoch!==o.epoch||u.status!=="available"||u.targetOwnerId!==e.targetOwnerId||u.workspace!==e.workspace||u.goalId!==e.goalId||u.loopId!==e.loopId||u.contextDigest!==e.contextDigest||u.branch!==e.branch||u.currentMilestoneId!==e.currentMilestoneId||u.currentTaskId!==e.currentTaskId||JSON.stringify(u.agentIds)!==JSON.stringify([...new Set(e.agentIds??[])])||JSON.stringify(u.operations)!==JSON.stringify(e.operations??[]))throw new l("CONFLICT","Prepare identity was reused for different work or ownership");return r=!0,u}}let n=(e.operations??[]).filter(u=>u.status==="running"&&u.sideEffecting);if(n.length>0)throw new l("UNSAFE_HANDOFF","Running side-effecting operations must settle before execution handoff",{operationIds:n.map(u=>u.operationId)});if(e.goalId&&this.requireGoal(t,e.goalId),e.loopId&&!t.loops.some(u=>u.id===e.loopId))throw new l("NOT_FOUND",`Loop ${e.loopId} was not found`);let s=t.handoffs.find(u=>["prepared","available","claimed"].includes(u.status));if(s)throw new l("CONFLICT",`Handoff ${s.id} is already active`);let a=this.now(),c={schemaVersion:1,id:this.idFactory("handoff"),version:1,sessionId:t.sessionId,...e.goalId?{goalId:e.goalId}:{},...e.loopId?{loopId:e.loopId}:{},status:"available",sourceOwnerId:o.ownerId,...i?{prepareRequestId:i}:{},...e.targetOwnerId?{targetOwnerId:p(e.targetOwnerId,"targetOwnerId",512)}:{},sourceLeaseEpoch:o.epoch,...e.workspace?{workspace:p(e.workspace,"workspace",32768)}:{},...e.branch?{branch:p(e.branch,"branch",1024)}:{},...e.currentMilestoneId?{currentMilestoneId:e.currentMilestoneId}:{},...e.currentTaskId?{currentTaskId:e.currentTaskId}:{},agentIds:[...new Set(e.agentIds??[])],operations:w(e.operations??[]),...e.contextDigest?{contextDigest:p(e.contextDigest,"contextDigest",512)}:{},createdAt:a,updatedAt:a};return t.handoffs.push(c),this.appendEvent(t,"handoff.created",{handoffId:c.id,goalId:c.goalId,loopId:c.loopId,ownerId:o.ownerId,data:{targetOwnerId:c.targetOwnerId}}),c},!1,()=>!r)}async claimHandoff(e){let r,i=!1,t=e.claimRequestId===void 0?void 0:p(e.claimRequestId,"claimRequestId",512);return{handoff:await this.mutate(e.sessionId,n=>{let s=n.handoffs.find(u=>u.id===e.handoffId);if(!s)throw new l("NOT_FOUND",`Handoff ${e.handoffId} was not found`);if(s.status!=="available"){let u=n.owner;if(t&&s.claimRequestId===t&&["claimed","completed"].includes(s.status)&&s.claimedBy===e.targetOwnerId&&u?.ownerId===e.targetOwnerId&&u.epoch===s.targetLeaseEpoch&&u.host===e.host&&u.processId===e.processId&&!this.ownerExpired(u,this.now()))return r=u,i=!0,s;throw new l("CONFLICT",`Handoff ${s.id} is ${s.status}`,{claimedBy:s.claimedBy})}if(s.targetOwnerId&&s.targetOwnerId!==e.targetOwnerId)throw new l("CONFLICT",`Handoff ${s.id} is reserved for ${s.targetOwnerId}`);let a=n.owner;if(!a||a.ownerId!==s.sourceOwnerId||a.epoch!==s.sourceLeaseEpoch)throw new l("CONFLICT",`Handoff ${s.id} no longer matches the source ownership epoch`);let c=this.now();return r=this.newOwner(e.targetOwnerId,a.epoch+1,{processId:e.processId,host:e.host,leaseMs:e.leaseMs},c),n.owner=r,n.ownershipEpoch=r.epoch,s.status="claimed",s.claimedBy=e.targetOwnerId,t&&(s.claimRequestId=t),s.targetOwnerId=e.targetOwnerId,s.targetLeaseEpoch=r.epoch,s.claimedAt=c,s.updatedAt=c,s.version+=1,this.appendEvent(n,"handoff.claimed",{handoffId:s.id,goalId:s.goalId,loopId:s.loopId,ownerId:e.targetOwnerId,data:{sourceOwnerId:s.sourceOwnerId,epoch:r.epoch}}),s},!1,()=>!i),owner:w(r)}}async completeHandoff(e,r,i,t){let o=!1;return this.mutate(e,n=>{let s=this.requireOwner(n,i,t);if(this.ownerExpired(s,this.now()))throw new l("LEASE_EXPIRED",`Ownership lease ${t} expired`);let a=n.handoffs.find(c=>c.id===r);if(!a)throw new l("NOT_FOUND",`Handoff ${r} was not found`);if(a.claimedBy!==i||a.targetLeaseEpoch!==s.epoch||!["claimed","completed"].includes(a.status))throw new l("CONFLICT",`Handoff ${a.id} cannot be completed by ${i}`);return a.status==="completed"?(o=!0,a):(a.status="completed",a.completedAt=this.now(),a.updatedAt=a.completedAt,a.version+=1,this.appendEvent(n,"handoff.completed",{handoffId:r,goalId:a.goalId,loopId:a.loopId,ownerId:i,data:{epoch:n.owner?.epoch}}),a)},!1,()=>!o)}async cancelHandoff(e,r,i,t){let o=!1;return this.mutate(e,n=>{let s=n.handoffs.find(c=>c.id===r);if(!s)throw new l("NOT_FOUND",`Handoff ${r} was not found`);if(s.sourceOwnerId!==i)throw new l("CONFLICT",`Handoff ${r} was not offered by ${i}`);if(s.status==="cancelled")return o=!0,s;if(s.status!=="available"&&s.status!=="prepared")throw new l("CONFLICT",`Handoff ${r} is ${s.status} and can no longer be cancelled`);let a=this.requireOwner(n,i,t);if(this.ownerExpired(a,this.now()))throw new l("LEASE_EXPIRED",`Ownership lease ${t} expired`);if(s.sourceLeaseEpoch!==a.epoch)throw new l("CONFLICT",`Handoff ${r} belongs to an earlier ownership epoch`);return s.status="cancelled",s.cancelledAt=this.now(),s.updatedAt=s.cancelledAt,s.version+=1,this.appendEvent(n,"handoff.cancelled",{handoffId:r,goalId:s.goalId,loopId:s.loopId,ownerId:i,data:{epoch:a.epoch}}),s},!1,()=>!o)}async failHandoff(e,r,i){return this.mutate(e,t=>{let o=t.handoffs.find(n=>n.id===r);if(!o)throw new l("NOT_FOUND",`Handoff ${r} was not found`);return["completed","cancelled","failed"].includes(o.status)||(o.status="failed",o.failureReason=p(i,"reason"),o.failedAt=this.now(),o.updatedAt=o.failedAt,o.version+=1,this.appendEvent(t,"handoff.failed",{handoffId:r,goalId:o.goalId,loopId:o.loopId,data:{reason:o.failureReason}})),o},!0)}async mutateGoal(e,r,i,t,o=!0){return this.mutate(e,n=>{let s=this.requireGoal(n,r);this.assertVersion(s.id,s.version,i);let a=this.now();return t(s,a,n),s.version+=1,s.updatedAt=a,o&&this.appendEvent(n,"goal.updated",{goalId:r,data:{status:s.status,version:s.version}}),s})}async mutateLoop(e,r,i,t,o=!0,n=!1){return this.mutate(e,s=>{let a=s.loops.find(u=>u.id===r);if(!a)throw new l("NOT_FOUND",`Loop ${r} was not found`);this.assertVersion(a.id,a.version,i);let c=this.now();return t(a,c,s),a.version+=1,a.updatedAt=c,o&&this.appendEvent(s,"loop.iteration",{loopId:r,goalId:a.goalId,data:{status:a.status,version:a.version}}),a},n)}assertGoalIterationAdmission(e,r,i,t=!1){if(!r.goalId)return;let o=this.requireGoal(e,r.goalId);if(o.status!=="active")throw new l("CONFLICT",`Goal ${o.id} is ${o.status}; no iteration was admitted`);let n=re(o.limits);if(n?.maxTokens!==void 0&&!t)throw new l("BUDGET_UNAVAILABLE","Goal token allowance is not bound to request-level admission; no iteration was admitted",{goalId:o.id,limit:"maxTokens"});if(n?.maxWallClockMs!==void 0){let s=Date.parse(o.createdAt),a=Date.parse(i);if(!Number.isFinite(s)||!Number.isFinite(a)||a<s)throw new l("BUDGET_UNAVAILABLE","Goal wall-clock allowance cannot be verified",{goalId:o.id,limit:"maxWallClockMs"});if(a-s>=n.maxWallClockMs)throw new l("BUDGET_EXCEEDED","Goal wall-clock limit reached; no iteration was admitted",{goalId:o.id,limit:"maxWallClockMs",maximum:n.maxWallClockMs})}if(n?.maxIterations!==void 0){let s=e.goalTurnAccounting!==void 0||e.schemaVersion===4?this.resolveGoalTurnAccounting(e,o):void 0;if(s?.coverage==="partial")throw new l("BUDGET_UNAVAILABLE","Legacy goal turn accounting is incomplete");let a=this.goalIterationCount(e,o)+(s?.baseIterations??0);if(!Number.isSafeInteger(a)||a<0)throw new l("BUDGET_UNAVAILABLE","Invalid goal iteration accounting");if(a>=n.maxIterations)throw new l("BUDGET_EXCEEDED","Goal iteration limit reached; no iteration was admitted",{goalId:o.id,limit:"maxIterations",admitted:a,maximum:n.maxIterations})}}isCliGoal(e){return"cli.accountedTurns"in e.metadata||"cli.createdByCliVersion"in e.metadata}goalIterationCount(e,r){let i=0;for(let t of e.loops.filter(o=>o.goalId===r.id)){if(!Array.isArray(t.iterations))throw new l("BUDGET_UNAVAILABLE","Goal iteration history is unavailable");let o=0;for(let n of t.iterations){if(!n||!Number.isSafeInteger(n.number)||n.number<=o)throw new l("BUDGET_UNAVAILABLE","Goal iteration history is invalid");o=n.number}if(i+=o,!Number.isSafeInteger(i))throw new l("BUDGET_UNAVAILABLE","Goal iteration count exceeds its supported range")}return i}resolveGoalTurnAccounting(e,r){let i=e.goalTurnAccounting;if(i!==void 0&&(!i||typeof i!="object"||Array.isArray(i)))throw new l("BUDGET_UNAVAILABLE","Persisted goal turn accounting is invalid");if(i&&Object.hasOwn(i,r.id)){let a=i[r.id];if(!a||a.schemaVersion!==1||!Number.isSafeInteger(a.baseIterations)||a.baseIterations<0||!["complete","partial"].includes(a.coverage))throw new l("BUDGET_UNAVAILABLE","Persisted goal turn accounting is invalid");return a}if(e.loops.some(a=>a.goalId===r.id&&a.iterations.some(c=>c.goalTurn||c.goalAccountingVersion)))throw new l("BUDGET_UNAVAILABLE","Recorded goal turns are missing their protected accounting");let t=this.goalIterationCount(e,r),o=r.metadata["cli.accountedTurns"],n=typeof o=="number"&&Number.isSafeInteger(o)&&o>=0,s=this.isCliGoal(r)&&(!n||o>0&&t>0);return{schemaVersion:1,baseIterations:n&&t===0?o:0,coverage:s?"partial":"complete"}}initializeGoalTurnAccounting(e,r){let i=this.resolveGoalTurnAccounting(e,r);if(i.coverage==="partial"&&r.limits?.maxIterations!==void 0)throw new l("BUDGET_UNAVAILABLE","Legacy goal turn accounting needs reconciliation before bounded execution");e.goalTurnAccounting??={},Object.defineProperty(e.goalTurnAccounting,r.id,{value:i,writable:!0,enumerable:!0,configurable:!0})}goalTurnHash(e){let r=p(e,"requestHash",64).toLowerCase();if(!/^[0-9a-f]{64}$/.test(r))throw new l("INVALID","Goal turn requestHash must be a SHA-256 digest");return r}goalTurnState(e,r,i,t){let o=this.resolveGoalTurnAccounting(e,r),n=this.goalIterationCount(e,r)+o.baseIterations;if(!Number.isSafeInteger(n))throw new l("BUDGET_UNAVAILABLE","Goal turn count exceeds its supported range");return w({goal:r,admittedTurns:n,accountingCoverage:o.coverage,...i?{loopId:i.id,loopVersion:i.version,loopStatus:i.status,resumeRequested:i.resumeRequested===!0}:{},...t?{iterationNumber:t.number,iterationStatus:t.status,...t.goalTurn?{requestId:t.goalTurn.requestId,requestHash:t.goalTurn.requestHash}:{},canRecover:t.status==="running"&&this.goalTurnOwnerExited(t)}:{}})}goalTurnOwnerExited(e){let r=e.goalTurn?.executor;if(r?.kind!=="local-sdk"||r.host!==O.hostname()||!Number.isSafeInteger(r.processId)||r.processId<=0)return!1;try{return process.kill(r.processId,0),!1}catch(i){return i.code==="ESRCH"}}recalculateProgress(e,r){let i=e.tasks.filter(t=>t.status==="completed").length;e.progress.completedTaskCount=i,e.progress.totalTaskCount=e.tasks.length,e.progress.percent=e.tasks.length?Math.round(i/e.tasks.length*100):void 0,e.progress.outstanding=e.tasks.filter(t=>!["completed","cancelled"].includes(t.status)).map(t=>t.title),e.progress.updatedAt=r}requireGoal(e,r){let i=e.goals.find(t=>t.id===r);if(!i)throw new l("NOT_FOUND",`Goal ${r} was not found`);return i}requireOwner(e,r,i){let t=e.owner;if(!t||t.ownerId!==r||t.leaseId!==i)throw new l("NOT_OWNER",`${r} does not own session ${e.sessionId}`,{owner:t});return t}assertVersion(e,r,i){if(!Number.isInteger(i)||i<1||r!==i)throw new l("CONFLICT",`Expected ${e} version ${i}, found ${r}`,{expected:i,actual:r})}newOwner(e,r,i,t){let o=i.leaseMs??this.ownerLeaseMs;if(!Number.isSafeInteger(o)||o<1)throw new l("INVALID","leaseMs must be a positive safe integer");return{ownerId:p(e,"ownerId",512),leaseId:this.idFactory("owner"),epoch:r,acquiredAt:t,heartbeatAt:t,expiresAt:new Date(b(t)+o).toISOString(),...i.processId!==void 0?{processId:i.processId}:{},...i.host?{host:p(i.host,"host",512)}:{}}}ownerExpired(e,r){return b(e.expiresAt)<=b(r)?!0:e.processId!==void 0&&e.host===O.hostname()&&!H(e.processId)}appendEvent(e,r,i){let t={schemaVersion:1,id:this.idFactory("event"),sequence:(e.events.at(-1)?.sequence??0)+1,type:r,sessionId:e.sessionId,...i.goalId?{goalId:i.goalId}:{},...i.loopId?{loopId:i.loopId}:{},...i.handoffId?{handoffId:i.handoffId}:{},...i.ownerId?{ownerId:i.ownerId}:{},timestamp:this.now(),data:w(i.data)};e.events.push(t),e.events.length>this.maximumEventsPerSession&&e.events.splice(0,e.events.length-this.maximumEventsPerSession)}async mutate(e,r,i=!1,t=()=>!0){let o=p(e,"sessionId",1024);return this.withSessionLock(o,async()=>{let n=await this.readState(o);if(n.admissionFence&&!i)throw new l("CONFLICT","Session execution is blocked by a persisted lifecycle fence");let s=n.schemaVersion;this.promoteGoalBudgetEnvelope(n),n.schemaVersion!==s&&await this.writeState(n);let a=r(n);return t(a)&&(n.version+=1,n.updatedAt=this.now(),await this.writeState(n)),w(a)})}statePath(e){return E.join(this.rootDirectory,"sessions",`${oe(e)}.json`)}lockPath(e){return`${this.statePath(e)}.lock`}async readState(e){let r=this.statePath(e);try{let i=await h.readFile(r,"utf8"),t=JSON.parse(i);if(!te.includes(t.schemaVersion)||t.sessionId!==e)throw new l("INVALID",`Coordination state at ${r} does not match session ${e}`);if(t.admissionFence!==void 0){let o=t.admissionFence;if(!o||o.schemaVersion!==1||typeof o.authorityId!="string"||!o.authorityId.trim()||typeof o.operationId!="string"||!o.operationId.trim()||!["archive","delete"].includes(o.action)||!Number.isFinite(Date.parse(o.createdAt)))throw new l("INVALID","Persisted lifecycle fence is corrupt; execution remains unavailable")}return(!Number.isSafeInteger(t.ownershipEpoch)||t.ownershipEpoch<0)&&(t.ownershipEpoch=Math.max(t.owner?.epoch??0,...t.handoffs.map(o=>o.targetLeaseEpoch??o.sourceLeaseEpoch??0))),t}catch(i){if(i.code!=="ENOENT")throw i;let t=this.now();return{schemaVersion:1,sessionId:e,version:0,ownershipEpoch:0,goals:[],loops:[],handoffs:[],events:[],createdAt:t,updatedAt:t}}}promoteGoalBudgetEnvelope(e){(e.goalTurnAccounting!==void 0||e.loops.some(r=>r.resumeRequested!==void 0||r.iterations.some(i=>i.goalTurn!==void 0)))&&(e.schemaVersion=4),e.schemaVersion<3&&e.goals.some(r=>r.limits!==void 0&&(!r.limits||typeof r.limits!="object"||Array.isArray(r.limits)||Object.keys(r.limits).length>0))&&(e.schemaVersion=3)}async writeState(e){this.promoteGoalBudgetEnvelope(e);let r=this.statePath(e.sessionId),i=E.dirname(r);await h.mkdir(i,{recursive:!0});let t=`${r}.${process.pid}.${(0,x.randomUUID)()}.tmp`,o=await h.open(t,"wx");try{await o.writeFile(`${JSON.stringify(e,null,2)}
2
+ `,"utf8"),await o.sync()}finally{await o.close()}try{await this.renameReplacing(t,r);try{let n=await h.open(i,"r");try{await n.sync()}finally{await n.close()}}catch{}}finally{await h.unlink(t).catch(()=>{})}}async renameReplacing(e,r){for(let i=0;;i+=1)try{await h.rename(e,r);return}catch(t){let o=t.code,n=ee[i];if(process.platform!=="win32"||!o||!M.has(o)||n===void 0)throw t;await new Promise(s=>setTimeout(s,n))}}async withSessionLock(e,r){let i=this.lockPath(e),t=E.join(i,"owner.json"),o=(0,x.randomUUID)(),n=`${i}.candidate.${o}`,s=Date.now();await h.mkdir(E.dirname(i),{recursive:!0});let a={schemaVersion:1,token:o,pid:process.pid,host:O.hostname(),acquiredAt:this.now()};await h.mkdir(n),await h.writeFile(E.join(n,"owner.json"),JSON.stringify(a),{encoding:"utf8",flag:"wx"});for(let c=0;;c+=1)try{await h.rename(n,i);break}catch(u){let f=u.code;if(!(!!f&&new Set(["EEXIST","ENOTEMPTY","ENOTDIR","EBUSY"]).has(f)||process.platform==="win32"&&!!f&&M.has(f)))throw await h.rm(n,{recursive:!0,force:!0}).catch(()=>{}),u;let k=await this.staleLockOwner(i,t);if(k){await this.quarantineLock(i,k.token,"stale");continue}if(Date.now()-s>=this.lockTimeoutMs)throw await h.rm(n,{recursive:!0,force:!0}).catch(()=>{}),new l("CONFLICT",`Timed out waiting for coordination lock for session ${e}`);await new Promise(_=>setTimeout(_,Math.min(100,5+c*5)+Math.floor(Math.random()*10)))}try{return await r()}finally{await this.quarantineLock(i,o,"released"),await h.rm(n,{recursive:!0,force:!0}).catch(()=>{})}}async staleLockOwner(e,r){try{let[i,t]=await Promise.all([h.readFile(r,"utf8").catch(()=>""),h.stat(e)]),o=i?JSON.parse(i):void 0;return!o||o.host!==O.hostname()||H(o.pid)?void 0:Date.now()-t.mtimeMs>this.lockStaleMs?o:void 0}catch{return}}async quarantineLock(e,r,i){let t=E.join(e,"owner.json"),o=i==="stale"?`${e}.stale.${oe(r)}`:`${e}.${i}.${r}.${(0,x.randomUUID)()}`;for(let n=0;;n+=1){let s;try{s=JSON.parse(await h.readFile(t,"utf8"))}catch(a){if(a.code==="ENOENT")return;throw a}if(s.token!==r)return;try{await h.rename(e,o);break}catch(a){let c=a.code;if(i==="stale")try{if(JSON.parse(await h.readFile(E.join(o,"owner.json"),"utf8")).token===r)return}catch{}if(c==="ENOENT"||c==="EEXIST")return;let u=ee[n];if(process.platform!=="win32"||!c||!M.has(c)||u===void 0)throw a;await new Promise(f=>setTimeout(f,u))}}if(i!=="stale")for(let n=0;;n+=1)try{await h.rm(o,{recursive:!0});return}catch(s){let a=s.code;if(a==="ENOENT")return;let c=Re[n];if(process.platform!=="win32"||!a||!M.has(a)||c===void 0)throw s;await new Promise(u=>setTimeout(u,c))}}};function L(d,e){if(!d||typeof d!="object"||Array.isArray(d))throw new Error(`${e} must be an object`);return d}function m(d,e){if(typeof d!="string"||!d.trim())throw new Error(`${e} must be a non-empty string`);return d}function R(d,e){if(typeof d!="number"||!Number.isInteger(d))throw new Error(`${e} must be an integer`);return d}async function Le(d,e){let{action:r,sessionId:i}=e,t=e.payload??{};if(t.sessionId!==void 0&&t.sessionId!==i)throw new l("INVALID","Payload sessionId must match the routed sessionId");let o;switch(r){case"state.get":o=await d.getSessionState(i);break;case"goal.create":o=await d.createGoal({...t,sessionId:i});break;case"goal.update":o=await d.updateGoal(i,m(t.goalId,"goalId"),R(t.expectedVersion,"expectedVersion"),L(t.update,"update"));break;case"goal.complete":o=await d.completeGoal(i,m(t.goalId,"goalId"),R(t.expectedVersion,"expectedVersion"),L(t.verification,"verification"));break;case"goal.cancel":o=await d.cancelGoal(i,m(t.goalId,"goalId"),R(t.expectedVersion,"expectedVersion"),m(t.reason,"reason"));break;case"goal.steer":o=await d.steerGoal(i,m(t.goalId,"goalId"),R(t.expectedVersion,"expectedVersion"),m(t.instruction,"instruction"));break;case"loop.start":o=await d.startLoop({sessionId:i,kind:m(t.kind,"kind"),...typeof t.goalId=="string"?{goalId:t.goalId}:{},...typeof t.activity=="string"?{activity:t.activity}:{},...t.schedule?{schedule:L(t.schedule,"schedule")}:{}});break;case"loop.get":o=await d.getLoop(i,typeof t.loopId=="string"?t.loopId:void 0);break;case"loop.begin":o=await d.beginLoopIteration(i,m(t.loopId,"loopId"),R(t.expectedVersion,"expectedVersion"),m(t.activity,"activity"),typeof t.taskId=="string"?t.taskId:void 0);break;case"loop.finish":o=await d.finishLoopIteration(i,m(t.loopId,"loopId"),R(t.expectedVersion,"expectedVersion"),L(t.result,"result"));break;case"loop.set_status":o=await d.setLoopStatus(i,m(t.loopId,"loopId"),R(t.expectedVersion,"expectedVersion"),m(t.status,"status"),typeof t.reason=="string"?t.reason:void 0);break;case"ownership.acquire":o=await d.acquireOwnership(i,m(t.ownerId,"ownerId"),L(t.options??{},"options"));break;case"ownership.renew":o=await d.renewOwnership(i,m(t.ownerId,"ownerId"),m(t.leaseId,"leaseId"),typeof t.leaseMs=="number"?t.leaseMs:void 0);break;case"ownership.release":o=await d.releaseOwnership(i,m(t.ownerId,"ownerId"),m(t.leaseId,"leaseId"));break;case"handoff.create":o=await d.createHandoff({...t,sessionId:i});break;case"handoff.claim":o=await d.claimHandoff({sessionId:i,handoffId:m(t.handoffId,"handoffId"),targetOwnerId:m(t.targetOwnerId,"targetOwnerId"),...typeof t.processId=="number"?{processId:t.processId}:{},...typeof t.host=="string"?{host:t.host}:{}});break;case"handoff.complete":o=await d.completeHandoff(i,m(t.handoffId,"handoffId"),m(t.ownerId,"ownerId"),m(t.leaseId,"leaseId"));break;case"handoff.fail":o=await d.failHandoff(i,m(t.handoffId,"handoffId"),m(t.reason,"reason"));break;default:throw new l("INVALID","Unsupported coordination action")}let n=await d.getSessionState(i),s=r==="state.get"||r==="loop.get"?void 0:n.events.at(-1);return{action:r,sessionId:i,result:o,state:n,...s?{event:s}:{}}}var ne=require("node:crypto"),ie=require("node:os");var j=class{sessionId;ownerId;store;processId;host;leaseMs;heartbeatMs;claimHandoffId;claimRequestId;onOwnershipLost;prepareDestination;destinationTimeoutMs;initializationAbort=new AbortController;timer;heartbeatInFlight=!1;owner;ready=!1;starting;stopping;stopped=!1;lostError;preparedHandoffId;preparingHandoff=!1;handoffOutcomeUncertain=!1;constructor(e){if(this.store=e.store??new C,this.sessionId=e.sessionId,this.processId=e.processId??process.pid,this.host=e.host??(0,ie.hostname)(),this.ownerId=e.ownerId??`runtime:${this.host}:${this.processId}:${(0,ne.randomUUID)().slice(0,8)}`,this.leaseMs=e.leaseMs??3e4,this.heartbeatMs=e.heartbeatMs??Math.max(250,Math.floor(this.leaseMs/3)),this.heartbeatMs>=this.leaseMs)throw new Error("heartbeatMs must be shorter than leaseMs");if(this.claimHandoffId=e.claimHandoffId,this.claimRequestId=e.claimRequestId,this.onOwnershipLost=e.onOwnershipLost,this.prepareDestination=e.prepareDestination,this.destinationTimeoutMs=e.destinationTimeoutMs??Math.min(1e4,Math.floor(this.leaseMs/2)),!Number.isSafeInteger(this.destinationTimeoutMs)||this.destinationTimeoutMs<1||this.destinationTimeoutMs>=this.leaseMs)throw new Error("destinationTimeoutMs must be a positive integer shorter than leaseMs")}get currentOwner(){return this.active&&this.owner?structuredClone(this.owner):void 0}get active(){return this.ready&&!!this.owner&&!this.stopped&&this.lostError===void 0&&!this.preparingHandoff&&!this.preparedHandoffId}async start(){if(this.stopped)throw new Error("Execution lease session has already stopped");if(this.lostError!==void 0)throw this.lostError;return this.ready&&this.owner?(this.assertExecutionAllowed(),structuredClone(this.owner)):(this.starting??=this.initialize(),structuredClone(await this.starting))}async initialize(){try{if(this.claimHandoffId){let e=await this.store.claimHandoff({sessionId:this.sessionId,handoffId:this.claimHandoffId,targetOwnerId:this.ownerId,processId:this.processId,host:this.host,leaseMs:this.leaseMs,...this.claimRequestId?{claimRequestId:this.claimRequestId}:{}});if(this.owner=e.owner,this.stopped)throw new Error("Execution lease session has already stopped");if(this.prepareDestination&&await this.prepareClaimedDestination(e.handoff),this.stopped)throw new Error("Execution lease session has already stopped");await this.store.completeHandoff(this.sessionId,this.claimHandoffId,this.ownerId,this.owner.leaseId)}else this.owner=await this.store.acquireOwnership(this.sessionId,this.ownerId,{processId:this.processId,host:this.host,leaseMs:this.leaseMs});if(this.stopped)throw new Error("Execution lease session has already stopped");if(this.owner=await this.store.renewOwnership(this.sessionId,this.ownerId,this.owner.leaseId,this.leaseMs),this.stopped)throw new Error("Execution lease session has already stopped");return this.ready=!0,this.timer=setInterval(()=>{this.heartbeat()},this.heartbeatMs),this.timer.unref?.(),structuredClone(this.owner)}catch(e){throw this.ready=!1,this.markLost(e instanceof Error?e:new Error("Execution lease initialization failed",{cause:e})),this.lostError}}async prepareClaimedDestination(e){let r=this.initializationAbort.signal,i,t;try{let o=new Promise((n,s)=>{t=()=>s(r.reason??new Error("Destination preparation cancelled")),r.addEventListener("abort",t,{once:!0}),i=setTimeout(()=>this.initializationAbort.abort(new Error("Destination preparation timed out")),this.destinationTimeoutMs),r.aborted&&t()});await Promise.race([o,Promise.resolve().then(()=>(r.throwIfAborted(),this.prepareDestination({handoff:structuredClone(e),signal:r})))]),r.throwIfAborted()}finally{i&&clearTimeout(i),t&&r.removeEventListener("abort",t)}}async assertOwned(){this.assertExecutionAllowed();let e=await this.renewHeldLease();return this.assertExecutionAllowed(),e}assertExecutionAllowed(){if(this.stopped)throw new Error("Execution surface is detached");if(this.lostError)throw this.lostError;if(this.preparingHandoff)throw new Error("Execution surface is preparing a handoff and is detached from mutation");if(this.preparedHandoffId)throw new Error(`Execution surface prepared handoff ${this.preparedHandoffId} and is detached from mutation`);if(!this.ready||!this.owner)throw new Error("Execution ownership was not started")}async renewHeldLease(){if(!this.owner)throw new Error("Execution ownership was not started");try{let e=await this.renewOrRecover(this.owner.leaseId);if(this.stopped)throw new Error("Execution surface is detached");return this.owner=e,structuredClone(this.owner)}catch(e){throw this.markLost(e),e}}async renewOrRecover(e){try{return await this.store.renewOwnership(this.sessionId,this.ownerId,e,this.leaseMs)}catch(r){if(!(r instanceof Error&&"code"in r&&r.code==="LEASE_EXPIRED")||!this.store.recoverExpiredOwnership||this.preparingHandoff||this.preparedHandoffId||this.stopped)throw r;return this.store.recoverExpiredOwnership(this.sessionId,this.ownerId,e,this.processId,this.leaseMs)}}async prepareHandoff(e={}){if(this.preparedHandoffId)throw new Error(`Handoff ${this.preparedHandoffId} is already prepared`);this.assertExecutionAllowed(),this.preparingHandoff=!0;try{let r=await this.renewHeldLease();this.handoffOutcomeUncertain=!0;let i=await this.store.createHandoff({...e,sessionId:this.sessionId,sourceOwnerId:r.ownerId,sourceLeaseId:r.leaseId});return this.preparedHandoffId=i.id,this.handoffOutcomeUncertain=!1,i}catch(r){throw this.markLost(r instanceof Error?r:new Error("Handoff preparation failed",{cause:r})),r}finally{this.preparingHandoff=!1}}async cancelPreparedHandoff(){let e=this.preparedHandoffId;if(!e)throw new Error("No prepared handoff to cancel");if(!this.store.cancelHandoff)throw new Error("This execution store cannot cancel a prepared handoff");if(this.stopped)throw new Error("Execution surface is detached");if(this.lostError)throw this.lostError;if(!this.owner)throw new Error("Execution ownership was not started");let r=await this.store.cancelHandoff(this.sessionId,e,this.ownerId,this.owner.leaseId);if(r.id!==e||r.status!=="cancelled")throw new Error(`Handoff ${e} was not cancelled`);return this.preparedHandoffId=void 0,await this.renewHeldLease(),r}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 r=this.owner;if(this.owner=void 0,!(e.release===!1||this.preparedHandoffId||this.handoffOutcomeUncertain||!r))try{await this.store.releaseOwnership(this.sessionId,r.ownerId,r.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 se=require("node:crypto"),q=require("node:perf_hooks");async function _e(d,e){let r=e.waitMs??0;if(!Number.isSafeInteger(r)||r<0||r>6e4)throw new l("INVALID","waitMs must be an integer from 0 through 60000");if(e.sinceRevision!==void 0&&!/^[a-f0-9]{64}$/.test(e.sinceRevision))throw new l("INVALID","Invalid handoff revision");if(typeof e.handoffId!="string"||!e.handoffId.trim()||e.handoffId.length>1024)throw new l("INVALID","Invalid handoff identifier");let i=q.performance.now()+r;for(;;){e.signal?.throwIfAborted();let t=await d.getSessionState(e.sessionId);e.signal?.throwIfAborted();let o=t.handoffs.find(a=>a.id===e.handoffId);if(!o)throw new l("NOT_FOUND","Handoff not found in the authorized session");let n=(0,se.createHash)("sha256").update(JSON.stringify([t.sessionId,o.id,o.version,o.status,t.ownershipEpoch,t.owner?.ownerId??null,t.owner?.epoch??null])).digest("hex"),s=e.sinceRevision===void 0||n!==e.sinceRevision;if(s||q.performance.now()>=i)return{sessionId:t.sessionId,handoffId:o.id,revision:n,changed:s,status:o.status,handoffVersion:o.version,ownershipEpoch:t.ownershipEpoch,sourceOwnerId:o.sourceOwnerId,...o.targetOwnerId?{targetOwnerId:o.targetOwnerId}:{}};await new Promise((a,c)=>{let u=e.signal,g=setTimeout(()=>{u?.removeEventListener("abort",v),a()},Math.min(100,Math.max(1,i-q.performance.now()))),v=()=>{clearTimeout(g),u?.removeEventListener("abort",v),c(u?.reason??new Error("Handoff wait cancelled"))};u?.addEventListener("abort",v,{once:!0}),u?.aborted&&v()})}}var de=require("node:crypto"),K=require("node:fs"),y=require("node:fs/promises"),I=require("node:path");var ae=require("node:crypto");function F(d){return{algorithm:"sha256",value:(0,ae.createHash)("sha256").update(d).digest("hex")}}var ce=1e4,le=8*1024*1024,ue=64*1024*1024;function fe(d){if(typeof d!="string"||!d||d.length>2048||(0,I.isAbsolute)(d)||/[\\:*?"<>|]/.test(d)||[...d].some(r=>r.charCodeAt(0)<32))throw new Error("Invalid portable snapshot path");let e=d.split("/");if(e.some(r=>!r||r==="."||r===".."||/[. ]$/.test(r)||/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(r)))throw new Error("Ambiguous portable snapshot path");if(e.some(r=>/^(?:\.git|\.ssh|\.aws|\.npmrc|\.netrc|\.xeno-handoff-ready|credentials(?:\.json)?|id_rsa|id_ed25519)$/i.test(r)||/^\.env(?:\.|$)/i.test(r)))throw new Error("Credential or repository-control path cannot be transferred");return d}function pe(d){return F(JSON.stringify([d.schemaVersion,d.sessionId,d.totalBytes,d.files.map(e=>[e.path,e.size,e.sha256,e.executable])])).value}function he(d,e){if(d.schemaVersion!==1||d.sessionId!==e||!Array.isArray(d.files)||d.files.length>ce||!Number.isSafeInteger(d.totalBytes)||d.totalBytes<0||d.totalBytes>ue)throw new Error("Invalid handoff snapshot manifest");let r=new Set,i=0;for(let t of d.files){if(fe(t.path),!Number.isSafeInteger(t.size)||t.size<0||t.size>le||!/^[a-f0-9]{64}$/.test(t.sha256)||typeof t.executable!="boolean")throw new Error("Invalid handoff snapshot file");let o=t.path.toLowerCase();if(r.has(o))throw new Error("Snapshot paths collide on Windows");r.add(o),i+=t.size}for(let t of r){let o=t.split("/");for(let n=1;n<o.length;n++)if(r.has(o.slice(0,n).join("/")))throw new Error("Snapshot file conflicts with a directory")}if(i!==d.totalBytes||pe(d)!==d.digest)throw new Error("Handoff snapshot manifest integrity mismatch")}async function Q(d,e){let r=d;for(let o of e.split("/"))if(r=(0,I.join)(r,o),(await(0,y.lstat)(r)).isSymbolicLink())throw new Error("Snapshot symlinks are not supported");let i=await(0,y.realpath)(r),t=(0,I.relative)(d,i);if(t===".."||t.startsWith(`..${I.sep}`)||(0,I.isAbsolute)(t))throw new Error("Snapshot path escaped its root");return r}async function Ne(d){if(!d.sessionId||d.sessionId.length>1024||d.paths.length>ce)throw new Error("Invalid snapshot scope");let e=await(0,y.realpath)(d.root),r=[],i=new Map,t=0;for(let n of[...d.paths].sort()){if(d.signal?.throwIfAborted(),fe(n),!await d.authorizeFile(n))throw new Error("Snapshot file transfer is not authorized");let s=await Q(e,n),a=await(0,y.lstat)(s),c=await(0,y.open)(s,K.constants.O_RDONLY|(K.constants.O_NOFOLLOW??0));try{let u=await c.stat();if(await Q(e,n),a.ino!==u.ino||a.dev!==u.dev||a.ctimeMs!==u.ctimeMs)throw new Error("Snapshot source was replaced before reading");if(!u.isFile()||u.size>le||t+u.size>ue)throw new Error("Snapshot file or total byte limit exceeded");let f=Buffer.alloc(u.size),g=0;for(;g<f.length;){d.signal?.throwIfAborted();let{bytesRead:J}=await c.read(f,g,f.length-g,g);if(!J)throw new Error("Snapshot source changed while reading");g+=J}let v=await c.stat(),k=await(0,y.lstat)(s);if(await Q(e,n),u.size!==v.size||u.mtimeMs!==v.mtimeMs||u.ctimeMs!==v.ctimeMs||k.isSymbolicLink()||k.ino!==u.ino||k.dev!==u.dev)throw new Error("Snapshot source changed while reading");let _=F(f).value;r.push({path:n,size:f.length,sha256:_,executable:(u.mode&73)!==0}),i.set(_,f),t+=f.length}finally{await c.close()}}let o={schemaVersion:1,sessionId:d.sessionId,files:r,totalBytes:t,digest:""};return o.digest=pe(o),he(o,d.sessionId),{manifest:o,blobs:i}}async function Pe(d){let e=structuredClone(d.manifest);if(he(e,d.sessionId),!await d.authorizeManifest(structuredClone(e)))throw new Error("Snapshot restoration is not authorized");d.signal?.throwIfAborted();let r=(0,I.resolve)(d.destination);if(await(0,y.realpath)((0,I.dirname)(r))!==(0,I.dirname)(r))throw new Error("Snapshot destination parent must be canonical");try{throw await(0,y.lstat)(r),new Error("Snapshot destination already exists")}catch(n){if(n.code!=="ENOENT")throw n}let t=`${r}.staging-${(0,de.randomUUID)()}`;await(0,y.mkdir)(t,{mode:448});for(let n of e.files){d.signal?.throwIfAborted();let s=await d.readBlob(n.sha256,n.size);if(s.byteLength!==n.size||F(s).value!==n.sha256)throw new Error("Snapshot blob integrity mismatch; staging retained");let a=(0,I.join)(t,...n.path.split("/"));await(0,y.mkdir)((0,I.dirname)(a),{recursive:!0,mode:448});let c=await(0,y.open)(a,"wx",n.executable?448:384);try{await c.writeFile(s),await c.sync()}finally{await c.close()}}d.signal?.throwIfAborted();let o=await(0,y.open)((0,I.join)(t,".xeno-handoff-ready"),"wx",384);try{await o.writeFile(JSON.stringify({digest:e.digest,sessionId:e.sessionId})),await o.sync()}finally{await o.close()}return{directory:t,digest:e.digest,files:e.files.length,bytes:e.totalBytes}}var ge=require("node:crypto"),me=/^sha256:[0-9a-f]{64}$/;function De(d){return typeof d=="string"&&me.test(d)}function Ge(d){return`sha256:${(0,ge.createHash)("sha256").update(d).digest("hex")}`}0&&(module.exports={DurableXenoCoordinationStore,XENO_CONTEXT_DIGEST_PATTERN,XENO_COORDINATION_BUDGET_SESSION_SCHEMA_VERSION,XENO_COORDINATION_MANAGED_SESSION_SCHEMA_VERSION,XENO_COORDINATION_SCHEMA_VERSION,XENO_COORDINATION_TURN_SESSION_SCHEMA_VERSION,XenoCoordinationError,XenoExecutionLeaseSession,captureXenoHandoffSnapshot,computeXenoContextDigest,executeXenoCoordinationAction,isXenoContextDigest,restoreXenoHandoffSnapshot,waitForXenoHandoffStatus});