@xenosystem/agent-cli 0.5.193 → 0.5.194

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -3245,7 +3245,7 @@ ${Fe}${ee.compose(Wfe(),ee.bold)("\u2717")} ${l6(e)}
3245
3245
  `)}function FD(){return`
3246
3246
  ${Fe}${Me("Goodbye.")}
3247
3247
  `}var _qn,EWt,Wfe,yr,Me,DD,l6,kWt,HS,Bqn,Mqn,Oqn,V,Fe,PWt,uHe,O,Jfe,xWt,hHe,TWt,d6,xa=Ae(()=>{"use strict";gd();at();Xd();sWt();jfe();dHe();_qn=new Wy(process.stdout),EWt=new Wy(process.stderr),Wfe=()=>Ws(),yr=e=>Wfe()(e),Me=ee.dim,DD=ee.bold,l6=e=>Wfe()(e),kWt="\u25A0",HS="\u2514",Bqn={open:"\x1B[4m",close:"\x1B[24m"};Mqn={Read:e=>Jm()(e),ReadImage:e=>Jm()(e),Glob:e=>Jm()(e),Grep:e=>Jm()(e),ElfAnalyze:e=>Jm()(e),MemoryRead:e=>Jm()(e),Write:e=>yP()(e),Edit:e=>yP()(e),MemoryWrite:e=>yP()(e),Bash:e=>tHe()(e),GitStatus:e=>Jm()(e),GitDiff:e=>Jm()(e),GitLog:e=>Jm()(e),GitBranch:e=>Jm()(e),GitCommit:e=>tHe()(e),WebSearch:e=>ee.cyan(e),WebFetch:e=>ee.cyan(e),TaskOutput:e=>Jm()(e),TaskInput:e=>ee.cyan(e),TaskStop:e=>af()(e)};Oqn={Edit:"Update",Glob:"Search",Grep:"Search",WebSearch:"Web Search",WebFetch:"Web Fetch"};V={accent:yr,purple:l6,cyan:l6,dim:Me,bold:DD,red:l6,green:l6},Fe=" ",PWt=1e3,uHe=3;O={moveTo:(e,t)=>`\x1B[${e};${t}H`,saveCursor:()=>"\x1B[s",restoreCursor:()=>"\x1B[u",setScrollRegion:(e,t)=>`\x1B[${e};${t}r`,resetScrollRegion:()=>"\x1B[r",eraseLine:()=>"\x1B[2K",clearScreen:()=>"\x1B[2J\x1B[3J\x1B[H",showCursor:()=>"\x1B[?25h",hideCursor:()=>"\x1B[?25l",disableWrap:()=>"\x1B[?7l",enableWrap:()=>"\x1B[?7h",enableMouseReporting:()=>"\x1B[?1000h\x1B[?1006h",disableMouseReporting:()=>"\x1B[?1006l\x1B[?1000l",enableBracketedPaste:()=>"\x1B[?2004h",disableBracketedPaste:()=>"\x1B[?2004l"};Jfe=30;xWt=3;hHe=class{atLineStart=!0;writeFn;constructor(t){this.writeFn=t??(r=>{_qn.writeOrdered(r,"stream")})}write(t){let r="";for(let n of t)this.atLineStart&&(r+=Fe,this.atLineStart=!1),r+=n,n===`
3248
- `&&(this.atLineStart=!0);this.writeFn(r)}reset(){this.atLineStart=!0}markLineStarted(){this.atLineStart=!1}},TWt=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],d6=class{interval=null;frameIndex=0;lastLength=0;writeFn;clearFn;constructor(t,r){this.writeFn=t??(n=>{EWt.writeFrame(n,"spinner")}),this.clearFn=r??(()=>{EWt.writeFrame(`\r${" ".repeat(this.lastLength)}\r`,"spinner")})}start(t){this.stop(),this.frameIndex=0,this.interval=setInterval(()=>{let r=TWt[this.frameIndex%TWt.length],n=`${yr(r)} ${Me(t)}`;this.writeFn(`\r${" ".repeat(this.lastLength)}\r${n}`),this.lastLength=t.length+4,this.frameIndex++},80)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null,this.clearFn(),this.lastLength=0)}}});import{randomInt as eVn}from"node:crypto";function tVn(e){return typeof e=="string"&&Ca.some(t=>t.id===e)}function wHe(){let e=TA().uiMascot;return tVn(e)?e:null}function _h(){return wHe()??rVn}function u6(e){wo({uiMascot:e})}function UD(){let e=TA().uiColor;return typeof e=="string"&&Wm(e)?eHe(e):eHe()}function DWt(e=process.stdout){return e.isTTY===!0&&!process.env.NO_COLOR&&process.env.TERM!=="dumb"&&process.env.XENO_ASCII_UI!=="1"&&process.env.XENO_REDUCED_MOTION!=="1"&&!process.env.CI}function nVn(e,t,r){let n=t==="done",i=r%1.6,o=n&&i<.6?-3*Math.sin(Math.PI*i/.6):0,s=n&&i>=.6&&i<.78?.8*Math.sin(Math.PI*(i-.6)/.18):0,a=(Math.sin(r*1.6)+1)/2,l=Math.max(-1,Math.min(1,Math.sin(r*.55)*1.6)),c=r%4.2,d=!n&&(c<.12||c>.26&&c<.36),u=-Math.PI/2.8+.5*Math.sin(r*9),p=(g,A,w,y,b=0,I=.6)=>n?[Bn(g-w,A+.4,g,A-y*.55,I,"K"),Bn(g,A-y*.55,g+w,A+.4,I,"K")]:d?[Bn(g-w,A+y*.35,g+w,A+y*.35,I,"K")]:[ur(g+l*.5,A,w,y,"K",b),ur(g-w*.3+l*.7,A-y*.4,Math.max(.6,w*.36),Math.max(.6,w*.36),"W")],f=g=>g.k==="e"?{...g,cx:32-g.cx,rot:-g.rot}:g.k==="l"?{...g,x1:32-g.x1,x2:32-g.x2}:g,h=[],m=o;if(e==="bean"){h.push(ur(12,28,3.2,1.9,"O"),ur(20,28,3.2,1.9,"O"),Bn(8.5,19,5.6,22.5,1.7,"B")),h.push(n?Bn(23.5,18,23.5+5*Math.cos(u),18+5*Math.sin(u),1.7,"B"):Bn(23.5,19,26.4,22.5,1.7,"B"));let g=n?Math.sin(r*9)*.5:Math.sin(r*1.6)*.4;h.push(Bn(17,10,18.2,5.2,.9,"B"),Bn(18.2,5.2,20.2,3.6,.9,"B"),ur(21.2,3.4+g,1.9,1.9,"O")),h.push(ur(16,18.5-a*.3,9+s,9.8+a*.4-s,"B"),ur(16,22.2,5.2,4.2,"C"),ur(10.2,19.6,1.3,.9,"O"),ur(21.8,19.6,1.3,.9,"O")),h.push(...p(12.6,15.5,2.1,2.9),...p(19.4,15.5,2.1,2.9)),h.push(n?ur(16,19.9,1.4,1.1,"K"):Bn(15,19.6,17,19.6,.45,"K"))}if(e==="ocu"){let g=[Bn(10.5,9.5,8.5,5.5,1.3,"O"),Bn(8.5,5.5,10.5,3.2,1.1,"O")];h.push(...g,...g.map(f),ur(11.5,27.5,3,1.8,"B"),ur(20.5,27.5,3,1.8,"B"),Bn(7,18,4.5,21.5,1.6,"B")),h.push(n?Bn(25,17,25+4.5*Math.cos(u),17+4.5*Math.sin(u),1.6,"B"):Bn(25,18,27.5,21.5,1.6,"B")),h.push(ur(16,17.5-a*.3,10+s,10+a*.4-s,"B")),n?h.push(Bn(11.5,17,16,13.5,.75,"K"),Bn(16,13.5,20.5,17,.75,"K")):d?h.push(Bn(11.5,16.8,20.5,16.8,.75,"K")):h.push(ur(16,16,4.8,4.3,"C"),ur(16+l*1.4,16.4,2.8,2.8,"O"),ur(16+l*1.6,16.4,1.3,1.3,"K"),ur(15+l*1.4,15,.8,.8,"W")),h.push(n?ur(16,23,1.8,1.2,"K"):Bn(14.5,23,17.5,23,.5,"K"))}if(e==="squee"){for(let g=0;g<4;g++){let A=9.8+g*4.13,w=g<2?-1:1;if(n&&g===3){let b=A+6*Math.cos(u),I=19+6*Math.sin(u);h.push(Bn(A,19,b,I,1.6,"B"),ur(b,I,1.5,1.5,"O"));continue}let y=Math.sin(r*1.4+g*1.1)*1.3;h.push(Bn(A,19,A+y,25,1.6,"B"),Bn(A+y,25,A+y+w*2.2,26.8,1.3,"O"))}h.push(ur(16,18.5,8.6,2.6,"B"),ur(16,12.5-a*.3,9.2+s,8.6+a*.4,"B"),ur(11.5,8.2,1.1,1,"S"),ur(20.5,7.5,1.4,1.2,"S"),ur(16,5.8,.9,.8,"S")),h.push(ur(10.4,16.4,1.2,.8,"O"),ur(21.6,16.4,1.2,.8,"O"),...p(12.6,13.5,1.9,2.5),...p(19.4,13.5,1.9,2.5)),h.push(n?ur(16,17.2,1.2,.9,"K"):Bn(15.2,17,16.8,17,.45,"K"))}if(e==="greeb"){let g=[Bn(12.5,5.5,10.5,2.4,.8,"B"),ur(10,2,1.5,1.5,"O")];h.push(...g,...g.map(f),ur(13.5,29,2.2,1.4,"B"),ur(18.5,29,2.2,1.4,"B"),Bn(12,23,9.5,26,1.1,"B")),h.push(n?Bn(20,22.5,20+4*Math.cos(u),22.5+4*Math.sin(u),1.1,"B"):Bn(20,23,22.5,26,1.1,"B")),h.push(ur(16,24.5,4.6,4.2,"B"),ur(16,16.5,5.6,4.4,"B"),ur(16,11.5-a*.3,10.2+s,8.2+a*.4,"B")),h.push(...p(11.3,12.8,3.4,2.1,.45,.7),...p(20.7,12.8,3.4,2.1,-.45,.7)),h.push(n?ur(16,18.4,1,.8,"K"):Bn(15.4,18.4,16.6,18.4,.4,"K"))}if(e==="quad"){let g=y=>y<.5?4*y*y*y:1-Math.pow(-2*y+2,3)/2,A=(n?90*(Math.floor(r/.8)+g(Math.min(1,r%.8/.5))):5*Math.sin(r*1.2))*Math.PI/180,w=(y,b,I)=>{let v=y-16,E=b-16.5;return[16+v*Math.cos(I)-E*Math.sin(I),16.5+v*Math.sin(I)+E*Math.cos(I)]};for(let y=0;y<4;y++){let b=A+y*Math.PI/2,I=w(10.5,11,b),v=w(6.6,7.1,b),E=w(6.6,10.2,b);h.push(Bn(I[0],I[1],v[0],v[1],1.7,"B"),Bn(v[0],v[1],E[0],E[1],1.5,"B"),ur(E[0],E[1],1.45,1.45,"O"))}h.push({k:"r",cx:16,cy:16.5-a*.2,w:17+s,h:16.5+a*.4,r:5,m:"B"},ur(11.4,19.2,1.2,.8,"O"),ur(20.6,19.2,1.2,.8,"O")),h.push(...p(12.9,15.6,1.9,2.6),...p(19.1,15.6,1.9,2.6),n?ur(16,19.6,1.2,.9,"K"):Bn(15.2,19.4,16.8,19.4,.45,"K"))}if(e==="zip"){m=Math.sin(r*1.2)+o*.6,n&&h.push({k:"d",cx:16,cy:27,rx:6.5,ry:5.5,m:"O",ph:Math.floor(r*6)%2}),h.push(ur(16,21.2,6,1.5,"S"),ur(16,18.3,14,3.6,"G"),ur(16,16.7,11,1.6,"B"));let g=Math.floor(r*3)%5;[6,11,16,21,26].forEach((A,w)=>h.push(ur(A,19.3,1,.8,w===g?"O":"K"))),h.push(ur(16,11.5,6.6,6.2,"Q"),Bn(16,9,17.6,6.8,.6,"O"),ur(18,6.4,.9,.9,"O"),ur(16,12.4,4,3.8,"O")),h.push(...p(14.4,12.4,1,1.4,0,.45),...p(17.6,12.4,1,1.4,0,.45),Bn(11.6,9.4,12.6,7.4,.55,"W")),n&&h.push(Bn(22,13.6,22+3.8*Math.cos(u),13.6+3.8*Math.sin(u),.9,"O"))}for(let g of h)g.k==="l"?(g.y1+=m,g.y2+=m):g.cy+=m;return h}function iVn(e,t,r){if(e.k==="e"){let o=t-e.cx,s=r-e.cy;if(e.rot){let c=Math.cos(-e.rot),d=Math.sin(-e.rot);[o,s]=[o*c-s*d,o*d+s*c]}let a=o/e.rx,l=s/e.ry;return a*a+l*l<=1?[a,l]:null}if(e.k==="l"){let o=e.x2-e.x1,s=e.y2-e.y1,a=o*o+s*s||1,l=Math.max(0,Math.min(1,((t-e.x1)*o+(r-e.y1)*s)/a)),c=e.x1+o*l,d=e.y1+s*l;return Math.hypot(t-c,r-d)<=e.r?[(t-c)/e.r,(r-d)/e.r]:null}if(e.k==="r"){let o=t-e.cx,s=r-e.cy,a=Math.max(Math.abs(o)-(e.w/2-e.r),0),l=Math.max(Math.abs(s)-(e.h/2-e.r),0);return Math.hypot(a,l)<=e.r?[o/(e.w/2),s/(e.h/2)]:null}let n=(t-e.cx)/e.rx,i=(r-e.cy)/e.ry;return n*n+i*i<=1&&(Math.floor(t)+Math.floor(r)+e.ph)%2===0&&Math.abs(t-e.cx)<=1+(r-(e.cy-e.ry))*.6?[0,0]:null}function NWt(e,t){return"#"+e.slice(1).match(/../g).map(r=>{let n=parseInt(r,16),i=t>=1?n+(255-n)*(t-1):n*t;return Math.round(Math.max(0,Math.min(255,i))).toString(16).padStart(2,"0")}).join("")}function yHe(e,t,r,n,i=16){let o=nVn(e,t,r),s=32/i,a=[NWt(n,1.3),n,NWt(n,.7)],l=[];for(let c=0;c<i;c++){let d=[];for(let u=0;u<i;u++){let p=null;for(let f=o.length-1;f>=0;f--){let h=o[f],m=iVn(h,(u+.5)*s,(c+.5)*s);if(!m)continue;let g=h.m==="O"?a:oVn[h.m],A=-(m[0]*.6+m[1]*.8);p=g.length===1?g[0]:g[A>.42?0:A<-.38?2:1];break}d.push(p)}l.push(d)}return l}function ehe(e,t,r,n,i={}){let o=i.size??16,s=i.color??!0,a=yHe(e,t,r,n,o),l=[];for(let c=0;c<o;c+=2){let d="";for(let u=0;u<o;u++){let p=a[c][u],f=a[c+1]?.[u]??null;!p&&!f?d+=" ":s?p&&f?d+=p===f?ee.hex(p)("\u2588"):ee.compose(ee.hex(p),ee.bgHex(f))("\u2580"):d+=p?ee.hex(p)("\u2580"):ee.hex(f)("\u2584"):d+=p&&f?"\u2588":p?"\u2580":"\u2584"}l.push(d)}return l}var Ca,rVn,ur,Bn,oVn,kP=Ae(()=>{"use strict";gd();Qo();Xd();Ca=[{id:"bean",name:"Bean",blurb:"Round, one antenna, always curious."},{id:"ocu",name:"Ocu",blurb:"One big eye and two hooked horns."},{id:"squee",name:"Squee",blurb:"A dome on four swaying tentacles."},{id:"greeb",name:"Greeb",blurb:"The classic visitor. The quiet one."},{id:"quad",name:"Quad",blurb:"Wears the mark's four hooked arms."},{id:"zip",name:"Zip",blurb:"Rides a saucer with chasing lights."}];rVn=Ca[eVn(Ca.length)].id;ur=(e,t,r,n,i,o=0)=>({k:"e",cx:e,cy:t,rx:r,ry:n,m:i,rot:o}),Bn=(e,t,r,n,i,o)=>({k:"l",x1:e,y1:t,x2:r,y2:n,r:i,m:o});oVn={B:["#FAF9F4","#E4E3DC","#B4B3AA"],C:["#FFFFFF","#F6F5F0","#DAD9D1"],G:["#D2D1CA","#A3A29B","#6F6E68"],Q:["#4A4A48","#2E2E2D","#1E1E1D"],K:["#0B0B0B"],W:["#FFFFFF"],S:["#B4B3AA"]}});var Ce,Zi=Ae(()=>{"use strict";Ce="0.5.193"});import{createHash as JWn,randomUUID as fhe}from"node:crypto";import*as fi from"node:fs/promises";import*as VS from"node:os";import*as Xm from"node:path";import{homedir as j6t,platform as zWn,release as XWn}from"node:os";import{resolve as $6t}from"node:path";import{randomUUID as s6n}from"node:crypto";import{hostname as a6n}from"node:os";import{randomUUID as l6n}from"node:crypto";import{constants as U6t}from"node:fs";import{lstat as Ahe,mkdir as Q6t,open as zHe,realpath as YHe}from"node:fs/promises";import{dirname as WHe,isAbsolute as q6t,join as XHe,relative as c6n,resolve as d6n,sep as u6n}from"node:path";import{createHash as p6n}from"node:crypto";import{createHash as f6n}from"node:crypto";function YWn(){let e=process.env.XENO_AGENT_HOME?.trim();return e?$6t(e):$6t(j6t(),".xeno-agent")}function M6t(e){if(typeof e!="string"||!e.trim()||e.length>512)throw new G6t("INVALID","Invalid quota identity.");return e}function H6t(e){let t=r=>({id:M6t(r?.id),generation:M6t(r?.generation)});if(!e||e.agent&&!e.team)throw new G6t("INVALID","A child quota scope requires its complete ancestry.");return{workspace:t(e.workspace),...e.team?{team:t(e.team)}:{},...e.agent?{agent:t(e.agent)}:{},...e.goal!==void 0?{goal:t(e.goal)}:{}}}function O6t(e){return JSON.stringify(H6t(e))}function Mr(e,t,r=16384){let n=e.trim();if(!n||n.length>r)throw new Te("INVALID",`${t} must be non-empty and no longer than ${r} characters`);return n}function mhe(e,t){return[...new Set((e??[]).map(r=>Mr(r,t)))]}function L6t(e){if(e===void 0)return;if(!e||typeof e!="object"||Array.isArray(e))throw new Te("INVALID","Goal limits must be an object when provided");let t={};for(let[r,n]of Object.entries(e)){if(r!=="maxIterations"&&r!=="maxTokens"&&r!=="maxWallClockMs")throw new Te("INVALID","Unknown goal limit");if(n!==void 0){if(!Number.isSafeInteger(n)||n<=0)throw new Te("INVALID",`${r} must be a positive safe integer when provided`);t[r]=n}}return t}function n6n(e){if(e){if(e.kind!=="fixed-interval"&&e.kind!=="dynamic")throw new Te("INVALID","schedule.kind must be fixed-interval or dynamic");if(e.kind==="fixed-interval"&&(!Number.isSafeInteger(e.intervalMs)||(e.intervalMs??0)<=0))throw new Te("INVALID","Fixed-interval schedules require a positive safe intervalMs");if(e.intervalMs!==void 0&&(!Number.isSafeInteger(e.intervalMs)||e.intervalMs<=0))throw new Te("INVALID","schedule.intervalMs must be a positive safe integer when provided");for(let t of["nextRunAt","expiresAt"]){let r=e[t];if(r!==void 0&&!Number.isFinite(Date.parse(r)))throw new Te("INVALID",`schedule.${t} must be an ISO timestamp when provided`)}return Yd(e)}}function Yd(e){return structuredClone(e)}function SI(e){let t=Date.parse(e);return Number.isFinite(t)?t:0}function ghe(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function i6n(e){return{summary:"Goal created; work has not started.",completedTaskCount:0,totalTaskCount:0,outstanding:[],decisions:[],updatedAt:e}}function o6n(){return{status:"pending",criteria:[],evidence:[]}}function F6t(e){return JWn("sha256").update(e).digest("hex")}function KHe(e){return{algorithm:"sha256",value:p6n("sha256").update(e).digest("hex")}}function z6t(e){if(typeof e!="string"||!e||e.length>2048||q6t(e)||/[\\:*?"<>|]/.test(e)||[...e].some(r=>r.charCodeAt(0)<32))throw new Error("Invalid portable snapshot path");let t=e.split("/");if(t.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(t.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 e}function X6t(e){return KHe(JSON.stringify([e.schemaVersion,e.sessionId,e.totalBytes,e.files.map(t=>[t.path,t.size,t.sha256,t.executable])])).value}function Y6t(e,t){if(e.schemaVersion!==1||e.sessionId!==t||!Array.isArray(e.files)||e.files.length>V6t||!Number.isSafeInteger(e.totalBytes)||e.totalBytes<0||e.totalBytes>J6t)throw new Error("Invalid handoff snapshot manifest");let r=new Set,n=0;for(let i of e.files){if(z6t(i.path),!Number.isSafeInteger(i.size)||i.size<0||i.size>W6t||!/^[a-f0-9]{64}$/.test(i.sha256)||typeof i.executable!="boolean")throw new Error("Invalid handoff snapshot file");let o=i.path.toLowerCase();if(r.has(o))throw new Error("Snapshot paths collide on Windows");r.add(o),n+=i.size}for(let i of r){let o=i.split("/");for(let s=1;s<o.length;s++)if(r.has(o.slice(0,s).join("/")))throw new Error("Snapshot file conflicts with a directory")}if(n!==e.totalBytes||X6t(e)!==e.digest)throw new Error("Handoff snapshot manifest integrity mismatch")}async function JHe(e,t){let r=e;for(let o of t.split("/"))if(r=XHe(r,o),(await Ahe(r)).isSymbolicLink())throw new Error("Snapshot symlinks are not supported");let n=await YHe(r),i=c6n(e,n);if(i===".."||i.startsWith(`..${u6n}`)||q6t(i))throw new Error("Snapshot path escaped its root");return r}async function K6t(e){if(!e.sessionId||e.sessionId.length>1024||e.paths.length>V6t)throw new Error("Invalid snapshot scope");let t=await YHe(e.root),r=[],n=new Map,i=0;for(let s of[...e.paths].sort()){if(e.signal?.throwIfAborted(),z6t(s),!await e.authorizeFile(s))throw new Error("Snapshot file transfer is not authorized");let a=await JHe(t,s),l=await Ahe(a),c=await zHe(a,U6t.O_RDONLY|(U6t.O_NOFOLLOW??0));try{let d=await c.stat();if(await JHe(t,s),l.ino!==d.ino||l.dev!==d.dev||l.ctimeMs!==d.ctimeMs)throw new Error("Snapshot source was replaced before reading");if(!d.isFile()||d.size>W6t||i+d.size>J6t)throw new Error("Snapshot file or total byte limit exceeded");let u=Buffer.alloc(d.size),p=0;for(;p<u.length;){e.signal?.throwIfAborted();let{bytesRead:g}=await c.read(u,p,u.length-p,p);if(!g)throw new Error("Snapshot source changed while reading");p+=g}let f=await c.stat(),h=await Ahe(a);if(await JHe(t,s),d.size!==f.size||d.mtimeMs!==f.mtimeMs||d.ctimeMs!==f.ctimeMs||h.isSymbolicLink()||h.ino!==d.ino||h.dev!==d.dev)throw new Error("Snapshot source changed while reading");let m=KHe(u).value;r.push({path:s,size:u.length,sha256:m,executable:(d.mode&73)!==0}),n.set(m,u),i+=u.length}finally{await c.close()}}let o={schemaVersion:1,sessionId:e.sessionId,files:r,totalBytes:i,digest:""};return o.digest=X6t(o),Y6t(o,e.sessionId),{manifest:o,blobs:n}}async function Z6t(e){let t=structuredClone(e.manifest);if(Y6t(t,e.sessionId),!await e.authorizeManifest(structuredClone(t)))throw new Error("Snapshot restoration is not authorized");e.signal?.throwIfAborted();let r=d6n(e.destination);if(await YHe(WHe(r))!==WHe(r))throw new Error("Snapshot destination parent must be canonical");try{throw await Ahe(r),new Error("Snapshot destination already exists")}catch(o){if(o.code!=="ENOENT")throw o}let n=`${r}.staging-${l6n()}`;await Q6t(n,{mode:448});for(let o of t.files){e.signal?.throwIfAborted();let s=await e.readBlob(o.sha256,o.size);if(s.byteLength!==o.size||KHe(s).value!==o.sha256)throw new Error("Snapshot blob integrity mismatch; staging retained");let a=XHe(n,...o.path.split("/"));await Q6t(WHe(a),{recursive:!0,mode:448});let l=await zHe(a,"wx",o.executable?448:384);try{await l.writeFile(s),await l.sync()}finally{await l.close()}}e.signal?.throwIfAborted();let i=await zHe(XHe(n,".xeno-handoff-ready"),"wx",384);try{await i.writeFile(JSON.stringify({digest:t.digest,sessionId:t.sessionId})),await i.sync()}finally{await i.close()}return{directory:n,digest:t.digest,files:t.files.length,bytes:t.totalBytes}}function eJt(e){return typeof e=="string"&&h6n.test(e)}function WS(e){return`sha256:${f6n("sha256").update(e).digest("hex")}`}var Te,xcs,Ccs,Tcs,PP,Rcs,G6t,KWn,ZWn,e6n,t6n,hhe,N6t,r6n,D6t,whe,_P,V6t,W6t,J6t,h6n,BP=Ae(()=>{"use strict";Te=class extends Error{constructor(e,t,r={}){super(t),this.code=e,this.details=r,this.name="XenoCoordinationError"}code;details},xcs=zWn(),Ccs=XWn(),Tcs=j6t();PP="[redacted]",Rcs=[[/-----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${PP}`],[/((?:^|[\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${PP}`],[/\b(Bearer|Basic|Token|DPoP)\s+[A-Za-z0-9._~+/=-]{6,}/gi,`$1 ${PP}`],[/\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,PP],[/\beyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}/g,PP],[/([?&#;](?:access_token|refresh_token|id_token|token|key|api[_-]?key|secret|client_secret|password|signature|sig)=)[^&#\s"'<>]+/gi,`$1${PP}`],[/(\b[a-z][a-z0-9+.-]*:\/\/)[^/\s:@"']+:[^/\s@"']+@/gi,`$1${PP}@`]],G6t=class extends Error{constructor(e,t){super(t),this.code=e,this.name="QuotaError"}code;retryable=!1};KWn=3e4,ZWn=3e4,e6n=6e4,t6n=2e4,hhe=new Set(["EACCES","EBUSY","EPERM"]),N6t=[5,10,20,40,80,160,320],r6n=[5,10,20,40,80,160,320],D6t=[1,2,3,4];whe=class{get goalTurnAdmissionVersion(){return 1}rootDirectory;now;idFactory;ownerLeaseMs;lockTimeoutMs;lockStaleMs;maximumEventsPerSession;constructor(e={}){this.rootDirectory=e.rootDirectory??Xm.join(YWn(),"coordination"),this.now=e.now??(()=>new Date().toISOString()),this.idFactory=e.idFactory??(t=>`${t}_${fhe()}`),this.ownerLeaseMs=e.ownerLeaseMs??KWn,this.lockTimeoutMs=e.lockTimeoutMs??ZWn,this.lockStaleMs=e.lockStaleMs??e6n,this.maximumEventsPerSession=e.maximumEventsPerSession??t6n}async getSessionState(e){let t=Mr(e,"sessionId",1024);return Yd(await this.readState(t))}async fenceAdmission(e,t,r){let n=Mr(r.authorityId,"authorityId",512),i=Mr(r.operationId,"operationId",512);if(!Number.isSafeInteger(t)||t<0)throw new Te("INVALID","Expected session version must be a nonnegative safe integer");if(r.action!=="archive"&&r.action!=="delete")throw new Te("INVALID","Unsupported admission fence action");return this.mutate(e,o=>{let s=o.admissionFence;if(s?.authorityId===n&&s.operationId===i&&s.action===r.action)return s;if(o.version!==t)throw new Te("CONFLICT","Session version changed before lifecycle fencing",{expected:t,actual:o.version});if(s?.authorityId===n&&s.action==="archive"&&r.action==="archive")return s;if(s&&!(s.authorityId===n&&s.action==="archive"&&r.action==="delete"))throw new Te("CONFLICT","Another lifecycle fence already owns this session");let a={schemaVersion:1,authorityId:n,operationId:i,action:r.action,createdAt:this.now()};return o.admissionFence=a,o.schemaVersion===1&&(o.schemaVersion=2),this.appendEvent(o,"admission.fenced",{data:{authorityId:n,operationId:i,action:r.action}}),a},!0)}async clearAdmissionFence(e,t,r,n){await this.mutate(e,i=>{this.assertVersion(e,i.version,t);let o=i.admissionFence;if(!o||o.authorityId!==r||o.operationId!==n)throw new Te("CONFLICT","Lifecycle fence identity does not match");if(o.action==="delete")throw new Te("CONFLICT","Deleted session admission cannot be restored");if(i.owner)throw new Te("CONFLICT","Execution ownership must settle before restoration");i.admissionFence=void 0,this.appendEvent(i,"admission.restored",{data:{authorityId:r,operationId:n}})},!0)}async releaseDeadLifecycleOwner(e,t,r,n){await this.mutate(e,i=>{this.assertVersion(e,i.version,t);let o=i.admissionFence;if(!o||o.authorityId!==r||o.operationId!==n)throw new Te("CONFLICT","Lifecycle fence identity does not match");let s=i.owner;if(s){if(s.host!==VS.hostname()||!Number.isInteger(s.processId)||(s.processId??0)<=0||ghe(s.processId))throw new Te("CONFLICT","Execution owner exit has not been proved");i.owner=void 0,this.appendEvent(i,"ownership.released",{ownerId:s.ownerId,data:{epoch:s.epoch,reason:"fenced-local-owner-exited"}})}},!0)}async listSessionStates(){let e=Xm.join(this.rootDirectory,"sessions"),t;try{t=await fi.readdir(e)}catch(r){if(r.code==="ENOENT")return[];throw r}return(await Promise.all(t.filter(r=>r.endsWith(".json")).map(async r=>{try{let n=JSON.parse(await fi.readFile(Xm.join(e,r),"utf8"));return!D6t.includes(n.schemaVersion)||typeof n.sessionId!="string"?void 0:((!Number.isSafeInteger(n.ownershipEpoch)||n.ownershipEpoch<0)&&(n.ownershipEpoch=Math.max(n.owner?.epoch??0,...n.handoffs.map(i=>i.targetLeaseEpoch??i.sourceLeaseEpoch??0))),n)}catch{return}}))).filter(r=>r!==void 0).sort((r,n)=>SI(n.updatedAt)-SI(r.updatedAt)).map(r=>Yd(r))}async createGoal(e){let t=Mr(e.sessionId,"sessionId",1024),r=L6t(e.limits);return this.mutate(t,n=>{let i=n.goals.find(l=>["active","paused","waiting","blocked"].includes(l.status));if(i)throw new Te("CONFLICT",`Session ${t} already has active goal ${i.id}`);let o=this.now(),s=(e.successCriteria??[]).map(l=>typeof l=="string"?{id:this.idFactory("criterion"),description:Mr(l,"successCriteria"),required:!0}:{id:l.id?Mr(l.id,"successCriteria.id",512):this.idFactory("criterion"),description:Mr(l.description,"successCriteria.description"),required:l.required}),a={schemaVersion:1,id:this.idFactory("goal"),version:1,sessionId:t,objective:Mr(e.objective,"objective"),...e.why?{why:Mr(e.why,"why")}:{},successCriteria:s,constraints:mhe(e.constraints,"constraints"),...r?{limits:r}:{},metadata:Yd(e.metadata??{}),status:"active",milestones:[],tasks:[],progress:i6n(o),verification:o6n(),steering:[],createdAt:o,updatedAt:o};return n.goals.push(a),this.appendEvent(n,"goal.created",{goalId:a.id,data:{objective:a.objective}}),a})}async getGoal(e,t){let r=await this.getSessionState(e),n=t?r.goals.find(i=>i.id===t):[...r.goals].reverse().find(i=>["active","paused","waiting","blocked"].includes(i.status));return n?Yd(n):void 0}async updateGoal(e,t,r,n){return this.mutate(e,i=>{let o=this.requireGoal(i,t);if(this.assertVersion(o.id,o.version,r),["completed","cancelled","failed"].includes(o.status))throw new Te("CONFLICT",`Goal ${o.id} is terminal (${o.status})`);let s=o.status!=="active";if(n.status==="active"&&o.status==="blocked"?o.status="active":n.status&&(o.status=n.status),n.objective!==void 0&&(o.objective=Mr(n.objective,"objective")),n.why!==void 0&&(o.why=Mr(n.why,"why")),n.constraints&&(o.constraints=mhe(n.constraints,"constraints")),n.successCriteria&&(o.successCriteria=Yd(n.successCriteria)),n.progress&&(o.progress={...o.progress,...Yd(n.progress),outstanding:mhe(n.progress.outstanding??o.progress.outstanding,"progress.outstanding"),decisions:mhe(n.progress.decisions??o.progress.decisions,"progress.decisions"),updatedAt:this.now()}),n.verification&&(o.verification=Yd(n.verification)),n.metadata&&(o.metadata=Yd(n.metadata)),s&&o.status==="active")for(let a of i.loops.filter(l=>l.goalId===t&&l.kind==="goal-continuation"&&l.status==="running"))a.resumeRequested=!0,a.version+=1,a.updatedAt=this.now();return o.version+=1,o.updatedAt=this.now(),this.appendEvent(i,"goal.updated",{goalId:o.id,data:{status:o.status,version:o.version}}),o},n.status!==void 0&&["paused","cancelled","failed"].includes(n.status))}async addMilestone(e,t,r,n){return this.mutateGoal(e,t,r,(i,o)=>{let s={id:this.idFactory("milestone"),title:Mr(n.title,"milestone.title"),...n.description?{description:Mr(n.description,"milestone.description")}:{},status:i.milestones.some(a=>a.status==="active")?"pending":"active",taskIds:[],createdAt:o,updatedAt:o};i.milestones.push(s),i.progress.currentMilestoneId??=s.id,i.progress.updatedAt=o})}async addTask(e,t,r,n){return this.mutateGoal(e,t,r,(i,o)=>{let s=i.milestones.find(c=>c.id===n.milestoneId);if(!s)throw new Te("NOT_FOUND",`Milestone ${n.milestoneId} was not found`);if(n.parentTaskId&&!i.tasks.some(c=>c.id===n.parentTaskId))throw new Te("NOT_FOUND",`Parent task ${n.parentTaskId} was not found`);let a=[...new Set(n.dependsOn??[])];for(let c of a)if(!i.tasks.some(d=>d.id===c))throw new Te("NOT_FOUND",`Task dependency ${c} was not found`);let l={id:this.idFactory("task"),milestoneId:s.id,...n.parentTaskId?{parentTaskId:n.parentTaskId}:{},title:Mr(n.title,"task.title"),...n.description?{description:Mr(n.description,"task.description")}:{},status:a.length===0?"ready":"pending",...n.assignedAgentId?{assignedAgentId:Mr(n.assignedAgentId,"task.assignedAgentId",512)}:{},...a.length?{dependsOn:a}:{},createdAt:o,updatedAt:o};i.tasks.push(l),s.taskIds.push(l.id),s.updatedAt=o,i.progress.totalTaskCount=i.tasks.length,i.progress.outstanding=i.tasks.filter(c=>c.status!=="completed").map(c=>c.title),i.progress.updatedAt=o})}async updateTask(e,t,r,n,i){return this.mutateGoal(e,t,n,(o,s)=>{let a=o.tasks.find(c=>c.id===r);if(!a)throw new Te("NOT_FOUND",`Task ${r} was not found`);a.status=i.status,i.progress!==void 0&&(a.progress=Mr(i.progress,"task.progress")),i.resultEventId!==void 0&&(a.resultEventId=Mr(i.resultEventId,"task.resultEventId",512)),i.assignedAgentId!==void 0&&(a.assignedAgentId=Mr(i.assignedAgentId,"task.assignedAgentId",512)),a.updatedAt=s,a.status==="completed"&&(a.completedAt=s);let l=o.milestones.find(c=>c.id===a.milestoneId);if(l){let c=o.tasks.filter(d=>d.milestoneId===l.id);c.length>0&&c.every(d=>d.status==="completed")?(l.status="completed",l.completedAt=s):c.some(d=>d.status==="running")?l.status="active":c.some(d=>d.status==="blocked")&&(l.status="blocked"),l.updatedAt=s}for(let c of o.tasks)c.status!=="pending"||!c.dependsOn?.length||c.dependsOn.every(d=>o.tasks.find(u=>u.id===d)?.status==="completed")&&(c.status="ready",c.updatedAt=s);this.recalculateProgress(o,s)})}async steerGoal(e,t,r,n){return this.mutateGoal(e,t,r,(i,o,s)=>{let a=this.idFactory("steer");i.steering.push({id:a,instruction:Mr(n,"instruction"),createdAt:o}),this.appendEvent(s,"goal.steered",{goalId:t,data:{steeringId:a}})},!1)}async consumeGoalSteering(e,t,r){let n=[];return{goal:await this.mutateGoal(e,t,r,(i,o)=>{n=i.steering.filter(s=>!s.consumedAt).map(({id:s,instruction:a,createdAt:l})=>({id:s,instruction:a,createdAt:l}));for(let s of i.steering)s.consumedAt||(s.consumedAt=o)}),instructions:n}}async completeGoal(e,t,r,n){if(n.status!=="passed")throw new Te("VERIFICATION_REQUIRED","Goal completion requires passed verification");return this.mutate(e,i=>{let o=this.requireGoal(i,t);this.assertVersion(o.id,o.version,r);let s=o.successCriteria.filter(c=>c.required),a=s.filter(c=>{let d=n.criteria.find(u=>u.criterionId===c.id);return!d?.satisfied||d.evidence.length===0});if(a.length>0)throw new Te("VERIFICATION_REQUIRED","Required success criteria lack passing evidence",{unmetCriteria:a.map(c=>c.id)});if(s.length===0&&n.evidence.length===0)throw new Te("VERIFICATION_REQUIRED","Goal completion requires at least one durable evidence reference");let l=this.now();return o.status="completed",o.verification=Yd(n),o.verification.verifiedAt??=l,o.completedAt=l,o.updatedAt=l,o.version+=1,this.appendEvent(i,"goal.completed",{goalId:t,data:{evidence:o.verification.evidence}}),o},!0)}async cancelGoal(e,t,r,n){return this.mutate(e,i=>{let o=this.requireGoal(i,t);if(this.assertVersion(o.id,o.version,r),["completed","cancelled","failed"].includes(o.status))return o;o.status="cancelled",o.updatedAt=this.now(),o.version+=1,this.appendEvent(i,"goal.cancelled",{goalId:t,data:{reason:Mr(n,"reason")}});for(let s of i.loops.filter(a=>a.goalId===t&&["running","paused","waiting"].includes(a.status)))s.status="stopped",s.resumeRequested!==void 0&&(s.resumeRequested=!1),s.stopReason=`Goal cancelled: ${n}`,s.stoppedAt=this.now(),s.updatedAt=s.stoppedAt,s.version+=1;return o},!0)}async startLoop(e){return this.mutate(e.sessionId,t=>this.createLoopRecord(t,e))}createLoopRecord(e,t){if(t.kind==="goal-continuation"&&!t.goalId)throw new Te("INVALID","Goal-continuation loops require a goalId");if(t.goalId){let s=this.requireGoal(e,t.goalId);if(["completed","cancelled","failed"].includes(s.status))throw new Te("CONFLICT",`Cannot start a loop for terminal goal ${s.id}`)}if(t.kind==="scheduled"&&!t.schedule)throw new Te("INVALID","Scheduled loops require schedule metadata");if(t.kind!=="scheduled"&&t.schedule)throw new Te("INVALID","Only scheduled loops may carry schedule metadata");let r=n6n(t.schedule),n=e.loops.find(s=>s.goalId===t.goalId&&s.kind===t.kind&&["running","paused","waiting"].includes(s.status));if(n)throw new Te("CONFLICT",`Loop ${n.id} is already active`);let i=this.now(),o={schemaVersion:1,id:this.idFactory("loop"),version:1,sessionId:e.sessionId,...t.goalId?{goalId:t.goalId}:{},kind:t.kind,status:"running",...t.activity?{currentActivity:Mr(t.activity,"activity")}:{},iterations:[],...r?{schedule:r}:{},createdAt:i,updatedAt:i};return e.loops.push(o),this.appendEvent(e,"loop.started",{loopId:o.id,goalId:o.goalId,data:{kind:o.kind}}),o}async getLoop(e,t){let r=await this.getSessionState(e),n=t?r.loops.find(i=>i.id===t):[...r.loops].reverse().find(i=>["running","paused","waiting"].includes(i.status));return n?Yd(n):void 0}async beginLoopIteration(e,t,r,n,i){return this.mutateLoop(e,t,r,(o,s,a)=>{this.appendLoopIteration(a,o,s,n,i)},!1)}appendLoopIteration(e,t,r,n,i,o=!1){if(t.status!=="running")throw new Te("CONFLICT",`Loop ${t.id} is ${t.status}`);if(t.goalId){let l=this.requireGoal(e,t.goalId);this.isCliGoal(l)&&this.initializeGoalTurnAccounting(e,l)}if(this.assertGoalIterationAdmission(e,t,r,o),t.iterations.some(l=>l.status==="running"))throw new Te("CONFLICT",`Loop ${t.id} already has a running iteration`);let s=(t.iterations.at(-1)?.number??0)+1;t.currentActivity=Mr(n,"activity");let a={number:s,startedAt:r,status:"running",activity:t.currentActivity,...t.goalId&&e.goalTurnAccounting?.[t.goalId]?{goalAccountingVersion:1}:{},...i?{taskId:Mr(i,"taskId",512)}:{}};return t.iterations.push(a),t.resumeRequested!==void 0&&(t.resumeRequested=!1),this.appendEvent(e,"loop.iteration",{loopId:t.id,goalId:t.goalId,data:{number:s,phase:"started",activity:t.currentActivity}}),a}async admitGoalTurn(e){return this.admitGoalTurnWithOwner(e)}async admitQuotaGoalTurn(e,t,r,n){let i=H6t(r),o=await this.getGoal(e.sessionId,e.goalId);if(!o||o.sessionId!==e.sessionId||o.limits?.maxTokens===void 0)throw new Te("BUDGET_UNAVAILABLE","The exact token-bounded goal is unavailable for quota admission");if(this.isCliGoal(o)&&o.metadata["cli.tokenQuotaVersion"]!==1)throw new Te("BUDGET_UNAVAILABLE","Legacy CLI goal token spend is unknown; quota admission requires creation-time provenance");if(i.goal?.id!==o.id||i.goal.generation!==o.createdAt)throw new Te("BUDGET_UNAVAILABLE","Quota scope does not identify this durable goal generation");let s=await t.policy(i);if(!s||O6t(s.scope)!==O6t(i)||s.limits.tokensLifetime===void 0||s.limits.tokensLifetime===null||s.limits.tokensLifetime>o.limits.maxTokens)throw new Te("BUDGET_UNAVAILABLE","Goal quota policy is absent or wider than the goal's explicit token limit");let a=await t.remainingTokens(i);if(a===null)throw new Te("BUDGET_UNAVAILABLE","Goal token accounting has no durable remaining allowance");if(a<1)throw new Te("BUDGET_EXCEEDED","Goal token allowance is exhausted");return this.admitGoalTurnWithOwner(e,n,{goalId:o.id,createdAt:o.createdAt,maximum:o.limits.maxTokens})}async admitOwnedGoalTurn(e,t){if(!t||!Number.isSafeInteger(t.epoch)||t.epoch<1)throw new Te("INVALID","An exact execution ownership epoch is required");return this.admitGoalTurnWithOwner(e,{...t})}async admitGoalTurnWithOwner(e,t,r){let n=Mr(e.requestId,"requestId",512),i=this.goalTurnHash(e.requestHash);return this.mutate(e.sessionId,o=>{if(t){let d=this.requireOwner(o,t.ownerId,t.leaseId);if(d.epoch!==t.epoch)throw new Te("NOT_OWNER","Execution ownership epoch changed");if(this.ownerExpired(d,this.now()))throw new Te("LEASE_EXPIRED","Execution ownership expired");if(o.handoffs.some(u=>["prepared","available"].includes(u.status)&&u.sourceLeaseEpoch===d.epoch)||o.handoffs.some(u=>u.status==="claimed"&&u.targetLeaseEpoch===d.epoch))throw new Te("UNSAFE_HANDOFF","Execution handoff has not settled")}let s=this.requireGoal(o,e.goalId);if(r&&(s.id!==r.goalId||s.createdAt!==r.createdAt||s.limits?.maxTokens!==r.maximum))throw new Te("BUDGET_UNAVAILABLE","Goal token limit changed after quota verification");for(let d of o.loops.filter(u=>u.goalId===s.id)){let u=d.iterations.find(p=>p.goalTurn?.requestId===n);if(u){if(u.goalTurn?.requestHash!==i)throw new Te("CONFLICT","Goal turn identity was reused for different work");return{...this.goalTurnState(o,s,d,u),admitted:!1}}}if(this.assertVersion(s.id,s.version,e.expectedGoalVersion),s.status!=="active")throw new Te("CONFLICT",`Goal ${s.id} is ${s.status}`);let a=[...o.loops].reverse().find(d=>d.goalId===s.id&&d.kind==="goal-continuation");if(e.expectedLoopId!==void 0){if(!a||a.id!==e.expectedLoopId)throw new Te("CONFLICT","Goal continuation loop changed before admission");this.assertVersion(a.id,a.version,e.expectedLoopVersion??-1)}else if(e.expectedLoopVersion!==void 0)throw new Te("INVALID","A goal turn loop version requires its exact loop ID");if(a&&a.status!=="running")throw new Te("CONFLICT",`Goal loop ${a.id} is ${a.status}; resume or start it explicitly`);this.initializeGoalTurnAccounting(o,s),a??=this.createLoopRecord(o,{sessionId:o.sessionId,goalId:s.id,kind:"goal-continuation"});let l=this.now(),c=this.appendLoopIteration(o,a,l,"Interactive goal turn",void 0,r!==void 0);if(e.executionKind!==void 0&&e.executionKind!=="local-sdk"&&e.executionKind!=="external")throw new Te("INVALID","Unknown goal execution lane");return c.goalTurn={requestId:n,requestHash:i,executor:e.executionKind==="local-sdk"?{kind:"local-sdk",processId:process.pid,host:VS.hostname()}:{kind:"external"}},a.version+=1,a.updatedAt=l,{...this.goalTurnState(o,s,a,c),admitted:!0}},!1,o=>o.admitted)}async getGoalTurnState(e,t,r){let n=await this.getSessionState(e),i=t?n.goals.find(l=>l.id===t):[...n.goals].reverse().find(l=>["active","paused","waiting","blocked"].includes(l.status));if(!i)return;let o=n.loops.filter(l=>l.goalId===i.id),s=r?o.find(l=>l.iterations.some(c=>c.goalTurn?.requestId===r)):[...o].reverse().find(l=>l.kind==="goal-continuation"),a=r?s?.iterations.find(l=>l.goalTurn?.requestId===r):s?.iterations.at(-1);if(r&&!a)throw new Te("NOT_FOUND","Goal turn was not found");return this.goalTurnState(n,i,s,a)}async finishGoalTurn(e){if(!["completed","failed","interrupted"].includes(e.status))throw new Te("INVALID","Invalid goal turn outcome");let t=this.goalTurnHash(e.requestHash);return this.mutate(e.sessionId,r=>{let n=this.requireGoal(r,e.goalId),i=r.loops.find(s=>s.goalId===n.id&&s.iterations.some(a=>a.goalTurn?.requestId===e.requestId)),o=i?.iterations.find(s=>s.goalTurn?.requestId===e.requestId);if(!i||!o)throw new Te("NOT_FOUND","Goal turn was not found");if(o.goalTurn?.requestHash!==t)throw new Te("CONFLICT","Goal turn settlement identity does not match");return o.status==="running"&&(this.settleLoopIteration(r,i,o,this.now(),{status:n.status==="cancelled"||["stopped","failed"].includes(i.status)?"interrupted":e.status}),i.version+=1,i.updatedAt=this.now()),this.goalTurnState(r,n,i,o)},!0)}async recoverGoalTurn(e,t,r){return this.mutate(e,n=>{let i=this.requireGoal(n,t),o=n.loops.find(a=>a.goalId===t&&a.iterations.some(l=>l.goalTurn?.requestId===r)),s=o?.iterations.find(a=>a.goalTurn?.requestId===r);if(!o||!s)throw new Te("NOT_FOUND","Goal turn was not found");if(s.status==="running"){if(!this.goalTurnOwnerExited(s))throw new Te("NOT_OWNER","The original local goal executor has not been proved exited; external execution requires reconciliation");this.settleLoopIteration(n,o,s,this.now(),{status:"interrupted",error:"Original local SDK executor exited; inspect persisted results before retrying work"}),o.resumeRequested=i.status==="active"&&o.status==="running",o.version+=1,o.updatedAt=this.now()}return this.goalTurnState(n,i,o,s)},!0)}async finishLoopIteration(e,t,r,n){return this.mutateLoop(e,t,r,(i,o,s)=>{let a=[...i.iterations].reverse().find(l=>l.status==="running");if(!a)throw new Te("CONFLICT",`Loop ${i.id} has no running iteration`);this.settleLoopIteration(s,i,a,o,n)},!1,!0)}settleLoopIteration(e,t,r,n,i){r.status=i.status,r.completedAt=n,i.verificationEventId&&(r.verificationEventId=Mr(i.verificationEventId,"verificationEventId",512)),i.error&&(r.error=Mr(i.error,"error")),t.status=["stopped","completed","failed"].includes(t.status)?t.status:e.admissionFence?"paused":i.nextStatus??(t.status==="paused"||t.status==="waiting"?t.status:"running"),this.appendEvent(e,"loop.iteration",{loopId:t.id,goalId:t.goalId,data:{number:r.number,phase:"finished",status:i.status}})}async setLoopStatus(e,t,r,n,i){return this.mutateLoop(e,t,r,(o,s,a)=>{let l=o.status;if(["stopped","completed","failed"].includes(l))throw new Te("CONFLICT",`Loop ${o.id} is terminal (${l})`);let c=[...o.iterations].reverse().find(u=>u.status==="running");if(c&&n==="completed")throw new Te("CONFLICT",`Loop ${o.id} cannot complete while iteration ${c.number} is running`);c&&(n==="stopped"||n==="failed")&&(c.status=n==="failed"?"failed":"interrupted",c.completedAt=s,c.error=Mr(i??n,"reason")),o.status=n,o.kind==="goal-continuation"&&(o.resumeRequested=n==="running"),["stopped","completed","failed"].includes(n)&&(o.stoppedAt=s,o.stopReason=Mr(i??n,"reason"));let d=n==="paused"?"loop.paused":n==="waiting"?"loop.waiting":n==="running"&&(l==="paused"||l==="waiting")?"loop.resumed":n==="completed"?"loop.completed":n==="failed"?"loop.failed":"loop.stopped";this.appendEvent(a,d,{loopId:t,goalId:o.goalId,data:{previous:l,status:n,...i?{reason:i}:{}}})},!1,n!=="running"&&n!=="waiting")}async acquireOwnership(e,t,r={}){return this.mutate(e,n=>{let i=this.now();if(n.owner&&!this.ownerExpired(n.owner,i)){if(n.owner.ownerId===t&&r.processId!==void 0&&n.owner.processId===r.processId&&(r.host===void 0||n.owner.host===r.host))return n.owner;throw new Te("CONFLICT",`Session ${e} is owned by ${n.owner.ownerId}`,{owner:n.owner})}let o=n.owner&&this.ownerExpired(n.owner,i)?n.owner:void 0;if(o)for(let l of n.handoffs.filter(c=>c.status==="claimed"&&c.claimedBy===o.ownerId&&c.targetLeaseEpoch===o.epoch))l.status="failed",l.failureReason=`Claimed owner ${o.ownerId} lost its execution lease before completing the handoff.`,l.failedAt=i,l.updatedAt=i,l.version+=1,this.appendEvent(n,"handoff.failed",{handoffId:l.id,goalId:l.goalId,loopId:l.loopId,data:{reason:l.failureReason,expiredLeaseId:o.leaseId}});let s=n.ownershipEpoch+1;for(let l of n.handoffs.filter(c=>["prepared","available"].includes(c.status)&&c.sourceLeaseEpoch<s))l.status="failed",l.failureReason="Source ownership epoch was superseded before the handoff was claimed.",l.failedAt=i,l.updatedAt=i,l.version+=1,this.appendEvent(n,"handoff.failed",{handoffId:l.id,data:{epoch:s,reason:l.failureReason}});let a=this.newOwner(t,s,r,i);return n.owner=a,n.ownershipEpoch=s,this.appendEvent(n,"ownership.acquired",{ownerId:t,data:{epoch:s,leaseId:a.leaseId}}),a})}async renewOwnership(e,t,r,n=this.ownerLeaseMs){return this.mutate(e,i=>{let o=this.requireOwner(i,t,r);if(this.ownerExpired(o,this.now()))throw new Te("LEASE_EXPIRED",`Ownership lease ${r} expired`);return o.heartbeatAt=this.now(),o.expiresAt=new Date(SI(o.heartbeatAt)+n).toISOString(),this.appendEvent(i,"ownership.renewed",{ownerId:t,data:{epoch:o.epoch,leaseId:r}}),o})}async recoverExpiredOwnership(e,t,r,n,i=this.ownerLeaseMs){return this.mutate(e,o=>{let s=this.requireOwner(o,t,r);if(s.processId!==n||s.host!==VS.hostname()||!ghe(n))throw new Te("LEASE_EXPIRED",`Ownership lease ${r} expired and cannot be recovered by process ${n}`);let a=this.now(),l=Math.max(0,SI(a)-SI(s.expiresAt));return s.heartbeatAt=a,s.expiresAt=new Date(SI(a)+i).toISOString(),this.appendEvent(o,l>0?"ownership.recovered":"ownership.renewed",{ownerId:t,data:{epoch:s.epoch,leaseId:r,...l>0?{expiredForMs:l}:{}}}),s})}async releaseOwnership(e,t,r){return this.mutate(e,n=>{let i=this.requireOwner(n,t,r);for(let o of n.handoffs.filter(s=>s.status==="claimed"&&s.claimedBy===t&&s.targetLeaseEpoch===i.epoch))o.status="failed",o.failureReason="Target released execution ownership before completing the handoff.",o.failedAt=this.now(),o.updatedAt=o.failedAt,o.version+=1,this.appendEvent(n,"handoff.failed",{handoffId:o.id,ownerId:t,data:{epoch:i.epoch,reason:o.failureReason}});return n.owner=void 0,this.appendEvent(n,"ownership.released",{ownerId:t,data:{epoch:i.epoch}}),i},!0)}async createHandoff(e){let t=!1,r=e.prepareRequestId===void 0?void 0:Mr(e.prepareRequestId,"prepareRequestId",512);return this.mutate(e.sessionId,n=>{let i=this.requireOwner(n,e.sourceOwnerId,e.sourceLeaseId);if(this.ownerExpired(i,this.now()))throw new Te("LEASE_EXPIRED",`Ownership lease ${i.leaseId} expired`);if(r){let c=n.handoffs.find(d=>d.prepareRequestId===r);if(c){if(c.sourceOwnerId!==i.ownerId||c.sourceLeaseEpoch!==i.epoch||c.status!=="available"||c.targetOwnerId!==e.targetOwnerId||c.workspace!==e.workspace||c.goalId!==e.goalId||c.loopId!==e.loopId||c.contextDigest!==e.contextDigest||c.branch!==e.branch||c.currentMilestoneId!==e.currentMilestoneId||c.currentTaskId!==e.currentTaskId||JSON.stringify(c.agentIds)!==JSON.stringify([...new Set(e.agentIds??[])])||JSON.stringify(c.operations)!==JSON.stringify(e.operations??[]))throw new Te("CONFLICT","Prepare identity was reused for different work or ownership");return t=!0,c}}let o=(e.operations??[]).filter(c=>c.status==="running"&&c.sideEffecting);if(o.length>0)throw new Te("UNSAFE_HANDOFF","Running side-effecting operations must settle before execution handoff",{operationIds:o.map(c=>c.operationId)});if(e.goalId&&this.requireGoal(n,e.goalId),e.loopId&&!n.loops.some(c=>c.id===e.loopId))throw new Te("NOT_FOUND",`Loop ${e.loopId} was not found`);let s=n.handoffs.find(c=>["prepared","available","claimed"].includes(c.status));if(s)throw new Te("CONFLICT",`Handoff ${s.id} is already active`);let a=this.now(),l={schemaVersion:1,id:this.idFactory("handoff"),version:1,sessionId:n.sessionId,...e.goalId?{goalId:e.goalId}:{},...e.loopId?{loopId:e.loopId}:{},status:"available",sourceOwnerId:i.ownerId,...r?{prepareRequestId:r}:{},...e.targetOwnerId?{targetOwnerId:Mr(e.targetOwnerId,"targetOwnerId",512)}:{},sourceLeaseEpoch:i.epoch,...e.workspace?{workspace:Mr(e.workspace,"workspace",32768)}:{},...e.branch?{branch:Mr(e.branch,"branch",1024)}:{},...e.currentMilestoneId?{currentMilestoneId:e.currentMilestoneId}:{},...e.currentTaskId?{currentTaskId:e.currentTaskId}:{},agentIds:[...new Set(e.agentIds??[])],operations:Yd(e.operations??[]),...e.contextDigest?{contextDigest:Mr(e.contextDigest,"contextDigest",512)}:{},createdAt:a,updatedAt:a};return n.handoffs.push(l),this.appendEvent(n,"handoff.created",{handoffId:l.id,goalId:l.goalId,loopId:l.loopId,ownerId:i.ownerId,data:{targetOwnerId:l.targetOwnerId}}),l},!1,()=>!t)}async claimHandoff(e){let t,r=!1,n=e.claimRequestId===void 0?void 0:Mr(e.claimRequestId,"claimRequestId",512);return{handoff:await this.mutate(e.sessionId,i=>{let o=i.handoffs.find(l=>l.id===e.handoffId);if(!o)throw new Te("NOT_FOUND",`Handoff ${e.handoffId} was not found`);if(o.status!=="available"){let l=i.owner;if(n&&o.claimRequestId===n&&["claimed","completed"].includes(o.status)&&o.claimedBy===e.targetOwnerId&&l?.ownerId===e.targetOwnerId&&l.epoch===o.targetLeaseEpoch&&l.host===e.host&&l.processId===e.processId&&!this.ownerExpired(l,this.now()))return t=l,r=!0,o;throw new Te("CONFLICT",`Handoff ${o.id} is ${o.status}`,{claimedBy:o.claimedBy})}if(o.targetOwnerId&&o.targetOwnerId!==e.targetOwnerId)throw new Te("CONFLICT",`Handoff ${o.id} is reserved for ${o.targetOwnerId}`);let s=i.owner;if(!s||s.ownerId!==o.sourceOwnerId||s.epoch!==o.sourceLeaseEpoch)throw new Te("CONFLICT",`Handoff ${o.id} no longer matches the source ownership epoch`);let a=this.now();return t=this.newOwner(e.targetOwnerId,s.epoch+1,{processId:e.processId,host:e.host,leaseMs:e.leaseMs},a),i.owner=t,i.ownershipEpoch=t.epoch,o.status="claimed",o.claimedBy=e.targetOwnerId,n&&(o.claimRequestId=n),o.targetOwnerId=e.targetOwnerId,o.targetLeaseEpoch=t.epoch,o.claimedAt=a,o.updatedAt=a,o.version+=1,this.appendEvent(i,"handoff.claimed",{handoffId:o.id,goalId:o.goalId,loopId:o.loopId,ownerId:e.targetOwnerId,data:{sourceOwnerId:o.sourceOwnerId,epoch:t.epoch}}),o},!1,()=>!r),owner:Yd(t)}}async completeHandoff(e,t,r,n){let i=!1;return this.mutate(e,o=>{let s=this.requireOwner(o,r,n);if(this.ownerExpired(s,this.now()))throw new Te("LEASE_EXPIRED",`Ownership lease ${n} expired`);let a=o.handoffs.find(l=>l.id===t);if(!a)throw new Te("NOT_FOUND",`Handoff ${t} was not found`);if(a.claimedBy!==r||a.targetLeaseEpoch!==s.epoch||!["claimed","completed"].includes(a.status))throw new Te("CONFLICT",`Handoff ${a.id} cannot be completed by ${r}`);return a.status==="completed"?(i=!0,a):(a.status="completed",a.completedAt=this.now(),a.updatedAt=a.completedAt,a.version+=1,this.appendEvent(o,"handoff.completed",{handoffId:t,goalId:a.goalId,loopId:a.loopId,ownerId:r,data:{epoch:o.owner?.epoch}}),a)},!1,()=>!i)}async cancelHandoff(e,t,r,n){let i=!1;return this.mutate(e,o=>{let s=o.handoffs.find(l=>l.id===t);if(!s)throw new Te("NOT_FOUND",`Handoff ${t} was not found`);if(s.sourceOwnerId!==r)throw new Te("CONFLICT",`Handoff ${t} was not offered by ${r}`);if(s.status==="cancelled")return i=!0,s;if(s.status!=="available"&&s.status!=="prepared")throw new Te("CONFLICT",`Handoff ${t} is ${s.status} and can no longer be cancelled`);let a=this.requireOwner(o,r,n);if(this.ownerExpired(a,this.now()))throw new Te("LEASE_EXPIRED",`Ownership lease ${n} expired`);if(s.sourceLeaseEpoch!==a.epoch)throw new Te("CONFLICT",`Handoff ${t} belongs to an earlier ownership epoch`);return s.status="cancelled",s.cancelledAt=this.now(),s.updatedAt=s.cancelledAt,s.version+=1,this.appendEvent(o,"handoff.cancelled",{handoffId:t,goalId:s.goalId,loopId:s.loopId,ownerId:r,data:{epoch:a.epoch}}),s},!1,()=>!i)}async failHandoff(e,t,r){return this.mutate(e,n=>{let i=n.handoffs.find(o=>o.id===t);if(!i)throw new Te("NOT_FOUND",`Handoff ${t} was not found`);return["completed","cancelled","failed"].includes(i.status)||(i.status="failed",i.failureReason=Mr(r,"reason"),i.failedAt=this.now(),i.updatedAt=i.failedAt,i.version+=1,this.appendEvent(n,"handoff.failed",{handoffId:t,goalId:i.goalId,loopId:i.loopId,data:{reason:i.failureReason}})),i},!0)}async mutateGoal(e,t,r,n,i=!0){return this.mutate(e,o=>{let s=this.requireGoal(o,t);this.assertVersion(s.id,s.version,r);let a=this.now();return n(s,a,o),s.version+=1,s.updatedAt=a,i&&this.appendEvent(o,"goal.updated",{goalId:t,data:{status:s.status,version:s.version}}),s})}async mutateLoop(e,t,r,n,i=!0,o=!1){return this.mutate(e,s=>{let a=s.loops.find(c=>c.id===t);if(!a)throw new Te("NOT_FOUND",`Loop ${t} was not found`);this.assertVersion(a.id,a.version,r);let l=this.now();return n(a,l,s),a.version+=1,a.updatedAt=l,i&&this.appendEvent(s,"loop.iteration",{loopId:t,goalId:a.goalId,data:{status:a.status,version:a.version}}),a},o)}assertGoalIterationAdmission(e,t,r,n=!1){if(!t.goalId)return;let i=this.requireGoal(e,t.goalId);if(i.status!=="active")throw new Te("CONFLICT",`Goal ${i.id} is ${i.status}; no iteration was admitted`);let o=L6t(i.limits);if(o?.maxTokens!==void 0&&!n)throw new Te("BUDGET_UNAVAILABLE","Goal token allowance is not bound to request-level admission; no iteration was admitted",{goalId:i.id,limit:"maxTokens"});if(o?.maxWallClockMs!==void 0){let s=Date.parse(i.createdAt),a=Date.parse(r);if(!Number.isFinite(s)||!Number.isFinite(a)||a<s)throw new Te("BUDGET_UNAVAILABLE","Goal wall-clock allowance cannot be verified",{goalId:i.id,limit:"maxWallClockMs"});if(a-s>=o.maxWallClockMs)throw new Te("BUDGET_EXCEEDED","Goal wall-clock limit reached; no iteration was admitted",{goalId:i.id,limit:"maxWallClockMs",maximum:o.maxWallClockMs})}if(o?.maxIterations!==void 0){let s=e.goalTurnAccounting!==void 0||e.schemaVersion===4?this.resolveGoalTurnAccounting(e,i):void 0;if(s?.coverage==="partial")throw new Te("BUDGET_UNAVAILABLE","Legacy goal turn accounting is incomplete");let a=this.goalIterationCount(e,i)+(s?.baseIterations??0);if(!Number.isSafeInteger(a)||a<0)throw new Te("BUDGET_UNAVAILABLE","Invalid goal iteration accounting");if(a>=o.maxIterations)throw new Te("BUDGET_EXCEEDED","Goal iteration limit reached; no iteration was admitted",{goalId:i.id,limit:"maxIterations",admitted:a,maximum:o.maxIterations})}}isCliGoal(e){return"cli.accountedTurns"in e.metadata||"cli.createdByCliVersion"in e.metadata}goalIterationCount(e,t){let r=0;for(let n of e.loops.filter(i=>i.goalId===t.id)){if(!Array.isArray(n.iterations))throw new Te("BUDGET_UNAVAILABLE","Goal iteration history is unavailable");let i=0;for(let o of n.iterations){if(!o||!Number.isSafeInteger(o.number)||o.number<=i)throw new Te("BUDGET_UNAVAILABLE","Goal iteration history is invalid");i=o.number}if(r+=i,!Number.isSafeInteger(r))throw new Te("BUDGET_UNAVAILABLE","Goal iteration count exceeds its supported range")}return r}resolveGoalTurnAccounting(e,t){let r=e.goalTurnAccounting;if(r!==void 0&&(!r||typeof r!="object"||Array.isArray(r)))throw new Te("BUDGET_UNAVAILABLE","Persisted goal turn accounting is invalid");if(r&&Object.hasOwn(r,t.id)){let a=r[t.id];if(!a||a.schemaVersion!==1||!Number.isSafeInteger(a.baseIterations)||a.baseIterations<0||!["complete","partial"].includes(a.coverage))throw new Te("BUDGET_UNAVAILABLE","Persisted goal turn accounting is invalid");return a}if(e.loops.some(a=>a.goalId===t.id&&a.iterations.some(l=>l.goalTurn||l.goalAccountingVersion)))throw new Te("BUDGET_UNAVAILABLE","Recorded goal turns are missing their protected accounting");let n=this.goalIterationCount(e,t),i=t.metadata["cli.accountedTurns"],o=typeof i=="number"&&Number.isSafeInteger(i)&&i>=0,s=this.isCliGoal(t)&&(!o||i>0&&n>0);return{schemaVersion:1,baseIterations:o&&n===0?i:0,coverage:s?"partial":"complete"}}initializeGoalTurnAccounting(e,t){let r=this.resolveGoalTurnAccounting(e,t);if(r.coverage==="partial"&&t.limits?.maxIterations!==void 0)throw new Te("BUDGET_UNAVAILABLE","Legacy goal turn accounting needs reconciliation before bounded execution");e.goalTurnAccounting??={},Object.defineProperty(e.goalTurnAccounting,t.id,{value:r,writable:!0,enumerable:!0,configurable:!0})}goalTurnHash(e){let t=Mr(e,"requestHash",64).toLowerCase();if(!/^[0-9a-f]{64}$/.test(t))throw new Te("INVALID","Goal turn requestHash must be a SHA-256 digest");return t}goalTurnState(e,t,r,n){let i=this.resolveGoalTurnAccounting(e,t),o=this.goalIterationCount(e,t)+i.baseIterations;if(!Number.isSafeInteger(o))throw new Te("BUDGET_UNAVAILABLE","Goal turn count exceeds its supported range");return Yd({goal:t,admittedTurns:o,accountingCoverage:i.coverage,...r?{loopId:r.id,loopVersion:r.version,loopStatus:r.status,resumeRequested:r.resumeRequested===!0}:{},...n?{iterationNumber:n.number,iterationStatus:n.status,...n.goalTurn?{requestId:n.goalTurn.requestId,requestHash:n.goalTurn.requestHash}:{},canRecover:n.status==="running"&&this.goalTurnOwnerExited(n)}:{}})}goalTurnOwnerExited(e){let t=e.goalTurn?.executor;if(t?.kind!=="local-sdk"||t.host!==VS.hostname()||!Number.isSafeInteger(t.processId)||t.processId<=0)return!1;try{return process.kill(t.processId,0),!1}catch(r){return r.code==="ESRCH"}}recalculateProgress(e,t){let r=e.tasks.filter(n=>n.status==="completed").length;e.progress.completedTaskCount=r,e.progress.totalTaskCount=e.tasks.length,e.progress.percent=e.tasks.length?Math.round(r/e.tasks.length*100):void 0,e.progress.outstanding=e.tasks.filter(n=>!["completed","cancelled"].includes(n.status)).map(n=>n.title),e.progress.updatedAt=t}requireGoal(e,t){let r=e.goals.find(n=>n.id===t);if(!r)throw new Te("NOT_FOUND",`Goal ${t} was not found`);return r}requireOwner(e,t,r){let n=e.owner;if(!n||n.ownerId!==t||n.leaseId!==r)throw new Te("NOT_OWNER",`${t} does not own session ${e.sessionId}`,{owner:n});return n}assertVersion(e,t,r){if(!Number.isInteger(r)||r<1||t!==r)throw new Te("CONFLICT",`Expected ${e} version ${r}, found ${t}`,{expected:r,actual:t})}newOwner(e,t,r,n){let i=r.leaseMs??this.ownerLeaseMs;if(!Number.isSafeInteger(i)||i<1)throw new Te("INVALID","leaseMs must be a positive safe integer");return{ownerId:Mr(e,"ownerId",512),leaseId:this.idFactory("owner"),epoch:t,acquiredAt:n,heartbeatAt:n,expiresAt:new Date(SI(n)+i).toISOString(),...r.processId!==void 0?{processId:r.processId}:{},...r.host?{host:Mr(r.host,"host",512)}:{}}}ownerExpired(e,t){return SI(e.expiresAt)<=SI(t)?!0:e.processId!==void 0&&e.host===VS.hostname()&&!ghe(e.processId)}appendEvent(e,t,r){let n={schemaVersion:1,id:this.idFactory("event"),sequence:(e.events.at(-1)?.sequence??0)+1,type:t,sessionId:e.sessionId,...r.goalId?{goalId:r.goalId}:{},...r.loopId?{loopId:r.loopId}:{},...r.handoffId?{handoffId:r.handoffId}:{},...r.ownerId?{ownerId:r.ownerId}:{},timestamp:this.now(),data:Yd(r.data)};e.events.push(n),e.events.length>this.maximumEventsPerSession&&e.events.splice(0,e.events.length-this.maximumEventsPerSession)}async mutate(e,t,r=!1,n=()=>!0){let i=Mr(e,"sessionId",1024);return this.withSessionLock(i,async()=>{let o=await this.readState(i);if(o.admissionFence&&!r)throw new Te("CONFLICT","Session execution is blocked by a persisted lifecycle fence");let s=o.schemaVersion;this.promoteGoalBudgetEnvelope(o),o.schemaVersion!==s&&await this.writeState(o);let a=t(o);return n(a)&&(o.version+=1,o.updatedAt=this.now(),await this.writeState(o)),Yd(a)})}statePath(e){return Xm.join(this.rootDirectory,"sessions",`${F6t(e)}.json`)}lockPath(e){return`${this.statePath(e)}.lock`}async readState(e){let t=this.statePath(e);try{let r=await fi.readFile(t,"utf8"),n=JSON.parse(r);if(!D6t.includes(n.schemaVersion)||n.sessionId!==e)throw new Te("INVALID",`Coordination state at ${t} does not match session ${e}`);if(n.admissionFence!==void 0){let i=n.admissionFence;if(!i||i.schemaVersion!==1||typeof i.authorityId!="string"||!i.authorityId.trim()||typeof i.operationId!="string"||!i.operationId.trim()||!["archive","delete"].includes(i.action)||!Number.isFinite(Date.parse(i.createdAt)))throw new Te("INVALID","Persisted lifecycle fence is corrupt; execution remains unavailable")}return(!Number.isSafeInteger(n.ownershipEpoch)||n.ownershipEpoch<0)&&(n.ownershipEpoch=Math.max(n.owner?.epoch??0,...n.handoffs.map(i=>i.targetLeaseEpoch??i.sourceLeaseEpoch??0))),n}catch(r){if(r.code!=="ENOENT")throw r;let n=this.now();return{schemaVersion:1,sessionId:e,version:0,ownershipEpoch:0,goals:[],loops:[],handoffs:[],events:[],createdAt:n,updatedAt:n}}}promoteGoalBudgetEnvelope(e){(e.goalTurnAccounting!==void 0||e.loops.some(t=>t.resumeRequested!==void 0||t.iterations.some(r=>r.goalTurn!==void 0)))&&(e.schemaVersion=4),e.schemaVersion<3&&e.goals.some(t=>t.limits!==void 0&&(!t.limits||typeof t.limits!="object"||Array.isArray(t.limits)||Object.keys(t.limits).length>0))&&(e.schemaVersion=3)}async writeState(e){this.promoteGoalBudgetEnvelope(e);let t=this.statePath(e.sessionId),r=Xm.dirname(t);await fi.mkdir(r,{recursive:!0});let n=`${t}.${process.pid}.${fhe()}.tmp`,i=await fi.open(n,"wx");try{await i.writeFile(`${JSON.stringify(e,null,2)}
3248
+ `&&(this.atLineStart=!0);this.writeFn(r)}reset(){this.atLineStart=!0}markLineStarted(){this.atLineStart=!1}},TWt=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],d6=class{interval=null;frameIndex=0;lastLength=0;writeFn;clearFn;constructor(t,r){this.writeFn=t??(n=>{EWt.writeFrame(n,"spinner")}),this.clearFn=r??(()=>{EWt.writeFrame(`\r${" ".repeat(this.lastLength)}\r`,"spinner")})}start(t){this.stop(),this.frameIndex=0,this.interval=setInterval(()=>{let r=TWt[this.frameIndex%TWt.length],n=`${yr(r)} ${Me(t)}`;this.writeFn(`\r${" ".repeat(this.lastLength)}\r${n}`),this.lastLength=t.length+4,this.frameIndex++},80)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null,this.clearFn(),this.lastLength=0)}}});import{randomInt as eVn}from"node:crypto";function tVn(e){return typeof e=="string"&&Ca.some(t=>t.id===e)}function wHe(){let e=TA().uiMascot;return tVn(e)?e:null}function _h(){return wHe()??rVn}function u6(e){wo({uiMascot:e})}function UD(){let e=TA().uiColor;return typeof e=="string"&&Wm(e)?eHe(e):eHe()}function DWt(e=process.stdout){return e.isTTY===!0&&!process.env.NO_COLOR&&process.env.TERM!=="dumb"&&process.env.XENO_ASCII_UI!=="1"&&process.env.XENO_REDUCED_MOTION!=="1"&&!process.env.CI}function nVn(e,t,r){let n=t==="done",i=r%1.6,o=n&&i<.6?-3*Math.sin(Math.PI*i/.6):0,s=n&&i>=.6&&i<.78?.8*Math.sin(Math.PI*(i-.6)/.18):0,a=(Math.sin(r*1.6)+1)/2,l=Math.max(-1,Math.min(1,Math.sin(r*.55)*1.6)),c=r%4.2,d=!n&&(c<.12||c>.26&&c<.36),u=-Math.PI/2.8+.5*Math.sin(r*9),p=(g,A,w,y,b=0,I=.6)=>n?[Bn(g-w,A+.4,g,A-y*.55,I,"K"),Bn(g,A-y*.55,g+w,A+.4,I,"K")]:d?[Bn(g-w,A+y*.35,g+w,A+y*.35,I,"K")]:[ur(g+l*.5,A,w,y,"K",b),ur(g-w*.3+l*.7,A-y*.4,Math.max(.6,w*.36),Math.max(.6,w*.36),"W")],f=g=>g.k==="e"?{...g,cx:32-g.cx,rot:-g.rot}:g.k==="l"?{...g,x1:32-g.x1,x2:32-g.x2}:g,h=[],m=o;if(e==="bean"){h.push(ur(12,28,3.2,1.9,"O"),ur(20,28,3.2,1.9,"O"),Bn(8.5,19,5.6,22.5,1.7,"B")),h.push(n?Bn(23.5,18,23.5+5*Math.cos(u),18+5*Math.sin(u),1.7,"B"):Bn(23.5,19,26.4,22.5,1.7,"B"));let g=n?Math.sin(r*9)*.5:Math.sin(r*1.6)*.4;h.push(Bn(17,10,18.2,5.2,.9,"B"),Bn(18.2,5.2,20.2,3.6,.9,"B"),ur(21.2,3.4+g,1.9,1.9,"O")),h.push(ur(16,18.5-a*.3,9+s,9.8+a*.4-s,"B"),ur(16,22.2,5.2,4.2,"C"),ur(10.2,19.6,1.3,.9,"O"),ur(21.8,19.6,1.3,.9,"O")),h.push(...p(12.6,15.5,2.1,2.9),...p(19.4,15.5,2.1,2.9)),h.push(n?ur(16,19.9,1.4,1.1,"K"):Bn(15,19.6,17,19.6,.45,"K"))}if(e==="ocu"){let g=[Bn(10.5,9.5,8.5,5.5,1.3,"O"),Bn(8.5,5.5,10.5,3.2,1.1,"O")];h.push(...g,...g.map(f),ur(11.5,27.5,3,1.8,"B"),ur(20.5,27.5,3,1.8,"B"),Bn(7,18,4.5,21.5,1.6,"B")),h.push(n?Bn(25,17,25+4.5*Math.cos(u),17+4.5*Math.sin(u),1.6,"B"):Bn(25,18,27.5,21.5,1.6,"B")),h.push(ur(16,17.5-a*.3,10+s,10+a*.4-s,"B")),n?h.push(Bn(11.5,17,16,13.5,.75,"K"),Bn(16,13.5,20.5,17,.75,"K")):d?h.push(Bn(11.5,16.8,20.5,16.8,.75,"K")):h.push(ur(16,16,4.8,4.3,"C"),ur(16+l*1.4,16.4,2.8,2.8,"O"),ur(16+l*1.6,16.4,1.3,1.3,"K"),ur(15+l*1.4,15,.8,.8,"W")),h.push(n?ur(16,23,1.8,1.2,"K"):Bn(14.5,23,17.5,23,.5,"K"))}if(e==="squee"){for(let g=0;g<4;g++){let A=9.8+g*4.13,w=g<2?-1:1;if(n&&g===3){let b=A+6*Math.cos(u),I=19+6*Math.sin(u);h.push(Bn(A,19,b,I,1.6,"B"),ur(b,I,1.5,1.5,"O"));continue}let y=Math.sin(r*1.4+g*1.1)*1.3;h.push(Bn(A,19,A+y,25,1.6,"B"),Bn(A+y,25,A+y+w*2.2,26.8,1.3,"O"))}h.push(ur(16,18.5,8.6,2.6,"B"),ur(16,12.5-a*.3,9.2+s,8.6+a*.4,"B"),ur(11.5,8.2,1.1,1,"S"),ur(20.5,7.5,1.4,1.2,"S"),ur(16,5.8,.9,.8,"S")),h.push(ur(10.4,16.4,1.2,.8,"O"),ur(21.6,16.4,1.2,.8,"O"),...p(12.6,13.5,1.9,2.5),...p(19.4,13.5,1.9,2.5)),h.push(n?ur(16,17.2,1.2,.9,"K"):Bn(15.2,17,16.8,17,.45,"K"))}if(e==="greeb"){let g=[Bn(12.5,5.5,10.5,2.4,.8,"B"),ur(10,2,1.5,1.5,"O")];h.push(...g,...g.map(f),ur(13.5,29,2.2,1.4,"B"),ur(18.5,29,2.2,1.4,"B"),Bn(12,23,9.5,26,1.1,"B")),h.push(n?Bn(20,22.5,20+4*Math.cos(u),22.5+4*Math.sin(u),1.1,"B"):Bn(20,23,22.5,26,1.1,"B")),h.push(ur(16,24.5,4.6,4.2,"B"),ur(16,16.5,5.6,4.4,"B"),ur(16,11.5-a*.3,10.2+s,8.2+a*.4,"B")),h.push(...p(11.3,12.8,3.4,2.1,.45,.7),...p(20.7,12.8,3.4,2.1,-.45,.7)),h.push(n?ur(16,18.4,1,.8,"K"):Bn(15.4,18.4,16.6,18.4,.4,"K"))}if(e==="quad"){let g=y=>y<.5?4*y*y*y:1-Math.pow(-2*y+2,3)/2,A=(n?90*(Math.floor(r/.8)+g(Math.min(1,r%.8/.5))):5*Math.sin(r*1.2))*Math.PI/180,w=(y,b,I)=>{let v=y-16,E=b-16.5;return[16+v*Math.cos(I)-E*Math.sin(I),16.5+v*Math.sin(I)+E*Math.cos(I)]};for(let y=0;y<4;y++){let b=A+y*Math.PI/2,I=w(10.5,11,b),v=w(6.6,7.1,b),E=w(6.6,10.2,b);h.push(Bn(I[0],I[1],v[0],v[1],1.7,"B"),Bn(v[0],v[1],E[0],E[1],1.5,"B"),ur(E[0],E[1],1.45,1.45,"O"))}h.push({k:"r",cx:16,cy:16.5-a*.2,w:17+s,h:16.5+a*.4,r:5,m:"B"},ur(11.4,19.2,1.2,.8,"O"),ur(20.6,19.2,1.2,.8,"O")),h.push(...p(12.9,15.6,1.9,2.6),...p(19.1,15.6,1.9,2.6),n?ur(16,19.6,1.2,.9,"K"):Bn(15.2,19.4,16.8,19.4,.45,"K"))}if(e==="zip"){m=Math.sin(r*1.2)+o*.6,n&&h.push({k:"d",cx:16,cy:27,rx:6.5,ry:5.5,m:"O",ph:Math.floor(r*6)%2}),h.push(ur(16,21.2,6,1.5,"S"),ur(16,18.3,14,3.6,"G"),ur(16,16.7,11,1.6,"B"));let g=Math.floor(r*3)%5;[6,11,16,21,26].forEach((A,w)=>h.push(ur(A,19.3,1,.8,w===g?"O":"K"))),h.push(ur(16,11.5,6.6,6.2,"Q"),Bn(16,9,17.6,6.8,.6,"O"),ur(18,6.4,.9,.9,"O"),ur(16,12.4,4,3.8,"O")),h.push(...p(14.4,12.4,1,1.4,0,.45),...p(17.6,12.4,1,1.4,0,.45),Bn(11.6,9.4,12.6,7.4,.55,"W")),n&&h.push(Bn(22,13.6,22+3.8*Math.cos(u),13.6+3.8*Math.sin(u),.9,"O"))}for(let g of h)g.k==="l"?(g.y1+=m,g.y2+=m):g.cy+=m;return h}function iVn(e,t,r){if(e.k==="e"){let o=t-e.cx,s=r-e.cy;if(e.rot){let c=Math.cos(-e.rot),d=Math.sin(-e.rot);[o,s]=[o*c-s*d,o*d+s*c]}let a=o/e.rx,l=s/e.ry;return a*a+l*l<=1?[a,l]:null}if(e.k==="l"){let o=e.x2-e.x1,s=e.y2-e.y1,a=o*o+s*s||1,l=Math.max(0,Math.min(1,((t-e.x1)*o+(r-e.y1)*s)/a)),c=e.x1+o*l,d=e.y1+s*l;return Math.hypot(t-c,r-d)<=e.r?[(t-c)/e.r,(r-d)/e.r]:null}if(e.k==="r"){let o=t-e.cx,s=r-e.cy,a=Math.max(Math.abs(o)-(e.w/2-e.r),0),l=Math.max(Math.abs(s)-(e.h/2-e.r),0);return Math.hypot(a,l)<=e.r?[o/(e.w/2),s/(e.h/2)]:null}let n=(t-e.cx)/e.rx,i=(r-e.cy)/e.ry;return n*n+i*i<=1&&(Math.floor(t)+Math.floor(r)+e.ph)%2===0&&Math.abs(t-e.cx)<=1+(r-(e.cy-e.ry))*.6?[0,0]:null}function NWt(e,t){return"#"+e.slice(1).match(/../g).map(r=>{let n=parseInt(r,16),i=t>=1?n+(255-n)*(t-1):n*t;return Math.round(Math.max(0,Math.min(255,i))).toString(16).padStart(2,"0")}).join("")}function yHe(e,t,r,n,i=16){let o=nVn(e,t,r),s=32/i,a=[NWt(n,1.3),n,NWt(n,.7)],l=[];for(let c=0;c<i;c++){let d=[];for(let u=0;u<i;u++){let p=null;for(let f=o.length-1;f>=0;f--){let h=o[f],m=iVn(h,(u+.5)*s,(c+.5)*s);if(!m)continue;let g=h.m==="O"?a:oVn[h.m],A=-(m[0]*.6+m[1]*.8);p=g.length===1?g[0]:g[A>.42?0:A<-.38?2:1];break}d.push(p)}l.push(d)}return l}function ehe(e,t,r,n,i={}){let o=i.size??16,s=i.color??!0,a=yHe(e,t,r,n,o),l=[];for(let c=0;c<o;c+=2){let d="";for(let u=0;u<o;u++){let p=a[c][u],f=a[c+1]?.[u]??null;!p&&!f?d+=" ":s?p&&f?d+=p===f?ee.hex(p)("\u2588"):ee.compose(ee.hex(p),ee.bgHex(f))("\u2580"):d+=p?ee.hex(p)("\u2580"):ee.hex(f)("\u2584"):d+=p&&f?"\u2588":p?"\u2580":"\u2584"}l.push(d)}return l}var Ca,rVn,ur,Bn,oVn,kP=Ae(()=>{"use strict";gd();Qo();Xd();Ca=[{id:"bean",name:"Bean",blurb:"Round, one antenna, always curious."},{id:"ocu",name:"Ocu",blurb:"One big eye and two hooked horns."},{id:"squee",name:"Squee",blurb:"A dome on four swaying tentacles."},{id:"greeb",name:"Greeb",blurb:"The classic visitor. The quiet one."},{id:"quad",name:"Quad",blurb:"Wears the mark's four hooked arms."},{id:"zip",name:"Zip",blurb:"Rides a saucer with chasing lights."}];rVn=Ca[eVn(Ca.length)].id;ur=(e,t,r,n,i,o=0)=>({k:"e",cx:e,cy:t,rx:r,ry:n,m:i,rot:o}),Bn=(e,t,r,n,i,o)=>({k:"l",x1:e,y1:t,x2:r,y2:n,r:i,m:o});oVn={B:["#FAF9F4","#E4E3DC","#B4B3AA"],C:["#FFFFFF","#F6F5F0","#DAD9D1"],G:["#D2D1CA","#A3A29B","#6F6E68"],Q:["#4A4A48","#2E2E2D","#1E1E1D"],K:["#0B0B0B"],W:["#FFFFFF"],S:["#B4B3AA"]}});var Ce,Zi=Ae(()=>{"use strict";Ce="0.5.194"});import{createHash as JWn,randomUUID as fhe}from"node:crypto";import*as fi from"node:fs/promises";import*as VS from"node:os";import*as Xm from"node:path";import{homedir as j6t,platform as zWn,release as XWn}from"node:os";import{resolve as $6t}from"node:path";import{randomUUID as s6n}from"node:crypto";import{hostname as a6n}from"node:os";import{randomUUID as l6n}from"node:crypto";import{constants as U6t}from"node:fs";import{lstat as Ahe,mkdir as Q6t,open as zHe,realpath as YHe}from"node:fs/promises";import{dirname as WHe,isAbsolute as q6t,join as XHe,relative as c6n,resolve as d6n,sep as u6n}from"node:path";import{createHash as p6n}from"node:crypto";import{createHash as f6n}from"node:crypto";function YWn(){let e=process.env.XENO_AGENT_HOME?.trim();return e?$6t(e):$6t(j6t(),".xeno-agent")}function M6t(e){if(typeof e!="string"||!e.trim()||e.length>512)throw new G6t("INVALID","Invalid quota identity.");return e}function H6t(e){let t=r=>({id:M6t(r?.id),generation:M6t(r?.generation)});if(!e||e.agent&&!e.team)throw new G6t("INVALID","A child quota scope requires its complete ancestry.");return{workspace:t(e.workspace),...e.team?{team:t(e.team)}:{},...e.agent?{agent:t(e.agent)}:{},...e.goal!==void 0?{goal:t(e.goal)}:{}}}function O6t(e){return JSON.stringify(H6t(e))}function Mr(e,t,r=16384){let n=e.trim();if(!n||n.length>r)throw new Te("INVALID",`${t} must be non-empty and no longer than ${r} characters`);return n}function mhe(e,t){return[...new Set((e??[]).map(r=>Mr(r,t)))]}function L6t(e){if(e===void 0)return;if(!e||typeof e!="object"||Array.isArray(e))throw new Te("INVALID","Goal limits must be an object when provided");let t={};for(let[r,n]of Object.entries(e)){if(r!=="maxIterations"&&r!=="maxTokens"&&r!=="maxWallClockMs")throw new Te("INVALID","Unknown goal limit");if(n!==void 0){if(!Number.isSafeInteger(n)||n<=0)throw new Te("INVALID",`${r} must be a positive safe integer when provided`);t[r]=n}}return t}function n6n(e){if(e){if(e.kind!=="fixed-interval"&&e.kind!=="dynamic")throw new Te("INVALID","schedule.kind must be fixed-interval or dynamic");if(e.kind==="fixed-interval"&&(!Number.isSafeInteger(e.intervalMs)||(e.intervalMs??0)<=0))throw new Te("INVALID","Fixed-interval schedules require a positive safe intervalMs");if(e.intervalMs!==void 0&&(!Number.isSafeInteger(e.intervalMs)||e.intervalMs<=0))throw new Te("INVALID","schedule.intervalMs must be a positive safe integer when provided");for(let t of["nextRunAt","expiresAt"]){let r=e[t];if(r!==void 0&&!Number.isFinite(Date.parse(r)))throw new Te("INVALID",`schedule.${t} must be an ISO timestamp when provided`)}return Yd(e)}}function Yd(e){return structuredClone(e)}function SI(e){let t=Date.parse(e);return Number.isFinite(t)?t:0}function ghe(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function i6n(e){return{summary:"Goal created; work has not started.",completedTaskCount:0,totalTaskCount:0,outstanding:[],decisions:[],updatedAt:e}}function o6n(){return{status:"pending",criteria:[],evidence:[]}}function F6t(e){return JWn("sha256").update(e).digest("hex")}function KHe(e){return{algorithm:"sha256",value:p6n("sha256").update(e).digest("hex")}}function z6t(e){if(typeof e!="string"||!e||e.length>2048||q6t(e)||/[\\:*?"<>|]/.test(e)||[...e].some(r=>r.charCodeAt(0)<32))throw new Error("Invalid portable snapshot path");let t=e.split("/");if(t.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(t.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 e}function X6t(e){return KHe(JSON.stringify([e.schemaVersion,e.sessionId,e.totalBytes,e.files.map(t=>[t.path,t.size,t.sha256,t.executable])])).value}function Y6t(e,t){if(e.schemaVersion!==1||e.sessionId!==t||!Array.isArray(e.files)||e.files.length>V6t||!Number.isSafeInteger(e.totalBytes)||e.totalBytes<0||e.totalBytes>J6t)throw new Error("Invalid handoff snapshot manifest");let r=new Set,n=0;for(let i of e.files){if(z6t(i.path),!Number.isSafeInteger(i.size)||i.size<0||i.size>W6t||!/^[a-f0-9]{64}$/.test(i.sha256)||typeof i.executable!="boolean")throw new Error("Invalid handoff snapshot file");let o=i.path.toLowerCase();if(r.has(o))throw new Error("Snapshot paths collide on Windows");r.add(o),n+=i.size}for(let i of r){let o=i.split("/");for(let s=1;s<o.length;s++)if(r.has(o.slice(0,s).join("/")))throw new Error("Snapshot file conflicts with a directory")}if(n!==e.totalBytes||X6t(e)!==e.digest)throw new Error("Handoff snapshot manifest integrity mismatch")}async function JHe(e,t){let r=e;for(let o of t.split("/"))if(r=XHe(r,o),(await Ahe(r)).isSymbolicLink())throw new Error("Snapshot symlinks are not supported");let n=await YHe(r),i=c6n(e,n);if(i===".."||i.startsWith(`..${u6n}`)||q6t(i))throw new Error("Snapshot path escaped its root");return r}async function K6t(e){if(!e.sessionId||e.sessionId.length>1024||e.paths.length>V6t)throw new Error("Invalid snapshot scope");let t=await YHe(e.root),r=[],n=new Map,i=0;for(let s of[...e.paths].sort()){if(e.signal?.throwIfAborted(),z6t(s),!await e.authorizeFile(s))throw new Error("Snapshot file transfer is not authorized");let a=await JHe(t,s),l=await Ahe(a),c=await zHe(a,U6t.O_RDONLY|(U6t.O_NOFOLLOW??0));try{let d=await c.stat();if(await JHe(t,s),l.ino!==d.ino||l.dev!==d.dev||l.ctimeMs!==d.ctimeMs)throw new Error("Snapshot source was replaced before reading");if(!d.isFile()||d.size>W6t||i+d.size>J6t)throw new Error("Snapshot file or total byte limit exceeded");let u=Buffer.alloc(d.size),p=0;for(;p<u.length;){e.signal?.throwIfAborted();let{bytesRead:g}=await c.read(u,p,u.length-p,p);if(!g)throw new Error("Snapshot source changed while reading");p+=g}let f=await c.stat(),h=await Ahe(a);if(await JHe(t,s),d.size!==f.size||d.mtimeMs!==f.mtimeMs||d.ctimeMs!==f.ctimeMs||h.isSymbolicLink()||h.ino!==d.ino||h.dev!==d.dev)throw new Error("Snapshot source changed while reading");let m=KHe(u).value;r.push({path:s,size:u.length,sha256:m,executable:(d.mode&73)!==0}),n.set(m,u),i+=u.length}finally{await c.close()}}let o={schemaVersion:1,sessionId:e.sessionId,files:r,totalBytes:i,digest:""};return o.digest=X6t(o),Y6t(o,e.sessionId),{manifest:o,blobs:n}}async function Z6t(e){let t=structuredClone(e.manifest);if(Y6t(t,e.sessionId),!await e.authorizeManifest(structuredClone(t)))throw new Error("Snapshot restoration is not authorized");e.signal?.throwIfAborted();let r=d6n(e.destination);if(await YHe(WHe(r))!==WHe(r))throw new Error("Snapshot destination parent must be canonical");try{throw await Ahe(r),new Error("Snapshot destination already exists")}catch(o){if(o.code!=="ENOENT")throw o}let n=`${r}.staging-${l6n()}`;await Q6t(n,{mode:448});for(let o of t.files){e.signal?.throwIfAborted();let s=await e.readBlob(o.sha256,o.size);if(s.byteLength!==o.size||KHe(s).value!==o.sha256)throw new Error("Snapshot blob integrity mismatch; staging retained");let a=XHe(n,...o.path.split("/"));await Q6t(WHe(a),{recursive:!0,mode:448});let l=await zHe(a,"wx",o.executable?448:384);try{await l.writeFile(s),await l.sync()}finally{await l.close()}}e.signal?.throwIfAborted();let i=await zHe(XHe(n,".xeno-handoff-ready"),"wx",384);try{await i.writeFile(JSON.stringify({digest:t.digest,sessionId:t.sessionId})),await i.sync()}finally{await i.close()}return{directory:n,digest:t.digest,files:t.files.length,bytes:t.totalBytes}}function eJt(e){return typeof e=="string"&&h6n.test(e)}function WS(e){return`sha256:${f6n("sha256").update(e).digest("hex")}`}var Te,xcs,Ccs,Tcs,PP,Rcs,G6t,KWn,ZWn,e6n,t6n,hhe,N6t,r6n,D6t,whe,_P,V6t,W6t,J6t,h6n,BP=Ae(()=>{"use strict";Te=class extends Error{constructor(e,t,r={}){super(t),this.code=e,this.details=r,this.name="XenoCoordinationError"}code;details},xcs=zWn(),Ccs=XWn(),Tcs=j6t();PP="[redacted]",Rcs=[[/-----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${PP}`],[/((?:^|[\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${PP}`],[/\b(Bearer|Basic|Token|DPoP)\s+[A-Za-z0-9._~+/=-]{6,}/gi,`$1 ${PP}`],[/\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,PP],[/\beyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}/g,PP],[/([?&#;](?:access_token|refresh_token|id_token|token|key|api[_-]?key|secret|client_secret|password|signature|sig)=)[^&#\s"'<>]+/gi,`$1${PP}`],[/(\b[a-z][a-z0-9+.-]*:\/\/)[^/\s:@"']+:[^/\s@"']+@/gi,`$1${PP}@`]],G6t=class extends Error{constructor(e,t){super(t),this.code=e,this.name="QuotaError"}code;retryable=!1};KWn=3e4,ZWn=3e4,e6n=6e4,t6n=2e4,hhe=new Set(["EACCES","EBUSY","EPERM"]),N6t=[5,10,20,40,80,160,320],r6n=[5,10,20,40,80,160,320],D6t=[1,2,3,4];whe=class{get goalTurnAdmissionVersion(){return 1}rootDirectory;now;idFactory;ownerLeaseMs;lockTimeoutMs;lockStaleMs;maximumEventsPerSession;constructor(e={}){this.rootDirectory=e.rootDirectory??Xm.join(YWn(),"coordination"),this.now=e.now??(()=>new Date().toISOString()),this.idFactory=e.idFactory??(t=>`${t}_${fhe()}`),this.ownerLeaseMs=e.ownerLeaseMs??KWn,this.lockTimeoutMs=e.lockTimeoutMs??ZWn,this.lockStaleMs=e.lockStaleMs??e6n,this.maximumEventsPerSession=e.maximumEventsPerSession??t6n}async getSessionState(e){let t=Mr(e,"sessionId",1024);return Yd(await this.readState(t))}async fenceAdmission(e,t,r){let n=Mr(r.authorityId,"authorityId",512),i=Mr(r.operationId,"operationId",512);if(!Number.isSafeInteger(t)||t<0)throw new Te("INVALID","Expected session version must be a nonnegative safe integer");if(r.action!=="archive"&&r.action!=="delete")throw new Te("INVALID","Unsupported admission fence action");return this.mutate(e,o=>{let s=o.admissionFence;if(s?.authorityId===n&&s.operationId===i&&s.action===r.action)return s;if(o.version!==t)throw new Te("CONFLICT","Session version changed before lifecycle fencing",{expected:t,actual:o.version});if(s?.authorityId===n&&s.action==="archive"&&r.action==="archive")return s;if(s&&!(s.authorityId===n&&s.action==="archive"&&r.action==="delete"))throw new Te("CONFLICT","Another lifecycle fence already owns this session");let a={schemaVersion:1,authorityId:n,operationId:i,action:r.action,createdAt:this.now()};return o.admissionFence=a,o.schemaVersion===1&&(o.schemaVersion=2),this.appendEvent(o,"admission.fenced",{data:{authorityId:n,operationId:i,action:r.action}}),a},!0)}async clearAdmissionFence(e,t,r,n){await this.mutate(e,i=>{this.assertVersion(e,i.version,t);let o=i.admissionFence;if(!o||o.authorityId!==r||o.operationId!==n)throw new Te("CONFLICT","Lifecycle fence identity does not match");if(o.action==="delete")throw new Te("CONFLICT","Deleted session admission cannot be restored");if(i.owner)throw new Te("CONFLICT","Execution ownership must settle before restoration");i.admissionFence=void 0,this.appendEvent(i,"admission.restored",{data:{authorityId:r,operationId:n}})},!0)}async releaseDeadLifecycleOwner(e,t,r,n){await this.mutate(e,i=>{this.assertVersion(e,i.version,t);let o=i.admissionFence;if(!o||o.authorityId!==r||o.operationId!==n)throw new Te("CONFLICT","Lifecycle fence identity does not match");let s=i.owner;if(s){if(s.host!==VS.hostname()||!Number.isInteger(s.processId)||(s.processId??0)<=0||ghe(s.processId))throw new Te("CONFLICT","Execution owner exit has not been proved");i.owner=void 0,this.appendEvent(i,"ownership.released",{ownerId:s.ownerId,data:{epoch:s.epoch,reason:"fenced-local-owner-exited"}})}},!0)}async listSessionStates(){let e=Xm.join(this.rootDirectory,"sessions"),t;try{t=await fi.readdir(e)}catch(r){if(r.code==="ENOENT")return[];throw r}return(await Promise.all(t.filter(r=>r.endsWith(".json")).map(async r=>{try{let n=JSON.parse(await fi.readFile(Xm.join(e,r),"utf8"));return!D6t.includes(n.schemaVersion)||typeof n.sessionId!="string"?void 0:((!Number.isSafeInteger(n.ownershipEpoch)||n.ownershipEpoch<0)&&(n.ownershipEpoch=Math.max(n.owner?.epoch??0,...n.handoffs.map(i=>i.targetLeaseEpoch??i.sourceLeaseEpoch??0))),n)}catch{return}}))).filter(r=>r!==void 0).sort((r,n)=>SI(n.updatedAt)-SI(r.updatedAt)).map(r=>Yd(r))}async createGoal(e){let t=Mr(e.sessionId,"sessionId",1024),r=L6t(e.limits);return this.mutate(t,n=>{let i=n.goals.find(l=>["active","paused","waiting","blocked"].includes(l.status));if(i)throw new Te("CONFLICT",`Session ${t} already has active goal ${i.id}`);let o=this.now(),s=(e.successCriteria??[]).map(l=>typeof l=="string"?{id:this.idFactory("criterion"),description:Mr(l,"successCriteria"),required:!0}:{id:l.id?Mr(l.id,"successCriteria.id",512):this.idFactory("criterion"),description:Mr(l.description,"successCriteria.description"),required:l.required}),a={schemaVersion:1,id:this.idFactory("goal"),version:1,sessionId:t,objective:Mr(e.objective,"objective"),...e.why?{why:Mr(e.why,"why")}:{},successCriteria:s,constraints:mhe(e.constraints,"constraints"),...r?{limits:r}:{},metadata:Yd(e.metadata??{}),status:"active",milestones:[],tasks:[],progress:i6n(o),verification:o6n(),steering:[],createdAt:o,updatedAt:o};return n.goals.push(a),this.appendEvent(n,"goal.created",{goalId:a.id,data:{objective:a.objective}}),a})}async getGoal(e,t){let r=await this.getSessionState(e),n=t?r.goals.find(i=>i.id===t):[...r.goals].reverse().find(i=>["active","paused","waiting","blocked"].includes(i.status));return n?Yd(n):void 0}async updateGoal(e,t,r,n){return this.mutate(e,i=>{let o=this.requireGoal(i,t);if(this.assertVersion(o.id,o.version,r),["completed","cancelled","failed"].includes(o.status))throw new Te("CONFLICT",`Goal ${o.id} is terminal (${o.status})`);let s=o.status!=="active";if(n.status==="active"&&o.status==="blocked"?o.status="active":n.status&&(o.status=n.status),n.objective!==void 0&&(o.objective=Mr(n.objective,"objective")),n.why!==void 0&&(o.why=Mr(n.why,"why")),n.constraints&&(o.constraints=mhe(n.constraints,"constraints")),n.successCriteria&&(o.successCriteria=Yd(n.successCriteria)),n.progress&&(o.progress={...o.progress,...Yd(n.progress),outstanding:mhe(n.progress.outstanding??o.progress.outstanding,"progress.outstanding"),decisions:mhe(n.progress.decisions??o.progress.decisions,"progress.decisions"),updatedAt:this.now()}),n.verification&&(o.verification=Yd(n.verification)),n.metadata&&(o.metadata=Yd(n.metadata)),s&&o.status==="active")for(let a of i.loops.filter(l=>l.goalId===t&&l.kind==="goal-continuation"&&l.status==="running"))a.resumeRequested=!0,a.version+=1,a.updatedAt=this.now();return o.version+=1,o.updatedAt=this.now(),this.appendEvent(i,"goal.updated",{goalId:o.id,data:{status:o.status,version:o.version}}),o},n.status!==void 0&&["paused","cancelled","failed"].includes(n.status))}async addMilestone(e,t,r,n){return this.mutateGoal(e,t,r,(i,o)=>{let s={id:this.idFactory("milestone"),title:Mr(n.title,"milestone.title"),...n.description?{description:Mr(n.description,"milestone.description")}:{},status:i.milestones.some(a=>a.status==="active")?"pending":"active",taskIds:[],createdAt:o,updatedAt:o};i.milestones.push(s),i.progress.currentMilestoneId??=s.id,i.progress.updatedAt=o})}async addTask(e,t,r,n){return this.mutateGoal(e,t,r,(i,o)=>{let s=i.milestones.find(c=>c.id===n.milestoneId);if(!s)throw new Te("NOT_FOUND",`Milestone ${n.milestoneId} was not found`);if(n.parentTaskId&&!i.tasks.some(c=>c.id===n.parentTaskId))throw new Te("NOT_FOUND",`Parent task ${n.parentTaskId} was not found`);let a=[...new Set(n.dependsOn??[])];for(let c of a)if(!i.tasks.some(d=>d.id===c))throw new Te("NOT_FOUND",`Task dependency ${c} was not found`);let l={id:this.idFactory("task"),milestoneId:s.id,...n.parentTaskId?{parentTaskId:n.parentTaskId}:{},title:Mr(n.title,"task.title"),...n.description?{description:Mr(n.description,"task.description")}:{},status:a.length===0?"ready":"pending",...n.assignedAgentId?{assignedAgentId:Mr(n.assignedAgentId,"task.assignedAgentId",512)}:{},...a.length?{dependsOn:a}:{},createdAt:o,updatedAt:o};i.tasks.push(l),s.taskIds.push(l.id),s.updatedAt=o,i.progress.totalTaskCount=i.tasks.length,i.progress.outstanding=i.tasks.filter(c=>c.status!=="completed").map(c=>c.title),i.progress.updatedAt=o})}async updateTask(e,t,r,n,i){return this.mutateGoal(e,t,n,(o,s)=>{let a=o.tasks.find(c=>c.id===r);if(!a)throw new Te("NOT_FOUND",`Task ${r} was not found`);a.status=i.status,i.progress!==void 0&&(a.progress=Mr(i.progress,"task.progress")),i.resultEventId!==void 0&&(a.resultEventId=Mr(i.resultEventId,"task.resultEventId",512)),i.assignedAgentId!==void 0&&(a.assignedAgentId=Mr(i.assignedAgentId,"task.assignedAgentId",512)),a.updatedAt=s,a.status==="completed"&&(a.completedAt=s);let l=o.milestones.find(c=>c.id===a.milestoneId);if(l){let c=o.tasks.filter(d=>d.milestoneId===l.id);c.length>0&&c.every(d=>d.status==="completed")?(l.status="completed",l.completedAt=s):c.some(d=>d.status==="running")?l.status="active":c.some(d=>d.status==="blocked")&&(l.status="blocked"),l.updatedAt=s}for(let c of o.tasks)c.status!=="pending"||!c.dependsOn?.length||c.dependsOn.every(d=>o.tasks.find(u=>u.id===d)?.status==="completed")&&(c.status="ready",c.updatedAt=s);this.recalculateProgress(o,s)})}async steerGoal(e,t,r,n){return this.mutateGoal(e,t,r,(i,o,s)=>{let a=this.idFactory("steer");i.steering.push({id:a,instruction:Mr(n,"instruction"),createdAt:o}),this.appendEvent(s,"goal.steered",{goalId:t,data:{steeringId:a}})},!1)}async consumeGoalSteering(e,t,r){let n=[];return{goal:await this.mutateGoal(e,t,r,(i,o)=>{n=i.steering.filter(s=>!s.consumedAt).map(({id:s,instruction:a,createdAt:l})=>({id:s,instruction:a,createdAt:l}));for(let s of i.steering)s.consumedAt||(s.consumedAt=o)}),instructions:n}}async completeGoal(e,t,r,n){if(n.status!=="passed")throw new Te("VERIFICATION_REQUIRED","Goal completion requires passed verification");return this.mutate(e,i=>{let o=this.requireGoal(i,t);this.assertVersion(o.id,o.version,r);let s=o.successCriteria.filter(c=>c.required),a=s.filter(c=>{let d=n.criteria.find(u=>u.criterionId===c.id);return!d?.satisfied||d.evidence.length===0});if(a.length>0)throw new Te("VERIFICATION_REQUIRED","Required success criteria lack passing evidence",{unmetCriteria:a.map(c=>c.id)});if(s.length===0&&n.evidence.length===0)throw new Te("VERIFICATION_REQUIRED","Goal completion requires at least one durable evidence reference");let l=this.now();return o.status="completed",o.verification=Yd(n),o.verification.verifiedAt??=l,o.completedAt=l,o.updatedAt=l,o.version+=1,this.appendEvent(i,"goal.completed",{goalId:t,data:{evidence:o.verification.evidence}}),o},!0)}async cancelGoal(e,t,r,n){return this.mutate(e,i=>{let o=this.requireGoal(i,t);if(this.assertVersion(o.id,o.version,r),["completed","cancelled","failed"].includes(o.status))return o;o.status="cancelled",o.updatedAt=this.now(),o.version+=1,this.appendEvent(i,"goal.cancelled",{goalId:t,data:{reason:Mr(n,"reason")}});for(let s of i.loops.filter(a=>a.goalId===t&&["running","paused","waiting"].includes(a.status)))s.status="stopped",s.resumeRequested!==void 0&&(s.resumeRequested=!1),s.stopReason=`Goal cancelled: ${n}`,s.stoppedAt=this.now(),s.updatedAt=s.stoppedAt,s.version+=1;return o},!0)}async startLoop(e){return this.mutate(e.sessionId,t=>this.createLoopRecord(t,e))}createLoopRecord(e,t){if(t.kind==="goal-continuation"&&!t.goalId)throw new Te("INVALID","Goal-continuation loops require a goalId");if(t.goalId){let s=this.requireGoal(e,t.goalId);if(["completed","cancelled","failed"].includes(s.status))throw new Te("CONFLICT",`Cannot start a loop for terminal goal ${s.id}`)}if(t.kind==="scheduled"&&!t.schedule)throw new Te("INVALID","Scheduled loops require schedule metadata");if(t.kind!=="scheduled"&&t.schedule)throw new Te("INVALID","Only scheduled loops may carry schedule metadata");let r=n6n(t.schedule),n=e.loops.find(s=>s.goalId===t.goalId&&s.kind===t.kind&&["running","paused","waiting"].includes(s.status));if(n)throw new Te("CONFLICT",`Loop ${n.id} is already active`);let i=this.now(),o={schemaVersion:1,id:this.idFactory("loop"),version:1,sessionId:e.sessionId,...t.goalId?{goalId:t.goalId}:{},kind:t.kind,status:"running",...t.activity?{currentActivity:Mr(t.activity,"activity")}:{},iterations:[],...r?{schedule:r}:{},createdAt:i,updatedAt:i};return e.loops.push(o),this.appendEvent(e,"loop.started",{loopId:o.id,goalId:o.goalId,data:{kind:o.kind}}),o}async getLoop(e,t){let r=await this.getSessionState(e),n=t?r.loops.find(i=>i.id===t):[...r.loops].reverse().find(i=>["running","paused","waiting"].includes(i.status));return n?Yd(n):void 0}async beginLoopIteration(e,t,r,n,i){return this.mutateLoop(e,t,r,(o,s,a)=>{this.appendLoopIteration(a,o,s,n,i)},!1)}appendLoopIteration(e,t,r,n,i,o=!1){if(t.status!=="running")throw new Te("CONFLICT",`Loop ${t.id} is ${t.status}`);if(t.goalId){let l=this.requireGoal(e,t.goalId);this.isCliGoal(l)&&this.initializeGoalTurnAccounting(e,l)}if(this.assertGoalIterationAdmission(e,t,r,o),t.iterations.some(l=>l.status==="running"))throw new Te("CONFLICT",`Loop ${t.id} already has a running iteration`);let s=(t.iterations.at(-1)?.number??0)+1;t.currentActivity=Mr(n,"activity");let a={number:s,startedAt:r,status:"running",activity:t.currentActivity,...t.goalId&&e.goalTurnAccounting?.[t.goalId]?{goalAccountingVersion:1}:{},...i?{taskId:Mr(i,"taskId",512)}:{}};return t.iterations.push(a),t.resumeRequested!==void 0&&(t.resumeRequested=!1),this.appendEvent(e,"loop.iteration",{loopId:t.id,goalId:t.goalId,data:{number:s,phase:"started",activity:t.currentActivity}}),a}async admitGoalTurn(e){return this.admitGoalTurnWithOwner(e)}async admitQuotaGoalTurn(e,t,r,n){let i=H6t(r),o=await this.getGoal(e.sessionId,e.goalId);if(!o||o.sessionId!==e.sessionId||o.limits?.maxTokens===void 0)throw new Te("BUDGET_UNAVAILABLE","The exact token-bounded goal is unavailable for quota admission");if(this.isCliGoal(o)&&o.metadata["cli.tokenQuotaVersion"]!==1)throw new Te("BUDGET_UNAVAILABLE","Legacy CLI goal token spend is unknown; quota admission requires creation-time provenance");if(i.goal?.id!==o.id||i.goal.generation!==o.createdAt)throw new Te("BUDGET_UNAVAILABLE","Quota scope does not identify this durable goal generation");let s=await t.policy(i);if(!s||O6t(s.scope)!==O6t(i)||s.limits.tokensLifetime===void 0||s.limits.tokensLifetime===null||s.limits.tokensLifetime>o.limits.maxTokens)throw new Te("BUDGET_UNAVAILABLE","Goal quota policy is absent or wider than the goal's explicit token limit");let a=await t.remainingTokens(i);if(a===null)throw new Te("BUDGET_UNAVAILABLE","Goal token accounting has no durable remaining allowance");if(a<1)throw new Te("BUDGET_EXCEEDED","Goal token allowance is exhausted");return this.admitGoalTurnWithOwner(e,n,{goalId:o.id,createdAt:o.createdAt,maximum:o.limits.maxTokens})}async admitOwnedGoalTurn(e,t){if(!t||!Number.isSafeInteger(t.epoch)||t.epoch<1)throw new Te("INVALID","An exact execution ownership epoch is required");return this.admitGoalTurnWithOwner(e,{...t})}async admitGoalTurnWithOwner(e,t,r){let n=Mr(e.requestId,"requestId",512),i=this.goalTurnHash(e.requestHash);return this.mutate(e.sessionId,o=>{if(t){let d=this.requireOwner(o,t.ownerId,t.leaseId);if(d.epoch!==t.epoch)throw new Te("NOT_OWNER","Execution ownership epoch changed");if(this.ownerExpired(d,this.now()))throw new Te("LEASE_EXPIRED","Execution ownership expired");if(o.handoffs.some(u=>["prepared","available"].includes(u.status)&&u.sourceLeaseEpoch===d.epoch)||o.handoffs.some(u=>u.status==="claimed"&&u.targetLeaseEpoch===d.epoch))throw new Te("UNSAFE_HANDOFF","Execution handoff has not settled")}let s=this.requireGoal(o,e.goalId);if(r&&(s.id!==r.goalId||s.createdAt!==r.createdAt||s.limits?.maxTokens!==r.maximum))throw new Te("BUDGET_UNAVAILABLE","Goal token limit changed after quota verification");for(let d of o.loops.filter(u=>u.goalId===s.id)){let u=d.iterations.find(p=>p.goalTurn?.requestId===n);if(u){if(u.goalTurn?.requestHash!==i)throw new Te("CONFLICT","Goal turn identity was reused for different work");return{...this.goalTurnState(o,s,d,u),admitted:!1}}}if(this.assertVersion(s.id,s.version,e.expectedGoalVersion),s.status!=="active")throw new Te("CONFLICT",`Goal ${s.id} is ${s.status}`);let a=[...o.loops].reverse().find(d=>d.goalId===s.id&&d.kind==="goal-continuation");if(e.expectedLoopId!==void 0){if(!a||a.id!==e.expectedLoopId)throw new Te("CONFLICT","Goal continuation loop changed before admission");this.assertVersion(a.id,a.version,e.expectedLoopVersion??-1)}else if(e.expectedLoopVersion!==void 0)throw new Te("INVALID","A goal turn loop version requires its exact loop ID");if(a&&a.status!=="running")throw new Te("CONFLICT",`Goal loop ${a.id} is ${a.status}; resume or start it explicitly`);this.initializeGoalTurnAccounting(o,s),a??=this.createLoopRecord(o,{sessionId:o.sessionId,goalId:s.id,kind:"goal-continuation"});let l=this.now(),c=this.appendLoopIteration(o,a,l,"Interactive goal turn",void 0,r!==void 0);if(e.executionKind!==void 0&&e.executionKind!=="local-sdk"&&e.executionKind!=="external")throw new Te("INVALID","Unknown goal execution lane");return c.goalTurn={requestId:n,requestHash:i,executor:e.executionKind==="local-sdk"?{kind:"local-sdk",processId:process.pid,host:VS.hostname()}:{kind:"external"}},a.version+=1,a.updatedAt=l,{...this.goalTurnState(o,s,a,c),admitted:!0}},!1,o=>o.admitted)}async getGoalTurnState(e,t,r){let n=await this.getSessionState(e),i=t?n.goals.find(l=>l.id===t):[...n.goals].reverse().find(l=>["active","paused","waiting","blocked"].includes(l.status));if(!i)return;let o=n.loops.filter(l=>l.goalId===i.id),s=r?o.find(l=>l.iterations.some(c=>c.goalTurn?.requestId===r)):[...o].reverse().find(l=>l.kind==="goal-continuation"),a=r?s?.iterations.find(l=>l.goalTurn?.requestId===r):s?.iterations.at(-1);if(r&&!a)throw new Te("NOT_FOUND","Goal turn was not found");return this.goalTurnState(n,i,s,a)}async finishGoalTurn(e){if(!["completed","failed","interrupted"].includes(e.status))throw new Te("INVALID","Invalid goal turn outcome");let t=this.goalTurnHash(e.requestHash);return this.mutate(e.sessionId,r=>{let n=this.requireGoal(r,e.goalId),i=r.loops.find(s=>s.goalId===n.id&&s.iterations.some(a=>a.goalTurn?.requestId===e.requestId)),o=i?.iterations.find(s=>s.goalTurn?.requestId===e.requestId);if(!i||!o)throw new Te("NOT_FOUND","Goal turn was not found");if(o.goalTurn?.requestHash!==t)throw new Te("CONFLICT","Goal turn settlement identity does not match");return o.status==="running"&&(this.settleLoopIteration(r,i,o,this.now(),{status:n.status==="cancelled"||["stopped","failed"].includes(i.status)?"interrupted":e.status}),i.version+=1,i.updatedAt=this.now()),this.goalTurnState(r,n,i,o)},!0)}async recoverGoalTurn(e,t,r){return this.mutate(e,n=>{let i=this.requireGoal(n,t),o=n.loops.find(a=>a.goalId===t&&a.iterations.some(l=>l.goalTurn?.requestId===r)),s=o?.iterations.find(a=>a.goalTurn?.requestId===r);if(!o||!s)throw new Te("NOT_FOUND","Goal turn was not found");if(s.status==="running"){if(!this.goalTurnOwnerExited(s))throw new Te("NOT_OWNER","The original local goal executor has not been proved exited; external execution requires reconciliation");this.settleLoopIteration(n,o,s,this.now(),{status:"interrupted",error:"Original local SDK executor exited; inspect persisted results before retrying work"}),o.resumeRequested=i.status==="active"&&o.status==="running",o.version+=1,o.updatedAt=this.now()}return this.goalTurnState(n,i,o,s)},!0)}async finishLoopIteration(e,t,r,n){return this.mutateLoop(e,t,r,(i,o,s)=>{let a=[...i.iterations].reverse().find(l=>l.status==="running");if(!a)throw new Te("CONFLICT",`Loop ${i.id} has no running iteration`);this.settleLoopIteration(s,i,a,o,n)},!1,!0)}settleLoopIteration(e,t,r,n,i){r.status=i.status,r.completedAt=n,i.verificationEventId&&(r.verificationEventId=Mr(i.verificationEventId,"verificationEventId",512)),i.error&&(r.error=Mr(i.error,"error")),t.status=["stopped","completed","failed"].includes(t.status)?t.status:e.admissionFence?"paused":i.nextStatus??(t.status==="paused"||t.status==="waiting"?t.status:"running"),this.appendEvent(e,"loop.iteration",{loopId:t.id,goalId:t.goalId,data:{number:r.number,phase:"finished",status:i.status}})}async setLoopStatus(e,t,r,n,i){return this.mutateLoop(e,t,r,(o,s,a)=>{let l=o.status;if(["stopped","completed","failed"].includes(l))throw new Te("CONFLICT",`Loop ${o.id} is terminal (${l})`);let c=[...o.iterations].reverse().find(u=>u.status==="running");if(c&&n==="completed")throw new Te("CONFLICT",`Loop ${o.id} cannot complete while iteration ${c.number} is running`);c&&(n==="stopped"||n==="failed")&&(c.status=n==="failed"?"failed":"interrupted",c.completedAt=s,c.error=Mr(i??n,"reason")),o.status=n,o.kind==="goal-continuation"&&(o.resumeRequested=n==="running"),["stopped","completed","failed"].includes(n)&&(o.stoppedAt=s,o.stopReason=Mr(i??n,"reason"));let d=n==="paused"?"loop.paused":n==="waiting"?"loop.waiting":n==="running"&&(l==="paused"||l==="waiting")?"loop.resumed":n==="completed"?"loop.completed":n==="failed"?"loop.failed":"loop.stopped";this.appendEvent(a,d,{loopId:t,goalId:o.goalId,data:{previous:l,status:n,...i?{reason:i}:{}}})},!1,n!=="running"&&n!=="waiting")}async acquireOwnership(e,t,r={}){return this.mutate(e,n=>{let i=this.now();if(n.owner&&!this.ownerExpired(n.owner,i)){if(n.owner.ownerId===t&&r.processId!==void 0&&n.owner.processId===r.processId&&(r.host===void 0||n.owner.host===r.host))return n.owner;throw new Te("CONFLICT",`Session ${e} is owned by ${n.owner.ownerId}`,{owner:n.owner})}let o=n.owner&&this.ownerExpired(n.owner,i)?n.owner:void 0;if(o)for(let l of n.handoffs.filter(c=>c.status==="claimed"&&c.claimedBy===o.ownerId&&c.targetLeaseEpoch===o.epoch))l.status="failed",l.failureReason=`Claimed owner ${o.ownerId} lost its execution lease before completing the handoff.`,l.failedAt=i,l.updatedAt=i,l.version+=1,this.appendEvent(n,"handoff.failed",{handoffId:l.id,goalId:l.goalId,loopId:l.loopId,data:{reason:l.failureReason,expiredLeaseId:o.leaseId}});let s=n.ownershipEpoch+1;for(let l of n.handoffs.filter(c=>["prepared","available"].includes(c.status)&&c.sourceLeaseEpoch<s))l.status="failed",l.failureReason="Source ownership epoch was superseded before the handoff was claimed.",l.failedAt=i,l.updatedAt=i,l.version+=1,this.appendEvent(n,"handoff.failed",{handoffId:l.id,data:{epoch:s,reason:l.failureReason}});let a=this.newOwner(t,s,r,i);return n.owner=a,n.ownershipEpoch=s,this.appendEvent(n,"ownership.acquired",{ownerId:t,data:{epoch:s,leaseId:a.leaseId}}),a})}async renewOwnership(e,t,r,n=this.ownerLeaseMs){return this.mutate(e,i=>{let o=this.requireOwner(i,t,r);if(this.ownerExpired(o,this.now()))throw new Te("LEASE_EXPIRED",`Ownership lease ${r} expired`);return o.heartbeatAt=this.now(),o.expiresAt=new Date(SI(o.heartbeatAt)+n).toISOString(),this.appendEvent(i,"ownership.renewed",{ownerId:t,data:{epoch:o.epoch,leaseId:r}}),o})}async recoverExpiredOwnership(e,t,r,n,i=this.ownerLeaseMs){return this.mutate(e,o=>{let s=this.requireOwner(o,t,r);if(s.processId!==n||s.host!==VS.hostname()||!ghe(n))throw new Te("LEASE_EXPIRED",`Ownership lease ${r} expired and cannot be recovered by process ${n}`);let a=this.now(),l=Math.max(0,SI(a)-SI(s.expiresAt));return s.heartbeatAt=a,s.expiresAt=new Date(SI(a)+i).toISOString(),this.appendEvent(o,l>0?"ownership.recovered":"ownership.renewed",{ownerId:t,data:{epoch:s.epoch,leaseId:r,...l>0?{expiredForMs:l}:{}}}),s})}async releaseOwnership(e,t,r){return this.mutate(e,n=>{let i=this.requireOwner(n,t,r);for(let o of n.handoffs.filter(s=>s.status==="claimed"&&s.claimedBy===t&&s.targetLeaseEpoch===i.epoch))o.status="failed",o.failureReason="Target released execution ownership before completing the handoff.",o.failedAt=this.now(),o.updatedAt=o.failedAt,o.version+=1,this.appendEvent(n,"handoff.failed",{handoffId:o.id,ownerId:t,data:{epoch:i.epoch,reason:o.failureReason}});return n.owner=void 0,this.appendEvent(n,"ownership.released",{ownerId:t,data:{epoch:i.epoch}}),i},!0)}async createHandoff(e){let t=!1,r=e.prepareRequestId===void 0?void 0:Mr(e.prepareRequestId,"prepareRequestId",512);return this.mutate(e.sessionId,n=>{let i=this.requireOwner(n,e.sourceOwnerId,e.sourceLeaseId);if(this.ownerExpired(i,this.now()))throw new Te("LEASE_EXPIRED",`Ownership lease ${i.leaseId} expired`);if(r){let c=n.handoffs.find(d=>d.prepareRequestId===r);if(c){if(c.sourceOwnerId!==i.ownerId||c.sourceLeaseEpoch!==i.epoch||c.status!=="available"||c.targetOwnerId!==e.targetOwnerId||c.workspace!==e.workspace||c.goalId!==e.goalId||c.loopId!==e.loopId||c.contextDigest!==e.contextDigest||c.branch!==e.branch||c.currentMilestoneId!==e.currentMilestoneId||c.currentTaskId!==e.currentTaskId||JSON.stringify(c.agentIds)!==JSON.stringify([...new Set(e.agentIds??[])])||JSON.stringify(c.operations)!==JSON.stringify(e.operations??[]))throw new Te("CONFLICT","Prepare identity was reused for different work or ownership");return t=!0,c}}let o=(e.operations??[]).filter(c=>c.status==="running"&&c.sideEffecting);if(o.length>0)throw new Te("UNSAFE_HANDOFF","Running side-effecting operations must settle before execution handoff",{operationIds:o.map(c=>c.operationId)});if(e.goalId&&this.requireGoal(n,e.goalId),e.loopId&&!n.loops.some(c=>c.id===e.loopId))throw new Te("NOT_FOUND",`Loop ${e.loopId} was not found`);let s=n.handoffs.find(c=>["prepared","available","claimed"].includes(c.status));if(s)throw new Te("CONFLICT",`Handoff ${s.id} is already active`);let a=this.now(),l={schemaVersion:1,id:this.idFactory("handoff"),version:1,sessionId:n.sessionId,...e.goalId?{goalId:e.goalId}:{},...e.loopId?{loopId:e.loopId}:{},status:"available",sourceOwnerId:i.ownerId,...r?{prepareRequestId:r}:{},...e.targetOwnerId?{targetOwnerId:Mr(e.targetOwnerId,"targetOwnerId",512)}:{},sourceLeaseEpoch:i.epoch,...e.workspace?{workspace:Mr(e.workspace,"workspace",32768)}:{},...e.branch?{branch:Mr(e.branch,"branch",1024)}:{},...e.currentMilestoneId?{currentMilestoneId:e.currentMilestoneId}:{},...e.currentTaskId?{currentTaskId:e.currentTaskId}:{},agentIds:[...new Set(e.agentIds??[])],operations:Yd(e.operations??[]),...e.contextDigest?{contextDigest:Mr(e.contextDigest,"contextDigest",512)}:{},createdAt:a,updatedAt:a};return n.handoffs.push(l),this.appendEvent(n,"handoff.created",{handoffId:l.id,goalId:l.goalId,loopId:l.loopId,ownerId:i.ownerId,data:{targetOwnerId:l.targetOwnerId}}),l},!1,()=>!t)}async claimHandoff(e){let t,r=!1,n=e.claimRequestId===void 0?void 0:Mr(e.claimRequestId,"claimRequestId",512);return{handoff:await this.mutate(e.sessionId,i=>{let o=i.handoffs.find(l=>l.id===e.handoffId);if(!o)throw new Te("NOT_FOUND",`Handoff ${e.handoffId} was not found`);if(o.status!=="available"){let l=i.owner;if(n&&o.claimRequestId===n&&["claimed","completed"].includes(o.status)&&o.claimedBy===e.targetOwnerId&&l?.ownerId===e.targetOwnerId&&l.epoch===o.targetLeaseEpoch&&l.host===e.host&&l.processId===e.processId&&!this.ownerExpired(l,this.now()))return t=l,r=!0,o;throw new Te("CONFLICT",`Handoff ${o.id} is ${o.status}`,{claimedBy:o.claimedBy})}if(o.targetOwnerId&&o.targetOwnerId!==e.targetOwnerId)throw new Te("CONFLICT",`Handoff ${o.id} is reserved for ${o.targetOwnerId}`);let s=i.owner;if(!s||s.ownerId!==o.sourceOwnerId||s.epoch!==o.sourceLeaseEpoch)throw new Te("CONFLICT",`Handoff ${o.id} no longer matches the source ownership epoch`);let a=this.now();return t=this.newOwner(e.targetOwnerId,s.epoch+1,{processId:e.processId,host:e.host,leaseMs:e.leaseMs},a),i.owner=t,i.ownershipEpoch=t.epoch,o.status="claimed",o.claimedBy=e.targetOwnerId,n&&(o.claimRequestId=n),o.targetOwnerId=e.targetOwnerId,o.targetLeaseEpoch=t.epoch,o.claimedAt=a,o.updatedAt=a,o.version+=1,this.appendEvent(i,"handoff.claimed",{handoffId:o.id,goalId:o.goalId,loopId:o.loopId,ownerId:e.targetOwnerId,data:{sourceOwnerId:o.sourceOwnerId,epoch:t.epoch}}),o},!1,()=>!r),owner:Yd(t)}}async completeHandoff(e,t,r,n){let i=!1;return this.mutate(e,o=>{let s=this.requireOwner(o,r,n);if(this.ownerExpired(s,this.now()))throw new Te("LEASE_EXPIRED",`Ownership lease ${n} expired`);let a=o.handoffs.find(l=>l.id===t);if(!a)throw new Te("NOT_FOUND",`Handoff ${t} was not found`);if(a.claimedBy!==r||a.targetLeaseEpoch!==s.epoch||!["claimed","completed"].includes(a.status))throw new Te("CONFLICT",`Handoff ${a.id} cannot be completed by ${r}`);return a.status==="completed"?(i=!0,a):(a.status="completed",a.completedAt=this.now(),a.updatedAt=a.completedAt,a.version+=1,this.appendEvent(o,"handoff.completed",{handoffId:t,goalId:a.goalId,loopId:a.loopId,ownerId:r,data:{epoch:o.owner?.epoch}}),a)},!1,()=>!i)}async cancelHandoff(e,t,r,n){let i=!1;return this.mutate(e,o=>{let s=o.handoffs.find(l=>l.id===t);if(!s)throw new Te("NOT_FOUND",`Handoff ${t} was not found`);if(s.sourceOwnerId!==r)throw new Te("CONFLICT",`Handoff ${t} was not offered by ${r}`);if(s.status==="cancelled")return i=!0,s;if(s.status!=="available"&&s.status!=="prepared")throw new Te("CONFLICT",`Handoff ${t} is ${s.status} and can no longer be cancelled`);let a=this.requireOwner(o,r,n);if(this.ownerExpired(a,this.now()))throw new Te("LEASE_EXPIRED",`Ownership lease ${n} expired`);if(s.sourceLeaseEpoch!==a.epoch)throw new Te("CONFLICT",`Handoff ${t} belongs to an earlier ownership epoch`);return s.status="cancelled",s.cancelledAt=this.now(),s.updatedAt=s.cancelledAt,s.version+=1,this.appendEvent(o,"handoff.cancelled",{handoffId:t,goalId:s.goalId,loopId:s.loopId,ownerId:r,data:{epoch:a.epoch}}),s},!1,()=>!i)}async failHandoff(e,t,r){return this.mutate(e,n=>{let i=n.handoffs.find(o=>o.id===t);if(!i)throw new Te("NOT_FOUND",`Handoff ${t} was not found`);return["completed","cancelled","failed"].includes(i.status)||(i.status="failed",i.failureReason=Mr(r,"reason"),i.failedAt=this.now(),i.updatedAt=i.failedAt,i.version+=1,this.appendEvent(n,"handoff.failed",{handoffId:t,goalId:i.goalId,loopId:i.loopId,data:{reason:i.failureReason}})),i},!0)}async mutateGoal(e,t,r,n,i=!0){return this.mutate(e,o=>{let s=this.requireGoal(o,t);this.assertVersion(s.id,s.version,r);let a=this.now();return n(s,a,o),s.version+=1,s.updatedAt=a,i&&this.appendEvent(o,"goal.updated",{goalId:t,data:{status:s.status,version:s.version}}),s})}async mutateLoop(e,t,r,n,i=!0,o=!1){return this.mutate(e,s=>{let a=s.loops.find(c=>c.id===t);if(!a)throw new Te("NOT_FOUND",`Loop ${t} was not found`);this.assertVersion(a.id,a.version,r);let l=this.now();return n(a,l,s),a.version+=1,a.updatedAt=l,i&&this.appendEvent(s,"loop.iteration",{loopId:t,goalId:a.goalId,data:{status:a.status,version:a.version}}),a},o)}assertGoalIterationAdmission(e,t,r,n=!1){if(!t.goalId)return;let i=this.requireGoal(e,t.goalId);if(i.status!=="active")throw new Te("CONFLICT",`Goal ${i.id} is ${i.status}; no iteration was admitted`);let o=L6t(i.limits);if(o?.maxTokens!==void 0&&!n)throw new Te("BUDGET_UNAVAILABLE","Goal token allowance is not bound to request-level admission; no iteration was admitted",{goalId:i.id,limit:"maxTokens"});if(o?.maxWallClockMs!==void 0){let s=Date.parse(i.createdAt),a=Date.parse(r);if(!Number.isFinite(s)||!Number.isFinite(a)||a<s)throw new Te("BUDGET_UNAVAILABLE","Goal wall-clock allowance cannot be verified",{goalId:i.id,limit:"maxWallClockMs"});if(a-s>=o.maxWallClockMs)throw new Te("BUDGET_EXCEEDED","Goal wall-clock limit reached; no iteration was admitted",{goalId:i.id,limit:"maxWallClockMs",maximum:o.maxWallClockMs})}if(o?.maxIterations!==void 0){let s=e.goalTurnAccounting!==void 0||e.schemaVersion===4?this.resolveGoalTurnAccounting(e,i):void 0;if(s?.coverage==="partial")throw new Te("BUDGET_UNAVAILABLE","Legacy goal turn accounting is incomplete");let a=this.goalIterationCount(e,i)+(s?.baseIterations??0);if(!Number.isSafeInteger(a)||a<0)throw new Te("BUDGET_UNAVAILABLE","Invalid goal iteration accounting");if(a>=o.maxIterations)throw new Te("BUDGET_EXCEEDED","Goal iteration limit reached; no iteration was admitted",{goalId:i.id,limit:"maxIterations",admitted:a,maximum:o.maxIterations})}}isCliGoal(e){return"cli.accountedTurns"in e.metadata||"cli.createdByCliVersion"in e.metadata}goalIterationCount(e,t){let r=0;for(let n of e.loops.filter(i=>i.goalId===t.id)){if(!Array.isArray(n.iterations))throw new Te("BUDGET_UNAVAILABLE","Goal iteration history is unavailable");let i=0;for(let o of n.iterations){if(!o||!Number.isSafeInteger(o.number)||o.number<=i)throw new Te("BUDGET_UNAVAILABLE","Goal iteration history is invalid");i=o.number}if(r+=i,!Number.isSafeInteger(r))throw new Te("BUDGET_UNAVAILABLE","Goal iteration count exceeds its supported range")}return r}resolveGoalTurnAccounting(e,t){let r=e.goalTurnAccounting;if(r!==void 0&&(!r||typeof r!="object"||Array.isArray(r)))throw new Te("BUDGET_UNAVAILABLE","Persisted goal turn accounting is invalid");if(r&&Object.hasOwn(r,t.id)){let a=r[t.id];if(!a||a.schemaVersion!==1||!Number.isSafeInteger(a.baseIterations)||a.baseIterations<0||!["complete","partial"].includes(a.coverage))throw new Te("BUDGET_UNAVAILABLE","Persisted goal turn accounting is invalid");return a}if(e.loops.some(a=>a.goalId===t.id&&a.iterations.some(l=>l.goalTurn||l.goalAccountingVersion)))throw new Te("BUDGET_UNAVAILABLE","Recorded goal turns are missing their protected accounting");let n=this.goalIterationCount(e,t),i=t.metadata["cli.accountedTurns"],o=typeof i=="number"&&Number.isSafeInteger(i)&&i>=0,s=this.isCliGoal(t)&&(!o||i>0&&n>0);return{schemaVersion:1,baseIterations:o&&n===0?i:0,coverage:s?"partial":"complete"}}initializeGoalTurnAccounting(e,t){let r=this.resolveGoalTurnAccounting(e,t);if(r.coverage==="partial"&&t.limits?.maxIterations!==void 0)throw new Te("BUDGET_UNAVAILABLE","Legacy goal turn accounting needs reconciliation before bounded execution");e.goalTurnAccounting??={},Object.defineProperty(e.goalTurnAccounting,t.id,{value:r,writable:!0,enumerable:!0,configurable:!0})}goalTurnHash(e){let t=Mr(e,"requestHash",64).toLowerCase();if(!/^[0-9a-f]{64}$/.test(t))throw new Te("INVALID","Goal turn requestHash must be a SHA-256 digest");return t}goalTurnState(e,t,r,n){let i=this.resolveGoalTurnAccounting(e,t),o=this.goalIterationCount(e,t)+i.baseIterations;if(!Number.isSafeInteger(o))throw new Te("BUDGET_UNAVAILABLE","Goal turn count exceeds its supported range");return Yd({goal:t,admittedTurns:o,accountingCoverage:i.coverage,...r?{loopId:r.id,loopVersion:r.version,loopStatus:r.status,resumeRequested:r.resumeRequested===!0}:{},...n?{iterationNumber:n.number,iterationStatus:n.status,...n.goalTurn?{requestId:n.goalTurn.requestId,requestHash:n.goalTurn.requestHash}:{},canRecover:n.status==="running"&&this.goalTurnOwnerExited(n)}:{}})}goalTurnOwnerExited(e){let t=e.goalTurn?.executor;if(t?.kind!=="local-sdk"||t.host!==VS.hostname()||!Number.isSafeInteger(t.processId)||t.processId<=0)return!1;try{return process.kill(t.processId,0),!1}catch(r){return r.code==="ESRCH"}}recalculateProgress(e,t){let r=e.tasks.filter(n=>n.status==="completed").length;e.progress.completedTaskCount=r,e.progress.totalTaskCount=e.tasks.length,e.progress.percent=e.tasks.length?Math.round(r/e.tasks.length*100):void 0,e.progress.outstanding=e.tasks.filter(n=>!["completed","cancelled"].includes(n.status)).map(n=>n.title),e.progress.updatedAt=t}requireGoal(e,t){let r=e.goals.find(n=>n.id===t);if(!r)throw new Te("NOT_FOUND",`Goal ${t} was not found`);return r}requireOwner(e,t,r){let n=e.owner;if(!n||n.ownerId!==t||n.leaseId!==r)throw new Te("NOT_OWNER",`${t} does not own session ${e.sessionId}`,{owner:n});return n}assertVersion(e,t,r){if(!Number.isInteger(r)||r<1||t!==r)throw new Te("CONFLICT",`Expected ${e} version ${r}, found ${t}`,{expected:r,actual:t})}newOwner(e,t,r,n){let i=r.leaseMs??this.ownerLeaseMs;if(!Number.isSafeInteger(i)||i<1)throw new Te("INVALID","leaseMs must be a positive safe integer");return{ownerId:Mr(e,"ownerId",512),leaseId:this.idFactory("owner"),epoch:t,acquiredAt:n,heartbeatAt:n,expiresAt:new Date(SI(n)+i).toISOString(),...r.processId!==void 0?{processId:r.processId}:{},...r.host?{host:Mr(r.host,"host",512)}:{}}}ownerExpired(e,t){return SI(e.expiresAt)<=SI(t)?!0:e.processId!==void 0&&e.host===VS.hostname()&&!ghe(e.processId)}appendEvent(e,t,r){let n={schemaVersion:1,id:this.idFactory("event"),sequence:(e.events.at(-1)?.sequence??0)+1,type:t,sessionId:e.sessionId,...r.goalId?{goalId:r.goalId}:{},...r.loopId?{loopId:r.loopId}:{},...r.handoffId?{handoffId:r.handoffId}:{},...r.ownerId?{ownerId:r.ownerId}:{},timestamp:this.now(),data:Yd(r.data)};e.events.push(n),e.events.length>this.maximumEventsPerSession&&e.events.splice(0,e.events.length-this.maximumEventsPerSession)}async mutate(e,t,r=!1,n=()=>!0){let i=Mr(e,"sessionId",1024);return this.withSessionLock(i,async()=>{let o=await this.readState(i);if(o.admissionFence&&!r)throw new Te("CONFLICT","Session execution is blocked by a persisted lifecycle fence");let s=o.schemaVersion;this.promoteGoalBudgetEnvelope(o),o.schemaVersion!==s&&await this.writeState(o);let a=t(o);return n(a)&&(o.version+=1,o.updatedAt=this.now(),await this.writeState(o)),Yd(a)})}statePath(e){return Xm.join(this.rootDirectory,"sessions",`${F6t(e)}.json`)}lockPath(e){return`${this.statePath(e)}.lock`}async readState(e){let t=this.statePath(e);try{let r=await fi.readFile(t,"utf8"),n=JSON.parse(r);if(!D6t.includes(n.schemaVersion)||n.sessionId!==e)throw new Te("INVALID",`Coordination state at ${t} does not match session ${e}`);if(n.admissionFence!==void 0){let i=n.admissionFence;if(!i||i.schemaVersion!==1||typeof i.authorityId!="string"||!i.authorityId.trim()||typeof i.operationId!="string"||!i.operationId.trim()||!["archive","delete"].includes(i.action)||!Number.isFinite(Date.parse(i.createdAt)))throw new Te("INVALID","Persisted lifecycle fence is corrupt; execution remains unavailable")}return(!Number.isSafeInteger(n.ownershipEpoch)||n.ownershipEpoch<0)&&(n.ownershipEpoch=Math.max(n.owner?.epoch??0,...n.handoffs.map(i=>i.targetLeaseEpoch??i.sourceLeaseEpoch??0))),n}catch(r){if(r.code!=="ENOENT")throw r;let n=this.now();return{schemaVersion:1,sessionId:e,version:0,ownershipEpoch:0,goals:[],loops:[],handoffs:[],events:[],createdAt:n,updatedAt:n}}}promoteGoalBudgetEnvelope(e){(e.goalTurnAccounting!==void 0||e.loops.some(t=>t.resumeRequested!==void 0||t.iterations.some(r=>r.goalTurn!==void 0)))&&(e.schemaVersion=4),e.schemaVersion<3&&e.goals.some(t=>t.limits!==void 0&&(!t.limits||typeof t.limits!="object"||Array.isArray(t.limits)||Object.keys(t.limits).length>0))&&(e.schemaVersion=3)}async writeState(e){this.promoteGoalBudgetEnvelope(e);let t=this.statePath(e.sessionId),r=Xm.dirname(t);await fi.mkdir(r,{recursive:!0});let n=`${t}.${process.pid}.${fhe()}.tmp`,i=await fi.open(n,"wx");try{await i.writeFile(`${JSON.stringify(e,null,2)}
3249
3249
  `,"utf8"),await i.sync()}finally{await i.close()}try{await this.renameReplacing(n,t);try{let o=await fi.open(r,"r");try{await o.sync()}finally{await o.close()}}catch{}}finally{await fi.unlink(n).catch(()=>{})}}async renameReplacing(e,t){for(let r=0;;r+=1)try{await fi.rename(e,t);return}catch(n){let i=n.code,o=N6t[r];if(process.platform!=="win32"||!i||!hhe.has(i)||o===void 0)throw n;await new Promise(s=>setTimeout(s,o))}}async withSessionLock(e,t){let r=this.lockPath(e),n=Xm.join(r,"owner.json"),i=fhe(),o=`${r}.candidate.${i}`,s=Date.now();await fi.mkdir(Xm.dirname(r),{recursive:!0});let a={schemaVersion:1,token:i,pid:process.pid,host:VS.hostname(),acquiredAt:this.now()};await fi.mkdir(o),await fi.writeFile(Xm.join(o,"owner.json"),JSON.stringify(a),{encoding:"utf8",flag:"wx"});for(let l=0;;l+=1)try{await fi.rename(o,r);break}catch(c){let d=c.code;if(!(d&&new Set(["EEXIST","ENOTEMPTY","ENOTDIR","EBUSY"]).has(d)||process.platform==="win32"&&d&&hhe.has(d)))throw await fi.rm(o,{recursive:!0,force:!0}).catch(()=>{}),c;let u=await this.staleLockOwner(r,n);if(u){await this.quarantineLock(r,u.token,"stale");continue}if(Date.now()-s>=this.lockTimeoutMs)throw await fi.rm(o,{recursive:!0,force:!0}).catch(()=>{}),new Te("CONFLICT",`Timed out waiting for coordination lock for session ${e}`);await new Promise(p=>setTimeout(p,Math.min(100,5+l*5)+Math.floor(Math.random()*10)))}try{return await t()}finally{await this.quarantineLock(r,i,"released"),await fi.rm(o,{recursive:!0,force:!0}).catch(()=>{})}}async staleLockOwner(e,t){try{let[r,n]=await Promise.all([fi.readFile(t,"utf8").catch(()=>""),fi.stat(e)]),i=r?JSON.parse(r):void 0;return!i||i.host!==VS.hostname()||ghe(i.pid)?void 0:Date.now()-n.mtimeMs>this.lockStaleMs?i:void 0}catch{return}}async quarantineLock(e,t,r){let n=Xm.join(e,"owner.json"),i=r==="stale"?`${e}.stale.${F6t(t)}`:`${e}.${r}.${t}.${fhe()}`;for(let o=0;;o+=1){let s;try{s=JSON.parse(await fi.readFile(n,"utf8"))}catch(a){if(a.code==="ENOENT")return;throw a}if(s.token!==t)return;try{await fi.rename(e,i);break}catch(a){let l=a.code;if(r==="stale")try{if(JSON.parse(await fi.readFile(Xm.join(i,"owner.json"),"utf8")).token===t)return}catch{}if(l==="ENOENT"||l==="EEXIST")return;let c=N6t[o];if(process.platform!=="win32"||!l||!hhe.has(l)||c===void 0)throw a;await new Promise(d=>setTimeout(d,c))}}if(r!=="stale")for(let o=0;;o+=1)try{await fi.rm(i,{recursive:!0});return}catch(s){let a=s.code;if(a==="ENOENT")return;let l=r6n[o];if(process.platform!=="win32"||!a||!hhe.has(a)||l===void 0)throw s;await new Promise(c=>setTimeout(c,l))}}},_P=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 whe,this.sessionId=e.sessionId,this.processId=e.processId??process.pid,this.host=e.host??a6n(),this.ownerId=e.ownerId??`runtime:${this.host}:${this.processId}:${s6n().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 t=this.initializationAbort.signal,r,n;try{let i=new Promise((o,s)=>{n=()=>s(t.reason??new Error("Destination preparation cancelled")),t.addEventListener("abort",n,{once:!0}),r=setTimeout(()=>this.initializationAbort.abort(new Error("Destination preparation timed out")),this.destinationTimeoutMs),t.aborted&&n()});await Promise.race([i,Promise.resolve().then(()=>(t.throwIfAborted(),this.prepareDestination({handoff:structuredClone(e),signal:t})))]),t.throwIfAborted()}finally{r&&clearTimeout(r),n&&t.removeEventListener("abort",n)}}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(t){if(!(t instanceof Error&&"code"in t&&t.code==="LEASE_EXPIRED")||!this.store.recoverExpiredOwnership||this.preparingHandoff||this.preparedHandoffId||this.stopped)throw t;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 t=await this.renewHeldLease();this.handoffOutcomeUncertain=!0;let r=await this.store.createHandoff({...e,sessionId:this.sessionId,sourceOwnerId:t.ownerId,sourceLeaseId:t.leaseId});return this.preparedHandoffId=r.id,this.handoffOutcomeUncertain=!1,r}catch(t){throw this.markLost(t instanceof Error?t:new Error("Handoff preparation failed",{cause:t})),t}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 t=await this.store.cancelHandoff(this.sessionId,e,this.ownerId,this.owner.leaseId);if(t.id!==e||t.status!=="cancelled")throw new Error(`Handoff ${e} was not cancelled`);return this.preparedHandoffId=void 0,await this.renewHeldLease(),t}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 t=this.owner;if(this.owner=void 0,!(e.release===!1||this.preparedHandoffId||this.handoffOutcomeUncertain||!t))try{await this.store.releaseOwnership(this.sessionId,t.ownerId,t.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))}};V6t=1e4,W6t=8*1024*1024,J6t=64*1024*1024;h6n=/^sha256:[0-9a-f]{64}$/});var tJt=Ae(()=>{"use strict"});var rJt=Ae(()=>{"use strict"});function m6n(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(!["connected","signed-out","scope-missing","unavailable"].includes(String(t.status))||t.reason!==void 0&&typeof t.reason!="string"||t.plan!==void 0&&typeof t.plan!="string"||t.creditsBalance!==void 0&&(typeof t.creditsBalance!="number"||!Number.isFinite(t.creditsBalance))||t.usedPercent!==void 0&&(typeof t.usedPercent!="number"||!Number.isFinite(t.usedPercent))||t.resetsAt!==void 0&&t.resetsAt!==null&&typeof t.resetsAt!="string"||t.exhausted!==void 0&&typeof t.exhausted!="boolean"||t.usageCreditsEnabled!==void 0&&typeof t.usageCreditsEnabled!="boolean"||t.usageCreditsBalance!==void 0&&(typeof t.usageCreditsBalance!="number"||!Number.isFinite(t.usageCreditsBalance))||t.canManageUsageCredits!==void 0&&typeof t.canManageUsageCredits!="boolean"||t.totalCostMicro!==void 0&&(typeof t.totalCostMicro!="number"||!Number.isFinite(t.totalCostMicro)))return!1;if(t.spendCaps!==void 0){if(!Array.isArray(t.spendCaps))return!1;for(let r of t.spendCaps){if(!r||typeof r!="object"||Array.isArray(r))return!1;let n=r;if(typeof n.windowSec!="number"||!Number.isFinite(n.windowSec)||typeof n.limitMicro!="string"||typeof n.spentMicro!="string")return!1}}if(t.workspaceWallet!==void 0&&t.workspaceWallet!==null){if(typeof t.workspaceWallet!="object"||Array.isArray(t.workspaceWallet))return!1;let r=t.workspaceWallet;if(typeof r.workspaceId!="string"||typeof r.billingMode!="string"||typeof r.credits!="number"||typeof r.availableCredits!="number"||typeof r.pendingCredits!="number"||typeof r.isFrozen!="boolean"||typeof r.seats!="number")return!1}if(t.workspaceBudget!==void 0&&t.workspaceBudget!==null&&(typeof t.workspaceBudget!="object"||Array.isArray(t.workspaceBudget)))return!1;if(t.costByModelMicro!==void 0){if(!Array.isArray(t.costByModelMicro))return!1;for(let r of t.costByModelMicro){if(!r||typeof r!="object"||Array.isArray(r))return!1;let n=r;if(typeof n.model!="string"||typeof n.events!="number"||typeof n.costMicro!="number"||typeof n.inputTokens!="number"||typeof n.outputTokens!="number")return!1}}return!0}function nJt(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(t.success===!1)return typeof t.error=="string";if(t.success!==!0||!t.snapshot||typeof t.snapshot!="object"||Array.isArray(t.snapshot))return!1;let r=t.snapshot,n=o=>typeof o=="number"&&Number.isSafeInteger(o)&&o>=0,i=(o,s,a,l=!1)=>Array.isArray(o)&&o.every(c=>c&&typeof c=="object"&&!Array.isArray(c)&&typeof c[s]=="string"&&n(c[a])&&(!l||c.cost===null));return r.source==="local-runtime-journal"&&r.billingStatus==="unavailable"&&r.totalCost===null&&typeof r.observedAt=="string"&&Number.isFinite(Date.parse(r.observedAt))&&n(r.totalTokens)&&n(r.totalRequests)&&n(r.unmeasuredRequests)&&r.unmeasuredRequests<=r.totalRequests&&i(r.dailyUsage,"label","value")&&i(r.weeklyUsage,"label","value")&&i(r.monthlyUsage,"label","value")&&i(r.costByModel,"model","tokens",!0)&&i(r.topAgents,"name","tokens",!0)&&(r.billingAuthority===void 0||m6n(r.billingAuthority))}var iJt=Ae(()=>{"use strict"});var oJt=Ae(()=>{"use strict"});function sJt(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.success===!1?typeof t.error=="string":t.success===!0&&typeof t.source=="string"&&g6n.has(t.source)&&typeof t.observedAt=="string"&&Number.isFinite(Date.parse(t.observedAt))&&(t.retentionDays===void 0||typeof t.retentionDays=="number"&&Number.isSafeInteger(t.retentionDays)&&t.retentionDays>=1)&&typeof t.complete=="boolean"&&(t.complete?t.nextCursor===null:typeof t.nextCursor=="string"&&t.nextCursor.length>0&&t.nextCursor.length<=4096)&&Array.isArray(t.entries)&&t.entries.length<=1e4&&t.entries.every(r=>r&&typeof r=="object"&&["id","timestamp","action","actor","target","details"].every(n=>typeof r[n]=="string")&&Number.isFinite(Date.parse(r.timestamp)))}var g6n,aJt=Ae(()=>{"use strict";g6n=new Set(["local-runtime-journal","account-security-audit","workspace-audit"])});function cJt(e){return!ZHe(e)||typeof e.success!="boolean"||e.error!==void 0&&(typeof e.error!="string"||e.error.length>1e3)?!1:e.success?e.content!==void 0&&(typeof e.content!="string"||e.content.length>128e3)||e.loadedModel!==void 0&&!lJt(e.loadedModel)||e.models!==void 0&&(!Array.isArray(e.models)||e.models.length>1e3||!e.models.every(t=>ZHe(t)&&lJt(t.id)&&typeof t.name=="string"&&t.name.length<=512&&(t.contextWindowTokens===void 0||Number.isSafeInteger(t.contextWindowTokens)&&t.contextWindowTokens>0)))||e.usage!==void 0&&(!ZHe(e.usage)||!["inputTokens","outputTokens"].every(t=>Number.isSafeInteger(e.usage[t])&&(e.usage[t]??-1)>=0))?!1:e.content!==void 0||e.models!==void 0||e.loadedModel!==void 0:typeof e.error=="string"&&!!e.error}var ZHe,lJt,dJt=Ae(()=>{"use strict";ZHe=e=>!!e&&typeof e=="object"&&!Array.isArray(e),lJt=e=>typeof e=="string"&&e.length>0&&e.length<=512&&!/[\x00-\x1f\x7f]/.test(e)});var Jcs,uJt=Ae(()=>{"use strict";Jcs=new TextEncoder});var pJt=Ae(()=>{"use strict"});function fJt(e){return eqe(e)&&typeof e.action=="string"&&y6n.has(e.action)&&$P(e.url,"string")&&$P(e.text,"string")&&$P(e.key,"string")&&$P(e.x,"number")&&$P(e.y,"number")&&$P(e.scrollY,"number")}function tqe(e){if(!eqe(e))return!1;if(e.ok===!1)return typeof e.error=="string";if(e.ok!==!0||typeof e.url!="string"||typeof e.title!="string"||typeof e.loading!="boolean"||!$P(e.text,"string"))return!1;if(e.image===void 0)return!0;let t=e.image;return eqe(t)&&t.mediaType==="image/jpeg"&&typeof t.base64=="string"&&t.base64.length<=v6n&&Number.isFinite(t.width)&&Number.isFinite(t.height)}var yhe,A6n,w6n,y6n,b6n,v6n,eqe,$P,rqe=Ae(()=>{"use strict";yhe="preview.act",A6n=["status","screenshot","read","console"],w6n=["open","reload","back","forward","click","type","key","scroll"],y6n=new Set([...A6n,...w6n]),b6n=256*1024,v6n=24*1024*1024,eqe=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),$P=(e,t)=>e===void 0||(t==="number"?Number.isFinite(e):typeof e=="string"&&e.length<=b6n)});function k6n(e){return nqe(e)&&typeof e.method=="string"&&E6n.has(e.method)&&typeof e.url=="string"&&e.url.length<=2048&&e.url.startsWith("https://")}function hJt(e){if(e===null)return!0;if(!nqe(e))return!1;let t=(r,n)=>typeof r=="string"&&r.length>0&&r.length<=n&&!/[\s\r\n]/.test(r.replace(/^(Bearer|DPoP) /,""));return t(e.authorization,16384)&&/^(Bearer|DPoP) /.test(e.authorization)&&(e.dpop===void 0||t(e.dpop,8192))}function mJt(e){return!nqe(e)||e.kind!=="host-request"||typeof e.id!="string"||e.id.length===0?!1:e.method===yhe?fJt(e.input):e.method===I6n&&k6n(e.input)}var I6n,E6n,nqe,gJt=Ae(()=>{"use strict";rqe();I6n="account.authorize",E6n=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD"]),nqe=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});var AJt=Ae(()=>{"use strict"});var wJt=Ae(()=>{"use strict"});var yJt=Ae(()=>{"use strict"});var iqe,bJt=Ae(()=>{"use strict";iqe="1.0.0"});var CJt={};ho(CJt,{TERMINAL_WEB_JOB_STATES:()=>bhe,WEB_JOB_PROGRESS_OPERATIONS:()=>sqe,WEB_JOB_PROGRESS_SCHEMA:()=>MP,WEB_JOB_PROGRESS_SCHEMA_VERSION:()=>I6,WEB_JOB_PROGRESS_STATES:()=>aqe,deriveWebJobProgress:()=>vhe,isTerminalWebJobState:()=>xI,isWebJobProgress:()=>cqe,parseWebJobProgress:()=>E6,webJobProgressSignature:()=>dqe});function xI(e){return bhe.includes(e)}function IJt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function EJt(e,t){return Object.keys(e).every(r=>t.has(r))}function lqe(e,t){return typeof e=="string"&&e.trim().length>0&&e.length<=t&&!/[\u0000-\u001f\u007f]/u.test(e)}function oqe(e){return lqe(e,64)&&Number.isFinite(Date.parse(e))}function xJt(e){return lqe(e,120)&&/^[A-Za-z0-9._:-]+$/u.test(e)}function kJt(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function E6(e){if(!IJt(e)||!EJt(e,S6n))throw new TypeError("invalid Web Context progress object");if(e.schema!==MP||e.schemaVersion!==I6||e.contractVersion!==iqe)throw new TypeError("unsupported Web Context progress schema");if(!lqe(e.jobId,256))throw new TypeError("invalid Web Context progress jobId");if(!sqe.includes(e.operation))throw new TypeError("invalid Web Context progress operation");if(!aqe.includes(e.state))throw new TypeError("invalid Web Context progress state");let t=xI(e.state);if(e.terminal!==t)throw new TypeError("inconsistent Web Context terminal state");if(t){if(e.terminalState!==e.state)throw new TypeError("invalid Web Context terminalState")}else if("terminalState"in e)throw new TypeError("non-terminal Web Context progress cannot carry terminalState");if("terminalReason"in e&&(!t||!xJt(e.terminalReason)))throw new TypeError("invalid Web Context terminalReason");if(!IJt(e.counters)||!EJt(e.counters,vJt))throw new TypeError("invalid Web Context progress counters");for(let n of vJt)if(!kJt(e.counters[n]))throw new TypeError(`invalid Web Context counter ${n}`);let r=Number(e.counters.queuedPages)+Number(e.counters.activePages)+Number(e.counters.completedPages)+Number(e.counters.failedPages)+Number(e.counters.excludedPages);if(e.counters.knownPages!==r)throw new TypeError("inconsistent Web Context knownPages counter");if(!kJt(e.sequence))throw new TypeError("invalid Web Context progress sequence");if(!oqe(e.observedAt))throw new TypeError("invalid Web Context observedAt");if("createdAt"in e&&!oqe(e.createdAt))throw new TypeError("invalid Web Context createdAt");if("updatedAt"in e&&!oqe(e.updatedAt))throw new TypeError("invalid Web Context updatedAt");return structuredClone(e)}function cqe(e){try{return E6(e),!0}catch{return!1}}function v6(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):0}function SJt(e){return typeof e=="string"&&e.length>0?e:void 0}function vhe(e,t,r=new Date().toISOString()){let n=v6(e.queuedPages),i=v6(e.activePages),o=v6(e.completedPages),s=v6(e.failedPages),a=v6(e.excludedPages),l={queuedPages:n,activePages:i,completedPages:o,failedPages:s,excludedPages:a,knownPages:n+i+o+s+a},c=xI(e.state),d=xJt(e.terminalReason)?e.terminalReason:void 0,u=SJt(e.createdAt),p=SJt(e.updatedAt);return{schema:MP,schemaVersion:I6,contractVersion:iqe,jobId:e.jobId,operation:e.operation,state:e.state,terminal:c,...c?{terminalState:e.state}:{},...d?{terminalReason:d}:{},counters:l,sequence:t,observedAt:r,...u?{createdAt:u}:{},...p?{updatedAt:p}:{}}}function dqe(e){let t=e.counters;return[e.jobId,e.operation,e.state,e.terminalReason??"",e.updatedAt??"",t.queuedPages,t.activePages,t.completedPages,t.failedPages,t.excludedPages].join("|")}var MP,I6,bhe,sqe,aqe,S6n,vJt,KD=Ae(()=>{"use strict";bJt();MP="xeno.web-context.job-progress",I6="1.0.0",bhe=["completed","partial","failed","cancelled"],sqe=["scrape","batch-scrape","map","crawl","render","extract"],aqe=["queued","running",...bhe];S6n=new Set(["schema","schemaVersion","contractVersion","jobId","operation","state","terminal","terminalState","terminalReason","counters","sequence","observedAt","createdAt","updatedAt"]),vJt=new Set(["queuedPages","activePages","completedPages","failedPages","excludedPages","knownPages"])});var TJt=Ae(()=>{"use strict"});var RJt=Ae(()=>{"use strict"});var PJt=Ae(()=>{"use strict"});var _Jt=Ae(()=>{"use strict"});var BJt=Ae(()=>{"use strict"});var $Jt=Ae(()=>{"use strict";BJt()});var MJt=Ae(()=>{"use strict"});var OJt=Ae(()=>{"use strict"});var NJt=Ae(()=>{"use strict"});var DJt=Ae(()=>{"use strict"});var x6n,LJt=Ae(()=>{"use strict";Xy();x6n=1024*1024});function R6n(e){return ds(e)?e.kind==="xeno-credits"||e.kind==="local"?!0:e.kind==="own-key"&&Sn(e.provider)&&Sn(e.label)&&(e.status===void 0||typeof e.status=="string"):!1}function _6n(e){if(!ds(e)||!["loading","fresh","stale","unavailable"].includes(String(e.state))||typeof e.refreshing!="boolean"||e.source!==void 0&&e.source!=="api"&&e.source!=="platform-auth")return!1;for(let t of["lastSuccessAt","freshUntil","staleUntil","nextRetryAt"])if(e[t]!==void 0&&(typeof e[t]!="number"||!Number.isSafeInteger(e[t])||e[t]<0))return!1;if(e.lastSuccessAt!==void 0&&e.freshUntil!==void 0&&Number(e.freshUntil)<Number(e.lastSuccessAt)||e.freshUntil!==void 0&&e.staleUntil!==void 0&&Number(e.staleUntil)<Number(e.freshUntil)||(e.state==="fresh"||e.state==="stale")&&(e.lastSuccessAt===void 0||e.freshUntil===void 0||e.staleUntil===void 0))return!1;if(e.failure!==void 0){let t=e.failure;if(!ds(t)||!P6n.includes(t.code)||typeof t.retryable!="boolean"||t.retryAfterMs!==void 0&&(typeof t.retryAfterMs!="number"||!Number.isSafeInteger(t.retryAfterMs)||t.retryAfterMs<0||t.retryAfterMs>6e5))return!1}return!0}function O6n(e){return typeof e=="string"&&M6n.test(e)?e:void 0}function N6n(e){return typeof e=="string"&&C6n.includes(e)}function FJt(e){return ds(e)?Sn(e.clientId)&&Sn(e.clientVersion)&&Sn(e.instanceId)&&N6n(e.surface):!1}function QJt(e){return!ds(e)||!ds(e.protocol)||!ds(e.host)||!ds(e.storage)?!1:Number.isInteger(e.protocol.current)&&j6n(e.protocol.supported)&&Sn(e.host.instanceId)&&Sn(e.host.version)&&(e.host.buildIdentity===void 0||typeof e.host.buildIdentity=="string"&&/^[a-f0-9]{64}$/.test(e.host.buildIdentity))&&(e.host.runtimeVersion===void 0||typeof e.host.runtimeVersion=="string"&&/^\d+\.\d+\.\d+$/.test(e.host.runtimeVersion))&&(e.host.catalogRecoveryVersion===void 0||e.host.catalogRecoveryVersion===1)&&(e.host.maintenanceVersion===void 0||e.host.maintenanceVersion===1)&&(e.host.authority==="primary"||e.host.authority==="diagnostic-read-only")&&(e.host.processBoundary==="in-process"||e.host.processBoundary==="per-user-service")&&e.storage.owner==="xeno-agent-host"&&Number.isInteger(e.storage.schemaVersion)&&Number.isInteger(e.storage.eventSchemaVersion)&&FJt(e.surface)}function uqe(e){return!ds(e)||!Sn(e.revision)||!Array.isArray(e.providers)?!1:e.providers.every(U6n)}function D6n(e){return!ds(e)||!ds(e.event)?!1:Sn(e.id)&&Number.isInteger(e.sequence)&&typeof e.sequence=="number"&&e.sequence>=0&&Sn(e.timestamp)&&Sn(e.conversationId)&&Sn(e.requestId)&&Sn(e.type)&&Sn(e.source)}function jJt(e){return!ds(e)||!Array.isArray(e.events)?!1:(e.nextSequence===null||typeof e.nextSequence=="number"&&Number.isInteger(e.nextSequence)&&e.nextSequence>=0)&&e.events.every(D6n)}function GJt(e){return!ds(e)||typeof e.success!="boolean"?!1:e.success?(e.status==="accepted"||e.status==="replayed")&&Sn(e.conversationId)&&Sn(e.requestId)&&Sn(e.adapterId)&&ds(e.selection)&&Sn(e.selection.providerId)&&Sn(e.selection.catalogRevision):Sn(e.code)&&Sn(e.safeError)}function HJt(e){return!ds(e)||typeof e.success!="boolean"?!1:e.success?(e.status==="cancel_requested"||e.status==="replayed")&&Sn(e.conversationId)&&Sn(e.requestId):Sn(e.code)&&Sn(e.safeError)}function qJt(e){return ds(e)&&Sn(e.id)&&typeof e.sequence=="number"&&Number.isInteger(e.sequence)&&e.sequence>0&&typeof e.timestamp=="number"&&Number.isFinite(e.timestamp)&&L6n(e.type)&&e.source==="host"&&e.schemaVersion===1&&e.redactionState==="safe"&&"payload"in e&&(e.type!=="account.state.changed"||ds(e.payload)&&typeof e.payload.pending=="boolean")}function L6n(e){return typeof e=="string"&&$6n.includes(e)}function VJt(e,t,r){if(e.surface.surface!==t.surface||e.surface.instanceId!==t.instanceId)throw new Ra("surface_mismatch",`Agent host acknowledged ${e.surface.surface}/${e.surface.instanceId} instead of ${t.surface}/${t.instanceId}.`);if(e.protocol.current<r.min||e.protocol.current>r.max||r.max<e.protocol.supported.min||r.min>e.protocol.supported.max)throw new Ra("protocol_mismatch",`Agent host protocol ${e.protocol.current} is incompatible with client range ${r.min}-${r.max}.`)}function F6n(e){return!(!ds(e)||e.chatExecution!==void 0&&!k6(e.chatExecution)||e.durableResume!==void 0&&!k6(e.durableResume)||e.nativeTuiAttach!==void 0&&!k6(e.nativeTuiAttach)||e.reconciliation!==void 0&&!k6(e.reconciliation)||e.modelSwitchInPlace!==void 0&&!k6(e.modelSwitchInPlace)||e.resumeCompatibilityKey!==void 0&&typeof e.resumeCompatibilityKey!="string")}function k6(e){return ds(e)?(e.status==="available"||e.status==="degraded"||e.status==="blocked"||e.status==="unsupported")&&(e.source==="provider"||e.source==="host"||e.source==="policy")&&(e.reason===void 0||typeof e.reason=="string")&&(e.version===void 0||typeof e.version=="string"):!1}function U6n(e){return ds(e)?Sn(e.id)&&typeof e.kind=="string"&&T6n.includes(e.kind)&&Sn(e.displayName)&&WJt(e.availability)&&ds(e.capabilities)&&(e.providerSession===void 0||F6n(e.providerSession))&&(e.catalogState===void 0||_6n(e.catalogState))&&Array.isArray(e.models)&&e.models.every(Q6n)&&Sn(e.catalogRevision):!1}function Q6n(e){return ds(e)&&Sn(e.id)&&Sn(e.displayName)&&WJt(e.availability)&&(e.funding===void 0||R6n(e.funding))&&(e.reasoningOptions===void 0||Array.isArray(e.reasoningOptions)&&e.reasoningOptions.every(t=>ds(t)&&Sn(t.id)&&Sn(t.label)&&(t.runtimeModelId===void 0||Sn(t.runtimeModelId))&&(t.runtimeReasoningEffort===void 0||typeof t.runtimeReasoningEffort=="string"&&/^[a-z][a-z0-9_-]{0,79}$/i.test(t.runtimeReasoningEffort))&&(t.isDefault===void 0||typeof t.isDefault=="boolean")))}function WJt(e){return e==="available"||e==="degraded"||e==="blocked"||e==="unavailable"}function j6n(e){return ds(e)&&Number.isInteger(e.min)&&Number.isInteger(e.max)&&typeof e.min=="number"&&typeof e.max=="number"&&e.min>0&&e.max>=e.min}function Sn(e){return typeof e=="string"&&e.trim().length>0}function ds(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ehe(e){for(let t of H6n)for(let r of G6n)if(e===`${t}tool.${r}`)return r;return null}function OP(e,t){let r=e?.[t];return typeof r=="string"&&r.trim()?r:void 0}function khe(e){let t=e.event;return OP(t,"toolName")||OP(t,"tool")||OP(t,"name")||OP(t,"title")||OP(t,"kind")}function eL(e){let t=e.event;return OP(t,"toolCallId")||OP(t,"tool_call_id")}function She(e){let t=e.event;for(let r of["rawInput","input","arguments","parameters","args"]){let n=t?.[r];if(n&&typeof n=="object"&&!Array.isArray(n))return n}}function xhe(e){let t=e.event;for(let r of["rawOutput","output","result","content"]){let n=t?.[r];if(typeof n=="string")return n.length>0?n:void 0;if(n!=null)try{let i=JSON.stringify(n);if(i&&i!=="{}"&&i!=="[]")return i}catch{}}}function Che(e){return e==="completed"?!0:e==="failed"||e==="cancelled"?!1:null}var ZD,UJt,C6n,T6n,P6n,Ihe,B6n,pds,$6n,M6n,Ra,G6n,H6n,Xy=Ae(()=>{"use strict";tJt();rJt();iJt();oJt();aJt();dJt();uJt();pJt();gJt();rqe();AJt();wJt();yJt();KD();TJt();RJt();PJt();_Jt();$Jt();MJt();OJt();NJt();DJt();LJt();ZD=1,UJt=1,C6n=["standalone-desktop","remote","hub-embed","shell-embed","embed-preview","panel-embed","headless-client","extension-panel"],T6n=["sdk-native","xeno-cloud","cli-app-server","cli-remote","acp"];P6n=["timeout","network","rate-limited","server","auth-required","forbidden","invalid-response","configuration","cancelled"];Ihe=128e3,B6n=["workspace.usage","workspace.audit","inference.request","workspace.schedule","workspace.backup","workspace.environment","host.maintenance","remote.control","account.request","account.lend","workforce.request","workspace.notifications","workspace.rules","workspace.browser","workspace.browser.session","workspace.machine.browser","workspace.machine.devices","workspace.machine.grant","workspace.machine.grants","workspace.machine.revoke","workspace.machine.act","host.handshake","providers.list","providers.refresh","surface.tools.list","runtime.events.list","workspace.lifecycle.apply","state.workspaces.load","state.workspaces.save","state.conversations.load","state.conversations.save","state.conversations.delete","workspace.access.grant","workspace.access.list","workspace.access.revoke","coordination.held.list","coordination.held.release","coordination.policy.set","coordination.state.get","coordination.action","workspace.application.grant","workspace.directory.list","workspace.file.read","workspace.file.write","workspace.command.run","workspace.terminal.start","workspace.terminal.stop","workspace.pty.start","workspace.pty.snapshot","workspace.pty.input","workspace.pty.resize","workspace.pty.clear","workspace.pty.stop","conversation.open","conversation.fork","conversation.resume","conversation.transcript","conversation.annotate","conversation.attachment.read","conversation.branch.select","conversation.rewind","conversation.compact","xeno.tui.attach","provider.lanes.list","provider.lanes.get","provider.lanes.select","provider.native.attach","provider.native.detach","provider.native.reattach","provider.native.stop","provider.reconcile","turn.start","turn.cancel","turn.steer","context.inject","turn.queue","turn.queue.list","run.observation.snapshot","run.observation.change","run.observation.overlaps","fleet.view","fleet.route","fleet.plan","subagent.run.create","subagent.run.list","subagent.run.cancel","subagent.scheduler.status","subagent.scheduler.recover","session.list","session.attach","session.detach","session.snapshot","session.input","session.takeover","session.release","session.setMode","acp.agents.list","acp.agents.addPreset","acp.agents.remove","acp.catalog.list","acp.catalog.sync","acp.catalog.setEnabled","acp.catalog.setProviderEnabled","acp.catalog.updateProvider","acp.catalog.setPreferred","acp.agent.certify","acp.agent.test","acp.capabilitySnapshot.get","acp.command.invoke","intake.sources.list","intake.items.list","intake.item.claim","intake.item.release","intake.item.dispatch","knowledge.list","knowledge.record","knowledge.forget","knowledge.context","turn.queue.drop","elicitation.choose-directory.answer","elicitation.workspace-placement.answer","elicitation.permission.answer","turn.resume","acp.provider.approve","permissions.rules.list","permissions.rules.revoke","elicitation.ask-user.answer","sdk.sessions.list","sdk.sessions.show","sdk.sessions.attach","sdk.sessions.detach","sdk.sessions.delete","sdk.sessions.clean","sdk.checkpoints.list","sdk.checkpoints.restore","sdk.checkpoints.delete","sdk.tasks.output","sdk.tasks.stop","engineering.git.status","engineering.git.diff","engineering.git.stage","engineering.git.unstage","engineering.git.commit","engineering.git.branch","engineering.git.push","engineering.git.pr.create","engineering.devServer.list","engineering.devServer.start","engineering.devServer.stop","engineering.git.pr.status","engineering.git.pr.feedback","engineering.git.pr.merge","engineering.workCopy.list","engineering.workCopy.create","engineering.workCopy.remove","engineering.landing.enqueue","engineering.landing.remove","engineering.landing.status","engineering.landing.land","engineering.landing.verify","engineering.checks.discover","engineering.checks.run","engineering.background.start","engineering.background.list","engineering.background.output","engineering.background.stop","engineering.runs.list","engineering.diagnostics","engineering.patches.list","engineering.patches.enqueue","engineering.patches.update","engineering.patches.review","engineering.checkpoints.list","engineering.checkpoints.compare","engineering.checkpoints.restore","engineering.sessions.list","engineering.runtime.timeline","pluginMcp.snapshot","pluginMcp.installPlugin","pluginMcp.installLocalPlugin","pluginMcp.activatePlugin","pluginMcp.deactivatePlugin","pluginMcp.uninstallPlugin","pluginMcp.updatePlugin","pluginMcp.setPluginTrust","pluginMcp.trustPublisher","pluginMcp.untrustPublisher","pluginMcp.setRequireSignedPlugins","pluginMcp.upsertMcpServer","pluginMcp.removeMcpServer","pluginMcp.setMcpApproval","pluginMcp.reloadMcp","pluginMcp.setMcpRegistryPolicy","pluginMcp.setScopedPolicy","pluginMcp.deleteScopedPolicy","pluginMcp.searchMarketplace","pluginMcp.syncProjectMcp","pluginMcp.callMcpTool","pluginMcp.getMcpPrompt","pluginMcp.readMcpResource","pluginMcp.preflightTrust","skills.list","skills.get","skills.setEnabled","hooks.list","hooks.trust","hooks.disable","approvals.list","approvals.revoke","approvals.clear","recipes.list","recipes.compile","recipes.run","evals.list","evals.inspect","evals.run","evals.report","evals.compare","org.knowledge","org.playbooks","org.secrets","org.serviceUsers","github.appPlan","github.appVerify","github.mapWebhook","share.export","share.inspect","mcpAuth.status","mcpAuth.login","mcpAuth.loginStatus","mcpAuth.logout","runs.list","runs.get","runs.events","runs.stop","workflows.definitions","workflows.validate","workflows.create","workflows.list","workflows.get","workflows.events","workflows.start","workflows.pause","workflows.resume","workflows.cancel","workflows.retryChild","workflows.skipChild","workflows.rerun","workflows.save","artifacts.list","artifacts.get","artifacts.read","artifacts.publish","artifacts.promote","artifacts.keep-as-tool","artifacts.share","artifacts.comment","artifacts.reply","artifacts.comments","coordination.peers.list","coordination.peers.send","coordination.peers.messages","coordination.peers.decide"],pds=new Set(B6n),$6n=["host.ready","host.retirement.requested","provider.catalog.changed","account.state.changed","state.workspaces.changed","state.conversations.changed","runtime.event.appended","runtime.event.transient","turn.execution.completed","turn.execution.failed","turn.execution.abandoned","elicitation.choose-directory.requested","elicitation.workspace-placement.requested","elicitation.permission.requested","elicitation.ask-user.requested","task.changed","workspace.terminal.data","workspace.terminal.exit","workspace.pty.data","workspace.pty.exit","coordination.event","remote.host.event","remote.status.changed","run.observation","session.event","provider.lane.created","provider.lane.selected","provider.lane.resumed","provider.lane.invalidated","provider.writer.acquired","provider.writer.renewed","provider.writer.released","provider.writer.recovery_classified","provider.native_tui.started","provider.native_tui.detached","provider.native_tui.exited","provider.reconciliation.started","provider.reconciliation.completed","provider.reconciliation.failed","provider.portable_context.acknowledged_partial"],M6n=/^[A-Z][A-Z0-9_]{1,63}$/;Ra=class extends Error{code;reason;constructor(t,r,n){super(r),this.name="AgentHostProtocolError",this.code=t,this.reason=O6n(n)}};G6n=["started","updated","completed","failed","cancelled"],H6n=["","acp."]});import{createHash as Lds,randomBytes as q6n,timingSafeEqual as Fds}from"node:crypto";import{createConnection as V6n}from"node:net";function z6n(e,t,r){if(J6n.has(e))return Math.max(r,XJt);if(e!=="workspace.command.run")return r;let n=x6(t)?t:void 0,i=typeof n?.timeoutMs=="number"&&Number.isFinite(n.timeoutMs)?Math.max(1e3,Math.min(12e4,Math.floor(n.timeoutMs))):2e4;return Math.max(r,i+5e3)}function X6n(e){return!x6(e)||e.kind!=="response"||typeof e.id!="string"||typeof e.ok!="boolean"?!1:e.ok?"output"in e:x6(e.error)&&eJn(e.error.code)&&typeof e.error.message=="string"&&(e.error.reason===void 0||typeof e.error.reason=="string")}function Y6n(e){return x6(e)&&e.kind==="event"&&qJt(e.event)}function K6n(e,t,r){YJt(e,t,r)}function YJt(e,t,r){let n=`${JSON.stringify(t)}
3250
3250
  `;if(Buffer.byteLength(n,"utf8")>r)throw new Ra("invalid_response","Local Agent host RPC frame exceeds the size limit.");e.write(n,"utf8")}function zJt(e,t){if(!e.trim())throw new Error("Local Agent host endpoint is required.");if(t.length<32)throw new Error("Local Agent host transportToken must contain at least 32 characters.")}function NP(e){return typeof e=="number"&&Number.isInteger(e)&&e>0?e:void 0}function Z6n(e){let t=NP(e)||W6n;if(t>JJt)throw new Error(`Local Agent host RPC frame limit cannot exceed ${JJt} bytes.`);return t}function eJn(e){return e==="invalid_handshake"||e==="protocol_mismatch"||e==="surface_mismatch"||e==="not_connected"||e==="invalid_response"}function pqe(e){return e instanceof Error?e:new Error(String(e))}function x6(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function The(e,t){return e instanceof Error&&"code"in e&&e.code===t}var W6n,JJt,XJt,J6n,S6,fqe,tL=Ae(()=>{"use strict";Xy();W6n=32*1024*1024,JJt=64*1024*1024,XJt=12e4,J6n=new Set(["acp.catalog.list","acp.catalog.sync","acp.agent.certify","acp.agent.test","acp.provider.approve"]),S6=class{endpoint;transportToken;openStream;protocolVersion;maxFrameBytes;requestTimeoutMs;onDisconnect;listeners=new Set;pending=new Map;requestPrefix=q6n(12).toString("hex");requestSequence=0;socket=null;connectPromise=null;accountAuthorizer=null;previewHandler=null;setAccountAuthorizer(t){this.accountAuthorizer=t}setPreviewHandler(t){this.previewHandler=t}constructor(t){this.openStream=t.openStream,this.transportToken=t.transportToken??"",this.openStream||zJt(t.endpoint,this.transportToken),this.endpoint=t.endpoint,this.protocolVersion=NP(t.protocolVersion)||ZD,this.maxFrameBytes=Z6n(t.maxFrameBytes),this.requestTimeoutMs=NP(t.requestTimeoutMs)||XJt,this.onDisconnect=t.onDisconnect}get connected(){return this.socket!==null&&!this.socket.destroyed}async connect(){if(!this.connected)return this.connectPromise?this.connectPromise:(this.connectPromise=(this.openStream?this.connectStream(this.openStream):this.connectSocket()).finally(()=>{this.connectPromise=null}),this.connectPromise)}connectSocket(){return new Promise((t,r)=>{let n=V6n(this.endpoint),i=s=>{n.off("connect",o),this.socket=null,r(s)},o=()=>{n.off("error",i),n.setNoDelay(!0),this.socket=n,t()};n.once("error",i),n.once("connect",o),this.read(n)})}async connectStream(t){let{stream:r,transportToken:n}=await t();zJt(this.endpoint,n),this.transportToken=n,this.socket=r,this.read(r)}read(t){let r=new fqe(this.maxFrameBytes,n=>this.receive(n));t.on("data",n=>{try{r.push(n)}catch(i){this.disconnect(pqe(i))}}),t.on("error",n=>this.disconnect(n)),t.on("end",()=>this.disconnect(new Error("Local Agent host connection closed."))),t.on("close",()=>this.disconnect(new Error("Local Agent host connection closed."))),t.resume()}async request(t,r){await this.connect();let n=this.socket;if(!n||n.destroyed)throw new Ra("not_connected","Local Agent host is not connected.");let i=`${this.requestPrefix}:${++this.requestSequence}`,o={kind:"request",id:i,protocolVersion:this.protocolVersion,token:this.transportToken,method:t,input:structuredClone(r)};return new Promise((s,a)=>{let l=z6n(t,r,this.requestTimeoutMs),c=setTimeout(()=>{this.pending.delete(i),a(new Ra("not_connected",`Local Agent host request timed out: ${t}.`))},l);this.pending.set(i,{resolve:d=>s(d),reject:a,timeout:c});try{K6n(n,o,this.maxFrameBytes)}catch(d){clearTimeout(c),this.pending.delete(i),a(pqe(d))}})}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}close(){this.disconnect(new Error("Local Agent host client closed."))}receive(t){let r;try{r=JSON.parse(t)}catch{this.disconnect(new Ra("invalid_response","Local Agent host returned malformed JSON."));return}if(Y6n(r)){for(let i of[...this.listeners])i(structuredClone(r.event));return}if(mJt(r)){this.answerHostRequest(r);return}if(!X6n(r)){this.disconnect(new Ra("invalid_response","Local Agent host returned an invalid RPC frame."));return}let n=this.pending.get(r.id);n&&(clearTimeout(n.timeout),this.pending.delete(r.id),r.ok?n.resolve(structuredClone(r.output)):n.reject(new Ra(r.error.code,r.error.message,r.error.reason)))}async answerHostRequest(t){let r=null;if(t.method===yhe){r={ok:!1,error:"This app has no preview."};try{if(this.previewHandler){let i=await this.previewHandler(t.input);r=tqe(i)?i:{ok:!1,error:"The preview gave no usable answer."}}}catch(i){r={ok:!1,error:pqe(i).message}}}else try{let i=this.accountAuthorizer?await this.accountAuthorizer({method:t.input.method,url:t.input.url}):null;r=hJt(i)?i:null}catch{r=null}let n=this.socket;if(!(!n||n.destroyed))try{YJt(n,{kind:"host-response",id:t.id,ok:!0,output:r},this.maxFrameBytes)}catch{}}disconnect(t){let r=this.socket;this.socket=null,r&&!r.destroyed&&r.destroy();for(let n of this.pending.values())clearTimeout(n.timeout),n.reject(t);this.pending.clear(),r&&this.onDisconnect?.(t)}};fqe=class{maxFrameBytes;onFrame;buffer=Buffer.alloc(0);constructor(t,r){this.maxFrameBytes=t,this.onFrame=r}push(t){if(this.buffer=this.buffer.length===0?t:Buffer.concat([this.buffer,t]),this.buffer.length>this.maxFrameBytes&&this.buffer.indexOf(10)<0)throw new Ra("invalid_response","Local Agent host RPC frame exceeds the size limit.");let r=this.buffer.indexOf(10);for(;r>=0;){if(r>this.maxFrameBytes)throw new Ra("invalid_response","Local Agent host RPC frame exceeds the size limit.");let n=this.buffer.subarray(0,r);this.buffer=this.buffer.subarray(r+1);let i=n.toString("utf8").replace(/\r$/,"");i&&this.onFrame(i),r=this.buffer.indexOf(10)}}}});function KJt(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.value!="string"?!1:t.kind==="windows-start-ticks-v1"&&/^\d{16,22}$/.test(t.value)||t.kind==="linux-boot-start-v1"&&/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}:\d+$/.test(t.value)}var hqe=Ae(()=>{"use strict"});import{readFile as tJn}from"node:fs/promises";import{join as ZJt}from"node:path";function Rhe(e){let t=e.isProcessAlive||nJn;try{return!t(e.pid)}catch{return!1}}async function Phe(e){let t=ZJt(e,"agent-host.lock");try{let r=await ezt(t);return r.state==="released"?null:tzt(r)}catch(r){if(The(r,"ENOENT"))return null;throw r}}async function _he(e){let t=ZJt(e,"agent-host.lock");try{let r=await ezt(t);return r.state==="released"?null:{descriptor:tzt(r),transportToken:r.transportToken}}catch(r){if(The(r,"ENOENT"))return null;throw r}}async function ezt(e){return rJn(await tJn(e,"utf8"))}function rJn(e){if(Buffer.byteLength(e)>16384)throw new Error("Agent host authority lease exceeds its size bound.");let t;try{t=JSON.parse(e)}catch{throw new Error("Agent host authority lease is malformed.")}if(!iJn(t)||t.schemaVersion!==1&&t.schemaVersion!==2||typeof t.instanceId!="string"||typeof t.pid!="number"||typeof t.endpoint!="string"||typeof t.protocolVersion!="number"||typeof t.acquiredAt!="number"||typeof t.heartbeatAt!="number"||typeof t.transportToken!="string"||t.transportToken.length<32||t.transportToken.length>256||!t.instanceId.trim()||t.instanceId.length>256||!t.endpoint.trim()||t.endpoint.length>4096||!Number.isSafeInteger(t.pid)||t.pid<=0||!Number.isSafeInteger(t.protocolVersion)||t.protocolVersion<=0||!Number.isSafeInteger(t.acquiredAt)||t.acquiredAt<0||!Number.isSafeInteger(t.heartbeatAt)||t.heartbeatAt<0||t.processBirth!==void 0&&!KJt(t.processBirth)||t.schemaVersion===2&&t.state!=="active"&&t.state!=="released"||t.schemaVersion===1&&t.state!==void 0)throw new Error("Agent host authority lease is invalid.");return t}function tzt(e){return{schemaVersion:e.schemaVersion,instanceId:e.instanceId,pid:e.pid,endpoint:e.endpoint,protocolVersion:e.protocolVersion,acquiredAt:e.acquiredAt,heartbeatAt:e.heartbeatAt,...e.processBirth?{processBirth:{...e.processBirth}}:{}}}function nJn(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return!The(t,"ESRCH")}}function iJn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Bhe=Ae(()=>{"use strict";tL();hqe()});async function gqe(e){let t=NP(e.protocolVersion)||ZD,r=NP(e.connectTimeoutMs)||5e3,n=NP(e.requestTimeoutMs)||3e4,i=await Phe(e.rootDirectory);if(!i)return{attached:!1,reason:"no-host",detail:"No XENO Agent host is running for this user. Start the Agent app, or run the host detached."};if(Rhe({heartbeatAt:i.heartbeatAt,pid:i.pid,at:(e.now||Date.now)(),...e.staleAfterMs===void 0?{}:{staleAfterMs:e.staleAfterMs},...e.isProcessAlive?{isProcessAlive:e.isProcessAlive}:{}}))return{attached:!1,reason:"host-gone",detail:`The recorded Agent host (pid ${i.pid}) is no longer running. Start the Agent app again.`};if(i.protocolVersion!==t)return{attached:!1,reason:"protocol-mismatch",hostProtocol:i.protocolVersion,clientProtocol:t,detail:`The running Agent host speaks protocol ${i.protocolVersion} and this client speaks ${t}. Update whichever is older.`};let o=await _he(e.rootDirectory);if(!o||o.descriptor.instanceId!==i.instanceId)return{attached:!1,reason:"unreachable",detail:"The Agent host changed while connecting. Retry."};let s=new S6({endpoint:o.descriptor.endpoint,transportToken:o.transportToken,protocolVersion:t,requestTimeoutMs:n,...e.onDisconnect?{onDisconnect:e.onDisconnect}:{}});try{await oJn(s,r)}catch(a){return s.close(),{attached:!1,reason:"unreachable",detail:a instanceof Error?a.message:String(a)}}return{attached:!0,session:new mqe({role:"attached-client",descriptor:o.descriptor,transport:s})}}async function oJn(e,t){let r=Date.now()+t,n;do try{await e.connect();return}catch(i){if(n=rzt(i),!sJn(n)||Date.now()>=r)break;await aJn(Math.min(50,Math.max(1,r-Date.now())))}while(Date.now()<r);throw n||new Error("Unable to connect to the local Agent host authority.")}function sJn(e){if(!("code"in e))return!1;let t=e.code;return t==="ENOENT"||t==="ECONNREFUSED"||t==="EPIPE"}function aJn(e){return new Promise(t=>setTimeout(t,e))}function rzt(e){return e instanceof Error?e:new Error(String(e))}var mqe,nzt=Ae(()=>{"use strict";Xy();Bhe();tL();mqe=class{role;descriptor;transport;server;lease;onAuthorityLost;heartbeatTimer;heartbeatPending=!1;closed=!1;closeFlight;constructor(t){this.role=t.role,this.descriptor={...t.descriptor},this.transport=t.transport,this.server=t.server,this.lease=t.lease,this.onAuthorityLost=t.onAuthorityLost,this.lease&&t.heartbeatIntervalMs&&(this.heartbeatTimer=setInterval(()=>{this.heartbeat()},t.heartbeatIntervalMs),this.heartbeatTimer.unref?.())}close(){return this.closed?Promise.resolve():this.closeFlight?this.closeFlight:(this.closeFlight=(async()=>{this.transport.close(),await this.server?.close(),await this.lease?.release(),this.closed=!0,this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0)})().catch(t=>{throw this.closeFlight=void 0,t}),this.closeFlight)}async heartbeat(){if(!(this.closed||this.heartbeatPending||!this.lease)){this.heartbeatPending=!0;try{await this.lease.heartbeat()}catch(t){let r=rzt(t);await this.close().catch(()=>{}),this.onAuthorityLost?.(r)}finally{this.heartbeatPending=!1}}}}});import{createConnection as lJn}from"node:net";import{homedir as cJn}from"node:os";function ozt(e,t={}){return new Promise((r,n)=>{let i=Buffer.alloc(0),o=c=>{clearTimeout(l),e.off("data",a),e.off("end",s),e.off("error",n),c()},s=()=>o(()=>n(new Error("The connection closed before the bridge was set up."))),a=c=>{i=Buffer.concat([i,c]);let d=i.indexOf(10);if(d<0){i.length>1024&&o(()=>n(new Error("The bridge was sent an invalid first line.")));return}let u=i.subarray(0,d).toString("utf8").replace(/\r$/,""),p=i.subarray(d+1);o(()=>{if(e.pause(),p.length>0&&e.unshift(p),!u.startsWith(izt)){n(new Error("The bridge was sent an invalid first line."));return}let f=u.slice(izt.length);if(f===uJn){r(void 0);return}let h=Buffer.from(f,"base64");if(h.length!==32||h.toString("base64")!==f){n(new Error("The bridge was sent an invalid key."));return}r(f)})},l=setTimeout(()=>o(()=>n(new Error("The bridge was not told how to start."))),t.timeoutMs??pJn);e.on("data",a),e.once("end",s),e.once("error",n)})}async function szt(e){let t=await _he(e.rootDirectory);if(!t)throw new Error("No XENO Agent host is running for this user.");let r=lJn(t.descriptor.endpoint);await new Promise((i,o)=>{r.once("connect",i),r.once("error",o)});let n={instanceId:t.descriptor.instanceId,protocolVersion:t.descriptor.protocolVersion,transportToken:t.transportToken,homeDirectory:cJn()};e.output.write(`${dJn}${JSON.stringify(n)}
3251
3251
  `),await new Promise(i=>{let o=()=>{r.destroy(),i()};r.once("close",o),r.once("error",o),e.input.once("end",o),e.input.once("error",o),e.input.pipe(r),r.pipe(e.output,{end:!1})})}var dJn,izt,uJn,pJn,aus,Aqe=Ae(()=>{"use strict";Bhe();tL();dJn="xeno-host-bridge/1 ",izt="xeno-host-bridge-key/1 ",uJn="-",pJn=15e3,aus=64*1024});var fus,azt=Ae(()=>{"use strict";Aqe();tL();fus=8*1024});import{join as fJn,resolve as czt}from"node:path";function JS(e){let t=lzt(e.homeDirectory);if(!t)throw new Error("Agent host homeDirectory is required.");let r=lzt(e.hostRootDirectory);return r||fJn(czt(t,hJn),mJn)}function lzt(e){return typeof e=="string"&&e.trim()?czt(e.trim()):void 0}var hJn,mJn,dzt=Ae(()=>{"use strict";hJn=".xeno",mJn="agent-host-v1"});var C6=Ae(()=>{"use strict";tL();Bhe();hqe();nzt();Aqe();azt();dzt()});import{existsSync as gJn}from"fs";import{join as cf}from"path";import{createDirs as AJn}from"@xenosystem/primitives/dirs";function wJn(e,t=[]){return{pluginDir:cf(e,"plugins"),mcpConfigDir:cf(e,"mcp"),mcpDataDir:cf(e,"mcp"),protectedPaths:[...t,cf(e,"credentials.json")],layout:"legacy"}}function yJn(e,t=[]){return{pluginDir:cf(e.data,"extensions","plugins"),mcpConfigDir:cf(e.config,"extensions","mcp"),mcpDataDir:cf(e.data,"extensions","mcp"),protectedPaths:[...t,e.secrets],layout:"extensions"}}function bJn(e,t){return!uzt(e)&&uzt(t)?t:e}function pzt(e,t=process.env){let r=AJn({home:e,env:t}),n=cf(e,".ssh");return bJn(yJn({data:r.root("data"),config:r.root("config"),secrets:r.root("secrets")},[n]),wJn(cf(e,".xeno"),[n]))}function fzt(e,t){return e.XENO_AGENT_HOST_ROOT?.trim()?cf(t,"coordination"):void 0}var uzt,wqe=Ae(()=>{"use strict";uzt=e=>[cf(e.pluginDir,"plugins.json"),cf(e.pluginDir,"trust.json"),cf(e.mcpConfigDir,"servers.json"),cf(e.mcpConfigDir,"sdk-approvals.json")].some(t=>gJn(t))});import{homedir as vJn}from"node:os";function eo(e={}){if(e.rootDirectory)return new whe(e);let t=JS({homeDirectory:vJn(),...process.env.XENO_AGENT_HOST_ROOT?{hostRootDirectory:process.env.XENO_AGENT_HOST_ROOT}:{}}),r=fzt(process.env,t);return new whe({...e,...r?{rootDirectory:r}:{}})}var qA=Ae(()=>{"use strict";BP();C6();wqe()});function SJn(e){if(e===void 0||e==="")return"";if(!kJn.test(e)||e.split("/").includes(".."))throw new TypeError("pathPrefix must be an absolute path such as /v1/web");return e}function P6(e){return e.signal?{signal:e.signal}:{}}function xJn(e,t){if(!t)return`scrape job ended in ${e}`;let[r,n]=t.split(":",2),i=n?` (${n})`:"";switch(r){case"SITE_BLOCKED":return`the site refused the request${i}; it blocks automated access, so use another source`;case"RATE_LIMITED":return"the site is rate-limiting requests; try again later";case"NOT_FOUND":return"the page does not exist (HTTP 404/410)";case"NETWORK_ERROR":return"the site could not be reached (network error)";case"DEADLINE_EXCEEDED":return"the page did not respond within the time budget";case"MIME_DENIED":return"the page is not a supported document type";case"ROBOTS_DENIED":case"ROBOTS_DISALLOWED":return"the site's robots.txt does not allow this page to be fetched";case"ROBOTS_UNAVAILABLE":return"the site's robots.txt could not be read, so the page was not fetched";default:return/^HTTP_\d{3}$/.test(r??"")?`the site answered HTTP ${r.slice(5)}`:`the page could not be retrieved (${t})`}}function gzt(e,t){let r=e;return{message:t,...typeof r?.code=="string"?{code:r.code}:{},...typeof r?.status=="number"?{status:r.status}:{}}}function CJn(e,t){if(typeof e!="object"||e===null||!Object.isExtensible(e))return e;try{Object.defineProperty(e,"cancellation",{value:t,enumerable:!0,configurable:!0,writable:!0})}catch{}return e}function TJn(e,t){let r=0,n,i=!1;return async o=>{if(!e)return;let s=xI(o.state);if(s&&i)return;let a=vhe(o,r),l=dqe(a);if(!(n===l&&!s)){n=l,r+=1,s&&(i=!0);try{await e(a)}catch(c){throw Object.assign(new Error("job progress listener failed"),{code:"PROGRESS_LISTENER_FAILED",jobId:t,state:a.state,cause:c})}}}}var kJn,_6,Azt=Ae(()=>{"use strict";KD();KD();kJn=/^\/[A-Za-z0-9._~-]+(?:\/[A-Za-z0-9._~-]+)*$/;_6=class{#e;#r;#n;#i;constructor(t){if(this.#e=new URL(t.baseUrl),this.#r=t.token,this.#i=SJn(t.pathPrefix),!this.#r.trim())throw new TypeError("token is required");this.#n=t.fetchImpl??fetch}#o(t){if(this.#i==="")return new URL(t,this.#e);if(!t.startsWith("/v1/"))throw new TypeError("pathPrefix can only rewrite /v1 routes");return new URL(`${this.#i}${t.slice(3)}`,this.#e)}async#t(t,r={}){let n=await this.#n(this.#o(t),{...r,redirect:"error",headers:{authorization:`Bearer ${this.#r}`,...r.body?{"content-type":"application/json"}:{},...r.headers}});if(!n.ok){let i=`HTTP ${n.status}`,o;try{let s=await n.json();i=s.error?.message??i,o=s.error?.code}catch{}throw Object.assign(new Error(i),{status:n.status,...o?{code:o}:{}})}return n.status===204?void 0:await n.json()}async#s(t,r={}){let n=await this.#n(this.#o(t),{...r,redirect:"error",headers:{authorization:`Bearer ${this.#r}`,...r.headers}});if(!n.ok){let i=`HTTP ${n.status}`,o;try{let s=await n.json();i=s.error?.message??i,o=s.error?.code}catch{}throw Object.assign(new Error(i),{status:n.status,...o?{code:o}:{}})}return n}capabilities(){return this.#t("/v1/capabilities")}account(t={}){return this.#t("/v1/account",P6(t))}usage(){return this.#t("/v1/usage")}search(t,r={}){return this.#t("/v1/search",{method:"POST",body:JSON.stringify(t),...P6(r)})}searchAndScrape(t,r={}){return this.#t("/v1/search-and-scrape",{method:"POST",body:JSON.stringify(t),...P6(r)})}scrape(t){return this.#t("/v1/scrape",{method:"POST",body:JSON.stringify(t)})}render(t){return this.#t("/v1/render",{method:"POST",body:JSON.stringify(t)})}map(t){return this.#t("/v1/map",{method:"POST",body:JSON.stringify(t)})}crawl(t){return this.#t("/v1/crawl",{method:"POST",body:JSON.stringify(t)})}batchScrape(t){return this.#t("/v1/batch-scrape",{method:"POST",body:JSON.stringify(t)})}activity(t={}){let r=new URLSearchParams;return t.limit&&r.set("limit",String(t.limit)),t.cursor&&r.set("cursor",t.cursor),this.#t(`/v1/activity?${r}`)}job(t){return this.#t(`/v1/jobs/${encodeURIComponent(t)}`)}frontier(t,r={}){let n=new URLSearchParams;return r.limit&&n.set("limit",String(r.limit)),r.cursor&&n.set("cursor",r.cursor),this.#t(`/v1/jobs/${encodeURIComponent(t)}/frontier?${n}`)}results(t,r={}){let n=new URLSearchParams;return r.limit&&n.set("limit",String(r.limit)),r.cursor&&n.set("cursor",r.cursor),this.#t(`/v1/jobs/${encodeURIComponent(t)}/results?${n}`,P6(r))}async artifact(t,r,n={}){if(!/^artifact:[a-f0-9]{64}$/i.test(r))throw new TypeError("artifactId is invalid");let i=await this.#s(`/v1/jobs/${encodeURIComponent(t)}/artifacts/${r}`,P6(n)),o=i.headers.get("etag")??void 0;return{jobId:t,artifactId:r,mediaType:i.headers.get("content-type")?.split(";",1)[0]?.trim()||"application/octet-stream",bytes:new Uint8Array(await i.arrayBuffer()),...o?{etag:o}:{}}}cancel(t){return this.#t(`/v1/jobs/${encodeURIComponent(t)}/cancel`,{method:"POST"})}resume(t){return this.#t(`/v1/jobs/${encodeURIComponent(t)}/resume`,{method:"POST"})}webhookDeliveries(t){return this.#t(`/v1/jobs/${encodeURIComponent(t)}/webhooks`)}upload(t){return this.#t("/v1/artifacts",{method:"POST",body:JSON.stringify(t)})}parse(t){return this.#t("/v1/parse",{method:"POST",body:JSON.stringify(t)})}extract(t){return this.#t("/v1/extract",{method:"POST",body:JSON.stringify(t)})}monitors(){return this.#t("/v1/monitors")}createMonitor(t){return this.#t("/v1/monitors",{method:"POST",body:JSON.stringify(t)})}monitorChecks(t,r=100){return this.#t(`/v1/monitors/${encodeURIComponent(t)}/checks?limit=${r}`)}setMonitorState(t,r){return this.#t(`/v1/monitors/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify({state:r})})}removeMonitor(t){return this.#t(`/v1/monitors/${encodeURIComponent(t)}`,{method:"DELETE"})}async#a(t,r,n,i){let o;try{({job:o}=await this.cancel(t))}catch(p){return{attempted:!0,trigger:r,jobId:t,outcome:"failed",error:gzt(p,"Web Context cancellation failed")}}let s=i.cancelConfirmationMs??2e3,a=Date.now()+(Number.isFinite(s)&&s>0?s:0),l=i.pollMs??500,c,d=async p=>{try{await n(p)}catch(f){c??=gzt(f,"Web Context progress listener failed during cancellation confirmation")}};for(await d(o);!xI(o.state)&&Date.now()<a;){await new Promise(f=>{setTimeout(f,Math.min(l,Math.max(0,a-Date.now())))});let p;try{({job:p}=await this.job(t))}catch{break}o=p,await d(o)}let u=xI(o.state)?vhe(o,0):void 0;return{attempted:!0,trigger:r,jobId:t,outcome:o.state==="cancelled"?"cancelled":"requested",...u?{terminalProgress:u}:{},...c?{listenerError:c}:{}}}async waitForJob(t,r={}){let n=Date.now()+(r.timeoutMs??12e4),i=TJn(r.onProgress,t),o;try{for(;Date.now()<n;){if(r.signal?.aborted)throw o="abort",r.signal.reason;let{job:s}=await this.job(t);if(await i(s),xI(s.state))return s;await new Promise((a,l)=>{let c=setTimeout(a,r.pollMs??500);r.signal?.addEventListener("abort",()=>{clearTimeout(c),o="abort",l(r.signal?.reason)},{once:!0})})}throw o="timeout",Object.assign(new Error("job wait timed out"),{code:"WAIT_TIMEOUT",jobId:t})}catch(s){let a=o==="abort"?r.cancelOnAbort===!0:o==="timeout"?r.cancelOnTimeout===!0:!1;throw!o||!a?s:CJn(s,await this.#a(t,o,i,r))}}async scrapeAndWait(t,r={}){let n=await this.scrape(t),i=await this.waitForJob(n.job.jobId,r);if(i.state!=="completed"&&i.state!=="partial"){let l;try{let d=(await this.results(i.jobId,{limit:1})).items.find(u=>typeof u.errorCode=="string")?.errorCode;typeof d=="string"&&(l=d)}catch{}throw Object.assign(new Error(xJn(i.state,l)),{code:"JOB_NOT_COMPLETED",jobId:i.jobId,state:i.state,...l?{reason:l}:{}})}let o=await this.results(i.jobId,{limit:1}),s=o.items.find(l=>l.state==="completed"&&typeof l.artifactId=="string")??o.items.find(l=>typeof l.artifactId=="string");if(!s?.artifactId)throw Object.assign(new Error("completed scrape job has no readable artifact"),{code:"JOB_ARTIFACT_MISSING",jobId:i.jobId});let a=await this.artifact(i.jobId,s.artifactId);return{job:i,item:s,artifact:a,text:new TextDecoder().decode(a.bytes)}}}});import{readFileSync as RJn}from"node:fs";function Eqe(e=process.env,t){let r=t??e.XENO_WEB_CONTEXT_MAX_PROVIDER_COST_USD;if(r===void 0)return;let n=Number(r.trim());if(!/^[0-9]+(?:\.[0-9]+)?$/.test(r.trim())||!Number.isFinite(n)||n<0)throw Object.assign(new Error("Web Context provider cost budget must be a finite non-negative decimal USD amount."),{code:"WEB_CONTEXT_INVALID_BUDGET"});return n}function B6(e,t,r,n=5){if(r!==void 0&&(!Number.isSafeInteger(r)||r<1))throw Object.assign(new Error("Web Context account returned an invalid page quota."),{code:"WEB_CONTEXT_INVALID_ACCOUNT"});if(e==="search"&&(!Number.isSafeInteger(n)||n<1||n>20))throw Object.assign(new Error("Web Context search result count must be an integer from 1 to 20."),{code:"WEB_CONTEXT_INVALID_BUDGET"});let i=e==="map"||e==="crawl"?100:e==="search"?n:1;return{maxAttempts:3,maxConcurrency:4,maxBytes:1e7,maxPages:Math.min(i,r??i),maxDurationMs:12e4,maxRedirects:8,maxProviderCostUsd:t??0,...t===void 0?{providerCostMode:"account-default"}:{}}}function _Jn(e=process.env){let t=e.XENO_WEB_CONTEXT_TOKEN?.trim();if(t)return t;let r=e.XENO_WEB_CONTEXT_TOKEN_FILE?.trim();if(r){let n=RJn(r,"utf8").trim();if(n)return n}throw Object.assign(new Error("XENO Web Context is not configured. Set XENO_WEB_CONTEXT_TOKEN or XENO_WEB_CONTEXT_TOKEN_FILE."),{code:"WEB_CONTEXT_NOT_CONFIGURED"})}function BJn(e=process.env,t={}){let r=e.XENO_WEB_CONTEXT_URL?.trim(),n=!!(e.XENO_WEB_CONTEXT_TOKEN?.trim()||e.XENO_WEB_CONTEXT_TOKEN_FILE?.trim());if(r||n)return{baseUrl:r||PJn,token:_Jn(e),source:"explicit",auth:"bearer"};let i=e.XENO_API_KEY?.trim();return i?{baseUrl:wzt,token:i,pathPrefix:yzt,source:"account",auth:"bearer"}:{baseUrl:wzt,pathPrefix:yzt,source:"account",auth:"dpop"}}function $Jn(){return Object.assign(new Error("XENO Web Context needs a XENO account. Sign in with `xeno`, or set XENO_WEB_CONTEXT_URL and XENO_WEB_CONTEXT_TOKEN."),{code:"WEB_CONTEXT_NOT_CONFIGURED"})}function MJn(e={}){return async(t,r)=>{let n=typeof t=="string"?t:t instanceof URL?t.href:t.url,i=(r?.method??"GET").toUpperCase(),s=await(e.accountHost?await e.accountHost():await tl()).authorize(i,n,["inference:run"]),a=new Headers(r?.headers);if(s)return a.set("authorization",`DPoP ${s.token}`),a.set("dpop",s.headers.dpop),fetch(t,{...r,headers:a});let l=qy(e);if(l.state!=="present")throw $Jn();return a.set("authorization",`Bearer ${l.key}`),fetch(t,{...r,headers:a})}}function kqe(e=process.env,t={}){let r=BJn(e,t);return r.auth==="dpop"?new _6({baseUrl:r.baseUrl,token:"dpop-account-session",pathPrefix:r.pathPrefix,fetchImpl:MJn(t)}):new _6({baseUrl:r.baseUrl,token:r.token??"",...r.pathPrefix?{pathPrefix:r.pathPrefix}:{}})}function bzt(e=process.env){let t=Eqe(e),r=B6("fetch",t),n=_ce({actor:{id:"xeno-agent-cli",kind:"agent"},scope:{kind:"local-profile",profileId:"pending-token-scope"},classification:"public",purposePrefix:"xeno-agent-cli:chat",budget:{...r,maxProviderCostUsd:t,durationMs:r.maxDurationMs}});return{client:new Iqe(e),createRequest:(i,o)=>{let s=n(i,o);return i==="search"&&(s.budget.maxPages=B6("search",r.maxProviderCostUsd,void 0,typeof o.maxResults=="number"?o.maxResults:5).maxPages),s}}}var PJn,wzt,yzt,Iqe,Sqe=Ae(()=>{"use strict";Azt();NA();of();at();PJn="http://127.0.0.1:8080",wzt="https://api.xenostudio.ai",yzt="/v1/web";Iqe=class{constructor(t){this.env=t}env;client;account;async search(t){return this.getClient().search(await this.bindTenant(t,"search",t.count))}async scrapeAndWait(t,r){return this.getClient().scrapeAndWait(await this.bindTenant(t,"fetch"),r)}getClient(){return this.client??=kqe(this.env),this.client}async bindTenant(t,r,n){this.account??=this.getClient().account();let i=await this.account,o=B6(r,t.budget.maxProviderCostUsd,i.quota?.maxPagesPerJob,n);return{...t,scope:{kind:"tenant",tenantId:i.tenantId},budget:{...t.budget,maxPages:Math.min(t.budget.maxPages,o.maxPages)}}}}});function $6(e){return e.type==="run.self_review"}function M6(e){return{status:e.status,summary:e.summary,findings:[...e.findings],fixes:[...e.fixes],unverified:[...e.unverified],fixToolCalls:e.fixToolCalls,verificationsRerun:e.verificationsRerun,changedFiles:[...e.changedFiles],durationMs:e.durationMs}}function vzt(e){return e.replace(/\s+/g," ").trim()}function O6(e){let t=vzt(e.summary).replace(/^(?:self[ -]review:\s*)+/i,""),r=[];e.findings.length>0&&r.push(`${e.findings.length} finding${e.findings.length===1?"":"s"}`),e.fixes.length>0&&r.push(`${e.fixes.length} fix${e.fixes.length===1?"":"es"}`),e.unverified.length>0&&r.push(`${e.unverified.length} unverified`);let n=r.length>0?` (${r.join(", ")})`:"";return e.status==="failed"?`Self-review failed: ${t||"no summary"}${n}`:e.status==="timed_out"?`Self-review timed out: ${t||"no summary"}${n}`:`Self-review: ${t||"no issues reported"}${n}`}function xqe(e){let t=[],r=(n,i)=>{if(i.length!==0){t.push(`${n}:`);for(let o of i)t.push(` - ${vzt(o)}`)}};return r("Findings",e.findings),r("Fixes",e.fixes),r("Unverified",e.unverified),e.changedFiles.length>0&&t.push(`Changed files: ${e.changedFiles.join(", ")}`),t.push(`Fix tool calls: ${e.fixToolCalls} \xB7 verifications rerun: ${e.verificationsRerun} \xB7 ${(e.durationMs/1e3).toFixed(1)}s`),t.join(`
@@ -6717,7 +6717,7 @@ ${A.path}`}:{success:!1,output:"",error:`Workflow run not found or cannot be sav
6717
6717
  `),i||(process.exitCode=1)}),e.command("rerun").description("Rerun a previous workflow run").argument("<run-id>","Workflow run ID").option("--json","Emit machine-readable JSON").option("--yes","Start without an interactive approval prompt").action(async(t,r)=>{let n=$l();if(n){sc(n,!!r.json);return}if(!zmr(r.yes)){sc(Xmr(),!!r.json);return}let i;try{i=await fw(o=>o.rerun(t,process.cwd()))}catch(o){sc(zx(o),!!r.json);return}if(r.json){np(qmr(i));return}process.stdout.write(i?Dbe(i):`Workflow run not found: ${t}
6718
6718
  `),i||(process.exitCode=1)}),e.action(()=>{let t=new St().listDefinitions(process.cwd());process.stdout.write(`Workflows: ${t.length}
6719
6719
  `);for(let r of t)process.stdout.write(` ${r.name}
6720
- `)}),e}Pz();Qo();var Fbe=[{name:"pause",status:"paused",description:"Pause future goal turns without clearing the objective or refunding usage"},{name:"resume",status:"active",description:"Resume a nonterminal goal, retaining its identity and remaining allowance"}];Uh();ou();tw();rw();Or();import{randomUUID as w1i}from"node:crypto";async function sgr(e,t,r){let n={history:[...r]};if(typeof e.conversationTranscript!="function")return n;let i;try{i=await e.conversationTranscript({conversationId:t})}catch{return n}if(!i.success||!Array.isArray(i.items))return n;let o=i.items.filter(a=>a.kind==="user").map(a=>a.text),s=r.filter(a=>a.role==="user").map(a=>a.content);if(o.length!==s.length)return n;for(let a=0;a<o.length;a+=1)if(o[a]!==s[a])return n;return{historySource:"host"}}UZe();var y1i=["openConversation","resumeConversation","listProviderLanes","selectProviderLane","attachProviderNative","detachProviderNative","reattachProviderNative","stopProviderNative","reconcileProviderLane"];function b1i(e){let t=e.client,r=y1i.filter(n=>typeof t[n]!="function");if(r.length>0)throw new Error(`HOST_COCKPIT_CLIENT_UPGRADE_REQUIRED: the installed Agent Interface client does not support ${r.join(", ")}. Install the coordinated Agent Interface package release.`);return e.client}function dg(e,t){let r=t.code?`${t.code}: `:"";throw new Error(`${e} failed: ${r}${t.error??"the host returned no safe error"}`)}function QZe(e,t){if(!e.conversationId||!e.hostStorageIdentity)throw new Error("Agent host omitted the durable conversation binding.");if(t&&(t.conversationId!==e.conversationId||t.hostStorageIdentity!==e.hostStorageIdentity))throw new Error("HOST_CONVERSATION_AUTHORITY_MISMATCH: the host returned a different durable binding.");return{schemaVersion:1,conversationId:e.conversationId,hostStorageIdentity:e.hostStorageIdentity}}function pgr(e,t,r){let n=e.slice(1).filter(i=>i!==t);if(n.length>r||n.some(i=>i.startsWith("-")))throw new Error(`Invalid arguments for /provider ${e[0]}; supported option: ${t}.`);return n}function jZe(e){return e.flatMap(t=>{let r=typeof t.content=="string"?t.content:Array.isArray(t.content)?t.content.flatMap(n=>{if(!n||typeof n!="object"||Array.isArray(n))return[];let i=n;return i.type==="text"&&typeof i.text=="string"?[i.text]:[]}).join(""):"";return r.length>0?[{role:t.role,content:r}]:[]})}var Zx=class{constructor(t){this.options=t}options;host;client;activeTurn;laneChosenHere=!1;activeLane;pendingFileRestore;nativeTerminalByLane=new Map;runOptionsByProvider=new Map;async close(){let t=this.host;this.host=void 0,this.client=void 0,t&&await t.session.close()}async useDefaultLane(t){let r=this.options.authority?.();if(r&&!r.carried)throw new Error(r.reason);if(!this.options.loadBinding()){let i=await this.ensureClient(),s=(await Yx(await i.listProviders({includeUnavailable:!0}),()=>i.listProviders({includeUnavailable:!0}))).providers.find(a=>a.id===Kx);if(s?.availability!=="available")throw new Error(s?.safeUnavailableReason??"The Agent host does not offer its own agent.");if(!s.models.some(a=>a.id===t))throw new Error(`Provider ${Kx} does not advertise model ${JSON.stringify(t)}.`)}await this.listLanes();let n=this.activeLane;n&&(n.runtimeProviderId!==Kx||this.laneChosenHere||n.modelId===t)||await this.select(Kx,t)}async steerActiveTurn(t){let r=this.activeTurn;return r?(await(await this.ensureClient()).steerTurn({...r,instruction:t}).catch(()=>{}))?.success===!0:!1}get routesTurnsThroughHost(){return this.activeLane!==void 0||this.options.loadBinding()!==void 0}async delegationHost(){let t=await this.ensureHost(),{binding:r}=await this.ensureConversation();return{host:t,binding:r}}async runTurn(t){let r=await this.ensureHost(),{binding:n}=await this.listLanes(),i=this.activeLane;if(!i)throw new Error("PROVIDER_LANE_REQUIRED: select a host provider with /provider use <provider-id> first.");let o=this.options.authority?.();if(o&&!o.carried)throw new Error(`TURN_AUTHORITY_NOT_CARRIED: ${o.reason}`);let{history:s,execution:a,...l}=t,{run:c,...d}=a??{},u={...o?.carried?o.authority.execution:{},...d,...c&&await this.laneHoldsRunOptions(i.runtimeProviderId)?{run:c}:{}},p=await sgr(r.client,n.conversationId,s??[]);return FZe(r,{...l,onAccepted:f=>{this.activeTurn={conversationId:n.conversationId,requestId:f}},...p,conversationId:n.conversationId,providerId:i.runtimeProviderId,...i.modelId?{modelId:i.modelId}:{},mode:o?.carried?o.authority.mode:this.options.mode(),...o?.carried?{workspace:o.authority.workspace}:{},...Object.keys(u).length>0?{execution:u}:{}}).finally(()=>{this.activeTurn=void 0})}async laneHoldsRunOptions(t){let r=this.runOptionsByProvider.get(t);if(r!==void 0)return r;let o=(await(await this.ensureClient()).listProviders({includeUnavailable:!0})).providers.find(s=>s.id===t)?.capabilities?.["turn.run-options"]?.status==="available";return this.runOptionsByProvider.set(t,o),o}async hostTranscript(){let t=await this.ensureHost(),{binding:r}=await this.ensureConversation(),n=await t.client.conversationTranscript({conversationId:r.conversationId});if(!n.success)throw new Error(n.error??"The Agent host could not read this conversation.");return n.items??[]}async compactOnHost(t){let r=await this.ensureHost(),{binding:n}=await this.listLanes(),i=this.activeLane;if(!i)throw new Error("PROVIDER_LANE_REQUIRED: select a host provider with /provider use <provider-id> first.");let s=(await Yx(await r.client.listProviders(),()=>r.client.listProviders())).providers.find(l=>l.id===i.runtimeProviderId);if(!s)throw new Error(`The Agent host no longer offers provider ${i.runtimeProviderId}.`);let a=await r.client.compactConversation({conversationId:n.conversationId,selection:{providerId:s.id,catalogRevision:s.catalogRevision,...i.modelId?{modelId:i.modelId}:{}},...t?.trim()?{instructions:t.trim()}:{}});if(!a.success||!a.summary||!a.throughRequestId)throw new Error(a.error??"The Agent host could not compact this conversation.");return{summary:a.summary,throughRequestId:a.throughRequestId}}async branchOnHost(t){let r=await this.ensureHost(),{binding:n}=await this.listLanes(),i=this.activeLane,o=t.kind==="rewind"?await r.client.rewindConversation({conversationId:n.conversationId,toRequestId:t.toRequestId}):await r.client.forkConversation({conversationId:n.conversationId,...t.throughRequestId?{throughRequestId:t.throughRequestId}:{}});if(!o.success||!o.conversationId)throw new Error(o.error??`The Agent host could not ${t.kind} this conversation.`);let s=await(await this.ensureClient()).openConversation({conversationId:o.conversationId,mode:this.options.mode(),...this.options.mode()==="development"?{workingDirectory:this.options.workingDirectory()}:{}});s.success||dg("conversation open",s),await this.options.saveBinding(QZe(s)),this.activeLane=s.activeLane,i&&await this.select(i.runtimeProviderId,i.modelId);let a=await r.client.conversationTranscript({conversationId:o.conversationId}),l="restore"in o?o.restore:void 0;return this.pendingFileRestore=l?{...l,conversationId:n.conversationId}:void 0,{conversationId:o.conversationId,items:a.success?a.items??[]:[],...l?{restore:l}:{}}}async restoreRewoundFiles(t={}){let r=this.pendingFileRestore;if(!r)throw new Error("Nothing to restore: no /rewind in this session undid a file change.");if(t.confirm&&!r.previewToken)throw new Error("Preview first: run /rewind files, then /rewind files --confirm.");let n=await this.ensureHost(),i=this.options.workingDirectory(),o=await n.client.requestEngineering("engineering.checkpoints.restore",{rootDirectory:i,checkpointId:r.checkpointId,conversationId:r.conversationId,requestId:r.requestId,...t.confirm?{confirmed:!0,previewToken:r.previewToken,conflictStrategy:t.overwrite?"overwrite":"abort"}:{}});if(!o.success&&!o.conflicts?.length)throw new Error(o.error??"The Agent host could not restore those files.");return t.confirm||(r.previewToken=o.previewToken),o.restored&&(this.pendingFileRestore=void 0),{checkpointId:r.checkpointId,wouldRestoreFiles:o.wouldRestoreFiles??[],conflicts:(o.conflicts??[]).map(s=>({relativePath:s.relativePath,reason:s.reason})),restored:o.restored===!0,restoredFiles:o.restoredFiles??[]}}async execute(t){let r=t[0]?.toLowerCase()??"status";switch(r){case"host":{let i=await(await this.ensureClient()).listProviders({includeUnavailable:!0});return{schemaVersion:"xeno.cli.provider-cockpit.v1",kind:"host",catalogRevision:i.revision,providers:i.providers}}case"use":return this.laneChosenHere=!0,this.select(t[1],t[2]);case"sessions":return this.listLanes();case"status":return this.status();case"native":return this.nativeAttach(t[1]);case"detach":return this.nativeDetach(t[1],t[2]);case"reattach":return this.nativeReattach(t[1],t[2]);case"stop":{let[n,i]=pgr(t,"--force",2);return this.nativeStop(n,i,t.includes("--force"))}case"reconcile":{let[n]=pgr(t,"--ack-partial",1);return this.reconcile(n,t.includes("--ack-partial"))}default:throw new Error(`Unknown host provider command: ${r}`)}}async ensureHost(){if(this.host)return this.host;let t=await this.options.attach();try{let r=b1i(t);return await r.connect(),this.host=t,this.client=r,await this.options.onConnected?.(t).catch(()=>{}),t}catch(r){throw await t.session.close().catch(()=>{}),r}}async ensureClient(){return await this.ensureHost(),this.client}async ensureConversation(){let t=await this.ensureClient(),r=this.options.loadBinding(),n=r?await t.resumeConversation({conversationId:r.conversationId}):await t.openConversation({mode:this.options.mode(),startedIn:"terminal",...this.options.mode()==="development"?{workingDirectory:this.options.workingDirectory()}:{}});n.success||dg(r?"conversation resume":"conversation open",n);let i=QZe(n,r);return r&&n.mode&&n.mode!==this.options.mode()&&(n=await t.openConversation({conversationId:r.conversationId,mode:this.options.mode(),...this.options.mode()==="development"?{workingDirectory:this.options.workingDirectory()}:{}}),n.success||dg("conversation mode transition",n),i=QZe(n,r)),await this.options.saveBinding(i),this.activeLane=n.activeLane,{binding:i,result:n}}async ensureAcpClient(){let t=await this.ensureClient();if(typeof t.requestAcp!="function")throw new Error("HOST_ACP_CLIENT_UPGRADE_REQUIRED: the installed Agent Interface client does not expose requestAcp(). Install @xenosystem/agent-interface-client >= 0.1.217.");return t}async acpList(){return(await this.ensureAcpClient()).requestAcp("acp.agents.list",{})}async acpCatalog(t={}){let r=await this.ensureAcpClient();return t.sync?r.requestAcp("acp.catalog.sync",{refresh:t.refresh!==!1,autoCertify:!1}):r.requestAcp("acp.catalog.list",{...t.refresh?{refresh:!0}:{}})}async acpAddPreset(t){return(await this.ensureAcpClient()).requestAcp("acp.agents.addPreset",{presetId:t})}async acpApprove(t,r="approve"){return(await this.ensureAcpClient()).requestAcp("acp.provider.approve",{agentId:t,action:r})}async acpCertify(t){return(await this.ensureAcpClient()).requestAcp("acp.agent.certify",{agentId:t})}async acpRemove(t){return(await this.ensureAcpClient()).requestAcp("acp.agents.remove",{agentId:t})}async acpModels(t){let r=await this.ensureClient(),i=(await Yx(await r.listProviders({includeUnavailable:!0}),()=>r.listProviders({includeUnavailable:!0}))).providers.find(o=>o.id===t||o.id===`acp:${t}`);if(!i)throw new Error(`The Agent host has no ACP provider ${JSON.stringify(t)}.`);return{providerId:i.id,displayName:i.displayName,availability:i.availability,models:i.models}}async useAcp(t,r){return this.laneChosenHere=!0,this.select(t,r)}async useDefaultSdk(t){return this.laneChosenHere=!0,this.select(Kx,t)}async select(t,r){if(!t)throw new Error("Usage: /provider use <provider-id> [model-id]");let n=await this.ensureClient(),i=await Yx(await n.listProviders({includeUnavailable:!0}),()=>n.listProviders({includeUnavailable:!0})),o=i.providers.find(d=>d.id===t)??i.providers.find(d=>d.id===`acp:${t}`);if(!o)throw new Error(`The Agent host has no provider ${JSON.stringify(t)}.`);let s=o.id;if(o.availability!=="available")throw new Error(o.safeUnavailableReason??`Provider ${s} is unavailable.`);if(r&&!o.models.some(d=>d.id===r))throw new Error(`Provider ${s} does not advertise model ${JSON.stringify(r)}.`);let{binding:a}=await this.ensureConversation(),l=w1i(),c=await n.selectProviderLane({conversationId:a.conversationId,providerId:s,catalogRevision:o.catalogRevision,...r?{modelId:r}:{}},{commandId:l,idempotencyKey:`cli:provider:select:${l}`});if(c.success||dg("provider selection",c),!c.lane)throw new Error("Agent host selected a provider without returning its redacted lane.");return this.activeLane=c.lane,{schemaVersion:"xeno.cli.provider-cockpit.v1",kind:"selected",binding:a,lane:c.lane}}async listLanes(){let t=await this.ensureClient(),{binding:r}=await this.ensureConversation(),n=await t.listProviderLanes({conversationId:r.conversationId,includeHistorical:!0});n.success||dg("provider lane list",n);let i=n.lanes??[];return this.activeLane=i.find(o=>o.laneId===n.activeLaneId),{schemaVersion:"xeno.cli.provider-cockpit.v1",kind:"sessions",binding:r,...n.activeLaneId?{activeLaneId:n.activeLaneId}:{},lanes:i}}async status(){let{binding:t,result:r}=await this.ensureConversation(),n=await this.listLanes();return{schemaVersion:"xeno.cli.provider-cockpit.v1",kind:"status",binding:t,...r.mode?{mode:r.mode}:{},...this.activeLane?{activeLane:this.activeLane}:{},lanes:n.lanes}}async resolveLane(t){let r=await this.listLanes(),n=t??r.activeLaneId;if(!n)throw new Error("No active provider lane. Use /provider use first.");let i=r.lanes.find(o=>o.laneId===n);if(!i)throw new Error(`Provider lane ${JSON.stringify(n)} was not found.`);return{binding:r.binding,lane:i}}async nativeAttach(t){if(!this.options.attachNativeTerminal)throw new Error("NATIVE_TUI_REQUIRES_TTY: native provider attach requires an interactive terminal surface.");let r=await this.ensureHost(),n=await this.ensureClient(),{binding:i,lane:o}=await this.resolveLane(t),s=await n.attachProviderNative({conversationId:i.conversationId,laneId:o.laneId,expectedLaneRevision:o.revision,cols:process.stdout.columns||80,rows:process.stdout.rows||24});if(s.success||dg("native provider attach",s),!s.terminalId)throw new Error("Agent host started a native provider without returning its terminal handle.");if(this.nativeTerminalByLane.set(o.laneId,s.terminalId),await this.options.attachNativeTerminal({host:r,binding:i,lane:o,terminalId:s.terminalId})==="detached"){let l=await n.detachProviderNative({conversationId:i.conversationId,laneId:o.laneId,terminalId:s.terminalId});l.success||dg("native provider detach",l)}else this.nativeTerminalByLane.delete(o.laneId);return{schemaVersion:"xeno.cli.provider-cockpit.v1",kind:"native",binding:i,laneId:o.laneId,terminalId:s.terminalId,...s.laneRevision===void 0?{}:{laneRevision:s.laneRevision}}}async nativeReattach(t,r){if(!this.options.attachNativeTerminal)throw new Error("NATIVE_TUI_REQUIRES_TTY: native provider attach requires an interactive terminal surface.");let n=await this.ensureHost(),i=await this.ensureClient(),o=await this.resolveLane(t),s=r??this.nativeTerminalByLane.get(o.lane.laneId);if(!s)throw new Error("NATIVE_TERMINAL_HANDLE_REQUIRED: pass the terminal id shown when the native TUI was started.");let a=await i.reattachProviderNative({conversationId:o.binding.conversationId,laneId:o.lane.laneId,terminalId:s});if(a.success||dg("native provider reattach",a),this.nativeTerminalByLane.set(o.lane.laneId,s),await this.options.attachNativeTerminal({host:n,binding:o.binding,lane:o.lane,terminalId:s})==="detached"){let c=await i.detachProviderNative({conversationId:o.binding.conversationId,laneId:o.lane.laneId,terminalId:s});c.success||dg("native provider detach",c)}else this.nativeTerminalByLane.delete(o.lane.laneId);return{schemaVersion:"xeno.cli.provider-cockpit.v1",kind:"native-reattached",binding:o.binding,laneId:o.lane.laneId,terminalId:s}}async nativeDetach(t,r){let n=await this.ensureClient(),i=await this.resolveLane(t),o=await n.detachProviderNative({conversationId:i.binding.conversationId,laneId:i.lane.laneId,...r?{terminalId:r}:{}});return o.success||dg("native provider detach",o),{schemaVersion:"xeno.cli.provider-cockpit.v1",kind:"native-detached",binding:i.binding,laneId:i.lane.laneId}}async nativeStop(t,r,n=!1){let i=await this.ensureClient(),o=await this.resolveLane(t),s=await i.stopProviderNative({conversationId:o.binding.conversationId,laneId:o.lane.laneId,...r?{terminalId:r}:{},...n?{force:!0}:{},reason:"Stopped from XENO Agent CLI provider cockpit"});return s.success||dg("native provider stop",s),s.exited===!0&&this.nativeTerminalByLane.delete(o.lane.laneId),{schemaVersion:"xeno.cli.provider-cockpit.v1",kind:"native-stopped",binding:o.binding,laneId:o.lane.laneId,exited:s.exited===!0}}async reconcile(t,r=!1){let n=await this.ensureClient(),i=await this.resolveLane(t),o=await n.reconcileProviderLane({conversationId:i.binding.conversationId,laneId:i.lane.laneId,expectedLaneRevision:i.lane.revision,...r?{acknowledgePartialContext:!0}:{}});if(o.success||dg("provider reconciliation",o),!o.lane)throw new Error("Agent host reconciled a provider without returning its lane projection.");return this.activeLane=o.lane,{schemaVersion:"xeno.cli.provider-cockpit.v1",kind:"reconciled",binding:i.binding,lane:o.lane,acknowledgedPartial:o.acknowledgedPartial===!0}}};function UU(e){if(e.kind==="host"){let t=["**Host Providers**",""];for(let r of e.providers){let n=r.models.map(i=>i.id).join(", ")||"provider default";t.push(` ${r.displayName} (${r.id}) \xB7 ${r.availability}`),t.push(` Models: ${n}`)}return`${t.join(`
6720
+ `)}),e}Pz();Qo();var Fbe=[{name:"pause",status:"paused",description:"Pause future goal turns without clearing the objective or refunding usage"},{name:"resume",status:"active",description:"Resume a nonterminal goal, retaining its identity and remaining allowance"}];Uh();ou();tw();rw();Or();import{randomUUID as w1i}from"node:crypto";async function sgr(e,t,r){let n={history:[...r]};if(typeof e.conversationTranscript!="function")return n;let i;try{i=await e.conversationTranscript({conversationId:t})}catch{return n}if(!i.success||!Array.isArray(i.items))return n;let o=i.items.filter(a=>a.kind==="user").map(a=>a.text),s=r.filter(a=>a.role==="user").map(a=>a.content);if(o.length!==s.length)return n;for(let a=0;a<o.length;a+=1)if(o[a]!==s[a])return n;return{historySource:"host"}}UZe();var y1i=["openConversation","resumeConversation","listProviderLanes","selectProviderLane","attachProviderNative","detachProviderNative","reattachProviderNative","stopProviderNative","reconcileProviderLane"];function b1i(e){let t=e.client,r=y1i.filter(n=>typeof t[n]!="function");if(r.length>0)throw new Error(`HOST_COCKPIT_CLIENT_UPGRADE_REQUIRED: the installed Agent Interface client does not support ${r.join(", ")}. Install the coordinated Agent Interface package release.`);return e.client}function dg(e,t){let r=t.code?`${t.code}: `:"";throw new Error(`${e} failed: ${r}${t.error??"the host returned no safe error"}`)}function QZe(e,t){if(!e.conversationId||!e.hostStorageIdentity)throw new Error("Agent host omitted the durable conversation binding.");if(t&&(t.conversationId!==e.conversationId||t.hostStorageIdentity.length>0&&t.hostStorageIdentity!==e.hostStorageIdentity))throw new Error("HOST_CONVERSATION_AUTHORITY_MISMATCH: the host returned a different durable binding.");return{schemaVersion:1,conversationId:e.conversationId,hostStorageIdentity:e.hostStorageIdentity}}function pgr(e,t,r){let n=e.slice(1).filter(i=>i!==t);if(n.length>r||n.some(i=>i.startsWith("-")))throw new Error(`Invalid arguments for /provider ${e[0]}; supported option: ${t}.`);return n}function jZe(e){return e.flatMap(t=>{let r=typeof t.content=="string"?t.content:Array.isArray(t.content)?t.content.flatMap(n=>{if(!n||typeof n!="object"||Array.isArray(n))return[];let i=n;return i.type==="text"&&typeof i.text=="string"?[i.text]:[]}).join(""):"";return r.length>0?[{role:t.role,content:r}]:[]})}var Zx=class{constructor(t){this.options=t}options;host;client;activeTurn;laneChosenHere=!1;activeLane;pendingFileRestore;nativeTerminalByLane=new Map;runOptionsByProvider=new Map;async close(){let t=this.host;this.host=void 0,this.client=void 0,t&&await t.session.close()}async useDefaultLane(t){let r=this.options.authority?.();if(r&&!r.carried)throw new Error(r.reason);if(!this.options.loadBinding()){let i=await this.ensureClient(),s=(await Yx(await i.listProviders({includeUnavailable:!0}),()=>i.listProviders({includeUnavailable:!0}))).providers.find(a=>a.id===Kx);if(s?.availability!=="available")throw new Error(s?.safeUnavailableReason??"The Agent host does not offer its own agent.");if(!s.models.some(a=>a.id===t))throw new Error(`Provider ${Kx} does not advertise model ${JSON.stringify(t)}.`)}await this.listLanes();let n=this.activeLane;n&&(n.runtimeProviderId!==Kx||this.laneChosenHere||n.modelId===t)||await this.select(Kx,t)}async steerActiveTurn(t){let r=this.activeTurn;return r?(await(await this.ensureClient()).steerTurn({...r,instruction:t}).catch(()=>{}))?.success===!0:!1}get routesTurnsThroughHost(){return this.activeLane!==void 0||this.options.loadBinding()!==void 0}async delegationHost(){let t=await this.ensureHost(),{binding:r}=await this.ensureConversation();return{host:t,binding:r}}async runTurn(t){let r=await this.ensureHost(),{binding:n}=await this.listLanes(),i=this.activeLane;if(!i)throw new Error("PROVIDER_LANE_REQUIRED: select a host provider with /provider use <provider-id> first.");let o=this.options.authority?.();if(o&&!o.carried)throw new Error(`TURN_AUTHORITY_NOT_CARRIED: ${o.reason}`);let{history:s,execution:a,...l}=t,{run:c,...d}=a??{},u={...o?.carried?o.authority.execution:{},...d,...c&&await this.laneHoldsRunOptions(i.runtimeProviderId)?{run:c}:{}},p=await sgr(r.client,n.conversationId,s??[]);return FZe(r,{...l,onAccepted:f=>{this.activeTurn={conversationId:n.conversationId,requestId:f}},...p,conversationId:n.conversationId,providerId:i.runtimeProviderId,...i.modelId?{modelId:i.modelId}:{},mode:o?.carried?o.authority.mode:this.options.mode(),...o?.carried?{workspace:o.authority.workspace}:{},...Object.keys(u).length>0?{execution:u}:{}}).finally(()=>{this.activeTurn=void 0})}async laneHoldsRunOptions(t){let r=this.runOptionsByProvider.get(t);if(r!==void 0)return r;let o=(await(await this.ensureClient()).listProviders({includeUnavailable:!0})).providers.find(s=>s.id===t)?.capabilities?.["turn.run-options"]?.status==="available";return this.runOptionsByProvider.set(t,o),o}async hostTranscript(){let t=await this.ensureHost(),{binding:r}=await this.ensureConversation(),n=await t.client.conversationTranscript({conversationId:r.conversationId});if(!n.success)throw new Error(n.error??"The Agent host could not read this conversation.");return n.items??[]}async compactOnHost(t){let r=await this.ensureHost(),{binding:n}=await this.listLanes(),i=this.activeLane;if(!i)throw new Error("PROVIDER_LANE_REQUIRED: select a host provider with /provider use <provider-id> first.");let s=(await Yx(await r.client.listProviders(),()=>r.client.listProviders())).providers.find(l=>l.id===i.runtimeProviderId);if(!s)throw new Error(`The Agent host no longer offers provider ${i.runtimeProviderId}.`);let a=await r.client.compactConversation({conversationId:n.conversationId,selection:{providerId:s.id,catalogRevision:s.catalogRevision,...i.modelId?{modelId:i.modelId}:{}},...t?.trim()?{instructions:t.trim()}:{}});if(!a.success||!a.summary||!a.throughRequestId)throw new Error(a.error??"The Agent host could not compact this conversation.");return{summary:a.summary,throughRequestId:a.throughRequestId}}async branchOnHost(t){let r=await this.ensureHost(),{binding:n}=await this.listLanes(),i=this.activeLane,o=t.kind==="rewind"?await r.client.rewindConversation({conversationId:n.conversationId,toRequestId:t.toRequestId}):await r.client.forkConversation({conversationId:n.conversationId,...t.throughRequestId?{throughRequestId:t.throughRequestId}:{}});if(!o.success||!o.conversationId)throw new Error(o.error??`The Agent host could not ${t.kind} this conversation.`);let s=await(await this.ensureClient()).openConversation({conversationId:o.conversationId,mode:this.options.mode(),...this.options.mode()==="development"?{workingDirectory:this.options.workingDirectory()}:{}});s.success||dg("conversation open",s),await this.options.saveBinding(QZe(s)),this.activeLane=s.activeLane,i&&await this.select(i.runtimeProviderId,i.modelId);let a=await r.client.conversationTranscript({conversationId:o.conversationId}),l="restore"in o?o.restore:void 0;return this.pendingFileRestore=l?{...l,conversationId:n.conversationId}:void 0,{conversationId:o.conversationId,items:a.success?a.items??[]:[],...l?{restore:l}:{}}}async restoreRewoundFiles(t={}){let r=this.pendingFileRestore;if(!r)throw new Error("Nothing to restore: no /rewind in this session undid a file change.");if(t.confirm&&!r.previewToken)throw new Error("Preview first: run /rewind files, then /rewind files --confirm.");let n=await this.ensureHost(),i=this.options.workingDirectory(),o=await n.client.requestEngineering("engineering.checkpoints.restore",{rootDirectory:i,checkpointId:r.checkpointId,conversationId:r.conversationId,requestId:r.requestId,...t.confirm?{confirmed:!0,previewToken:r.previewToken,conflictStrategy:t.overwrite?"overwrite":"abort"}:{}});if(!o.success&&!o.conflicts?.length)throw new Error(o.error??"The Agent host could not restore those files.");return t.confirm||(r.previewToken=o.previewToken),o.restored&&(this.pendingFileRestore=void 0),{checkpointId:r.checkpointId,wouldRestoreFiles:o.wouldRestoreFiles??[],conflicts:(o.conflicts??[]).map(s=>({relativePath:s.relativePath,reason:s.reason})),restored:o.restored===!0,restoredFiles:o.restoredFiles??[]}}async execute(t){let r=t[0]?.toLowerCase()??"status";switch(r){case"host":{let i=await(await this.ensureClient()).listProviders({includeUnavailable:!0});return{schemaVersion:"xeno.cli.provider-cockpit.v1",kind:"host",catalogRevision:i.revision,providers:i.providers}}case"use":return this.laneChosenHere=!0,this.select(t[1],t[2]);case"sessions":return this.listLanes();case"status":return this.status();case"native":return this.nativeAttach(t[1]);case"detach":return this.nativeDetach(t[1],t[2]);case"reattach":return this.nativeReattach(t[1],t[2]);case"stop":{let[n,i]=pgr(t,"--force",2);return this.nativeStop(n,i,t.includes("--force"))}case"reconcile":{let[n]=pgr(t,"--ack-partial",1);return this.reconcile(n,t.includes("--ack-partial"))}default:throw new Error(`Unknown host provider command: ${r}`)}}async ensureHost(){if(this.host)return this.host;let t=await this.options.attach();try{let r=b1i(t);return await r.connect(),this.host=t,this.client=r,await this.options.onConnected?.(t).catch(()=>{}),t}catch(r){throw await t.session.close().catch(()=>{}),r}}async ensureClient(){return await this.ensureHost(),this.client}async ensureConversation(){let t=await this.ensureClient(),r=this.options.loadBinding(),n=r?await t.resumeConversation({conversationId:r.conversationId}):await t.openConversation({mode:this.options.mode(),startedIn:"terminal",...this.options.mode()==="development"?{workingDirectory:this.options.workingDirectory()}:{}});n.success||dg(r?"conversation resume":"conversation open",n);let i=QZe(n,r);return r&&n.mode&&n.mode!==this.options.mode()&&(n=await t.openConversation({conversationId:r.conversationId,mode:this.options.mode(),...this.options.mode()==="development"?{workingDirectory:this.options.workingDirectory()}:{}}),n.success||dg("conversation mode transition",n),i=QZe(n,r)),await this.options.saveBinding(i),this.activeLane=n.activeLane,{binding:i,result:n}}async ensureAcpClient(){let t=await this.ensureClient();if(typeof t.requestAcp!="function")throw new Error("HOST_ACP_CLIENT_UPGRADE_REQUIRED: the installed Agent Interface client does not expose requestAcp(). Install @xenosystem/agent-interface-client >= 0.1.217.");return t}async acpList(){return(await this.ensureAcpClient()).requestAcp("acp.agents.list",{})}async acpCatalog(t={}){let r=await this.ensureAcpClient();return t.sync?r.requestAcp("acp.catalog.sync",{refresh:t.refresh!==!1,autoCertify:!1}):r.requestAcp("acp.catalog.list",{...t.refresh?{refresh:!0}:{}})}async acpAddPreset(t){return(await this.ensureAcpClient()).requestAcp("acp.agents.addPreset",{presetId:t})}async acpApprove(t,r="approve"){return(await this.ensureAcpClient()).requestAcp("acp.provider.approve",{agentId:t,action:r})}async acpCertify(t){return(await this.ensureAcpClient()).requestAcp("acp.agent.certify",{agentId:t})}async acpRemove(t){return(await this.ensureAcpClient()).requestAcp("acp.agents.remove",{agentId:t})}async acpModels(t){let r=await this.ensureClient(),i=(await Yx(await r.listProviders({includeUnavailable:!0}),()=>r.listProviders({includeUnavailable:!0}))).providers.find(o=>o.id===t||o.id===`acp:${t}`);if(!i)throw new Error(`The Agent host has no ACP provider ${JSON.stringify(t)}.`);return{providerId:i.id,displayName:i.displayName,availability:i.availability,models:i.models}}async useAcp(t,r){return this.laneChosenHere=!0,this.select(t,r)}async useDefaultSdk(t){return this.laneChosenHere=!0,this.select(Kx,t)}async select(t,r){if(!t)throw new Error("Usage: /provider use <provider-id> [model-id]");let n=await this.ensureClient(),i=await Yx(await n.listProviders({includeUnavailable:!0}),()=>n.listProviders({includeUnavailable:!0})),o=i.providers.find(d=>d.id===t)??i.providers.find(d=>d.id===`acp:${t}`);if(!o)throw new Error(`The Agent host has no provider ${JSON.stringify(t)}.`);let s=o.id;if(o.availability!=="available")throw new Error(o.safeUnavailableReason??`Provider ${s} is unavailable.`);if(r&&!o.models.some(d=>d.id===r))throw new Error(`Provider ${s} does not advertise model ${JSON.stringify(r)}.`);let{binding:a}=await this.ensureConversation(),l=w1i(),c=await n.selectProviderLane({conversationId:a.conversationId,providerId:s,catalogRevision:o.catalogRevision,...r?{modelId:r}:{}},{commandId:l,idempotencyKey:`cli:provider:select:${l}`});if(c.success||dg("provider selection",c),!c.lane)throw new Error("Agent host selected a provider without returning its redacted lane.");return this.activeLane=c.lane,{schemaVersion:"xeno.cli.provider-cockpit.v1",kind:"selected",binding:a,lane:c.lane}}async listLanes(){let t=await this.ensureClient(),{binding:r}=await this.ensureConversation(),n=await t.listProviderLanes({conversationId:r.conversationId,includeHistorical:!0});n.success||dg("provider lane list",n);let i=n.lanes??[];return this.activeLane=i.find(o=>o.laneId===n.activeLaneId),{schemaVersion:"xeno.cli.provider-cockpit.v1",kind:"sessions",binding:r,...n.activeLaneId?{activeLaneId:n.activeLaneId}:{},lanes:i}}async status(){let{binding:t,result:r}=await this.ensureConversation(),n=await this.listLanes();return{schemaVersion:"xeno.cli.provider-cockpit.v1",kind:"status",binding:t,...r.mode?{mode:r.mode}:{},...this.activeLane?{activeLane:this.activeLane}:{},lanes:n.lanes}}async resolveLane(t){let r=await this.listLanes(),n=t??r.activeLaneId;if(!n)throw new Error("No active provider lane. Use /provider use first.");let i=r.lanes.find(o=>o.laneId===n);if(!i)throw new Error(`Provider lane ${JSON.stringify(n)} was not found.`);return{binding:r.binding,lane:i}}async nativeAttach(t){if(!this.options.attachNativeTerminal)throw new Error("NATIVE_TUI_REQUIRES_TTY: native provider attach requires an interactive terminal surface.");let r=await this.ensureHost(),n=await this.ensureClient(),{binding:i,lane:o}=await this.resolveLane(t),s=await n.attachProviderNative({conversationId:i.conversationId,laneId:o.laneId,expectedLaneRevision:o.revision,cols:process.stdout.columns||80,rows:process.stdout.rows||24});if(s.success||dg("native provider attach",s),!s.terminalId)throw new Error("Agent host started a native provider without returning its terminal handle.");if(this.nativeTerminalByLane.set(o.laneId,s.terminalId),await this.options.attachNativeTerminal({host:r,binding:i,lane:o,terminalId:s.terminalId})==="detached"){let l=await n.detachProviderNative({conversationId:i.conversationId,laneId:o.laneId,terminalId:s.terminalId});l.success||dg("native provider detach",l)}else this.nativeTerminalByLane.delete(o.laneId);return{schemaVersion:"xeno.cli.provider-cockpit.v1",kind:"native",binding:i,laneId:o.laneId,terminalId:s.terminalId,...s.laneRevision===void 0?{}:{laneRevision:s.laneRevision}}}async nativeReattach(t,r){if(!this.options.attachNativeTerminal)throw new Error("NATIVE_TUI_REQUIRES_TTY: native provider attach requires an interactive terminal surface.");let n=await this.ensureHost(),i=await this.ensureClient(),o=await this.resolveLane(t),s=r??this.nativeTerminalByLane.get(o.lane.laneId);if(!s)throw new Error("NATIVE_TERMINAL_HANDLE_REQUIRED: pass the terminal id shown when the native TUI was started.");let a=await i.reattachProviderNative({conversationId:o.binding.conversationId,laneId:o.lane.laneId,terminalId:s});if(a.success||dg("native provider reattach",a),this.nativeTerminalByLane.set(o.lane.laneId,s),await this.options.attachNativeTerminal({host:n,binding:o.binding,lane:o.lane,terminalId:s})==="detached"){let c=await i.detachProviderNative({conversationId:o.binding.conversationId,laneId:o.lane.laneId,terminalId:s});c.success||dg("native provider detach",c)}else this.nativeTerminalByLane.delete(o.lane.laneId);return{schemaVersion:"xeno.cli.provider-cockpit.v1",kind:"native-reattached",binding:o.binding,laneId:o.lane.laneId,terminalId:s}}async nativeDetach(t,r){let n=await this.ensureClient(),i=await this.resolveLane(t),o=await n.detachProviderNative({conversationId:i.binding.conversationId,laneId:i.lane.laneId,...r?{terminalId:r}:{}});return o.success||dg("native provider detach",o),{schemaVersion:"xeno.cli.provider-cockpit.v1",kind:"native-detached",binding:i.binding,laneId:i.lane.laneId}}async nativeStop(t,r,n=!1){let i=await this.ensureClient(),o=await this.resolveLane(t),s=await i.stopProviderNative({conversationId:o.binding.conversationId,laneId:o.lane.laneId,...r?{terminalId:r}:{},...n?{force:!0}:{},reason:"Stopped from XENO Agent CLI provider cockpit"});return s.success||dg("native provider stop",s),s.exited===!0&&this.nativeTerminalByLane.delete(o.lane.laneId),{schemaVersion:"xeno.cli.provider-cockpit.v1",kind:"native-stopped",binding:o.binding,laneId:o.lane.laneId,exited:s.exited===!0}}async reconcile(t,r=!1){let n=await this.ensureClient(),i=await this.resolveLane(t),o=await n.reconcileProviderLane({conversationId:i.binding.conversationId,laneId:i.lane.laneId,expectedLaneRevision:i.lane.revision,...r?{acknowledgePartialContext:!0}:{}});if(o.success||dg("provider reconciliation",o),!o.lane)throw new Error("Agent host reconciled a provider without returning its lane projection.");return this.activeLane=o.lane,{schemaVersion:"xeno.cli.provider-cockpit.v1",kind:"reconciled",binding:i.binding,lane:o.lane,acknowledgedPartial:o.acknowledgedPartial===!0}}};function UU(e){if(e.kind==="host"){let t=["**Host Providers**",""];for(let r of e.providers){let n=r.models.map(i=>i.id).join(", ")||"provider default";t.push(` ${r.displayName} (${r.id}) \xB7 ${r.availability}`),t.push(` Models: ${n}`)}return`${t.join(`
6721
6721
  `)}
6722
6722
  `}if(e.kind==="selected")return`Selected host provider ${e.lane.providerDisplayName??e.lane.runtimeProviderId}${e.lane.modelId?` / ${e.lane.modelId}`:""} on lane ${e.lane.laneId}.
6723
6723
  `;if(e.kind==="sessions"){let t=["**Provider Sessions**",""];for(let r of e.lanes){let n=r.laneId===e.activeLaneId?"*":" ";t.push(`${n} ${r.laneId} ${r.runtimeProviderId} ${r.status} r${r.revision}`)}return e.lanes.length===0&&t.push(" No provider lanes yet."),`${t.join(`
@@ -10511,8 +10511,8 @@ ${t}`);return e.options[Number.parseInt(r,10)-1]?.value??null};async function vk
10511
10511
  `)}
10512
10512
  Choose an option:`),o=Number.parseInt(i,10);if(Number.isInteger(o)&&o>=1&&o<=e.options.length){let a=e.options[o-1];return{answer:a,selectedOption:a}}let s=e.options.find(a=>a===i.trim());if(s)return{answer:s,selectedOption:s};throw new Error("AskUser expected one of the provided options")}return{answer:await vke(t?`${e.question}
10513
10513
  ${t}`:e.question)}}}function aBr(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Izi(e){let t=e.requestedSchema;if(!t||!aBr(t.properties))return[];let r=new Set(Array.isArray(t.required)?t.required.filter(i=>typeof i=="string"):[]),n=[];for(let[i,o]of Object.entries(t.properties)){if(!aBr(o))continue;let s=o.type,a=s==="number"||s==="integer"||s==="boolean"?s:"string",l=Array.isArray(o.enum)?o.enum.filter(c=>typeof c=="string"||typeof c=="number"||typeof c=="boolean").map(String):void 0;n.push({name:i,type:a,required:r.has(i),...typeof o.description=="string"?{description:o.description}:{},...l&&l.length>0?{options:l}:{}})}return n}function Ezi(e){let t=e.required?"required":"optional",r=e.options&&e.options.length>0?` options=${e.options.join("|")}`:"",n=e.description?` - ${e.description}`:"";return`${e.name} (${e.type}, ${t})${r}${n}`}function kzi(e,t){if(e.type==="boolean"){let r=t.trim().toLowerCase();if(r==="true"||r==="yes"||r==="1")return!0;if(r==="false"||r==="no"||r==="0")return!1;throw new Error(`Expected boolean value for MCP elicitation field "${e.name}"`)}if(e.type==="number"||e.type==="integer"){let r=Number(t);if(!Number.isFinite(r)||e.type==="integer"&&!Number.isInteger(r))throw new Error(`Expected ${e.type} value for MCP elicitation field "${e.name}"`);return r}return t}function Szi(e){return async t=>{let r=Izi(t),n=await e({question:`MCP server "${t.serverName}" requests input: ${t.message}`,context:["Do not provide secrets or credentials through MCP elicitation.",...r.length>0?["Fields:",...r.map(s=>`- ${Ezi(s)}`)]:[]].join(`
10514
- `),options:["accept","decline","cancel"]}),i=n.selectedOption??n.answer.trim().toLowerCase();if(i==="cancel")return{action:"cancel"};if(i!=="accept")return{action:"decline"};let o={};for(let s of r){let a=await e({question:`MCP ${t.serverName}: ${s.name}${s.required?" (required)":" (optional)"}`,...s.description?{context:s.description}:{},...s.options&&s.options.length>0?{options:s.options}:{}}),l=(a.selectedOption??a.answer).trim();!l&&!s.required||(o[s.name]=kzi(s,l))}return{action:"accept",content:o}}}function i$r(e,t,r,n,i,o,s,a){let l=sl({cwd:e,askUser:n,sandbox:o,...s?{ownerSessionId:s}:{}});if(ug(l,e),i){let c=XR(r,t);hI(i,l,[],d=>wD(d,c)&&(a?.capabilities.mcpServers===void 0||a.capabilities.mcpServers.includes(d.server)))}return l}function lBr(e){let t=e.trim().replace(/\s+/g,"_");return t.length>64?`${t.slice(0,61)}...`:t}function o$r(e){if(!e)return[];try{return e.listResources().slice(0,50).map(t=>{let r=lBr(t.server),n=lBr(t.name??t.uri);return{name:`@mcp/${r}/${n}`,description:`MCP resource${t.mimeType?` (${t.mimeType})`:""}`,insertText:`@mcp/${encodeURIComponent(t.server)}/${encodeURIComponent(t.uri)} `}})}catch{return[]}}var xzi=new Set(["Send","CoordinationSend"]);function cBr(e){return xzi.has(e)}async function s$r(e){if(!e.enabled)return{refreshMcpTools:()=>{},reconcile:async()=>{},dispose:()=>{}};let t=()=>{let m=e.getProfile?.();if(e.getProfile&&!m)throw new Error("Parent profile is unavailable; MCP connection was refused.");return m},r=t(),n=r?.capabilities.mcpServers,i=()=>{let m=t()?.capabilities.mcpServers;return n===void 0?m:n.filter(g=>m===void 0||m.includes(g))},o=m=>{let g=i();return g===void 0||g.includes(m)},s=EE({...e.askUser?{handleElicitation:Szi(e.askUser)}:{},...r?{permissionProfile:Za(r.capabilities.permissionProfile)??void 0}:{}}),a=[],l=!1,c=new Map,d=(m,g)=>{if(l||!e.onServerStateChanged)return;let A=Kbe(m,g);c.get(m)!==A&&(!c.has(m)&&c.size>=128&&c.delete(c.keys().next().value),c.set(m,A),e.onServerStateChanged(A))},u=()=>{l||(a=hI(s,e.toolRegistry,a,m=>o(m.server)),ui(e.toolRegistry,t()?.capabilities.tools))},p=s.onServerStateChanged(m=>{l||((m.reason==="tools_changed"||m.reason==="prompts_changed"||m.reason==="resources_changed"||m.reason==="connected"||m.reason==="disconnected")&&u(),e.onServerStateChanged&&(m.reason==="connected"?(c.delete(m.serverName),e.onServerStateChanged(`MCP connected: ${m.serverName}`)):m.reason==="tools_changed"?e.onServerStateChanged(`MCP tools updated: ${m.serverName}`):m.reason==="prompts_changed"?e.onServerStateChanged(`MCP prompts updated: ${m.serverName}`):m.reason==="resources_changed"?e.onServerStateChanged(`MCP resources updated: ${m.serverName}`):m.reason==="resource_updated"&&m.resourceUri?e.onServerStateChanged(`MCP resource updated: ${m.serverName} ${m.resourceUri}`):m.reason==="error"&&m.state.error&&d(m.serverName,m.state.error)))}),f=async m=>{let g=await Yz(s,{cwd:e.cwd,allowedServers:i(),...m?{promptForApproval:m}:{}}),A=await M_(s,{cwd:e.cwd,filter:w=>o(w.name),...m?{promptForApproval:m}:{}});return LF(g,A)},h;try{h=await f(e.promptForApproval)}catch(m){throw l=!0,p(),s.dispose(),m}for(let m of h.errors)d(m.name,m.error);return u(),{mcpManager:s,refreshMcpTools:u,reconcile:async()=>{if(l)throw new Error("MCP runtime is disposed.");await f(),u()},dispose:()=>{if(!l){l=!0,p(),c.clear();for(let m of a)e.toolRegistry.unregister(m);a=[],s.dispose()}},summary:Azi(h)}}async function yat(e,t=process.platform){try{if((await DA()).authenticated)return!0}catch{}if(US(t))return process.stderr.write(bo("XENO chat requires account sign-in, which is available on Windows and Linux. On this operating system, use `xeno run` with XENO_API_KEY for unattended execution.")),process.exitCode=1,!1;let n=await jst({skipSuccessScreen:!0,preferDeviceCode:!!(process.env.SSH_CONNECTION||process.env.SSH_CLIENT||process.env.SSH_TTY)});return n.kind==="exit"?(process.stderr.write(FD()),process.exitCode=0,!1):n.kind==="error"?(process.stderr.write(bo(n.message)),process.exitCode=1,!1):(await DA()).authenticated?(Tfe()===!1&&process.stderr.write(`${Rfe}
10515
- `),!0):(process.stderr.write(bo("XENO sign-in did not establish current request authority.")),process.exitCode=1,!1)}async function Czi(e){try{if((await DA()).authenticated)return!0}catch{}return process.stderr.write("XENO account sign-in is required for chat. Run `xeno` in an interactive terminal to sign in, or `xeno login --device`. For unattended API-key execution, use `xeno run`.\n"),process.exitCode=1,!1}async function a$r(e,t,r,n,i,o){let s=OX(e.executionAuthority);if(s){if(e.executionOwnerId)throw new Error("--execution-owner cannot be combined with an execution authority: the authority names the owner from this host's executor token.");return await gfr(s,t,{...i?{claimHandoffId:i}:{},...o?{onOwnershipLost:o}:{},readContext:()=>Fye(Ze.getSessionDir(t))})}return new _P({sessionId:r,...e.executionOwnerId??n?{ownerId:e.executionOwnerId??n}:{},...i?{claimHandoffId:i}:{}})}async function l$r(e){let t=EHe(),r=process.cwd(),n=e.agentName?.trim()?Vi(e.agentName,r).compiled:e.agentProfile??Vi("assistant",r).compiled,i=e.role??n?.memory.role,o=n?.memory.scope,s=n?Za(n.capabilities.permissionProfile)??void 0:void 0,a="";s6(r);let l=oat(e.accessibilityMode);Q_r(l),e.accessibilityMode=l;let c=nhe();if(!process.stdin.isTTY){await dBr(e);return}let d=l==="plain"||!!e.lineInput||process.env.XENO_LINE_INPUT==="1"||!e.rawTui&&c.recommendedInputMode==="line",u=_ar(),p=!d&&!u&&!!e.peerLaunch&&!QWt()&&(await iE()).available,f;if(_fe()&&!US(process.platform))p||(await ZW().catch(()=>{}),f=DA().then(Ut=>Ut.authenticated,()=>!1),await new Promise(Ut=>setImmediate(Ut)));else if(!await S1("auth-sign-in-check",()=>yat(e)))return;if(d){if(f&&!await f&&!await S1("auth-sign-in-check",()=>yat(e)))return;await dBr(e);return}if(!rI(r)){if(!(await Oar(r)).trusted){process.stderr.write(FD()),process.exitCode=0;return}Ale(r,!0)}if(p&&e.peerLaunch){await t(),await bI(),await $ar({cwd:r,...e.peerLaunch,apiKey:e.apiKey,initialSessionId:typeof e.resume=="string"?e.resume:void 0});return}let h=u?new rwe(u):void 0,m,g=!1,A=()=>{},w=new Promise(Ut=>{A=Ut}),y=Promise.resolve(),b=0,I=Date.now(),v,E,S,x,k,C,P,_,R,B=null,$,M=()=>{},j=()=>{},D=async()=>{},N=async()=>{},Q,L={},U=!1,re,ce={},ne=new Set,ie=Hst(yt),he=async(Ut,Wa)=>{let Ci=`session-${Ut.meta.id}`;if(re?.sessionId===Ci&&!Wa){await re.assertOwned();return}let Pr=await a$r(e,Ut.meta.id,Ci,re?.ownerId,Wa,Qe=>{if(re===Pr)try{ce.current?.(Qe)}catch{}});try{await S1("execution-lease",()=>Pr.start())}catch(Qe){throw await Pr.stop(),Qe}let Jr=re;re=Pr,await Jr?.stop()},ke=!1,Se=null,_e=null,we=null,Ve,$e,wt,et=null,ze,Xe=new Promise(Ut=>{ze=Ut}),pr=Gst(),$s,pa,ii=()=>($s??=Promise.resolve().then(bc),$s),bc=async()=>{ke=!0,f&&await Promise.race([f.catch(()=>!1),new Promise(Ut=>setTimeout(Ut,1e4).unref())]);try{await lj(Vst({peerRuntime:()=>Ve?.stop(),artifactRuntime:()=>$e?.stop(),stopHooks:async()=>{L.current&&await yb(L.current,void 0,{command:"chat",mode:"tui"})},timers:()=>{Se&&clearInterval(Se),Se=null,_e&&clearInterval(_e),_e=null,wt&&clearInterval(wt),wt=void 0},directShell:()=>we?.interrupt(),backgroundProcesses:()=>ie.cleanup(),imagePreviews:[...ne].map(Ut=>()=>qst(Ut,H5)),agentCredential:()=>et?.close(),mcp:()=>j(),providerCockpit:()=>Q?.close(),executionLease:()=>re?.stop(),sessionRuntime:()=>uP({sessionManager:E,auditLogger:C,modelUsage:pa?.()}),computerHost:t,accountHost:bI,terminal:()=>v?.cleanup(),processListeners:()=>{h?.close(),pr.dispose()}}))}catch(Ut){throw process.exitCode=1,process.stderr.write(`${a_r(Ut)}
10514
+ `),options:["accept","decline","cancel"]}),i=n.selectedOption??n.answer.trim().toLowerCase();if(i==="cancel")return{action:"cancel"};if(i!=="accept")return{action:"decline"};let o={};for(let s of r){let a=await e({question:`MCP ${t.serverName}: ${s.name}${s.required?" (required)":" (optional)"}`,...s.description?{context:s.description}:{},...s.options&&s.options.length>0?{options:s.options}:{}}),l=(a.selectedOption??a.answer).trim();!l&&!s.required||(o[s.name]=kzi(s,l))}return{action:"accept",content:o}}}function i$r(e,t,r,n,i,o,s,a){let l=sl({cwd:e,askUser:n,sandbox:o,...s?{ownerSessionId:s}:{}});if(ug(l,e),i){let c=XR(r,t);hI(i,l,[],d=>wD(d,c)&&(a?.capabilities.mcpServers===void 0||a.capabilities.mcpServers.includes(d.server)))}return l}function lBr(e){let t=e.trim().replace(/\s+/g,"_");return t.length>64?`${t.slice(0,61)}...`:t}function o$r(e){if(!e)return[];try{return e.listResources().slice(0,50).map(t=>{let r=lBr(t.server),n=lBr(t.name??t.uri);return{name:`@mcp/${r}/${n}`,description:`MCP resource${t.mimeType?` (${t.mimeType})`:""}`,insertText:`@mcp/${encodeURIComponent(t.server)}/${encodeURIComponent(t.uri)} `}})}catch{return[]}}var xzi=new Set(["Send","CoordinationSend"]);function cBr(e){return xzi.has(e)}async function s$r(e){if(!e.enabled)return{refreshMcpTools:()=>{},reconcile:async()=>{},dispose:()=>{}};let t=()=>{let m=e.getProfile?.();if(e.getProfile&&!m)throw new Error("Parent profile is unavailable; MCP connection was refused.");return m},r=t(),n=r?.capabilities.mcpServers,i=()=>{let m=t()?.capabilities.mcpServers;return n===void 0?m:n.filter(g=>m===void 0||m.includes(g))},o=m=>{let g=i();return g===void 0||g.includes(m)},s=EE({...e.askUser?{handleElicitation:Szi(e.askUser)}:{},...r?{permissionProfile:Za(r.capabilities.permissionProfile)??void 0}:{}}),a=[],l=!1,c=new Map,d=(m,g)=>{if(l||!e.onServerStateChanged)return;let A=Kbe(m,g);c.get(m)!==A&&(!c.has(m)&&c.size>=128&&c.delete(c.keys().next().value),c.set(m,A),e.onServerStateChanged(A))},u=()=>{l||(a=hI(s,e.toolRegistry,a,m=>o(m.server)),ui(e.toolRegistry,t()?.capabilities.tools))},p=s.onServerStateChanged(m=>{l||((m.reason==="tools_changed"||m.reason==="prompts_changed"||m.reason==="resources_changed"||m.reason==="connected"||m.reason==="disconnected")&&u(),e.onServerStateChanged&&(m.reason==="connected"?(c.delete(m.serverName),e.onServerStateChanged(`MCP connected: ${m.serverName}`)):m.reason==="tools_changed"?e.onServerStateChanged(`MCP tools updated: ${m.serverName}`):m.reason==="prompts_changed"?e.onServerStateChanged(`MCP prompts updated: ${m.serverName}`):m.reason==="resources_changed"?e.onServerStateChanged(`MCP resources updated: ${m.serverName}`):m.reason==="resource_updated"&&m.resourceUri?e.onServerStateChanged(`MCP resource updated: ${m.serverName} ${m.resourceUri}`):m.reason==="error"&&m.state.error&&d(m.serverName,m.state.error)))}),f=async m=>{let g=await Yz(s,{cwd:e.cwd,allowedServers:i(),...m?{promptForApproval:m}:{}}),A=await M_(s,{cwd:e.cwd,filter:w=>o(w.name),...m?{promptForApproval:m}:{}});return LF(g,A)},h;try{h=await f(e.promptForApproval)}catch(m){throw l=!0,p(),s.dispose(),m}for(let m of h.errors)d(m.name,m.error);return u(),{mcpManager:s,refreshMcpTools:u,reconcile:async()=>{if(l)throw new Error("MCP runtime is disposed.");await f(),u()},dispose:()=>{if(!l){l=!0,p(),c.clear();for(let m of a)e.toolRegistry.unregister(m);a=[],s.dispose()}},summary:Azi(h)}}async function yat(e,t=process.platform){if(e.acpProvider?.trim())return!0;try{if((await DA()).authenticated)return!0}catch{}if(US(t))return process.stderr.write(bo("XENO chat requires account sign-in, which is available on Windows and Linux. On this operating system, use `xeno run` with XENO_API_KEY for unattended execution.")),process.exitCode=1,!1;let n=await jst({skipSuccessScreen:!0,preferDeviceCode:!!(process.env.SSH_CONNECTION||process.env.SSH_CLIENT||process.env.SSH_TTY)});return n.kind==="exit"?(process.stderr.write(FD()),process.exitCode=0,!1):n.kind==="error"?(process.stderr.write(bo(n.message)),process.exitCode=1,!1):(await DA()).authenticated?(Tfe()===!1&&process.stderr.write(`${Rfe}
10515
+ `),!0):(process.stderr.write(bo("XENO sign-in did not establish current request authority.")),process.exitCode=1,!1)}async function Czi(e){if(e.acpProvider?.trim())return!0;try{if((await DA()).authenticated)return!0}catch{}return process.stderr.write("XENO account sign-in is required for chat. Run `xeno` in an interactive terminal to sign in, or `xeno login --device`. For unattended API-key execution, use `xeno run`.\n"),process.exitCode=1,!1}async function a$r(e,t,r,n,i,o){let s=OX(e.executionAuthority);if(s){if(e.executionOwnerId)throw new Error("--execution-owner cannot be combined with an execution authority: the authority names the owner from this host's executor token.");return await gfr(s,t,{...i?{claimHandoffId:i}:{},...o?{onOwnershipLost:o}:{},readContext:()=>Fye(Ze.getSessionDir(t))})}return new _P({sessionId:r,...e.executionOwnerId??n?{ownerId:e.executionOwnerId??n}:{},...i?{claimHandoffId:i}:{}})}async function l$r(e){let t=EHe(),r=process.cwd(),n=e.agentName?.trim()?Vi(e.agentName,r).compiled:e.agentProfile??Vi("assistant",r).compiled,i=e.role??n?.memory.role,o=n?.memory.scope,s=n?Za(n.capabilities.permissionProfile)??void 0:void 0,a="";s6(r);let l=oat(e.accessibilityMode);Q_r(l),e.accessibilityMode=l;let c=nhe();if(!process.stdin.isTTY){await dBr(e);return}let d=l==="plain"||!!e.lineInput||process.env.XENO_LINE_INPUT==="1"||!e.rawTui&&c.recommendedInputMode==="line",u=_ar(),p=!d&&!u&&!!e.peerLaunch&&!QWt()&&(await iE()).available,f;if(!e.acpProvider?.trim()&&_fe()&&!US(process.platform))p||(await ZW().catch(()=>{}),f=DA().then(Ut=>Ut.authenticated,()=>!1),await new Promise(Ut=>setImmediate(Ut)));else if(!await S1("auth-sign-in-check",()=>yat(e)))return;if(d){if(f&&!await f&&!await S1("auth-sign-in-check",()=>yat(e)))return;await dBr(e);return}if(!rI(r)){if(!(await Oar(r)).trusted){process.stderr.write(FD()),process.exitCode=0;return}Ale(r,!0)}if(p&&e.peerLaunch){await t(),await bI(),await $ar({cwd:r,...e.peerLaunch,apiKey:e.apiKey,initialSessionId:typeof e.resume=="string"?e.resume:void 0});return}let h=u?new rwe(u):void 0,m,g=!1,A=()=>{},w=new Promise(Ut=>{A=Ut}),y=Promise.resolve(),b=0,I=Date.now(),v,E,S,x,k,C,P,_,R,B=null,$,M=()=>{},j=()=>{},D=async()=>{},N=async()=>{},Q,L={},U=!1,re,ce={},ne=new Set,ie=Hst(yt),he=async(Ut,Wa)=>{let Ci=`session-${Ut.meta.id}`;if(re?.sessionId===Ci&&!Wa){await re.assertOwned();return}let Pr=await a$r(e,Ut.meta.id,Ci,re?.ownerId,Wa,Qe=>{if(re===Pr)try{ce.current?.(Qe)}catch{}});try{await S1("execution-lease",()=>Pr.start())}catch(Qe){throw await Pr.stop(),Qe}let Jr=re;re=Pr,await Jr?.stop()},ke=!1,Se=null,_e=null,we=null,Ve,$e,wt,et=null,ze,Xe=new Promise(Ut=>{ze=Ut}),pr=Gst(),$s,pa,ii=()=>($s??=Promise.resolve().then(bc),$s),bc=async()=>{ke=!0,f&&await Promise.race([f.catch(()=>!1),new Promise(Ut=>setTimeout(Ut,1e4).unref())]);try{await lj(Vst({peerRuntime:()=>Ve?.stop(),artifactRuntime:()=>$e?.stop(),stopHooks:async()=>{L.current&&await yb(L.current,void 0,{command:"chat",mode:"tui"})},timers:()=>{Se&&clearInterval(Se),Se=null,_e&&clearInterval(_e),_e=null,wt&&clearInterval(wt),wt=void 0},directShell:()=>we?.interrupt(),backgroundProcesses:()=>ie.cleanup(),imagePreviews:[...ne].map(Ut=>()=>qst(Ut,H5)),agentCredential:()=>et?.close(),mcp:()=>j(),providerCockpit:()=>Q?.close(),executionLease:()=>re?.stop(),sessionRuntime:()=>uP({sessionManager:E,auditLogger:C,modelUsage:pa?.()}),computerHost:t,accountHost:bI,terminal:()=>v?.cleanup(),processListeners:()=>{h?.close(),pr.dispose()}}))}catch(Ut){throw process.exitCode=1,process.stderr.write(`${a_r(Ut)}
10516
10516
  `),Ut}finally{ze()}},Va=0,th=1500;pr.on("beforeExit",()=>{ii().catch(()=>{process.exitCode=1})}),pr.on("SIGINT",async()=>{let Ut=Date.now();if(Ut-Va>th){Va=Ut,process.stderr.write(V.dim(`
10517
10517
  Press Ctrl+C again to exit.
10518
10518
  `));return}try{await ii(),process.exit(130)}catch{process.exit(1)}}),pr.on("SIGTERM",async()=>{try{await ii(),process.exit(143)}catch{process.exit(1)}}),process.platform==="win32"&&pr.on("SIGBREAK",async()=>{try{await ii(),process.exit(0)}catch{process.exit(1)}});try{let Ut=new St;wa("before-screen"),v=new XD({model:e.model,safeMode:e.safeMode,effort:e.effort,permissionMode:e.resume?"plan":e.permissionMode,executionMode:e.executionMode??"agent",delegationEnabled:!1,...n?{agentProfile:{label:n.profile.presentation.label,glyph:n.profile.presentation.glyph}}:{},maxContextTokens:0,statusLineCommand:process.env.XENO_STATUS_LINE_COMMAND,statusLineStartedAtMs:I,mentionCompletions:()=>o$r($),workflowCompletions:()=>Ut.listDefinitions(process.cwd()).slice(0,50).map(T=>({name:T.name,description:T.description||"Saved workflow"})),onToggleDelegation:T=>{Yg(T),Ge()},onPasteImage:async()=>{if(!_)throw new Error("A session directory is required for private clipboard attachments.");return A_r({directory:Eg(_,"attachments","clipboard")})},onVoiceDictation:()=>rY(),onOpenRewind:async()=>{await Rre()},onOpenAgentSession:T=>G_e(T),onAttachAgentSession:T=>nkt(T),onOpenDelegationAgent:T=>tkt(T),onStopDelegationAgent:T=>{let F=Vg.get(T);!F||F.finished||rh.cancel(F.taskId,"stopped from the delegation dock")&&v.showTransientActivityNotice(`Stopping ${T}`)},onStopAgentSession:T=>amn(T),onOpenWorkflow:T=>lmn(T),onStopWorkflow:T=>cmn(T),onOutputAction:async T=>{if(T.action==="restore"){let W=ga(T.userMessageOrdinal);if(W<0){v.showTransientActivityNotice("Could not find that user turn");return}let le=xu(),xe=le?await le.inspectAtOrAfter(W):null,be=[],J=Ie.messages.length-W;if(be.push(`${V.dim("Messages to remove:")} ${J}`),be.push(""),!xe?.hadRestorePoints)be.push(`${V.dim("Workspace:")} conversation only (no file restore points)`);else{be.push(`${V.dim("Workspace:")} ${xe.exactWorkspaceRestore?"exact restore available":"partial restore (some tools untracked)"}`),xe.unsupportedTools.length>0&&be.push(`${V.dim("Untracked tools:")} ${xe.unsupportedTools.join(", ")}`);let oe=[],de=[];for(let dt of xe.points)for(let qt of dt.mutations)qt.existedBefore?oe.includes(qt.relativePath)||oe.push(qt.relativePath):de.includes(qt.relativePath)||de.push(qt.relativePath);if(oe.length>0){be.push(""),be.push(V.accent("Files to revert:"));for(let dt of oe)be.push(` ${V.dim("~")} ${dt}`)}if(de.length>0){be.push(""),be.push(V.accent("Files to remove (created during turn):"));for(let dt of de)be.push(` ${V.dim("+")} ${dt}`)}oe.length===0&&de.length===0&&(be.push(""),be.push(V.dim("No tracked file changes.")));let st=xe.filePreviews??[];if(st.length>0){be.push(""),be.push(V.accent("Diff preview:"));for(let dt of st.slice(0,3)){let qt=dt.action==="remove"?"remove":"revert";be.push(`${V.dim(qt)} ${dt.relativePath}${dt.truncated?" (truncated)":""}`);for(let ft of dt.lines.slice(0,24))be.push(` ${ft}`);dt.lines.length>24&&be.push(` ...and ${dt.lines.length-24} more diff lines`)}st.length>3&&be.push(`...and ${st.length-3} more file diff previews`)}}await v.infoPanel({title:"Restore Details",subtitle:`Rewind to before: ${T.text}`,lines:be,footerHint:"Enter to restore \u2022 Esc to cancel"}),(await D3(T.userMessageOrdinal)).ok&&Ld(`Restored to before "${T.text}"`);return}if(!(await D3(T.userMessageOrdinal)).ok)return;let H=T.action==="edit"?"Edit":"Retry";if(Ld(`${H}: restored to before "${T.text}"`),T.action==="edit"){v.setInputText(T.text,{cursor:"end",escCancelable:!0});return}v.setInputText(T.text,{cursor:"end",escCancelable:!1}),v.handleEnter()},onFixTypo:T=>ezi(T,e.apiKey),onRewriteAs:(T,F,H)=>tzi(T,F,H,e.apiKey),onSubmit:pBr.bind(T=>{b++;let F=async()=>{if(/^\/(?:new-subchat|subchats)(?:\s|$)/i.test(T)){if(!h){v.writeError("Peer sessions require the fullscreen terminal cockpit.");return}let J=T.match(/^\/subchats\s+limit\s+(\d+)\s*$/i);J?(await h.request("limit",{limit:Number(J[1])}),v.writeInfo(`Peer turn concurrency set to ${J[1]}.`)):await h.request(/^\/new-subchat\s*$/i.test(T)?"new":"menu");return}if(!/^\/(?:exit|quit)(?:\s|$)/i.test(T)&&!/^\/handoff\s+(?:status|cancel|claim)(?:\s|$)/i.test(T))try{await re?.assertOwned()}catch(J){v.writeError(`Execution is detached: ${J instanceof Error?J.message:String(J)}`);return}let le=ZAe(T);if(le!==null){if(!le.trim()||!await bO())return;if(!we){v.writeError("Direct shell runtime is not initialized");return}let J=await we.run(le);J.denied&&v.writeError(J.denied);let te=v.takeQueuedMessage();te&&setTimeout(()=>{v.setInputText(te,{cursor:"end",escCancelable:!1}),v.handleEnter()},50);return}if(h7e(T)&&sat(T)===void 0){if((/^\/(?:goal|loop|rename)(?:\s|$)/i.test(T)||/^\/compact\s*$/i.test(T))&&!await bO())return;let J=await a7e(T,{cwd:r,model:e.model,reasoningEffort:e.effort,permissionMode:e.permissionMode,executionMode:Qe,sessionId:E?.meta.id,sessionName:E?.meta.name,onRenameSession:async te=>{if(Q?.routesTurnsThroughHost)throw new Error("Rename this provider session from its owning host.");await re?.assertOwned();let oe=await CXe(E,te);return v.setSessionName(oe),gr.syncPresence(),oe},peerRuntime:gr,artifactRuntime:yu,costDisplay:v.getCostDisplay(),safeMode:e.safeMode,sessionDir:E?Ze.getSessionDir(E.meta.id):void 0,parentSessionId:E?.meta.id??Ur,memoryManager:x,checkpointManager:S,sessionManager:E,auditLogger:C,mcpManager:$,refreshMcpTools:M,messages:g?Ie.messages:[],onOutput:te=>v.writeOutput(te),onContextCompacted:async te=>{if(!E)throw new Error("A durable CLI session is required to compact context.");await E.transcript.append({type:"context_compressed",data:te})},onAttachProcess:async te=>{if(!Xn){v.writeError("ATTACH_REQUIRES_TTY: terminal attach runtime is not initialized");return}let oe=await Xn.attach(te);oe.ok||v.writeError(oe.message)},reloadConfig:lt,onHelp:async()=>{await v.helpPanel()},onPanel:async te=>{await v.infoPanel(te)},onActionPicker:async te=>await v.actionPicker(te),buildSystemPrompt:Dp,toolDefinitions:()=>Fi.getDefinitions(),requestToolDefinitions:()=>Qe==="chatOnly"?[]:Fi.getDefinitionsForRequest(),maxContextTokens:g?Ie.modelContextWindow:0,contextBudgetSource:Q9?.source,hookRuntime:L.current,outputStyles:f2,turnRestoreManager:B,providerCockpit:Q,executionLeaseSession:re,onBeforeExecutionHandoff:rmn,onClaimExecutionHandoff:async te=>{if(!E)throw new Error("No durable session to reclaim");await Gp(E.meta.id,te)},onExecutionHandoffCancelled:async()=>{if(!E)throw new Error("No durable session to resume");await Gp(E.meta.id,void 0,!0)},onProviderCockpitChanged:te=>{let oe=te.kind==="selected"||te.kind==="reconciled"?te.lane:te.kind==="status"?te.activeLane:te.kind==="sessions"?te.lanes.find(de=>de.laneId===te.activeLaneId):void 0;if(oe){let de=oe.modelDisplayName??oe.modelId;v.setModel(`${oe.providerDisplayName??oe.runtimeProviderId}${de?` / ${de}`:""}`);let st=oe.runtimeProviderId==="acp:agy-local"?"agy -p":oe.runtimeProviderId.startsWith("acp:")?"acp":void 0;v.setProviderSessionStatus({provider:oe.providerDisplayName??oe.runtimeProviderId,...de?{model:de}:{},mode:oe.workspaceEpoch.wireMode,scope:oe.workspaceEpoch.kind,laneId:oe.laneId,state:oe.status,...st?{complianceTag:st}:{}})}}});if(J.handled){if(J.messages&&(Ie.messages=J.messages,await E?.updateMessageCount(J.messages.length)),J.resumeSessionId){await Gp(J.resumeSessionId);return}J.triggerTurnPrompt&&setTimeout(()=>{v.setInputText(J.triggerTurnPrompt,{cursor:"end",escCancelable:!1}),v.handleEnter()},50);return}}if(T==="/login"||T.startsWith("/login ")){let te=T.slice(6).trim().split(/\s+/).filter(Boolean)[0]?.toLowerCase();if(te==="status"){let oe=await LA({validate:!0});v.writeInfo(vI(oe).trimEnd());return}if(te==="api-key"){v.writeOutput(bo("Credential paste is retired. Set XENO_API_KEY before starting unattended execution, or use XENO sign-in."));return}if(te==="help"){v.writeInfo("Xeno auth\nUse `/login` to launch the sign-in welcome screen.\nUse `/login status` to inspect local auth.\nUse XENO_API_KEY for nonpersisted unattended execution.");return}if(!te){let oe=await v.actionPicker({title:"Xeno Sign In",description:"Choose a sign-in method. The chat UI stays attached while Xeno waits for completion.",options:[{value:"browser",label:"Browser Login",detail:"Open xenostudio.ai and authorize this CLI session"},{value:"device-code",label:"Device Code",detail:"Use a one-time code for remote/headless terminals"},{value:"status",label:"Auth Status",detail:"Inspect the current local auth state"}],selectedIndex:0});if(!oe){v.writeInfo("Sign-in cancelled.");return}if(oe==="status"){let ft=await LA({validate:!0});v.writeInfo(vI(ft).trimEnd());return}let de=ft=>new Promise(fe=>{if(ft.aborted){fe("complete");return}ft.addEventListener("abort",()=>fe("complete"),{once:!0})});v.writeInfo(oe==="browser"?"Starting browser sign-in...":"Starting device-code sign-in...");let{runBrowserFlow:st,runDeviceCodeFlow:dt}=await Promise.resolve().then(()=>(D9(),XEe)),qt=oe==="browser"?await st({authBaseURL:pi,apiBaseURL:e.baseURL,silent:!0,waitForCancel:de,onStarted:ft=>{v.writeInfo(["Browser sign-in started.",`Open: ${ft.auth_url}`,`Local callback: ${ft.redirect_uri}`].join(`
@@ -13358,7 +13358,7 @@ Continue it: xeno chat --resume ${d.sessionId}
13358
13358
  `)}
13359
13359
  `)},l=(d,u,p=1)=>{let f=d instanceof Error?d.message:String(d);u?r(`${JSON.stringify({ok:!1,error:f},null,2)}
13360
13360
  `):n(`[!] ${f}
13361
- `),process.exitCode=p},c=new ye("acp").description("Manage and run XENO ACP agents (including ToS-compliant agy -p, Codex, Claude, Gemini, OpenCode) through the shared Agent host");return c.command("list").description("List configured ACP agents and their certification & compliance status").option("--json","Emit machine-readable JSON").action(async d=>{try{let u=await s({},f=>f.acpList()),p=u.agents.length?["Configured ACP agents:",...u.agents.map(f=>` ${f.id.padEnd(16)} ${(f.enabled?"enabled":"disabled").padEnd(9)} cert=${(f.certificationStatus??"not_certified").padEnd(14)} tui=${f.hasNativeTui?"yes":"no "} ${Bxe(f.compliance)}`)]:["No ACP agents configured yet. Run `xeno acp add agy-local --approve --certify` or `xeno acp catalog`."];a(u,d.json,p),u.ok||(process.exitCode=1)}catch(u){l(u,d.json)}}),c.command("catalog").description("List available managed and ACP Registry providers").option("--sync","Refresh and synchronize against the official ACP Registry").option("--json","Emit machine-readable JSON").action(async d=>{try{let u=await s({},m=>m.acpCatalog({sync:!!d.sync,refresh:!!d.sync})),p=u.catalog??u.snapshot,f=p?.providers??p?.entries??[],h=f.length?[`ACP provider catalog (${f.length} entries):`,...f.map(m=>` ${m.id.padEnd(20)} ${m.name.padEnd(28)} status=${String(m.status??(m.ready?"ready":m.installed?"installed":"available"))}`)]:["ACP catalog returned 0 entries."];a(u,d.json,h)}catch(u){l(u,d.json)}}),c.command("add").description("Add a managed ACP provider preset (e.g. agy-local, codex-local, claude-local, kimi)").argument("<preset-id>","Managed preset ID").option("--approve","Approve the provider policy immediately after adding").option("--certify","Run live certification probe after adding/approving").option("--json","Emit machine-readable JSON").action(async(d,u)=>{try{let p=await s({},async g=>{let A=await g.acpAddPreset(d);if(!A.ok||!A.agent)return{ok:!1,stage:"add",added:A};let w=A.agent.id,y,b;return(u.approve||u.certify)&&(y=await g.acpApprove(w,"approve")),u.certify&&(b=await g.acpCertify(w)),{ok:!0,agent:A.agent,...y?{approval:y}:{},...b?{certification:b}:{}}});if(!p.ok){let g=p.added?.reason??`Could not add preset '${d}'.`;a(p,u.json,[`[!] ${g}`]),process.exitCode=2;return}let f=p.certification,h=f?.result?.status??(f?f.success?"certified":"failed":void 0),m=[`Added ACP agent: ${p.agent.id} (${p.agent.name})`,...p.agent.compliance?[`Compliance: ${Bxe(p.agent.compliance)}`]:[],...p.approval?["Policy approval: applied"]:[],...h?[`Certification: ${h}${f?.error?` (${f.error})`:""}`]:[]];a(p,u.json,m),u.certify&&f&&(!f.success||h&&h!=="certified"&&h!=="fixture_only")&&(process.exitCode=3)}catch(p){l(p,u.json)}}),c.command("approve").description("Approve or revoke an ACP provider policy").argument("<id>","Configured ACP agent ID").option("--revoke","Revoke existing approval instead of approving").option("--json","Emit machine-readable JSON").action(async(d,u)=>{try{let p=u.revoke?"revoke":"approve",f=await s({},h=>h.acpApprove(d,p));a(f,u.json,[`ACP policy ${p} for ${d}: ${f.success?f.status:f.safeError??f.status??"failed"}`]),f.success||(process.exitCode=1)}catch(p){l(p,u.json)}}),c.command("certify").description("Run a live certification probe against a configured ACP agent").argument("<id>","Configured ACP agent ID").option("--json","Emit machine-readable JSON").action(async(d,u)=>{try{let p=await s({},h=>h.acpCertify(d)),f=p.result?.status??(p.success?"certified":"failed");a(p,u.json,[`Certification for ${d}: ${f}${p.error?` \u2014 ${p.error}`:""}`]),(!p.success||f!=="certified"&&f!=="fixture_only")&&(process.exitCode=f==="authentication_required"||f==="blocked_by_environment"?3:1)}catch(p){l(p,u.json)}}),c.command("models").description("Discover available models for a configured ACP provider").argument("<id>","ACP provider ID (e.g. agy-local or acp:agy-local)").option("--json","Emit machine-readable JSON").action(async(d,u)=>{try{let p=await s({},h=>h.acpModels(d)),f=p.models.length?[`Models for ${p.displayName} (${p.providerId}, ${p.availability}):`,...p.models.map(h=>` ${h.id.padEnd(32)} ${h.displayName??h.id}`)]:[`No models advertised for ${p.providerId} (availability: ${p.availability}).`];a(p,u.json,f)}catch(p){l(p,u.json)}}),c.command("status").description("Show shared Agent host lease health and configured ACP agent readiness").option("--json","Emit machine-readable JSON").action(async d=>{try{let u=await o(),p=await s({},g=>g.acpList()),f=u.attach.attempted&&u.attach.attached?"connected":u.lease?u.leaseOwnerGone?"stale-lease":`pid=${u.lease.pid}`:"not-running",h={ok:!0,host:u,acp:p},m=[`Shared Agent host: ${f}`,`Configured ACP agents: ${p.agents.length} (${p.agents.filter(g=>g.certificationStatus==="certified").length} certified)`,...p.agents.map(g=>` - ${g.id}: ${g.enabled?"enabled":"disabled"} \xB7 cert=${g.certificationStatus??"not_certified"} \xB7 ${Bxe(g.compliance)}`)];a(h,d.json,m)}catch(u){l(u,d.json)}}),c.command("audit").description("Inspect verifiable ToS and subprocess compliance profiles for configured ACP agents").option("--provider <id>","Filter to a specific ACP provider ID").option("--json","Emit machine-readable JSON").action(async d=>{try{let u=await s({},A=>A.acpList()),f=(d.provider?u.agents.filter(A=>A.id===d.provider||`acp:${A.id}`===d.provider):u.agents).map(A=>{let w=A.compliance?A.compliance.directVendorEndpointsAllowed===!1:!0;return{id:A.id,name:A.name,compliant:w,compliance:A.compliance??null}}),h=f.every(A=>A.compliant),m={ok:h,count:f.length,agents:f},g=f.length?[`XENO ACP Compliance Audit (${h?"PASS":"VIOLATION"}):`,...f.map(A=>` ${A.id.padEnd(16)} ${A.compliant?"COMPLIANT":"VIOLATION"} ${Bxe(A.compliance??void 0)}${A.compliance?.policyCitation?`
13361
+ `),process.exitCode=p},c=new ye("acp").description("Manage and run XENO ACP agents (including ToS-compliant agy -p, Codex, Claude, Gemini, OpenCode) through the shared Agent host");return c.command("list").description("List configured ACP agents and their certification & compliance status").option("--json","Emit machine-readable JSON").action(async d=>{try{let u=await s({},f=>f.acpList()),p=u.agents.length?["Configured ACP agents:",...u.agents.map(f=>` ${f.id.padEnd(16)} ${(f.enabled?"enabled":"disabled").padEnd(9)} cert=${(f.certificationStatus??"not_certified").padEnd(14)} tui=${f.hasNativeTui?"yes":"no "} ${Bxe(f.compliance)}`)]:["No ACP agents configured yet. Run `xeno acp add agy-local --approve --certify` or `xeno acp catalog`."];a(u,d.json,p),u.ok||(process.exitCode=1)}catch(u){l(u,d.json)}}),c.command("catalog").description("List available managed and ACP Registry providers").option("--sync","Refresh and synchronize against the official ACP Registry").option("--json","Emit machine-readable JSON").action(async d=>{try{let u=await s({},m=>m.acpCatalog({sync:!!d.sync,refresh:!!d.sync})),p=u.catalog??u.snapshot,f=p?.providers??p?.entries??[],h=f.length?[`ACP provider catalog (${f.length} entries):`,...f.map(m=>` ${m.id.padEnd(20)} ${m.name.padEnd(28)} status=${String(m.status??(m.ready?"ready":m.installed?"installed":"available"))}`)]:["ACP catalog returned 0 entries."];a(u,d.json,h)}catch(u){l(u,d.json)}}),c.command("add").description("Add a managed ACP provider preset (e.g. agy-local, codex-local, claude-local, kimi)").argument("<preset-id>","Managed preset ID").option("--approve","Approve the provider policy immediately after adding").option("--certify","Run live certification probe after adding/approving").option("--json","Emit machine-readable JSON").action(async(d,u)=>{try{let p=await s({},async A=>{let w=await A.acpAddPreset(d);if(!w.ok||!w.agent)return{ok:!1,stage:"add",added:w};let y=w.agent.id,b,I;return(u.approve||u.certify)&&(b=await A.acpApprove(y,"approve")),u.certify&&(I=await A.acpCertify(y)),{ok:!0,agent:w.agent,...b?{approval:b}:{},...I?{certification:I}:{}}});if(!p.ok){let A=p.added?.reason??`Could not add preset '${d}'.`;a(p,u.json,[`[!] ${A}`]),process.exitCode=2;return}let f=p.certification,h=f?.result?.certification?.status??f?.result?.status??(f?f.success?"certified":"failed":void 0),m=f?.success===!0&&(h===void 0||h==="certified"||h==="fixture_only"||h==="PASSED"||h==="FALLBACK_FIXTURE_ONLY"),g=[`Added ACP agent: ${p.agent.id} (${p.agent.name})`,...p.agent.compliance?[`Compliance: ${Bxe(p.agent.compliance)}`]:[],...p.approval?["Policy approval: applied"]:[],...h?[`Certification: ${h}${f?.error?` (${f.error})`:""}`]:[]];a(p,u.json,g),u.certify&&f&&!m&&(process.exitCode=3)}catch(p){l(p,u.json)}}),c.command("approve").description("Approve or revoke an ACP provider policy").argument("<id>","Configured ACP agent ID").option("--revoke","Revoke existing approval instead of approving").option("--json","Emit machine-readable JSON").action(async(d,u)=>{try{let p=u.revoke?"revoke":"approve",f=await s({},h=>h.acpApprove(d,p));a(f,u.json,[`ACP policy ${p} for ${d}: ${f.success?f.status:f.safeError??f.status??"failed"}`]),f.success||(process.exitCode=1)}catch(p){l(p,u.json)}}),c.command("certify").description("Run a live certification probe against a configured ACP agent").argument("<id>","Configured ACP agent ID").option("--json","Emit machine-readable JSON").action(async(d,u)=>{try{let p=await s({},g=>g.acpCertify(d)),f=p.result,h=f?.certification?.status??f?.status??(p.success?"certified":"failed"),m=p.success&&(h==="certified"||h==="fixture_only"||h==="PASSED"||h==="FALLBACK_FIXTURE_ONLY");a(p,u.json,[`Certification for ${d}: ${h}${p.error?` \u2014 ${p.error}`:""}`]),m||(process.exitCode=h==="authentication_required"||h==="blocked_by_environment"?3:1)}catch(p){l(p,u.json)}}),c.command("models").description("Discover available models for a configured ACP provider").argument("<id>","ACP provider ID (e.g. agy-local or acp:agy-local)").option("--json","Emit machine-readable JSON").action(async(d,u)=>{try{let p=await s({},h=>h.acpModels(d)),f=p.models.length?[`Models for ${p.displayName} (${p.providerId}, ${p.availability}):`,...p.models.map(h=>` ${h.id.padEnd(32)} ${h.displayName??h.id}`)]:[`No models advertised for ${p.providerId} (availability: ${p.availability}).`];a(p,u.json,f)}catch(p){l(p,u.json)}}),c.command("status").description("Show shared Agent host lease health and configured ACP agent readiness").option("--json","Emit machine-readable JSON").action(async d=>{try{let u=await o(),p=await s({},g=>g.acpList()),f=u.attach.attempted&&u.attach.attached?"connected":u.lease?u.leaseOwnerGone?"stale-lease":`pid=${u.lease.pid}`:"not-running",h={ok:!0,host:u,acp:p},m=[`Shared Agent host: ${f}`,`Configured ACP agents: ${p.agents.length} (${p.agents.filter(g=>g.certificationStatus==="certified").length} certified)`,...p.agents.map(g=>` - ${g.id}: ${g.enabled?"enabled":"disabled"} \xB7 cert=${g.certificationStatus??"not_certified"} \xB7 ${Bxe(g.compliance)}`)];a(h,d.json,m)}catch(u){l(u,d.json)}}),c.command("audit").description("Inspect verifiable ToS and subprocess compliance profiles for configured ACP agents").option("--provider <id>","Filter to a specific ACP provider ID").option("--json","Emit machine-readable JSON").action(async d=>{try{let u=await s({},A=>A.acpList()),f=(d.provider?u.agents.filter(A=>A.id===d.provider||`acp:${A.id}`===d.provider):u.agents).map(A=>{let w=A.compliance?A.compliance.directVendorEndpointsAllowed===!1:!0;return{id:A.id,name:A.name,compliant:w,compliance:A.compliance??null}}),h=f.every(A=>A.compliant),m={ok:h,count:f.length,agents:f},g=f.length?[`XENO ACP Compliance Audit (${h?"PASS":"VIOLATION"}):`,...f.map(A=>` ${A.id.padEnd(16)} ${A.compliant?"COMPLIANT":"VIOLATION"} ${Bxe(A.compliance??void 0)}${A.compliance?.policyCitation?`
13362
13362
  policy: ${A.compliance.policyCitation}`:""}`)]:["No matching configured ACP agents found to audit."];a(m,d.json,g),h||(process.exitCode=4)}catch(u){l(u,d.json)}}),c.command("remove").description("Remove a configured ACP agent from the shared Agent host registry").argument("<id>","Configured ACP agent ID").option("--json","Emit machine-readable JSON").action(async(d,u)=>{try{let p=await s({},f=>f.acpRemove(d));a(p,u.json,[p.ok&&p.removed?`Removed ACP agent: ${d}`:`[!] ${p.reason??`ACP agent '${d}' not found.`}`]),p.ok||(process.exitCode=1)}catch(p){l(p,u.json)}}),c.command("run").description("Run a prompt through a configured ACP provider via the shared Agent host").argument("<provider>","ACP provider ID (e.g. agy-local, codex-local, claude-local)").argument("[prompt...]","Prompt text to send").option("-m, --model <id>","Model ID to request from the ACP provider").option("-c, --conversation <id>","Resume an existing host conversation ID").option("--mode <mode>","Workspace mode: chat or development","chat").option("--cwd <dir>","Working directory for development mode").option("--json","Emit NDJSON / structured JSON output").action(async(d,u,p)=>{let f=u.join(" ").trim();if(!f){l('Prompt text is required: `xeno acp run <provider> "<prompt>"`',p.json,2);return}let h=p.mode==="development"?"development":"chat",m=new AbortController,g=()=>{m.abort()};process.once("SIGINT",g);try{await s({mode:h,cwd:p.cwd??t,...p.conversation?{conversationId:p.conversation}:{}},async A=>{let w=await A.useAcp(d,p.model);if(w.kind!=="selected")throw new Error("Could not select ACP provider lane.");let y=!1,b=await A.runTurn({prompt:f,signal:m.signal,onText:S=>{y=!0,p.json?r(`${JSON.stringify({event:"delta",text:S})}
13363
13363
  `):r(S)}}),I=await A.execute(["status"]),v=I.kind==="status"?I.activeLane:w.lane;if(!b.ok){let S={ok:!1,reason:b.reason,detail:b.detail,conversationId:w.binding.conversationId,laneId:v?.laneId};p.json?r(`${JSON.stringify(S)}
13364
13364
  `):n(`