@xenosystem/agent-cli 0.5.188 → 0.5.189
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/cli.js +1 -1
- package/dist/index.js +2 -2
- package/dist/metafile-esm.json +1 -1
- package/dist/sdk-build-identity.json +10 -10
- package/node_modules/@xeno-corporation/account/dist/node.js +11 -6
- package/node_modules/@xeno-corporation/account/dist/node.js.map +1 -1
- package/node_modules/@xeno-corporation/account/dist/node.mjs +11 -6
- package/node_modules/@xeno-corporation/account/dist/node.mjs.map +1 -1
- package/node_modules/@xeno-corporation/account/package.json +1 -1
- package/package.json +6 -6
package/dist/index.js
CHANGED
|
@@ -3218,7 +3218,7 @@ ${Fe}${z.compose(sfe(),z.bold)("\u2717")} ${GW(e)}
|
|
|
3218
3218
|
`)}function yD(){return`
|
|
3219
3219
|
${Fe}${$e("Goodbye.")}
|
|
3220
3220
|
`}var V4n,oVt,sfe,wr,$e,AD,GW,sVt,_S,q4n,J4n,z4n,q,Fe,pVt,t8e,M,afe,lVt,i8e,dVt,HW,xa=we(()=>{"use strict";ud();st();zd();GHt();tfe();e8e();V4n=new Gy(process.stdout),oVt=new Gy(process.stderr),sfe=()=>Ws(),wr=e=>sfe()(e),$e=z.dim,AD=z.bold,GW=e=>sfe()(e),sVt="\u25A0",_S="\u2514",q4n={open:"\x1B[4m",close:"\x1B[24m"};J4n={Read:e=>qm()(e),ReadImage:e=>qm()(e),Glob:e=>qm()(e),Grep:e=>qm()(e),ElfAnalyze:e=>qm()(e),MemoryRead:e=>qm()(e),Write:e=>rP()(e),Edit:e=>rP()(e),MemoryWrite:e=>rP()(e),Bash:e=>V3e()(e),GitStatus:e=>qm()(e),GitDiff:e=>qm()(e),GitLog:e=>qm()(e),GitBranch:e=>qm()(e),GitCommit:e=>V3e()(e),WebSearch:e=>z.cyan(e),WebFetch:e=>z.cyan(e),TaskOutput:e=>qm()(e),TaskInput:e=>z.cyan(e),TaskStop:e=>of()(e)};z4n={Edit:"Update",Glob:"Search",Grep:"Search",WebSearch:"Web Search",WebFetch:"Web Fetch"};q={accent:wr,purple:GW,cyan:GW,dim:$e,bold:AD,red:GW,green:GW},Fe=" ",pVt=1e3,t8e=3;M={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"};afe=30;lVt=3;i8e=class{atLineStart=!0;writeFn;constructor(t){this.writeFn=t??(r=>{V4n.writeOrdered(r,"stream")})}write(t){let r="";for(let n of t)this.atLineStart&&(r+=Fe,this.atLineStart=!1),r+=n,n===`
|
|
3221
|
-
`&&(this.atLineStart=!0);this.writeFn(r)}reset(){this.atLineStart=!0}markLineStarted(){this.atLineStart=!1}},dVt=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],HW=class{interval=null;frameIndex=0;lastLength=0;writeFn;clearFn;constructor(t,r){this.writeFn=t??(n=>{oVt.writeFrame(n,"spinner")}),this.clearFn=r??(()=>{oVt.writeFrame(`\r${" ".repeat(this.lastLength)}\r`,"spinner")})}start(t){this.stop(),this.frameIndex=0,this.interval=setInterval(()=>{let r=dVt[this.frameIndex%dVt.length],n=`${wr(r)} ${$e(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 h3n}from"node:crypto";function m3n(e){return typeof e=="string"&&Ca.some(t=>t.id===e)}function l8e(){let e=xA().uiMascot;return m3n(e)?e:null}function Rh(){return l8e()??g3n}function VW(e){Ao({uiMascot:e})}function bD(){let e=xA().uiColor;return typeof e=="string"&&Vm(e)?H3e(e):H3e()}function yVt(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 A3n(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 w3n(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 wVt(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 c8e(e,t,r,n,i=16){let o=A3n(e,t,r),s=32/i,a=[wVt(n,1.3),n,wVt(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=w3n(h,(u+.5)*s,(c+.5)*s);if(!m)continue;let g=h.m==="O"?a:y3n[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 ffe(e,t,r,n,i={}){let o=i.size??16,s=i.color??!0,a=c8e(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?z.hex(p)("\u2588"):z.compose(z.hex(p),z.bgHex(f))("\u2580"):d+=p?z.hex(p)("\u2580"):z.hex(f)("\u2584"):d+=p&&f?"\u2588":p?"\u2580":"\u2584"}l.push(d)}return l}var Ca,g3n,ur,Bn,y3n,aP=we(()=>{"use strict";ud();Qo();zd();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."}];g3n=Ca[h3n(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});y3n={B:["#FAF9F4","#E4E3DC","#B4B3AA"],C:["#FFFFFF","#F6F5F0","#DAD9D1"],G:["#D2D1CA","#A3A29B","#6F6E68"],Q:["#4A4A48","#2E2E2D","#1E1E1D"],K:["#0B0B0B"],W:["#FFFFFF"],S:["#B4B3AA"]}});var Pe,bo=we(()=>{"use strict";Pe="0.5.188"});import{createHash as lHn,randomUUID as xfe}from"node:crypto";import*as fi from"node:fs/promises";import*as $S from"node:os";import*as Jm from"node:path";import{homedir as kqt,platform as cHn,release as dHn}from"node:os";import{resolve as mqt}from"node:path";import{randomUUID as bHn}from"node:crypto";import{hostname as vHn}from"node:os";import{randomUUID as IHn}from"node:crypto";import{constants as Iqt}from"node:fs";import{lstat as Pfe,mkdir as Eqt,open as F8e,realpath as Q8e}from"node:fs/promises";import{dirname as D8e,isAbsolute as Cqt,join as U8e,relative as EHn,resolve as kHn,sep as SHn}from"node:path";import{createHash as xHn}from"node:crypto";import{createHash as CHn}from"node:crypto";function uHn(){let e=process.env.XENO_AGENT_HOME?.trim();return e?mqt(e):mqt(kqt(),".xeno-agent")}function gqt(e){if(typeof e!="string"||!e.trim()||e.length>512)throw new Sqt("INVALID","Invalid quota identity.");return e}function xqt(e){let t=r=>({id:gqt(r?.id),generation:gqt(r?.generation)});if(!e||e.agent&&!e.team)throw new Sqt("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 Aqt(e){return JSON.stringify(xqt(e))}function $r(e,t,r=16384){let n=e.trim();if(!n||n.length>r)throw new Ce("INVALID",`${t} must be non-empty and no longer than ${r} characters`);return n}function Tfe(e,t){return[...new Set((e??[]).map(r=>$r(r,t)))]}function bqt(e){if(e===void 0)return;if(!e||typeof e!="object"||Array.isArray(e))throw new Ce("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 Ce("INVALID","Unknown goal limit");if(n!==void 0){if(!Number.isSafeInteger(n)||n<=0)throw new Ce("INVALID",`${r} must be a positive safe integer when provided`);t[r]=n}}return t}function AHn(e){if(e){if(e.kind!=="fixed-interval"&&e.kind!=="dynamic")throw new Ce("INVALID","schedule.kind must be fixed-interval or dynamic");if(e.kind==="fixed-interval"&&(!Number.isSafeInteger(e.intervalMs)||(e.intervalMs??0)<=0))throw new Ce("INVALID","Fixed-interval schedules require a positive safe intervalMs");if(e.intervalMs!==void 0&&(!Number.isSafeInteger(e.intervalMs)||e.intervalMs<=0))throw new Ce("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 Ce("INVALID",`schedule.${t} must be an ISO timestamp when provided`)}return Xd(e)}}function Xd(e){return structuredClone(e)}function wI(e){let t=Date.parse(e);return Number.isFinite(t)?t:0}function Rfe(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function wHn(e){return{summary:"Goal created; work has not started.",completedTaskCount:0,totalTaskCount:0,outstanding:[],decisions:[],updatedAt:e}}function yHn(){return{status:"pending",criteria:[],evidence:[]}}function vqt(e){return lHn("sha256").update(e).digest("hex")}function G8e(e){return{algorithm:"sha256",value:xHn("sha256").update(e).digest("hex")}}function _qt(e){if(typeof e!="string"||!e||e.length>2048||Cqt(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 Bqt(e){return G8e(JSON.stringify([e.schemaVersion,e.sessionId,e.totalBytes,e.files.map(t=>[t.path,t.size,t.sha256,t.executable])])).value}function $qt(e,t){if(e.schemaVersion!==1||e.sessionId!==t||!Array.isArray(e.files)||e.files.length>Tqt||!Number.isSafeInteger(e.totalBytes)||e.totalBytes<0||e.totalBytes>Pqt)throw new Error("Invalid handoff snapshot manifest");let r=new Set,n=0;for(let i of e.files){if(_qt(i.path),!Number.isSafeInteger(i.size)||i.size<0||i.size>Rqt||!/^[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||Bqt(e)!==e.digest)throw new Error("Handoff snapshot manifest integrity mismatch")}async function L8e(e,t){let r=e;for(let o of t.split("/"))if(r=U8e(r,o),(await Pfe(r)).isSymbolicLink())throw new Error("Snapshot symlinks are not supported");let n=await Q8e(r),i=EHn(e,n);if(i===".."||i.startsWith(`..${SHn}`)||Cqt(i))throw new Error("Snapshot path escaped its root");return r}async function Mqt(e){if(!e.sessionId||e.sessionId.length>1024||e.paths.length>Tqt)throw new Error("Invalid snapshot scope");let t=await Q8e(e.root),r=[],n=new Map,i=0;for(let s of[...e.paths].sort()){if(e.signal?.throwIfAborted(),_qt(s),!await e.authorizeFile(s))throw new Error("Snapshot file transfer is not authorized");let a=await L8e(t,s),l=await Pfe(a),c=await F8e(a,Iqt.O_RDONLY|(Iqt.O_NOFOLLOW??0));try{let d=await c.stat();if(await L8e(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>Rqt||i+d.size>Pqt)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 Pfe(a);if(await L8e(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=G8e(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=Bqt(o),$qt(o,e.sessionId),{manifest:o,blobs:n}}async function Oqt(e){let t=structuredClone(e.manifest);if($qt(t,e.sessionId),!await e.authorizeManifest(structuredClone(t)))throw new Error("Snapshot restoration is not authorized");e.signal?.throwIfAborted();let r=kHn(e.destination);if(await Q8e(D8e(r))!==D8e(r))throw new Error("Snapshot destination parent must be canonical");try{throw await Pfe(r),new Error("Snapshot destination already exists")}catch(o){if(o.code!=="ENOENT")throw o}let n=`${r}.staging-${IHn()}`;await Eqt(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||G8e(s).value!==o.sha256)throw new Error("Snapshot blob integrity mismatch; staging retained");let a=U8e(n,...o.path.split("/"));await Eqt(D8e(a),{recursive:!0,mode:448});let l=await F8e(a,"wx",o.executable?448:384);try{await l.writeFile(s),await l.sync()}finally{await l.close()}}e.signal?.throwIfAborted();let i=await F8e(U8e(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 Nqt(e){return typeof e=="string"&&THn.test(e)}function MS(e){return`sha256:${CHn("sha256").update(e).digest("hex")}`}var Ce,Hns,Vns,qns,fP,Wns,Sqt,pHn,fHn,hHn,mHn,Cfe,wqt,gHn,yqt,_fe,hP,Tqt,Rqt,Pqt,THn,mP=we(()=>{"use strict";Ce=class extends Error{constructor(e,t,r={}){super(t),this.code=e,this.details=r,this.name="XenoCoordinationError"}code;details},Hns=cHn(),Vns=dHn(),qns=kqt();fP="[redacted]",Wns=[[/-----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${fP}`],[/((?:^|[\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${fP}`],[/\b(Bearer|Basic|Token|DPoP)\s+[A-Za-z0-9._~+/=-]{6,}/gi,`$1 ${fP}`],[/\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,fP],[/\beyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}/g,fP],[/([?&#;](?:access_token|refresh_token|id_token|token|key|api[_-]?key|secret|client_secret|password|signature|sig)=)[^&#\s"'<>]+/gi,`$1${fP}`],[/(\b[a-z][a-z0-9+.-]*:\/\/)[^/\s:@"']+:[^/\s@"']+@/gi,`$1${fP}@`]],Sqt=class extends Error{constructor(e,t){super(t),this.code=e,this.name="QuotaError"}code;retryable=!1};pHn=3e4,fHn=3e4,hHn=6e4,mHn=2e4,Cfe=new Set(["EACCES","EBUSY","EPERM"]),wqt=[5,10,20,40,80,160,320],gHn=[5,10,20,40,80,160,320],yqt=[1,2,3,4];_fe=class{get goalTurnAdmissionVersion(){return 1}rootDirectory;now;idFactory;ownerLeaseMs;lockTimeoutMs;lockStaleMs;maximumEventsPerSession;constructor(e={}){this.rootDirectory=e.rootDirectory??Jm.join(uHn(),"coordination"),this.now=e.now??(()=>new Date().toISOString()),this.idFactory=e.idFactory??(t=>`${t}_${xfe()}`),this.ownerLeaseMs=e.ownerLeaseMs??pHn,this.lockTimeoutMs=e.lockTimeoutMs??fHn,this.lockStaleMs=e.lockStaleMs??hHn,this.maximumEventsPerSession=e.maximumEventsPerSession??mHn}async getSessionState(e){let t=$r(e,"sessionId",1024);return Xd(await this.readState(t))}async fenceAdmission(e,t,r){let n=$r(r.authorityId,"authorityId",512),i=$r(r.operationId,"operationId",512);if(!Number.isSafeInteger(t)||t<0)throw new Ce("INVALID","Expected session version must be a nonnegative safe integer");if(r.action!=="archive"&&r.action!=="delete")throw new Ce("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 Ce("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 Ce("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 Ce("CONFLICT","Lifecycle fence identity does not match");if(o.action==="delete")throw new Ce("CONFLICT","Deleted session admission cannot be restored");if(i.owner)throw new Ce("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 Ce("CONFLICT","Lifecycle fence identity does not match");let s=i.owner;if(s){if(s.host!==$S.hostname()||!Number.isInteger(s.processId)||(s.processId??0)<=0||Rfe(s.processId))throw new Ce("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=Jm.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(Jm.join(e,r),"utf8"));return!yqt.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)=>wI(n.updatedAt)-wI(r.updatedAt)).map(r=>Xd(r))}async createGoal(e){let t=$r(e.sessionId,"sessionId",1024),r=bqt(e.limits);return this.mutate(t,n=>{let i=n.goals.find(l=>["active","paused","waiting","blocked"].includes(l.status));if(i)throw new Ce("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:$r(l,"successCriteria"),required:!0}:{id:l.id?$r(l.id,"successCriteria.id",512):this.idFactory("criterion"),description:$r(l.description,"successCriteria.description"),required:l.required}),a={schemaVersion:1,id:this.idFactory("goal"),version:1,sessionId:t,objective:$r(e.objective,"objective"),...e.why?{why:$r(e.why,"why")}:{},successCriteria:s,constraints:Tfe(e.constraints,"constraints"),...r?{limits:r}:{},metadata:Xd(e.metadata??{}),status:"active",milestones:[],tasks:[],progress:wHn(o),verification:yHn(),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?Xd(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 Ce("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=$r(n.objective,"objective")),n.why!==void 0&&(o.why=$r(n.why,"why")),n.constraints&&(o.constraints=Tfe(n.constraints,"constraints")),n.successCriteria&&(o.successCriteria=Xd(n.successCriteria)),n.progress&&(o.progress={...o.progress,...Xd(n.progress),outstanding:Tfe(n.progress.outstanding??o.progress.outstanding,"progress.outstanding"),decisions:Tfe(n.progress.decisions??o.progress.decisions,"progress.decisions"),updatedAt:this.now()}),n.verification&&(o.verification=Xd(n.verification)),n.metadata&&(o.metadata=Xd(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:$r(n.title,"milestone.title"),...n.description?{description:$r(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 Ce("NOT_FOUND",`Milestone ${n.milestoneId} was not found`);if(n.parentTaskId&&!i.tasks.some(c=>c.id===n.parentTaskId))throw new Ce("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 Ce("NOT_FOUND",`Task dependency ${c} was not found`);let l={id:this.idFactory("task"),milestoneId:s.id,...n.parentTaskId?{parentTaskId:n.parentTaskId}:{},title:$r(n.title,"task.title"),...n.description?{description:$r(n.description,"task.description")}:{},status:a.length===0?"ready":"pending",...n.assignedAgentId?{assignedAgentId:$r(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 Ce("NOT_FOUND",`Task ${r} was not found`);a.status=i.status,i.progress!==void 0&&(a.progress=$r(i.progress,"task.progress")),i.resultEventId!==void 0&&(a.resultEventId=$r(i.resultEventId,"task.resultEventId",512)),i.assignedAgentId!==void 0&&(a.assignedAgentId=$r(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:$r(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 Ce("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 Ce("VERIFICATION_REQUIRED","Required success criteria lack passing evidence",{unmetCriteria:a.map(c=>c.id)});if(s.length===0&&n.evidence.length===0)throw new Ce("VERIFICATION_REQUIRED","Goal completion requires at least one durable evidence reference");let l=this.now();return o.status="completed",o.verification=Xd(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:$r(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 Ce("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 Ce("CONFLICT",`Cannot start a loop for terminal goal ${s.id}`)}if(t.kind==="scheduled"&&!t.schedule)throw new Ce("INVALID","Scheduled loops require schedule metadata");if(t.kind!=="scheduled"&&t.schedule)throw new Ce("INVALID","Only scheduled loops may carry schedule metadata");let r=AHn(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 Ce("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:$r(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?Xd(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 Ce("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 Ce("CONFLICT",`Loop ${t.id} already has a running iteration`);let s=(t.iterations.at(-1)?.number??0)+1;t.currentActivity=$r(n,"activity");let a={number:s,startedAt:r,status:"running",activity:t.currentActivity,...t.goalId&&e.goalTurnAccounting?.[t.goalId]?{goalAccountingVersion:1}:{},...i?{taskId:$r(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=xqt(r),o=await this.getGoal(e.sessionId,e.goalId);if(!o||o.sessionId!==e.sessionId||o.limits?.maxTokens===void 0)throw new Ce("BUDGET_UNAVAILABLE","The exact token-bounded goal is unavailable for quota admission");if(this.isCliGoal(o)&&o.metadata["cli.tokenQuotaVersion"]!==1)throw new Ce("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 Ce("BUDGET_UNAVAILABLE","Quota scope does not identify this durable goal generation");let s=await t.policy(i);if(!s||Aqt(s.scope)!==Aqt(i)||s.limits.tokensLifetime===void 0||s.limits.tokensLifetime===null||s.limits.tokensLifetime>o.limits.maxTokens)throw new Ce("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 Ce("BUDGET_UNAVAILABLE","Goal token accounting has no durable remaining allowance");if(a<1)throw new Ce("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 Ce("INVALID","An exact execution ownership epoch is required");return this.admitGoalTurnWithOwner(e,{...t})}async admitGoalTurnWithOwner(e,t,r){let n=$r(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 Ce("NOT_OWNER","Execution ownership epoch changed");if(this.ownerExpired(d,this.now()))throw new Ce("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 Ce("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 Ce("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 Ce("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 Ce("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 Ce("CONFLICT","Goal continuation loop changed before admission");this.assertVersion(a.id,a.version,e.expectedLoopVersion??-1)}else if(e.expectedLoopVersion!==void 0)throw new Ce("INVALID","A goal turn loop version requires its exact loop ID");if(a&&a.status!=="running")throw new Ce("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 Ce("INVALID","Unknown goal execution lane");return c.goalTurn={requestId:n,requestHash:i,executor:e.executionKind==="local-sdk"?{kind:"local-sdk",processId:process.pid,host:$S.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 Ce("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 Ce("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 Ce("NOT_FOUND","Goal turn was not found");if(o.goalTurn?.requestHash!==t)throw new Ce("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 Ce("NOT_FOUND","Goal turn was not found");if(s.status==="running"){if(!this.goalTurnOwnerExited(s))throw new Ce("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 Ce("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=$r(i.verificationEventId,"verificationEventId",512)),i.error&&(r.error=$r(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 Ce("CONFLICT",`Loop ${o.id} is terminal (${l})`);let c=[...o.iterations].reverse().find(u=>u.status==="running");if(c&&n==="completed")throw new Ce("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=$r(i??n,"reason")),o.status=n,o.kind==="goal-continuation"&&(o.resumeRequested=n==="running"),["stopped","completed","failed"].includes(n)&&(o.stoppedAt=s,o.stopReason=$r(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 Ce("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 Ce("LEASE_EXPIRED",`Ownership lease ${r} expired`);return o.heartbeatAt=this.now(),o.expiresAt=new Date(wI(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!==$S.hostname()||!Rfe(n))throw new Ce("LEASE_EXPIRED",`Ownership lease ${r} expired and cannot be recovered by process ${n}`);let a=this.now(),l=Math.max(0,wI(a)-wI(s.expiresAt));return s.heartbeatAt=a,s.expiresAt=new Date(wI(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:$r(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 Ce("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 Ce("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 Ce("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 Ce("NOT_FOUND",`Loop ${e.loopId} was not found`);let s=n.handoffs.find(c=>["prepared","available","claimed"].includes(c.status));if(s)throw new Ce("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:$r(e.targetOwnerId,"targetOwnerId",512)}:{},sourceLeaseEpoch:i.epoch,...e.workspace?{workspace:$r(e.workspace,"workspace",32768)}:{},...e.branch?{branch:$r(e.branch,"branch",1024)}:{},...e.currentMilestoneId?{currentMilestoneId:e.currentMilestoneId}:{},...e.currentTaskId?{currentTaskId:e.currentTaskId}:{},agentIds:[...new Set(e.agentIds??[])],operations:Xd(e.operations??[]),...e.contextDigest?{contextDigest:$r(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:$r(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 Ce("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 Ce("CONFLICT",`Handoff ${o.id} is ${o.status}`,{claimedBy:o.claimedBy})}if(o.targetOwnerId&&o.targetOwnerId!==e.targetOwnerId)throw new Ce("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 Ce("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:Xd(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 Ce("LEASE_EXPIRED",`Ownership lease ${n} expired`);let a=o.handoffs.find(l=>l.id===t);if(!a)throw new Ce("NOT_FOUND",`Handoff ${t} was not found`);if(a.claimedBy!==r||a.targetLeaseEpoch!==s.epoch||!["claimed","completed"].includes(a.status))throw new Ce("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 Ce("NOT_FOUND",`Handoff ${t} was not found`);if(s.sourceOwnerId!==r)throw new Ce("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 Ce("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 Ce("LEASE_EXPIRED",`Ownership lease ${n} expired`);if(s.sourceLeaseEpoch!==a.epoch)throw new Ce("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 Ce("NOT_FOUND",`Handoff ${t} was not found`);return["completed","cancelled","failed"].includes(i.status)||(i.status="failed",i.failureReason=$r(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 Ce("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 Ce("CONFLICT",`Goal ${i.id} is ${i.status}; no iteration was admitted`);let o=bqt(i.limits);if(o?.maxTokens!==void 0&&!n)throw new Ce("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 Ce("BUDGET_UNAVAILABLE","Goal wall-clock allowance cannot be verified",{goalId:i.id,limit:"maxWallClockMs"});if(a-s>=o.maxWallClockMs)throw new Ce("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 Ce("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 Ce("BUDGET_UNAVAILABLE","Invalid goal iteration accounting");if(a>=o.maxIterations)throw new Ce("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 Ce("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 Ce("BUDGET_UNAVAILABLE","Goal iteration history is invalid");i=o.number}if(r+=i,!Number.isSafeInteger(r))throw new Ce("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 Ce("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 Ce("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 Ce("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 Ce("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=$r(e,"requestHash",64).toLowerCase();if(!/^[0-9a-f]{64}$/.test(t))throw new Ce("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 Ce("BUDGET_UNAVAILABLE","Goal turn count exceeds its supported range");return Xd({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!==$S.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 Ce("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 Ce("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 Ce("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 Ce("INVALID","leaseMs must be a positive safe integer");return{ownerId:$r(e,"ownerId",512),leaseId:this.idFactory("owner"),epoch:t,acquiredAt:n,heartbeatAt:n,expiresAt:new Date(wI(n)+i).toISOString(),...r.processId!==void 0?{processId:r.processId}:{},...r.host?{host:$r(r.host,"host",512)}:{}}}ownerExpired(e,t){return wI(e.expiresAt)<=wI(t)?!0:e.processId!==void 0&&e.host===$S.hostname()&&!Rfe(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:Xd(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=$r(e,"sessionId",1024);return this.withSessionLock(i,async()=>{let o=await this.readState(i);if(o.admissionFence&&!r)throw new Ce("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)),Xd(a)})}statePath(e){return Jm.join(this.rootDirectory,"sessions",`${vqt(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(!yqt.includes(n.schemaVersion)||n.sessionId!==e)throw new Ce("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 Ce("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=Jm.dirname(t);await fi.mkdir(r,{recursive:!0});let n=`${t}.${process.pid}.${xfe()}.tmp`,i=await fi.open(n,"wx");try{await i.writeFile(`${JSON.stringify(e,null,2)}
|
|
3221
|
+
`&&(this.atLineStart=!0);this.writeFn(r)}reset(){this.atLineStart=!0}markLineStarted(){this.atLineStart=!1}},dVt=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],HW=class{interval=null;frameIndex=0;lastLength=0;writeFn;clearFn;constructor(t,r){this.writeFn=t??(n=>{oVt.writeFrame(n,"spinner")}),this.clearFn=r??(()=>{oVt.writeFrame(`\r${" ".repeat(this.lastLength)}\r`,"spinner")})}start(t){this.stop(),this.frameIndex=0,this.interval=setInterval(()=>{let r=dVt[this.frameIndex%dVt.length],n=`${wr(r)} ${$e(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 h3n}from"node:crypto";function m3n(e){return typeof e=="string"&&Ca.some(t=>t.id===e)}function l8e(){let e=xA().uiMascot;return m3n(e)?e:null}function Rh(){return l8e()??g3n}function VW(e){Ao({uiMascot:e})}function bD(){let e=xA().uiColor;return typeof e=="string"&&Vm(e)?H3e(e):H3e()}function yVt(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 A3n(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 w3n(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 wVt(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 c8e(e,t,r,n,i=16){let o=A3n(e,t,r),s=32/i,a=[wVt(n,1.3),n,wVt(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=w3n(h,(u+.5)*s,(c+.5)*s);if(!m)continue;let g=h.m==="O"?a:y3n[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 ffe(e,t,r,n,i={}){let o=i.size??16,s=i.color??!0,a=c8e(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?z.hex(p)("\u2588"):z.compose(z.hex(p),z.bgHex(f))("\u2580"):d+=p?z.hex(p)("\u2580"):z.hex(f)("\u2584"):d+=p&&f?"\u2588":p?"\u2580":"\u2584"}l.push(d)}return l}var Ca,g3n,ur,Bn,y3n,aP=we(()=>{"use strict";ud();Qo();zd();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."}];g3n=Ca[h3n(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});y3n={B:["#FAF9F4","#E4E3DC","#B4B3AA"],C:["#FFFFFF","#F6F5F0","#DAD9D1"],G:["#D2D1CA","#A3A29B","#6F6E68"],Q:["#4A4A48","#2E2E2D","#1E1E1D"],K:["#0B0B0B"],W:["#FFFFFF"],S:["#B4B3AA"]}});var Pe,bo=we(()=>{"use strict";Pe="0.5.189"});import{createHash as lHn,randomUUID as xfe}from"node:crypto";import*as fi from"node:fs/promises";import*as $S from"node:os";import*as Jm from"node:path";import{homedir as kqt,platform as cHn,release as dHn}from"node:os";import{resolve as mqt}from"node:path";import{randomUUID as bHn}from"node:crypto";import{hostname as vHn}from"node:os";import{randomUUID as IHn}from"node:crypto";import{constants as Iqt}from"node:fs";import{lstat as Pfe,mkdir as Eqt,open as F8e,realpath as Q8e}from"node:fs/promises";import{dirname as D8e,isAbsolute as Cqt,join as U8e,relative as EHn,resolve as kHn,sep as SHn}from"node:path";import{createHash as xHn}from"node:crypto";import{createHash as CHn}from"node:crypto";function uHn(){let e=process.env.XENO_AGENT_HOME?.trim();return e?mqt(e):mqt(kqt(),".xeno-agent")}function gqt(e){if(typeof e!="string"||!e.trim()||e.length>512)throw new Sqt("INVALID","Invalid quota identity.");return e}function xqt(e){let t=r=>({id:gqt(r?.id),generation:gqt(r?.generation)});if(!e||e.agent&&!e.team)throw new Sqt("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 Aqt(e){return JSON.stringify(xqt(e))}function $r(e,t,r=16384){let n=e.trim();if(!n||n.length>r)throw new Ce("INVALID",`${t} must be non-empty and no longer than ${r} characters`);return n}function Tfe(e,t){return[...new Set((e??[]).map(r=>$r(r,t)))]}function bqt(e){if(e===void 0)return;if(!e||typeof e!="object"||Array.isArray(e))throw new Ce("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 Ce("INVALID","Unknown goal limit");if(n!==void 0){if(!Number.isSafeInteger(n)||n<=0)throw new Ce("INVALID",`${r} must be a positive safe integer when provided`);t[r]=n}}return t}function AHn(e){if(e){if(e.kind!=="fixed-interval"&&e.kind!=="dynamic")throw new Ce("INVALID","schedule.kind must be fixed-interval or dynamic");if(e.kind==="fixed-interval"&&(!Number.isSafeInteger(e.intervalMs)||(e.intervalMs??0)<=0))throw new Ce("INVALID","Fixed-interval schedules require a positive safe intervalMs");if(e.intervalMs!==void 0&&(!Number.isSafeInteger(e.intervalMs)||e.intervalMs<=0))throw new Ce("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 Ce("INVALID",`schedule.${t} must be an ISO timestamp when provided`)}return Xd(e)}}function Xd(e){return structuredClone(e)}function wI(e){let t=Date.parse(e);return Number.isFinite(t)?t:0}function Rfe(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function wHn(e){return{summary:"Goal created; work has not started.",completedTaskCount:0,totalTaskCount:0,outstanding:[],decisions:[],updatedAt:e}}function yHn(){return{status:"pending",criteria:[],evidence:[]}}function vqt(e){return lHn("sha256").update(e).digest("hex")}function G8e(e){return{algorithm:"sha256",value:xHn("sha256").update(e).digest("hex")}}function _qt(e){if(typeof e!="string"||!e||e.length>2048||Cqt(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 Bqt(e){return G8e(JSON.stringify([e.schemaVersion,e.sessionId,e.totalBytes,e.files.map(t=>[t.path,t.size,t.sha256,t.executable])])).value}function $qt(e,t){if(e.schemaVersion!==1||e.sessionId!==t||!Array.isArray(e.files)||e.files.length>Tqt||!Number.isSafeInteger(e.totalBytes)||e.totalBytes<0||e.totalBytes>Pqt)throw new Error("Invalid handoff snapshot manifest");let r=new Set,n=0;for(let i of e.files){if(_qt(i.path),!Number.isSafeInteger(i.size)||i.size<0||i.size>Rqt||!/^[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||Bqt(e)!==e.digest)throw new Error("Handoff snapshot manifest integrity mismatch")}async function L8e(e,t){let r=e;for(let o of t.split("/"))if(r=U8e(r,o),(await Pfe(r)).isSymbolicLink())throw new Error("Snapshot symlinks are not supported");let n=await Q8e(r),i=EHn(e,n);if(i===".."||i.startsWith(`..${SHn}`)||Cqt(i))throw new Error("Snapshot path escaped its root");return r}async function Mqt(e){if(!e.sessionId||e.sessionId.length>1024||e.paths.length>Tqt)throw new Error("Invalid snapshot scope");let t=await Q8e(e.root),r=[],n=new Map,i=0;for(let s of[...e.paths].sort()){if(e.signal?.throwIfAborted(),_qt(s),!await e.authorizeFile(s))throw new Error("Snapshot file transfer is not authorized");let a=await L8e(t,s),l=await Pfe(a),c=await F8e(a,Iqt.O_RDONLY|(Iqt.O_NOFOLLOW??0));try{let d=await c.stat();if(await L8e(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>Rqt||i+d.size>Pqt)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 Pfe(a);if(await L8e(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=G8e(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=Bqt(o),$qt(o,e.sessionId),{manifest:o,blobs:n}}async function Oqt(e){let t=structuredClone(e.manifest);if($qt(t,e.sessionId),!await e.authorizeManifest(structuredClone(t)))throw new Error("Snapshot restoration is not authorized");e.signal?.throwIfAborted();let r=kHn(e.destination);if(await Q8e(D8e(r))!==D8e(r))throw new Error("Snapshot destination parent must be canonical");try{throw await Pfe(r),new Error("Snapshot destination already exists")}catch(o){if(o.code!=="ENOENT")throw o}let n=`${r}.staging-${IHn()}`;await Eqt(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||G8e(s).value!==o.sha256)throw new Error("Snapshot blob integrity mismatch; staging retained");let a=U8e(n,...o.path.split("/"));await Eqt(D8e(a),{recursive:!0,mode:448});let l=await F8e(a,"wx",o.executable?448:384);try{await l.writeFile(s),await l.sync()}finally{await l.close()}}e.signal?.throwIfAborted();let i=await F8e(U8e(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 Nqt(e){return typeof e=="string"&&THn.test(e)}function MS(e){return`sha256:${CHn("sha256").update(e).digest("hex")}`}var Ce,Hns,Vns,qns,fP,Wns,Sqt,pHn,fHn,hHn,mHn,Cfe,wqt,gHn,yqt,_fe,hP,Tqt,Rqt,Pqt,THn,mP=we(()=>{"use strict";Ce=class extends Error{constructor(e,t,r={}){super(t),this.code=e,this.details=r,this.name="XenoCoordinationError"}code;details},Hns=cHn(),Vns=dHn(),qns=kqt();fP="[redacted]",Wns=[[/-----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${fP}`],[/((?:^|[\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${fP}`],[/\b(Bearer|Basic|Token|DPoP)\s+[A-Za-z0-9._~+/=-]{6,}/gi,`$1 ${fP}`],[/\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,fP],[/\beyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}/g,fP],[/([?&#;](?:access_token|refresh_token|id_token|token|key|api[_-]?key|secret|client_secret|password|signature|sig)=)[^&#\s"'<>]+/gi,`$1${fP}`],[/(\b[a-z][a-z0-9+.-]*:\/\/)[^/\s:@"']+:[^/\s@"']+@/gi,`$1${fP}@`]],Sqt=class extends Error{constructor(e,t){super(t),this.code=e,this.name="QuotaError"}code;retryable=!1};pHn=3e4,fHn=3e4,hHn=6e4,mHn=2e4,Cfe=new Set(["EACCES","EBUSY","EPERM"]),wqt=[5,10,20,40,80,160,320],gHn=[5,10,20,40,80,160,320],yqt=[1,2,3,4];_fe=class{get goalTurnAdmissionVersion(){return 1}rootDirectory;now;idFactory;ownerLeaseMs;lockTimeoutMs;lockStaleMs;maximumEventsPerSession;constructor(e={}){this.rootDirectory=e.rootDirectory??Jm.join(uHn(),"coordination"),this.now=e.now??(()=>new Date().toISOString()),this.idFactory=e.idFactory??(t=>`${t}_${xfe()}`),this.ownerLeaseMs=e.ownerLeaseMs??pHn,this.lockTimeoutMs=e.lockTimeoutMs??fHn,this.lockStaleMs=e.lockStaleMs??hHn,this.maximumEventsPerSession=e.maximumEventsPerSession??mHn}async getSessionState(e){let t=$r(e,"sessionId",1024);return Xd(await this.readState(t))}async fenceAdmission(e,t,r){let n=$r(r.authorityId,"authorityId",512),i=$r(r.operationId,"operationId",512);if(!Number.isSafeInteger(t)||t<0)throw new Ce("INVALID","Expected session version must be a nonnegative safe integer");if(r.action!=="archive"&&r.action!=="delete")throw new Ce("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 Ce("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 Ce("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 Ce("CONFLICT","Lifecycle fence identity does not match");if(o.action==="delete")throw new Ce("CONFLICT","Deleted session admission cannot be restored");if(i.owner)throw new Ce("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 Ce("CONFLICT","Lifecycle fence identity does not match");let s=i.owner;if(s){if(s.host!==$S.hostname()||!Number.isInteger(s.processId)||(s.processId??0)<=0||Rfe(s.processId))throw new Ce("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=Jm.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(Jm.join(e,r),"utf8"));return!yqt.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)=>wI(n.updatedAt)-wI(r.updatedAt)).map(r=>Xd(r))}async createGoal(e){let t=$r(e.sessionId,"sessionId",1024),r=bqt(e.limits);return this.mutate(t,n=>{let i=n.goals.find(l=>["active","paused","waiting","blocked"].includes(l.status));if(i)throw new Ce("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:$r(l,"successCriteria"),required:!0}:{id:l.id?$r(l.id,"successCriteria.id",512):this.idFactory("criterion"),description:$r(l.description,"successCriteria.description"),required:l.required}),a={schemaVersion:1,id:this.idFactory("goal"),version:1,sessionId:t,objective:$r(e.objective,"objective"),...e.why?{why:$r(e.why,"why")}:{},successCriteria:s,constraints:Tfe(e.constraints,"constraints"),...r?{limits:r}:{},metadata:Xd(e.metadata??{}),status:"active",milestones:[],tasks:[],progress:wHn(o),verification:yHn(),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?Xd(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 Ce("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=$r(n.objective,"objective")),n.why!==void 0&&(o.why=$r(n.why,"why")),n.constraints&&(o.constraints=Tfe(n.constraints,"constraints")),n.successCriteria&&(o.successCriteria=Xd(n.successCriteria)),n.progress&&(o.progress={...o.progress,...Xd(n.progress),outstanding:Tfe(n.progress.outstanding??o.progress.outstanding,"progress.outstanding"),decisions:Tfe(n.progress.decisions??o.progress.decisions,"progress.decisions"),updatedAt:this.now()}),n.verification&&(o.verification=Xd(n.verification)),n.metadata&&(o.metadata=Xd(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:$r(n.title,"milestone.title"),...n.description?{description:$r(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 Ce("NOT_FOUND",`Milestone ${n.milestoneId} was not found`);if(n.parentTaskId&&!i.tasks.some(c=>c.id===n.parentTaskId))throw new Ce("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 Ce("NOT_FOUND",`Task dependency ${c} was not found`);let l={id:this.idFactory("task"),milestoneId:s.id,...n.parentTaskId?{parentTaskId:n.parentTaskId}:{},title:$r(n.title,"task.title"),...n.description?{description:$r(n.description,"task.description")}:{},status:a.length===0?"ready":"pending",...n.assignedAgentId?{assignedAgentId:$r(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 Ce("NOT_FOUND",`Task ${r} was not found`);a.status=i.status,i.progress!==void 0&&(a.progress=$r(i.progress,"task.progress")),i.resultEventId!==void 0&&(a.resultEventId=$r(i.resultEventId,"task.resultEventId",512)),i.assignedAgentId!==void 0&&(a.assignedAgentId=$r(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:$r(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 Ce("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 Ce("VERIFICATION_REQUIRED","Required success criteria lack passing evidence",{unmetCriteria:a.map(c=>c.id)});if(s.length===0&&n.evidence.length===0)throw new Ce("VERIFICATION_REQUIRED","Goal completion requires at least one durable evidence reference");let l=this.now();return o.status="completed",o.verification=Xd(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:$r(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 Ce("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 Ce("CONFLICT",`Cannot start a loop for terminal goal ${s.id}`)}if(t.kind==="scheduled"&&!t.schedule)throw new Ce("INVALID","Scheduled loops require schedule metadata");if(t.kind!=="scheduled"&&t.schedule)throw new Ce("INVALID","Only scheduled loops may carry schedule metadata");let r=AHn(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 Ce("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:$r(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?Xd(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 Ce("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 Ce("CONFLICT",`Loop ${t.id} already has a running iteration`);let s=(t.iterations.at(-1)?.number??0)+1;t.currentActivity=$r(n,"activity");let a={number:s,startedAt:r,status:"running",activity:t.currentActivity,...t.goalId&&e.goalTurnAccounting?.[t.goalId]?{goalAccountingVersion:1}:{},...i?{taskId:$r(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=xqt(r),o=await this.getGoal(e.sessionId,e.goalId);if(!o||o.sessionId!==e.sessionId||o.limits?.maxTokens===void 0)throw new Ce("BUDGET_UNAVAILABLE","The exact token-bounded goal is unavailable for quota admission");if(this.isCliGoal(o)&&o.metadata["cli.tokenQuotaVersion"]!==1)throw new Ce("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 Ce("BUDGET_UNAVAILABLE","Quota scope does not identify this durable goal generation");let s=await t.policy(i);if(!s||Aqt(s.scope)!==Aqt(i)||s.limits.tokensLifetime===void 0||s.limits.tokensLifetime===null||s.limits.tokensLifetime>o.limits.maxTokens)throw new Ce("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 Ce("BUDGET_UNAVAILABLE","Goal token accounting has no durable remaining allowance");if(a<1)throw new Ce("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 Ce("INVALID","An exact execution ownership epoch is required");return this.admitGoalTurnWithOwner(e,{...t})}async admitGoalTurnWithOwner(e,t,r){let n=$r(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 Ce("NOT_OWNER","Execution ownership epoch changed");if(this.ownerExpired(d,this.now()))throw new Ce("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 Ce("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 Ce("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 Ce("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 Ce("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 Ce("CONFLICT","Goal continuation loop changed before admission");this.assertVersion(a.id,a.version,e.expectedLoopVersion??-1)}else if(e.expectedLoopVersion!==void 0)throw new Ce("INVALID","A goal turn loop version requires its exact loop ID");if(a&&a.status!=="running")throw new Ce("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 Ce("INVALID","Unknown goal execution lane");return c.goalTurn={requestId:n,requestHash:i,executor:e.executionKind==="local-sdk"?{kind:"local-sdk",processId:process.pid,host:$S.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 Ce("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 Ce("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 Ce("NOT_FOUND","Goal turn was not found");if(o.goalTurn?.requestHash!==t)throw new Ce("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 Ce("NOT_FOUND","Goal turn was not found");if(s.status==="running"){if(!this.goalTurnOwnerExited(s))throw new Ce("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 Ce("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=$r(i.verificationEventId,"verificationEventId",512)),i.error&&(r.error=$r(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 Ce("CONFLICT",`Loop ${o.id} is terminal (${l})`);let c=[...o.iterations].reverse().find(u=>u.status==="running");if(c&&n==="completed")throw new Ce("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=$r(i??n,"reason")),o.status=n,o.kind==="goal-continuation"&&(o.resumeRequested=n==="running"),["stopped","completed","failed"].includes(n)&&(o.stoppedAt=s,o.stopReason=$r(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 Ce("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 Ce("LEASE_EXPIRED",`Ownership lease ${r} expired`);return o.heartbeatAt=this.now(),o.expiresAt=new Date(wI(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!==$S.hostname()||!Rfe(n))throw new Ce("LEASE_EXPIRED",`Ownership lease ${r} expired and cannot be recovered by process ${n}`);let a=this.now(),l=Math.max(0,wI(a)-wI(s.expiresAt));return s.heartbeatAt=a,s.expiresAt=new Date(wI(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:$r(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 Ce("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 Ce("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 Ce("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 Ce("NOT_FOUND",`Loop ${e.loopId} was not found`);let s=n.handoffs.find(c=>["prepared","available","claimed"].includes(c.status));if(s)throw new Ce("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:$r(e.targetOwnerId,"targetOwnerId",512)}:{},sourceLeaseEpoch:i.epoch,...e.workspace?{workspace:$r(e.workspace,"workspace",32768)}:{},...e.branch?{branch:$r(e.branch,"branch",1024)}:{},...e.currentMilestoneId?{currentMilestoneId:e.currentMilestoneId}:{},...e.currentTaskId?{currentTaskId:e.currentTaskId}:{},agentIds:[...new Set(e.agentIds??[])],operations:Xd(e.operations??[]),...e.contextDigest?{contextDigest:$r(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:$r(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 Ce("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 Ce("CONFLICT",`Handoff ${o.id} is ${o.status}`,{claimedBy:o.claimedBy})}if(o.targetOwnerId&&o.targetOwnerId!==e.targetOwnerId)throw new Ce("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 Ce("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:Xd(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 Ce("LEASE_EXPIRED",`Ownership lease ${n} expired`);let a=o.handoffs.find(l=>l.id===t);if(!a)throw new Ce("NOT_FOUND",`Handoff ${t} was not found`);if(a.claimedBy!==r||a.targetLeaseEpoch!==s.epoch||!["claimed","completed"].includes(a.status))throw new Ce("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 Ce("NOT_FOUND",`Handoff ${t} was not found`);if(s.sourceOwnerId!==r)throw new Ce("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 Ce("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 Ce("LEASE_EXPIRED",`Ownership lease ${n} expired`);if(s.sourceLeaseEpoch!==a.epoch)throw new Ce("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 Ce("NOT_FOUND",`Handoff ${t} was not found`);return["completed","cancelled","failed"].includes(i.status)||(i.status="failed",i.failureReason=$r(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 Ce("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 Ce("CONFLICT",`Goal ${i.id} is ${i.status}; no iteration was admitted`);let o=bqt(i.limits);if(o?.maxTokens!==void 0&&!n)throw new Ce("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 Ce("BUDGET_UNAVAILABLE","Goal wall-clock allowance cannot be verified",{goalId:i.id,limit:"maxWallClockMs"});if(a-s>=o.maxWallClockMs)throw new Ce("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 Ce("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 Ce("BUDGET_UNAVAILABLE","Invalid goal iteration accounting");if(a>=o.maxIterations)throw new Ce("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 Ce("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 Ce("BUDGET_UNAVAILABLE","Goal iteration history is invalid");i=o.number}if(r+=i,!Number.isSafeInteger(r))throw new Ce("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 Ce("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 Ce("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 Ce("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 Ce("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=$r(e,"requestHash",64).toLowerCase();if(!/^[0-9a-f]{64}$/.test(t))throw new Ce("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 Ce("BUDGET_UNAVAILABLE","Goal turn count exceeds its supported range");return Xd({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!==$S.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 Ce("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 Ce("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 Ce("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 Ce("INVALID","leaseMs must be a positive safe integer");return{ownerId:$r(e,"ownerId",512),leaseId:this.idFactory("owner"),epoch:t,acquiredAt:n,heartbeatAt:n,expiresAt:new Date(wI(n)+i).toISOString(),...r.processId!==void 0?{processId:r.processId}:{},...r.host?{host:$r(r.host,"host",512)}:{}}}ownerExpired(e,t){return wI(e.expiresAt)<=wI(t)?!0:e.processId!==void 0&&e.host===$S.hostname()&&!Rfe(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:Xd(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=$r(e,"sessionId",1024);return this.withSessionLock(i,async()=>{let o=await this.readState(i);if(o.admissionFence&&!r)throw new Ce("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)),Xd(a)})}statePath(e){return Jm.join(this.rootDirectory,"sessions",`${vqt(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(!yqt.includes(n.schemaVersion)||n.sessionId!==e)throw new Ce("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 Ce("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=Jm.dirname(t);await fi.mkdir(r,{recursive:!0});let n=`${t}.${process.pid}.${xfe()}.tmp`,i=await fi.open(n,"wx");try{await i.writeFile(`${JSON.stringify(e,null,2)}
|
|
3222
3222
|
`,"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=wqt[r];if(process.platform!=="win32"||!i||!Cfe.has(i)||o===void 0)throw n;await new Promise(s=>setTimeout(s,o))}}async withSessionLock(e,t){let r=this.lockPath(e),n=Jm.join(r,"owner.json"),i=xfe(),o=`${r}.candidate.${i}`,s=Date.now();await fi.mkdir(Jm.dirname(r),{recursive:!0});let a={schemaVersion:1,token:i,pid:process.pid,host:$S.hostname(),acquiredAt:this.now()};await fi.mkdir(o),await fi.writeFile(Jm.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&&Cfe.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 Ce("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!==$S.hostname()||Rfe(i.pid)?void 0:Date.now()-n.mtimeMs>this.lockStaleMs?i:void 0}catch{return}}async quarantineLock(e,t,r){let n=Jm.join(e,"owner.json"),i=r==="stale"?`${e}.stale.${vqt(t)}`:`${e}.${r}.${t}.${xfe()}`;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(Jm.join(i,"owner.json"),"utf8")).token===t)return}catch{}if(l==="ENOENT"||l==="EEXIST")return;let c=wqt[o];if(process.platform!=="win32"||!l||!Cfe.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=gHn[o];if(process.platform!=="win32"||!a||!Cfe.has(a)||l===void 0)throw s;await new Promise(c=>setTimeout(c,l))}}},hP=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 _fe,this.sessionId=e.sessionId,this.processId=e.processId??process.pid,this.host=e.host??vHn(),this.ownerId=e.ownerId??`runtime:${this.host}:${this.processId}:${bHn().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))}};Tqt=1e4,Rqt=8*1024*1024,Pqt=64*1024*1024;THn=/^sha256:[0-9a-f]{64}$/});var Dqt=we(()=>{"use strict"});var Lqt=we(()=>{"use strict"});function Fqt(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)}var Uqt=we(()=>{"use strict"});var Qqt=we(()=>{"use strict"});function Gqt(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&&t.source==="local-runtime-journal"&&typeof t.observedAt=="string"&&Number.isFinite(Date.parse(t.observedAt))&&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 jqt=we(()=>{"use strict"});function Vqt(e){return!j8e(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&&!Hqt(e.loadedModel)||e.models!==void 0&&(!Array.isArray(e.models)||e.models.length>1e3||!e.models.every(t=>j8e(t)&&Hqt(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&&(!j8e(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 j8e,Hqt,qqt=we(()=>{"use strict";j8e=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Hqt=e=>typeof e=="string"&&e.length>0&&e.length<=512&&!/[\x00-\x1f\x7f]/.test(e)});var pis,Wqt=we(()=>{"use strict";pis=new TextEncoder});function Jqt(e){return H8e(e)&&typeof e.action=="string"&&_Hn.has(e.action)&&gP(e.url,"string")&&gP(e.text,"string")&&gP(e.key,"string")&&gP(e.x,"number")&&gP(e.y,"number")&&gP(e.scrollY,"number")}function V8e(e){if(!H8e(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"||!gP(e.text,"string"))return!1;if(e.image===void 0)return!0;let t=e.image;return H8e(t)&&t.mediaType==="image/jpeg"&&typeof t.base64=="string"&&t.base64.length<=$Hn&&Number.isFinite(t.width)&&Number.isFinite(t.height)}var Bfe,RHn,PHn,_Hn,BHn,$Hn,H8e,gP,q8e=we(()=>{"use strict";Bfe="preview.act",RHn=["status","screenshot","read","console"],PHn=["open","reload","back","forward","click","type","key","scroll"],_Hn=new Set([...RHn,...PHn]),BHn=256*1024,$Hn=24*1024*1024,H8e=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),gP=(e,t)=>e===void 0||(t==="number"?Number.isFinite(e):typeof e=="string"&&e.length<=BHn)});function NHn(e){return W8e(e)&&typeof e.method=="string"&&OHn.has(e.method)&&typeof e.url=="string"&&e.url.length<=2048&&e.url.startsWith("https://")}function zqt(e){if(e===null)return!0;if(!W8e(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 Xqt(e){return!W8e(e)||e.kind!=="host-request"||typeof e.id!="string"||e.id.length===0?!1:e.method===Bfe?Jqt(e.input):e.method===MHn&&NHn(e.input)}var MHn,OHn,W8e,Yqt=we(()=>{"use strict";q8e();MHn="account.authorize",OHn=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD"]),W8e=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});var Kqt=we(()=>{"use strict"});var Zqt=we(()=>{"use strict"});var J8e,eWt=we(()=>{"use strict";J8e="1.0.0"});var aWt={};fo(aWt,{TERMINAL_WEB_JOB_STATES:()=>$fe,WEB_JOB_PROGRESS_OPERATIONS:()=>X8e,WEB_JOB_PROGRESS_SCHEMA:()=>AP,WEB_JOB_PROGRESS_SCHEMA_VERSION:()=>r6,WEB_JOB_PROGRESS_STATES:()=>Y8e,deriveWebJobProgress:()=>Mfe,isTerminalWebJobState:()=>yI,isWebJobProgress:()=>Z8e,parseWebJobProgress:()=>n6,webJobProgressSignature:()=>eHe});function yI(e){return $fe.includes(e)}function rWt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function nWt(e,t){return Object.keys(e).every(r=>t.has(r))}function K8e(e,t){return typeof e=="string"&&e.trim().length>0&&e.length<=t&&!/[\u0000-\u001f\u007f]/u.test(e)}function z8e(e){return K8e(e,64)&&Number.isFinite(Date.parse(e))}function sWt(e){return K8e(e,120)&&/^[A-Za-z0-9._:-]+$/u.test(e)}function iWt(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function n6(e){if(!rWt(e)||!nWt(e,DHn))throw new TypeError("invalid Web Context progress object");if(e.schema!==AP||e.schemaVersion!==r6||e.contractVersion!==J8e)throw new TypeError("unsupported Web Context progress schema");if(!K8e(e.jobId,256))throw new TypeError("invalid Web Context progress jobId");if(!X8e.includes(e.operation))throw new TypeError("invalid Web Context progress operation");if(!Y8e.includes(e.state))throw new TypeError("invalid Web Context progress state");let t=yI(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||!sWt(e.terminalReason)))throw new TypeError("invalid Web Context terminalReason");if(!rWt(e.counters)||!nWt(e.counters,tWt))throw new TypeError("invalid Web Context progress counters");for(let n of tWt)if(!iWt(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(!iWt(e.sequence))throw new TypeError("invalid Web Context progress sequence");if(!z8e(e.observedAt))throw new TypeError("invalid Web Context observedAt");if("createdAt"in e&&!z8e(e.createdAt))throw new TypeError("invalid Web Context createdAt");if("updatedAt"in e&&!z8e(e.updatedAt))throw new TypeError("invalid Web Context updatedAt");return structuredClone(e)}function Z8e(e){try{return n6(e),!0}catch{return!1}}function t6(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):0}function oWt(e){return typeof e=="string"&&e.length>0?e:void 0}function Mfe(e,t,r=new Date().toISOString()){let n=t6(e.queuedPages),i=t6(e.activePages),o=t6(e.completedPages),s=t6(e.failedPages),a=t6(e.excludedPages),l={queuedPages:n,activePages:i,completedPages:o,failedPages:s,excludedPages:a,knownPages:n+i+o+s+a},c=yI(e.state),d=sWt(e.terminalReason)?e.terminalReason:void 0,u=oWt(e.createdAt),p=oWt(e.updatedAt);return{schema:AP,schemaVersion:r6,contractVersion:J8e,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 eHe(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 AP,r6,$fe,X8e,Y8e,DHn,tWt,BD=we(()=>{"use strict";eWt();AP="xeno.web-context.job-progress",r6="1.0.0",$fe=["completed","partial","failed","cancelled"],X8e=["scrape","batch-scrape","map","crawl","render","extract"],Y8e=["queued","running",...$fe];DHn=new Set(["schema","schemaVersion","contractVersion","jobId","operation","state","terminal","terminalState","terminalReason","counters","sequence","observedAt","createdAt","updatedAt"]),tWt=new Set(["queuedPages","activePages","completedPages","failedPages","excludedPages","knownPages"])});var lWt=we(()=>{"use strict"});var cWt=we(()=>{"use strict"});var dWt=we(()=>{"use strict"});var uWt=we(()=>{"use strict"});var pWt=we(()=>{"use strict"});var fWt=we(()=>{"use strict";pWt()});var hWt=we(()=>{"use strict"});var mWt=we(()=>{"use strict"});var gWt=we(()=>{"use strict"});var AWt=we(()=>{"use strict"});var LHn,wWt=we(()=>{"use strict";Vy();LHn=1024*1024});function QHn(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 jHn(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)||!GHn.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 WHn(e){return typeof e=="string"&&qHn.test(e)?e:void 0}function JHn(e){return typeof e=="string"&&FHn.includes(e)}function yWt(e){return ds(e)?Sn(e.clientId)&&Sn(e.clientVersion)&&Sn(e.instanceId)&&JHn(e.surface):!1}function vWt(e){return!ds(e)||!ds(e.protocol)||!ds(e.host)||!ds(e.storage)?!1:Number.isInteger(e.protocol.current)&&eVn(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)&&yWt(e.surface)}function tHe(e){return!ds(e)||!Sn(e.revision)||!Array.isArray(e.providers)?!1:e.providers.every(KHn)}function zHn(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 IWt(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(zHn)}function EWt(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 kWt(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 SWt(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)&&XHn(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 XHn(e){return typeof e=="string"&&VHn.includes(e)}function xWt(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 YHn(e){return!(!ds(e)||e.chatExecution!==void 0&&!i6(e.chatExecution)||e.durableResume!==void 0&&!i6(e.durableResume)||e.nativeTuiAttach!==void 0&&!i6(e.nativeTuiAttach)||e.reconciliation!==void 0&&!i6(e.reconciliation)||e.modelSwitchInPlace!==void 0&&!i6(e.modelSwitchInPlace)||e.resumeCompatibilityKey!==void 0&&typeof e.resumeCompatibilityKey!="string")}function i6(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 KHn(e){return ds(e)?Sn(e.id)&&typeof e.kind=="string"&&UHn.includes(e.kind)&&Sn(e.displayName)&&CWt(e.availability)&&ds(e.capabilities)&&(e.providerSession===void 0||YHn(e.providerSession))&&(e.catalogState===void 0||jHn(e.catalogState))&&Array.isArray(e.models)&&e.models.every(ZHn)&&Sn(e.catalogRevision):!1}function ZHn(e){return ds(e)&&Sn(e.id)&&Sn(e.displayName)&&CWt(e.availability)&&(e.funding===void 0||QHn(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 CWt(e){return e==="available"||e==="degraded"||e==="blocked"||e==="unavailable"}function eVn(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 Nfe(e){for(let t of rVn)for(let r of tVn)if(e===`${t}tool.${r}`)return r;return null}function wP(e,t){let r=e?.[t];return typeof r=="string"&&r.trim()?r:void 0}function Dfe(e){let t=e.event;return wP(t,"toolName")||wP(t,"tool")||wP(t,"name")||wP(t,"title")||wP(t,"kind")}function MD(e){let t=e.event;return wP(t,"toolCallId")||wP(t,"tool_call_id")}function Lfe(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 Ffe(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 Ufe(e){return e==="completed"?!0:e==="failed"||e==="cancelled"?!1:null}var $D,bWt,FHn,UHn,GHn,Ofe,HHn,Ris,VHn,qHn,Ra,tVn,rVn,Vy=we(()=>{"use strict";Dqt();Lqt();Uqt();Qqt();jqt();qqt();Wqt();Yqt();q8e();Kqt();Zqt();BD();lWt();cWt();dWt();uWt();fWt();hWt();mWt();gWt();AWt();wWt();$D=1,bWt=1,FHn=["standalone-desktop","remote","hub-embed","shell-embed","embed-preview","panel-embed","headless-client","extension-panel"],UHn=["sdk-native","xeno-cloud","cli-app-server","cli-remote","acp"];GHn=["timeout","network","rate-limited","server","auth-required","forbidden","invalid-response","configuration","cancelled"];Ofe=128e3,HHn=["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.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"],Ris=new Set(HHn),VHn=["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"],qHn=/^[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=WHn(n)}};tVn=["started","updated","completed","failed","cancelled"],rVn=["","acp."]});import{createHash as Zis,randomBytes as nVn,timingSafeEqual as eos}from"node:crypto";import{createConnection as iVn}from"node:net";function aVn(e,t,r){if(e!=="workspace.command.run")return r;let n=s6(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 lVn(e){return!s6(e)||e.kind!=="response"||typeof e.id!="string"||typeof e.ok!="boolean"?!1:e.ok?"output"in e:s6(e.error)&&pVn(e.error.code)&&typeof e.error.message=="string"&&(e.error.reason===void 0||typeof e.error.reason=="string")}function cVn(e){return s6(e)&&e.kind==="event"&&SWt(e.event)}function dVn(e,t,r){PWt(e,t,r)}function PWt(e,t,r){let n=`${JSON.stringify(t)}
|
|
3223
3223
|
`;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 RWt(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 yP(e){return typeof e=="number"&&Number.isInteger(e)&&e>0?e:void 0}function uVn(e){let t=yP(e)||oVn;if(t>TWt)throw new Error(`Local Agent host RPC frame limit cannot exceed ${TWt} bytes.`);return t}function pVn(e){return e==="invalid_handshake"||e==="protocol_mismatch"||e==="surface_mismatch"||e==="not_connected"||e==="invalid_response"}function rHe(e){return e instanceof Error?e:new Error(String(e))}function s6(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Qfe(e,t){return e instanceof Error&&"code"in e&&e.code===t}var oVn,TWt,sVn,o6,nHe,OD=we(()=>{"use strict";Vy();oVn=32*1024*1024,TWt=64*1024*1024,sVn=3e4,o6=class{endpoint;transportToken;openStream;protocolVersion;maxFrameBytes;requestTimeoutMs;onDisconnect;listeners=new Set;pending=new Map;requestPrefix=nVn(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||RWt(t.endpoint,this.transportToken),this.endpoint=t.endpoint,this.protocolVersion=yP(t.protocolVersion)||$D,this.maxFrameBytes=uVn(t.maxFrameBytes),this.requestTimeoutMs=yP(t.requestTimeoutMs)||sVn,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=iVn(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();RWt(this.endpoint,n),this.transportToken=n,this.socket=r,this.read(r)}read(t){let r=new nHe(this.maxFrameBytes,n=>this.receive(n));t.on("data",n=>{try{r.push(n)}catch(i){this.disconnect(rHe(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=aVn(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{dVn(n,o,this.maxFrameBytes)}catch(d){clearTimeout(c),this.pending.delete(i),a(rHe(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(cVn(r)){for(let i of[...this.listeners])i(structuredClone(r.event));return}if(Xqt(r)){this.answerHostRequest(r);return}if(!lVn(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===Bfe){r={ok:!1,error:"This app has no preview."};try{if(this.previewHandler){let i=await this.previewHandler(t.input);r=V8e(i)?i:{ok:!1,error:"The preview gave no usable answer."}}}catch(i){r={ok:!1,error:rHe(i).message}}}else try{let i=this.accountAuthorizer?await this.accountAuthorizer({method:t.input.method,url:t.input.url}):null;r=zqt(i)?i:null}catch{r=null}let n=this.socket;if(!(!n||n.destroyed))try{PWt(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)}};nHe=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 _Wt(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 iHe=we(()=>{"use strict"});import{readFile as fVn}from"node:fs/promises";import{join as BWt}from"node:path";function Gfe(e){let t=e.isProcessAlive||mVn;try{return!t(e.pid)}catch{return!1}}async function jfe(e){let t=BWt(e,"agent-host.lock");try{let r=await $Wt(t);return r.state==="released"?null:MWt(r)}catch(r){if(Qfe(r,"ENOENT"))return null;throw r}}async function Hfe(e){let t=BWt(e,"agent-host.lock");try{let r=await $Wt(t);return r.state==="released"?null:{descriptor:MWt(r),transportToken:r.transportToken}}catch(r){if(Qfe(r,"ENOENT"))return null;throw r}}async function $Wt(e){return hVn(await fVn(e,"utf8"))}function hVn(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(!gVn(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&&!_Wt(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 MWt(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 mVn(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return!Qfe(t,"ESRCH")}}function gVn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Vfe=we(()=>{"use strict";OD();iHe()});async function sHe(e){let t=yP(e.protocolVersion)||$D,r=yP(e.connectTimeoutMs)||5e3,n=yP(e.requestTimeoutMs)||3e4,i=await jfe(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(Gfe({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 Hfe(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 o6({endpoint:o.descriptor.endpoint,transportToken:o.transportToken,protocolVersion:t,requestTimeoutMs:n});try{await AVn(s,r)}catch(a){return s.close(),{attached:!1,reason:"unreachable",detail:a instanceof Error?a.message:String(a)}}return{attached:!0,session:new oHe({role:"attached-client",descriptor:o.descriptor,transport:s})}}async function AVn(e,t){let r=Date.now()+t,n;do try{await e.connect();return}catch(i){if(n=OWt(i),!wVn(n)||Date.now()>=r)break;await yVn(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 wVn(e){if(!("code"in e))return!1;let t=e.code;return t==="ENOENT"||t==="ECONNREFUSED"||t==="EPIPE"}function yVn(e){return new Promise(t=>setTimeout(t,e))}function OWt(e){return e instanceof Error?e:new Error(String(e))}var oHe,NWt=we(()=>{"use strict";Vy();Vfe();OD();oHe=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=OWt(t);await this.close().catch(()=>{}),this.onAuthorityLost?.(r)}finally{this.heartbeatPending=!1}}}}});import{createConnection as bVn}from"node:net";import{homedir as vVn}from"node:os";function LWt(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(DWt)){n(new Error("The bridge was sent an invalid first line."));return}let f=u.slice(DWt.length);if(f===EVn){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??kVn);e.on("data",a),e.once("end",s),e.once("error",n)})}async function FWt(e){let t=await Hfe(e.rootDirectory);if(!t)throw new Error("No XENO Agent host is running for this user.");let r=bVn(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:vVn()};e.output.write(`${IVn}${JSON.stringify(n)}
|
|
3224
3224
|
`),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 IVn,DWt,EVn,kVn,Ios,aHe=we(()=>{"use strict";Vfe();OD();IVn="xeno-host-bridge/1 ",DWt="xeno-host-bridge-key/1 ",EVn="-",kVn=15e3,Ios=64*1024});var Tos,UWt=we(()=>{"use strict";aHe();OD();Tos=8*1024});import{join as SVn,resolve as GWt}from"node:path";function OS(e){let t=QWt(e.homeDirectory);if(!t)throw new Error("Agent host homeDirectory is required.");let r=QWt(e.hostRootDirectory);return r||SVn(GWt(t,xVn),CVn)}function QWt(e){return typeof e=="string"&&e.trim()?GWt(e.trim()):void 0}var xVn,CVn,jWt=we(()=>{"use strict";xVn=".xeno",CVn="agent-host-v1"});var a6=we(()=>{"use strict";OD();Vfe();iHe();NWt();aHe();UWt();jWt()});import{existsSync as TVn}from"fs";import{join as af}from"path";import{createDirs as RVn}from"@xenosystem/primitives/dirs";function PVn(e,t=[]){return{pluginDir:af(e,"plugins"),mcpConfigDir:af(e,"mcp"),mcpDataDir:af(e,"mcp"),protectedPaths:[...t,af(e,"credentials.json")],layout:"legacy"}}function _Vn(e,t=[]){return{pluginDir:af(e.data,"extensions","plugins"),mcpConfigDir:af(e.config,"extensions","mcp"),mcpDataDir:af(e.data,"extensions","mcp"),protectedPaths:[...t,e.secrets],layout:"extensions"}}function BVn(e,t){return!HWt(e)&&HWt(t)?t:e}function VWt(e,t=process.env){let r=RVn({home:e,env:t}),n=af(e,".ssh");return BVn(_Vn({data:r.root("data"),config:r.root("config"),secrets:r.root("secrets")},[n]),PVn(af(e,".xeno"),[n]))}function qWt(e,t){return e.XENO_AGENT_HOST_ROOT?.trim()?af(t,"coordination"):void 0}var HWt,lHe=we(()=>{"use strict";HWt=e=>[af(e.pluginDir,"plugins.json"),af(e.pluginDir,"trust.json"),af(e.mcpConfigDir,"servers.json"),af(e.mcpConfigDir,"sdk-approvals.json")].some(t=>TVn(t))});import{homedir as $Vn}from"node:os";function Zi(e={}){if(e.rootDirectory)return new _fe(e);let t=OS({homeDirectory:$Vn(),...process.env.XENO_AGENT_HOST_ROOT?{hostRootDirectory:process.env.XENO_AGENT_HOST_ROOT}:{}}),r=qWt(process.env,t);return new _fe({...e,...r?{rootDirectory:r}:{}})}var jA=we(()=>{"use strict";mP();a6();lHe()});function DVn(e){if(e===void 0||e==="")return"";if(!NVn.test(e)||e.split("/").includes(".."))throw new TypeError("pathPrefix must be an absolute path such as /v1/web");return e}function d6(e){return e.signal?{signal:e.signal}:{}}function LVn(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 zWt(e,t){let r=e;return{message:t,...typeof r?.code=="string"?{code:r.code}:{},...typeof r?.status=="number"?{status:r.status}:{}}}function FVn(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 UVn(e,t){let r=0,n,i=!1;return async o=>{if(!e)return;let s=yI(o.state);if(s&&i)return;let a=Mfe(o,r),l=eHe(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 NVn,u6,XWt=we(()=>{"use strict";BD();BD();NVn=/^\/[A-Za-z0-9._~-]+(?:\/[A-Za-z0-9._~-]+)*$/;u6=class{#e;#r;#n;#i;constructor(t){if(this.#e=new URL(t.baseUrl),this.#r=t.token,this.#i=DVn(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",d6(t))}usage(){return this.#t("/v1/usage")}search(t,r={}){return this.#t("/v1/search",{method:"POST",body:JSON.stringify(t),...d6(r)})}searchAndScrape(t,r={}){return this.#t("/v1/search-and-scrape",{method:"POST",body:JSON.stringify(t),...d6(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}`,d6(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}`,d6(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:zWt(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??=zWt(f,"Web Context progress listener failed during cancellation confirmation")}};for(await d(o);!yI(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=yI(o.state)?Mfe(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=UVn(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),yI(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:FVn(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(LVn(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 QVn}from"node:fs";function fHe(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 p6(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 jVn(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=QVn(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 HVn(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||GVn,token:jVn(e),source:"explicit",auth:"bearer"};let i=e.XENO_API_KEY?.trim();return i?{baseUrl:YWt,token:i,pathPrefix:KWt,source:"account",auth:"bearer"}:{baseUrl:YWt,pathPrefix:KWt,source:"account",auth:"dpop"}}function VVn(){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 qVn(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 Rl()).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=Uy(e);if(l.state!=="present")throw VVn();return a.set("authorization",`Bearer ${l.key}`),fetch(t,{...r,headers:a})}}function hHe(e=process.env,t={}){let r=HVn(e,t);return r.auth==="dpop"?new u6({baseUrl:r.baseUrl,token:"dpop-account-session",pathPrefix:r.pathPrefix,fetchImpl:qVn(t)}):new u6({baseUrl:r.baseUrl,token:r.token??"",...r.pathPrefix?{pathPrefix:r.pathPrefix}:{}})}function ZWt(e=process.env){let t=fHe(e),r=p6("fetch",t),n=Xle({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 pHe(e),createRequest:(i,o)=>{let s=n(i,o);return i==="search"&&(s.budget.maxPages=p6("search",r.maxProviderCostUsd,void 0,typeof o.maxResults=="number"?o.maxResults:5).maxPages),s}}}var GVn,YWt,KWt,pHe,mHe=we(()=>{"use strict";XWt();MA();rf();st();GVn="http://127.0.0.1:8080",YWt="https://api.xenostudio.ai",KWt="/v1/web";pHe=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??=hHe(this.env),this.client}async bindTenant(t,r,n){this.account??=this.getClient().account();let i=await this.account,o=p6(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 f6(e){return e.type==="run.self_review"}function h6(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 e6t(e){return e.replace(/\s+/g," ").trim()}function m6(e){let t=e6t(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 gHe(e){let t=[],r=(n,i)=>{if(i.length!==0){t.push(`${n}:`);for(let o of i)t.push(` - ${e6t(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(`
|
|
@@ -6644,7 +6644,7 @@ ${n}`}}import{execFileSync as Wpr}from"node:child_process";function Qbi(){let e=
|
|
|
6644
6644
|
`),i.model||i.baseURL||i.apiKey||i.maxTokens||i.permissionMode||i.plugins&&i.plugins.length>0||i.mcpServers&&i.mcpServers.length>0||r.onOutput(` (no settings configured)
|
|
6645
6645
|
`),r.onOutput(`
|
|
6646
6646
|
`),{handled:!0}}function Nx(e){let t=Math.max(0,Math.floor(e)),r=Math.floor(t/1e3),n=Math.floor(r/3600),i=Math.floor(r%3600/60),o=r%60;return n>0?`${n}h ${i}m ${o}s`:i>0?`${i}m ${o}s`:`${o}s`}function ifr(e){let t=["Last Session Summary",`- model: ${e.model}`,`- mode: ${e.mode??"unknown"}`,`- status: ${e.status??"unknown"}`,`- started: ${e.startedAt}`,`- ended: ${e.endedAt}`,`- duration: ${Nx(e.durationMs)}`,`- tokens: ${e.tokenUsage.input.toLocaleString()} in / ${e.tokenUsage.output.toLocaleString()} out / ${e.tokenUsage.total.toLocaleString()} total`,`- estimated cost: ${XR(e.estimatedCostUsd)}`];return e.sessionId&&t.splice(1,0,`- session: ${e.sessionId}`),e.role&&t.splice(e.sessionId?2:1,0,`- role: ${e.role}`),e.messageCount!==void 0&&t.push(`- messages: ${e.messageCount}`),t.join(`
|
|
6647
|
-
`)}function wvi(e){let t=e.replace(/\s+/g," ").trim();return t.length>72?`${t.slice(0,69)}...`:t}async function Lye(e){if(!e.checkpointManager||e.messages.length===0)return null;let t=`Branch before rewind to "${wvi(e.targetPrompt)}"`,r=await e.checkpointManager.create({trigger:"manual",messages:e.messages,description:t});if(e.sessionManager){let n=[r.id,...e.sessionManager.meta.checkpoints.filter(i=>i!==r.id)];await e.sessionManager.updateMeta({checkpoints:n}),await e.sessionManager.transcript.append({type:"checkpoint",data:{id:r.id,action:"create",name:t,trigger:"manual",messageCount:e.messages.length}})}return r.id}Qo();bo();var yvi={"0.5.188":["Fixed: with Ask first, the agent really asks before it writes or edits a file in your folder. 0.5.187 said so, but the engine still let a write inside the folder through without a question; this version runs the engine that asks (SDK 0.10.123).","Fixed: when you refuse something the agent asked to do, it is told you refused and to stop and ask you, instead of being told nobody was there, so it no longer tries another way to do the same thing."],"0.5.187":["Fixed: nothing a run writes about your project shows up in git status any more. Its notes live in .xeno/local/, which git ignores.","Fixed: with Ask first, the agent asks before it creates a new file, as it already did before editing one.","Fixed: a turn run through ACP on the shared Agent host uses the same up-to-date engine as every other turn, so it waits out a rate limit too."],"0.5.186":['Fixed: a rate limit no longer ends a run after a few seconds. When a provider says "too many requests", the agent now waits it out: at least as long as the provider asks, backing off up to a minute, for up to three minutes in all.','Fixed: a run that stops on a rate limit says so. It used to be reported as a permission problem (exit 2) when an earlier tool call had been denied. `xeno run --json` now reports `error` with `error_category: "rate_limit"`.'],"0.5.185":["Fixed: commands chained with `;` run in process-hardened and contained runs on Windows."],"0.5.184":["Fixed: `xeno run` on the shared host uses the model you chose. It used to run the host's default, a different model each time, when the host listed yours under another name.","Fixed: cmd switches such as `cd /d`, `dir /b` and `findstr /i` are no longer refused as paths, and commands chained with `;` run on Windows.","Fixed: `xeno run` prints the agent's last reply as the answer, and a Windows PATH that starts with `;` no longer breaks every command.",`Fixed: the agent always writes its own answer. The shared host used to end a turn right after a tool ran and show the tool's raw output instead, for example a whole file after a request that said "read" and "exact".`],"0.5.183":["Fixed: when a command fails, the agent now reads the error and keeps going. The shared host used to end the turn two seconds after a failure and show the raw error as the answer.","Fixed: commands written in PowerShell run on Windows again. The shared host sent every command to cmd.exe, which refused PowerShell.","Fixed: Stop on Windows ends everything a command started, including programs a PowerShell command launched.","Fixed: Stop always ends the turn cleanly, even while the agent is waiting for the model's first answer."],"0.5.182":["Fixed: 0.5.181 could not sign in, because it was published without its account module. Update if you installed it.","Fixed: a machine reached over SSH can now run turns, with the key to its stored state kept on your PC."],"0.5.181":["New: xeno host bridge, which the XENO Agent desktop app runs on a Linux or macOS machine over SSH. You do not run it yourself."],"0.5.180":["Fixed: xeno run no longer refuses when you saved bypassPermissions as your permission mode. Your saved setting is your choice. Asking for bypass on a command line still has to pass the safety check."],"0.5.179":["Security: bypassPermissions now has to pass the safety check however you turn it on, including --permission-mode and saved config. It runs only in a container with no internet, or with XENO_ALLOW_UNSAFE_BYPASS=1."],"0.5.178":["A newer CLI no longer runs silently on an older XENO Agent host that another app started: an idle older host is replaced, and a busy one is named."],"0.5.177":["When XENO Corpus is installed, it can search your conversations, including what compaction drops from the agent's context."],"0.5.176":["Machine mode now uses XENO Use 0.3.2, which is proprietary. Nothing in how it works changed."],"0.5.175":["/machine in a chat, or xeno --machine, lets the agent use this Windows PC. Run /machine again to stop.","xeno browser connect links XENO Extension in your own Chrome or Edge to the agent."],"0.5.174":["xeno run --machine lets the agent use this Windows PC: real screenshots, clicks and typing. XENO Use downloads itself the first time.","Browser tools work in your own signed-in Chrome or Edge once the extension and its companion are connected."],"0.5.173":["xeno run --mcp and xeno run --image now run on the shared Agent host.","The default model can see images a tool returns: gpt-6-luna and gpt-6.1-sol receive the picture instead of a note saying they cannot."],"0.5.172":["xeno run now goes through the shared Agent host when you are signed in, with its tool lists, fallback models and required JSON answer."],"0.5.171":["Fixed: a chat on the shared Agent host stopped after 10 tool rounds. It now uses your limit, 50 by default.",'--continue no longer fails with "already locked" after a chat on the shared Agent host.',"A chat on the host keeps its web limits and keeps short questions short."],"0.5.170":["MCP servers you approved now work in a chat on the shared Agent host, each started in its own folder.","A chat tells you when a folder's server is waiting for approval."],"0.5.169":["Windows: the helper that runs commands is now one fixed program, so antivirus is far less likely to delete it."],"0.5.168":["A chat with MCP enabled stays in the CLI process again, so its MCP tools are there; the shared Agent host does not load them yet."],"0.5.167":["Windows: commands no longer fail with spawn UNKNOWN when antivirus quarantines the process launcher.","xeno host status now says whether a chat runs on the shared Agent host."],"0.5.166":["Interactive chat now runs on the shared Agent host by default, so conversations appear in the desktop app. XENO_AGENT_ATTACH=0 turns it off."],"0.5.165":["Several CLI jobs can share one sign-in: one renews at a time, and a half-finished renewal recovers by itself instead of asking for xeno login.","On the shared Agent host, a turn now draws its tools and token counts like any other, and Esc stops it and the command it was running.","If the direct route is down, a turn on the shared Agent host takes the Cloudflare route instead of failing."],"0.5.164":["On the shared Agent host, an edit made in the desktop app now reaches the terminal: the turn you edited away stops going to the model, and what you attach or rate there is kept too.","Windows: a scanner briefly holding a file no longer fails a scheduled job or other background write."],"0.5.163":["Conversations you start on the shared Agent host now appear in the XENO Agent desktop app, marked as started in the terminal, and you can carry on from either side."],"0.5.162":["On the shared Agent host, /rewind now puts your files back too: /rewind files shows what would change, /rewind files --confirm restores them. A file you edited since is never overwritten unless you add --overwrite.","Turns on the shared Agent host now remember what earlier turns did, not only what they said, so the model no longer doubts work it already finished."],"0.5.161":["On the shared Agent host, /rewind <n> continues from just before turn n in a new conversation; the original is kept. /rewind lists the turns.","On the shared Agent host, /compact summarises on the host: later turns are sent the summary, and every original turn is kept.","/fork [n] on the shared Agent host branches the host's conversation, all of it or through turn n."],"0.5.160":["In xeno chat on the shared Agent host, the host now keeps the conversation: a turn sends only your new message, and the host supplies the rest from its own record.","Conversations the host did not record from the start keep sending the CLI's own history, so nothing loses context."],"0.5.159":["--security-level process-hardened now runs on the shared Agent host instead of being refused, with the same restricted Windows token as a local run.","--security-level contained and --untrusted are still refused on the host, and say why."],"0.5.158":["An MCP server you signed into with xeno mcp login now works in the XENO Agent app too: the app uses the same stored credentials.","Opening a sign-in or app-server link no longer goes through cmd on Windows, so a crafted URL cannot run a command.","Share bundles now hide credentials found in a prompt or a tool's output, not only under secret-named fields.","xeno org, xeno github, xeno share and xeno mcp run on the same SDK code as the app; their behaviour is unchanged."],"0.5.157":["Chat turns run on the shared Agent host now carry this chat's permission mode and folders. Before, they ran with the host's defaults.","--mode chat can run on the Agent host: its turns ask the host for no tools, and a host that cannot enforce that refuses the turn. Before, a chat-only turn could not attach at all.","A chat turn whose settings the host cannot honour (such as --security-level contained) is refused with the reason, instead of running with weaker settings.","Plan mode works on the Agent host: the host's turn plans without changing anything, and its plan comes to you here for approval.","The agent can make a tool you keep and run again: it publishes a page as a tool on your XENO account. /artifacts publish|promote take --tool [--category <c>], and /artifacts keep-as-tool <id> keeps a hosted page as one."],"0.5.156":["xeno eval now uses the same eval code as the XENO Agent app, from the SDK; the app runs a project's eval suites itself. Nothing about how xeno eval behaves changes."],"0.5.155":["xeno recipes run now starts the recipe's workflow through the XENO Agent host, like xeno workflow run: the host drives it and runs each step, so it keeps going after this terminal closes, and the XENO Agent app's Recipes and Workflows tabs show it."],"0.5.154":["/approved-tools now also shows the folders you always allowed (they were remembered but never listed); remove takes a folder as well as a tool key, and clear forgets both. The XENO Agent app's Approvals tab manages the same list."],"0.5.153":["Your hooks now run in the XENO Agent app as well: the CLI and the app share one hook loader, one trust store and one runtime, from the SDK. A hook you trust with xeno hooks trust runs in both; an untrusted or disabled one runs in neither."],"0.5.152":["xeno ws: when a capability is not granted, the message names Settings \u203A Connected apps once instead of twice.","Scheduled workflows (xeno schedule workflow \u2026) now also run while the XENO Agent app is open, without the CLI daemon. Each schedule is claimed before it starts, so it never starts twice."],"0.5.150":["Scheduled prompts (/loop, the Cron tools and xeno app-server's schedules) now use the same scheduler as the XENO Agent app, from the SDK. The XENO Agent app runs a folder's scheduled jobs itself now, so they run while the app is open even without a terminal; a job is claimed before it runs, so it never runs twice. Schedules you already have keep working unchanged.","Security: built with XENO Agent Interface 0.1.140 (Electron 45.1.0, Node 24.22.1, fixing CVE-2026-111497) and XENO Agent SDK 0.10.92."],"0.5.149":["/artifacts publish (a local page) and adding a comment with /artifacts comments now go through the XENO Agent host, the same pages the app shows. Pages, links and comments work as before."],"0.5.148":["A policy you set with /peers policy now wins over the automatic rule: accept delivers even from a session running with more autonomy than this one. Leave it unset and messages that would move trust upward are still held for you.","Messages between sessions follow the coordination rules everywhere: the same message sent twice in a row is refused, and when a session's queue is full the oldest unread message is dropped and its sender told."],"0.5.147":["Messages between sessions now go through the XENO Agent host: /peers send, accept, refuse and cancel, the peer tool and the peer cockpit. The host checks that a session is really the one it says it is, and every surface sees the change as it happens."],"0.5.146":["xeno workflow run, pause, resume, cancel, retry, skip, rerun, save and create now go through the XENO Agent host, the same one the app's Workflows tab uses. The host runs the workflow, so it keeps going after this terminal closes, and after the host restarts.","Fixed: cancelling a workflow the host was running could stop the host itself. It now cancels only the workflow."],"0.5.145":['xeno run can approve a list of commands: --allowed-tools "Bash(command:python3 *)" lets an unattended run use matching commands without asking, and still refuses anything else, including a listed command that chains on a second one.',"An agent file's permissionMode is now reported as not applied, instead of being ignored silently. Choose the permission mode where the run is started.","xeno run --prompt-file - reads the prompt from standard input."],"0.5.144":["Background runs and workflows now run on the XENO Agent SDK's run store, the same one the XENO Agent app reads, so a workflow you start or pause in either one is the same workflow. Your existing runs and workflows are read as they are."],"0.5.143":["Goals and loops are now changed through the XENO Agent host, the same one the app uses: /goal, xeno goal and /loop send their changes there, so the app shows them as they happen.","Pausing, resuming or clearing a running goal still wins, now through the host as well.","Fixed (--line-input): a line you type while a command or an automatic turn is still running now runs next and its reply stays on screen. Before, the reply could be erased, or the line never ran."],"0.5.142":["Plugins and MCP servers are now managed by the XENO Agent host, the same one the app uses: xeno plugin, /plugin, /mcp and xeno mcp send their changes there, so the CLI and the app follow one set of rules.","Enabling a plugin now records that you trust it, so the app's host keeps it on instead of switching it off.","Fixed: /plugin uninstall no longer deletes the folder of a plugin you installed from your own project.","Fixed: xeno plugin list no longer crashes on an empty plugins.json."],"0.5.141":["Skills are the same in the CLI and the XENO Agent app. /skills and xeno skills now read one shared skill set, the same one the app's new Skills tab shows, so a skill you turn on in one is on in the other.","Turns run in the shared Agent host (XENO_AGENT_ATTACH) now have your skills too; before, they had none."],"0.5.140":["The CLI and the XENO Agent app no longer replace each other's background host. A running Agent host is now replaced only by a newer one; before, whichever started last swapped in its own copy, so an older app could downgrade the host the CLI started."],"0.5.139":["xeno plugin and the XENO Agent app now share one plugin store, ~/.xeno/data/extensions/plugins, so a plugin installed in one shows up in the other. Plugins still in ~/.xeno-agent/plugins keep working until xeno-home migrate copies them across; nothing is moved or deleted for you.","Your XENO files live in ~/.xeno. Installed updates and run logs used to go to the AppData folders; the CLI still reads them there, so nothing is lost, and the next xeno update installs into ~/.xeno.","An Agent-mode session grants the shared host the folders it was given, which you can see and revoke in the XENO Agent app under Settings > Folder Access, and /mcp decisions are recorded in the host too."],"0.5.138":["With XENO_AGENT_ATTACH set, the CLI starts the shared XENO Agent host itself when none is running, the same host the desktop app uses. It keeps running after the CLI exits, and the next CLI or the desktop app joins it.","A turn that fails in the host now fails the run. Before, a provider error could print status ok with an empty answer.","Turns through the host report real token usage and tool calls instead of zeros.","A long shell command collapses with a vertical \u22EE in the gutter, so the card's left rule stays unbroken."],"0.5.137":["XENO Agent turns can run in the shared Agent host, the same one the desktop app uses: set XENO_AGENT_ATTACH=1 (or require) for xeno run, or use /provider use sdk-native in chat. Turns run as your own XENO account; you never sign in twice.","Full Access carries through to the host as its full-access mode: no prompts inside the workspace, and writes outside it are still refused."],"0.5.136":["Security update: the bundled XENO account library moves to 0.4.1 and zod 4.6.7 (fixes a memory-exhaustion advisory that affects every zod 3 release), and undici moves to 6.29.1."],"0.5.135":["A slash command you have typed in full now shows in your accent colour, so you can see it will run, and deleting a letter brings the matching suggestions back.","After /logout, the next start shows the sign-in screen straight away instead of flashing the chat first.",'The sign-in waiting screens keep "Esc or Ctrl+C to cancel" on the bottom row, and the browser page you land on after approving is now a designed XENO page with your alien.'],"0.5.134":["Closing the terminal or ending xeno during a sign-in refresh no longer leaves you signed out: the next start finishes that refresh instead of asking you to sign in again.","The status bar keeps its colours on a narrow terminal, so Ctrl+Down shows which item you are on; long rows drop their least useful parts instead of turning grey.","After xeno login, your alien waves above the XENO name."],"0.5.133":["If your sign-in turns out to be invalid after chat has opened (expired, or a refresh that was cut off), chat now shows the sign-in screen right there and carries on once you sign in, instead of exiting and asking you to run xeno login.","The sign-in screen now animates the whole crew of six aliens, one after another, with its key hints along the bottom of the terminal. Esc on the sign-in screen exits straight away.","A CLI installed with npm no longer hands off to an older version that xeno update activated earlier."],"0.5.132":['New sign-in screen: six animated XENO aliens. Pick yours on first sign-in or any time with /alien; its detail follows your /color. The long browser link is now a clickable "Open the sign-in page" where your terminal supports it, and the device page now also answers at xenosystem.ai/device.',"Escape stops the running turn and clears queued messages; double Escape opens rewind only when the agent is idle and the input box and queue are empty.","/color adds Add color: type a #RRGGBB hex code and it stays in the picker after restarting.","xeno update installs beside running sessions, so an open session no longer makes the update fail with EBUSY. Pairs with @xenosystem/agent-sdk 0.10.77.","xeno run -y no longer overrides a --permission-mode you chose; device sign-in waits through short platform outages; XENO_ACCOUNT_PROFILE keeps a separate sign-in beside your normal one.","Chat draws its screen right away and checks your sign-in in the background; quitting during startup lets an in-progress sign-in refresh finish, so it can no longer leave your sign-in interrupted."],"0.5.131":["Escape interrupts the running turn and clears queued follow-ups without scheduling rewind. Double Escape opens rewind only on an idle, empty composer with no queued prompts; clearing input never counts as a rewind press."],"0.5.130":["/color now offers Add color: enter a #RRGGBB hex code, save it, and select it again after restarting. /theme and direct /color #RRGGBB commands support the same saved colors."],"0.5.129":["Updates install beside running sessions and activate atomically after signature, integrity, dependency and version checks; open sessions keep their loaded runtime."],"0.5.128":["Streamed partial paragraphs now appear before the next newline, with a replaceable preview that becomes formatted Markdown without duplicate text.","Gateway keepalives display Waiting for model output instead of Receiving model response. Fullscreen progress separates each model request's elapsed time from whole-turn elapsed time and labels cumulative turn tokens explicitly."],"0.5.127":["Long fenced code lines now wrap inside the code block: every continuation row repeats the left border and indentation instead of spilling to the terminal's left edge. Blank rows and wide Unicode characters remain aligned."],"0.5.126":["Self-review appears below the Worked for turn divider in fullscreen and line mode, with one Self-review label. Review limitations remain visible.","Shell calls show a readable command block with PowerShell labels, terminal-width wrapping and expandable long scripts instead of truncated multiline parentheses."],"0.5.125":["xeno update now recognizes Linux/macOS npm command symlinks as npm installs, so it installs the latest version instead of incorrectly asking for a native download. Background update eligibility uses the same resolved entry path.","Native checksum links use the correct GitHub Release download URL. Genuine native binaries still retain their own installation channel."],"0.5.124":["Chat now requires XENO account sign-in even with a model API key or local model. A valid account session is reused; signed-out piped chat stops with sign-in guidance. Use xeno run for unattended API-key execution.","SSH sign-in uses a device code in the running terminal. Browser and device sign-in open xenosystem.ai; existing token issuer and credential storage remain unchanged.","Linux without a system keyring keeps account sign-in only for the running process. Sign in inside xeno to use chat, or configure a Secret Service keyring for persistence."],"0.5.123":['After a turn that changed files, the agent now reviews its own work and shows one line after the reply, such as "Self-review: checked the edit; tests pass". Findings, fixes and anything left unverified expand with ctrl+o. A review that failed or ran out of time says so (SDK 0.10.75).',"`xeno run --json` includes the review as a `selfReview` field. Turn it off with `selfReview: false` in config or XENO_SELF_REVIEW=0.","Read-only commands containing JavaScript arrow functions no longer trigger a review by mistake. Windows commands also work when a deeply nested temporary directory would prevent the process launcher from starting."],"0.5.122":["Chat no longer gets a second, confused reply: the check that stops the agent claiming it made a file without verifying it now runs only when the turn actually wrote something (SDK 0.10.73)."],"0.5.121":['Signing in works again. 0.5.117 to 0.5.120 were published without the bundled account module, so `xeno login` reported "XENO sign-in is unavailable". This release is built with the isolated release builder, which refuses a package without it.'],"0.5.120":['`xeno update` works on Windows again: it failed with "spawn EINVAL" because newer Node refuses to start npm.cmd without a shell.',"The background auto-updater uses the same safe launch, so it no longer prints a Node deprecation warning."],"0.5.119":["`/import` turns a Claude Code, Codex or opencode session into a real XENO session, keeping turns, tool calls and results, lists what could not be carried, and offers to resume it. `xeno import <agent> <session> --json` does the same from a script.",'Updates install themselves in the background for global npm installs: at most every 12 hours, never a downgrade, rolled back if the new version does not start. A green "Update installed \xB7 Restart to update" appears above the input. Turn it off with XENO_NO_AUTOUPDATE=1 or `autoUpdates: false`.','Typing `!` shows a pink `!` prompt and "! for shell mode", so a shell command no longer looks like a chat message.',"Pasting or typing the path of an image turns it into an [Image #N] chip, like a clipboard image; Backspace removes the whole chip.",'`/exit` no longer reports "cleanup remains unconfirmed" for harmless steps. When something real is left behind it names the step, with details in ~/.xeno-agent/logs/cli.log.',"Resuming a session whose history has an unfinished tool call or an orphaned tool result repairs it once and saves the repair, so the provider accepts the next turn (`xeno --resume`, `/resume`, `xeno run --resume` and imported sessions).",'When an agent profile asks before an external action (a push, a publish, a deploy), chat asks "Allow <action> <target>?" with Yes / Yes for this session / No. Headless runs deny unless permissions are bypassed (SDK 0.10.72).',"A turn refused for an unfinished tool call shows the SDK's own explanation and what to do, instead of a generic error."],"0.5.118":['A turn no longer dies with "An error occurred while processing your request." after the agent changes directory: a `cd` inside a Bash call moves the session\'s working directory, and that is no longer mistaken for another terminal taking over the conversation.',"Failures now say what went wrong instead of hiding the cause in the session audit log (SDK 0.10.70)."],"0.5.117":["Act as one of your XENO agents: `xeno run --as <agent>` and `/as <agent>` in chat use the agent's identity, instructions, model and tools.","As an agent, xeno sees the tasks delegated to it, claims one while it works and releases it when the run ends. New comments arrive before the turn finishes."],"0.5.116":["Sign in with your XENO account on Linux, including Google Cloud Shell and SSH: `xeno login`, `xeno login --device`, or the chat welcome screen.","On Linux the sign-in is kept in the desktop keyring (Secret Service). Without a keyring it lasts until the process exits, and xeno says so; it is never written to a file."],"0.5.115":["On Linux and macOS, chat says account sign-in is Windows-only for now and names the API-key route, instead of a menu that could only fail.","Long sessions no longer freeze after you send a message: skills are no longer rescanned hundreds of times per request.","Rewind puts the removed message back in the input box. Restore notices disappear instead of staying in the conversation.","Published artifacts return to the tray when you resume a session, with fresh working local links.","Context usage uses the model's real window. The working row says when history is compacting, a model is responding, or a request is retrying; token totals say input+output.","SDK 0.10.66 retries incomplete tool calls instead of ending on a promise. A single denial no longer stops the loop; unattended denials name the allowed commands. Incomplete turns say so."],"0.5.114":["ReadImage shows the model the actual picture instead of text."],"0.5.113":["Overwriting a file shows a diff; Esc Esc opens a redesigned rewind picker; tables and long lines wrap cleanly.","Ctrl+Down moves into the footer; the status row shows context usage in plain words."],"0.5.112":['A long run is no longer refused with "Historical arguments violate schema" after the model sends an invalid tool call.',"A request that reads like a question (for example with a typo) is no longer refused its file changes; the permission mode decides."],"0.5.111":["Headless runs can use the skills they were given: loading a skill no longer asks for permission. What a skill does still asks as usual.","Uses SDK 0.10.61."],"0.5.110":["Acting as one of your XENO agents (`xeno run --as`, `/as`), the agent can also use the platform's image, video, Library and chat services, within its division budget.","`xeno auth status` says when a previous sign-in was interrupted, and that `xeno login` fixes it.","Uses SDK 0.10.60."],"0.5.109":["`xeno login` works without an interactive terminal (from an agent's `!` prompt, a pipe or a script): it uses device sign-in and says so, instead of ending silently.",'A failed sign-in says why (the account error and its code), with anything token-shaped removed, instead of only "could not be completed".',"`xeno auth status` reports whether you are signed in even when an API key pays for model requests."],"0.5.108":['Signing in works again. Since 0.5.95 the npm package was missing the module that holds your XENO sign-in, so `xeno login` said "XENO sign-in is unavailable". The release check now refuses any package that cannot load it.'],"0.5.107":["`/as` in chat: act as one of your XENO agents in the same conversation. `/as` lists them, `/as <name>` switches, `/as me` returns to you. Each switch revokes the previous agent credential, and leaving the chat revokes the last one.","`xeno run --resume` acts as the agent the session acted as before, with a fresh credential. Only the agent id is stored; `--as me` clears it.","Lines piped into `xeno chat` now run in order. Before, a slash command could end the session while later lines were still waiting.","Uses SDK 0.10.59."],"0.5.106":["`xeno run` takes its prompt from standard input (`xeno run -`, or piped with no prompt) or from `--prompt-file <path>`, so a prompt longer than a command line allows reaches the model as the message itself, up to 8 MB.","`xeno run --as <agent>` acts as one of your XENO agents: its instructions, model, effort and tool policy, with the XENO Tasks tools ready. Its credential stays in memory and is revoked when the run ends, however it ends. `--json` reports `acting_as`.","`xeno spawn <args>` hands the rest of the command to XENO Spawn.","Uses SDK 0.10.58."],"0.5.105":["`xeno run` saves every run as a session and prints its `session_id` in `--json` output. `--resume <id>` continues that conversation with a new prompt, and `--continue` picks up this folder's most recent session. Both work for local runs, not with --delegate, --remote or --bg."],"0.5.104":["`xeno run --output-schema <file>`: the final answer must be JSON that matches the given JSON Schema. An answer that does not match is sent back with the errors to fix, and the valid result is returned as `structured_output` in the JSON output. If no valid answer arrives, the run ends incomplete (exit 1).","Uses SDK 0.10.55."],"0.5.103":["A run that produced every output named in XENO_REQUIRED_OUTPUT_PATHS_JSON now reports ok (exit 0) even if one of its tool calls was denied along the way. The denial is still listed in tool_summary and the audit. Without declared outputs, a denial is still the outcome.","`xeno run --allowed-tools` and `--disallowed-tools` (comma-separated) control which tools the agent is offered. The limit also applies to helpers it starts."],"0.5.102":["A research run whose answer is a written document that cites its sources is no longer held open asking for the sources again in chat.","Uses SDK 0.10.54."],"0.5.101":["Skills found by default are named project:<name> or user:<name>, so the Skill tool resolves the name it was given, and the same name in project and user folders is two skills.","Child agents and background workers inherit their parent's skills again; the interactive-child inheritance tests pass.","Uses SDK 0.10.53."],"0.5.100":["You can set how much web research one turn may do. `xeno run` and chat accept --max-web-searches (1 to 200), --max-web-fetches (1 to 500) and --max-web-calls, or the environment variables XENO_MAX_WEB_SEARCHES, XENO_MAX_WEB_FETCHES and XENO_MAX_WEB_CALLS. Without them the limits are unchanged: 5 searches and 12 fetches for a research request, 3 and 4 for a quick question. A value that is not a whole number in range stops the command with a message. Each search can cost provider money, up to the per-request cap.","Uses SDK 0.10.42."],"0.5.99":["Web search uses your account's configured provider allowance when you have not set a limit. Explicit limits still narrow it, including zero: XENO_WEB_CONTEXT_MAX_PROVIDER_COST_USD and --provider-cost-budget-usd never silently authorize additional spending.","WebFetch reports the recorded reason when a page cannot be retrieved, such as site refusal, a missing page, rate limiting or a network error, instead of only saying the scrape failed. Conversational tools preserve the specific error code for the agent. Explicit site refusals are not bypassed.","Uses SDK 0.10.41 and Web Context client 0.1.5. The HTML transcript redesign and /provider picker remain outside this release."],"0.5.98":["Chat draws its composer before loading session state or building the agent. You can type immediately; early submissions wait until restoration, permission state and execution ownership are ready. In five real-terminal runs on our large workspace, the usable frame appeared in 579 ms median. Line-input chat also preserves input received before readiness, including piped input ending at EOF.","Terminal updates repaint only changed lines; typing and in-place tool updates no longer redraw the whole screen. The status command refreshes on changes with a bounded cadence. --version runs from a tiny entry without loading the agent runtime.","Background dispatch helpers report their results back when they settle. The footer separates the agent list from status by one blank row, keeps main and helpers adjacent, shows state on the left and aligns elapsed time and tokens on the right.","Web Context uses your signed-in XENO account by default, with a fresh DPoP proof for each request. XENO_API_KEY also works; explicit Web Context endpoint/token settings still take precedence. Gateway-prefixed search, fetch and artifact reads use Web Context client 0.1.3.","Uses SDK 0.10.40, including faster startup, background reports and the compatible Web Context client peer. The new transcript design and /provider picker are not part of this release."],"0.5.97":["Long sessions stay fast. Adding a line to the conversation no longer redraws the whole history: with 2,000 rows on screen, a new tool row went from about 8.5 seconds to about 5 milliseconds.","Each screen update is sent to the terminal in one piece, wrapped so terminals that support it paint it all at once, which removes flicker and half-drawn frames.","Typing @ to pick a file no longer reads the folder on every key; the listing is reused for two seconds. Set XENO_RENDER_STATS=1 to log frame times and key-to-screen latency to ~/.xeno/render-stats.jsonl."],"0.5.96":['The /model list is the full list the XENO API serves, read live. It shows "Loading models..." while it loads, says so plainly if the list cannot be loaded instead of offering a short built-in list, and keeps models that are temporarily unavailable at the bottom with the reason; picking one is refused with that reason.',"Switching to a model from the live list no longer makes a second network check, so the switch is immediate. Uses @xenosystem/agent-sdk 0.10.38."],"0.5.95":['Messages between sessions are now one line each. A sent message reads "sent to SESSION2: ... \xB7 queued" and its state (queued, held, delivered, running, reported, failed) updates in place; a received one reads "from SESSION1: ...". The full text and message id are behind ctrl+o, and the Send tool no longer prints its own call and JSON result.',"Tool rows no longer wait. A finished tool row settles at once instead of staying for at least 0.7 seconds, and the end of a turn no longer waits for it. Tool results open collapsed (ctrl+o to expand) instead of opening expanded and collapsing 2.2 seconds later."],"0.5.94":["You can save a model API key once with `xeno auth login --api-key`. It is read from a hidden prompt or from standard input, never from the command line, and it is checked with XENO before it is saved. XENO_API_KEY still takes precedence when it is set.","Where the key is kept: on Windows it is protected by Windows DPAPI for your Windows user account, using the native system call, and nothing is saved if that protection is unavailable. On Linux it goes into the desktop keyring (Secret Service, via secret-tool) when one is available, and otherwise into a file only you can read. On macOS it is a file only you can read.","If you used an earlier version, your saved API key moves to the new protected store the first time you start this version, and the old plaintext file loses only that key. Your previous sign-in cannot be carried over: run `xeno login` once to sign in again.","`xeno auth status` shows where the model credential is stored without printing any part of a key. On a machine that has never signed in it says 'not signed in' and how to sign in, rather than reporting a fault. `xeno logout` and `xeno auth logout` remove a saved key.","Account sign-in is available on Windows only for now. On macOS and Linux, `xeno login` says so and points to `xeno auth login --api-key` or XENO_API_KEY. Account sign-in is also bundled inside the CLI, so installing from npm needs nothing from a private registry.","Plan mode now works through the model's own tools: it starts planning by itself when the work calls for it and hands you the plan to approve. You can approve, approve with edits typed in your editor or the input box (your version is what gets carried out), or send it back with feedback. Tools from connected servers that only read keep working while planning. From @xenosystem/agent-sdk 0.10.35.","Stopping a helper at the exact moment it starts a tool no longer crashes the app.","Notification history and dismissal stay within the selected workspace, including isolated helper worktrees and deleted-parent recovery. Control Room actions accept the exact displayed snapshot for 60 seconds and refuse changed state.","MCP authentication failures identify the exact server and its dedicated login command. Repeated failures do not produce duplicate notices, and line-input chat shows the same recovery guidance as fullscreen chat.","Web fetch requests one page instead of exceeding the connected account's page quota. Map and crawl respect the account's page limit. Paid web search supports an explicit per-request USD budget and still defaults to no spending.","A prepared session handoff can now be cancelled from the original fullscreen or line-input chat. The exact offer is withdrawn before the conversation writer resumes; other detached execution stays refused."],"0.5.93":["Plan mode is here. Start with --permission-mode plan, type /plan, or press Shift+Tab: the agent can read and investigate but every change is refused until you approve its plan, including changes a helper agent would make. Plan mode survives a crash and resume, and xeno run returns the plan instead of waiting for an approval.","A session can now move to another enrolled computer with its conversation: the receiving computer downloads it from the execution authority and checks it is exactly the same before taking over. A computer that loses ownership now also stops the background tasks, helper sessions and workflow runs that session started.","Helper agents can be stopped one at a time from the agent list, cancelling a turn stops its helpers, and a helper that ran out of budget is shown as unfinished instead of done.","Every command that takes a prompt now refuses a /command it cannot run instead of sending it to the model, pause and resume on Windows really suspend the work, and slow Windows process queries no longer make commands time out. /goal clear, /goal pause and /loop stop now always win against a running goal loop, and a !command typed during a turn runs as a shell command."],"0.5.92":["A /command the chat does not know is no longer sent to the model as a prompt. Typos like /revew, commands this mode does not support, and commands from another lane now stop with a message naming the command and why, and nothing is sent. This covers the chat, xeno run, background runs and the app server.","Moving a session between computers through an execution authority now recovers safely: a computer that loses contact stops working on the session before another can take it, a failed or abandoned move hands the session back to the computer that offered it, and /handoff cancel withdraws an offer. The receiving computer checks it has exactly the same conversation before taking over.","Helper agents now keep their background tasks private: a helper can no longer read or stop its parent's or another helper's tasks, and the reverse."],"0.5.91":["You can now stop two computers from working on the same session at once. Run xeno app-server --http --execution-authority on one machine, enrol each computer with xeno executors add, and start chats with --execution-authority. While one computer has a session, another is refused until the first lets go or stops responding. Before, each computer only checked its own records, so two could both think they had the session."],"0.5.90":["Forking a conversation now makes you choose, instead of deciding silently: the whole conversation or only up to a checkpoint, and whether the fork shares this folder or gets its own git worktree. Use /fork in the chat, or xeno sessions fork with --history and --working-tree. An isolated fork says how many uncommitted changes it does not carry over. Before, every fork quietly shared the same folder, so both conversations changed the same files."],"0.5.89":["A helper started with dispatch_agent now shows in the agent list below the input while it works. Press Enter on it to open its conversation; what you type there reaches it at its next step, and once it finishes the conversation stays open to read. Before, it was one line in the transcript and its conversation could not be seen.","/agents now lists the agents started from this chat, numbered, so /attach 2 opens the one shown as 2."],"0.5.88":["With helper agents working, pressing Enter on a helper now opens its conversation in the chat, as it happens. While it is still working, what you type there reaches it at its next step. Once it has finished, the conversation stays open to read. Before, Enter showed only a status panel.","A large delegation budget no longer breaks the helpers. Given 200,000 tokens or more, a helper stopped before sending anything, because its whole budget was being reserved as room for one reply. From @xenosystem/agent-sdk 0.10.29."],"0.5.87":["Open a background agent's conversation right in the chat with /attach, by its name, its number in the agent list, or its id. Inside it, /attach opens an agent it started. Esc or /back goes back one level, and /main returns to your own chat. Before, opening an agent's agent lost the way back to the one you came from.","With helper agents working, the Down key now reaches the background agents below them too. Before, it stopped at the helpers."],"0.5.86":["An agent file's max-tokens and deadline now also apply when the agent is called as a helper in the middle of a chat, not only when it runs in the background."],"0.5.85":["xeno agents new now takes --max-tokens and --deadline (for example 30m), so a background run can have its own budget and time limit. They are kept with the run, so relaunching it does not reset them, and a reply in progress is stopped when the time limit passes.","An agent file can set a default budget with max-tokens and deadline at the top. It applies to background work started as that agent, unless you give a budget yourself. From @xenosystem/agent-sdk 0.10.28."],"0.5.84":["A background agent can now be given its own token budget and time limit when it is started. It stops once it has spent the budget, and when the time limit passes it stops, even in the middle of a reply. Both are kept with the session, so restarting the worker does not reset them. Before, a background agent had no limit of its own unless its parent goal had one."],"0.5.83":["With delegation on, each helper agent now stays inside its share of the delegation token budget. Before, the budget only limited each single reply, so a helper given 1,200 tokens could keep calling tools and spend several times that. It now stops once its share is spent and says how much it used. From @xenosystem/agent-sdk 0.10.26."],"0.5.82":["If the CLI closes while the agent is waiting for your answer, the question comes back when you resume the session, with the same choices. Before, the question was lost: the agent was told it had been interrupted and not to repeat it, so it never asked again. Press Esc to skip it and answer in your own words instead."],"0.5.81":["Tools from MCP servers now work with every model. Their names contain dots, and several models refused any request that included one: Claude and DeepSeek failed the whole turn, and gpt-6 answered with nothing. The tool still shows its real name in the terminal and in permission prompts. From @xenosystem/agent-sdk 0.10.23."],"0.5.80":["A tool server that sends a huge reply no longer ties up the agent. A reply over 16 MB is refused as it arrives, and the request fails right away with a clear error. Before, a 200 MB reply was read in full, which took about 48 seconds, and then almost all of it was thrown away. From @xenosystem/agent-sdk 0.10.22."],"0.5.79":["Long sessions stay fast to scroll. In a session of 10,000 messages, one scroll step took about 430 ms and now takes about 24 ms, and a keypress went from about 27 ms to about 4 ms. Resizing and entering scroll mode got faster too.","Images from tools now reach models that accept images even when the name is new, such as gpt-6, because the model list says which models take images. From @xenosystem/agent-sdk 0.10.21.","A reply that ends without the model sending anything now shows as an error instead of an empty, finished turn. From @xenosystem/agent-sdk 0.10.21."],"0.5.78":["When a tool's output is too long and gets shortened, the agent can now read the part that was left out. The full output is kept, and the new ToolOutput tool reads it back. Before, a long shell command lost its middle for good. From @xenosystem/agent-sdk 0.10.19.","ToolOutput reads appear in the compact tool-activity row with the other reads, and the tool line shows which stored output and offset it read."],"0.5.77":["Long sessions no longer slow down as they grow. Adding output used to re-draw the whole conversation every time, so each new line took longer the more was already on screen. Now 10,000 blocks of output take under a second instead of minutes, and memory stays flat.","The spinner on a running tool stays in the right place as output scrolls, including after it scrolls off screen and back."],"0.5.76":["Model endpoints behind a proxy that ignores streaming now work. Their reply is read as one complete answer instead of failing as a broken stream. From @xenosystem/agent-sdk 0.10.18."],"0.5.75":["A model reply cut off in the middle of a tool call no longer runs that tool with empty input. The agent is told the call was not run and nothing was changed.","If you stop the agent after it has sent a change, it is told the change may have happened, and to check before trying again, instead of being told it was cancelled. The same applies to a change that timed out.","The request time limit now covers the whole reply, not just the moment the reply starts. A reply that stalls part-way now ends at the limit instead of hanging. A timed-out request is not repeated automatically, because it may still be running.","`xeno harbor` analysis recognises the new timeout and dropped-stream messages as transport failures, as it did the old wording.","Uses @xenosystem/agent-sdk 0.10.17."],"0.5.74":["New Patch tool: the agent can change several files in one all-or-nothing edit, including adding, moving and deleting files. Nothing is written unless every change matches the files as they are. In accept-edits mode it is approved automatically, like Edit. From @xenosystem/agent-sdk 0.10.16.","Patch is treated as a file write everywhere a write is: it is denied in hosted runs that allow no edits, shown with the files it touches in the tool line and background session details, and counted by the completion checks that look at which files a run wrote."],"0.5.73":["Background and workflow workers that start slowly, for example on a busy machine, now claim their slot reliably. Before, a worker that took more than about 4 seconds to start could lose its slot and exit without a trace, leaving its run stuck as running. A worker that misses the longer start-up window is now refused with a recorded reason.","Stopping all of an agent's background processes now always finishes (from @xenosystem/agent-sdk 0.10.14)."],"0.5.72":['When no approval screen is available and the agent asks for permission in a plain terminal, typing "y" now approves. Before, every answer was recorded as a denial. For a command asking for extra access, the question now lists exactly what it wants and why. Uses @xenosystem/agent-sdk 0.10.13.'],"0.5.71":["Approving or rejecting an agent session's permission request in the Control Room now takes effect. Before, the session ignored the answer and kept waiting until it was stopped.","Control Room approvals and the SDK's built-in approval screens show a command's exact extra access and its reason, the same as the terminal prompt. Uses @xenosystem/agent-sdk 0.10.12."],"0.5.70":['When a command asks for access beyond its sandbox (network or extra folders), the approval prompt lists exactly what it wants and the reason it gave. It offers "Yes, for this call only" instead of "always", because an elevated command needs your approval every time. Uses @xenosystem/agent-sdk 0.10.11.'],"0.5.69":[`The agent can run a command in a specific directory, or through a specific shell (bash, sh, powershell, pwsh or cmd), for that one call, without moving the session's directory. The tool call line shows both, e.g. "npm test (in packages/app, via pwsh)".`,'Approving a command "always" covers only the directory and shell it was approved in, and the approval prompt names both.',"Requires @xenosystem/agent-sdk 0.10.10."],"0.5.68":["New: `xeno ctx-viz --audit` reports tools that are defined but registered by no lane, defined twice, or pointed at by an alias that goes nowhere. Run it from a CLI checkout; it exits 1 when it finds anything.",'Saving artifacts and other local records no longer fails intermittently on Windows with "EPERM: operation not permitted, rename" when another program briefly holds the file.',"Requires @xenosystem/agent-sdk 0.10.9."],"0.5.67":["Auto permission mode no longer asks before ElfAnalyze or ToolSearch, which default mode allows without asking.","The permission audit log labels every tool with the same risk level shown everywhere else.","New generated references: docs/TOOL_CATALOGUE.md (every tool per chat/run/ACP lane) and docs/TOOL_MAPPING.md (the permission decision per mode, how the terminal shows it, and its tests).","Requires @xenosystem/agent-sdk 0.10.8."],"0.5.66":["When a goal token budget runs out, the message now says how many tokens are left and how many the next request needs.",'A goal run no longer fails with "Ownership lease expired" when the process briefly stalls; the session keeps its lease as long as nobody else took it.',"Requires @xenosystem/agent-sdk 0.10.7."],"0.5.65":["Goal token limits now work on the XENO cloud route as a SOFT budget: each request's output is capped to what is left, measured usage is charged, and the goal stops once the limit is spent. One request may overshoot slightly, and the overshoot is recorded.","Local xeno-rt keeps its exact, hard limit. /goal status, xeno run and the chat notice say which kind of limit applies.","Requires @xenosystem/agent-sdk 0.10.5."],"0.5.64":["Removed the direct OpenAI Responses lane for bounded goals that 0.5.63 added. Token-limited goals run on local xeno-rt; other lanes refuse bounded work before inference, as in 0.5.62.","Background runs still refuse inline --api-key arguments, so a credential never reaches a worker's process arguments."],"0.5.63":["Bounded CLI goals can now use the official OpenAI Responses endpoint through an explicit OpenAI base URL and API key. Exact input counting, capped output and durable settlement share the same goal allowance as local xeno-rt.","The Responses lane refuses mutable remote image URLs, invalid counts and unsupported hosts before inference. It is fixture-qualified; live OpenAI and hosted/ACP quota qualification remain open.","Background runs refuse inline API keys before daemon handoff or worker spawn; use an environment or saved credential. Headless quota admission and execution now resolve the same provider endpoint."],"0.5.62":["Goals can use a durable total token limit in the local xeno-rt lane. The allowance survives restarts and is shared with local child agents; unsupported provider lanes refuse bounded work before inference.","TUI commands now execute in order, so renaming a session and immediately preparing a handoff cannot race their transcript and ownership changes.","Automatic goal continuation no longer inserts text into the command you are typing."],"0.5.61":["Goals can now carry an explicit total token limit with /goal set --max-tokens or xeno run --goal-max-tokens. The allowance survives restarts and is shared with local child agents.","Token-limited goals require a local xeno-rt runtime that advertises exact prompt counting and an enforced token ceiling. Other execution lanes report that requirement before starting work.","Automatic goal continuation no longer inserts text into a command you are typing. Human input received during a turn is queued for the next turn."],"0.5.60":[`The four canonical tools \u2014 Send, Receive, ListAgents, ListSessions \u2014 are now the CLI's own, bound to this session's peer runtime. 0.5.58 announced them and shipped the SDK's stock versions, which have no host: they recorded every message as coming from "unknown", so a delegated task's report had no sender to return to, and they forced every message to kind "task", so a note or a question ran a whole turn in the receiving session instead of being injected or asked. Both were silent. The name the release notes told the model to prefer was the one that got this wrong, while the legacy CoordinationSend it replaced got it right.`,"CoordinationSend and CoordinationQuery keep working, and are hidden again. They had been promoted back into the model's tool list beside their own canonical names, so one capability was offered twice.","ListAgents and ListSessions exist for the first time. They answer different questions on purpose \u2014 who you can send to, versus what is running where.","Sending now writes a Sent to row whoever sends. It was rendered only by the /peers command, so a human saw it and the model did not \u2014 the same asymmetry 0.5.59 fixed for arriving messages, in the other direction."],"0.5.59":["Inbound messages from other sessions now land as durable transcript rows on the live path: Received from, including a task waiting until idle and a held message with /peers accept, not a notice that scrolls away."],"0.5.58":["Unified agent architecture: sub-agents are full sessions, docked under the main-agent in the panel beneath the input box or detached as their own window \u2014 one engine, two presentations.","Messages between sessions are now first-class transcript rows in both directions: Sent to / Received from with the message visible, not a transient notice that scrolled away.","Wire vocabulary: the model gets four canonical tools \u2014 Send, Receive, ListAgents, ListSessions. CoordinationSend/CoordinationQuery keep working as hidden aliases.","Picks up SDK 0.10.0, which ships the canonical wire vocabulary and the alias layer."],"0.5.57":["Reliability pass from the goal-reconciliation: one shared projection now turns runtime events into assistant text (run turns and host-delegated branches used to keep separate copies, the class of bug where a tool payload renders as chat text).","Provider cockpit hardening: the host's durable conversation binding is validated before any mode or scope change, a mismatched host can no longer receive your project as a side effect, and the active provider lane is re-read every turn so a selection changed in another window takes effect immediately.","Tool start/end events are now driven by the interface contract's own vocabulary (phase, call id, success) instead of re-parsing raw type strings.","Release plumbing: the packed CLI manifest now records the publishable SDK version rather than the local build reference, and the security-boundary audit resolves file: SDK links through the installed package."],"0.5.56":["Independent sessions can now delegate to each other, the way Claude Code's SendMessage works: /rename names this session (shown on the input border), /peers lists every XENO Agent session on this machine, and /message <session> <task> hands it work that runs INSIDE that session with its own workspace and permissions; the result comes back here automatically.","The model has the same two primitives as the Interface - CoordinationQuery and CoordinationSend - so 'ask my DB - PLUGIN session to audit the auth flow' works in plain language. Delivery and completion are separate states; a task left running by a crashed session is marked recovery-required and never re-run.","Picks up SDK 0.9.39: the durable peer store behind this, a strict /rename commit (a failed disk write is a failed rename), and permission classification of the two coordination tools.","Typing a slash command that takes an argument ghosts its placeholder after the cursor, e.g. /rename [name].","Rendered artifacts, the way Claude Code's Artifact tool works: the model writes an HTML page and publishes it with the Artifact tool; the page appears as a link tray under the status bar (ctrl+] opens it) and is served from a private loopback viewer under a sandboxing CSP. Comments left on the page come back into the conversation as turns, and republishing the same artifact_id keeps the link.","Two homes, your choice: local is private to this machine and needs no account; home cloud (or /artifacts promote <id>) hosts the same revision on your XENO account at xenostudio.ai/a/<id>, private until /artifacts share <id> turns link sharing on. Hosted comments reach the session the same way local ones do."],"0.5.55":["Updated to SDK 0.9.38: app-server retries and permission responses enforce current tenant, workspace, and connection authority.","Fixed standalone startup by bundling the web-context client with the CLI.","Qualified context recovery, schemas, scheduling, subagents, skills, and app-server regression checks on Windows and Linux."],"0.5.54":["Picks up SDK 0.9.37, which corrects the root cause published in 0.9.36: the Linux install failure came from lockfile metadata, not from the dependency itself.","The 0.9.36 fix was correct and is retained; only its explanation was wrong, and a wrong cause is worse than none because the next person reasons from it.","Fixes a crash where a second CLI session in the same workspace killed the first one: listing schedules took a cross-process mutation lock, and the resulting error came from a background timer with no catch, which terminates the process."],"0.5.53":["Picks up SDK 0.9.36: a Windows-only native addon was a hard dependency, so `npm ci` failed outright on Linux - the SDK could not be installed there at all.","The addon is now optional and loaded lazily, which is what its call sites already assumed. Found by running the full suite on a real Linux filesystem rather than a mounted Windows drive."],"0.5.52":["Picks up SDK 0.9.35: a model the gateway cannot route was classified as a retryable server error, so a permanently wrong model id would be retried on a backoff loop forever.","A model that is temporarily unavailable stays retryable, so only the unroutable case changed. Found by a live provider conformance run against the XENO gateway."],"0.5.51":["Picks up SDK 0.9.34, which fixes provider error classification: a bad API key returning HTTP 400 was reported as a missing model capability rather than an authentication failure.","That told you your model lacked a feature when your key was simply wrong. Found by a live provider canary - offline tests prove what we send, never how we read what comes back."],"0.5.50":["Picks up SDK 0.9.33, which fixes a permission-rule wildcard that could span a carriage return: Bash(command:git*) matched 'git status\\rrm -rf /', so a prefix rule an operator wrote as a constraint could authorize a composed command.","On a terminal a carriage return returns the cursor to column zero, so an approval preview could display one command while the shell received a second one. A single * now stops at every line terminator and ** remains strictly broader."],"0.5.49":["Picks up SDK 0.9.32, which fixes a single-writer violation: a live session owner whose heartbeat stalled could be treated as stale and have its lock taken by a second writer.","A long tool call, a paused debugger or a saturated event loop no longer risks losing session ownership; a genuinely dead owner is still reclaimed immediately."],"0.5.48":["xeno handoff status gains --since-revision and --wait-ms: a caller passes the revision it already saw and the command returns when the session actually moves, instead of re-reading the whole session in a loop.","A wait that reaches its deadline exits 2 rather than 1, so an unchanged session reads as a retryable observation rather than a failure."],"0.5.47":["xeno sessions show gains --history and --cursor: recent transcript activity is read in a bounded window with a continuation cursor, instead of loading an entire transcript to display the last few entries.","New xeno agents wait <run-ids...> waits for the first of several background runs to reach a terminal state, or every run with --all. A deadline exits 2 rather than 1, so a caller can tell a timeout from a failure.","New xeno mcp resource-templates lists parameterized resources a connected MCP server offers; servers without template support are unaffected.","AskUser questions can now be cancelled, so an unanswered question no longer holds a turn open indefinitely (via SDK 0.9.31)."],"0.5.46":["Sessions can be branched: xeno sessions fork <id> creates a new session from an existing one without changing the original, carrying its transcript history and linking back to its parent, so both lines of work stay resumable.","Sessions can be titled, pinned and archived: xeno sessions title, pin and archive. Pinned sessions lead every listing regardless of activity, and archiving retains the transcript rather than deleting it.","xeno sessions list gains --archived, and shows titles and pin state inline."],"0.5.45":["The top-level xeno ctx-viz command now exposes the same bounded live tool inventory as the interactive TUI, with cursor paging and permission-safe metadata.","Inventory output clearly separates registered tools from request-loaded schemas and never grants execution authority."],"0.5.44":["File tools now complete reliably in standalone and packaged CLI processes, including guarded Edit and Write results after permission approval.","Durable interrupted-session recovery now preserves receipt-before-status crash ordering and requires explicit respawn for fresh input.","Worker stop, lease revocation, permission approval, workflow recovery, and goal-budget controls are qualified through the unsigned Windows candidate package.","Synced Agent SDK 0.9.28 with the awaited tool-operation liveness repair and recovery contracts."],"0.5.43":["Provider-native Codex and Claude continuations can be attached from the XENO provider cockpit without replacing the XENO TUI; exact provider session identity, workspace, and ownership survive detach, reattach, and Interface handoff.","The native terminal path mirrors user messages into the owning graphical conversation and keeps XENO application system instructions out of provider-visible chat text.","Synced XENO ACP 0.2.13 and Agent Interface 0.1.23 after the earlier immutable candidates were published without moving their npm latest tags."],"0.5.42":["Durable Web Context operations now render the canonical typed evidence progress stream in human and NDJSON modes without inventing counters.","SIGINT and external abort request exactly one service-side cancellation and report whether the durable job reached a confirmed terminal state.","Synced Web Context 0.1.1, Agent SDK 0.9.25, and Agent Interface 0.1.22 for the negotiated ACP v2 evidence contract."],"0.5.41":["Durable compaction now flushes the recoverable session snapshot before mutating resident history, so repeated long-context cycles and crash recovery retain completed turns.","Chat and non-interactive run paths bind the real host parent-session identity before delegating, keeping nested work and results attached to the correct resumable conversation.","Execution handoff preserves writer fencing and live ownership across A-to-B-to-C resume while Loop continuation remains unbounded by default.","Synced the public Agent SDK 0.9.24 and Agent Interface 0.1.21 registry packages for the qualified Goal / Loop / Handoff contract."],"0.5.40":["Added durable Goal records with explicit criteria, milestones, delegated tasks, progress, steering, and evidence-gated completion.","Added distinct scheduled, development, and goal-continuation loops that are unbounded by default, persist every iteration, survive restart, and remain recoverable after an iteration failure.","Added live, heartbeat-backed execution handoff across resumed terminals with atomic A-to-B-to-C transfer and immediate source fencing; one-shot commands cannot impersonate a live owner.","Handoff now flushes and relinquishes the source session-writer lock before printing the resume command, so the target can resume the same transcript without either terminal deleting or rewriting the other's lock state.","Synced Agent SDK 0.9.23 and Agent Interface 0.1.20 for the shared Goal / Loop / Handoff runtime contract."],"0.5.39":["Added XENO Web Context search, fetch, render, map, crawl, extract, job wait/cancel/resume, and Browser handoff commands with canonical evidence metadata.","Preserved Chat and Agent session mode/workspace identity across CLI and Interface resume paths.","Synced Agent SDK 0.9.22 and Agent Interface 0.1.19 for the typed Web Context runtime event contract."],"0.5.38":["Corrective Agent Interface handoff: explicit Chat, Agent, and resume launch intent now wins over restored persisted desktop tabs after session hydration.","`xeno agent --interface` preserves the exact granted workspace even when the desktop has existing Chat history, while `xeno chat --interface` remains Chat-only with no project grant.","Synced the Agent Interface client and contract packages to the installable 0.1.18 release."],"0.5.37":["`xeno chat --interface` opens the canonical desktop surface as XENO Chat with Chat-only authority and no project grant.","`xeno agent --interface` opens the same surface as XENO Agent and grants the exact current local workspace.","Synced the Agent Interface client and contract packages to 0.1.16."],"0.5.36":["`xeno chat` and `xeno agent` now launch the same canonical XENO terminal interface while preserving their invoked identity: Chat is branded XENO CHAT and Agent is branded XENO AGENT.","Chat mode owns a private managed workspace and cannot be promoted to Agent authority by saved settings or `--mode`; Agent mode keeps the explicit local-workspace and full-capability contract.","Windows Terminal multiline paste remains one editable composer item and submits as one persisted user message, including fragmented bracketed-paste frames.","Synced the Agent Interface client and contract packages to 0.1.15 and the Agent SDK to 0.9.21."],"0.5.35":["The provider cockpit now exposes durable provider lanes, exact native attach and detach, explicit stop and reconcile controls, and persists whether each Agent session is Chat mode or Agent mode.","The status bar shows the active provider lane, and non-interactive provider, lane, attach, and reconcile commands expose the same control plane to scripts.","The local release gate now builds the native Windows XENO PTY before integration tests and typechecks the complete test surface from a clean checkout.","Synced the Agent Interface client and contract packages to 0.1.12 and the Agent SDK to 0.9.18."],"0.5.34":["Windows multiline-paste recovery now keys off the actual win32 runtime even when terminal TTY capability probing reports an inconclusive profile.","Input diagnostics now record the runtime platform, terminal profile, and stdin/stdout TTY state so real-terminal evidence explains which paste path ran."],"0.5.33":["Windows Terminal multiline paste now remains one editable composer message even when Windows omits bracketed-paste markers because virtual-terminal input is unavailable.","Real bracketed-paste frames still retain stateful fragmented-stream handling, and an ordinary Enter remains a submit after the short paste-boundary grace period.","Synced the Agent Interface client and contract packages to 0.1.11 and the Agent SDK to 0.9.17."],"0.5.32":["Recent-session state now stays inside XENO_AGENT_HOME and uses durable per-workspace updates, preventing Windows EPERM contention and lost concurrent session entries.","PowerShell command completion now drains the final stdout pipe data before settling, so successful commands cannot intermittently return empty output."],"0.5.31":["Windows Terminal bracketed-paste mode is now explicitly negotiated for the full composer lifetime, correcting 0.5.30's incomplete decoder-only repair.","Native TUI and external-editor handoffs release terminal paste mode before transfer and restore it only after XENO regains terminal ownership.","`--interface` now waits for an exact nonce-bound acknowledgement from the desktop renderer instead of reporting success when an older app merely spawned and ignored the resume request.","Managed finite operations can continue beyond the generic three-turn safety cap, recent-session writes are serialized across processes, and background commands receive privacy-safe semantic fallback labels."],"0.5.30":["Multiline terminal pastes now remain one editable composer message even when Windows Terminal fragments the bracketed-paste frame across multiple input chunks.","Complete bracketed-paste frames are handled before generic Escape sequences, and their terminal markers never leak into the submitted prompt."],"0.5.29":["ACP provider cockpit: resume durable Codex, Claude, and compatible provider lanes without replaying the XENO transcript into a new native session.","Attach, detach, reattach, stop, and reconcile native provider TUIs with one-writer ownership between the XENO TUI, Agent Interface, and provider terminal.","`--interface` handoff now preserves the selected conversation host binding and exact provider continuation identity.","Background work uses semantic task names, and continuation checkpoints retain the original objective instead of ending a live operation at an arbitrary automatic-turn boundary.","Synced Agent Interface client/contract to 0.1.8 and @xenosystem/agent-sdk to 0.9.14."],"0.5.28":["The root `xeno --help` output now exposes `--interface` and `--resume [id]`, so terminal-to-desktop session handoff is discoverable at the exact command surface where it is used."],"0.5.27":["Open the XENO Agent Interface from the terminal with `xeno --interface`, resuming an exact session ID or the latest session in the current workspace.","Long-running background commands now stay alive while active, preserve native PowerShell syntax, and display meaningful task names.","Short follow-through messages such as do it and proceed now retain implementation authority, while nested continuations preserve the original objective.","Synced @xenosystem/agent-sdk to 0.9.13."],"0.5.26":["Terminal bracketed paste & multi-line input: bracketed paste frames are cleanly decoded, collapsed into `[Pasted text #N +N lines]` tokens for large blocks, and submitted with full uncorrupted text without escape code dropouts.","Dynamic terminal reflow: turn receipts, turn dividers, and prompt bubbles adapt smoothly to window resize events without clipping."],"0.5.25":["Interactive `/status`, `/config`, `/usage`, `/stats`, `/settings` multi-tab modal with live search, keyboard cycling, and instant ~/.xeno/config.json persistence.","Live 52-week session activity heatmap, longest/current streak metrics, active days summary, lifetime token metrics, and favorite model analytics.","Real-time git workspace analytics including active branch, ahead/behind counts, working tree diff additions/deletions, and live turn API elapsed times.","Turn receipt visual polish with right-margin padding and formatted recap indentation.","Interactive `/handoff` command: switch seamlessly between specialist agents with prompt context and intent transfer.","Zero-config `.claude/agents/*.md` & `.xeno/agents/*.md` discovery with level-ordered priority shadowing.","Host mid-turn steering (`turn.steer`) and subagent wire payload artifacts integration.","Synced @xenosystem/agent-sdk to 0.9.12 with enhanced offline grace monetization validation.","xeno-rt: resolved Qwen 3.8 / 3.5 MTP NextN architecture prefixes and prevented layer 32 recurrent tensor probe failure."],"0.5.24":["Published with exact matching CLI_VERSION literal, guarded by verify:version in CI.","Synced @xenosystem/agent-sdk to 0.9.11, pulling model-aware context budgets from live gateway `/v1/models` catalog.","`/import` now immediately triggers context reconstruction turns rather than pausing at the input prompt."],"0.5.23":["Model-aware context budget: queries gateway `/v1/models` catalog for authoritative `context_window` limits.","Context compaction request byte budget scaled to prevent false refusals on large toolsets."],"0.5.22":["`/context` divided by a hardcoded 200,000 regardless of which model you are on. That figure is XENO's window and nobody else's: on a 128,000-token OpenAI model the gauge read about 12% where the truth was 19%, and near the limit it said \"Context is healthy\" with compaction imminent; on Google's 1,000,000-token window it pegged at 100% from a fifth of the way in and warned permanently. It now divides by the budget the SDK actually resolved for the run.","The gauge also says how well it knows that number. A configured budget is exact and prints a plain percentage; a provider profile is one window for every model that provider serves, so it prints `~62%` and labels itself approximate. Before any turn has reported, it says the 200,000 is an assumption rather than presenting it as fact.","The numerator was always right and is unchanged: it sums the messages currently in context, so it falls when a compaction drops them. Only the denominator was asserted rather than resolved."],"0.5.21":["Security: undici 6.27.0 -> 6.28.0, closing a cookie-injection advisory. This repo had 12 open alerts and this was the ONLY one that reaches shipped code \u2014 the five rated HIGH are all build and test tooling. Fixing by severity rank would have addressed the wrong thing first.","Worktree cleanup could delete THROUGH a junction. That is the failure that destroyed two repositories on 2026-08-03: on Windows a recursive delete follows a junction and removes the target, and npm creates one for every file: dependency. Cleanup now clears the reparse point itself and never the thing it points at.","Worktree cleanup had also decayed into a no-op \u2014 its filter excluded every orphan it existed to remove, so it ran, reported success, and cleaned nothing. And a reparse-point scan that hits its cap now REFUSES rather than returning a short list, because a truncated scan that looks complete is how the delete above becomes safe-looking.","The control-plane `list()` was not a read: it wrote once per stale record, every time anything listed runs. Listing is now free of side effects.","`/import` brings a session from another agent CLI into XENO and continues it \u2014 including agy stores, where the obvious store turned out not to be the best source. `--imported` shows what is on disk and says plainly that it persists. The source transcript is never touched, and that is enforced rather than intended.","Delegated branches now run on the Agent host under XENO_AGENT_ATTACH, report tool progress while they work, and the CLI reads the HOST's audit rather than only its own. Previously a host-routed branch was silent until it finished, and a refusal blamed a missing stream that in fact existed.","`xeno host status` now reports WHICH lanes the host offers and why a blocked one is blocked \u2014 including whose environment the blockage is about, which was the part that made the old message useless.","Pinned to @xenosystem/agent-sdk 0.9.10. The pin had been two releases stale, so work that shipped in 0.9.9 reached nobody. 0.9.10 also reports how full an agent's context is: turn.completed carries the RESIDENT token count, not the cumulative billing counter, and context.pressure arrives after every model response. The obvious field re-adds the whole prompt each turn \u2014 measured live, three one-word turns reported 3049, 6106 then 9171 tokens while the context grew by about eight.","Budget accounting no longer reads the entire run store when no budget cap is configured."],"0.5.20":["Pinned to @xenosystem/agent-sdk 0.9.8. The SDK's ownership policy still labelled this CLI by a scope retired in 8363d30c, which had failed the release smoke on every run since 2026-08-13 \u2014 the mismatch was never in this repo, so the fix was a repin rather than a workaround.","The release smoke now derives how strict it should be from the release trust policy: while no signing identity is approved it holds the engineering bar, and it tightens by itself the moment one lands. It previously demanded a signature no ordinary CI run could produce, and had failed for long enough to read as background noise.","First test coverage of the native manifest signing path, which had never executed once. Signer and verifier each carry their own copy of the canonical-JSON serializer and cannot import each other, so a drift as small as key ordering would have invalidated every release signature \u2014 and would have surfaced on release day, looking like a key problem.","Windows: temporary-directory cleanup no longer loses a race with exiting child processes, and the certification matrix checks out correctly on Windows ARM. `force: true` suppresses ENOENT, not EPERM, so the previous cleanup looked defensive and was not.","Groundwork for interactive Ctrl+C on Windows: the native addon can now raise a real console interrupt. Writing 0x03 into a ConPTY does not raise a signal, which is why Ctrl+C has never worked there. NOT yet wired \u2014 the console attach succeeds and the event is raised, and a ConPTY client still does not observe it."],"0.5.19":["The CLI did nothing at all on Linux and macOS. Its entry point did not resolve symlinks, so every npx and global install ran the wrong path and exited silently \u2014 the install looked successful and the binary did nothing. Fixed.","Agent permission decisions now reach an actual human on both rails, rather than being resolved without one.","A remote run that is read-only now says so, instead of failing silently and leaving you to work out why nothing changed.","The version the binary REPORTS is now bound to the version npm publishes, and a test enforces it. They had drifted: 0.5.18 was published as a package whose `--version` said 0.5.17.","\u26A0\uFE0F 0.5.18 exists on npm and was published from a branch that was never merged. It is superseded by this release, which is cut from `main`. If you installed 0.5.18, upgrade."],"0.5.17":["The CLI now ships as @xenosystem/agent-cli. The former name @xeno-corporation/xeno-agent-cli is deprecated on npm and receives no further releases; the `xeno`, `xeno-agent` and `xeno-code` binaries are unchanged, so nothing in your shell or scripts has to change.","The exact SDK pin moves with it: the CLI is bound to @xenosystem/agent-sdk 0.8.12. 0.8.11 was never published under either name and cannot be \u2014 GitLab evaluates .gitlab-ci.yml as it exists at the tag, and tag sdk-v0.8.11 predates that pipeline.","This release cannot be installed until @xenosystem/agent-sdk 0.8.12 is live on the registry; the release pipeline fails closed on --require-dependencies-published until it is."],"0.5.16":["Windows 11 ARM64 containment certification now performs architecture-neutral MXC host preparation with the reviewed x64 helper through operating-system emulation while keeping the contained runtime native ARM64.","The CLI is bound exactly to SDK 0.8.11, whose host-preparation reports distinguish the host architecture from the reviewed setup-helper architecture and retain timeout diagnostics."],"0.5.15":["macOS and Linux standalone diagnostics now report their verified POSIX process-group lifecycle independently from the stronger process-hardened sandbox level, preserving truthful security status while certifying full-tree cancellation, timeout, and shutdown behavior.","Generated Harbor benchmark and audit workspaces are excluded from source control, keeping Windows ARM64 checkouts below platform path limits and removing 9,938 generated artifacts from release candidates."],"0.5.14":["Windows 11 24H2 containment admission now uses the authoritative non-server NT client build floor instead of rejecting current Azure and GitHub Windows 11 images whose legacy registry ProductName still says Windows 10.","Windows Server remains fail-closed, pre-26100 clients remain ineligible, and both x64 and ARM64 host identities have regression coverage."],"0.5.13":["Hosted Windows x64 containment certification now fails closed unless the runner is Windows 11 24H2 or newer, the platform supported by Microsoft MXC, instead of treating Windows Server runner failures as product failures.","The certification matrix accepts a protected XENO_WINDOWS_X64_RUNNER label for an ephemeral Windows 11 x64 runner while keeping all other hosted platform rows unchanged.","Containment failure reports preserve bounded head-and-tail diagnostics through SDK 0.8.10 so the actionable trailing Win32 or MXC error is retained."],"0.5.12":["Windows MXC containment now launches its unrestricted host from the prepared system-drive temporary directory, outside directories whose DACLs are mutated by the contained policy, and certification captures official redacted MXC diagnostics.","Internal background session workers no longer start a competing global reconciler, preventing slower macOS hosts from quarantining a healthy turn between transcript append and checkpoint commit.","The interactive attach/input/stop smoke now follows the actual persisted inbox sequence and records worker logs on failure; the CLI is bound exactly to SDK 0.8.9."],"0.5.11":["Windows x64 containment certification now launches the MXC host and contained runtime with working-directory and temporary paths on the prepared system drive, matching split-drive GitHub runners.","The CLI is bound exactly to SDK 0.8.8, preserving the passing Linux, macOS, and Windows ARM64 conformance behavior while repairing Windows x64 ProcessContainer startup."],"0.5.10":["Linux containment certification now keeps disposable fixtures under the OS-private temporary mount instead of GitHub's workspace-projected runner directory, preserving the unlisted-filesystem boundary probe.","Windows certification retains the MXC-prepared system-drive fixture root required by hosted runners whose workspace and default temp directory use another volume."],"0.5.9":["Windows containment certification now creates its disposable fixtures on the MXC-prepared system drive, including hosted runners whose workspace and default temp directory live on another volume.","Standalone Windows certification now performs the same explicit host preparation and temporary-root binding as the native package matrix."],"0.5.8":["Native containment certification now compiles its macOS UI-policy probe against the stable libsystem_sandbox ABI without depending on private SDK headers.","Windows certification now distinguishes MXC's persistent per-policy DACL requirement from its explicit one-time host-preparation warnings."],"0.5.7":["The immutable CLI candidate now binds SDK 0.8.5 to the exact canonical Linux npm tarball bytes used by certification."],"0.5.6":["Windows containment certification now performs Microsoft MXC's explicit idempotent host preparation before AppContainer+DACL conformance.","macOS ARM64 certification now records behavioral Seatbelt evidence for pasteboard, WindowServer, LaunchServices, and HID isolation."],"0.5.5":["Native certification now resolves the SDK candidate artifact from the same workspace path on Bash and PowerShell runners.","SDK containment assets retain executable package modes on Linux and macOS, with a source regression check for every reviewed Unix binary."],"0.5.4":["Native engineering certification jobs now download the exact SDK tarball produced by the successful parent gate before installing dependencies.","The six-platform matrix remains source-bound to one immutable CLI tag and one immutable SDK candidate artifact."],"0.5.3":["Candidate packaging accepts both npm 11 array-form and npm 12 package-keyed JSON, with explicit diagnostics for malformed output.","Hosted SDK packaging now parses a bounded JSON file instead of relying on a large shell variable or an obsolete npm output shape."],"0.5.2":["Hosted certification now caps SDK declaration generation at two concurrent entry points and cleans declaration output in isolated bounded-memory workers.","SDK build subprocess failures now report their terminating signal or exit status instead of producing a silent hosted-run failure."],"0.5.1":["Hosted certification now builds the exact SDK candidate in bounded declaration groups, preventing parallel TypeScript declaration generation from exhausting GitHub-hosted runner resources.","Post-freeze readiness now distinguishes exact candidate tags verified at the candidate commit from collisions in release, registry, feed, and service namespaces."],"0.5.0":["Agent Profiles now provide enforceable Assistant, SWE, Reviewer, Writer, Research, Product, CI, DevOps, and Legal Research identities with bounded tools, permissions, skills, hooks, memory, isolation, and external-action authority.","The XENO Artifact Protocol adds durable plans, patches, diffs, reviews, screenshots, recordings, reports, provenance, approvals, and evidence relationships shared across local, hosted, and Hub workflows.","Secure Execution Contracts and capability leases now make filesystem, network, secret, process, device, browser, and external-action authority explicit and auditable.","Skills v2 adds standards-compatible SKILL.md discovery, progressive loading, bundled resources, invocation policy, version identity, and compatibility with XENO, .agents, and Claude skill locations.","MCP now supports current Streamable HTTP sessions and OAuth discovery while retaining compatible stdio and legacy SSE connections.","Browser, computer-use, hosted-agent, semantic-index, production-review, spec-planning, secure-sharing, and provider-onboarding surfaces are integrated through the shared platform contracts.","The retained TUI now presents stable grouped tool activity, live task and subagent status, candidate-bound edit previews, context-pressure and compaction state, and clearer turn completion receipts.","Six-product candidate certification now binds the SDK, XENO Use, XENO Browser, Agents API, CLI, and Hub to exact source identities, versions, tags, evidence, and protected release gates."],"0.4.45":["This transitional release is engineering-tested but not GA-certified: native PTY artifacts are unsigned and remain disabled by default until the Azure signing identity is approved; ordinary CLI and pipe-mode commands remain available.","App Server v2 now provides durable threads and turns, typed clients, permission ownership and expiry, bounded replay and backpressure, authenticated HTTP access, and additive v1 compatibility.","The terminal renderer now uses committed retained frames, bounded coalescing, one normal write per frame, a responsive 50-agent footer, accessibility modes, and a native terminal compatibility matrix.","Release certification now fails closed on six native architectures, platform and manifest signatures, reproducible package payloads, SBOMs, provenance attestations, independent approvals, npm OIDC publication, and public clean-install verification.","Long chat prompts now soft-wrap into a growing six-row composer with Unicode-safe editing, visual Up/Down navigation, file-panel parity, and a temporary XENO_INPUT_SOFT_WRAP=0 rollback switch.","Long-running model-authored shell commands now use managed operations: Ctrl+B promotes the same process, finite background work waits without model polling, and durable continuations resume exactly once after terminal output arrives.","ReadImage now uses Xeno's dependency-free owned raster codec for bounded PNG, BMP, Netpbm, and core-SVG previews; /processes and doctor expose task control, process-tree containment, operation-schema, and codec status.","Dynamic workflows now expose first-class run limits and terminal reducer summaries in run records and inspect JSON.","Background agent sessions now deliver durable completion, failure, stop, and request-keyed needs-input notifications to interactive parent chats and bounded headless runs without clobbering prompt drafts.","Workflow orchestration includes grouped phase/child progress, parent-chat completion notifications, WorkflowWait, /workflows drill-down, watch JSONL snapshots, and ultracode workflow prompts.","Workflow starts now support plan preview and exact-definition approval memory, scheduler ticks are serialized, and workflow lifecycle metrics are available through the OTel usage export.","Tool activity now uses semantic Update and Search labels, contextual line-numbered edit previews, expandable read/search/shell output, and accurate failure rendering.","Interactive chat now blocks repeated inspections and unrequested mutations on short questions, gives explicit research a larger typo-tolerant evidence budget, and reserves a tool-free final-answer turn when work limits are reached."],"0.4.44":["Markdown source links now render as clickable terminal links in supported terminals, with visible URLs preserved when links are disabled."],"0.4.43":["New background agents now appear in the footer immediately after launch, and the footer can show up to eight agent sessions."],"0.4.42":["Background agent footer rows now fit the common three-agent fanout without hiding the first agent on compact terminals.","Completed background agent sessions now close after BackgroundAgentJoin returns their result to the main agent."],"0.4.41":["Completed background agent footer rows now keep a fixed runtime instead of continuing to count upward."],"0.4.40":["One-shot background agent sessions now mark done after returning their result, while user-follow-up sessions stay idle for continued chat."],"0.4.39":["Background agent session activity now uses concise status labels like Thinking instead of showing the full task prompt."],"0.4.38":["Opened background agent sessions now show their own session activity line while keeping main-agent tool progress isolated."],"0.4.37":["Opened background agent sessions no longer show the main agent's active tool progress line."],"0.4.36":["Opened background agent sessions now render the same main-chat transcript surface for user messages, assistant messages, tool calls, and tool results."],"0.4.35":["Background agent session chat now includes tool calls and tool results in its visible history."],"0.4.34":["Opening a footer background agent now switches the main chat surface into that agent session instead of showing a separate info panel.","Child-session input now queues messages to that agent while Esc returns to the main chat."],"0.4.33":["Background agent footer rows now repaint immediately during active turns.","Remembered background-agent approvals now apply to later background-agent launches."],"0.4.32":["Startup release-note hints now sit directly under the note text and render dimmed in the side panel."],"0.4.31":["Unread release notes now render beside the startup XENO AGENT header on wide terminals."],"0.4.30":["BackgroundAgentList now only reports current-chat footer sessions so old workspace agents do not hide missing new deployments."],"0.4.29":["Background agent footer markers now use filled and empty squares.","Opening a background agent from the footer now shows its session chat with transcript and message input."],"0.4.28":["First-run default model is now gpt-5.5 while saved user model choices are preserved.","Number keys in the model picker now type into search instead of selecting by index.","Model selections made with /model now persist as the user's saved default."],"0.4.27":["Background agent footer rows are now scoped to the current chat session."],"0.4.26":["Background agent rows now sit below the status line and inherit the live chat model."],"0.4.25":["Legacy BackgroundAgent calls now create footer-visible interactive background sessions."],"0.4.24":["Model picker support now has a `xeno models --json` command, share export proof, and GitHub review artifact contracts."],"0.4.23":["Model picker and /model listings now refresh Xeno API model availability before switching."],"0.4.22":["Hook review now shows command-hook hashes and supports trust, disable, and explain commands.","Expanded lifecycle hooks now cover permission decisions, stop failures, and delegated subagent start/stop events.","Set XENO_STATUS_LINE_COMMAND to replace the TUI status line with a cached command output.","Rewind now saves the abandoned conversation branch as a manual checkpoint before restoring.","Interactive chat now supports Ctrl+R history search, Ctrl+G prompt editing, /vim input mode, and /copy answer/block/diff clipboard copy.","/theme is now a discoverable alias for /color with user/project custom theme files, and /processes stop-all stops running background tasks."],"0.4.20":["Shell completions now include the current control-plane commands, flags, statuses, scopes, and usage groups.","The local app-server browser page now includes prompt and process controls on top of advanced JSON-RPC.","Published CLI and SDK packages now include GitHub repository metadata.","Docs now call out the temporary GitHub Actions startup_failure blocker while local gates remain authoritative."],"0.1.0":["Persistent shell sessions now preserve cwd and shell state across Bash calls.","Delegated planner, explorer, executor, and reviewer branches now support staged and parallel policies.","MCP now supports stdio and SSE transports, prompt discovery, resource reads, and live tool sync.","Notebook, ask-user, and memory tools are available in the shared agent runtime.","CLI operator workflows now include doctor, bug-report, config editing, cost summaries, and runtime inspection."]};function m9e(e=Pe){return yvi[e]??[]}function bvi(e=Pe){let t=_t().lastReleaseNotesSeen;return m9e(e).length>0&&t!==e}function mU(e=Pe){Ao({lastReleaseNotesSeen:e})}function Fye(e){let t=e??Pe,r=m9e(t);return r.length===0?`No release notes available for version ${t}.`:[`Release notes for version ${t}`,"",...r.map(n=>`- ${n}`)].join(`
|
|
6647
|
+
`)}function wvi(e){let t=e.replace(/\s+/g," ").trim();return t.length>72?`${t.slice(0,69)}...`:t}async function Lye(e){if(!e.checkpointManager||e.messages.length===0)return null;let t=`Branch before rewind to "${wvi(e.targetPrompt)}"`,r=await e.checkpointManager.create({trigger:"manual",messages:e.messages,description:t});if(e.sessionManager){let n=[r.id,...e.sessionManager.meta.checkpoints.filter(i=>i!==r.id)];await e.sessionManager.updateMeta({checkpoints:n}),await e.sessionManager.transcript.append({type:"checkpoint",data:{id:r.id,action:"create",name:t,trigger:"manual",messageCount:e.messages.length}})}return r.id}Qo();bo();var yvi={"0.5.189":['Fixed: `xeno auth status` and `xeno run` no longer fail with "Canonical XENO account host is unavailable" on Windows and Linux installs upgraded from an earlier account store (bundles `@xeno-corporation/account` 0.4.3).',"Updated: pins the Interface 0.1.208 host and runtime packages alongside XENO Agent 0.3.57."],"0.5.188":["Fixed: with Ask first, the agent really asks before it writes or edits a file in your folder. 0.5.187 said so, but the engine still let a write inside the folder through without a question; this version runs the engine that asks (SDK 0.10.123).","Fixed: when you refuse something the agent asked to do, it is told you refused and to stop and ask you, instead of being told nobody was there, so it no longer tries another way to do the same thing."],"0.5.187":["Fixed: nothing a run writes about your project shows up in git status any more. Its notes live in .xeno/local/, which git ignores.","Fixed: with Ask first, the agent asks before it creates a new file, as it already did before editing one.","Fixed: a turn run through ACP on the shared Agent host uses the same up-to-date engine as every other turn, so it waits out a rate limit too."],"0.5.186":['Fixed: a rate limit no longer ends a run after a few seconds. When a provider says "too many requests", the agent now waits it out: at least as long as the provider asks, backing off up to a minute, for up to three minutes in all.','Fixed: a run that stops on a rate limit says so. It used to be reported as a permission problem (exit 2) when an earlier tool call had been denied. `xeno run --json` now reports `error` with `error_category: "rate_limit"`.'],"0.5.185":["Fixed: commands chained with `;` run in process-hardened and contained runs on Windows."],"0.5.184":["Fixed: `xeno run` on the shared host uses the model you chose. It used to run the host's default, a different model each time, when the host listed yours under another name.","Fixed: cmd switches such as `cd /d`, `dir /b` and `findstr /i` are no longer refused as paths, and commands chained with `;` run on Windows.","Fixed: `xeno run` prints the agent's last reply as the answer, and a Windows PATH that starts with `;` no longer breaks every command.",`Fixed: the agent always writes its own answer. The shared host used to end a turn right after a tool ran and show the tool's raw output instead, for example a whole file after a request that said "read" and "exact".`],"0.5.183":["Fixed: when a command fails, the agent now reads the error and keeps going. The shared host used to end the turn two seconds after a failure and show the raw error as the answer.","Fixed: commands written in PowerShell run on Windows again. The shared host sent every command to cmd.exe, which refused PowerShell.","Fixed: Stop on Windows ends everything a command started, including programs a PowerShell command launched.","Fixed: Stop always ends the turn cleanly, even while the agent is waiting for the model's first answer."],"0.5.182":["Fixed: 0.5.181 could not sign in, because it was published without its account module. Update if you installed it.","Fixed: a machine reached over SSH can now run turns, with the key to its stored state kept on your PC."],"0.5.181":["New: xeno host bridge, which the XENO Agent desktop app runs on a Linux or macOS machine over SSH. You do not run it yourself."],"0.5.180":["Fixed: xeno run no longer refuses when you saved bypassPermissions as your permission mode. Your saved setting is your choice. Asking for bypass on a command line still has to pass the safety check."],"0.5.179":["Security: bypassPermissions now has to pass the safety check however you turn it on, including --permission-mode and saved config. It runs only in a container with no internet, or with XENO_ALLOW_UNSAFE_BYPASS=1."],"0.5.178":["A newer CLI no longer runs silently on an older XENO Agent host that another app started: an idle older host is replaced, and a busy one is named."],"0.5.177":["When XENO Corpus is installed, it can search your conversations, including what compaction drops from the agent's context."],"0.5.176":["Machine mode now uses XENO Use 0.3.2, which is proprietary. Nothing in how it works changed."],"0.5.175":["/machine in a chat, or xeno --machine, lets the agent use this Windows PC. Run /machine again to stop.","xeno browser connect links XENO Extension in your own Chrome or Edge to the agent."],"0.5.174":["xeno run --machine lets the agent use this Windows PC: real screenshots, clicks and typing. XENO Use downloads itself the first time.","Browser tools work in your own signed-in Chrome or Edge once the extension and its companion are connected."],"0.5.173":["xeno run --mcp and xeno run --image now run on the shared Agent host.","The default model can see images a tool returns: gpt-6-luna and gpt-6.1-sol receive the picture instead of a note saying they cannot."],"0.5.172":["xeno run now goes through the shared Agent host when you are signed in, with its tool lists, fallback models and required JSON answer."],"0.5.171":["Fixed: a chat on the shared Agent host stopped after 10 tool rounds. It now uses your limit, 50 by default.",'--continue no longer fails with "already locked" after a chat on the shared Agent host.',"A chat on the host keeps its web limits and keeps short questions short."],"0.5.170":["MCP servers you approved now work in a chat on the shared Agent host, each started in its own folder.","A chat tells you when a folder's server is waiting for approval."],"0.5.169":["Windows: the helper that runs commands is now one fixed program, so antivirus is far less likely to delete it."],"0.5.168":["A chat with MCP enabled stays in the CLI process again, so its MCP tools are there; the shared Agent host does not load them yet."],"0.5.167":["Windows: commands no longer fail with spawn UNKNOWN when antivirus quarantines the process launcher.","xeno host status now says whether a chat runs on the shared Agent host."],"0.5.166":["Interactive chat now runs on the shared Agent host by default, so conversations appear in the desktop app. XENO_AGENT_ATTACH=0 turns it off."],"0.5.165":["Several CLI jobs can share one sign-in: one renews at a time, and a half-finished renewal recovers by itself instead of asking for xeno login.","On the shared Agent host, a turn now draws its tools and token counts like any other, and Esc stops it and the command it was running.","If the direct route is down, a turn on the shared Agent host takes the Cloudflare route instead of failing."],"0.5.164":["On the shared Agent host, an edit made in the desktop app now reaches the terminal: the turn you edited away stops going to the model, and what you attach or rate there is kept too.","Windows: a scanner briefly holding a file no longer fails a scheduled job or other background write."],"0.5.163":["Conversations you start on the shared Agent host now appear in the XENO Agent desktop app, marked as started in the terminal, and you can carry on from either side."],"0.5.162":["On the shared Agent host, /rewind now puts your files back too: /rewind files shows what would change, /rewind files --confirm restores them. A file you edited since is never overwritten unless you add --overwrite.","Turns on the shared Agent host now remember what earlier turns did, not only what they said, so the model no longer doubts work it already finished."],"0.5.161":["On the shared Agent host, /rewind <n> continues from just before turn n in a new conversation; the original is kept. /rewind lists the turns.","On the shared Agent host, /compact summarises on the host: later turns are sent the summary, and every original turn is kept.","/fork [n] on the shared Agent host branches the host's conversation, all of it or through turn n."],"0.5.160":["In xeno chat on the shared Agent host, the host now keeps the conversation: a turn sends only your new message, and the host supplies the rest from its own record.","Conversations the host did not record from the start keep sending the CLI's own history, so nothing loses context."],"0.5.159":["--security-level process-hardened now runs on the shared Agent host instead of being refused, with the same restricted Windows token as a local run.","--security-level contained and --untrusted are still refused on the host, and say why."],"0.5.158":["An MCP server you signed into with xeno mcp login now works in the XENO Agent app too: the app uses the same stored credentials.","Opening a sign-in or app-server link no longer goes through cmd on Windows, so a crafted URL cannot run a command.","Share bundles now hide credentials found in a prompt or a tool's output, not only under secret-named fields.","xeno org, xeno github, xeno share and xeno mcp run on the same SDK code as the app; their behaviour is unchanged."],"0.5.157":["Chat turns run on the shared Agent host now carry this chat's permission mode and folders. Before, they ran with the host's defaults.","--mode chat can run on the Agent host: its turns ask the host for no tools, and a host that cannot enforce that refuses the turn. Before, a chat-only turn could not attach at all.","A chat turn whose settings the host cannot honour (such as --security-level contained) is refused with the reason, instead of running with weaker settings.","Plan mode works on the Agent host: the host's turn plans without changing anything, and its plan comes to you here for approval.","The agent can make a tool you keep and run again: it publishes a page as a tool on your XENO account. /artifacts publish|promote take --tool [--category <c>], and /artifacts keep-as-tool <id> keeps a hosted page as one."],"0.5.156":["xeno eval now uses the same eval code as the XENO Agent app, from the SDK; the app runs a project's eval suites itself. Nothing about how xeno eval behaves changes."],"0.5.155":["xeno recipes run now starts the recipe's workflow through the XENO Agent host, like xeno workflow run: the host drives it and runs each step, so it keeps going after this terminal closes, and the XENO Agent app's Recipes and Workflows tabs show it."],"0.5.154":["/approved-tools now also shows the folders you always allowed (they were remembered but never listed); remove takes a folder as well as a tool key, and clear forgets both. The XENO Agent app's Approvals tab manages the same list."],"0.5.153":["Your hooks now run in the XENO Agent app as well: the CLI and the app share one hook loader, one trust store and one runtime, from the SDK. A hook you trust with xeno hooks trust runs in both; an untrusted or disabled one runs in neither."],"0.5.152":["xeno ws: when a capability is not granted, the message names Settings \u203A Connected apps once instead of twice.","Scheduled workflows (xeno schedule workflow \u2026) now also run while the XENO Agent app is open, without the CLI daemon. Each schedule is claimed before it starts, so it never starts twice."],"0.5.150":["Scheduled prompts (/loop, the Cron tools and xeno app-server's schedules) now use the same scheduler as the XENO Agent app, from the SDK. The XENO Agent app runs a folder's scheduled jobs itself now, so they run while the app is open even without a terminal; a job is claimed before it runs, so it never runs twice. Schedules you already have keep working unchanged.","Security: built with XENO Agent Interface 0.1.140 (Electron 45.1.0, Node 24.22.1, fixing CVE-2026-111497) and XENO Agent SDK 0.10.92."],"0.5.149":["/artifacts publish (a local page) and adding a comment with /artifacts comments now go through the XENO Agent host, the same pages the app shows. Pages, links and comments work as before."],"0.5.148":["A policy you set with /peers policy now wins over the automatic rule: accept delivers even from a session running with more autonomy than this one. Leave it unset and messages that would move trust upward are still held for you.","Messages between sessions follow the coordination rules everywhere: the same message sent twice in a row is refused, and when a session's queue is full the oldest unread message is dropped and its sender told."],"0.5.147":["Messages between sessions now go through the XENO Agent host: /peers send, accept, refuse and cancel, the peer tool and the peer cockpit. The host checks that a session is really the one it says it is, and every surface sees the change as it happens."],"0.5.146":["xeno workflow run, pause, resume, cancel, retry, skip, rerun, save and create now go through the XENO Agent host, the same one the app's Workflows tab uses. The host runs the workflow, so it keeps going after this terminal closes, and after the host restarts.","Fixed: cancelling a workflow the host was running could stop the host itself. It now cancels only the workflow."],"0.5.145":['xeno run can approve a list of commands: --allowed-tools "Bash(command:python3 *)" lets an unattended run use matching commands without asking, and still refuses anything else, including a listed command that chains on a second one.',"An agent file's permissionMode is now reported as not applied, instead of being ignored silently. Choose the permission mode where the run is started.","xeno run --prompt-file - reads the prompt from standard input."],"0.5.144":["Background runs and workflows now run on the XENO Agent SDK's run store, the same one the XENO Agent app reads, so a workflow you start or pause in either one is the same workflow. Your existing runs and workflows are read as they are."],"0.5.143":["Goals and loops are now changed through the XENO Agent host, the same one the app uses: /goal, xeno goal and /loop send their changes there, so the app shows them as they happen.","Pausing, resuming or clearing a running goal still wins, now through the host as well.","Fixed (--line-input): a line you type while a command or an automatic turn is still running now runs next and its reply stays on screen. Before, the reply could be erased, or the line never ran."],"0.5.142":["Plugins and MCP servers are now managed by the XENO Agent host, the same one the app uses: xeno plugin, /plugin, /mcp and xeno mcp send their changes there, so the CLI and the app follow one set of rules.","Enabling a plugin now records that you trust it, so the app's host keeps it on instead of switching it off.","Fixed: /plugin uninstall no longer deletes the folder of a plugin you installed from your own project.","Fixed: xeno plugin list no longer crashes on an empty plugins.json."],"0.5.141":["Skills are the same in the CLI and the XENO Agent app. /skills and xeno skills now read one shared skill set, the same one the app's new Skills tab shows, so a skill you turn on in one is on in the other.","Turns run in the shared Agent host (XENO_AGENT_ATTACH) now have your skills too; before, they had none."],"0.5.140":["The CLI and the XENO Agent app no longer replace each other's background host. A running Agent host is now replaced only by a newer one; before, whichever started last swapped in its own copy, so an older app could downgrade the host the CLI started."],"0.5.139":["xeno plugin and the XENO Agent app now share one plugin store, ~/.xeno/data/extensions/plugins, so a plugin installed in one shows up in the other. Plugins still in ~/.xeno-agent/plugins keep working until xeno-home migrate copies them across; nothing is moved or deleted for you.","Your XENO files live in ~/.xeno. Installed updates and run logs used to go to the AppData folders; the CLI still reads them there, so nothing is lost, and the next xeno update installs into ~/.xeno.","An Agent-mode session grants the shared host the folders it was given, which you can see and revoke in the XENO Agent app under Settings > Folder Access, and /mcp decisions are recorded in the host too."],"0.5.138":["With XENO_AGENT_ATTACH set, the CLI starts the shared XENO Agent host itself when none is running, the same host the desktop app uses. It keeps running after the CLI exits, and the next CLI or the desktop app joins it.","A turn that fails in the host now fails the run. Before, a provider error could print status ok with an empty answer.","Turns through the host report real token usage and tool calls instead of zeros.","A long shell command collapses with a vertical \u22EE in the gutter, so the card's left rule stays unbroken."],"0.5.137":["XENO Agent turns can run in the shared Agent host, the same one the desktop app uses: set XENO_AGENT_ATTACH=1 (or require) for xeno run, or use /provider use sdk-native in chat. Turns run as your own XENO account; you never sign in twice.","Full Access carries through to the host as its full-access mode: no prompts inside the workspace, and writes outside it are still refused."],"0.5.136":["Security update: the bundled XENO account library moves to 0.4.1 and zod 4.6.7 (fixes a memory-exhaustion advisory that affects every zod 3 release), and undici moves to 6.29.1."],"0.5.135":["A slash command you have typed in full now shows in your accent colour, so you can see it will run, and deleting a letter brings the matching suggestions back.","After /logout, the next start shows the sign-in screen straight away instead of flashing the chat first.",'The sign-in waiting screens keep "Esc or Ctrl+C to cancel" on the bottom row, and the browser page you land on after approving is now a designed XENO page with your alien.'],"0.5.134":["Closing the terminal or ending xeno during a sign-in refresh no longer leaves you signed out: the next start finishes that refresh instead of asking you to sign in again.","The status bar keeps its colours on a narrow terminal, so Ctrl+Down shows which item you are on; long rows drop their least useful parts instead of turning grey.","After xeno login, your alien waves above the XENO name."],"0.5.133":["If your sign-in turns out to be invalid after chat has opened (expired, or a refresh that was cut off), chat now shows the sign-in screen right there and carries on once you sign in, instead of exiting and asking you to run xeno login.","The sign-in screen now animates the whole crew of six aliens, one after another, with its key hints along the bottom of the terminal. Esc on the sign-in screen exits straight away.","A CLI installed with npm no longer hands off to an older version that xeno update activated earlier."],"0.5.132":['New sign-in screen: six animated XENO aliens. Pick yours on first sign-in or any time with /alien; its detail follows your /color. The long browser link is now a clickable "Open the sign-in page" where your terminal supports it, and the device page now also answers at xenosystem.ai/device.',"Escape stops the running turn and clears queued messages; double Escape opens rewind only when the agent is idle and the input box and queue are empty.","/color adds Add color: type a #RRGGBB hex code and it stays in the picker after restarting.","xeno update installs beside running sessions, so an open session no longer makes the update fail with EBUSY. Pairs with @xenosystem/agent-sdk 0.10.77.","xeno run -y no longer overrides a --permission-mode you chose; device sign-in waits through short platform outages; XENO_ACCOUNT_PROFILE keeps a separate sign-in beside your normal one.","Chat draws its screen right away and checks your sign-in in the background; quitting during startup lets an in-progress sign-in refresh finish, so it can no longer leave your sign-in interrupted."],"0.5.131":["Escape interrupts the running turn and clears queued follow-ups without scheduling rewind. Double Escape opens rewind only on an idle, empty composer with no queued prompts; clearing input never counts as a rewind press."],"0.5.130":["/color now offers Add color: enter a #RRGGBB hex code, save it, and select it again after restarting. /theme and direct /color #RRGGBB commands support the same saved colors."],"0.5.129":["Updates install beside running sessions and activate atomically after signature, integrity, dependency and version checks; open sessions keep their loaded runtime."],"0.5.128":["Streamed partial paragraphs now appear before the next newline, with a replaceable preview that becomes formatted Markdown without duplicate text.","Gateway keepalives display Waiting for model output instead of Receiving model response. Fullscreen progress separates each model request's elapsed time from whole-turn elapsed time and labels cumulative turn tokens explicitly."],"0.5.127":["Long fenced code lines now wrap inside the code block: every continuation row repeats the left border and indentation instead of spilling to the terminal's left edge. Blank rows and wide Unicode characters remain aligned."],"0.5.126":["Self-review appears below the Worked for turn divider in fullscreen and line mode, with one Self-review label. Review limitations remain visible.","Shell calls show a readable command block with PowerShell labels, terminal-width wrapping and expandable long scripts instead of truncated multiline parentheses."],"0.5.125":["xeno update now recognizes Linux/macOS npm command symlinks as npm installs, so it installs the latest version instead of incorrectly asking for a native download. Background update eligibility uses the same resolved entry path.","Native checksum links use the correct GitHub Release download URL. Genuine native binaries still retain their own installation channel."],"0.5.124":["Chat now requires XENO account sign-in even with a model API key or local model. A valid account session is reused; signed-out piped chat stops with sign-in guidance. Use xeno run for unattended API-key execution.","SSH sign-in uses a device code in the running terminal. Browser and device sign-in open xenosystem.ai; existing token issuer and credential storage remain unchanged.","Linux without a system keyring keeps account sign-in only for the running process. Sign in inside xeno to use chat, or configure a Secret Service keyring for persistence."],"0.5.123":['After a turn that changed files, the agent now reviews its own work and shows one line after the reply, such as "Self-review: checked the edit; tests pass". Findings, fixes and anything left unverified expand with ctrl+o. A review that failed or ran out of time says so (SDK 0.10.75).',"`xeno run --json` includes the review as a `selfReview` field. Turn it off with `selfReview: false` in config or XENO_SELF_REVIEW=0.","Read-only commands containing JavaScript arrow functions no longer trigger a review by mistake. Windows commands also work when a deeply nested temporary directory would prevent the process launcher from starting."],"0.5.122":["Chat no longer gets a second, confused reply: the check that stops the agent claiming it made a file without verifying it now runs only when the turn actually wrote something (SDK 0.10.73)."],"0.5.121":['Signing in works again. 0.5.117 to 0.5.120 were published without the bundled account module, so `xeno login` reported "XENO sign-in is unavailable". This release is built with the isolated release builder, which refuses a package without it.'],"0.5.120":['`xeno update` works on Windows again: it failed with "spawn EINVAL" because newer Node refuses to start npm.cmd without a shell.',"The background auto-updater uses the same safe launch, so it no longer prints a Node deprecation warning."],"0.5.119":["`/import` turns a Claude Code, Codex or opencode session into a real XENO session, keeping turns, tool calls and results, lists what could not be carried, and offers to resume it. `xeno import <agent> <session> --json` does the same from a script.",'Updates install themselves in the background for global npm installs: at most every 12 hours, never a downgrade, rolled back if the new version does not start. A green "Update installed \xB7 Restart to update" appears above the input. Turn it off with XENO_NO_AUTOUPDATE=1 or `autoUpdates: false`.','Typing `!` shows a pink `!` prompt and "! for shell mode", so a shell command no longer looks like a chat message.',"Pasting or typing the path of an image turns it into an [Image #N] chip, like a clipboard image; Backspace removes the whole chip.",'`/exit` no longer reports "cleanup remains unconfirmed" for harmless steps. When something real is left behind it names the step, with details in ~/.xeno-agent/logs/cli.log.',"Resuming a session whose history has an unfinished tool call or an orphaned tool result repairs it once and saves the repair, so the provider accepts the next turn (`xeno --resume`, `/resume`, `xeno run --resume` and imported sessions).",'When an agent profile asks before an external action (a push, a publish, a deploy), chat asks "Allow <action> <target>?" with Yes / Yes for this session / No. Headless runs deny unless permissions are bypassed (SDK 0.10.72).',"A turn refused for an unfinished tool call shows the SDK's own explanation and what to do, instead of a generic error."],"0.5.118":['A turn no longer dies with "An error occurred while processing your request." after the agent changes directory: a `cd` inside a Bash call moves the session\'s working directory, and that is no longer mistaken for another terminal taking over the conversation.',"Failures now say what went wrong instead of hiding the cause in the session audit log (SDK 0.10.70)."],"0.5.117":["Act as one of your XENO agents: `xeno run --as <agent>` and `/as <agent>` in chat use the agent's identity, instructions, model and tools.","As an agent, xeno sees the tasks delegated to it, claims one while it works and releases it when the run ends. New comments arrive before the turn finishes."],"0.5.116":["Sign in with your XENO account on Linux, including Google Cloud Shell and SSH: `xeno login`, `xeno login --device`, or the chat welcome screen.","On Linux the sign-in is kept in the desktop keyring (Secret Service). Without a keyring it lasts until the process exits, and xeno says so; it is never written to a file."],"0.5.115":["On Linux and macOS, chat says account sign-in is Windows-only for now and names the API-key route, instead of a menu that could only fail.","Long sessions no longer freeze after you send a message: skills are no longer rescanned hundreds of times per request.","Rewind puts the removed message back in the input box. Restore notices disappear instead of staying in the conversation.","Published artifacts return to the tray when you resume a session, with fresh working local links.","Context usage uses the model's real window. The working row says when history is compacting, a model is responding, or a request is retrying; token totals say input+output.","SDK 0.10.66 retries incomplete tool calls instead of ending on a promise. A single denial no longer stops the loop; unattended denials name the allowed commands. Incomplete turns say so."],"0.5.114":["ReadImage shows the model the actual picture instead of text."],"0.5.113":["Overwriting a file shows a diff; Esc Esc opens a redesigned rewind picker; tables and long lines wrap cleanly.","Ctrl+Down moves into the footer; the status row shows context usage in plain words."],"0.5.112":['A long run is no longer refused with "Historical arguments violate schema" after the model sends an invalid tool call.',"A request that reads like a question (for example with a typo) is no longer refused its file changes; the permission mode decides."],"0.5.111":["Headless runs can use the skills they were given: loading a skill no longer asks for permission. What a skill does still asks as usual.","Uses SDK 0.10.61."],"0.5.110":["Acting as one of your XENO agents (`xeno run --as`, `/as`), the agent can also use the platform's image, video, Library and chat services, within its division budget.","`xeno auth status` says when a previous sign-in was interrupted, and that `xeno login` fixes it.","Uses SDK 0.10.60."],"0.5.109":["`xeno login` works without an interactive terminal (from an agent's `!` prompt, a pipe or a script): it uses device sign-in and says so, instead of ending silently.",'A failed sign-in says why (the account error and its code), with anything token-shaped removed, instead of only "could not be completed".',"`xeno auth status` reports whether you are signed in even when an API key pays for model requests."],"0.5.108":['Signing in works again. Since 0.5.95 the npm package was missing the module that holds your XENO sign-in, so `xeno login` said "XENO sign-in is unavailable". The release check now refuses any package that cannot load it.'],"0.5.107":["`/as` in chat: act as one of your XENO agents in the same conversation. `/as` lists them, `/as <name>` switches, `/as me` returns to you. Each switch revokes the previous agent credential, and leaving the chat revokes the last one.","`xeno run --resume` acts as the agent the session acted as before, with a fresh credential. Only the agent id is stored; `--as me` clears it.","Lines piped into `xeno chat` now run in order. Before, a slash command could end the session while later lines were still waiting.","Uses SDK 0.10.59."],"0.5.106":["`xeno run` takes its prompt from standard input (`xeno run -`, or piped with no prompt) or from `--prompt-file <path>`, so a prompt longer than a command line allows reaches the model as the message itself, up to 8 MB.","`xeno run --as <agent>` acts as one of your XENO agents: its instructions, model, effort and tool policy, with the XENO Tasks tools ready. Its credential stays in memory and is revoked when the run ends, however it ends. `--json` reports `acting_as`.","`xeno spawn <args>` hands the rest of the command to XENO Spawn.","Uses SDK 0.10.58."],"0.5.105":["`xeno run` saves every run as a session and prints its `session_id` in `--json` output. `--resume <id>` continues that conversation with a new prompt, and `--continue` picks up this folder's most recent session. Both work for local runs, not with --delegate, --remote or --bg."],"0.5.104":["`xeno run --output-schema <file>`: the final answer must be JSON that matches the given JSON Schema. An answer that does not match is sent back with the errors to fix, and the valid result is returned as `structured_output` in the JSON output. If no valid answer arrives, the run ends incomplete (exit 1).","Uses SDK 0.10.55."],"0.5.103":["A run that produced every output named in XENO_REQUIRED_OUTPUT_PATHS_JSON now reports ok (exit 0) even if one of its tool calls was denied along the way. The denial is still listed in tool_summary and the audit. Without declared outputs, a denial is still the outcome.","`xeno run --allowed-tools` and `--disallowed-tools` (comma-separated) control which tools the agent is offered. The limit also applies to helpers it starts."],"0.5.102":["A research run whose answer is a written document that cites its sources is no longer held open asking for the sources again in chat.","Uses SDK 0.10.54."],"0.5.101":["Skills found by default are named project:<name> or user:<name>, so the Skill tool resolves the name it was given, and the same name in project and user folders is two skills.","Child agents and background workers inherit their parent's skills again; the interactive-child inheritance tests pass.","Uses SDK 0.10.53."],"0.5.100":["You can set how much web research one turn may do. `xeno run` and chat accept --max-web-searches (1 to 200), --max-web-fetches (1 to 500) and --max-web-calls, or the environment variables XENO_MAX_WEB_SEARCHES, XENO_MAX_WEB_FETCHES and XENO_MAX_WEB_CALLS. Without them the limits are unchanged: 5 searches and 12 fetches for a research request, 3 and 4 for a quick question. A value that is not a whole number in range stops the command with a message. Each search can cost provider money, up to the per-request cap.","Uses SDK 0.10.42."],"0.5.99":["Web search uses your account's configured provider allowance when you have not set a limit. Explicit limits still narrow it, including zero: XENO_WEB_CONTEXT_MAX_PROVIDER_COST_USD and --provider-cost-budget-usd never silently authorize additional spending.","WebFetch reports the recorded reason when a page cannot be retrieved, such as site refusal, a missing page, rate limiting or a network error, instead of only saying the scrape failed. Conversational tools preserve the specific error code for the agent. Explicit site refusals are not bypassed.","Uses SDK 0.10.41 and Web Context client 0.1.5. The HTML transcript redesign and /provider picker remain outside this release."],"0.5.98":["Chat draws its composer before loading session state or building the agent. You can type immediately; early submissions wait until restoration, permission state and execution ownership are ready. In five real-terminal runs on our large workspace, the usable frame appeared in 579 ms median. Line-input chat also preserves input received before readiness, including piped input ending at EOF.","Terminal updates repaint only changed lines; typing and in-place tool updates no longer redraw the whole screen. The status command refreshes on changes with a bounded cadence. --version runs from a tiny entry without loading the agent runtime.","Background dispatch helpers report their results back when they settle. The footer separates the agent list from status by one blank row, keeps main and helpers adjacent, shows state on the left and aligns elapsed time and tokens on the right.","Web Context uses your signed-in XENO account by default, with a fresh DPoP proof for each request. XENO_API_KEY also works; explicit Web Context endpoint/token settings still take precedence. Gateway-prefixed search, fetch and artifact reads use Web Context client 0.1.3.","Uses SDK 0.10.40, including faster startup, background reports and the compatible Web Context client peer. The new transcript design and /provider picker are not part of this release."],"0.5.97":["Long sessions stay fast. Adding a line to the conversation no longer redraws the whole history: with 2,000 rows on screen, a new tool row went from about 8.5 seconds to about 5 milliseconds.","Each screen update is sent to the terminal in one piece, wrapped so terminals that support it paint it all at once, which removes flicker and half-drawn frames.","Typing @ to pick a file no longer reads the folder on every key; the listing is reused for two seconds. Set XENO_RENDER_STATS=1 to log frame times and key-to-screen latency to ~/.xeno/render-stats.jsonl."],"0.5.96":['The /model list is the full list the XENO API serves, read live. It shows "Loading models..." while it loads, says so plainly if the list cannot be loaded instead of offering a short built-in list, and keeps models that are temporarily unavailable at the bottom with the reason; picking one is refused with that reason.',"Switching to a model from the live list no longer makes a second network check, so the switch is immediate. Uses @xenosystem/agent-sdk 0.10.38."],"0.5.95":['Messages between sessions are now one line each. A sent message reads "sent to SESSION2: ... \xB7 queued" and its state (queued, held, delivered, running, reported, failed) updates in place; a received one reads "from SESSION1: ...". The full text and message id are behind ctrl+o, and the Send tool no longer prints its own call and JSON result.',"Tool rows no longer wait. A finished tool row settles at once instead of staying for at least 0.7 seconds, and the end of a turn no longer waits for it. Tool results open collapsed (ctrl+o to expand) instead of opening expanded and collapsing 2.2 seconds later."],"0.5.94":["You can save a model API key once with `xeno auth login --api-key`. It is read from a hidden prompt or from standard input, never from the command line, and it is checked with XENO before it is saved. XENO_API_KEY still takes precedence when it is set.","Where the key is kept: on Windows it is protected by Windows DPAPI for your Windows user account, using the native system call, and nothing is saved if that protection is unavailable. On Linux it goes into the desktop keyring (Secret Service, via secret-tool) when one is available, and otherwise into a file only you can read. On macOS it is a file only you can read.","If you used an earlier version, your saved API key moves to the new protected store the first time you start this version, and the old plaintext file loses only that key. Your previous sign-in cannot be carried over: run `xeno login` once to sign in again.","`xeno auth status` shows where the model credential is stored without printing any part of a key. On a machine that has never signed in it says 'not signed in' and how to sign in, rather than reporting a fault. `xeno logout` and `xeno auth logout` remove a saved key.","Account sign-in is available on Windows only for now. On macOS and Linux, `xeno login` says so and points to `xeno auth login --api-key` or XENO_API_KEY. Account sign-in is also bundled inside the CLI, so installing from npm needs nothing from a private registry.","Plan mode now works through the model's own tools: it starts planning by itself when the work calls for it and hands you the plan to approve. You can approve, approve with edits typed in your editor or the input box (your version is what gets carried out), or send it back with feedback. Tools from connected servers that only read keep working while planning. From @xenosystem/agent-sdk 0.10.35.","Stopping a helper at the exact moment it starts a tool no longer crashes the app.","Notification history and dismissal stay within the selected workspace, including isolated helper worktrees and deleted-parent recovery. Control Room actions accept the exact displayed snapshot for 60 seconds and refuse changed state.","MCP authentication failures identify the exact server and its dedicated login command. Repeated failures do not produce duplicate notices, and line-input chat shows the same recovery guidance as fullscreen chat.","Web fetch requests one page instead of exceeding the connected account's page quota. Map and crawl respect the account's page limit. Paid web search supports an explicit per-request USD budget and still defaults to no spending.","A prepared session handoff can now be cancelled from the original fullscreen or line-input chat. The exact offer is withdrawn before the conversation writer resumes; other detached execution stays refused."],"0.5.93":["Plan mode is here. Start with --permission-mode plan, type /plan, or press Shift+Tab: the agent can read and investigate but every change is refused until you approve its plan, including changes a helper agent would make. Plan mode survives a crash and resume, and xeno run returns the plan instead of waiting for an approval.","A session can now move to another enrolled computer with its conversation: the receiving computer downloads it from the execution authority and checks it is exactly the same before taking over. A computer that loses ownership now also stops the background tasks, helper sessions and workflow runs that session started.","Helper agents can be stopped one at a time from the agent list, cancelling a turn stops its helpers, and a helper that ran out of budget is shown as unfinished instead of done.","Every command that takes a prompt now refuses a /command it cannot run instead of sending it to the model, pause and resume on Windows really suspend the work, and slow Windows process queries no longer make commands time out. /goal clear, /goal pause and /loop stop now always win against a running goal loop, and a !command typed during a turn runs as a shell command."],"0.5.92":["A /command the chat does not know is no longer sent to the model as a prompt. Typos like /revew, commands this mode does not support, and commands from another lane now stop with a message naming the command and why, and nothing is sent. This covers the chat, xeno run, background runs and the app server.","Moving a session between computers through an execution authority now recovers safely: a computer that loses contact stops working on the session before another can take it, a failed or abandoned move hands the session back to the computer that offered it, and /handoff cancel withdraws an offer. The receiving computer checks it has exactly the same conversation before taking over.","Helper agents now keep their background tasks private: a helper can no longer read or stop its parent's or another helper's tasks, and the reverse."],"0.5.91":["You can now stop two computers from working on the same session at once. Run xeno app-server --http --execution-authority on one machine, enrol each computer with xeno executors add, and start chats with --execution-authority. While one computer has a session, another is refused until the first lets go or stops responding. Before, each computer only checked its own records, so two could both think they had the session."],"0.5.90":["Forking a conversation now makes you choose, instead of deciding silently: the whole conversation or only up to a checkpoint, and whether the fork shares this folder or gets its own git worktree. Use /fork in the chat, or xeno sessions fork with --history and --working-tree. An isolated fork says how many uncommitted changes it does not carry over. Before, every fork quietly shared the same folder, so both conversations changed the same files."],"0.5.89":["A helper started with dispatch_agent now shows in the agent list below the input while it works. Press Enter on it to open its conversation; what you type there reaches it at its next step, and once it finishes the conversation stays open to read. Before, it was one line in the transcript and its conversation could not be seen.","/agents now lists the agents started from this chat, numbered, so /attach 2 opens the one shown as 2."],"0.5.88":["With helper agents working, pressing Enter on a helper now opens its conversation in the chat, as it happens. While it is still working, what you type there reaches it at its next step. Once it has finished, the conversation stays open to read. Before, Enter showed only a status panel.","A large delegation budget no longer breaks the helpers. Given 200,000 tokens or more, a helper stopped before sending anything, because its whole budget was being reserved as room for one reply. From @xenosystem/agent-sdk 0.10.29."],"0.5.87":["Open a background agent's conversation right in the chat with /attach, by its name, its number in the agent list, or its id. Inside it, /attach opens an agent it started. Esc or /back goes back one level, and /main returns to your own chat. Before, opening an agent's agent lost the way back to the one you came from.","With helper agents working, the Down key now reaches the background agents below them too. Before, it stopped at the helpers."],"0.5.86":["An agent file's max-tokens and deadline now also apply when the agent is called as a helper in the middle of a chat, not only when it runs in the background."],"0.5.85":["xeno agents new now takes --max-tokens and --deadline (for example 30m), so a background run can have its own budget and time limit. They are kept with the run, so relaunching it does not reset them, and a reply in progress is stopped when the time limit passes.","An agent file can set a default budget with max-tokens and deadline at the top. It applies to background work started as that agent, unless you give a budget yourself. From @xenosystem/agent-sdk 0.10.28."],"0.5.84":["A background agent can now be given its own token budget and time limit when it is started. It stops once it has spent the budget, and when the time limit passes it stops, even in the middle of a reply. Both are kept with the session, so restarting the worker does not reset them. Before, a background agent had no limit of its own unless its parent goal had one."],"0.5.83":["With delegation on, each helper agent now stays inside its share of the delegation token budget. Before, the budget only limited each single reply, so a helper given 1,200 tokens could keep calling tools and spend several times that. It now stops once its share is spent and says how much it used. From @xenosystem/agent-sdk 0.10.26."],"0.5.82":["If the CLI closes while the agent is waiting for your answer, the question comes back when you resume the session, with the same choices. Before, the question was lost: the agent was told it had been interrupted and not to repeat it, so it never asked again. Press Esc to skip it and answer in your own words instead."],"0.5.81":["Tools from MCP servers now work with every model. Their names contain dots, and several models refused any request that included one: Claude and DeepSeek failed the whole turn, and gpt-6 answered with nothing. The tool still shows its real name in the terminal and in permission prompts. From @xenosystem/agent-sdk 0.10.23."],"0.5.80":["A tool server that sends a huge reply no longer ties up the agent. A reply over 16 MB is refused as it arrives, and the request fails right away with a clear error. Before, a 200 MB reply was read in full, which took about 48 seconds, and then almost all of it was thrown away. From @xenosystem/agent-sdk 0.10.22."],"0.5.79":["Long sessions stay fast to scroll. In a session of 10,000 messages, one scroll step took about 430 ms and now takes about 24 ms, and a keypress went from about 27 ms to about 4 ms. Resizing and entering scroll mode got faster too.","Images from tools now reach models that accept images even when the name is new, such as gpt-6, because the model list says which models take images. From @xenosystem/agent-sdk 0.10.21.","A reply that ends without the model sending anything now shows as an error instead of an empty, finished turn. From @xenosystem/agent-sdk 0.10.21."],"0.5.78":["When a tool's output is too long and gets shortened, the agent can now read the part that was left out. The full output is kept, and the new ToolOutput tool reads it back. Before, a long shell command lost its middle for good. From @xenosystem/agent-sdk 0.10.19.","ToolOutput reads appear in the compact tool-activity row with the other reads, and the tool line shows which stored output and offset it read."],"0.5.77":["Long sessions no longer slow down as they grow. Adding output used to re-draw the whole conversation every time, so each new line took longer the more was already on screen. Now 10,000 blocks of output take under a second instead of minutes, and memory stays flat.","The spinner on a running tool stays in the right place as output scrolls, including after it scrolls off screen and back."],"0.5.76":["Model endpoints behind a proxy that ignores streaming now work. Their reply is read as one complete answer instead of failing as a broken stream. From @xenosystem/agent-sdk 0.10.18."],"0.5.75":["A model reply cut off in the middle of a tool call no longer runs that tool with empty input. The agent is told the call was not run and nothing was changed.","If you stop the agent after it has sent a change, it is told the change may have happened, and to check before trying again, instead of being told it was cancelled. The same applies to a change that timed out.","The request time limit now covers the whole reply, not just the moment the reply starts. A reply that stalls part-way now ends at the limit instead of hanging. A timed-out request is not repeated automatically, because it may still be running.","`xeno harbor` analysis recognises the new timeout and dropped-stream messages as transport failures, as it did the old wording.","Uses @xenosystem/agent-sdk 0.10.17."],"0.5.74":["New Patch tool: the agent can change several files in one all-or-nothing edit, including adding, moving and deleting files. Nothing is written unless every change matches the files as they are. In accept-edits mode it is approved automatically, like Edit. From @xenosystem/agent-sdk 0.10.16.","Patch is treated as a file write everywhere a write is: it is denied in hosted runs that allow no edits, shown with the files it touches in the tool line and background session details, and counted by the completion checks that look at which files a run wrote."],"0.5.73":["Background and workflow workers that start slowly, for example on a busy machine, now claim their slot reliably. Before, a worker that took more than about 4 seconds to start could lose its slot and exit without a trace, leaving its run stuck as running. A worker that misses the longer start-up window is now refused with a recorded reason.","Stopping all of an agent's background processes now always finishes (from @xenosystem/agent-sdk 0.10.14)."],"0.5.72":['When no approval screen is available and the agent asks for permission in a plain terminal, typing "y" now approves. Before, every answer was recorded as a denial. For a command asking for extra access, the question now lists exactly what it wants and why. Uses @xenosystem/agent-sdk 0.10.13.'],"0.5.71":["Approving or rejecting an agent session's permission request in the Control Room now takes effect. Before, the session ignored the answer and kept waiting until it was stopped.","Control Room approvals and the SDK's built-in approval screens show a command's exact extra access and its reason, the same as the terminal prompt. Uses @xenosystem/agent-sdk 0.10.12."],"0.5.70":['When a command asks for access beyond its sandbox (network or extra folders), the approval prompt lists exactly what it wants and the reason it gave. It offers "Yes, for this call only" instead of "always", because an elevated command needs your approval every time. Uses @xenosystem/agent-sdk 0.10.11.'],"0.5.69":[`The agent can run a command in a specific directory, or through a specific shell (bash, sh, powershell, pwsh or cmd), for that one call, without moving the session's directory. The tool call line shows both, e.g. "npm test (in packages/app, via pwsh)".`,'Approving a command "always" covers only the directory and shell it was approved in, and the approval prompt names both.',"Requires @xenosystem/agent-sdk 0.10.10."],"0.5.68":["New: `xeno ctx-viz --audit` reports tools that are defined but registered by no lane, defined twice, or pointed at by an alias that goes nowhere. Run it from a CLI checkout; it exits 1 when it finds anything.",'Saving artifacts and other local records no longer fails intermittently on Windows with "EPERM: operation not permitted, rename" when another program briefly holds the file.',"Requires @xenosystem/agent-sdk 0.10.9."],"0.5.67":["Auto permission mode no longer asks before ElfAnalyze or ToolSearch, which default mode allows without asking.","The permission audit log labels every tool with the same risk level shown everywhere else.","New generated references: docs/TOOL_CATALOGUE.md (every tool per chat/run/ACP lane) and docs/TOOL_MAPPING.md (the permission decision per mode, how the terminal shows it, and its tests).","Requires @xenosystem/agent-sdk 0.10.8."],"0.5.66":["When a goal token budget runs out, the message now says how many tokens are left and how many the next request needs.",'A goal run no longer fails with "Ownership lease expired" when the process briefly stalls; the session keeps its lease as long as nobody else took it.',"Requires @xenosystem/agent-sdk 0.10.7."],"0.5.65":["Goal token limits now work on the XENO cloud route as a SOFT budget: each request's output is capped to what is left, measured usage is charged, and the goal stops once the limit is spent. One request may overshoot slightly, and the overshoot is recorded.","Local xeno-rt keeps its exact, hard limit. /goal status, xeno run and the chat notice say which kind of limit applies.","Requires @xenosystem/agent-sdk 0.10.5."],"0.5.64":["Removed the direct OpenAI Responses lane for bounded goals that 0.5.63 added. Token-limited goals run on local xeno-rt; other lanes refuse bounded work before inference, as in 0.5.62.","Background runs still refuse inline --api-key arguments, so a credential never reaches a worker's process arguments."],"0.5.63":["Bounded CLI goals can now use the official OpenAI Responses endpoint through an explicit OpenAI base URL and API key. Exact input counting, capped output and durable settlement share the same goal allowance as local xeno-rt.","The Responses lane refuses mutable remote image URLs, invalid counts and unsupported hosts before inference. It is fixture-qualified; live OpenAI and hosted/ACP quota qualification remain open.","Background runs refuse inline API keys before daemon handoff or worker spawn; use an environment or saved credential. Headless quota admission and execution now resolve the same provider endpoint."],"0.5.62":["Goals can use a durable total token limit in the local xeno-rt lane. The allowance survives restarts and is shared with local child agents; unsupported provider lanes refuse bounded work before inference.","TUI commands now execute in order, so renaming a session and immediately preparing a handoff cannot race their transcript and ownership changes.","Automatic goal continuation no longer inserts text into the command you are typing."],"0.5.61":["Goals can now carry an explicit total token limit with /goal set --max-tokens or xeno run --goal-max-tokens. The allowance survives restarts and is shared with local child agents.","Token-limited goals require a local xeno-rt runtime that advertises exact prompt counting and an enforced token ceiling. Other execution lanes report that requirement before starting work.","Automatic goal continuation no longer inserts text into a command you are typing. Human input received during a turn is queued for the next turn."],"0.5.60":[`The four canonical tools \u2014 Send, Receive, ListAgents, ListSessions \u2014 are now the CLI's own, bound to this session's peer runtime. 0.5.58 announced them and shipped the SDK's stock versions, which have no host: they recorded every message as coming from "unknown", so a delegated task's report had no sender to return to, and they forced every message to kind "task", so a note or a question ran a whole turn in the receiving session instead of being injected or asked. Both were silent. The name the release notes told the model to prefer was the one that got this wrong, while the legacy CoordinationSend it replaced got it right.`,"CoordinationSend and CoordinationQuery keep working, and are hidden again. They had been promoted back into the model's tool list beside their own canonical names, so one capability was offered twice.","ListAgents and ListSessions exist for the first time. They answer different questions on purpose \u2014 who you can send to, versus what is running where.","Sending now writes a Sent to row whoever sends. It was rendered only by the /peers command, so a human saw it and the model did not \u2014 the same asymmetry 0.5.59 fixed for arriving messages, in the other direction."],"0.5.59":["Inbound messages from other sessions now land as durable transcript rows on the live path: Received from, including a task waiting until idle and a held message with /peers accept, not a notice that scrolls away."],"0.5.58":["Unified agent architecture: sub-agents are full sessions, docked under the main-agent in the panel beneath the input box or detached as their own window \u2014 one engine, two presentations.","Messages between sessions are now first-class transcript rows in both directions: Sent to / Received from with the message visible, not a transient notice that scrolled away.","Wire vocabulary: the model gets four canonical tools \u2014 Send, Receive, ListAgents, ListSessions. CoordinationSend/CoordinationQuery keep working as hidden aliases.","Picks up SDK 0.10.0, which ships the canonical wire vocabulary and the alias layer."],"0.5.57":["Reliability pass from the goal-reconciliation: one shared projection now turns runtime events into assistant text (run turns and host-delegated branches used to keep separate copies, the class of bug where a tool payload renders as chat text).","Provider cockpit hardening: the host's durable conversation binding is validated before any mode or scope change, a mismatched host can no longer receive your project as a side effect, and the active provider lane is re-read every turn so a selection changed in another window takes effect immediately.","Tool start/end events are now driven by the interface contract's own vocabulary (phase, call id, success) instead of re-parsing raw type strings.","Release plumbing: the packed CLI manifest now records the publishable SDK version rather than the local build reference, and the security-boundary audit resolves file: SDK links through the installed package."],"0.5.56":["Independent sessions can now delegate to each other, the way Claude Code's SendMessage works: /rename names this session (shown on the input border), /peers lists every XENO Agent session on this machine, and /message <session> <task> hands it work that runs INSIDE that session with its own workspace and permissions; the result comes back here automatically.","The model has the same two primitives as the Interface - CoordinationQuery and CoordinationSend - so 'ask my DB - PLUGIN session to audit the auth flow' works in plain language. Delivery and completion are separate states; a task left running by a crashed session is marked recovery-required and never re-run.","Picks up SDK 0.9.39: the durable peer store behind this, a strict /rename commit (a failed disk write is a failed rename), and permission classification of the two coordination tools.","Typing a slash command that takes an argument ghosts its placeholder after the cursor, e.g. /rename [name].","Rendered artifacts, the way Claude Code's Artifact tool works: the model writes an HTML page and publishes it with the Artifact tool; the page appears as a link tray under the status bar (ctrl+] opens it) and is served from a private loopback viewer under a sandboxing CSP. Comments left on the page come back into the conversation as turns, and republishing the same artifact_id keeps the link.","Two homes, your choice: local is private to this machine and needs no account; home cloud (or /artifacts promote <id>) hosts the same revision on your XENO account at xenostudio.ai/a/<id>, private until /artifacts share <id> turns link sharing on. Hosted comments reach the session the same way local ones do."],"0.5.55":["Updated to SDK 0.9.38: app-server retries and permission responses enforce current tenant, workspace, and connection authority.","Fixed standalone startup by bundling the web-context client with the CLI.","Qualified context recovery, schemas, scheduling, subagents, skills, and app-server regression checks on Windows and Linux."],"0.5.54":["Picks up SDK 0.9.37, which corrects the root cause published in 0.9.36: the Linux install failure came from lockfile metadata, not from the dependency itself.","The 0.9.36 fix was correct and is retained; only its explanation was wrong, and a wrong cause is worse than none because the next person reasons from it.","Fixes a crash where a second CLI session in the same workspace killed the first one: listing schedules took a cross-process mutation lock, and the resulting error came from a background timer with no catch, which terminates the process."],"0.5.53":["Picks up SDK 0.9.36: a Windows-only native addon was a hard dependency, so `npm ci` failed outright on Linux - the SDK could not be installed there at all.","The addon is now optional and loaded lazily, which is what its call sites already assumed. Found by running the full suite on a real Linux filesystem rather than a mounted Windows drive."],"0.5.52":["Picks up SDK 0.9.35: a model the gateway cannot route was classified as a retryable server error, so a permanently wrong model id would be retried on a backoff loop forever.","A model that is temporarily unavailable stays retryable, so only the unroutable case changed. Found by a live provider conformance run against the XENO gateway."],"0.5.51":["Picks up SDK 0.9.34, which fixes provider error classification: a bad API key returning HTTP 400 was reported as a missing model capability rather than an authentication failure.","That told you your model lacked a feature when your key was simply wrong. Found by a live provider canary - offline tests prove what we send, never how we read what comes back."],"0.5.50":["Picks up SDK 0.9.33, which fixes a permission-rule wildcard that could span a carriage return: Bash(command:git*) matched 'git status\\rrm -rf /', so a prefix rule an operator wrote as a constraint could authorize a composed command.","On a terminal a carriage return returns the cursor to column zero, so an approval preview could display one command while the shell received a second one. A single * now stops at every line terminator and ** remains strictly broader."],"0.5.49":["Picks up SDK 0.9.32, which fixes a single-writer violation: a live session owner whose heartbeat stalled could be treated as stale and have its lock taken by a second writer.","A long tool call, a paused debugger or a saturated event loop no longer risks losing session ownership; a genuinely dead owner is still reclaimed immediately."],"0.5.48":["xeno handoff status gains --since-revision and --wait-ms: a caller passes the revision it already saw and the command returns when the session actually moves, instead of re-reading the whole session in a loop.","A wait that reaches its deadline exits 2 rather than 1, so an unchanged session reads as a retryable observation rather than a failure."],"0.5.47":["xeno sessions show gains --history and --cursor: recent transcript activity is read in a bounded window with a continuation cursor, instead of loading an entire transcript to display the last few entries.","New xeno agents wait <run-ids...> waits for the first of several background runs to reach a terminal state, or every run with --all. A deadline exits 2 rather than 1, so a caller can tell a timeout from a failure.","New xeno mcp resource-templates lists parameterized resources a connected MCP server offers; servers without template support are unaffected.","AskUser questions can now be cancelled, so an unanswered question no longer holds a turn open indefinitely (via SDK 0.9.31)."],"0.5.46":["Sessions can be branched: xeno sessions fork <id> creates a new session from an existing one without changing the original, carrying its transcript history and linking back to its parent, so both lines of work stay resumable.","Sessions can be titled, pinned and archived: xeno sessions title, pin and archive. Pinned sessions lead every listing regardless of activity, and archiving retains the transcript rather than deleting it.","xeno sessions list gains --archived, and shows titles and pin state inline."],"0.5.45":["The top-level xeno ctx-viz command now exposes the same bounded live tool inventory as the interactive TUI, with cursor paging and permission-safe metadata.","Inventory output clearly separates registered tools from request-loaded schemas and never grants execution authority."],"0.5.44":["File tools now complete reliably in standalone and packaged CLI processes, including guarded Edit and Write results after permission approval.","Durable interrupted-session recovery now preserves receipt-before-status crash ordering and requires explicit respawn for fresh input.","Worker stop, lease revocation, permission approval, workflow recovery, and goal-budget controls are qualified through the unsigned Windows candidate package.","Synced Agent SDK 0.9.28 with the awaited tool-operation liveness repair and recovery contracts."],"0.5.43":["Provider-native Codex and Claude continuations can be attached from the XENO provider cockpit without replacing the XENO TUI; exact provider session identity, workspace, and ownership survive detach, reattach, and Interface handoff.","The native terminal path mirrors user messages into the owning graphical conversation and keeps XENO application system instructions out of provider-visible chat text.","Synced XENO ACP 0.2.13 and Agent Interface 0.1.23 after the earlier immutable candidates were published without moving their npm latest tags."],"0.5.42":["Durable Web Context operations now render the canonical typed evidence progress stream in human and NDJSON modes without inventing counters.","SIGINT and external abort request exactly one service-side cancellation and report whether the durable job reached a confirmed terminal state.","Synced Web Context 0.1.1, Agent SDK 0.9.25, and Agent Interface 0.1.22 for the negotiated ACP v2 evidence contract."],"0.5.41":["Durable compaction now flushes the recoverable session snapshot before mutating resident history, so repeated long-context cycles and crash recovery retain completed turns.","Chat and non-interactive run paths bind the real host parent-session identity before delegating, keeping nested work and results attached to the correct resumable conversation.","Execution handoff preserves writer fencing and live ownership across A-to-B-to-C resume while Loop continuation remains unbounded by default.","Synced the public Agent SDK 0.9.24 and Agent Interface 0.1.21 registry packages for the qualified Goal / Loop / Handoff contract."],"0.5.40":["Added durable Goal records with explicit criteria, milestones, delegated tasks, progress, steering, and evidence-gated completion.","Added distinct scheduled, development, and goal-continuation loops that are unbounded by default, persist every iteration, survive restart, and remain recoverable after an iteration failure.","Added live, heartbeat-backed execution handoff across resumed terminals with atomic A-to-B-to-C transfer and immediate source fencing; one-shot commands cannot impersonate a live owner.","Handoff now flushes and relinquishes the source session-writer lock before printing the resume command, so the target can resume the same transcript without either terminal deleting or rewriting the other's lock state.","Synced Agent SDK 0.9.23 and Agent Interface 0.1.20 for the shared Goal / Loop / Handoff runtime contract."],"0.5.39":["Added XENO Web Context search, fetch, render, map, crawl, extract, job wait/cancel/resume, and Browser handoff commands with canonical evidence metadata.","Preserved Chat and Agent session mode/workspace identity across CLI and Interface resume paths.","Synced Agent SDK 0.9.22 and Agent Interface 0.1.19 for the typed Web Context runtime event contract."],"0.5.38":["Corrective Agent Interface handoff: explicit Chat, Agent, and resume launch intent now wins over restored persisted desktop tabs after session hydration.","`xeno agent --interface` preserves the exact granted workspace even when the desktop has existing Chat history, while `xeno chat --interface` remains Chat-only with no project grant.","Synced the Agent Interface client and contract packages to the installable 0.1.18 release."],"0.5.37":["`xeno chat --interface` opens the canonical desktop surface as XENO Chat with Chat-only authority and no project grant.","`xeno agent --interface` opens the same surface as XENO Agent and grants the exact current local workspace.","Synced the Agent Interface client and contract packages to 0.1.16."],"0.5.36":["`xeno chat` and `xeno agent` now launch the same canonical XENO terminal interface while preserving their invoked identity: Chat is branded XENO CHAT and Agent is branded XENO AGENT.","Chat mode owns a private managed workspace and cannot be promoted to Agent authority by saved settings or `--mode`; Agent mode keeps the explicit local-workspace and full-capability contract.","Windows Terminal multiline paste remains one editable composer item and submits as one persisted user message, including fragmented bracketed-paste frames.","Synced the Agent Interface client and contract packages to 0.1.15 and the Agent SDK to 0.9.21."],"0.5.35":["The provider cockpit now exposes durable provider lanes, exact native attach and detach, explicit stop and reconcile controls, and persists whether each Agent session is Chat mode or Agent mode.","The status bar shows the active provider lane, and non-interactive provider, lane, attach, and reconcile commands expose the same control plane to scripts.","The local release gate now builds the native Windows XENO PTY before integration tests and typechecks the complete test surface from a clean checkout.","Synced the Agent Interface client and contract packages to 0.1.12 and the Agent SDK to 0.9.18."],"0.5.34":["Windows multiline-paste recovery now keys off the actual win32 runtime even when terminal TTY capability probing reports an inconclusive profile.","Input diagnostics now record the runtime platform, terminal profile, and stdin/stdout TTY state so real-terminal evidence explains which paste path ran."],"0.5.33":["Windows Terminal multiline paste now remains one editable composer message even when Windows omits bracketed-paste markers because virtual-terminal input is unavailable.","Real bracketed-paste frames still retain stateful fragmented-stream handling, and an ordinary Enter remains a submit after the short paste-boundary grace period.","Synced the Agent Interface client and contract packages to 0.1.11 and the Agent SDK to 0.9.17."],"0.5.32":["Recent-session state now stays inside XENO_AGENT_HOME and uses durable per-workspace updates, preventing Windows EPERM contention and lost concurrent session entries.","PowerShell command completion now drains the final stdout pipe data before settling, so successful commands cannot intermittently return empty output."],"0.5.31":["Windows Terminal bracketed-paste mode is now explicitly negotiated for the full composer lifetime, correcting 0.5.30's incomplete decoder-only repair.","Native TUI and external-editor handoffs release terminal paste mode before transfer and restore it only after XENO regains terminal ownership.","`--interface` now waits for an exact nonce-bound acknowledgement from the desktop renderer instead of reporting success when an older app merely spawned and ignored the resume request.","Managed finite operations can continue beyond the generic three-turn safety cap, recent-session writes are serialized across processes, and background commands receive privacy-safe semantic fallback labels."],"0.5.30":["Multiline terminal pastes now remain one editable composer message even when Windows Terminal fragments the bracketed-paste frame across multiple input chunks.","Complete bracketed-paste frames are handled before generic Escape sequences, and their terminal markers never leak into the submitted prompt."],"0.5.29":["ACP provider cockpit: resume durable Codex, Claude, and compatible provider lanes without replaying the XENO transcript into a new native session.","Attach, detach, reattach, stop, and reconcile native provider TUIs with one-writer ownership between the XENO TUI, Agent Interface, and provider terminal.","`--interface` handoff now preserves the selected conversation host binding and exact provider continuation identity.","Background work uses semantic task names, and continuation checkpoints retain the original objective instead of ending a live operation at an arbitrary automatic-turn boundary.","Synced Agent Interface client/contract to 0.1.8 and @xenosystem/agent-sdk to 0.9.14."],"0.5.28":["The root `xeno --help` output now exposes `--interface` and `--resume [id]`, so terminal-to-desktop session handoff is discoverable at the exact command surface where it is used."],"0.5.27":["Open the XENO Agent Interface from the terminal with `xeno --interface`, resuming an exact session ID or the latest session in the current workspace.","Long-running background commands now stay alive while active, preserve native PowerShell syntax, and display meaningful task names.","Short follow-through messages such as do it and proceed now retain implementation authority, while nested continuations preserve the original objective.","Synced @xenosystem/agent-sdk to 0.9.13."],"0.5.26":["Terminal bracketed paste & multi-line input: bracketed paste frames are cleanly decoded, collapsed into `[Pasted text #N +N lines]` tokens for large blocks, and submitted with full uncorrupted text without escape code dropouts.","Dynamic terminal reflow: turn receipts, turn dividers, and prompt bubbles adapt smoothly to window resize events without clipping."],"0.5.25":["Interactive `/status`, `/config`, `/usage`, `/stats`, `/settings` multi-tab modal with live search, keyboard cycling, and instant ~/.xeno/config.json persistence.","Live 52-week session activity heatmap, longest/current streak metrics, active days summary, lifetime token metrics, and favorite model analytics.","Real-time git workspace analytics including active branch, ahead/behind counts, working tree diff additions/deletions, and live turn API elapsed times.","Turn receipt visual polish with right-margin padding and formatted recap indentation.","Interactive `/handoff` command: switch seamlessly between specialist agents with prompt context and intent transfer.","Zero-config `.claude/agents/*.md` & `.xeno/agents/*.md` discovery with level-ordered priority shadowing.","Host mid-turn steering (`turn.steer`) and subagent wire payload artifacts integration.","Synced @xenosystem/agent-sdk to 0.9.12 with enhanced offline grace monetization validation.","xeno-rt: resolved Qwen 3.8 / 3.5 MTP NextN architecture prefixes and prevented layer 32 recurrent tensor probe failure."],"0.5.24":["Published with exact matching CLI_VERSION literal, guarded by verify:version in CI.","Synced @xenosystem/agent-sdk to 0.9.11, pulling model-aware context budgets from live gateway `/v1/models` catalog.","`/import` now immediately triggers context reconstruction turns rather than pausing at the input prompt."],"0.5.23":["Model-aware context budget: queries gateway `/v1/models` catalog for authoritative `context_window` limits.","Context compaction request byte budget scaled to prevent false refusals on large toolsets."],"0.5.22":["`/context` divided by a hardcoded 200,000 regardless of which model you are on. That figure is XENO's window and nobody else's: on a 128,000-token OpenAI model the gauge read about 12% where the truth was 19%, and near the limit it said \"Context is healthy\" with compaction imminent; on Google's 1,000,000-token window it pegged at 100% from a fifth of the way in and warned permanently. It now divides by the budget the SDK actually resolved for the run.","The gauge also says how well it knows that number. A configured budget is exact and prints a plain percentage; a provider profile is one window for every model that provider serves, so it prints `~62%` and labels itself approximate. Before any turn has reported, it says the 200,000 is an assumption rather than presenting it as fact.","The numerator was always right and is unchanged: it sums the messages currently in context, so it falls when a compaction drops them. Only the denominator was asserted rather than resolved."],"0.5.21":["Security: undici 6.27.0 -> 6.28.0, closing a cookie-injection advisory. This repo had 12 open alerts and this was the ONLY one that reaches shipped code \u2014 the five rated HIGH are all build and test tooling. Fixing by severity rank would have addressed the wrong thing first.","Worktree cleanup could delete THROUGH a junction. That is the failure that destroyed two repositories on 2026-08-03: on Windows a recursive delete follows a junction and removes the target, and npm creates one for every file: dependency. Cleanup now clears the reparse point itself and never the thing it points at.","Worktree cleanup had also decayed into a no-op \u2014 its filter excluded every orphan it existed to remove, so it ran, reported success, and cleaned nothing. And a reparse-point scan that hits its cap now REFUSES rather than returning a short list, because a truncated scan that looks complete is how the delete above becomes safe-looking.","The control-plane `list()` was not a read: it wrote once per stale record, every time anything listed runs. Listing is now free of side effects.","`/import` brings a session from another agent CLI into XENO and continues it \u2014 including agy stores, where the obvious store turned out not to be the best source. `--imported` shows what is on disk and says plainly that it persists. The source transcript is never touched, and that is enforced rather than intended.","Delegated branches now run on the Agent host under XENO_AGENT_ATTACH, report tool progress while they work, and the CLI reads the HOST's audit rather than only its own. Previously a host-routed branch was silent until it finished, and a refusal blamed a missing stream that in fact existed.","`xeno host status` now reports WHICH lanes the host offers and why a blocked one is blocked \u2014 including whose environment the blockage is about, which was the part that made the old message useless.","Pinned to @xenosystem/agent-sdk 0.9.10. The pin had been two releases stale, so work that shipped in 0.9.9 reached nobody. 0.9.10 also reports how full an agent's context is: turn.completed carries the RESIDENT token count, not the cumulative billing counter, and context.pressure arrives after every model response. The obvious field re-adds the whole prompt each turn \u2014 measured live, three one-word turns reported 3049, 6106 then 9171 tokens while the context grew by about eight.","Budget accounting no longer reads the entire run store when no budget cap is configured."],"0.5.20":["Pinned to @xenosystem/agent-sdk 0.9.8. The SDK's ownership policy still labelled this CLI by a scope retired in 8363d30c, which had failed the release smoke on every run since 2026-08-13 \u2014 the mismatch was never in this repo, so the fix was a repin rather than a workaround.","The release smoke now derives how strict it should be from the release trust policy: while no signing identity is approved it holds the engineering bar, and it tightens by itself the moment one lands. It previously demanded a signature no ordinary CI run could produce, and had failed for long enough to read as background noise.","First test coverage of the native manifest signing path, which had never executed once. Signer and verifier each carry their own copy of the canonical-JSON serializer and cannot import each other, so a drift as small as key ordering would have invalidated every release signature \u2014 and would have surfaced on release day, looking like a key problem.","Windows: temporary-directory cleanup no longer loses a race with exiting child processes, and the certification matrix checks out correctly on Windows ARM. `force: true` suppresses ENOENT, not EPERM, so the previous cleanup looked defensive and was not.","Groundwork for interactive Ctrl+C on Windows: the native addon can now raise a real console interrupt. Writing 0x03 into a ConPTY does not raise a signal, which is why Ctrl+C has never worked there. NOT yet wired \u2014 the console attach succeeds and the event is raised, and a ConPTY client still does not observe it."],"0.5.19":["The CLI did nothing at all on Linux and macOS. Its entry point did not resolve symlinks, so every npx and global install ran the wrong path and exited silently \u2014 the install looked successful and the binary did nothing. Fixed.","Agent permission decisions now reach an actual human on both rails, rather than being resolved without one.","A remote run that is read-only now says so, instead of failing silently and leaving you to work out why nothing changed.","The version the binary REPORTS is now bound to the version npm publishes, and a test enforces it. They had drifted: 0.5.18 was published as a package whose `--version` said 0.5.17.","\u26A0\uFE0F 0.5.18 exists on npm and was published from a branch that was never merged. It is superseded by this release, which is cut from `main`. If you installed 0.5.18, upgrade."],"0.5.17":["The CLI now ships as @xenosystem/agent-cli. The former name @xeno-corporation/xeno-agent-cli is deprecated on npm and receives no further releases; the `xeno`, `xeno-agent` and `xeno-code` binaries are unchanged, so nothing in your shell or scripts has to change.","The exact SDK pin moves with it: the CLI is bound to @xenosystem/agent-sdk 0.8.12. 0.8.11 was never published under either name and cannot be \u2014 GitLab evaluates .gitlab-ci.yml as it exists at the tag, and tag sdk-v0.8.11 predates that pipeline.","This release cannot be installed until @xenosystem/agent-sdk 0.8.12 is live on the registry; the release pipeline fails closed on --require-dependencies-published until it is."],"0.5.16":["Windows 11 ARM64 containment certification now performs architecture-neutral MXC host preparation with the reviewed x64 helper through operating-system emulation while keeping the contained runtime native ARM64.","The CLI is bound exactly to SDK 0.8.11, whose host-preparation reports distinguish the host architecture from the reviewed setup-helper architecture and retain timeout diagnostics."],"0.5.15":["macOS and Linux standalone diagnostics now report their verified POSIX process-group lifecycle independently from the stronger process-hardened sandbox level, preserving truthful security status while certifying full-tree cancellation, timeout, and shutdown behavior.","Generated Harbor benchmark and audit workspaces are excluded from source control, keeping Windows ARM64 checkouts below platform path limits and removing 9,938 generated artifacts from release candidates."],"0.5.14":["Windows 11 24H2 containment admission now uses the authoritative non-server NT client build floor instead of rejecting current Azure and GitHub Windows 11 images whose legacy registry ProductName still says Windows 10.","Windows Server remains fail-closed, pre-26100 clients remain ineligible, and both x64 and ARM64 host identities have regression coverage."],"0.5.13":["Hosted Windows x64 containment certification now fails closed unless the runner is Windows 11 24H2 or newer, the platform supported by Microsoft MXC, instead of treating Windows Server runner failures as product failures.","The certification matrix accepts a protected XENO_WINDOWS_X64_RUNNER label for an ephemeral Windows 11 x64 runner while keeping all other hosted platform rows unchanged.","Containment failure reports preserve bounded head-and-tail diagnostics through SDK 0.8.10 so the actionable trailing Win32 or MXC error is retained."],"0.5.12":["Windows MXC containment now launches its unrestricted host from the prepared system-drive temporary directory, outside directories whose DACLs are mutated by the contained policy, and certification captures official redacted MXC diagnostics.","Internal background session workers no longer start a competing global reconciler, preventing slower macOS hosts from quarantining a healthy turn between transcript append and checkpoint commit.","The interactive attach/input/stop smoke now follows the actual persisted inbox sequence and records worker logs on failure; the CLI is bound exactly to SDK 0.8.9."],"0.5.11":["Windows x64 containment certification now launches the MXC host and contained runtime with working-directory and temporary paths on the prepared system drive, matching split-drive GitHub runners.","The CLI is bound exactly to SDK 0.8.8, preserving the passing Linux, macOS, and Windows ARM64 conformance behavior while repairing Windows x64 ProcessContainer startup."],"0.5.10":["Linux containment certification now keeps disposable fixtures under the OS-private temporary mount instead of GitHub's workspace-projected runner directory, preserving the unlisted-filesystem boundary probe.","Windows certification retains the MXC-prepared system-drive fixture root required by hosted runners whose workspace and default temp directory use another volume."],"0.5.9":["Windows containment certification now creates its disposable fixtures on the MXC-prepared system drive, including hosted runners whose workspace and default temp directory live on another volume.","Standalone Windows certification now performs the same explicit host preparation and temporary-root binding as the native package matrix."],"0.5.8":["Native containment certification now compiles its macOS UI-policy probe against the stable libsystem_sandbox ABI without depending on private SDK headers.","Windows certification now distinguishes MXC's persistent per-policy DACL requirement from its explicit one-time host-preparation warnings."],"0.5.7":["The immutable CLI candidate now binds SDK 0.8.5 to the exact canonical Linux npm tarball bytes used by certification."],"0.5.6":["Windows containment certification now performs Microsoft MXC's explicit idempotent host preparation before AppContainer+DACL conformance.","macOS ARM64 certification now records behavioral Seatbelt evidence for pasteboard, WindowServer, LaunchServices, and HID isolation."],"0.5.5":["Native certification now resolves the SDK candidate artifact from the same workspace path on Bash and PowerShell runners.","SDK containment assets retain executable package modes on Linux and macOS, with a source regression check for every reviewed Unix binary."],"0.5.4":["Native engineering certification jobs now download the exact SDK tarball produced by the successful parent gate before installing dependencies.","The six-platform matrix remains source-bound to one immutable CLI tag and one immutable SDK candidate artifact."],"0.5.3":["Candidate packaging accepts both npm 11 array-form and npm 12 package-keyed JSON, with explicit diagnostics for malformed output.","Hosted SDK packaging now parses a bounded JSON file instead of relying on a large shell variable or an obsolete npm output shape."],"0.5.2":["Hosted certification now caps SDK declaration generation at two concurrent entry points and cleans declaration output in isolated bounded-memory workers.","SDK build subprocess failures now report their terminating signal or exit status instead of producing a silent hosted-run failure."],"0.5.1":["Hosted certification now builds the exact SDK candidate in bounded declaration groups, preventing parallel TypeScript declaration generation from exhausting GitHub-hosted runner resources.","Post-freeze readiness now distinguishes exact candidate tags verified at the candidate commit from collisions in release, registry, feed, and service namespaces."],"0.5.0":["Agent Profiles now provide enforceable Assistant, SWE, Reviewer, Writer, Research, Product, CI, DevOps, and Legal Research identities with bounded tools, permissions, skills, hooks, memory, isolation, and external-action authority.","The XENO Artifact Protocol adds durable plans, patches, diffs, reviews, screenshots, recordings, reports, provenance, approvals, and evidence relationships shared across local, hosted, and Hub workflows.","Secure Execution Contracts and capability leases now make filesystem, network, secret, process, device, browser, and external-action authority explicit and auditable.","Skills v2 adds standards-compatible SKILL.md discovery, progressive loading, bundled resources, invocation policy, version identity, and compatibility with XENO, .agents, and Claude skill locations.","MCP now supports current Streamable HTTP sessions and OAuth discovery while retaining compatible stdio and legacy SSE connections.","Browser, computer-use, hosted-agent, semantic-index, production-review, spec-planning, secure-sharing, and provider-onboarding surfaces are integrated through the shared platform contracts.","The retained TUI now presents stable grouped tool activity, live task and subagent status, candidate-bound edit previews, context-pressure and compaction state, and clearer turn completion receipts.","Six-product candidate certification now binds the SDK, XENO Use, XENO Browser, Agents API, CLI, and Hub to exact source identities, versions, tags, evidence, and protected release gates."],"0.4.45":["This transitional release is engineering-tested but not GA-certified: native PTY artifacts are unsigned and remain disabled by default until the Azure signing identity is approved; ordinary CLI and pipe-mode commands remain available.","App Server v2 now provides durable threads and turns, typed clients, permission ownership and expiry, bounded replay and backpressure, authenticated HTTP access, and additive v1 compatibility.","The terminal renderer now uses committed retained frames, bounded coalescing, one normal write per frame, a responsive 50-agent footer, accessibility modes, and a native terminal compatibility matrix.","Release certification now fails closed on six native architectures, platform and manifest signatures, reproducible package payloads, SBOMs, provenance attestations, independent approvals, npm OIDC publication, and public clean-install verification.","Long chat prompts now soft-wrap into a growing six-row composer with Unicode-safe editing, visual Up/Down navigation, file-panel parity, and a temporary XENO_INPUT_SOFT_WRAP=0 rollback switch.","Long-running model-authored shell commands now use managed operations: Ctrl+B promotes the same process, finite background work waits without model polling, and durable continuations resume exactly once after terminal output arrives.","ReadImage now uses Xeno's dependency-free owned raster codec for bounded PNG, BMP, Netpbm, and core-SVG previews; /processes and doctor expose task control, process-tree containment, operation-schema, and codec status.","Dynamic workflows now expose first-class run limits and terminal reducer summaries in run records and inspect JSON.","Background agent sessions now deliver durable completion, failure, stop, and request-keyed needs-input notifications to interactive parent chats and bounded headless runs without clobbering prompt drafts.","Workflow orchestration includes grouped phase/child progress, parent-chat completion notifications, WorkflowWait, /workflows drill-down, watch JSONL snapshots, and ultracode workflow prompts.","Workflow starts now support plan preview and exact-definition approval memory, scheduler ticks are serialized, and workflow lifecycle metrics are available through the OTel usage export.","Tool activity now uses semantic Update and Search labels, contextual line-numbered edit previews, expandable read/search/shell output, and accurate failure rendering.","Interactive chat now blocks repeated inspections and unrequested mutations on short questions, gives explicit research a larger typo-tolerant evidence budget, and reserves a tool-free final-answer turn when work limits are reached."],"0.4.44":["Markdown source links now render as clickable terminal links in supported terminals, with visible URLs preserved when links are disabled."],"0.4.43":["New background agents now appear in the footer immediately after launch, and the footer can show up to eight agent sessions."],"0.4.42":["Background agent footer rows now fit the common three-agent fanout without hiding the first agent on compact terminals.","Completed background agent sessions now close after BackgroundAgentJoin returns their result to the main agent."],"0.4.41":["Completed background agent footer rows now keep a fixed runtime instead of continuing to count upward."],"0.4.40":["One-shot background agent sessions now mark done after returning their result, while user-follow-up sessions stay idle for continued chat."],"0.4.39":["Background agent session activity now uses concise status labels like Thinking instead of showing the full task prompt."],"0.4.38":["Opened background agent sessions now show their own session activity line while keeping main-agent tool progress isolated."],"0.4.37":["Opened background agent sessions no longer show the main agent's active tool progress line."],"0.4.36":["Opened background agent sessions now render the same main-chat transcript surface for user messages, assistant messages, tool calls, and tool results."],"0.4.35":["Background agent session chat now includes tool calls and tool results in its visible history."],"0.4.34":["Opening a footer background agent now switches the main chat surface into that agent session instead of showing a separate info panel.","Child-session input now queues messages to that agent while Esc returns to the main chat."],"0.4.33":["Background agent footer rows now repaint immediately during active turns.","Remembered background-agent approvals now apply to later background-agent launches."],"0.4.32":["Startup release-note hints now sit directly under the note text and render dimmed in the side panel."],"0.4.31":["Unread release notes now render beside the startup XENO AGENT header on wide terminals."],"0.4.30":["BackgroundAgentList now only reports current-chat footer sessions so old workspace agents do not hide missing new deployments."],"0.4.29":["Background agent footer markers now use filled and empty squares.","Opening a background agent from the footer now shows its session chat with transcript and message input."],"0.4.28":["First-run default model is now gpt-5.5 while saved user model choices are preserved.","Number keys in the model picker now type into search instead of selecting by index.","Model selections made with /model now persist as the user's saved default."],"0.4.27":["Background agent footer rows are now scoped to the current chat session."],"0.4.26":["Background agent rows now sit below the status line and inherit the live chat model."],"0.4.25":["Legacy BackgroundAgent calls now create footer-visible interactive background sessions."],"0.4.24":["Model picker support now has a `xeno models --json` command, share export proof, and GitHub review artifact contracts."],"0.4.23":["Model picker and /model listings now refresh Xeno API model availability before switching."],"0.4.22":["Hook review now shows command-hook hashes and supports trust, disable, and explain commands.","Expanded lifecycle hooks now cover permission decisions, stop failures, and delegated subagent start/stop events.","Set XENO_STATUS_LINE_COMMAND to replace the TUI status line with a cached command output.","Rewind now saves the abandoned conversation branch as a manual checkpoint before restoring.","Interactive chat now supports Ctrl+R history search, Ctrl+G prompt editing, /vim input mode, and /copy answer/block/diff clipboard copy.","/theme is now a discoverable alias for /color with user/project custom theme files, and /processes stop-all stops running background tasks."],"0.4.20":["Shell completions now include the current control-plane commands, flags, statuses, scopes, and usage groups.","The local app-server browser page now includes prompt and process controls on top of advanced JSON-RPC.","Published CLI and SDK packages now include GitHub repository metadata.","Docs now call out the temporary GitHub Actions startup_failure blocker while local gates remain authoritative."],"0.1.0":["Persistent shell sessions now preserve cwd and shell state across Bash calls.","Delegated planner, explorer, executor, and reviewer branches now support staged and parallel policies.","MCP now supports stdio and SSE transports, prompt discovery, resource reads, and live tool sync.","Notebook, ask-user, and memory tools are available in the shared agent runtime.","CLI operator workflows now include doctor, bug-report, config editing, cost summaries, and runtime inspection."]};function m9e(e=Pe){return yvi[e]??[]}function bvi(e=Pe){let t=_t().lastReleaseNotesSeen;return m9e(e).length>0&&t!==e}function mU(e=Pe){Ao({lastReleaseNotesSeen:e})}function Fye(e){let t=e??Pe,r=m9e(t);return r.length===0?`No release notes available for version ${t}.`:[`Release notes for version ${t}`,"",...r.map(n=>`- ${n}`)].join(`
|
|
6648
6648
|
`)}var vvi=4;function ofr(e=Pe){if(!bvi(e))return;let t=m9e(e),r=t.slice(0,vvi),n=t.length-r.length;return[`What's new in XENO AGENT v${e}`,...r.map(i=>`- ${i}`),n>0?`...and ${n} more. Run \`xeno release-notes\` to see everything.`:"Run `xeno release-notes` to view this again."].join(`
|
|
6649
6649
|
`)}tr();Lh();iu();lz();import{spawn as kvi}from"node:child_process";import{setTimeout as A9e}from"node:timers/promises";import{resolve as jye}from"node:path";il();$a();var afr="cancel",bf={name:"WorkflowCancel",command:`workflows ${afr}`,nativeVerb:afr,description:"Request cancellation of a local workflow and stop its child work. Acceptance is not confirmed termination. Inspect or wait on the same workflow while cancellation is pending; do not start replacement work until cancellation is confirmed.",argument:{name:"run_id",type:"string",required:!0,description:"Explicit workflow run ID; never inferred from the selected UI row."},mode:"always",requiresDisplay:!1,reversibility:"irreversible",parity:"exposed",readingTools:["WorkflowInspect","WorkflowWait"],readingCommand:"workflows inspect <run-id> --json",replyFields:{accepted:"True only after the durable cancellation request was read back. False means no workflow target was found.",cancelled:"True only when readback confirms cancellation and no child termination remains pending. False means cancellation is not confirmed, not that work is still running.",pending:"True when the request was accepted but termination or readback remains incomplete. Re-read the same workflow; this is not a new request.",operationId:"Stable cancellation operation ID, or null when no request was accepted. Repeated cancellation requests retain this ID.",run:"Observed cancellation snapshot (workflowRunId, workflowName, status, updatedAt, cancellation), or null if absent/unconfirmed. The native CLI retains its existing full run record; use WorkflowInspect for child details.",warning:"Present when accepted cancellation could not be confirmed or processed. It never grants permission to restart work."},cancellationFields:{schemaVersion:"Cancellation metadata schema version, currently 1.",operationId:"The same durable cancellation operation ID as the top-level reply.",workflowRunId:"Exact workflow targeted by this request.",requestedAt:"UTC timestamp of the durably published request.",pendingChildCount:"Children whose termination remains unconfirmed; absent before the first reconciliation pass.",lastError:"Optional bounded diagnostic about an unconfirmed child; absence does not independently prove completion.",completedAt:"Present only after child termination is confirmed.",notificationEnqueuedAt:"Present after the workflow-cancelled notification was persisted; it does not mean the parent consumed it."}};function gU(e,t){let r=e.run?.workflowName??t;return e.accepted?e.cancelled?`Cancelled ${r}`:`Cancellation pending for ${r}; inspect operation ${e.operationId}`:`Workflow run not found: ${t}`}function lfr(e){let t=e.run;return{...e,run:t?{workflowRunId:t.workflowRunId,workflowName:t.workflowName,status:t.status,updatedAt:t.updatedAt,cancellation:t.cancellation}:null}}var cfr=()=>[bf.description,`Mode: ${bf.mode}; requiresDisplay: ${bf.requiresDisplay}; reversibility: ${bf.reversibility}. Read back with ${bf.readingTools.join(" or ")}.`,"Returns JSON: "+Object.entries(bf.replyFields).map(([e,t])=>`${e}: ${t}`).join(" "),"Cancellation progress: "+Object.entries(bf.cancellationFields).map(([e,t])=>`${e}: ${t}`).join(" ")].join(" ");sF();var Qye=class extends Error{constructor(r,n){super(r);this.code=n;this.name="WorkflowHostRefusal"}code};function Uye(e){throw new Qye(e.error??"The Agent host refused the workflow change.",e.code)}function AU(e){return e.success?e.run??null:e.code==="NOT_FOUND"?null:Uye(e)}function Ivi(e){let t=new Set,r=async i=>{if(t.has(i))return;let o=await p_(e,[i]);if(o.granted.length===0&&o.failed.length>0)throw new Qye(`The Agent host did not accept this folder: ${o.failed[0].error}`,"FOLDER_NOT_GRANTED");t.add(i)},n=(i,o)=>e.requestWorkflows(i,o);return{async create(i,o){await r(i);let s=await n("workflows.create",{cwd:i,description:o});return!s.success||!s.definition?Uye(s):s.definition},async start(i,o,s,a){await r(i);let l=await n("workflows.start",{cwd:i,ref:o,input:s,...a.model?{model:a.model}:{},...a.sizeGuideline?{sizeGuideline:a.sizeGuideline}:{}});return!l.success||!l.run?Uye(l):l.run},pause:async i=>AU(await n("workflows.pause",{workflowRunId:i})),resume:async i=>AU(await n("workflows.resume",{workflowRunId:i})),async cancel(i){let o=await n("workflows.cancel",{workflowRunId:i});if(!o.success&&o.code==="NOT_FOUND")return{accepted:!1,cancelled:!1,pending:!1,operationId:null,run:null};let s=AU(o),a=s?.cancellation?.operationId??null,l=s?.status==="cancelled"&&s.cancellation?.pendingChildCount===0&&!!s.cancellation?.completedAt;return{accepted:!0,cancelled:l,pending:!l,operationId:a,run:s,...a?{}:{warning:"Cancellation was accepted but current state could not be confirmed. Inspect this operation; do not submit new work."}}},retryChild:async(i,o)=>AU(await n("workflows.retryChild",{workflowRunId:i,childRunId:o})),skipChild:async(i,o)=>AU(await n("workflows.skipChild",{workflowRunId:i,childRunId:o})),async rerun(i,o){return await r(o),AU(await n("workflows.rerun",{workflowRunId:i,cwd:o}))},async save(i,o){o.destination==="project"&&await r(o.cwd);let s=await n("workflows.save",{workflowRunId:i,cwd:o.cwd,destination:o.destination,...o.name?{name:o.name}:{}});return s.success?s.definition??null:s.code==="NOT_FOUND"?null:Uye(s)}}}function Evi(){return process.env.XENO_TEST_HOOKS==="1"&&process.env.XENO_TEST_WORKFLOWS==="store"}async function Gye(e,t){if(Evi())return t(e.local());let{withHostClient:r}=await Promise.resolve().then(()=>(lF(),aF));return r({clientVersion:e.clientVersion,what:"Workflows"},async n=>t(Ivi(n)))}bo();function tp(e){process.stdout.write(JSON.stringify(e,null,2)+`
|
|
6650
6650
|
`)}function Svi(e,t){if(t){tp(e);return}if(e.ok&&e.definition){process.stdout.write(`Workflow valid: ${e.definition.name}
|