@xenosystem/agent-cli 0.5.167 → 0.5.168

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -3208,7 +3208,7 @@ ${Fe}${X.compose(Cpe(),X.bold)("\u2717")} ${bG(e)}
3208
3208
  `)}function pD(){return`
3209
3209
  ${Fe}${Me("Goodbye.")}
3210
3210
  `}var _jn,wQt,Cpe,gr,Me,dD,bG,yQt,vS,Pjn,Ojn,Mjn,G,Fe,EQt,u8e,M,Tpe,bQt,h8e,IQt,IG,Sa=ye(()=>{"use strict";dd();st();Hd();eQt();Ipe();d8e();_jn=new LA(process.stdout),wQt=new LA(process.stderr),Cpe=()=>Gs(),gr=e=>Cpe()(e),Me=X.dim,dD=X.bold,bG=e=>Cpe()(e),yQt="\u25A0",vS="\u2514",Pjn={open:"\x1B[4m",close:"\x1B[24m"};Ojn={Read:e=>Dm()(e),ReadImage:e=>Dm()(e),Glob:e=>Dm()(e),Grep:e=>Dm()(e),ElfAnalyze:e=>Dm()(e),MemoryRead:e=>Dm()(e),Write:e=>WR()(e),Edit:e=>WR()(e),MemoryWrite:e=>WR()(e),Bash:e=>t8e()(e),GitStatus:e=>Dm()(e),GitDiff:e=>Dm()(e),GitLog:e=>Dm()(e),GitBranch:e=>Dm()(e),GitCommit:e=>t8e()(e),WebSearch:e=>X.cyan(e),WebFetch:e=>X.cyan(e),TaskOutput:e=>Dm()(e),TaskInput:e=>X.cyan(e),TaskStop:e=>ef()(e)};Mjn={Edit:"Update",Glob:"Search",Grep:"Search",WebSearch:"Web Search",WebFetch:"Web Fetch"};G={accent:gr,purple:bG,cyan:bG,dim:Me,bold:dD,red:bG,green:bG},Fe=" ",EQt=1e3,u8e=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"};Tpe=30;bQt=3;h8e=class{atLineStart=!0;writeFn;constructor(t){this.writeFn=t??(r=>{_jn.writeOrdered(r,"stream")})}write(t){let r="";for(let n of t)this.atLineStart&&(r+=Fe,this.atLineStart=!1),r+=n,n===`
3211
- `&&(this.atLineStart=!0);this.writeFn(r)}reset(){this.atLineStart=!0}markLineStarted(){this.atLineStart=!1}},IQt=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],IG=class{interval=null;frameIndex=0;lastLength=0;writeFn;clearFn;constructor(t,r){this.writeFn=t??(n=>{wQt.writeFrame(n,"spinner")}),this.clearFn=r??(()=>{wQt.writeFrame(`\r${" ".repeat(this.lastLength)}\r`,"spinner")})}start(t){this.stop(),this.frameIndex=0,this.interval=setInterval(()=>{let r=IQt[this.frameIndex%IQt.length],n=`${gr(r)} ${Me(t)}`;this.writeFn(`\r${" ".repeat(this.lastLength)}\r${n}`),this.lastLength=t.length+4,this.frameIndex++},80)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null,this.clearFn(),this.lastLength=0)}}});import{randomInt as Zjn}from"node:crypto";function e4n(e){return typeof e=="string"&&xa.some(t=>t.id===e)}function y8e(){let e=mw().uiMascot;return e4n(e)?e:null}function kh(){return y8e()??t4n}function kG(e){go({uiMascot:e})}function fD(){let e=mw().uiColor;return typeof e=="string"&&Bm(e)?e8e(e):e8e()}function PQt(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 r4n(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,w,y,A,b=0,I=.6)=>n?[Rn(g-y,w+.4,g,w-A*.55,I,"K"),Rn(g,w-A*.55,g+y,w+.4,I,"K")]:d?[Rn(g-y,w+A*.35,g+y,w+A*.35,I,"K")]:[dr(g+l*.5,w,y,A,"K",b),dr(g-y*.3+l*.7,w-A*.4,Math.max(.6,y*.36),Math.max(.6,y*.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(dr(12,28,3.2,1.9,"O"),dr(20,28,3.2,1.9,"O"),Rn(8.5,19,5.6,22.5,1.7,"B")),h.push(n?Rn(23.5,18,23.5+5*Math.cos(u),18+5*Math.sin(u),1.7,"B"):Rn(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(Rn(17,10,18.2,5.2,.9,"B"),Rn(18.2,5.2,20.2,3.6,.9,"B"),dr(21.2,3.4+g,1.9,1.9,"O")),h.push(dr(16,18.5-a*.3,9+s,9.8+a*.4-s,"B"),dr(16,22.2,5.2,4.2,"C"),dr(10.2,19.6,1.3,.9,"O"),dr(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?dr(16,19.9,1.4,1.1,"K"):Rn(15,19.6,17,19.6,.45,"K"))}if(e==="ocu"){let g=[Rn(10.5,9.5,8.5,5.5,1.3,"O"),Rn(8.5,5.5,10.5,3.2,1.1,"O")];h.push(...g,...g.map(f),dr(11.5,27.5,3,1.8,"B"),dr(20.5,27.5,3,1.8,"B"),Rn(7,18,4.5,21.5,1.6,"B")),h.push(n?Rn(25,17,25+4.5*Math.cos(u),17+4.5*Math.sin(u),1.6,"B"):Rn(25,18,27.5,21.5,1.6,"B")),h.push(dr(16,17.5-a*.3,10+s,10+a*.4-s,"B")),n?h.push(Rn(11.5,17,16,13.5,.75,"K"),Rn(16,13.5,20.5,17,.75,"K")):d?h.push(Rn(11.5,16.8,20.5,16.8,.75,"K")):h.push(dr(16,16,4.8,4.3,"C"),dr(16+l*1.4,16.4,2.8,2.8,"O"),dr(16+l*1.6,16.4,1.3,1.3,"K"),dr(15+l*1.4,15,.8,.8,"W")),h.push(n?dr(16,23,1.8,1.2,"K"):Rn(14.5,23,17.5,23,.5,"K"))}if(e==="squee"){for(let g=0;g<4;g++){let w=9.8+g*4.13,y=g<2?-1:1;if(n&&g===3){let b=w+6*Math.cos(u),I=19+6*Math.sin(u);h.push(Rn(w,19,b,I,1.6,"B"),dr(b,I,1.5,1.5,"O"));continue}let A=Math.sin(r*1.4+g*1.1)*1.3;h.push(Rn(w,19,w+A,25,1.6,"B"),Rn(w+A,25,w+A+y*2.2,26.8,1.3,"O"))}h.push(dr(16,18.5,8.6,2.6,"B"),dr(16,12.5-a*.3,9.2+s,8.6+a*.4,"B"),dr(11.5,8.2,1.1,1,"S"),dr(20.5,7.5,1.4,1.2,"S"),dr(16,5.8,.9,.8,"S")),h.push(dr(10.4,16.4,1.2,.8,"O"),dr(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?dr(16,17.2,1.2,.9,"K"):Rn(15.2,17,16.8,17,.45,"K"))}if(e==="greeb"){let g=[Rn(12.5,5.5,10.5,2.4,.8,"B"),dr(10,2,1.5,1.5,"O")];h.push(...g,...g.map(f),dr(13.5,29,2.2,1.4,"B"),dr(18.5,29,2.2,1.4,"B"),Rn(12,23,9.5,26,1.1,"B")),h.push(n?Rn(20,22.5,20+4*Math.cos(u),22.5+4*Math.sin(u),1.1,"B"):Rn(20,23,22.5,26,1.1,"B")),h.push(dr(16,24.5,4.6,4.2,"B"),dr(16,16.5,5.6,4.4,"B"),dr(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?dr(16,18.4,1,.8,"K"):Rn(15.4,18.4,16.6,18.4,.4,"K"))}if(e==="quad"){let g=A=>A<.5?4*A*A*A:1-Math.pow(-2*A+2,3)/2,w=(n?90*(Math.floor(r/.8)+g(Math.min(1,r%.8/.5))):5*Math.sin(r*1.2))*Math.PI/180,y=(A,b,I)=>{let v=A-16,k=b-16.5;return[16+v*Math.cos(I)-k*Math.sin(I),16.5+v*Math.sin(I)+k*Math.cos(I)]};for(let A=0;A<4;A++){let b=w+A*Math.PI/2,I=y(10.5,11,b),v=y(6.6,7.1,b),k=y(6.6,10.2,b);h.push(Rn(I[0],I[1],v[0],v[1],1.7,"B"),Rn(v[0],v[1],k[0],k[1],1.5,"B"),dr(k[0],k[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"},dr(11.4,19.2,1.2,.8,"O"),dr(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?dr(16,19.6,1.2,.9,"K"):Rn(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(dr(16,21.2,6,1.5,"S"),dr(16,18.3,14,3.6,"G"),dr(16,16.7,11,1.6,"B"));let g=Math.floor(r*3)%5;[6,11,16,21,26].forEach((w,y)=>h.push(dr(w,19.3,1,.8,y===g?"O":"K"))),h.push(dr(16,11.5,6.6,6.2,"Q"),Rn(16,9,17.6,6.8,.6,"O"),dr(18,6.4,.9,.9,"O"),dr(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),Rn(11.6,9.4,12.6,7.4,.55,"W")),n&&h.push(Rn(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 n4n(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 _Qt(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 A8e(e,t,r,n,i=16){let o=r4n(e,t,r),s=32/i,a=[_Qt(n,1.3),n,_Qt(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=n4n(h,(u+.5)*s,(c+.5)*s);if(!m)continue;let g=h.m==="O"?a:i4n[h.m],w=-(m[0]*.6+m[1]*.8);p=g.length===1?g[0]:g[w>.42?0:w<-.38?2:1];break}d.push(p)}l.push(d)}return l}function Mpe(e,t,r,n,i={}){let o=i.size??16,s=i.color??!0,a=A8e(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?X.hex(p)("\u2588"):X.compose(X.hex(p),X.bgHex(f))("\u2580"):d+=p?X.hex(p)("\u2580"):X.hex(f)("\u2584"):d+=p&&f?"\u2588":p?"\u2580":"\u2584"}l.push(d)}return l}var xa,t4n,dr,Rn,i4n,JR=ye(()=>{"use strict";dd();Uo();Hd();xa=[{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."}];t4n=xa[Zjn(xa.length)].id;dr=(e,t,r,n,i,o=0)=>({k:"e",cx:e,cy:t,rx:r,ry:n,m:i,rot:o}),Rn=(e,t,r,n,i,o)=>({k:"l",x1:e,y1:t,x2:r,y2:n,r:i,m:o});i4n={B:["#FAF9F4","#E4E3DC","#B4B3AA"],C:["#FFFFFF","#F6F5F0","#DAD9D1"],G:["#D2D1CA","#A3A29B","#6F6E68"],Q:["#4A4A48","#2E2E2D","#1E1E1D"],K:["#0B0B0B"],W:["#FFFFFF"],S:["#B4B3AA"]}});var Pe,Ao=ye(()=>{"use strict";Pe="0.5.167"});import{createHash as q3n,randomUUID as Vpe}from"node:crypto";import*as ci from"node:fs/promises";import*as kS from"node:os";import*as Fm from"node:path";import{homedir as OHt,platform as Q3n,release as H3n}from"node:os";import{resolve as EHt}from"node:path";import{randomUUID as eqn}from"node:crypto";import{hostname as tqn}from"node:os";import{randomUUID as rqn}from"node:crypto";import{constants as PHt}from"node:fs";import{lstat as Kpe,mkdir as $Ht,open as X8e,realpath as K8e}from"node:fs/promises";import{dirname as V8e,isAbsolute as BHt,join as J8e,relative as nqn,resolve as iqn,sep as oqn}from"node:path";import{createHash as sqn}from"node:crypto";import{createHash as aqn}from"node:crypto";function W3n(){let e=process.env.XENO_AGENT_HOME?.trim();return e?EHt(e):EHt(OHt(),".xeno-agent")}function SHt(e){if(typeof e!="string"||!e.trim()||e.length>512)throw new MHt("INVALID","Invalid quota identity.");return e}function NHt(e){let t=r=>({id:SHt(r?.id),generation:SHt(r?.generation)});if(!e||e.agent&&!e.team)throw new MHt("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 xHt(e){return JSON.stringify(NHt(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 Xpe(e,t){return[...new Set((e??[]).map(r=>$r(r,t)))]}function RHt(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 K3n(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 Wd(e)}}function Wd(e){return structuredClone(e)}function uI(e){let t=Date.parse(e);return Number.isFinite(t)?t:0}function Jpe(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function Y3n(e){return{summary:"Goal created; work has not started.",completedTaskCount:0,totalTaskCount:0,outstanding:[],decisions:[],updatedAt:e}}function Z3n(){return{status:"pending",criteria:[],evidence:[]}}function _Ht(e){return q3n("sha256").update(e).digest("hex")}function Y8e(e){return{algorithm:"sha256",value:sqn("sha256").update(e).digest("hex")}}function UHt(e){if(typeof e!="string"||!e||e.length>2048||BHt(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 jHt(e){return Y8e(JSON.stringify([e.schemaVersion,e.sessionId,e.totalBytes,e.files.map(t=>[t.path,t.size,t.sha256,t.executable])])).value}function qHt(e,t){if(e.schemaVersion!==1||e.sessionId!==t||!Array.isArray(e.files)||e.files.length>DHt||!Number.isSafeInteger(e.totalBytes)||e.totalBytes<0||e.totalBytes>FHt)throw new Error("Invalid handoff snapshot manifest");let r=new Set,n=0;for(let i of e.files){if(UHt(i.path),!Number.isSafeInteger(i.size)||i.size<0||i.size>LHt||!/^[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||jHt(e)!==e.digest)throw new Error("Handoff snapshot manifest integrity mismatch")}async function z8e(e,t){let r=e;for(let o of t.split("/"))if(r=J8e(r,o),(await Kpe(r)).isSymbolicLink())throw new Error("Snapshot symlinks are not supported");let n=await K8e(r),i=nqn(e,n);if(i===".."||i.startsWith(`..${oqn}`)||BHt(i))throw new Error("Snapshot path escaped its root");return r}async function QHt(e){if(!e.sessionId||e.sessionId.length>1024||e.paths.length>DHt)throw new Error("Invalid snapshot scope");let t=await K8e(e.root),r=[],n=new Map,i=0;for(let s of[...e.paths].sort()){if(e.signal?.throwIfAborted(),UHt(s),!await e.authorizeFile(s))throw new Error("Snapshot file transfer is not authorized");let a=await z8e(t,s),l=await Kpe(a),c=await X8e(a,PHt.O_RDONLY|(PHt.O_NOFOLLOW??0));try{let d=await c.stat();if(await z8e(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>LHt||i+d.size>FHt)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 Kpe(a);if(await z8e(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=Y8e(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=jHt(o),qHt(o,e.sessionId),{manifest:o,blobs:n}}async function HHt(e){let t=structuredClone(e.manifest);if(qHt(t,e.sessionId),!await e.authorizeManifest(structuredClone(t)))throw new Error("Snapshot restoration is not authorized");e.signal?.throwIfAborted();let r=iqn(e.destination);if(await K8e(V8e(r))!==V8e(r))throw new Error("Snapshot destination parent must be canonical");try{throw await Kpe(r),new Error("Snapshot destination already exists")}catch(o){if(o.code!=="ENOENT")throw o}let n=`${r}.staging-${rqn()}`;await $Ht(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||Y8e(s).value!==o.sha256)throw new Error("Snapshot blob integrity mismatch; staging retained");let a=J8e(n,...o.path.split("/"));await $Ht(V8e(a),{recursive:!0,mode:448});let l=await X8e(a,"wx",o.executable?448:384);try{await l.writeFile(s),await l.sync()}finally{await l.close()}}e.signal?.throwIfAborted();let i=await X8e(J8e(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 WHt(e){return typeof e=="string"&&lqn.test(e)}function ES(e){return`sha256:${aqn("sha256").update(e).digest("hex")}`}var Ce,Y7o,Z7o,eZo,r_,tZo,MHt,G3n,V3n,z3n,X3n,zpe,CHt,J3n,THt,Ype,n_,DHt,LHt,FHt,lqn,i_=ye(()=>{"use strict";Ce=class extends Error{constructor(e,t,r={}){super(t),this.code=e,this.details=r,this.name="XenoCoordinationError"}code;details},Y7o=Q3n(),Z7o=H3n(),eZo=OHt();r_="[redacted]",tZo=[[/-----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${r_}`],[/((?:^|[\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${r_}`],[/\b(Bearer|Basic|Token|DPoP)\s+[A-Za-z0-9._~+/=-]{6,}/gi,`$1 ${r_}`],[/\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,r_],[/\beyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}/g,r_],[/([?&#;](?:access_token|refresh_token|id_token|token|key|api[_-]?key|secret|client_secret|password|signature|sig)=)[^&#\s"'<>]+/gi,`$1${r_}`],[/(\b[a-z][a-z0-9+.-]*:\/\/)[^/\s:@"']+:[^/\s@"']+@/gi,`$1${r_}@`]],MHt=class extends Error{constructor(e,t){super(t),this.code=e,this.name="QuotaError"}code;retryable=!1};G3n=3e4,V3n=3e4,z3n=6e4,X3n=2e4,zpe=new Set(["EACCES","EBUSY","EPERM"]),CHt=[5,10,20,40,80,160,320],J3n=[5,10,20,40,80,160,320],THt=[1,2,3,4];Ype=class{get goalTurnAdmissionVersion(){return 1}rootDirectory;now;idFactory;ownerLeaseMs;lockTimeoutMs;lockStaleMs;maximumEventsPerSession;constructor(e={}){this.rootDirectory=e.rootDirectory??Fm.join(W3n(),"coordination"),this.now=e.now??(()=>new Date().toISOString()),this.idFactory=e.idFactory??(t=>`${t}_${Vpe()}`),this.ownerLeaseMs=e.ownerLeaseMs??G3n,this.lockTimeoutMs=e.lockTimeoutMs??V3n,this.lockStaleMs=e.lockStaleMs??z3n,this.maximumEventsPerSession=e.maximumEventsPerSession??X3n}async getSessionState(e){let t=$r(e,"sessionId",1024);return Wd(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!==kS.hostname()||!Number.isInteger(s.processId)||(s.processId??0)<=0||Jpe(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=Fm.join(this.rootDirectory,"sessions"),t;try{t=await ci.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 ci.readFile(Fm.join(e,r),"utf8"));return!THt.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)=>uI(n.updatedAt)-uI(r.updatedAt)).map(r=>Wd(r))}async createGoal(e){let t=$r(e.sessionId,"sessionId",1024),r=RHt(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:Xpe(e.constraints,"constraints"),...r?{limits:r}:{},metadata:Wd(e.metadata??{}),status:"active",milestones:[],tasks:[],progress:Y3n(o),verification:Z3n(),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?Wd(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=Xpe(n.constraints,"constraints")),n.successCriteria&&(o.successCriteria=Wd(n.successCriteria)),n.progress&&(o.progress={...o.progress,...Wd(n.progress),outstanding:Xpe(n.progress.outstanding??o.progress.outstanding,"progress.outstanding"),decisions:Xpe(n.progress.decisions??o.progress.decisions,"progress.decisions"),updatedAt:this.now()}),n.verification&&(o.verification=Wd(n.verification)),n.metadata&&(o.metadata=Wd(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=Wd(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=K3n(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?Wd(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=NHt(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||xHt(s.scope)!==xHt(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:kS.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(uI(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!==kS.hostname()||!Jpe(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,uI(a)-uI(s.expiresAt));return s.heartbeatAt=a,s.expiresAt=new Date(uI(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:Wd(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:Wd(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=RHt(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 Wd({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!==kS.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(uI(n)+i).toISOString(),...r.processId!==void 0?{processId:r.processId}:{},...r.host?{host:$r(r.host,"host",512)}:{}}}ownerExpired(e,t){return uI(e.expiresAt)<=uI(t)?!0:e.processId!==void 0&&e.host===kS.hostname()&&!Jpe(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:Wd(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)),Wd(a)})}statePath(e){return Fm.join(this.rootDirectory,"sessions",`${_Ht(e)}.json`)}lockPath(e){return`${this.statePath(e)}.lock`}async readState(e){let t=this.statePath(e);try{let r=await ci.readFile(t,"utf8"),n=JSON.parse(r);if(!THt.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=Fm.dirname(t);await ci.mkdir(r,{recursive:!0});let n=`${t}.${process.pid}.${Vpe()}.tmp`,i=await ci.open(n,"wx");try{await i.writeFile(`${JSON.stringify(e,null,2)}
3211
+ `&&(this.atLineStart=!0);this.writeFn(r)}reset(){this.atLineStart=!0}markLineStarted(){this.atLineStart=!1}},IQt=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],IG=class{interval=null;frameIndex=0;lastLength=0;writeFn;clearFn;constructor(t,r){this.writeFn=t??(n=>{wQt.writeFrame(n,"spinner")}),this.clearFn=r??(()=>{wQt.writeFrame(`\r${" ".repeat(this.lastLength)}\r`,"spinner")})}start(t){this.stop(),this.frameIndex=0,this.interval=setInterval(()=>{let r=IQt[this.frameIndex%IQt.length],n=`${gr(r)} ${Me(t)}`;this.writeFn(`\r${" ".repeat(this.lastLength)}\r${n}`),this.lastLength=t.length+4,this.frameIndex++},80)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null,this.clearFn(),this.lastLength=0)}}});import{randomInt as Zjn}from"node:crypto";function e4n(e){return typeof e=="string"&&xa.some(t=>t.id===e)}function y8e(){let e=mw().uiMascot;return e4n(e)?e:null}function kh(){return y8e()??t4n}function kG(e){go({uiMascot:e})}function fD(){let e=mw().uiColor;return typeof e=="string"&&Bm(e)?e8e(e):e8e()}function PQt(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 r4n(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,w,y,A,b=0,I=.6)=>n?[Rn(g-y,w+.4,g,w-A*.55,I,"K"),Rn(g,w-A*.55,g+y,w+.4,I,"K")]:d?[Rn(g-y,w+A*.35,g+y,w+A*.35,I,"K")]:[dr(g+l*.5,w,y,A,"K",b),dr(g-y*.3+l*.7,w-A*.4,Math.max(.6,y*.36),Math.max(.6,y*.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(dr(12,28,3.2,1.9,"O"),dr(20,28,3.2,1.9,"O"),Rn(8.5,19,5.6,22.5,1.7,"B")),h.push(n?Rn(23.5,18,23.5+5*Math.cos(u),18+5*Math.sin(u),1.7,"B"):Rn(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(Rn(17,10,18.2,5.2,.9,"B"),Rn(18.2,5.2,20.2,3.6,.9,"B"),dr(21.2,3.4+g,1.9,1.9,"O")),h.push(dr(16,18.5-a*.3,9+s,9.8+a*.4-s,"B"),dr(16,22.2,5.2,4.2,"C"),dr(10.2,19.6,1.3,.9,"O"),dr(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?dr(16,19.9,1.4,1.1,"K"):Rn(15,19.6,17,19.6,.45,"K"))}if(e==="ocu"){let g=[Rn(10.5,9.5,8.5,5.5,1.3,"O"),Rn(8.5,5.5,10.5,3.2,1.1,"O")];h.push(...g,...g.map(f),dr(11.5,27.5,3,1.8,"B"),dr(20.5,27.5,3,1.8,"B"),Rn(7,18,4.5,21.5,1.6,"B")),h.push(n?Rn(25,17,25+4.5*Math.cos(u),17+4.5*Math.sin(u),1.6,"B"):Rn(25,18,27.5,21.5,1.6,"B")),h.push(dr(16,17.5-a*.3,10+s,10+a*.4-s,"B")),n?h.push(Rn(11.5,17,16,13.5,.75,"K"),Rn(16,13.5,20.5,17,.75,"K")):d?h.push(Rn(11.5,16.8,20.5,16.8,.75,"K")):h.push(dr(16,16,4.8,4.3,"C"),dr(16+l*1.4,16.4,2.8,2.8,"O"),dr(16+l*1.6,16.4,1.3,1.3,"K"),dr(15+l*1.4,15,.8,.8,"W")),h.push(n?dr(16,23,1.8,1.2,"K"):Rn(14.5,23,17.5,23,.5,"K"))}if(e==="squee"){for(let g=0;g<4;g++){let w=9.8+g*4.13,y=g<2?-1:1;if(n&&g===3){let b=w+6*Math.cos(u),I=19+6*Math.sin(u);h.push(Rn(w,19,b,I,1.6,"B"),dr(b,I,1.5,1.5,"O"));continue}let A=Math.sin(r*1.4+g*1.1)*1.3;h.push(Rn(w,19,w+A,25,1.6,"B"),Rn(w+A,25,w+A+y*2.2,26.8,1.3,"O"))}h.push(dr(16,18.5,8.6,2.6,"B"),dr(16,12.5-a*.3,9.2+s,8.6+a*.4,"B"),dr(11.5,8.2,1.1,1,"S"),dr(20.5,7.5,1.4,1.2,"S"),dr(16,5.8,.9,.8,"S")),h.push(dr(10.4,16.4,1.2,.8,"O"),dr(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?dr(16,17.2,1.2,.9,"K"):Rn(15.2,17,16.8,17,.45,"K"))}if(e==="greeb"){let g=[Rn(12.5,5.5,10.5,2.4,.8,"B"),dr(10,2,1.5,1.5,"O")];h.push(...g,...g.map(f),dr(13.5,29,2.2,1.4,"B"),dr(18.5,29,2.2,1.4,"B"),Rn(12,23,9.5,26,1.1,"B")),h.push(n?Rn(20,22.5,20+4*Math.cos(u),22.5+4*Math.sin(u),1.1,"B"):Rn(20,23,22.5,26,1.1,"B")),h.push(dr(16,24.5,4.6,4.2,"B"),dr(16,16.5,5.6,4.4,"B"),dr(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?dr(16,18.4,1,.8,"K"):Rn(15.4,18.4,16.6,18.4,.4,"K"))}if(e==="quad"){let g=A=>A<.5?4*A*A*A:1-Math.pow(-2*A+2,3)/2,w=(n?90*(Math.floor(r/.8)+g(Math.min(1,r%.8/.5))):5*Math.sin(r*1.2))*Math.PI/180,y=(A,b,I)=>{let v=A-16,k=b-16.5;return[16+v*Math.cos(I)-k*Math.sin(I),16.5+v*Math.sin(I)+k*Math.cos(I)]};for(let A=0;A<4;A++){let b=w+A*Math.PI/2,I=y(10.5,11,b),v=y(6.6,7.1,b),k=y(6.6,10.2,b);h.push(Rn(I[0],I[1],v[0],v[1],1.7,"B"),Rn(v[0],v[1],k[0],k[1],1.5,"B"),dr(k[0],k[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"},dr(11.4,19.2,1.2,.8,"O"),dr(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?dr(16,19.6,1.2,.9,"K"):Rn(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(dr(16,21.2,6,1.5,"S"),dr(16,18.3,14,3.6,"G"),dr(16,16.7,11,1.6,"B"));let g=Math.floor(r*3)%5;[6,11,16,21,26].forEach((w,y)=>h.push(dr(w,19.3,1,.8,y===g?"O":"K"))),h.push(dr(16,11.5,6.6,6.2,"Q"),Rn(16,9,17.6,6.8,.6,"O"),dr(18,6.4,.9,.9,"O"),dr(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),Rn(11.6,9.4,12.6,7.4,.55,"W")),n&&h.push(Rn(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 n4n(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 _Qt(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 A8e(e,t,r,n,i=16){let o=r4n(e,t,r),s=32/i,a=[_Qt(n,1.3),n,_Qt(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=n4n(h,(u+.5)*s,(c+.5)*s);if(!m)continue;let g=h.m==="O"?a:i4n[h.m],w=-(m[0]*.6+m[1]*.8);p=g.length===1?g[0]:g[w>.42?0:w<-.38?2:1];break}d.push(p)}l.push(d)}return l}function Mpe(e,t,r,n,i={}){let o=i.size??16,s=i.color??!0,a=A8e(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?X.hex(p)("\u2588"):X.compose(X.hex(p),X.bgHex(f))("\u2580"):d+=p?X.hex(p)("\u2580"):X.hex(f)("\u2584"):d+=p&&f?"\u2588":p?"\u2580":"\u2584"}l.push(d)}return l}var xa,t4n,dr,Rn,i4n,JR=ye(()=>{"use strict";dd();Uo();Hd();xa=[{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."}];t4n=xa[Zjn(xa.length)].id;dr=(e,t,r,n,i,o=0)=>({k:"e",cx:e,cy:t,rx:r,ry:n,m:i,rot:o}),Rn=(e,t,r,n,i,o)=>({k:"l",x1:e,y1:t,x2:r,y2:n,r:i,m:o});i4n={B:["#FAF9F4","#E4E3DC","#B4B3AA"],C:["#FFFFFF","#F6F5F0","#DAD9D1"],G:["#D2D1CA","#A3A29B","#6F6E68"],Q:["#4A4A48","#2E2E2D","#1E1E1D"],K:["#0B0B0B"],W:["#FFFFFF"],S:["#B4B3AA"]}});var Pe,Ao=ye(()=>{"use strict";Pe="0.5.168"});import{createHash as q3n,randomUUID as Vpe}from"node:crypto";import*as ci from"node:fs/promises";import*as kS from"node:os";import*as Fm from"node:path";import{homedir as OHt,platform as Q3n,release as H3n}from"node:os";import{resolve as EHt}from"node:path";import{randomUUID as eqn}from"node:crypto";import{hostname as tqn}from"node:os";import{randomUUID as rqn}from"node:crypto";import{constants as PHt}from"node:fs";import{lstat as Kpe,mkdir as $Ht,open as X8e,realpath as K8e}from"node:fs/promises";import{dirname as V8e,isAbsolute as BHt,join as J8e,relative as nqn,resolve as iqn,sep as oqn}from"node:path";import{createHash as sqn}from"node:crypto";import{createHash as aqn}from"node:crypto";function W3n(){let e=process.env.XENO_AGENT_HOME?.trim();return e?EHt(e):EHt(OHt(),".xeno-agent")}function SHt(e){if(typeof e!="string"||!e.trim()||e.length>512)throw new MHt("INVALID","Invalid quota identity.");return e}function NHt(e){let t=r=>({id:SHt(r?.id),generation:SHt(r?.generation)});if(!e||e.agent&&!e.team)throw new MHt("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 xHt(e){return JSON.stringify(NHt(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 Xpe(e,t){return[...new Set((e??[]).map(r=>$r(r,t)))]}function RHt(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 K3n(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 Wd(e)}}function Wd(e){return structuredClone(e)}function uI(e){let t=Date.parse(e);return Number.isFinite(t)?t:0}function Jpe(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function Y3n(e){return{summary:"Goal created; work has not started.",completedTaskCount:0,totalTaskCount:0,outstanding:[],decisions:[],updatedAt:e}}function Z3n(){return{status:"pending",criteria:[],evidence:[]}}function _Ht(e){return q3n("sha256").update(e).digest("hex")}function Y8e(e){return{algorithm:"sha256",value:sqn("sha256").update(e).digest("hex")}}function UHt(e){if(typeof e!="string"||!e||e.length>2048||BHt(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 jHt(e){return Y8e(JSON.stringify([e.schemaVersion,e.sessionId,e.totalBytes,e.files.map(t=>[t.path,t.size,t.sha256,t.executable])])).value}function qHt(e,t){if(e.schemaVersion!==1||e.sessionId!==t||!Array.isArray(e.files)||e.files.length>DHt||!Number.isSafeInteger(e.totalBytes)||e.totalBytes<0||e.totalBytes>FHt)throw new Error("Invalid handoff snapshot manifest");let r=new Set,n=0;for(let i of e.files){if(UHt(i.path),!Number.isSafeInteger(i.size)||i.size<0||i.size>LHt||!/^[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||jHt(e)!==e.digest)throw new Error("Handoff snapshot manifest integrity mismatch")}async function z8e(e,t){let r=e;for(let o of t.split("/"))if(r=J8e(r,o),(await Kpe(r)).isSymbolicLink())throw new Error("Snapshot symlinks are not supported");let n=await K8e(r),i=nqn(e,n);if(i===".."||i.startsWith(`..${oqn}`)||BHt(i))throw new Error("Snapshot path escaped its root");return r}async function QHt(e){if(!e.sessionId||e.sessionId.length>1024||e.paths.length>DHt)throw new Error("Invalid snapshot scope");let t=await K8e(e.root),r=[],n=new Map,i=0;for(let s of[...e.paths].sort()){if(e.signal?.throwIfAborted(),UHt(s),!await e.authorizeFile(s))throw new Error("Snapshot file transfer is not authorized");let a=await z8e(t,s),l=await Kpe(a),c=await X8e(a,PHt.O_RDONLY|(PHt.O_NOFOLLOW??0));try{let d=await c.stat();if(await z8e(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>LHt||i+d.size>FHt)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 Kpe(a);if(await z8e(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=Y8e(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=jHt(o),qHt(o,e.sessionId),{manifest:o,blobs:n}}async function HHt(e){let t=structuredClone(e.manifest);if(qHt(t,e.sessionId),!await e.authorizeManifest(structuredClone(t)))throw new Error("Snapshot restoration is not authorized");e.signal?.throwIfAborted();let r=iqn(e.destination);if(await K8e(V8e(r))!==V8e(r))throw new Error("Snapshot destination parent must be canonical");try{throw await Kpe(r),new Error("Snapshot destination already exists")}catch(o){if(o.code!=="ENOENT")throw o}let n=`${r}.staging-${rqn()}`;await $Ht(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||Y8e(s).value!==o.sha256)throw new Error("Snapshot blob integrity mismatch; staging retained");let a=J8e(n,...o.path.split("/"));await $Ht(V8e(a),{recursive:!0,mode:448});let l=await X8e(a,"wx",o.executable?448:384);try{await l.writeFile(s),await l.sync()}finally{await l.close()}}e.signal?.throwIfAborted();let i=await X8e(J8e(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 WHt(e){return typeof e=="string"&&lqn.test(e)}function ES(e){return`sha256:${aqn("sha256").update(e).digest("hex")}`}var Ce,Y7o,Z7o,eZo,r_,tZo,MHt,G3n,V3n,z3n,X3n,zpe,CHt,J3n,THt,Ype,n_,DHt,LHt,FHt,lqn,i_=ye(()=>{"use strict";Ce=class extends Error{constructor(e,t,r={}){super(t),this.code=e,this.details=r,this.name="XenoCoordinationError"}code;details},Y7o=Q3n(),Z7o=H3n(),eZo=OHt();r_="[redacted]",tZo=[[/-----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${r_}`],[/((?:^|[\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${r_}`],[/\b(Bearer|Basic|Token|DPoP)\s+[A-Za-z0-9._~+/=-]{6,}/gi,`$1 ${r_}`],[/\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,r_],[/\beyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}/g,r_],[/([?&#;](?:access_token|refresh_token|id_token|token|key|api[_-]?key|secret|client_secret|password|signature|sig)=)[^&#\s"'<>]+/gi,`$1${r_}`],[/(\b[a-z][a-z0-9+.-]*:\/\/)[^/\s:@"']+:[^/\s@"']+@/gi,`$1${r_}@`]],MHt=class extends Error{constructor(e,t){super(t),this.code=e,this.name="QuotaError"}code;retryable=!1};G3n=3e4,V3n=3e4,z3n=6e4,X3n=2e4,zpe=new Set(["EACCES","EBUSY","EPERM"]),CHt=[5,10,20,40,80,160,320],J3n=[5,10,20,40,80,160,320],THt=[1,2,3,4];Ype=class{get goalTurnAdmissionVersion(){return 1}rootDirectory;now;idFactory;ownerLeaseMs;lockTimeoutMs;lockStaleMs;maximumEventsPerSession;constructor(e={}){this.rootDirectory=e.rootDirectory??Fm.join(W3n(),"coordination"),this.now=e.now??(()=>new Date().toISOString()),this.idFactory=e.idFactory??(t=>`${t}_${Vpe()}`),this.ownerLeaseMs=e.ownerLeaseMs??G3n,this.lockTimeoutMs=e.lockTimeoutMs??V3n,this.lockStaleMs=e.lockStaleMs??z3n,this.maximumEventsPerSession=e.maximumEventsPerSession??X3n}async getSessionState(e){let t=$r(e,"sessionId",1024);return Wd(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!==kS.hostname()||!Number.isInteger(s.processId)||(s.processId??0)<=0||Jpe(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=Fm.join(this.rootDirectory,"sessions"),t;try{t=await ci.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 ci.readFile(Fm.join(e,r),"utf8"));return!THt.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)=>uI(n.updatedAt)-uI(r.updatedAt)).map(r=>Wd(r))}async createGoal(e){let t=$r(e.sessionId,"sessionId",1024),r=RHt(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:Xpe(e.constraints,"constraints"),...r?{limits:r}:{},metadata:Wd(e.metadata??{}),status:"active",milestones:[],tasks:[],progress:Y3n(o),verification:Z3n(),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?Wd(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=Xpe(n.constraints,"constraints")),n.successCriteria&&(o.successCriteria=Wd(n.successCriteria)),n.progress&&(o.progress={...o.progress,...Wd(n.progress),outstanding:Xpe(n.progress.outstanding??o.progress.outstanding,"progress.outstanding"),decisions:Xpe(n.progress.decisions??o.progress.decisions,"progress.decisions"),updatedAt:this.now()}),n.verification&&(o.verification=Wd(n.verification)),n.metadata&&(o.metadata=Wd(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=Wd(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=K3n(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?Wd(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=NHt(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||xHt(s.scope)!==xHt(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:kS.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(uI(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!==kS.hostname()||!Jpe(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,uI(a)-uI(s.expiresAt));return s.heartbeatAt=a,s.expiresAt=new Date(uI(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:Wd(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:Wd(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=RHt(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 Wd({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!==kS.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(uI(n)+i).toISOString(),...r.processId!==void 0?{processId:r.processId}:{},...r.host?{host:$r(r.host,"host",512)}:{}}}ownerExpired(e,t){return uI(e.expiresAt)<=uI(t)?!0:e.processId!==void 0&&e.host===kS.hostname()&&!Jpe(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:Wd(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)),Wd(a)})}statePath(e){return Fm.join(this.rootDirectory,"sessions",`${_Ht(e)}.json`)}lockPath(e){return`${this.statePath(e)}.lock`}async readState(e){let t=this.statePath(e);try{let r=await ci.readFile(t,"utf8"),n=JSON.parse(r);if(!THt.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=Fm.dirname(t);await ci.mkdir(r,{recursive:!0});let n=`${t}.${process.pid}.${Vpe()}.tmp`,i=await ci.open(n,"wx");try{await i.writeFile(`${JSON.stringify(e,null,2)}
3212
3212
  `,"utf8"),await i.sync()}finally{await i.close()}try{await this.renameReplacing(n,t);try{let o=await ci.open(r,"r");try{await o.sync()}finally{await o.close()}}catch{}}finally{await ci.unlink(n).catch(()=>{})}}async renameReplacing(e,t){for(let r=0;;r+=1)try{await ci.rename(e,t);return}catch(n){let i=n.code,o=CHt[r];if(process.platform!=="win32"||!i||!zpe.has(i)||o===void 0)throw n;await new Promise(s=>setTimeout(s,o))}}async withSessionLock(e,t){let r=this.lockPath(e),n=Fm.join(r,"owner.json"),i=Vpe(),o=`${r}.candidate.${i}`,s=Date.now();await ci.mkdir(Fm.dirname(r),{recursive:!0});let a={schemaVersion:1,token:i,pid:process.pid,host:kS.hostname(),acquiredAt:this.now()};await ci.mkdir(o),await ci.writeFile(Fm.join(o,"owner.json"),JSON.stringify(a),{encoding:"utf8",flag:"wx"});for(let l=0;;l+=1)try{await ci.rename(o,r);break}catch(c){let d=c.code;if(!(d&&new Set(["EEXIST","ENOTEMPTY","ENOTDIR","EBUSY"]).has(d)||process.platform==="win32"&&d&&zpe.has(d)))throw await ci.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 ci.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 ci.rm(o,{recursive:!0,force:!0}).catch(()=>{})}}async staleLockOwner(e,t){try{let[r,n]=await Promise.all([ci.readFile(t,"utf8").catch(()=>""),ci.stat(e)]),i=r?JSON.parse(r):void 0;return!i||i.host!==kS.hostname()||Jpe(i.pid)?void 0:Date.now()-n.mtimeMs>this.lockStaleMs?i:void 0}catch{return}}async quarantineLock(e,t,r){let n=Fm.join(e,"owner.json"),i=r==="stale"?`${e}.stale.${_Ht(t)}`:`${e}.${r}.${t}.${Vpe()}`;for(let o=0;;o+=1){let s;try{s=JSON.parse(await ci.readFile(n,"utf8"))}catch(a){if(a.code==="ENOENT")return;throw a}if(s.token!==t)return;try{await ci.rename(e,i);break}catch(a){let l=a.code;if(r==="stale")try{if(JSON.parse(await ci.readFile(Fm.join(i,"owner.json"),"utf8")).token===t)return}catch{}if(l==="ENOENT"||l==="EEXIST")return;let c=CHt[o];if(process.platform!=="win32"||!l||!zpe.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 ci.rm(i,{recursive:!0});return}catch(s){let a=s.code;if(a==="ENOENT")return;let l=J3n[o];if(process.platform!=="win32"||!a||!zpe.has(a)||l===void 0)throw s;await new Promise(c=>setTimeout(c,l))}}},n_=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 Ype,this.sessionId=e.sessionId,this.processId=e.processId??process.pid,this.host=e.host??tqn(),this.ownerId=e.ownerId??`runtime:${this.host}:${this.processId}:${eqn().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))}};DHt=1e4,LHt=8*1024*1024,FHt=64*1024*1024;lqn=/^sha256:[0-9a-f]{64}$/});var GHt=ye(()=>{"use strict"});function VHt(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 zHt=ye(()=>{"use strict"});var XHt=ye(()=>{"use strict"});function JHt(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 KHt=ye(()=>{"use strict"});function ZHt(e){return!Z8e(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&&!YHt(e.loadedModel)||e.models!==void 0&&(!Array.isArray(e.models)||e.models.length>1e3||!e.models.every(t=>Z8e(t)&&YHt(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&&(!Z8e(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 Z8e,YHt,eWt=ye(()=>{"use strict";Z8e=e=>!!e&&typeof e=="object"&&!Array.isArray(e),YHt=e=>typeof e=="string"&&e.length>0&&e.length<=512&&!/[\x00-\x1f\x7f]/.test(e)});var AZo,tWt=ye(()=>{"use strict";AZo=new TextEncoder});function uqn(e){return eQe(e)&&typeof e.method=="string"&&dqn.has(e.method)&&typeof e.url=="string"&&e.url.length<=2048&&e.url.startsWith("https://")}function rWt(e){if(e===null)return!0;if(!eQe(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 nWt(e){return eQe(e)&&e.kind==="host-request"&&typeof e.id=="string"&&e.id.length>0&&e.method===cqn&&uqn(e.input)}var cqn,dqn,eQe,iWt=ye(()=>{"use strict";cqn="account.authorize",dqn=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD"]),eQe=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});var oWt=ye(()=>{"use strict"});var sWt=ye(()=>{"use strict"});var tQe,aWt=ye(()=>{"use strict";tQe="1.0.0"});var hWt={};$o(hWt,{TERMINAL_WEB_JOB_STATES:()=>Zpe,WEB_JOB_PROGRESS_OPERATIONS:()=>nQe,WEB_JOB_PROGRESS_SCHEMA:()=>o_,WEB_JOB_PROGRESS_SCHEMA_VERSION:()=>MG,WEB_JOB_PROGRESS_STATES:()=>iQe,deriveWebJobProgress:()=>efe,isTerminalWebJobState:()=>pI,isWebJobProgress:()=>sQe,parseWebJobProgress:()=>NG,webJobProgressSignature:()=>aQe});function pI(e){return Zpe.includes(e)}function cWt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function dWt(e,t){return Object.keys(e).every(r=>t.has(r))}function oQe(e,t){return typeof e=="string"&&e.trim().length>0&&e.length<=t&&!/[\u0000-\u001f\u007f]/u.test(e)}function rQe(e){return oQe(e,64)&&Number.isFinite(Date.parse(e))}function fWt(e){return oQe(e,120)&&/^[A-Za-z0-9._:-]+$/u.test(e)}function uWt(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function NG(e){if(!cWt(e)||!dWt(e,pqn))throw new TypeError("invalid Web Context progress object");if(e.schema!==o_||e.schemaVersion!==MG||e.contractVersion!==tQe)throw new TypeError("unsupported Web Context progress schema");if(!oQe(e.jobId,256))throw new TypeError("invalid Web Context progress jobId");if(!nQe.includes(e.operation))throw new TypeError("invalid Web Context progress operation");if(!iQe.includes(e.state))throw new TypeError("invalid Web Context progress state");let t=pI(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||!fWt(e.terminalReason)))throw new TypeError("invalid Web Context terminalReason");if(!cWt(e.counters)||!dWt(e.counters,lWt))throw new TypeError("invalid Web Context progress counters");for(let n of lWt)if(!uWt(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(!uWt(e.sequence))throw new TypeError("invalid Web Context progress sequence");if(!rQe(e.observedAt))throw new TypeError("invalid Web Context observedAt");if("createdAt"in e&&!rQe(e.createdAt))throw new TypeError("invalid Web Context createdAt");if("updatedAt"in e&&!rQe(e.updatedAt))throw new TypeError("invalid Web Context updatedAt");return structuredClone(e)}function sQe(e){try{return NG(e),!0}catch{return!1}}function OG(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):0}function pWt(e){return typeof e=="string"&&e.length>0?e:void 0}function efe(e,t,r=new Date().toISOString()){let n=OG(e.queuedPages),i=OG(e.activePages),o=OG(e.completedPages),s=OG(e.failedPages),a=OG(e.excludedPages),l={queuedPages:n,activePages:i,completedPages:o,failedPages:s,excludedPages:a,knownPages:n+i+o+s+a},c=pI(e.state),d=fWt(e.terminalReason)?e.terminalReason:void 0,u=pWt(e.createdAt),p=pWt(e.updatedAt);return{schema:o_,schemaVersion:MG,contractVersion:tQe,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 aQe(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 o_,MG,Zpe,nQe,iQe,pqn,lWt,SD=ye(()=>{"use strict";aWt();o_="xeno.web-context.job-progress",MG="1.0.0",Zpe=["completed","partial","failed","cancelled"],nQe=["scrape","batch-scrape","map","crawl","render","extract"],iQe=["queued","running",...Zpe];pqn=new Set(["schema","schemaVersion","contractVersion","jobId","operation","state","terminal","terminalState","terminalReason","counters","sequence","observedAt","createdAt","updatedAt"]),lWt=new Set(["queuedPages","activePages","completedPages","failedPages","excludedPages","knownPages"])});var mWt=ye(()=>{"use strict"});var gWt=ye(()=>{"use strict"});var wWt=ye(()=>{"use strict"});var yWt=ye(()=>{"use strict"});var AWt=ye(()=>{"use strict"});var bWt=ye(()=>{"use strict";AWt()});var vWt=ye(()=>{"use strict"});var IWt=ye(()=>{"use strict"});var kWt=ye(()=>{"use strict"});var EWt=ye(()=>{"use strict"});var fqn,SWt=ye(()=>{"use strict";SS();fqn=1024*1024});function gqn(e){return us(e)?e.kind==="xeno-credits"||e.kind==="local"?!0:e.kind==="own-key"&&In(e.provider)&&In(e.label)&&(e.status===void 0||typeof e.status=="string"):!1}function yqn(e){if(!us(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(!us(t)||!wqn.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 Iqn(e){return typeof e=="string"&&vqn.test(e)?e:void 0}function kqn(e){return typeof e=="string"&&hqn.includes(e)}function xWt(e){return us(e)?In(e.clientId)&&In(e.clientVersion)&&In(e.instanceId)&&kqn(e.surface):!1}function TWt(e){return!us(e)||!us(e.protocol)||!us(e.host)||!us(e.storage)?!1:Number.isInteger(e.protocol.current)&&Rqn(e.protocol.supported)&&In(e.host.instanceId)&&In(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)&&xWt(e.surface)}function lQe(e){return!us(e)||!In(e.revision)||!Array.isArray(e.providers)?!1:e.providers.every(Cqn)}function Eqn(e){return!us(e)||!us(e.event)?!1:In(e.id)&&Number.isInteger(e.sequence)&&typeof e.sequence=="number"&&e.sequence>=0&&In(e.timestamp)&&In(e.conversationId)&&In(e.requestId)&&In(e.type)&&In(e.source)}function RWt(e){return!us(e)||!Array.isArray(e.events)?!1:(e.nextSequence===null||typeof e.nextSequence=="number"&&Number.isInteger(e.nextSequence)&&e.nextSequence>=0)&&e.events.every(Eqn)}function _Wt(e){return!us(e)||typeof e.success!="boolean"?!1:e.success?(e.status==="accepted"||e.status==="replayed")&&In(e.conversationId)&&In(e.requestId)&&In(e.adapterId)&&us(e.selection)&&In(e.selection.providerId)&&In(e.selection.catalogRevision):In(e.code)&&In(e.safeError)}function PWt(e){return!us(e)||typeof e.success!="boolean"?!1:e.success?(e.status==="cancel_requested"||e.status==="replayed")&&In(e.conversationId)&&In(e.requestId):In(e.code)&&In(e.safeError)}function $Wt(e){return us(e)&&In(e.id)&&typeof e.sequence=="number"&&Number.isInteger(e.sequence)&&e.sequence>0&&typeof e.timestamp=="number"&&Number.isFinite(e.timestamp)&&Sqn(e.type)&&e.source==="host"&&e.schemaVersion===1&&e.redactionState==="safe"&&"payload"in e&&(e.type!=="account.state.changed"||us(e.payload)&&typeof e.payload.pending=="boolean")}function Sqn(e){return typeof e=="string"&&bqn.includes(e)}function OWt(e,t,r){if(e.surface.surface!==t.surface||e.surface.instanceId!==t.instanceId)throw new Ta("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 Ta("protocol_mismatch",`Agent host protocol ${e.protocol.current} is incompatible with client range ${r.min}-${r.max}.`)}function xqn(e){return!(!us(e)||e.chatExecution!==void 0&&!BG(e.chatExecution)||e.durableResume!==void 0&&!BG(e.durableResume)||e.nativeTuiAttach!==void 0&&!BG(e.nativeTuiAttach)||e.reconciliation!==void 0&&!BG(e.reconciliation)||e.modelSwitchInPlace!==void 0&&!BG(e.modelSwitchInPlace)||e.resumeCompatibilityKey!==void 0&&typeof e.resumeCompatibilityKey!="string")}function BG(e){return us(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 Cqn(e){return us(e)?In(e.id)&&typeof e.kind=="string"&&mqn.includes(e.kind)&&In(e.displayName)&&MWt(e.availability)&&us(e.capabilities)&&(e.providerSession===void 0||xqn(e.providerSession))&&(e.catalogState===void 0||yqn(e.catalogState))&&Array.isArray(e.models)&&e.models.every(Tqn)&&In(e.catalogRevision):!1}function Tqn(e){return us(e)&&In(e.id)&&In(e.displayName)&&MWt(e.availability)&&(e.funding===void 0||gqn(e.funding))&&(e.reasoningOptions===void 0||Array.isArray(e.reasoningOptions)&&e.reasoningOptions.every(t=>us(t)&&In(t.id)&&In(t.label)&&(t.runtimeModelId===void 0||In(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 MWt(e){return e==="available"||e==="degraded"||e==="blocked"||e==="unavailable"}function Rqn(e){return us(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 In(e){return typeof e=="string"&&e.trim().length>0}function us(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function tfe(e){for(let t of Pqn)for(let r of _qn)if(e===`${t}tool.${r}`)return r;return null}function s_(e,t){let r=e?.[t];return typeof r=="string"&&r.trim()?r:void 0}function rfe(e){let t=e.event;return s_(t,"toolName")||s_(t,"tool")||s_(t,"name")||s_(t,"title")||s_(t,"kind")}function CD(e){let t=e.event;return s_(t,"toolCallId")||s_(t,"tool_call_id")}function nfe(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 ife(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 ofe(e){return e==="completed"?!0:e==="failed"||e==="cancelled"?!1:null}var xD,CWt,hqn,mqn,wqn,Aqn,MZo,bqn,vqn,Ta,_qn,Pqn,SS=ye(()=>{"use strict";GHt();zHt();XHt();KHt();eWt();tWt();iWt();oWt();sWt();SD();mWt();gWt();wWt();yWt();bWt();vWt();IWt();kWt();EWt();SWt();xD=1,CWt=1,hqn=["standalone-desktop","hub-embed","shell-embed","embed-preview","panel-embed","headless-client","extension-panel"],mqn=["sdk-native","xeno-cloud","cli-app-server","cli-remote","acp"];wqn=["timeout","network","rate-limited","server","auth-required","forbidden","invalid-response","configuration","cancelled"];Aqn=["workspace.usage","workspace.audit","inference.request","workspace.schedule","workspace.backup","workspace.environment","host.maintenance","account.request","workforce.request","workspace.notifications","workspace.rules","workspace.browser","workspace.browser.session","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.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"],MZo=new Set(Aqn),bqn=["host.ready","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","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"],vqn=/^[A-Z][A-Z0-9_]{1,63}$/;Ta=class extends Error{code;reason;constructor(t,r,n){super(r),this.name="AgentHostProtocolError",this.code=t,this.reason=Iqn(n)}};_qn=["started","updated","completed","failed","cancelled"],Pqn=["","acp."]});import{createHash as res,randomBytes as $qn,timingSafeEqual as nes}from"node:crypto";import{createConnection as Oqn}from"node:net";function Bqn(e,t,r){if(e!=="workspace.command.run")return r;let n=afe(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 Dqn(e){return!afe(e)||e.kind!=="response"||typeof e.id!="string"||typeof e.ok!="boolean"?!1:e.ok?"output"in e:afe(e.error)&&qqn(e.error.code)&&typeof e.error.message=="string"&&(e.error.reason===void 0||typeof e.error.reason=="string")}function Lqn(e){return afe(e)&&e.kind==="event"&&$Wt(e.event)}function Fqn(e,t,r){DWt(e,t,r)}function DWt(e,t,r){let n=`${JSON.stringify(t)}
3213
3213
  `;if(Buffer.byteLength(n,"utf8")>r)throw new Ta("invalid_response","Local Agent host RPC frame exceeds the size limit.");e.write(n,"utf8")}function Uqn(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 a_(e){return typeof e=="number"&&Number.isInteger(e)&&e>0?e:void 0}function jqn(e){let t=a_(e)||Mqn;if(t>NWt)throw new Error(`Local Agent host RPC frame limit cannot exceed ${NWt} bytes.`);return t}function qqn(e){return e==="invalid_handshake"||e==="protocol_mismatch"||e==="surface_mismatch"||e==="not_connected"||e==="invalid_response"}function BWt(e){return e instanceof Error?e:new Error(String(e))}function afe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function lfe(e,t){return e instanceof Error&&"code"in e&&e.code===t}var Mqn,NWt,Nqn,sfe,cQe,cfe=ye(()=>{"use strict";SS();Mqn=32*1024*1024,NWt=64*1024*1024,Nqn=3e4,sfe=class{endpoint;transportToken;protocolVersion;maxFrameBytes;requestTimeoutMs;listeners=new Set;pending=new Map;requestPrefix=$qn(12).toString("hex");requestSequence=0;socket=null;connectPromise=null;accountAuthorizer=null;setAccountAuthorizer(t){this.accountAuthorizer=t}constructor(t){Uqn(t.endpoint,t.transportToken),this.endpoint=t.endpoint,this.transportToken=t.transportToken,this.protocolVersion=a_(t.protocolVersion)||xD,this.maxFrameBytes=jqn(t.maxFrameBytes),this.requestTimeoutMs=a_(t.requestTimeoutMs)||Nqn}get connected(){return this.socket!==null&&!this.socket.destroyed}async connect(){if(!this.connected)return this.connectPromise?this.connectPromise:(this.connectPromise=new Promise((t,r)=>{let n=Oqn(this.endpoint),i=new cQe(this.maxFrameBytes,a=>this.receive(a)),o=a=>{n.off("connect",s),this.socket=null,r(a)},s=()=>{n.off("error",o),n.setNoDelay(!0),this.socket=n,t()};n.once("error",o),n.once("connect",s),n.on("data",a=>{try{i.push(a)}catch(l){this.disconnect(BWt(l))}}),n.on("error",a=>this.disconnect(a)),n.on("close",()=>this.disconnect(new Error("Local Agent host connection closed.")))}).finally(()=>{this.connectPromise=null}),this.connectPromise)}async request(t,r){await this.connect();let n=this.socket;if(!n||n.destroyed)throw new Ta("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=Bqn(t,r,this.requestTimeoutMs),c=setTimeout(()=>{this.pending.delete(i),a(new Ta("not_connected",`Local Agent host request timed out: ${t}.`))},l);this.pending.set(i,{resolve:d=>s(d),reject:a,timeout:c});try{Fqn(n,o,this.maxFrameBytes)}catch(d){clearTimeout(c),this.pending.delete(i),a(BWt(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 Ta("invalid_response","Local Agent host returned malformed JSON."));return}if(Lqn(r)){for(let i of[...this.listeners])i(structuredClone(r.event));return}if(nWt(r)){this.answerHostRequest(r);return}if(!Dqn(r)){this.disconnect(new Ta("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 Ta(r.error.code,r.error.message,r.error.reason)))}async answerHostRequest(t){let r=null;try{let i=this.accountAuthorizer?await this.accountAuthorizer({method:t.input.method,url:t.input.url}):null;r=rWt(i)?i:null}catch{r=null}let n=this.socket;if(!(!n||n.destroyed))try{DWt(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()}};cQe=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 Ta("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 Ta("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 LWt(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 dQe=ye(()=>{"use strict"});import{readFile as Qqn}from"node:fs/promises";import{join as FWt}from"node:path";function dfe(e){let t=e.isProcessAlive||Wqn;try{return!t(e.pid)}catch{return!1}}async function ufe(e){let t=FWt(e,"agent-host.lock");try{let r=await jWt(t);return r.state==="released"?null:qWt(r)}catch(r){if(lfe(r,"ENOENT"))return null;throw r}}async function UWt(e){let t=FWt(e,"agent-host.lock");try{let r=await jWt(t);return r.state==="released"?null:{descriptor:qWt(r),transportToken:r.transportToken}}catch(r){if(lfe(r,"ENOENT"))return null;throw r}}async function jWt(e){return Hqn(await Qqn(e,"utf8"))}function Hqn(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(!Gqn(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&&!LWt(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 qWt(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 Wqn(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return!lfe(t,"ESRCH")}}function Gqn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var uQe=ye(()=>{"use strict";cfe();dQe()});async function fQe(e){let t=a_(e.protocolVersion)||xD,r=a_(e.connectTimeoutMs)||5e3,n=a_(e.requestTimeoutMs)||3e4,i=await ufe(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(dfe({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 UWt(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 sfe({endpoint:o.descriptor.endpoint,transportToken:o.transportToken,protocolVersion:t,requestTimeoutMs:n});try{await Vqn(s,r)}catch(a){return s.close(),{attached:!1,reason:"unreachable",detail:a instanceof Error?a.message:String(a)}}return{attached:!0,session:new pQe({role:"attached-client",descriptor:o.descriptor,transport:s})}}async function Vqn(e,t){let r=Date.now()+t,n;do try{await e.connect();return}catch(i){if(n=QWt(i),!zqn(n)||Date.now()>=r)break;await Xqn(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 zqn(e){if(!("code"in e))return!1;let t=e.code;return t==="ENOENT"||t==="ECONNREFUSED"||t==="EPIPE"}function Xqn(e){return new Promise(t=>setTimeout(t,e))}function QWt(e){return e instanceof Error?e:new Error(String(e))}var pQe,HWt=ye(()=>{"use strict";SS();uQe();cfe();pQe=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=QWt(t);await this.close().catch(()=>{}),this.onAuthorityLost?.(r)}finally{this.heartbeatPending=!1}}}}});import{join as Jqn,resolve as GWt}from"node:path";function TD(e){let t=WWt(e.homeDirectory);if(!t)throw new Error("Agent host homeDirectory is required.");let r=WWt(e.hostRootDirectory);return r||Jqn(GWt(t,Kqn),Yqn)}function WWt(e){return typeof e=="string"&&e.trim()?GWt(e.trim()):void 0}var Kqn,Yqn,VWt=ye(()=>{"use strict";Kqn=".xeno",Yqn="agent-host-v1"});var pfe=ye(()=>{"use strict";cfe();uQe();dQe();HWt();VWt()});import{existsSync as Zqn}from"fs";import{join as rf}from"path";import{createDirs as e8n}from"@xenosystem/primitives/dirs";function t8n(e,t=[]){return{pluginDir:rf(e,"plugins"),mcpConfigDir:rf(e,"mcp"),mcpDataDir:rf(e,"mcp"),protectedPaths:[...t,rf(e,"credentials.json")],layout:"legacy"}}function r8n(e,t=[]){return{pluginDir:rf(e.data,"extensions","plugins"),mcpConfigDir:rf(e.config,"extensions","mcp"),mcpDataDir:rf(e.data,"extensions","mcp"),protectedPaths:[...t,e.secrets],layout:"extensions"}}function n8n(e,t){return!zWt(e)&&zWt(t)?t:e}function XWt(e,t=process.env){let r=e8n({home:e,env:t}),n=rf(e,".ssh");return n8n(r8n({data:r.root("data"),config:r.root("config"),secrets:r.root("secrets")},[n]),t8n(rf(e,".xeno"),[n]))}function JWt(e,t){return e.XENO_AGENT_HOST_ROOT?.trim()?rf(t,"coordination"):void 0}var zWt,hQe=ye(()=>{"use strict";zWt=e=>[rf(e.pluginDir,"plugins.json"),rf(e.pluginDir,"trust.json"),rf(e.mcpConfigDir,"servers.json"),rf(e.mcpConfigDir,"sdk-approvals.json")].some(t=>Zqn(t))});import{homedir as i8n}from"node:os";function Zi(e={}){if(e.rootDirectory)return new Ype(e);let t=TD({homeDirectory:i8n(),...process.env.XENO_AGENT_HOST_ROOT?{hostRootDirectory:process.env.XENO_AGENT_HOST_ROOT}:{}}),r=JWt(process.env,t);return new Ype({...e,...r?{rootDirectory:r}:{}})}var $w=ye(()=>{"use strict";i_();pfe();hQe()});function l8n(e){if(e===void 0||e==="")return"";if(!a8n.test(e)||e.split("/").includes(".."))throw new TypeError("pathPrefix must be an absolute path such as /v1/web");return e}function FG(e){return e.signal?{signal:e.signal}:{}}function c8n(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 d8n(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 u8n(e,t){let r=0,n,i=!1;return async o=>{if(!e)return;let s=pI(o.state);if(s&&i)return;let a=efe(o,r),l=aQe(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 a8n,UG,e6t=ye(()=>{"use strict";SD();SD();a8n=/^\/[A-Za-z0-9._~-]+(?:\/[A-Za-z0-9._~-]+)*$/;UG=class{#e;#r;#n;#i;constructor(t){if(this.#e=new URL(t.baseUrl),this.#r=t.token,this.#i=l8n(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",FG(t))}usage(){return this.#t("/v1/usage")}search(t,r={}){return this.#t("/v1/search",{method:"POST",body:JSON.stringify(t),...FG(r)})}searchAndScrape(t,r={}){return this.#t("/v1/search-and-scrape",{method:"POST",body:JSON.stringify(t),...FG(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}`,FG(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}`,FG(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);!pI(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=pI(o.state)?efe(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=u8n(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),pI(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:d8n(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(c8n(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 p8n}from"node:fs";function AQe(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 jG(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 h8n(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=p8n(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 m8n(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||f8n,token:h8n(e),source:"explicit",auth:"bearer"};let i=e.XENO_API_KEY?.trim();return i?{baseUrl:t6t,token:i,pathPrefix:r6t,source:"account",auth:"bearer"}:{baseUrl:t6t,pathPrefix:r6t,source:"account",auth:"dpop"}}function g8n(){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 w8n(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 Cl()).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=BA(e);if(l.state!=="present")throw g8n();return a.set("authorization",`Bearer ${l.key}`),fetch(t,{...r,headers:a})}}function bQe(e=process.env,t={}){let r=m8n(e,t);return r.auth==="dpop"?new UG({baseUrl:r.baseUrl,token:"dpop-account-session",pathPrefix:r.pathPrefix,fetchImpl:w8n(t)}):new UG({baseUrl:r.baseUrl,token:r.token??"",...r.pathPrefix?{pathPrefix:r.pathPrefix}:{}})}function n6t(e=process.env){let t=AQe(e),r=jG("fetch",t),n=wle({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 yQe(e),createRequest:(i,o)=>{let s=n(i,o);return i==="search"&&(s.budget.maxPages=jG("search",r.maxProviderCostUsd,void 0,typeof o.maxResults=="number"?o.maxResults:5).maxPages),s}}}var f8n,t6t,r6t,yQe,vQe=ye(()=>{"use strict";e6t();kw();Yp();st();f8n="http://127.0.0.1:8080",t6t="https://api.xenostudio.ai",r6t="/v1/web";yQe=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??=bQe(this.env),this.client}async bindTenant(t,r,n){this.account??=this.getClient().account();let i=await this.account,o=jG(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 qG(e){return e.type==="run.self_review"}function QG(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 i6t(e){return e.replace(/\s+/g," ").trim()}function HG(e){let t=i6t(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 IQe(e){let t=[],r=(n,i)=>{if(i.length!==0){t.push(`${n}:`);for(let o of i)t.push(` - ${i6t(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(`
3214
3214
  `)}function kQe(e){return e.findings.length+e.fixes.length+e.unverified.length>0}function o6t(e,t=process.env){let r=t.XENO_SELF_REVIEW?.trim().toLowerCase();if(r==="0"||r==="false"||r==="off")return!1;if(!(r==="1"||r==="true"||r==="on")&&e===!1)return!1}var ffe=ye(()=>{"use strict"});function hfe(e){let t=e.type.toLowerCase();if(!(t.includes("tool")||CD(e))&&!(!t.includes("text")&&!t.includes("message")&&!t.includes("delta"))&&!(t.includes("complete")||t.includes("final")||t.includes("end")))for(let r of["delta","text","content","chunk"]){let n=e.event[r];if(typeof n=="string"&&n.length>0)return n}}function s6t(e){let t=e.type;if(t==="turn.failed"){for(let r of["error","message","safeError"]){let n=e.event[r];if(typeof n=="string"&&n.trim())return{failed:n.trim().slice(0,2e3)}}return{failed:"The agent run failed."}}if(t==="turn.completed"){let r=e.event.tokenUsage;if(r&&typeof r=="object"&&!Array.isArray(r)){let n=r,[i,o,s]=[n.input,n.output,n.total];if(typeof i=="number"&&typeof o=="number"&&typeof s=="number")return{tokenUsage:{input:i,output:o,total:s}}}}}var EQe=ye(()=>{"use strict";SS()});import{createHash as y8n}from"node:crypto";import{setTimeout as A8n}from"node:timers/promises";function I8n(e,t){return`subrun-${y8n("sha256").update(`${e}\0${t}`).digest("hex").slice(0,32)}`}async function k8n(e,t,r){return((await e.listRuntimeEvents({conversationId:t,subagentRunId:r,limit:500}))?.events??[]).map(i=>hfe(i)??"").join("")}function E8n(e,t,r,n){let i=new Set,o=typeof n.onToolStart=="function"||typeof n.onToolEnd=="function",s=a=>{try{a()}catch{}};return async function(){if(!o)return;let l=await e.listRuntimeEvents({conversationId:t,subagentRunId:r,limit:500}).catch(()=>null);for(let c of l?.events??[]){let d=tfe(String(c.type??""));if(!d)continue;let u=`${CD(c)??c.id}:${d}`;if(i.has(u))continue;i.add(u);let p=rfe(c)??"unknown";if(d==="started"&&n.onToolStart){let h=n.onToolStart;s(()=>h(p,nfe(c)??{}))}let f=ofe(d);if(f!==null&&n.onToolEnd){let h=n.onToolEnd;s(()=>h(p,{success:f,output:ife(c)??""}))}}}}function a6t(e){let t=e.pollIntervalMs??250;return async r=>{let n=r.task,i=I8n(e.rootTraceId,n.id),o={lastTraceId:null,tokenUsage:{input:0,output:0,total:0},async run(s){let a=Math.max(1e3,e.deadline-Date.now()),l={parentConversationId:e.parentConversationId,...e.parentRequestId===void 0?{}:{parentRequestId:e.parentRequestId},parentAgentId:e.parentAgentId,childConversationId:i,childAgentId:n.role?`delegated-${n.role}`:"delegated-branch",workspaceId:e.workspaceId,teamId:e.teamId,objective:s,...n.role===void 0?{}:{role:n.role},policy:{maxRuntimeMs:a}},c=await e.client.createSubagentRun(l);if(!c?.success||!c.run)throw new Error(c?.safeError??"The Agent host refused to create a subagent run for this delegated branch.");let d=c.run.id;o.lastTraceId=d;let u=E8n(e.client,i,d,{onToolStart:r.onToolStart,onToolEnd:r.onToolEnd});for(;;){if(e.signal?.aborted){await e.client.cancelSubagentRun({runId:d}).catch(()=>{});let m=new Error("Delegated branch was cancelled.");throw m.name="AgentInterruptedError",m}let f=((await e.client.listSubagentRuns({parentConversationId:e.parentConversationId}))?.runs??[]).find(m=>m.id===d),h=String(f?.status??"");if(b8n.has(h)){if(v8n.has(h))throw new Error(f?.error??`The delegated branch ended as '${h}' without reporting a reason.`);await u();let m=await k8n(e.client,i,d);if(m.length===0)throw new Error(`The delegated branch reported '${h}' but produced no readable output. Its runtime events carry no text for this run id.`);return m}if(Date.now()>=e.deadline)throw await e.client.cancelSubagentRun({runId:d}).catch(()=>{}),new Error("The delegated branch exceeded the time this run was given to wait.");await u(),await A8n(t,void 0,{signal:e.signal})}}};return o}}var b8n,v8n,l6t=ye(()=>{"use strict";SS();EQe();b8n=new Set(["completed","succeeded","failed","cancelled","error"]),v8n=new Set(["failed","cancelled","error"])});function WG(e,t){let r=e.run.bind(e);return e.run=async n=>{try{return await t.start(),await r(n)}finally{await t.stop()}},e}function fI(e){return!e||e.status==="completed"}function GG(e,t=r=>{bt.cleanupOwner(r)}){if(e)try{t(e)}catch{}}async function jA(e){let{agent:t,signal:r}=e,n=()=>GG(e.ownerSessionId,e.cleanupOwner),i=()=>{t.cancelCurrentTurn()};if(r?.aborted)throw n(),await e.lifecycle?.stop(),new ji;r?.addEventListener("abort",i,{once:!0});let o=!1;try{if(e.lifecycle&&(await e.lifecycle.start(r),r?.aborted))throw new ji;let s=await(e.run??(()=>t.run(e.prompt)))(),a=t.lastRunTermination??void 0;o=fI(a);let l=a?{status:a.status,reason:a.reason,...a.message?{message:a.message}:{}}:void 0;return{output:s,...l?{termination:l}:{},tokenUsage:{...t.tokenUsage}}}finally{r?.removeEventListener("abort",i),o||n(),await e.lifecycle?.stop()}}function l_(e,t,r){if(!t)return e;let n=e.run.bind(e);return e.run=async i=>{let o=!1;try{let s=await n(i);return o=fI(e.lastRunTermination),s}finally{o||GG(t,r)}},e}function SQe(e){return e.stopRequested||e.termination?.status==="interrupted"?"stopped":e.threw||e.termination?.status==="error"?"failed":fI(e.termination)?"completed":"unfinished"}function VG(e){let t=e.summary.cancelled??0,r=e.summary.incomplete??0,n=[];return r>0&&n.push(`${r} stopped before finishing`),t>0&&n.push(`${t} cancelled`),e.incomplete?`Delegation incomplete: no branch finished${n.length?` (${n.join(", ")})`:""}. The answer below is partial output from a branch that stopped early, not a final answer.`:n.length?`Delegation finished with unfinished branches: ${n.join(", ")}.`:void 0}var zG=ye(()=>{"use strict";st()});import{promises as aGe}from"node:fs";import{readdirSync as Hzt,renameSync as N8n}from"node:fs";import{existsSync as B8n}from"node:fs";import*as tl from"node:fs/promises";import*as rn from"node:path";import{spawn as Q8n,spawnSync as H8n}from"node:child_process";import{homedir as tXt,platform as z8n,release as X8n}from"node:os";import{resolve as p6t}from"node:path";import{isIP as h6t}from"node:net";import{createHash as y6t}from"node:crypto";import{mkdirSync as CQn,readFileSync as TQn,rmSync as gXt,writeFileSync as RQn}from"node:fs";import{hostname as wXt}from"node:os";import{dirname as _Qn}from"node:path";import{existsSync as b6t,realpathSync as jQn}from"node:fs";import{dirname as qQn,isAbsolute as QQn,join as HQn,resolve as The,sep as WQn}from"node:path";import{existsSync as QS,mkdirSync as IXt,renameSync as kXt,rmSync as _he,writeFileSync as EXt}from"node:fs";import{execFile as JQn,spawnSync as KQn}from"node:child_process";import{createHash as YQn,randomUUID as ZQn}from"node:crypto";import{tmpdir as SXt}from"node:os";import{join as MI}from"node:path";import{spawnSync as I6t}from"node:child_process";import{accessSync as nHn,constants as iHn,existsSync as $Xt,realpathSync as OXt,statSync as MXt}from"node:fs";import{delimiter as oHn,isAbsolute as sHn,join as aHn,resolve as NXt}from"node:path";import{createHash as pHn,createPublicKey as fHn,verify as hHn}from"node:crypto";import{readFileSync as mHn,statSync as gHn}from"node:fs";import{isAbsolute as wHn}from"node:path";import{createHash as Zfe,randomUUID as QXt}from"node:crypto";import{accessSync as IHn,chmodSync as E6t,constants as kHn,existsSync as Phe,lstatSync as cWe,mkdirSync as EHn,readFileSync as LV,realpathSync as HXt,statSync as WXt,unlinkSync as SHn,writeFileSync as xHn}from"node:fs";import{tmpdir as GXt}from"node:os";import{dirname as VXt,isAbsolute as dWe,join as FS,parse as S6t}from"node:path";import{spawnSync as x6t}from"node:child_process";import{fileURLToPath as CHn}from"node:url";import{randomBytes as KHn}from"node:crypto";import*as Hm from"path";import*as Wu from"path";import*as Mhe from"os";import*as Gu from"node:fs/promises";import{createHash as hWn,randomUUID as mWn}from"node:crypto";import{createHash as EWn}from"node:crypto";import{constants as D6t}from"node:fs";import{open as SWn,stat as xWn}from"node:fs/promises";import{resolve as CWn}from"node:path";import*as A_ from"path";import{randomUUID as _Wn}from"crypto";import*as bV from"path";import{randomUUID as PWn}from"crypto";import{stat as $Wn}from"fs/promises";import*as Lw from"path";import*as kI from"path";import{resolve as LQe}from"node:path";import{existsSync as LJt,statSync as FJt}from"node:fs";import{extname as HJt}from"node:path";import{createHash as QWn,randomBytes as HWn}from"node:crypto";import{closeSync as WWn,existsSync as Lhe,mkdirSync as GWn,openSync as VWn,readFileSync as t9t,readSync as zWn,readdirSync as XWn,statSync as r9t,unlinkSync as F6t,writeFileSync as kWe}from"node:fs";import{join as gz,resolve as JWn}from"node:path";import{closeSync as t6n,existsSync as r6n,openSync as n6n,readSync as i6n,statSync as o6n}from"node:fs";import{readFile as s6n}from"node:fs/promises";import{extname as s9t}from"node:path";import{existsSync as u6n}from"node:fs";import{dirname as j6t}from"node:path";import{existsSync as h6n}from"node:fs";import{dirname as m6n,extname as g6n}from"node:path";import{existsSync as FQe}from"node:fs";import{promises as E6n}from"node:fs";import{dirname as S6n,extname as x6n}from"node:path";import{readdir as U6n,stat as j6n}from"node:fs/promises";import{basename as q6n,join as Q6n,relative as v9t}from"node:path";import{execFile as V6n}from"node:child_process";import{existsSync as z6n,statSync as X6n}from"node:fs";import PWe,{dirname as J6n}from"node:path";import{execFile as iGn}from"node:child_process";import{existsSync as OWe,statSync as jhe}from"node:fs";import MWe,{dirname as oGn}from"node:path";import{readFile as sGn}from"node:fs/promises";import{createHash as qQe,randomUUID as kfe}from"node:crypto";import{accessSync as EGn,appendFileSync as SGn,constants as W6t,existsSync as xGn,lstatSync as CGn,mkdirSync as QQe,readFileSync as TGn,readdirSync as RGn,statSync as _Gn,writeFileSync as PGn}from"node:fs";import{join as HQe,resolve as $Gn}from"node:path";import{spawn as jGn}from"node:child_process";import{randomUUID as qGn}from"node:crypto";import{platform as Hhe}from"node:os";import{resolve as nKt}from"node:path";import{StringDecoder as J6t}from"node:string_decoder";import{createHash as GGn,randomUUID as dGt}from"node:crypto";import{closeSync as VGn,createWriteStream as uGt,existsSync as zGn,lstatSync as XGn,mkdirSync as JGn,openSync as KGn,readSync as pKt,rmSync as pGt,statSync as fGt}from"node:fs";import{join as eHe,resolve as tHe,sep as YGn}from"node:path";import{randomUUID as tVn}from"node:crypto";import{spawn as rVn}from"node:child_process";import{existsSync as nVn,mkdirSync as iVn,readFileSync as oVn,rmSync as EGt}from"node:fs";import{tmpdir as sVn}from"node:os";import{join as fKt,resolve as SGt}from"node:path";import{existsSync as xKt,statSync as CKt}from"node:fs";import{delimiter as IVn,isAbsolute as kVn,join as qWe,resolve as EVn}from"node:path";import{statSync as PVn}from"node:fs";import{isAbsolute as $Vn,normalize as OVn}from"node:path";import{randomUUID as iHe}from"node:crypto";import{existsSync as rVe,statSync as RKt}from"node:fs";import{tmpdir as DVn}from"node:os";import{join as LVn}from"node:path";import{randomUUID as OKt}from"node:crypto";import{promises as NGt}from"node:fs";import Izn from"node:path";import{createHash as F7t}from"node:crypto";import{existsSync as PJn,lstatSync as $Jn,mkdirSync as OJn,rmSync as MJn}from"node:fs";import{open as NJn,readFile as BJn,stat as nVt,writeFile as DJn}from"node:fs/promises";import{tmpdir as LJn}from"node:os";import{extname as w6e,join as Fme}from"node:path";import{existsSync as n9n,readFileSync as i9n,statSync as o9n}from"node:fs";import{spawnSync as I9n}from"node:child_process";import{spawnSync as S9n}from"node:child_process";import{existsSync as O9n,readFileSync as M9n,statSync as N9n}from"node:fs";import{existsSync as X9n}from"node:fs";import{mkdir as J9n,readFile as K9n,writeFile as mVt}from"node:fs/promises";import{dirname as Y9n,extname as gVt,join as Z9n}from"node:path";import{spawnSync as AKn}from"node:child_process";import{mkdtempSync as bKn,rmSync as vKn,writeFileSync as AVt}from"node:fs";import{tmpdir as IKn}from"node:os";import{join as PHe}from"node:path";import{existsSync as nme,mkdirSync as TKn,mkdtempSync as vVt,readFileSync as S6e,rmSync as RKn,statSync as ime}from"node:fs";import{spawnSync as _Kn}from"node:child_process";import{basename as IVt,isAbsolute as xZt,join as _fe,relative as PKn}from"node:path";import{tmpdir as OHe}from"node:os";import{createHash as $Kn}from"node:crypto";import{spawn as jme}from"node:child_process";import{accessSync as qKn,constants as QKn,readFileSync as qme}from"node:fs";import{delimiter as HKn,extname as q_,isAbsolute as WKn,join as GKn,resolve as Qme}from"node:path";import{fileURLToPath as OZt,pathToFileURL as Qm}from"node:url";import{readdirSync as uYn}from"node:fs";import{basename as pYn,relative as fYn,resolve as hYn,sep as sL}from"node:path";import{readdirSync as bYn}from"node:fs";import{dirname as vYn,join as GZt,relative as IYn}from"node:path";import{randomBytes as OYn}from"node:crypto";import{existsSync as YZt}from"node:fs";import{extname as ZZt}from"node:path";import{execFile as XYn}from"node:child_process";import{promisify as JYn}from"node:util";import{posix as N6e}from"node:path";import{posix as TV}from"node:path";import{randomUUID as q6e}from"node:crypto";import{existsSync as _V,mkdirSync as $Ve,readFileSync as A7n,readdirSync as vhe,rmSync as Ihe,statSync as b7n,writeFileSync as v7n}from"node:fs";import{hostname as I7n,userInfo as k7n}from"node:os";import{dirname as Rer,join as cf}from"node:path";import{performance as DHe}from"node:perf_hooks";import{execFileSync as fZn}from"node:child_process";import{randomUUID as hZn}from"node:crypto";import{createRequire as wZn}from"node:module";import{createHash as xZn,randomUUID as CZn}from"node:crypto";import{appendFileSync as TZn,closeSync as RZn,existsSync as qfe,fstatSync as _Zn,mkdirSync as $V,openSync as PZn,readFileSync as $Zn,readSync as OZn,readdirSync as dV,rmSync as uV,writeFileSync as khe}from"node:fs";import{basename as UHe,dirname as dtr,join as Vd,resolve as MZn}from"node:path";import{closeSync as NZn,fstatSync as BZn,openSync as DZn,readSync as LZn}from"node:fs";import{createHash as jZn}from"node:crypto";import{closeSync as qZn,fstatSync as XVt,openSync as QZn,readSync as HZn}from"node:fs";import{resolve as WZn}from"node:path";import{existsSync as GZn,linkSync as VZn,mkdirSync as zZn,readFileSync as XZn,rmSync as VVe,statSync as JZn,writeFileSync as KZn}from"node:fs";import{hostname as utr}from"node:os";import{dirname as YZn}from"node:path";import{randomUUID as ZZn}from"node:crypto";import{createHash as eei,randomBytes as tei}from"node:crypto";import{chmodSync as rei,existsSync as nei,mkdirSync as ptr,readFileSync as iei,unlinkSync as ftr,writeFileSync as oei}from"node:fs";import{dirname as sei,join as Ez}from"node:path";import{execFile as htr,execFileSync as zVe}from"node:child_process";import{promisify as mtr}from"node:util";import{createHash as aei}from"node:crypto";import{existsSync as gtr,readFileSync as XVe,readlinkSync as lei}from"node:fs";import{hostname as XS}from"node:os";import{createHash as Ctr,randomBytes as kei,randomUUID as Ttr}from"node:crypto";import{closeSync as Rtr,existsSync as sze,fstatSync as Eei,fsyncSync as Sei,mkdirSync as aze,openSync as _tr,readFileSync as V6e,readSync as xei,writeFileSync as Ptr}from"node:fs";import{cpus as Cei}from"node:os";import{dirname as $tr,isAbsolute as Tei,join as aL,resolve as Rei}from"node:path";import{renameSync as Lei}from"node:fs";import{createHash as Uei}from"node:crypto";import{join as jei}from"node:path";import{createHash as Wei,randomUUID as Gei}from"node:crypto";import{link as Vei,lstat as zei,mkdir as Xei,open as qHe,readdir as Jei,unlink as nzt}from"node:fs/promises";import{join as QHe,resolve as Kei}from"node:path";import{join as jtr}from"node:path";import{createHash as J6e,randomUUID as K6e}from"node:crypto";import{appendFileSync as fV,closeSync as fti,existsSync as wI,fstatSync as hti,mkdirSync as ZD,openSync as mti,readFileSync as qtr,readSync as gti,readdirSync as szt,writeFileSync as Qtr}from"node:fs";import{cpus as wti}from"node:os";import{basename as yti,dirname as Htr,isAbsolute as Wtr,join as ui,relative as Ati,resolve as JV}from"node:path";import{closeSync as bti,fstatSync as vti,openSync as Iti,readSync as kti}from"node:fs";import{randomUUID as azt}from"node:crypto";import{closeSync as Sti,fstatSync as lzt,linkSync as xti,openSync as Cti,readSync as Tti,unlinkSync as Rti,writeFileSync as _ti}from"node:fs";import{basename as Pti,join as Gtr}from"node:path";import{spawn as $ti}from"node:child_process";import{openSync as Y6e,closeSync as Z6e,fstatSync as Oti,readSync as Mti}from"node:fs";import{StringDecoder as czt}from"node:string_decoder";import{setTimeout as Nti}from"node:timers/promises";import{execFileSync as Bti}from"node:child_process";import{randomUUID as Dti}from"node:crypto";import{existsSync as Lti,lstatSync as Fti,mkdirSync as Uti,readdirSync as jti,rmdirSync as qti,unlinkSync as Qti}from"node:fs";import{isAbsolute as Hti,join as lze,resolve as oz}from"node:path";import*as yge from"fs";import{exec as Qri}from"node:child_process";import{promisify as Hri}from"node:util";function x8n(e){return e.startsWith("local:")}function R8n(e){let t=e.trim().toLowerCase();return!t||t.length>64||Fzt.test(t)||!Lzt.test(t)?null:t}function _8n(e,t){if(typeof t=="boolean")return t;if(typeof t=="number")return e!=="protocol_version"||!Number.isInteger(t)||t<0||t>100?null:t;if(typeof t!="string")return null;let r=R8n(t);if(!r)return null;let n=YHe.get(e);return n||(n=new Set,YHe.set(e,n)),!n.has(r)&&n.size>=Bzt?"other":(n.add(r),r)}function P8n(e={}){let t={};for(let[r,n]of Object.entries(e)){if(Object.keys(t).length>=Nzt)break;if(!Uzt.has(r))continue;let i=_8n(r,n);i!==null&&(t[r]=i)}return Object.freeze(t)}function Ozt(e){if(KHe.size===0||!Dzt.test(e.name)||e.name.length>128)return;let t=e.kind==="event"?1:e.value??1;if(!Number.isFinite(t)||t<0)return;let r=Object.freeze({schemaVersion:Mzt,kind:e.kind,name:e.name,value:Math.min(t,Number.MAX_SAFE_INTEGER),timestamp:(e.timestamp??new Date).toISOString(),attributes:P8n(e.attributes)});for(let n of KHe)try{n(r)}catch{}}function HD(e,t=1,r){Ozt({kind:"counter",name:e,value:t,attributes:r})}function JHe(e,t,r){Ozt({kind:"histogram",name:e,value:t,attributes:r})}function qzt(e){Dw.delete(e)}async function $8n(e){try{let t=await aGe.stat(e);return{mtimeMs:t.mtimeMs,size:t.size}}catch(t){if(t.code==="ENOENT")return null;throw t}}function d6t(e,t){for(Dw.delete(e),Dw.set(e,t);Dw.size>Qzt;){let r=Dw.keys().next().value;if(r===void 0)break;Dw.delete(r)}}async function O8n(e,t,r){let n=await aGe.open(e,"r");try{let i=Math.min(r,t),o=Buffer.alloc(i);return await n.read(o,0,i,t-i),o.toString("utf-8")}finally{await n.close()}}async function lGe(e,t,r,n={}){let i=await $8n(e);if(!i)return Dw.delete(e),null;let o=Dw.get(e);if(o&&o.mtimeMs===i.mtimeMs&&o.size===i.size&&o.values.has(t))return Vfe.hits+=1,d6t(e,o),o.values.get(t);let s,a=n.tailBytes;if(a!==void 0&&i.size>a&&(Vfe.reads+=1,s=r(await O8n(e,i.size,a),!0)),s===void 0){let d;try{d=await aGe.readFile(e,"utf-8")}catch(u){if(u.code==="ENOENT")return Dw.delete(e),null;throw u}Vfe.reads+=1,s=r(d,!1)}let l=Dw.get(e),c=l&&l.mtimeMs===i.mtimeMs&&l.size===i.size?l:{mtimeMs:i.mtimeMs,size:i.size,values:new Map};return c.values.set(t,s),d6t(e,c),s}function M8n(e){return lGe(e,"text",t=>t)}async function IL(e){await tl.mkdir(e,{recursive:!0})}async function zd(e,t){let r=rn.dirname(e);await IL(r);let n=Math.random().toString(36).substring(2,15),i=`${e}.tmp.${process.pid}.${n}`;try{await tl.writeFile(i,t),await D8n(i,e),qzt(e)}finally{try{await tl.unlink(i)}catch{}}}async function D8n(e,t){for(let r=0;;r+=1)try{await tl.rename(e,t);return}catch(n){let i=n.code,o=mGe[r];if(process.platform!=="win32"||!i||!hGe.has(i)||o===void 0)throw n;await new Promise(s=>setTimeout(s,o))}}function kL(e,t,r=N8n){for(let n=0;;n+=1)try{r(e,t);return}catch(i){let o=i.code,s=mGe[n];if(process.platform!=="win32"||!o||!hGe.has(o)||s===void 0)throw i;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,s)}}async function TQe(e,t){let r=rn.dirname(e);await IL(r),await tl.appendFile(e,t+`
@@ -5518,7 +5518,7 @@ public static class XenoProcessTree {
5518
5518
  `,"utf8")})}appendEventOnce(e,t,r){this.readEvents(e).some(n=>n.type===t&&n.payload.operation_id===r.operation_id&&n.payload.run_id===r.run_id)||this.appendEvent(e,t,r)}withRunTransaction(e,t,r=!1,n=!1){if(this.transactions.has(e))return t();let i=this.runDir(e);if(!n&&!wI(ui(i,"workflow.json")))return null;ZD(i,{recursive:!0});let o,s;try{try{o=hd(ui(i,"workflow-scheduler.lock"),`workflow-scheduler:${e}`,qo().producerVersion),s=hd(ui(i,"workflow.lock"),`workflow:${e}`,qo().producerVersion)}catch(l){if(r&&_h(l))return this.readRunWithProgress(e);throw l}this.transactions.add(e);let a;try{a=t()}catch(l){if(r&&l instanceof Ks&&l.code==="WORKFLOW_GOVERNOR_UNAVAILABLE"&&_h(l.cause))return this.readRunWithProgress(e);throw l}return a?this.readRunWithProgress(e)??this.withProgress(a):null}finally{this.transactions.delete(e),s?.release(),o?.release()}}withWorkflowLock(e,t,r){if(this.transactions.has(e))return r();ZD(this.runDir(e),{recursive:!0});let n=hd(ui(this.runDir(e),"workflow.lock"),`workflow:${e}:${t}`,qo().producerVersion);try{return r()}finally{n.release()}}write(e){let t=jS(e.workflowRunId,this.runsDir);if(t){let o=e.status==="cancelled"&&e.cancellation?.completedAt;e={...e,status:o?"cancelled":"cancelling",cancellation:{...e.cancellation,...t},...o?{}:{endedAt:void 0}}}let r=e.schemaVersion===2?vI(e):void 0,n=e.schemaVersion===2?{...e,limits:e.limits??pzt(e),usage:r?.usage??e.usage,phases:Wfe(e),childRecords:NV(e)}:e,i=qD(n);this.withWorkflowLock(e.workflowRunId,"write",()=>{mzt(ui(this.runDir(e.workflowRunId),"workflow.json"),i)})}withProgress(e){let t=vI(e);return{...e,limits:e.limits??pzt(e),usage:t.usage,phases:Wfe(e),childRecords:NV(e),progress:t}}runDir(e){return ui(this.runsDir,yti(e))}};hme();kGe();DI();hs();bos=2*1024*1024;SL();Kme();Kme();gn();AL();tb();gn();Fri=["initialize","capabilities.get","thread.start","thread.get","thread.list","thread.resume","thread.archive","thread.delete","turn.start","turn.get","turn.lookup","turn.steer","turn.interrupt","events.subscribe","events.unsubscribe","events.poll","events.replay","permission.respond","integrations.list","execution.acquire","execution.renew","execution.release","handoff.prepare","handoff.claim","handoff.complete","handoff.status","handoff.cancel"];hs();vos=new Set(Fri);Ame();Ime();hz();gn();Oc();ic();yz();xzt=new Map;Ome(jri);LGe();gn();Oc();Ime();hz();LGe();Ame();L_();vme();ic();hz();Ime();Mme();IJt();vme();_Jt();Xd();Pa();Ios=64*1024*1024,qri=8*1024*1024,kos=4*Math.ceil(qri/3);ic();DVe();Q_();Yme();Eos=300*1e3;ic();dz();SL();atr();j_();nVe();FVe();atr();SL();AL();SL();Q_();Oc();DI();Yme();F_();Xd();GS();ic();str();DI();UVe();kme();Oc();Oc();DI();hs();Sos=1024*1024;F_();ic();zS();ic();Tos={enabled:!0,executionTimeout:3e4,maxMemory:50*1024*1024,allowedHosts:[],blockedPaths:[]};gn();ic();Ros=Hri(Qri);ic();_os=1024*1024;gn();ic();SL();Q_();BI();OI();Ohe();dz();iGe=1e8,oGe=10080*60*1e3,df=class extends Error{constructor(e,t){super(t),this.code=e,this.name="SessionBudgetError"}code};Oz=class{quota;constructor(e=jei(Kn(),"session-token-quotas")){this.quota=new Zei(e)}scope(e){return{workspace:{id:Uei("sha256").update(`agent-session\0${e.sessionId}`).digest("hex"),generation:"agent-session-v1"},goal:{id:e.sessionId,generation:e.createdAt}}}async remainingTokens(e){return e.budget?.maxTokens===void 0?null:this.quota.remainingTokens(this.scope(e))}async prepare(e,t){let r=e.budget;if(!r)return;let n=t.now??Date.now();if(r.deadlineAt!==void 0&&n>=Date.parse(r.deadlineAt))throw new df("SESSION_DEADLINE_PASSED",`This background session's deadline passed at ${r.deadlineAt}, so no new model request was started.`);if(r.maxTokens===void 0)return;let i=this.scope(e),o=await this.quota.policy(i);if(o?.limits.tokensLifetime!==r.maxTokens){if(typeof o?.limits.tokensLifetime=="number"&&o.limits.tokensLifetime<r.maxTokens)throw new df("SESSION_BUDGET_INVALID","This session\u2019s token budget was raised after it started; that is refused.");await this.quota.setPolicy(i,{requestsPerMinute:null,tokensPerDay:null,tokensLifetime:r.maxTokens},o?.revision??0)}let s=await this.quota.remainingTokens(i);if(s!==null&&s<1)throw new df("SESSION_TOKEN_BUDGET_SPENT",`This background session has spent its ${r.maxTokens.toLocaleString("en-US")}-token budget, so no new model request was started.`);let a=x8n(t.model),l=t.inner??(a?t.createLocalProvider():t.agent.createSoftBudgetCloudProvider());return{scope:i,enforcement:a?"hard":"soft",provider:xQn(l,this.quota,i,a?{}:{enforcement:"soft"})}}},Czt=1,zHe=1,Wri=512,Gri=128,sGe=4*1024*1024;bge="Worker process is no longer running and did not record a terminal status.",Kri="agent-host",Arr="The process running this stopped before it finished; it runs again, as a new attempt, when a host is running.";vt=class{constructor(e=fze()){this.runsDir=e,$V(this.runsDir,{recursive:!0}),$V(this.activeMarkerDir(),{recursive:!0})}runsDir;nextActiveMarkerName=null;create(e){let t=zs(),r=Age(e.budget??e.agent?.budget,Date.parse(t)),n=vrr(),i=Vd(this.runsDir,n);$V(i,{recursive:!0});let o=Vd(i,"events.jsonl"),s={schemaVersion:Czt,runId:n,sessionId:n,rootRunId:e.rootRunId??n,...e.parentRunId?{parentRunId:e.parentRunId}:{},cwd:pze(e.cwd),workspaceId:zri(e.cwd),prompt:e.prompt,...e.title?{title:e.title}:{},status:e.status??"starting",model:e.model,...e.effort?{effort:e.effort}:{},...e.agent?{agent:e.agent}:{},...e.git?{git:e.git}:{},permissionMode:e.permissionMode,...e.executionSecurity?{executionSecurity:e.executionSecurity}:{},...e.capabilityPolicy?{capabilityPolicy:e.capabilityPolicy}:{},...e.configSnapshot?{configSnapshot:e.configSnapshot}:{},...LI(e.cliVersion),createdAt:t,updatedAt:t,lastActivityAt:t,pinned:!!e.pinned,attachedClients:0,cliVersion:e.cliVersion,stdoutPath:Vd(i,"stdout.log"),stderrPath:Vd(i,"stderr.log"),eventsPath:o,usage:Xri(),children:[],tags:e.tags??[],...r?{budget:r}:{},execution:e.execution??{surface:e.resourceSurface??(e.tags?.includes("workflow")?"workflow-child":"background-run"),priorityClass:e.resourcePriority??(e.tags?.includes("workflow")?"workflow":"background"),logicalChildId:n,attemptId:`${n}:attempt-1`,idempotencyKey:`${n}:attempt-1`,attempt:1,providerId:W_(e.model,e.configSnapshot?.baseURL),recoveryMode:e.recoveryMode??"manual",reservedTokens:4096}};return khe(s.stdoutPath,"","utf8"),khe(s.stderrPath,"","utf8"),khe(s.eventsPath,"","utf8"),this.write(s),this.appendEvent(n,"run_created",{cwd:s.cwd,model:s.model,...s.agent?{agent:s.agent}:{},...s.git?{git:s.git}:{},permissionMode:s.permissionMode,...s.executionSecurity?{executionSecurity:s.executionSecurity}:{},...s.capabilityPolicy?{capabilityPolicy:s.capabilityPolicy}:{},...s.configSnapshot?{configSnapshot:s.configSnapshot}:{},pinned:s.pinned}),s}get(e){let t=gI(this.recordPath(e));return t?this.refreshRecordStatus(t):null}getRaw(e){return gI(this.recordPath(e))}list(e={}){if(!qfe(this.runsDir))return[];let t=dV(this.runsDir,{withFileTypes:!0}).filter(r=>r.isDirectory()&&r.name.startsWith("run_")).map(r=>xhe(gI(this.recordPath(r.name)))).filter(r=>r!==null).filter(r=>e.all||!e.cwd||lL(r,e.cwd)).filter(r=>!e.status||e.status.includes(r.status)).sort(Gfe);return typeof e.limit=="number"&&e.limit>0?t.slice(0,e.limit):t}listActive(e={}){let t=this.activeMarkerDir();if(!qfe(t))return[];let r=dV(t,{withFileTypes:!0}).filter(n=>n.isFile()&&n.name.endsWith(".json")).map(n=>gI(Vd(t,n.name))?.runId).filter(n=>typeof n=="string").map(n=>{try{return this.get(n)}catch(i){if(Jri(i))return this.getRaw(n);throw i}}).filter(n=>n!==null&&!DV(n.status)).filter(n=>e.all||!e.cwd||lL(n,e.cwd)).filter(n=>!e.status||e.status.includes(n.status)).sort(Gfe);return typeof e.limit=="number"&&e.limit>0?r.slice(0,e.limit):r}markSpawned(e,t,r,n,i){return this.update(e,o=>({...o,status:"running",workerPid:t,...n?{workerIdentity:n}:{},...i?{workerLease:i}:{},resourceQueue:void 0,workerVersion:r,startedAt:o.startedAt??zs(),lastActivityAt:zs()}))}markStarted(e,t){return this.update(e,r=>({...r,status:"running",workerPid:t.pid,...t.workerIdentity?{workerIdentity:t.workerIdentity}:{},...t.executor?{executor:t.executor}:{},...t.workerLease?{workerLease:t.workerLease}:{},workerVersion:t.cliVersion,...t.model?{model:t.model}:{},...t.effort?{effort:t.effort}:{},startedAt:r.startedAt??zs(),lastActivityAt:zs()}))}markCompleted(e,t,r){let n=!1,i=this.update(e,o=>r&&JSON.stringify(o)!==JSON.stringify(r)?o:(n=!0,{...o,status:t.status,...t.statusReason?{statusReason:t.statusReason}:{},exitCode:t.exitCode??null,usage:t.usage??o.usage,endedAt:zs(),lastActivityAt:zs()}));return n?i:null}markSpawnRefused(e,t){return this.update(e,r=>r.execution?.attemptId!==t.attemptId||(r.workerPid??0)>0?r:{...r,status:"cancelled",statusReason:"Workflow cancellation prevented worker spawn.",endedAt:zs(),spawnRefusal:{permitId:t.permitId,fencingToken:t.fencingToken,attemptId:t.attemptId,recordedAt:zs()}})}listRaw(e={}){if(!qfe(this.runsDir))return[];let t=dV(this.runsDir,{withFileTypes:!0}).filter(r=>r.isDirectory()&&r.name.startsWith("run_")).map(r=>this.getRaw(r.name)).filter(r=>r!==null).filter(r=>e.all||!e.cwd||lL(r,e.cwd)).filter(r=>!e.status||e.status.includes(r.status)).sort(Gfe);return typeof e.limit=="number"&&e.limit>0?t.slice(0,e.limit):t}listReconciliationCandidates(e=[],t={}){let r=new Map,n=f=>{f&&(this.syncReconciliationMarker(f),DV(f.status)||r.set(f.runId,f))},i=Math.max(1,Math.min(1e4,Math.trunc(t.activeScanLimit??Gri))),o=dV(this.activeMarkerDir(),{withFileTypes:!0}).filter(f=>f.isFile()&&f.name.endsWith(".json")).map(f=>f.name).sort((f,h)=>h.localeCompare(f)),s=this.nextActiveMarkerName,a=s?Math.max(0,o.findIndex(f=>f<=s)):0,l=o.slice(a,a+i);this.nextActiveMarkerName=o[a+l.length]??null;for(let f of l){let h=Vd(this.activeMarkerDir(),f),m=gI(h);if(typeof m?.runId!="string"){uV(h,{force:!0});continue}let g=this.getRaw(m.runId);if(!g||DV(g.status)){uV(h,{force:!0});continue}r.set(g.runId,g)}for(let f of e){let h=this.getRaw(f);h&&(this.syncReconciliationMarker(h),r.set(h.runId,h))}let c=Math.max(1,Math.min(1e4,Math.trunc(t.migrationScanLimit??Wri))),d=gI(this.reconciliationScanPath()),u=0,p=d?.schemaVersion===zHe&&d.complete;if(!p){let f=dV(this.runsDir,{withFileTypes:!0}).filter(y=>y.isDirectory()&&y.name.startsWith("run_")).map(y=>y.name).sort((y,A)=>A.localeCompare(y)),h=d?.schemaVersion===zHe?d.nextRunId:void 0,m=h?Math.max(0,f.findIndex(y=>y<=h)):0,g=f.slice(m,m+c);for(let y of g)n(this.getRaw(y));u=g.length;let w=f[m+g.length];p=w===void 0,QD(this.reconciliationScanPath(),{schemaVersion:zHe,...w?{nextRunId:w}:{},complete:p,updatedAt:zs()})}return{records:[...r.values()].sort(Gfe),scanned:u,migrationComplete:p}}markQueuedForRecovery(e,t,r){let n=!1,i=this.update(e,o=>r&&JSON.stringify(o)!==JSON.stringify(r)?o:(n=!0,brr(o,t)));return n?i:null}setWorkerLease(e,t){return this.update(e,r=>({...r,workerLease:t}))}markQueuedForResources(e,t){return this.update(e,r=>({...r,status:"queued",statusReason:t.reason,resourceQueue:{reason:t.reason,priorityClass:t.priorityClass,queuedAt:zs(),...t.estimatedEligibleAt?{estimatedEligibleAt:t.estimatedEligibleAt}:{}}}))}compareAndUpdate(e,t,r){return this.update(e,n=>t(n)?r(n):n)}markCancelled(e,t){return this.update(e,r=>({...r,status:"cancelled",statusReason:t,endedAt:zs(),lastActivityAt:zs()}))}markSkipped(e,t="Skipped by user."){return this.update(e,r=>({...r,status:"skipped",statusReason:t,endedAt:zs(),lastActivityAt:zs()}))}markPaused(e,t="Paused by user."){let r=this.update(e,n=>({...n,status:"paused",statusReason:t,lastActivityAt:zs()}));return r&&this.appendEvent(e,"run_paused",{reason:t}),r}markResumed(e,t="Resumed by user."){let r=this.update(e,n=>{let i={...n,status:"running",statusReason:t,lastActivityAt:zs()};return delete i.endedAt,delete i.exitCode,i});return r&&this.appendEvent(e,"run_resumed",{reason:t}),r}setPinned(e,t){let r=this.update(e,n=>({...n,pinned:t,lastActivityAt:zs()}));return r&&this.appendEvent(e,t?"run_pinned":"run_unpinned",{pinned:t}),r}appendEvent(e,t,r={}){let n=this.lock(e);try{let i=gI(this.recordPath(e));i&&PI(e,i.workerLease);let o=i?.eventsPath??Vd(this.runsDir,e,"events.jsonl");$V(dtr(o),{recursive:!0});let s={schemaVersion:Czt,runId:e,type:t,timestamp:zs(),payload:r};TZn(o,JSON.stringify(s)+`
5519
5519
  `,"utf8"),i&&QD(this.recordPath(e),{...i,updatedAt:s.timestamp,lastActivityAt:s.timestamp})}finally{n.release()}}readEvents(e){let t=this.get(e);if(!t||!qfe(t.eventsPath))return[];let r=PZn(t.eventsPath,"r");try{let n=_Zn(r).size;if(n>sGe)throw new Error(`Run event journal exceeds the ${sGe} byte full-read limit; use readEventPage() or \`xeno agents events --page\` to retrieve it in bounded pages.`);let i=Buffer.alloc(n),o=0;for(;o<n;){let s=OZn(r,i,o,n-o,o);if(s===0)throw new Error("Run event journal changed during read; retry the operation.");o+=s}return i.toString("utf8").split(/\r?\n/).map(s=>s.trim()).filter(Boolean).map(s=>{try{return JSON.parse(s)}catch{return null}}).filter(s=>s!==null)}finally{RZn(r)}}tailEvents(e,t=80){let r=this.get(e);return r?xL(r.eventsPath,t):[]}readEventPage(e,t={}){let r=this.get(e);return r?kz(r.eventsPath,t):null}delete(e){uV(this.activeMarkerPath(e),{force:!0}),uV(Vd(this.runsDir,e),{recursive:!0,force:!0})}refreshRecordStatus(e){let t=xhe(e);if(!t||t===e)return e;let r;try{r=this.lock(e.runId,e.cliVersion)}catch(n){if(_h(n))return this.getRaw(e.runId);throw n}try{let n=this.getRaw(e.runId);if(!n)return null;let i=xhe(n);return!i||i===n?n:(PI(e.runId,n.workerLease),QD(this.recordPath(e.runId),i),this.syncReconciliationMarker(i),i)}finally{r.release()}}update(e,t){let r=this.lock(e);try{let n=gI(this.recordPath(e));if(!n)return null;PI(e,n.workerLease);let i=t(n);return i===n?n:(i.updatedAt=zs(),QD(this.recordPath(e),i),this.syncReconciliationMarker(i),i)}finally{r.release()}}write(e){let t=this.lock(e.runId,e.cliVersion);try{QD(this.recordPath(e.runId),e),this.syncReconciliationMarker(e)}finally{t.release()}}lock(e,t=qo().producerVersion){return hd(Vd(this.runDir(e),"run.lock"),`run:${e}`,t)}recordPath(e){return Vd(this.runsDir,XHe(UHe(e)),"run.json")}runDir(e){return Vd(this.runsDir,XHe(UHe(e)))}activeMarkerDir(){return Vd(this.runsDir,".active")}activeMarkerPath(e){return Vd(this.activeMarkerDir(),`${XHe(UHe(e))}.json`)}reconciliationScanPath(){return Vd(this.runsDir,".reconciliation-scan.json")}syncReconciliationMarker(e){let t=this.activeMarkerPath(e.runId);if(DV(e.status)){uV(t,{force:!0});return}let r={schemaVersion:1,runId:e.runId,status:e.status,updatedAt:e.updatedAt},n=gI(t);n?.schemaVersion===r.schemaVersion&&n.runId===r.runId&&n.status===r.status&&n.updatedAt===r.updatedAt||QD(t,r)}},UI=1});var rl=ye(()=>{"use strict";$a();Ao();Uo();ec();oD();WVe({producerVersion:Pe,defaultModel:()=>Pt().model?.trim()||Gr,workerInvocation:()=>{let e=process.argv[1];if(!e)throw new Error("Cannot determine current CLI entrypoint for background run.");return{command:process.execPath,prefix:[e]}},recordCounter:(e,t,r)=>ka(e,t,r),recordHistogram:(e,t,r)=>tf(e,t,r)})});var Mz=ye(()=>{"use strict";rl();$a()});import{createHash as eni,randomUUID as tni}from"node:crypto";import{setTimeout as rni}from"node:timers/promises";function nni(){return`delegation-${Date.now().toString(36)}-${tni().slice(0,8)}`}function ini(e,t){return async r=>{let n=e.createToolRegistry?void 0:U5(t,r.task.id);return l_((await ER({cwd:e.cwd,apiKey:e.apiKey,baseURL:e.baseURL,authorizeRequest:e.authorizeRequest,model:e.model,...e.fallbackModels?{fallbackModels:e.fallbackModels}:{},...e.effort?{effort:e.effort}:{},maxTokens:hS(r.task.maxTokens,e.maxOutputTokens),turnTokenBudget:r.task.maxTokens,maxIterations:r.task.maxIterations,parentSystemPrompt:e.parentSystemPrompt,parentExecutionMode:e.parentExecutionMode,subagentRole:r.task.role,permissionEngine:e.permissionEngine,toolRegistry:e.createToolRegistry?.(),...n?{ownerSessionId:n}:{},...e.auditLogger?{session:{auditLogger:e.auditLogger}}:{},onIteration:r.onIteration,onToolStart:r.onToolStart,onToolWillExecute:r.onToolWillExecute,onToolEnd:r.onToolEnd})).agent,n)}}async function oni(e){for(;;){if(e.signal?.aborted){e.governor.cancelQueued(e.request.requestId);let r=new Error("Delegated branch admission was cancelled.");throw r.name="AgentInterruptedError",r}let t=e.governor.acquire(e.request);if(t.status==="acquired")return t.permit;if(t.status==="active")throw new Ks("WORKFLOW_CONCURRENCY_LIMIT","Delegated branch attempt is already active.");if(t.status==="rejected")throw new Ks(t.code,t.reason);if(Date.now()>=e.deadline)throw e.governor.cancelQueued(e.request.requestId),new Ks("WORKFLOW_QUEUE_EXPIRED","Delegated branch exceeded its admission deadline.");await rni(50,void 0,{signal:e.signal})}}function sni(e,t,r){let n=e.run.bind(e),i=!1,o=a=>{i||(i=!0,t.settle({permitId:r.permitId,fencingToken:r.fencingToken,outcome:a,actualTokens:e.tokenUsage.total}))};e.run=async a=>{try{let l=await n(a);return o("completed"),l}catch(l){throw o(l instanceof Error&&l.name==="AgentInterruptedError"?"cancelled":"failed"),l}};let s=e;if(s.cancelCurrentTurn){let a=s.cancelCurrentTurn.bind(s);s.cancelCurrentTurn=()=>(o("cancelled"),a())}else if(s.cancel){let a=s.cancel.bind(s);s.cancel=()=>(o("cancelled"),a())}return e}async function Nz(e){e=oG(e);let t=new _l,r=e.rootTraceId??nni(),n=W_(e.model,e.baseURL),i=e.apiKey?cge({providerId:n,endpoint:e.baseURL,credential:e.apiKey,salt:dge()}):_L(n,process.env,e.baseURL),o=e.createBranchAgent??ini(e,r),s=Date.now()+e.timeoutMs,a=async l=>{let c=l.task,d=`${r}:${c.id}`,u=`${d}:attempt-1`,p=eni("sha256").update(`${r}\0${c.id}\0${c.prompt}`).digest("hex"),f=await oni({governor:t,request:{requestId:`admit:${d}:attempt-1`,operationId:d,surface:"delegated-branch",priorityClass:"foreground",runId:r,parentId:r,providerId:n,...i?{credentialFingerprint:i}:{},logicalChildId:d,attemptId:u,idempotencyKey:p,reservedTokens:c.maxTokens,runConcurrencyLimit:e.branchPolicy?.maxConcurrentBranches,runAttemptLimit:e.branchPolicy?.roles?.length,runTokenLimit:e.maxTotalTokens,queueDeadlineAt:new Date(s).toISOString()},deadline:s,signal:c.signal??e.signal});if(!t.claimEffect({permitId:f.permitId,fencingToken:f.fencingToken,effectKey:`delegated:${f.operationId}`}))throw t.settle({permitId:f.permitId,fencingToken:f.fencingToken,outcome:"duplicate_branch_suppressed"}),new Ks("WORKFLOW_CONCURRENCY_LIMIT","Duplicate delegated branch execution was suppressed.");try{let h=await o(l);return t.commitEffect({permitId:f.permitId,fencingToken:f.fencingToken,effectKey:`delegated:${f.operationId}`}),sni(h,t,f)}catch(h){throw t.settle({permitId:f.permitId,fencingToken:f.fencingToken,outcome:"branch_creation_failed"}),h}};if(e.hostDelegation){if(e.createBranchAgent)throw new Error("Host-routed delegation and a local createBranchAgent are mutually exclusive: the branch either executes on the Agent host or in this process. Pass one.");if(typeof e.onToolWillExecute=="function")throw new Error("Host-routed delegation cannot honour onToolWillExecute: it delays tool execution until it resolves, and a branch running on the Agent host does not wait for this process. A hook that cannot delay is not the hook you asked for, so it is refused rather than silently downgraded. Remove it to delegate on the host, or run without host delegation.");if(typeof e.onIteration=="function")throw new Error("Host-routed delegation cannot report onIteration: the host mints no iteration-bearing runtime event, so there is nothing to read \u2014 unlike onToolStart/onToolEnd, which now fire. Remove onIteration to delegate on the host, or run without host delegation.");return bue({...e,rootTraceId:r,createBranchAgent:a6t({...e.hostDelegation,rootTraceId:r,deadline:s,...e.signal===void 0?{}:{signal:e.signal}})})}return bue({...e,rootTraceId:r,createBranchAgent:a})}var Err=ye(()=>{"use strict";st();l6t();zG();iI();Mz();st()});var $h=ye(()=>{"use strict";rl();$a()});var Bz=ye(()=>{"use strict";rl();$a()});function Oh(e={}){let t=e.cwd??process.cwd(),r=e.store??new xt,n=(i,o={})=>{let s=r.readEvents(i);return o.limit&&o.limit>0?s.slice(-o.limit):s};return{create:i=>typeof i=="string"?r.createPromptAuthoredDefinition(t,i):r.createDefinitionFromInput(t,i),validate:i=>typeof i=="string"?r.resolveDefinition(t,i):r.validateDefinitionInput(t,i),run:(i,o="",s={})=>{let a=Pl();if(a)throw new Error(a);return r.startRun(t,i,o,s)},inspect:i=>r.getRun(i),events:n,eventsJsonl:(i,o={})=>n(i,o).map(s=>JSON.stringify(s)).join(`
5520
5520
  `),pause:i=>r.pause(i),resume:i=>{let o=Pl();if(o)throw new Error(o);return r.resume(i)},cancel:i=>r.cancel(i),retryChild:(i,o)=>{let s=Pl();if(s)throw new Error(s);return r.retryChild(i,o)},skipChild:(i,o)=>r.skipChild(i,o),save:(i,o={})=>r.save(i,{cwd:t,destination:o.destination??"project",...o.name?{name:o.name}:{}})}}var ani,Srr=ye(()=>{"use strict";$h();Bz();ani={create:(e,t)=>Oh(t).create(e),validate:(e,t)=>Oh(t).validate(e),run:(e,t,r,n)=>Oh(n).run(e,t,r),inspect:(e,t)=>Oh(t).inspect(e),events:(e,t,r)=>Oh(r).events(e,t),eventsJsonl:(e,t,r)=>Oh(r).eventsJsonl(e,t),pause:(e,t)=>Oh(t).pause(e),resume:(e,t)=>Oh(t).resume(e),cancel:(e,t)=>Oh(t).cancel(e),retryChild:(e,t,r)=>Oh(r).retryChild(e,t),skipChild:(e,t,r)=>Oh(r).skipChild(e,t),save:(e,t,r)=>Oh(r).save(e,t)}});var xrr={};$o(xrr,{AGENT_DAEMON_PROTOCOL_VERSION:()=>j2,AGENT_EFFORT_LEVELS:()=>vse,AGENT_PERMISSION_MODES:()=>Ise,AGENT_PROFILE_EXTERNAL_ACTIONS:()=>S0,APP_SERVER_PROMPT_BEARING_PARAMS:()=>rse,ARCHITECT_CAPABILITIES:()=>_qt,ARCHITECT_TOOL_NAMES:()=>Rqt,ARTIFACT_MAX_REVISION_BYTES:()=>g2,ARTIFACT_PAGE_CSP:()=>Jje,ARTIFACT_TOOL_CATEGORIES:()=>G1,ARTIFACT_TOOL_ORIGIN:()=>Gje,ARTIFACT_VIEWER_BASE_PORT:()=>Xje,AgentDaemonClient:()=>dUt,AgentDaemonServer:()=>cUt,AgentDebugger:()=>Zqt,AgentDefinitionLoader:()=>die,AgentDefinitionResolver:()=>uBe,AgentEvaluator:()=>e8t,AgentEventStore:()=>P4e,AgentFileSystemError:()=>mh,AgentHookRunner:()=>QBe,AgentInterruptedError:()=>ji,AgentLoop:()=>_5,AgentProfileValidationError:()=>n0,AgentProtocol:()=>N3t,AgentRegistry:()=>M3t,AgentRunController:()=>lUt,AgentRunError:()=>poe,AgentRunStore:()=>N4e,AppAgentFactory:()=>Wqt,AppContextInjector:()=>Iqe,AppContextManager:()=>gue,AppServerProtocolError:()=>Ye,AppServerRemoteError:()=>Xl,ArtifactCloudClient:()=>ZLt,ArtifactCloudError:()=>Cc,ArtifactWorkspace:()=>eFt,AuditLogger:()=>SR,AutoCheckpointHandler:()=>CR,AutoMemory:()=>PDe,AutoPermissionClassifier:()=>BUe,BUILT_IN_XENO_PROVIDER_PRESETS:()=>I3e,BackgroundProcessManager:()=>Die,COMPAT_TOOL_ALIASES:()=>Y1,CONFIG_VERSION:()=>AH,CheckpointManager:()=>Mm,CliGovernedAutomationRuntime:()=>bde,CodeValidator:()=>Yqt,CommandHookRunner:()=>HBe,CompletionGuardRegistry:()=>qce,ContainmentApprovalError:()=>vn,ContainmentCertificationError:()=>bn,ContextManager:()=>vR,ConversationStore:()=>H3t,CrossAppRouter:()=>O3t,CrossAppRouterError:()=>oH,DEFAULT_API_KEY:()=>ld,DEFAULT_IMAGE_MODEL:()=>EH,DEFAULT_MEMORY_BUDGETS:()=>Tae,DEFAULT_MODEL:()=>Gr,DEFAULT_PROMPT_SECTIONS_TOKEN_BUDGET:()=>UH,DEFAULT_PROTECTED_STATE_KEY_NAME:()=>Zce,DEFAULT_PROTECTED_STATE_SERVICE:()=>Yce,DEFAULT_SUBAGENT_BRANCH_POLICY:()=>R0,DEFAULT_SUBAGENT_REMOTE_MCP_BY_ROLE:()=>P5,DEFAULT_SUBAGENT_ROLES:()=>W1,DEFAULT_SUBAGENT_ROLE_PRECEDENCE:()=>U0,DEFAULT_SUBAGENT_TEAM_PRESET:()=>zp,DESCENDANT_HINT_DEFAULT_MAX_DEPTH:()=>Gce,DESCENDANT_HINT_DEFAULT_MAX_RESULTS:()=>Wce,DIRECT_SHELL_CONTEXT_WARNING:()=>Oae,DISPATCH_AGENT_ERROR_CODES:()=>Ja,DOCS_CAPABILITIES:()=>Lqt,DOCS_TOOL_NAMES:()=>Dqt,DualLLMProvider:()=>v3e,DurableXenoCapabilityLeaseRegistry:()=>LUe,DurableXenoCoordinationStore:()=>V4e,ENGINE_CAPABILITIES:()=>Mqt,ENGINE_TOOL_NAMES:()=>Oqt,ENTER_PLAN_MODE_TOOL_NAME:()=>C4e,EXIT_PLAN_MODE_TOOL_NAME:()=>T4e,ElectronAgentBridge:()=>_3t,EpisodicStore:()=>m4e,ExecutionGovernance:()=>j4e,ExecutionSecurityError:()=>Ud,ExternalActionGate:()=>vae,FALLBACK_MODELS:()=>dR,FILE_SYSTEM_PORT_TOOLS:()=>OFe,FILE_SYSTEM_PORT_UNAFFECTED_TOOLS:()=>hce,FileQuotaAuthority:()=>X4t,FileXenoArtifactRepository:()=>Ade,FileXenoProviderConnectionStore:()=>H4t,FileXenoShareRegistry:()=>ajt,HIGH_RISK_PERMISSIONS:()=>dqe,HookDecisionError:()=>J2,HookRunner:()=>tae,HookRuntime:()=>rae,HttpHookRunner:()=>WBe,IDENTITY_PATHS:()=>hA,INTERRUPTED_QUESTION_ERROR_CODE:()=>fle,INTERRUPTED_TOOL_RESULT_TEXT:()=>aB,IdentityLoader:()=>$A,IdentityResolver:()=>OA,InMemoryXenoArtifactRepository:()=>mde,InMemoryXenoCapabilityLeaseRegistry:()=>T1,InMemoryXenoTelemetryCollector:()=>mDe,InteractiveChatTurnGovernance:()=>QFe,InteractiveTurnGovernance:()=>NH,JsonSchemaCompilationError:()=>lB,LlmClient:()=>Nce,LocalLLMProvider:()=>kqe,LogLevel:()=>Cie,MANIFEST_FILENAME:()=>dH,MAX_CONTAINMENT_APPROVAL_AGE_MS:()=>Jce,MAX_CONTAINMENT_CERTIFICATION_BYTES:()=>hH,MAX_CONTAINMENT_CERTIFICATION_LIFETIME_MS:()=>Lse,MAX_DIRECT_SHELL_OUTPUT_CHARS:()=>RDe,MAX_HOST_WEB_FETCHES_PER_TURN:()=>MH,MAX_HOST_WEB_SEARCHES_PER_TURN:()=>OH,MAX_PLAN_CHARS:()=>eUt,MAX_READ_FILE_BYTES:()=>JN,MAX_READ_OUTPUT_CHARS:()=>IH,MCPCatalogError:()=>S1,MCPConnectionError:()=>zg,MCPHttpTransportError:()=>Ls,MCPManager:()=>_ue,MCPMessageTooLargeError:()=>Eue,MCPOAuthClient:()=>rqt,MCPServer:()=>sqt,MCP_APPS_EXTENSION_ID:()=>V6,MCP_APP_MIME_TYPE:()=>lW,MCP_APP_RESOURCE_SCHEME:()=>iqt,MCP_MAX_CATALOG_ENTRIES:()=>cH,MCP_PROTOCOL_VERSION:()=>eR,MCP_STDIO_MAX_MESSAGE_CHARS:()=>Z3t,MCP_SUPPORTED_PROTOCOL_VERSIONS:()=>xue,MEMORY_FILES:()=>Rae,MODEL_CATALOG_ACCOUNT_AUTH_VERSION:()=>sB,MODEL_REQUEST_TIMEOUT_PHASES:()=>Ece,MOTION_CAPABILITIES:()=>Xqt,MOTION_SYSTEM_PROMPT:()=>D3e,MOTION_TOOL_NAMES:()=>zqt,MemoryManager:()=>gw,MessageFlow:()=>Dce,ModelProviderRegistry:()=>Aae,ModelRequestTimeoutError:()=>i6,ModelResponseIncompleteError:()=>c0,MonitorManager:()=>hUt,MonitorStopTool:()=>gUt,MonitorTool:()=>mUt,NOTEBOOK_READ_NOT_A_NOTEBOOK:()=>Gae,NOTES_CAPABILITIES:()=>Hqt,NOTES_TOOL_NAMES:()=>Qqt,OtelExporter:()=>yUt,PATCH_DIRECTIVES:()=>ss,PATCH_ENVELOPE_BEGIN:()=>G2,PATCH_ENVELOPE_END:()=>y0,PATCH_LINE_PREFIXES:()=>cw,PEER_MESSAGE_DEFAULT_TTL_MS:()=>eoe,PEER_PRESENCE_TTL_MS:()=>Zie,PEER_SCHEMA_VERSION:()=>Em,PEER_TASK_TERMINAL_STATUSES:()=>gce,PIXEL_CAPABILITIES:()=>Vqt,PIXEL_SYSTEM_PROMPT:()=>B3e,PIXEL_TOOL_NAMES:()=>Gqt,PLUGIN_TRUST_STORE_FILENAME:()=>tR,PLUGIN_TRUST_STORE_SCHEMA_VERSION:()=>W5,PROCESS_TREE_ADAPTERS:()=>J5e,PROJECT_STATE_VERSION:()=>pae,PROVIDER_TOOL_NAME_PATTERN:()=>Rce,PeerMessagingStore:()=>Xp,PermissionEngine:()=>wh,PluginEventBus:()=>uqe,PluginHost:()=>Z6,PluginManager:()=>wqt,PluginMarketplace:()=>Fue,PluginSandbox:()=>cqe,PluginSettingsManager:()=>pqt,PluginToolBuilder:()=>uqt,ProfileManager:()=>k6,PromptHookRunner:()=>qBe,PromptSectionRegistry:()=>jce,ProtectedFileWriteError:()=>dw,ProviderError:()=>er,QueryLifecycle:()=>Lce,QuotaAcknowledgementError:()=>_ce,QuotaError:()=>Dr,READ_FILE_TOO_LARGE:()=>vH,READ_IMAGE_INVALID_CONTENT:()=>UW,READ_IMAGE_PREVIEW_UNAVAILABLE:()=>FW,READ_IMAGE_UNSUPPORTED_FORMAT:()=>LW,READ_IS_DIRECTORY:()=>DW,READ_ONLY_TOOL_NAMES:()=>bae,READ_UNSUPPORTED_ENCODING:()=>Wae,READ_UNSUPPORTED_FORMAT:()=>qae,READ_USE_NOTEBOOKREAD:()=>Hae,READ_USE_READIMAGE:()=>Qae,REQUIRED_CONTAINMENT_CONFORMANCE_CHECKS:()=>Y5,RunAuthorityRefusedError:()=>as,SANDBOX_MAX_DIR_ENTRIES:()=>PH,SANDBOX_MAX_READ_BYTES:()=>s0,SANDBOX_MAX_WRITE_BYTES:()=>_H,SDK_DEFAULT_MAX_ITERATIONS:()=>HH,SDK_DEFAULT_MAX_TOKENS:()=>$5,SDK_VERSION:()=>j0,SELF_REVIEW_DEFAULT_MIN_CHANGED_LINES:()=>Ace,SELF_REVIEW_STAGE_MARKER:()=>bce,SESSION_FORMAT_VERSION:()=>f5,SHEETS_CAPABILITIES:()=>Uqt,SHEETS_TOOL_NAMES:()=>Fqt,SLIDES_CAPABILITIES:()=>qqt,SLIDES_TOOL_NAMES:()=>jqt,SOUND_CAPABILITIES:()=>Kqt,SOUND_SYSTEM_PROMPT:()=>L3e,SOUND_TOOL_NAMES:()=>Jqt,SSETransport:()=>Sue,SUBAGENT_ROLE_ALIASES:()=>Qce,SUBAGENT_TEAM_PRESETS:()=>Hce,ScreenCapture:()=>C3t,ScreenCaptureError:()=>xc,SessionLock:()=>F5,SessionLockManager:()=>F5,SessionManager:()=>fS,SessionRegistry:()=>Ze,SkillStore:()=>g4e,SoulEngine:()=>T6,SqliteAutomationExecutionJournal:()=>Ije,SqliteCapabilityLeasePersistence:()=>zce,StdioTransport:()=>sH,StreamableHTTPTransport:()=>mse,SubagentBranchCancelledError:()=>aw,THREE_D_CAPABILITIES:()=>$qt,THREE_D_TOOL_NAMES:()=>Pqt,TOOL_OPERATION_SCHEMA_VERSION:()=>ow,TOOL_OPERATION_TERMINAL_STATES:()=>uW,TOOL_OUTPUT_MAX_READ_BYTES:()=>N1,TOOL_PAIRING_REFUSAL_PHRASES:()=>xce,TaskListManager:()=>oS,ToolFailureLoopGuard:()=>Fce,ToolMiddlewareRegistry:()=>Uce,ToolOperationManager:()=>Mie,ToolOrchestrator:()=>Ice,ToolRegistry:()=>yw,ToolSchemaProjectionError:()=>Fs,TranscriptWriter:()=>xl,TurnDiffTracker:()=>bR,TurnRestoreManager:()=>NA,UNANSWERED_QUESTION_PREFIX:()=>zW,UNBOUNDED_OPERATION_CONTINUATION_LIMIT:()=>$2,UnifiedExecError:()=>$u,UnifiedExecManager:()=>b5,UsageAccumulator:()=>D4e,UsageLedger:()=>wUt,VectorMemoryStore:()=>MW,WEB_CONTEXT_CONTRACT_VERSION:()=>yle,WEB_CONTEXT_GATEWAY_PATH_PREFIX:()=>_4e,WEB_CONTEXT_GATEWAY_URL:()=>R4e,WEB_CONTEXT_TOOL_RESULT_SCHEMA:()=>KW,WORKFLOW_CAPABILITIES:()=>Bqt,WORKFLOW_TOOL_NAMES:()=>Nqt,WorkflowPlanner:()=>YH,WorkflowRuntime:()=>fUt,WorkflowStore:()=>B4e,WorkspaceHookRuntime:()=>c4e,WorkspaceIndex:()=>R3t,XENO_AGENT_PROFILE_SCHEMA_VERSION:()=>K5,XENO_API_BASE:()=>ai,XENO_API_ORIGINS:()=>gae,XENO_APP_PROTOCOL_V2_METHODS:()=>_3e,XENO_APP_PROTOCOL_VERSIONS:()=>pse,XENO_ARTIFACT_ACTOR_KINDS:()=>gje,XENO_ARTIFACT_FILE_REPOSITORY_SCHEMA_VERSION:()=>yde,XENO_ARTIFACT_SCHEMA_VERSION:()=>eLt,XENO_ARTIFACT_SENSITIVITIES:()=>mje,XENO_ARTIFACT_STATES:()=>hje,XENO_AUTOMATION_OPERATIONS:()=>cS,XENO_AUTOMATION_PROTOCOL_VERSION:()=>YDt,XENO_BROWSER_CONTROL_PLANE_OPERATIONS:()=>aLt,XENO_BUILTIN_ARTIFACT_KINDS:()=>fje,XENO_BUILT_IN_SKILLS:()=>I4e,XENO_CAPABILITY_LEASE_SCHEMA_VERSION:()=>wH,XENO_CONTAINMENT_APPROVAL_SCHEMA:()=>s5,XENO_CONTAINMENT_CERTIFICATION_SCHEMA:()=>VN,XENO_CONTAINMENT_CONFORMANCE_SCHEMA:()=>Kce,XENO_CONTAINMENT_REVIEWER_TRUST_STORE_SCHEMA:()=>a5,XENO_CONTEXT_DIGEST_PATTERN:()=>J4e,XENO_CONTROL_ROOM_SCHEMA_VERSION:()=>zde,XENO_COORDINATION_BUDGET_SESSION_SCHEMA_VERSION:()=>ujt,XENO_COORDINATION_MANAGED_SESSION_SCHEMA_VERSION:()=>djt,XENO_COORDINATION_SCHEMA_VERSION:()=>cjt,XENO_COORDINATION_TURN_SESSION_SCHEMA_VERSION:()=>pjt,XENO_DEFLATE_CODEC_NAME:()=>yDe,XENO_DEFLATE_CODEC_VERSION:()=>ADe,XENO_DOMAINS:()=>bH,XENO_EVIDENCE_EDGE_TYPES:()=>pde,XENO_EVIDENCE_GRAPH_SCHEMA_VERSION:()=>tLt,XENO_EVIDENCE_NODE_TYPES:()=>ude,XENO_GIF_ANIMATION_POLICY:()=>xLe,XENO_GIF_CODEC_NAME:()=>ELe,XENO_GIF_CODEC_VERSION:()=>SLe,XENO_HANDOFF_SCHEMA_VERSION:()=>UUt,XENO_HOSTED_CONTROL_SCHEMA_VERSION:()=>iue,XENO_HOSTED_ENVIRONMENT_SCHEMA_VERSION:()=>Sjt,XENO_HOSTED_EVENT_SCHEMA_VERSION:()=>Cjt,XENO_HOSTED_EXECUTION_ADAPTER_CERTIFICATION_SCHEMA:()=>D5,XENO_HOSTED_EXECUTION_ADAPTER_MAX_CERTIFICATE_LIFETIME_MS:()=>K4e,XENO_HOSTED_EXECUTION_ADAPTER_PROTOCOL_VERSION:()=>Zoe,XENO_HOSTED_EXECUTION_PROTOCOL_VERSION:()=>Y4e,XENO_HOSTED_EXECUTION_TOOL_NAMES:()=>B6,XENO_HOSTED_RESULT_SCHEMA_VERSION:()=>oue,XENO_HOSTED_RUN_SCHEMA_VERSION:()=>xjt,XENO_HOSTED_TRIGGER_SCHEMA_VERSION:()=>Tjt,XENO_JPEG_CODEC_NAME:()=>PLe,XENO_JPEG_CODEC_VERSION:()=>$Le,XENO_MXC_ADAPTER_NAME:()=>gH,XENO_MXC_POLICY_VERSION:()=>jse,XENO_MXC_VERSION:()=>g0,XENO_ORACLE_REPORT_SCHEMA_VERSION:()=>sue,XENO_PAGE_ENTRY:()=>Sm,XENO_PAGE_MAX_BYTES:()=>Qje,XENO_PAGE_MAX_FILES:()=>Loe,XENO_PLUGIN_LOCK_FILENAME:()=>dW,XENO_PLUGIN_LOCK_SCHEMA_VERSION:()=>H5,XENO_PLUGIN_SIGNATURE_FILENAME:()=>R2,XENO_PLUGIN_SIGNATURE_SCHEMA_VERSION:()=>Due,XENO_PROCESS_TREE_KILL_TIMEOUT_MS:()=>_se,XENO_PROVIDER_CATALOG_SCHEMA_VERSION:()=>cue,XENO_PROVIDER_CONNECTION_STORE_SCHEMA_VERSION:()=>j6,XENO_RASTER_CODEC_NAME:()=>B1,XENO_RASTER_CODEC_VERSION:()=>xle,XENO_RASTER_PREVIEW_FORMATS:()=>Cle,XENO_RECIPE_SCHEMA_VERSION:()=>o3e,XENO_REPOSITORY_INDEX_SCHEMA_VERSION:()=>Jde,XENO_REVIEW_DIMENSIONS:()=>Fje,XENO_REVIEW_EVIDENCE_KINDS:()=>Uje,XENO_REVIEW_REPORT_SCHEMA_VERSION:()=>Sde,XENO_RT_DEFAULT_URL:()=>SW,XENO_SECURE_EXECUTION_CONTRACT_SCHEMA_VERSION:()=>yW,XENO_SHARE_REGISTRY_SCHEMA_VERSION:()=>jUt,XENO_SHARE_SCHEMA_VERSION:()=>FUt,XENO_SKILL_SCHEMA_VERSION:()=>XUe,XENO_SLASH_REFUSAL_NOTHING_SENT:()=>L5,XENO_SOURCE_RESEARCH_SCHEMA_VERSION:()=>aue,XENO_SPEC_EXECUTION_SCHEMA_VERSION:()=>O5,XENO_SPEC_SCHEMA_VERSION:()=>F2,XENO_SVG_RENDERER_NAME:()=>BLe,XENO_SVG_RENDERER_VERSION:()=>DLe,XENO_TELEMETRY_SCHEMA_VERSION:()=>Eae,XENO_UNSUPPORTED_SLASH_COMMAND_REASON:()=>rue,XENO_VP8_CODEC_NAME:()=>FLe,XENO_VP8_CODEC_VERSION:()=>ULe,XENO_WEBP_ANIMATION_POLICY:()=>HLe,XENO_WEBP_CODEC_NAME:()=>qLe,XENO_WEBP_CODEC_VERSION:()=>QLe,XenoAppServer:()=>mue,XenoAppServerV2Client:()=>fue,XenoArtifactRepositoryError:()=>Zt,XenoArtifactReviewService:()=>Toe,XenoArtifactStateTransitionError:()=>wje,XenoArtifactValidationError:()=>m6,XenoAuthError:()=>KQ,XenoAutomationError:()=>ve,XenoBrowserControlPlaneAdapter:()=>wde,XenoBrowserOwnerRuntime:()=>Tje,XenoCapabilityLeaseError:()=>ho,XenoComputerHostChannel:()=>sLt,XenoControlRoomValidationError:()=>Qs,XenoCoordinationError:()=>ke,XenoDiffParseError:()=>Bd,XenoEvidenceGraphBuilder:()=>kLt,XenoEvidenceGraphValidationError:()=>Oje,XenoExecutionLeaseSession:()=>hjt,XenoGovernedAutomationExecutor:()=>vje,XenoHostGovernedAutomationRuntime:()=>bde,XenoHostedExecutionJobError:()=>D6,XenoLoopbackAutomationAdapter:()=>Eje,XenoMultiAgentReviewCoordinator:()=>$Lt,XenoOracleCoordinator:()=>Xjt,XenoOracleValidationError:()=>Rm,XenoPageStore:()=>Wje,XenoProviderCatalog:()=>due,XenoRecipeValidationError:()=>sd,XenoRepositoryIndexFileStore:()=>LUt,XenoReviewValidationError:()=>id,XenoRuntimeEventBus:()=>bB,XenoSecureExecutionContractError:()=>El,XenoSourceResearchValidationError:()=>S2,XenoSpecLifecycleService:()=>TLt,XenoSpecValidationError:()=>nd,XenoTraceGraphRecorder:()=>n6,XenoUseComputerHttpAdapter:()=>Cje,acquireControlPlaneLock:()=>X1,activateSessionRuntime:()=>BR,activateXenoWorkspaceSkillRuntime:()=>jde,addPluginTrustedPublisher:()=>Wue,addProjectAllowedDirectory:()=>KBe,addProjectAllowedTool:()=>XBe,agentDefinitionFromProfile:()=>X5,agentProfileFromDefinition:()=>hBe,appServerSlashCommandRefusal:()=>N6,appendBoundedShellOutput:()=>Lie,appendGuidanceToResult:()=>wUe,applyFileSystemBinding:()=>$Fe,applyPatch:()=>QDe,approveMcpServer:()=>W6,areSignalHandlersInstalled:()=>WPt,artifactCompareTool:()=>fFe,artifactOperatorName:()=>JQ,artifactToolUrl:()=>Vje,askHuman:()=>l4e,askUserTool:()=>ALe,assertCurrentToolAuthorization:()=>DBe,assertDirectEndpointResolution:()=>sUe,assertPersistedXenoCapabilityLease:()=>lw,assertRequiredXenoAutomationEvidence:()=>VQ,assertSupportedMcpProtocolVersion:()=>W3e,assertUsableXenoApiKey:()=>$de,assertValidMcpAppResource:()=>eqe,assertValidXenoArtifact:()=>jd,assertValidXenoAutomationAdapterManifest:()=>RA,assertValidXenoAutomationRequest:()=>u0,assertValidXenoEvidenceGraph:()=>m2,assertValidXenoHostedExecutionJob:()=>nue,assertValidXenoOracleReport:()=>F6,assertValidXenoRecipeDefinition:()=>FB,assertValidXenoReviewPack:()=>xde,assertValidXenoReviewReport:()=>NB,assertValidXenoReviewTarget:()=>Cde,assertValidXenoSecureExecutionContract:()=>Hse,assertValidXenoSourceResearchReport:()=>U6,assertValidXenoSpecDocument:()=>A6,assertValidXenoSpecExecution:()=>Ede,assertXenoArtifactStateTransition:()=>GH,assertXenoAutomationAdapterConformant:()=>oLt,assertXenoAutomationAdapterRequirements:()=>cde,assertXenoAutomationAuthority:()=>D2,auditRiskLevelForTool:()=>j3e,authorizeShellExecution:()=>HW,backgroundProcessManager:()=>bt,bashTool:()=>pLe,benchmarkCodingTools:()=>Mde,bridgeXenoTelemetryToOpenTelemetry:()=>KRt,buildAtomicMessageGroups:()=>hUe,buildAuditReplayReport:()=>$B,buildAuditTraceReport:()=>PB,buildContainedProcessSpec:()=>z2t,buildContractLedgerGuidance:()=>kUt,buildDefaultSubagentTasks:()=>FBt,buildDelegatedRoleSystemPrompt:()=>SUe,buildHookEnvironment:()=>UBe,buildLinuxBubblewrapProcessSpec:()=>yBe,buildLspDefinitionReport:()=>hFe,buildLspDiagnosticsReport:()=>t6,buildLspDoctorReport:()=>qle,buildLspHoverReport:()=>gFe,buildLspReferencesReport:()=>mFe,buildMotionSystemPrompt:()=>yue,buildPixelSystemPrompt:()=>wue,buildProcessHardenedProcessSpec:()=>V2t,buildProjectBudgetFinalizationGuidance:()=>SUt,buildProjectExecutionGuidance:()=>EUt,buildProjectExecutionProfile:()=>xUt,buildPromptMemoryContext:()=>Y0,buildSecuredProcessSpec:()=>sR,buildSoundSystemPrompt:()=>Aue,buildSystemPrompt:()=>F0,buildToolFailureGuardResult:()=>gUe,buildXenoArtifactReviewAnchor:()=>Roe,buildXenoAutomationCapabilityUse:()=>dde,buildXenoRepositoryIndex:()=>Q4e,buildXenoRepositoryIndexWithEmbeddings:()=>_Ut,buildXenoSecureExecutionContract:()=>$Be,cachedModelContextWindow:()=>sDe,cachedModelImageInput:()=>aDe,calculateCost:()=>F3e,calculateReportedModelCost:()=>U3e,canTransitionXenoArtifactState:()=>Aje,canXenoRasterPreview:()=>zLe,canonicalPayload:()=>Dde,canonicalizeArtifactJson:()=>Qi,canonicalizeMcpResourceUri:()=>p5,canonicalizeSecurityPath:()=>$0,canonicalizeToolName:()=>ir,capabilitiesMoveTrustUpward:()=>BFe,captureXenoHandoffSnapshot:()=>Ijt,checkSandbox:()=>XFe,checkStructuredOutput:()=>Oqe,classifyArtifactToolAction:()=>qH,classifyExternalAction:()=>fDe,classifyForRead:()=>jae,classifyProviderHttpError:()=>IB,classifyProviderStreamError:()=>sS,classifyVerificationCommand:()=>ioe,classifyXenoProcessTreeKill:()=>Cse,classifyXenoSlashInput:()=>Qjt,cleanupReadImagePreviews:()=>yB,cleanupSessionRuntime:()=>DR,clearDescendantInstructionHintCache:()=>QBt,clearMcpServerApproval:()=>K3t,clearProjectAllowedDirectories:()=>lae,clearProjectAllowedTools:()=>sae,clearProjectLastSessionSummary:()=>$Rt,clearProjectMcpApproval:()=>ZBe,clearProjectMcpApprovals:()=>tDe,clipXenoAnsi:()=>tDt,cloudPublication:()=>LN,coerceSubagentRole:()=>c6,coerceSubagentTeamPreset:()=>IR,commandShapedSlashName:()=>MA,compileAgentProfile:()=>z5,compileJsonSchema:()=>Dae,compileRecipeWorkflow:()=>g3t,compileToolInputSchema:()=>NW,compileXenoRecipe:()=>a3e,compileXenoSkillActivation:()=>QDt,computeXenoContextDigest:()=>Ejt,configureImageGeneration:()=>B$t,configureSearch:()=>XW,configureSearchPermissionProfile:()=>bLe,configureXenoAnsi:()=>JBt,containmentApprovalSigningPayload:()=>FUe,containmentCertificationSigningPayload:()=>bBe,copyTextToClipboard:()=>D3t,crc32Xeno:()=>c_t,create3DTools:()=>Sqe,createAgentChildController:()=>V0,createAgentDefinitionFile:()=>o2t,createAgentDefinitionPromptSection:()=>t2t,createAgentRunId:()=>M4e,createAppServerExecutionLeaseStore:()=>q6,createAppServerV2HttpTransport:()=>hue,createArchitectTools:()=>Eqe,createArtifactCompareTool:()=>Lle,createArtifactPromptSection:()=>rFt,createArtifactTool:()=>Yje,createAskUserTool:()=>ple,createAudioTools:()=>N3e,createAuditBackedPermissionEngine:()=>NR,createBackgroundDispatchRegistry:()=>vB,createBashTool:()=>sle,createBenchBashMiddleware:()=>TUt,createCliAutomationAuditSink:()=>dS,createCliGovernedAutomationRuntime:()=>vde,createCommandBackedProtectedStateStore:()=>VUe,createDefaultToolRegistry:()=>nl,createDelegatedXenoAgent:()=>qL,createDirectProvider:()=>Mce,createDirectShellMessage:()=>eS,createDispatchAgentTool:()=>lle,createDispatchOutputTool:()=>wLe,createDocsTools:()=>Tqe,createEd25519Signer:()=>FFt,createEditTool:()=>uB,createElfAnalyzeTool:()=>Nle,createEngineTools:()=>xqe,createGcodeAnalyzeTool:()=>Ble,createGenerateImageTool:()=>gle,createGlobTool:()=>fB,createGovernanceExtensions:()=>RUt,createGrepTool:()=>hB,createHookToolMiddleware:()=>CFt,createHtmlSanitizerAuditTool:()=>Dle,createImageTools:()=>O3e,createInterruptedToolResult:()=>Iae,createListAgentsTool:()=>jFe,createListSessionsTool:()=>qFe,createLsTool:()=>Zle,createLspDefinitionTool:()=>Xle,createLspDiagnosticsTool:()=>Yle,createLspHoverTool:()=>Kle,createLspReferencesTool:()=>Jle,createMcpAppCapabilities:()=>X3e,createMcpAppExtensionCapabilities:()=>oqt,createMcpPkcePair:()=>z3e,createMcpPromptRegisteredTool:()=>aqe,createMcpRegisteredTool:()=>sqe,createMcpResourceRegisteredTool:()=>lqe,createMemoryProtectedStateStore:()=>MDt,createMemoryReadTool:()=>ece,createMemoryWriteTool:()=>tce,createNotebookEditTool:()=>nce,createNotebookReadTool:()=>rce,createNotesTools:()=>Pqe,createOllamaNativeProvider:()=>uUe,createOsProtectedStateStore:()=>d6,createPatchTool:()=>Jae,createPlanModeTools:()=>O6,createProtectedStateEnvelopeCipher:()=>NDt,createQuotaGovernedProvider:()=>iBt,createReadImageTool:()=>$le,createReadTool:()=>cB,createReceiveTool:()=>UFe,createReloadingXenoWorkspaceSkillPromptSections:()=>P6,createRemoteEvalGuard:()=>Xde,createRequestDeadline:()=>eUe,createSendTool:()=>FFe,createSheetsTools:()=>Rqe,createSlidesTools:()=>_qe,createSpeechRecognizer:()=>G3t,createSqliteAnalyzeTool:()=>Ole,createStructuredOutput:()=>Jue,createTaskInputTool:()=>fce,createTaskListTools:()=>_Fe,createTaskOutputTool:()=>uce,createTaskStopTool:()=>pce,createThinkTool:()=>cle,createToolAlias:()=>uA,createToolNameCodec:()=>LH,createToolOutputTool:()=>Kae,createToolRuntimeContext:()=>W0,createTrustedApplicationEnvironment:()=>ile,createUnavailableProtectedStateStore:()=>z2,createVideoTools:()=>M3e,createWebContextClientForRoute:()=>oUt,createWebContextFetchTool:()=>kLe,createWebContextRequestFactory:()=>wle,createWebContextSearchTool:()=>ILe,createWebSearchTool:()=>P$t,createWindowsDpapiProtectedCipher:()=>ODt,createWindowsDpapiProtectedFileStore:()=>GUe,createWorkflowClient:()=>Oh,createWorkflowTools:()=>Cqe,createWorkspaceHookRuntime:()=>wFt,createWriteTool:()=>dB,createXenoAgent:()=>Mh,createXenoAutomationConformanceReport:()=>kje,createXenoExtensionNativeAdapter:()=>gde,createXenoGovernedAutomationTools:()=>_je,createXenoHostAutomationAuditSink:()=>dS,createXenoHostGovernedAutomationRuntime:()=>vde,createXenoHostedControlCommand:()=>r3e,createXenoHostedEnvironmentManifest:()=>_jt,createXenoHostedEvent:()=>Pjt,createXenoHostedExecutionBoundaryReceipt:()=>Z4e,createXenoHostedRunResult:()=>L6,createXenoRasterPreview:()=>XLe,createXenoSecureShare:()=>GUt,createXenoSessionHandoff:()=>zUt,createXenoShareSigningIdentity:()=>WUt,createXenoSkillTool:()=>ide,createXenoSourceResearchExcerpt:()=>o4t,createXenoSourceResearchReport:()=>i4t,createXenoWorkspaceSkillBindings:()=>Hde,createXenoWorkspaceSkillPromptSections:()=>x4e,currentExecutionAdapterStatus:()=>eRt,decodeJwtPayload:()=>v6,decodeXenoBmp:()=>Rle,decodeXenoGif:()=>Ale,decodeXenoGifAnimation:()=>z$t,decodeXenoJpeg:()=>xH,decodeXenoNetpbm:()=>_le,decodeXenoPng:()=>Sle,decodeXenoSvg:()=>TOt,decodeXenoVp8:()=>kle,decodeXenoWebp:()=>Ele,defaultPeerDirectory:()=>LFe,defaultSkillRoots:()=>aje,defaultToolRuntimeContext:()=>Xn,defaultXenoReviewPack:()=>OLt,defaultXenoUserSkillsHome:()=>BB,deflateXenoZlib:()=>xae,delegatedBranchOutputTokens:()=>hS,delegatedBranchOwnerSessionId:()=>U5,deleteSession:()=>NFt,denyMcpServer:()=>G6,deriveHostedIdempotencyKey:()=>Mjt,describeXenoAutomationOperation:()=>Jp,detectLanguage:()=>bse,detectPluginRepositorySignals:()=>Uue,detectRepositoryDocumentKind:()=>H4e,detectRepositoryLanguage:()=>Kde,detectXenoSpecDrift:()=>RLt,deterministicReduce:()=>kUe,digestMessages:()=>pUe,directProviderConfigFromConnection:()=>U4t,disableWorkspaceHook:()=>dFt,discoverXenoSkills:()=>p6,dispatchAgentTool:()=>gLe,editTool:()=>jDe,elfAnalyzeTool:()=>aFe,emitPatchGbnf:()=>HDe,emitXenoTelemetry:()=>RW,encodeXenoPngRgb:()=>TH,enforceShellCommandPolicy:()=>zFe,enforceToolPolicy:()=>vce,ensureConfigDir:()=>EW,ensureDurableMessageIds:()=>Bce,ensureModelInputModalities:()=>lDe,ensureProjectStateDir:()=>zBe,estimateFullRequestBudget:()=>fUe,evaluateContainmentUiRestrictions:()=>HUe,evaluatePermissionProfileNetworkUrl:()=>iB,evaluateXenoCapabilityEligibility:()=>BBe,executeXenoCoordinationAction:()=>fjt,extractJsonCandidate:()=>$qe,extractJsonObject:()=>w4e,extractPageTitle:()=>Hje,extractToolPath:()=>S5,findMissingRequiredOutputs:()=>F4e,findModelMetadata:()=>hae,findUnansweredQuestion:()=>dle,findWorkspaceHookByHash:()=>fFt,findXenoSkill:()=>ZUe,findXenoWorkspaceSkill:()=>B5,fingerprintXenoComputerHostRequest:()=>Eoe,fingerprintXenoSecureExecutionContract:()=>Z2t,forgetRecentSession:()=>y_t,forgetRecentSessionById:()=>xie,formatBackgroundDispatchReport:()=>KFe,formatBoundedShellOutput:()=>Vg,formatCost:()=>B3t,formatDirectShellContext:()=>$ae,formatJsonSchemaErrors:()=>Lae,formatModelList:()=>mae,formatPromptContextBreakdown:()=>HB,gcodeAnalyzeTool:()=>cFe,generateImageTool:()=>vLe,generateSessionId:()=>xW,getAgentHome:()=>TRt,getAgentRunDir:()=>aUt,getAgentRunStoreDir:()=>sUt,getAvailableModels:()=>cR,getBenchmarkComputeBudgetHintForCommand:()=>UPt,getBenchmarkForegroundTimeoutForCommand:()=>jPt,getBestExecutionSecurityStatus:()=>PBe,getChatModels:()=>DRt,getConfigDir:()=>va,getDefaultProviderRegistry:()=>pDe,getExecutionSecurityCapabilityReport:()=>Qse,getExecutionSecurityStatus:()=>CA,getGlobIgnores:()=>zDe,getGrepIgnores:()=>JDe,getHighRiskPermissions:()=>dqt,getHookTrustPath:()=>_de,getImageGenerationConfig:()=>D$t,getJwtExpiry:()=>I6,getLinuxBubblewrapCapability:()=>Dse,getLogLevel:()=>E_t,getManagedConfigPath:()=>_A,getMcpAppMetadata:()=>z6,getMcpAppResourceUri:()=>Rue,getMcpApprovalDecision:()=>kue,getMcpAuthorizationServerMetadataUrls:()=>V3e,getMcpDefinitionFingerprint:()=>J6,getMcpPromptToolName:()=>Oue,getMcpProtectedResourceMetadataUrls:()=>G3e,getMcpResourceToolName:()=>Mue,getMcpToolName:()=>$ue,getModelName:()=>Ld,getMxcContainmentProbe:()=>z1,getMxcNativeAssetDescriptor:()=>SBe,getMxcWindowsHostPreparationDescriptor:()=>xBe,getMxcWindowsHostPreparationHelperArchitecture:()=>CBe,getPermissionProfile:()=>Ka,getPersistentShellSession:()=>lLe,getPersistentShellSpawnSpec:()=>VW,getPluginMcpServerImpacts:()=>eG,getPluginSkillImpacts:()=>Vde,getProcessContainmentStatus:()=>W2t,getProjectAgentDefinitionDirs:()=>lBe,getProjectAgentDefinitionsDir:()=>cBe,getProjectHooksConfigPath:()=>i4e,getProjectLastSessionSummary:()=>uae,getProjectMcpApproval:()=>cae,getProjectStatePath:()=>Lu,getReadImagePreviewCapability:()=>Ple,getRecentSessionsIndexPath:()=>uR,getSubagentTeamPresetDefinition:()=>EUe,getToolRiskLevel:()=>JFe,getUserAgentDefinitionsDir:()=>Ose,getUserHooksConfigPath:()=>n4e,getXenoProjectSkillsDir:()=>TR,getXenoProjectSkillsStatePath:()=>pS,getXenoUserSkillsDir:()=>uS,getXenoUserSkillsStatePath:()=>RR,getXenoWorkspaceSkillDiscoveryRoots:()=>R6,gitBranchTool:()=>lce,gitCommitTool:()=>ace,gitDiffTool:()=>oce,gitLogTool:()=>sce,gitStatusTool:()=>ice,globTool:()=>XDe,grepTool:()=>KDe,gunzipXeno:()=>d_t,gzipXeno:()=>Cae,hasProjectOnboardingCompleted:()=>iae,hasXenoTelemetrySubscribers:()=>zRt,hashContainmentConformanceReport:()=>xDt,hashHookDefinition:()=>t4e,hashPluginManifest:()=>Lue,hashPluginTree:()=>pqe,hookResultStatus:()=>SA,hostedEnvironmentIdentity:()=>Ojt,hostedSlashCommandRefusal:()=>e3e,htmlSanitizerAuditTool:()=>dFe,importLegacyXenoSkill:()=>YUe,inflateXenoRaw:()=>l_t,inflateXenoZlib:()=>Sae,initializeSessionRuntime:()=>Z0,inspectCliAutomationStatus:()=>g6,inspectMcpConfigSources:()=>H3e,inspectRuntimeManifests:()=>vue,inspectSecurityPath:()=>g5,inspectSystemPrompt:()=>MR,inspectWorkspaceHookConfigs:()=>Pde,inspectXenoHostAutomationStatus:()=>g6,inspectXenoRepositoryFreshness:()=>OUt,inspectXenoRepositorySymbol:()=>$Ut,installSignalHandlers:()=>nle,interruptedQuestionResult:()=>ule,invalidateAllObservedFiles:()=>D0,invalidateXenoWorkspaceSkillCache:()=>DB,invokeXenoSkill:()=>ode,invokeXenoWorkspaceSkill:()=>Wde,isArtifactToolCategory:()=>M5,isChatModel:()=>K1,isDangerousCommand:()=>tLe,isDirectShellMessage:()=>TDe,isExpiredJwt:()=>RFt,isExplicitResearchPrompt:()=>toe,isJwt:()=>b6,isLocalModel:()=>ph,isMcpAppResourceUri:()=>Y3e,isMcpOAuthTokenExpired:()=>tqt,isMcpToolVisibleToApp:()=>K3e,isMcpToolVisibleToModel:()=>J3e,isModelRequestTimeoutPhase:()=>W5t,isNotBeforeJwt:()=>p4e,isPathWithinAllowed:()=>Cm,isPeerTaskTerminal:()=>_1,isQuestionTool:()=>v5,isQuotaControlError:()=>n5,isReadOnlyToolName:()=>CW,isRemoteEvalCommand:()=>q4e,isScreenCaptureAvailable:()=>T3t,isSensitiveEnvironmentKey:()=>Fse,isSimpleInformationalPrompt:()=>$H,isSpeechRecognitionAvailable:()=>V3t,isSupportedMcpProtocolVersion:()=>Cue,isToolAllowedByXenoSkillActivation:()=>nje,isToolOperationTerminalState:()=>X5e,isUncOrDevicePath:()=>gBe,isValidAgentDefinitionName:()=>Mse,isValidModel:()=>BRt,isValidSessionId:()=>URt,isWorkspaceTrusted:()=>q0,isXenoApiOrigin:()=>fae,isXenoAutomationOperation:()=>lde,isXenoContextDigest:()=>Zde,killWindowsProcessTree:()=>Tse,killWindowsProcessTreeSync:()=>fW,legacyAgentArtifactToXenoArtifact:()=>WLt,listBuiltInAgentProfiles:()=>wW,listPermissionProfiles:()=>wRt,listPluginMcpServers:()=>Xue,listProjectAllowedDirectories:()=>YBe,listProjectAllowedTools:()=>JBe,listProjectApprovals:()=>Q0,listProjectMcpApprovals:()=>eDe,listSessions:()=>MFt,loadConfig:()=>Pt,loadConfiguredMcpServers:()=>Aw,loadMcpConfigFile:()=>H6,loadPluginTrustStore:()=>hw,loadPluginTrustStoreSync:()=>Hue,loadProjectConfig:()=>Ode,loadProjectState:()=>Hi,loadRecentSessionsIndex:()=>q1,loadSession:()=>OFt,loadUserConfig:()=>mw,loadWorkspaceHookEntries:()=>s4e,loadWorkspaceHooks:()=>o4e,loadXenoSkill:()=>f6,loadXenoWorkspaceSkill:()=>LB,loadXenoWorkspaceSkills:()=>N5,loadXenoWorkspaceSkillsWithDiagnostics:()=>K0,lookupRecentSession:()=>SDe,lsTool:()=>vFe,lspDefinitionTool:()=>yFe,lspDiagnosticsTool:()=>wFe,lspHoverTool:()=>AFe,lspReferencesTool:()=>bFe,markdownTitle:()=>Rde,matchPermissionRule:()=>fDt,matchesMcpRegistryEntryPolicy:()=>WB,materializeXenoAutomationEvidence:()=>Ioe,mcpInputSchemaToToolSchema:()=>nqe,memoryReadTool:()=>IFe,memoryWriteTool:()=>kFe,mentionsToolPairingRefusal:()=>oUe,mergeConfigs:()=>$Ft,migrateLegacyXenoWorkspaceSkills:()=>Gde,movesTrustUpward:()=>NFe,mxcWarningsRequireWindowsHostPreparation:()=>EBe,normalizeDirectShellResultRecord:()=>Pae,normalizeHookDecision:()=>Vse,normalizeMcpAppVisibility:()=>X6,normalizePagePath:()=>Foe,normalizePermissionProfileName:()=>yH,normalizeQuotaScope:()=>sw,normalizeRepositoryRelativePath:()=>Bje,normalizeSourceText:()=>nW,normalizeSubagentBranchPolicy:()=>xB,normalizeWorkingDirectory:()=>PW,normalizeXenoHostedControlAcknowledgement:()=>Gjt,normalizeXenoRequestContext:()=>uH,notebookEditTool:()=>SFe,notebookReadTool:()=>EFe,openSqliteAutomationExecutionJournal:()=>iLt,openSqliteCapabilityLeasePersistence:()=>yDt,pageContentType:()=>XQ,parseContainmentReviewerTrustStore:()=>UUe,parseMcpWwwAuthenticate:()=>Tue,parsePatch:()=>hR,parsePermissionRule:()=>NUe,parseRecipeInputs:()=>w3t,parseRecipeMode:()=>y3t,parseRetryAfter:()=>Sce,parseSessionId:()=>cDe,parseShellPathReferences:()=>VFe,parseSubagentRemoteMcpPolicy:()=>SB,parseSubagentRoleList:()=>EB,parseUnifiedDiff:()=>Ide,parseWebResearchBudget:()=>r5t,parseXenoAnsi:()=>CB,parseXenoRecipeDefinition:()=>s3e,patchPaths:()=>pB,patchTool:()=>WDe,peerShortId:()=>L0,pending:()=>k0,persistXenoAutomationEvidence:()=>VH,planXenoControlRoomAction:()=>bUt,pluginInfoRelevanceCandidate:()=>que,pluginListingRelevanceCandidate:()=>Que,pluginMcpApprovalKey:()=>bqe,pluginMcpServerConfigs:()=>vqe,pluginMcpServerName:()=>zue,pluginSignaturePayload:()=>fqe,preflightLocalModel:()=>NRt,prepareMxcWindowsHost:()=>B2t,presenceMovesTrustUpward:()=>DFe,probeLocalToolGrammarSupport:()=>dUe,probeXenoProvider:()=>L4t,projectToolDefinitionsForProvider:()=>x5,projectToolSchemaForProvider:()=>rUe,projectXenoControlRoom:()=>AUt,providerCapabilityError:()=>Gp,providerProtocolError:()=>Je,publicKeyFingerprint:()=>Yde,publishPlugin:()=>Cqt,quotaAncestors:()=>i5,quotaInteger:()=>No,quotaScopeKey:()=>fh,quotaText:()=>ch,rankPluginRelevance:()=>jue,readCliAutomationEnvironment:()=>J0,readImageTool:()=>eFe,readManifestFromDisk:()=>q5,readPluginDetachedSignature:()=>hqe,readPluginSupplyChainLockfile:()=>GB,readSessionFormatVersion:()=>P3e,readTool:()=>LDe,readToolOutput:()=>DDe,readXenoApiKey:()=>$3t,readXenoHostAutomationEnvironment:()=>J0,recipeInvocationSummary:()=>A3t,recordRecentSession:()=>$W,recordXenoCounter:()=>Zr,recordXenoEvent:()=>XRt,recordXenoHistogram:()=>Aa,recoverSessionMessages:()=>QB,redactXenoShareValue:()=>W4e,registerAgentChild:()=>ale,registerArtifactTool:()=>tFt,registerPlanModeTools:()=>PR,registerShutdownCleanup:()=>gB,registry:()=>wce,removeMcpServerConfig:()=>J3t,removePluginTrustedPublisher:()=>Gue,removeProjectAllowedDirectory:()=>aae,removeProjectAllowedTool:()=>oae,renderAgentDefinition:()=>i2t,renderAgentDefinitions:()=>n2t,renderAuditReplayMarkdown:()=>ade,renderAuditReplayReport:()=>MB,renderAuditTraceMarkdown:()=>sde,renderAuditTraceReport:()=>OB,renderAuditTraceSummaries:()=>xR,renderCliAutomationStatus:()=>w6,renderCodingBenchmarkMarkdown:()=>Bde,renderCodingBenchmarkReport:()=>Nde,renderContinuationIncompleteStatus:()=>mB,renderInline:()=>k1,renderLspDefinitionReport:()=>ANt,renderLspDiagnosticsReport:()=>Vle,renderLspDoctorReport:()=>zle,renderLspHoverReport:()=>vNt,renderLspReferencesReport:()=>bNt,renderMarkdownBody:()=>Tde,renderMarkdownPage:()=>zje,renderPeerLabel:()=>qi,renderToolContinuationInput:()=>WW,renderXenoHostAutomationStatus:()=>w6,renderXenoSkillCatalog:()=>h6,repairInterruptedToolCalls:()=>iH,repairOpenAIToolCallPairing:()=>Iie,repairToolExchangeHistory:()=>mUe,repairToolPairing:()=>N0,requestBackground:()=>y$t,requiresSecuredProcessLaunch:()=>vA,resetAllPersistentShellSessions:()=>r$t,resetBashBenchmarkGuards:()=>qPt,resetImageGenerationConfig:()=>L$t,resetMcpServerApprovals:()=>Y3t,resetMxcContainmentProbe:()=>TBe,resetPersistentShellSession:()=>ole,resetXenoAnsiPolicy:()=>KBt,resetXenoTelemetryCardinalityForTests:()=>YRt,resizeXenoRaster:()=>VLe,resolveAgentDefinition:()=>oR,resolveAgentProfile:()=>J5,resolveAgentToolPolicy:()=>cie,resolveBuiltInAgentProfile:()=>fBe,resolveCommandOnPath:()=>iS,resolveContainmentConformanceTemporaryRoot:()=>qUe,resolveDelegatedExecutionMode:()=>AUe,resolveExecutionSecurityLevel:()=>eB,resolveExecutionTrustMode:()=>qse,resolveExternalActionDecision:()=>gW,resolveInteractiveTurnMaxIterations:()=>i5t,resolveLocalRuntimeUrl:()=>J1,resolveModelContextTokens:()=>dDe,resolveModelMaxOutputTokens:()=>uDe,resolveModelRequestDeadlines:()=>ZFe,resolvePeerTarget:()=>r6,resolvePermissionProfile:()=>Jse,resolveRecipeReference:()=>m3t,resolveShellInvocation:()=>sLe,resolveSubagentRemoteMcpAccess:()=>kR,resolveSubagentWorkflowAnswer:()=>CUe,resolveWebContextRoute:()=>iUt,resolveXenoAutomationEvidencePolicy:()=>WH,resolveXenoSdkApiKey:()=>_Ft,restoreXenoHandoffSnapshot:()=>kjt,runAgentHook:()=>eae,runCommandHook:()=>zse,runContainmentConformanceSuite:()=>kDt,runDelegatedXenoTurn:()=>Nz,runDelegationPlan:()=>vUe,runDurableAutomation:()=>bje,runHookDefinition:()=>wie,runHooks:()=>yie,runHttpHook:()=>Yse,runPermissionRequestHooks:()=>vFt,runPostCompactHooks:()=>SFt,runPreCompactHooks:()=>EFt,runPromptHook:()=>Zse,runSessionStartHooks:()=>yFt,runStopFailureHooks:()=>bFt,runStopHooks:()=>AFt,runSubagentStartHooks:()=>IFt,runSubagentStopHooks:()=>kFt,runSubagentWorkflow:()=>TUe,runUserPromptSubmitHooks:()=>xFt,runXenoBoundedProcess:()=>$se,runXenoBoundedProcessSync:()=>Pse,runXenoProcessTreeKillHelper:()=>Rse,runXenoThread:()=>use,runXenoThreadStreamed:()=>v3t,sanitizeEnvironment:()=>Z5,sanitizeInheritedSkillActivations:()=>$6,sanitizeRecipeError:()=>T3e,sanitizeXenoTelemetryAttributes:()=>hDe,saveConfig:()=>go,saveMcpConfigFile:()=>Iue,saveProjectState:()=>IW,saveSession:()=>C6,scaffoldPlugin:()=>Sqt,scanAgentDefinitions:()=>Nse,scanDescendantInstructionHints:()=>_Ue,scanRecipes:()=>C3e,scoreMemories:()=>bBt,scorePluginRelevance:()=>gqe,searchXenoRepositoryIndex:()=>PUt,selectXenoProviderRoute:()=>F4t,selectXenoWorkspaceSkills:()=>_R,selectableOptions:()=>a4e,serializeXenoRecipe:()=>d4t,setLogLevel:()=>k_t,setPluginRequireSigned:()=>Vue,setProjectLastSessionSummary:()=>kW,setProjectMcpApproval:()=>dae,setProjectOnboardingCompleted:()=>Nm,setToolOutputStoreDirectory:()=>J_t,setWorkspaceTrusted:()=>nae,setXenoWorkspaceSkillEnabled:()=>Qde,setupAIHandlers:()=>P3t,sha256ArtifactBytes:()=>Ws,sha256ArtifactJson:()=>Qd,shouldEnableExecutionGovernance:()=>CUt,shouldRunSelfReview:()=>WFe,shouldSourceShellProfile:()=>kH,shouldUseIsolatedStdinForCommand:()=>rle,signSharePayload:()=>G4e,sqliteAnalyzeTool:()=>nFe,startArtifactViewer:()=>Kje,startPromptMemoryBundle:()=>Q3t,startSessionRuntime:()=>q3t,storeToolOutput:()=>rS,stripXenoAnsi:()=>$Ue,subscribeXenoTelemetry:()=>kae,summarizeAuditInputRecord:()=>q3e,summarizeAuditTraces:()=>lS,summarizeRuntimeInput:()=>soe,summarizeSubagentResults:()=>xUe,summarizeXenoArtifactReview:()=>hde,syncMcpToolsToRegistry:()=>eI,synthesizeSkill:()=>y4e,taskInputTool:()=>RFe,taskOutputTool:()=>CFe,taskStopTool:()=>TFe,testPlugin:()=>xqt,thinkTool:()=>yLe,toAgentDefinitionMetadata:()=>r2t,toLLMProvider:()=>h4e,toPeerPosture:()=>mce,toSerializableXenoWorkspaceSkill:()=>qde,toolEvidenceToXenoArtifact:()=>VLt,toolOperationManager:()=>et,toolOutputTool:()=>GDe,toolRiskLevel:()=>mA,truncationNotice:()=>zae,trustWorkspaceHook:()=>cFt,turnDiffSummaryToXenoArtifact:()=>XLt,unifiedDiffToXenoArtifact:()=>y6,unifiedExecManager:()=>G0,updateProjectState:()=>yh,upsertMcpServerConfig:()=>X3t,userRecipesDir:()=>pue,validateAgentDefinition:()=>dBe,validateAgentMcpServers:()=>mW,validateCapabilityLeaseRequest:()=>Gse,validateCapabilityMutationReceipt:()=>DUe,validateDelegationPlan:()=>bUe,validateDirectEndpoint:()=>kB,validateExecutionSecurityPolicy:()=>tB,validateJsonSchema:()=>ODe,validateManifest:()=>gse,validateMcpAppResource:()=>Z3e,validateToolContinuationGoal:()=>A5,validateXenoArtifact:()=>yje,validateXenoArtifactReviewEvent:()=>fde,validateXenoControlRoomSnapshot:()=>L4e,validateXenoEvidenceGraph:()=>Mje,validateXenoRepositoryIndex:()=>K2,validateXenoSdkApiKey:()=>PFt,validateXenoSecureExecutionContract:()=>OBe,validateXenoSpecDocument:()=>Dje,verifyContainmentCertification:()=>vBe,verifyContainmentCertificationApproval:()=>Xce,verifyPluginSupplyChain:()=>Y6,verifySignature:()=>A4e,verifySoulRecord:()=>UFt,verifyXenoHostedControlCommand:()=>Wjt,verifyXenoHostedEnvironmentManifest:()=>eue,verifyXenoHostedEventChain:()=>$jt,verifyXenoHostedExecutionAdapterCertification:()=>jjt,verifyXenoHostedExecutionJob:()=>t3e,verifyXenoHostedRunResult:()=>Vjt,verifyXenoHostedWebhook:()=>Fjt,verifyXenoSecureShare:()=>VUt,verifyXenoSessionHandoff:()=>XUt,waitForXenoHandoffStatus:()=>z4e,webFetchTool:()=>wB,webSearchTool:()=>mle,windowsDpapiProtect:()=>TB,windowsDpapiUnprotect:()=>RB,withXenoTelemetrySpan:()=>JRt,workflows:()=>ani,wrapXenoAnsi:()=>rDt,writePluginSupplyChainLockfile:()=>mqe,writeTool:()=>UDe,xenoAnsi:()=>I2,xenoAnsiVisibleWidth:()=>OUe,xenoArtifactToDiffDocument:()=>Nje,xenoArtifactToLegacyAgentArtifact:()=>GLt,xenoArtifactToOracleReport:()=>Kjt,xenoArtifactToReviewReport:()=>NLt,xenoArtifactToSourceResearchReport:()=>a4t,xenoArtifactToSpecDocument:()=>$oe,xenoArtifactToSpecExecution:()=>Lje,xenoArtifactToToolEvidence:()=>zLt,xenoArtifactToTurnDiffSummary:()=>JLt,xenoHostedExecutionAdapterSigningPayload:()=>Ujt,xenoOracleReportToArtifact:()=>Jjt,xenoRecipeFingerprint:()=>lue,xenoRequestContextHeaders:()=>kse,xenoReviewReportToArtifact:()=>MLt,xenoReviewReportToGitHubComments:()=>BLt,xenoSourceResearchReportToArtifact:()=>s4t,xenoSpecArtifactIds:()=>E2,xenoSpecExecutionToArtifact:()=>Ooe,xenoSpecToArtifactBundle:()=>Poe});function Mh(e={}){let t=e.selfReview!==void 0?e.selfReview:lni();return aS(oG({...e,skills:e.skills??!1,...t!==void 0?{selfReview:t}:{}}))}function lni(){let e;try{e=Pt().selfReview}catch{e=void 0}return o6t(e)}function qL(e){return ER(oG({...e,skills:e.skills??!1}))}function nl(e={}){return Ah({...e,webContext:e.webContext??n6t()})}var Er=ye(()=>{"use strict";st();vQe();iI();st();ffe();st();Err();Srr()});var Lge=ye(()=>{"use strict";rl();$a()});function Kii(e){return e??"inherit"}function Gz(e){return ir(e.trim())}function Yii(e){let t=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${t}$`)}function Zii(e){let t=e.trim();if(!t)return null;let r=t.indexOf("(");if(r<0)return{kind:"exact",raw:t,toolName:Gz(t)};if(!t.endsWith(")"))return null;let n=t.slice(0,r).trim(),i=t.slice(r+1,-1),o=i.indexOf(":");if(!n||o<0)return null;let s=i.slice(0,o).trim(),a=i.slice(o+1).trim();return s?{kind:"parameterized",raw:t,toolName:Gz(n),field:s,pattern:a,regex:Yii(a)}:null}function jze(e){return!e||e.length===0?[]:e.map(t=>Zii(t)).filter(t=>t!==null)}function qze(e){let t=jze(e.allow),r=jze(e.deny),n=new Set,i=[],o=new Set,s=[];for(let a of t)a.kind==="exact"?n.add(a.toolName):i.push(a);for(let a of r)a.kind==="exact"?o.add(a.toolName):s.push(a);return{mode:Kii(e.mode),allowExact:n,allowParameterized:i,denyExact:o,denyParameterized:s,hasAllowRules:t.length>0}}function eoi(e,t){return e?new Set([...e].filter(r=>t.has(r))):new Set(t)}function dnr(e){let t=e.hasAllowRules?new Set([...e.allowExact,...e.allowParameterized.map(r=>r.toolName)]):void 0;return e.mode==="none"?new Set:(e.mode==="readOnly"&&(t=eoi(t,cnr)),t)}function toi(e){return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):null}function lnr(e,t){if(!Object.prototype.hasOwnProperty.call(t,e.field))return!1;let r=toi(t[e.field]);return r===null?!1:e.regex.test(r)}function Hz(e){return{success:!1,output:"",error:`Tool call blocked by custom agent tool policy: ${e}`}}function unr(e,t){let r=o=>(o??"").split(",").map(s=>s.trim()).filter(Boolean),n=r(e),i=r(t);if(e!==void 0&&n.length===0)throw new Error("--allowed-tools needs at least one tool name.");if(!(n.length===0&&i.length===0))return{...n.length?{allow:n}:{},...i.length?{deny:i}:{}}}function pnr(e){if(!e)return[];let t=(r,n)=>jze(r).filter(i=>i.kind==="parameterized"&&i.toolName==="Bash"&&i.field==="command").map(i=>{if(i.pattern.length===0)throw new Error(`${i.raw} names no command.`);if(n==="allow"&&i.pattern.replace(/\*/g,"").trim().length===0)throw new Error(`${i.raw} would approve every command. Use --bypass-permissions for full access.`);return{tool:"Bash",pattern:i.pattern,decision:n}});return[...t(e.deny,"deny"),...t(e.allow,"allow")]}function ro(e,t){if(!t)return{removed:[]};let r=qze(t),n=dnr(r),i=[];for(let o of e.listNames()){let s=Gz(o),a=n?!n.has(s):!1,l=r.denyExact.has(s);(a||l)&&e.unregister(o)&&i.push(o)}return fnr(r,n,i)}function fnr(e,t,r){return{removed:r,...t?{allowed:[...t].sort()}:{},...e.denyExact.size>0||e.denyParameterized.length>0?{denied:[...e.denyExact,...e.denyParameterized.map(n=>n.toolName)].sort()}:{}}}function oc(e){if(!e)return;let t=qze(e);return async(r,n)=>{let i=Gz(r.toolName);if(t.mode==="none")return Hz(`${r.toolName} is disabled for this custom agent.`);if(t.mode==="readOnly"&&!cnr.has(i))return Hz(`${r.toolName} is not read-only.`);if(t.denyExact.has(i))return Hz(`${r.toolName} is denied.`);let o=t.denyParameterized.find(s=>s.toolName===i&&lnr(s,r.input));if(o)return Hz(`${o.raw} denied this input.`);if(t.hasAllowRules){let s=t.allowExact.has(i),a=t.allowParameterized.some(l=>l.toolName===i&&lnr(l,r.input));if(!s&&!a)return Hz(`${r.toolName} input does not match the custom agent allow-list.`)}return n()}}var cnr,Wz,tx=ye(()=>{"use strict";Er();cnr=new Set(["Read","Glob","Grep","LS","GitStatus","GitDiff","GitLog","WebFetch","WebSearch","MemoryRead","NotebookRead","ReadImage","SqliteAnalyze","ElfAnalyze","GcodeAnalyze","HtmlSanitizerAudit","ArtifactCompare","Think","ToolSearch","Skill",...cS.filter(e=>Jp(e).effect==="observe")]),Wz=class{constructor(t){this.registry=t}registry;removedTools=new Map;restore(){for(let[t,r]of this.removedTools)this.registry.has(t)||this.registry.register(r);this.removedTools.clear()}apply(t){if(this.restore(),!t)return{removed:[]};let r=qze(t),n=dnr(r),i=[];for(let o of this.registry.listNames()){let s=Gz(o),a=n?!n.has(s):!1,l=r.denyExact.has(s);if(!a&&!l)continue;let c=this.registry.get(o);c&&this.registry.unregister(o)&&(this.removedTools.set(o,c),i.push(o))}return fnr(r,n,i)}}});var gnr={};$o(gnr,{agentProfileSkillPolicy:()=>coi,assertCliAgentDelegationAllowed:()=>zge,assertCliChildContextAuthority:()=>eP,classifyAgentProfileExternalActions:()=>gd,cliAgentProfileBoundary:()=>Wm,createAgentProfileExternalActionMiddleware:()=>Kd,createReloadingAgentProfilePromptSection:()=>Xge,createReloadingAgentProfileToolPolicyMiddleware:()=>Jge,hasCurrentTurnAgentProfileApproval:()=>wd,listCliAgentProfiles:()=>Vz,resolveCliAgentProfile:()=>uf,resolveCliAgentProfileOrThrow:()=>Wi,resolveCliChildAgentProfile:()=>Z_,resolveCliLiveChildProfile:()=>sb,shellInvocationText:()=>mnr});import{isDeepStrictEqual as roi}from"node:util";function Gge(e){return e.trim().toLowerCase()}function noi(){let e=Pt().permissionProfile;return{source:"cli-config:permission-profile",permissionProfile:e==="read-only"||e==="trusted-dev"||e==="default"?e:"default"}}function Vge(){let e=[noi()],t=process.env.XENO_AGENT_EXTERNAL_ACTIONS?.trim().toLowerCase();return(t==="deny"||t==="ask")&&e.push({source:"run:external-actions",externalActions:{default:t}}),e}function uf(e,t=process.cwd(),r=Vge()){let n=Gge(e);if(!n)return null;let i=oR(n,t),o=J5({name:n,definition:i.definition,boundaries:r});return o?{definition:i.definition??X5(o.profile),compiled:o,source:i.definition?"custom":"built-in",scan:i.scan}:null}function Wi(e,t=process.cwd(),r){let n=e.trim(),i=uf(n,t,r);if(i)return i;let o=oR(n,t).scan,s=[...new Set([...wW().map(d=>d.id),...o.definitions.filter(d=>d.active).map(d=>d.name)])],a=Gge(n),l=s.filter(d=>d.includes(a)||a.includes(d)).slice(0,5),c=l.length>0?` Did you mean: ${l.join(", ")}?`:"";throw new Error(`Agent definition not found: ${n}. No matching built-in profile or custom definition.${c}`)}function Z_(e,t,r){if(!r)return Wi(e,t);let n=Wi(e,t,[...Vge(),Wm(r)]);return zge(n.definition.name,r),n}function zge(e,t){let r=t?.capabilities.delegatedAgents;if(r!==void 0&&!r.includes(Gge(e)))throw new Error(`Parent agent profile does not permit delegation to ${e}.`)}function Wm(e){return{source:`parent-profile:${e.fingerprint}`,tools:e.capabilities.tools,skills:{...e.capabilities.skills.allow!==void 0?{allow:e.capabilities.skills.allow}:{},deny:e.capabilities.skills.deny},hooks:{require:e.capabilities.hooks},...e.capabilities.mcpServers?{mcpServers:{allow:e.capabilities.mcpServers}}:{},...e.capabilities.delegatedAgents?{delegatedAgents:{allow:e.capabilities.delegatedAgents}}:{},permissionProfile:e.capabilities.permissionProfile,externalActions:e.capabilities.externalActions,maximumMemoryScope:e.memory.scope,maximumSoulMode:e.memory.soul,requiredIsolation:e.execution.isolation}}function sb(e,t,r){return Wi(e.profile.id,t,[...Vge(),Wm(e),...r?[Wm(r)]:[]]).compiled}function eP(e,t,r=!1){let n=z5(e.profile,{boundaries:[Wm(e),Wm(t)]}),i=o=>({...r?{tools:o.capabilities.tools,mcpServers:o.capabilities.mcpServers}:{},memory:o.memory,skills:o.capabilities.skills,hooks:o.capabilities.hooks,permissionProfile:o.capabilities.permissionProfile,externalActions:o.capabilities.externalActions,delegatedAgents:o.capabilities.delegatedAgents,isolation:o.execution.isolation});if(!roi(i(e),i(n)))throw Object.assign(new Error("Parent context authority narrowed; stop this child and start a fresh child under the current ceiling."),{code:"PARENT_CONTEXT_NARROWED",reason:"parent_context_narrowed",retryable:!1})}function Vz(e=process.cwd(),t=Vge()){let r=oR("__list__",e).scan,n=new Map;for(let i of wW()){let o=z5(i,{boundaries:t});n.set(i.id,{definition:X5(i),compiled:o,source:"built-in"})}for(let i of r.definitions.filter(o=>o.active)){let o=J5({name:i.name,definition:i,boundaries:t});o&&n.set(i.name,{definition:i,compiled:o,source:"custom"})}return[...n.values()].sort((i,o)=>i.definition.name.localeCompare(o.definition.name))}function Xge(e,t=process.cwd()){let r=e.trim(),n=Gge(r)||"unknown",i=()=>typeof t=="function"?t():t;return{name:`agent-profile:${n}:reload`,order:20,provide(o){if(!r)return null;let s=uf(r,i());return s?s.compiled.promptSection.provide(o):[`# XENO Agent Profile: ${r}`,"","This profile or custom definition is no longer available. Continue with the base session contract."].join(`
5521
- `)}}}function Jge(e,t=process.cwd()){let r=e.trim(),n=()=>typeof t=="function"?t():t;return async(i,o)=>{if(!r)return o();let s=uf(r,n());if(!s)return{success:!1,output:"",error:`Tool call blocked: XENO agent profile is unavailable: ${r}`};let a=oc(s.compiled.capabilities.tools);return a?a(i,o):o()}}function hnr(e){let t=[];for(let r of["command","action","operation","subcommand","method"])typeof e[r]=="string"&&t.push(e[r]);return typeof e.args=="string"&&t.push(e.args),Array.isArray(e.args)&&t.push(...e.args.filter(r=>typeof r=="string")),t.join(" ").trim().toLowerCase()}function ioi(e){return e.trim().replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().replace(/[^a-z0-9]+/g," ")}function mnr(e){return e.replace(/<<-?\s*(['"]?)([a-z_][a-z0-9_]*)\1[\s\S]*?\n[ \t]*\2(?![a-z0-9_])/g," ").replace(/\b((?:ba|z|da)?sh|pwsh|powershell)\s+(-[a-z]*c|-command)\s+(['"])([\s\S]*?)\3/g,"$1 ; $4 ;").replace(/'[^']*'|"(?:\\.|[^"\\])*"/g," ").replace(/\s+/g," ").trim()}function gd(e,t){let r=ioi(e),n=ooi.test(r),i=n?mnr(hnr(t)):hnr(t),o=new Set,s=c=>c.test(i)||c.test(r)||c.test(`${r} ${i}`),a=!/\b(?:get|list|status|inspect|show|plan|preview|validate|verify)\b/.test(r);return t.dryRun===!0||t.dry_run===!0||t.preview===!0||/\b(?:--dry-run|dry[ _-]?run|preview[ _-]?only)\b/.test(i)?[]:((a&&/\bpublish(?:er|ing)?\b/.test(r)||s(/\b(?:npm|pnpm|yarn)\s+(?:npm\s+)?publish\b|\bcargo\s+publish\b|\btwine\s+upload\b/))&&o.add("publish"),(a&&/\bdeploy(?:er|ment)?\b/.test(r)||s(/\b(?:wrangler|vercel|netlify|firebase|flyctl?|railway)\s+(?:deploy|publish)\b|\bkubectl\s+(?:apply|create|delete|patch|replace|rollout)\b|\bhelm\s+(?:install|upgrade|uninstall)\b|\bterraform\s+apply\b|\bpulumi\s+up\b|\baws\s+cloudformation\s+deploy\b/))&&o.add("deploy"),s(/\bgit\s+push\b|\bgithub\s+push\b|\bgitpush\b/)&&o.add("push"),(r==="push notification"||s(/\b(?:sendmail|mailx|mutt)\b|\bslack[ _-]?(?:send|post)\b/)||!n&&s(/\b(?:send|post)[ _-]?(?:email|message|notification)\b/))&&o.add("send"),!n&&s(/\b(?:purchase|checkout|buy|charge[ _-]?card|create[ _-]?payment)\b/)&&o.add("purchase"),s(/\b(?:signtool|codesign|notarytool)\b|\bcosign\s+sign\b|\b(?:artifact|binary|package)[ _-]?sign\b/)&&o.add("sign"),!n&&s(/\b(?:file|submit)[ _-]?(?:legal|court|claim|tax|trademark|patent)\b/)&&o.add("file-legal"),s(/\bterraform\s+(?:apply|destroy|import)\b|\bpulumi\s+(?:up|destroy|import)\b|\b(?:az|aws|gcloud)\s+[^;&|]*(?:create|update|delete|set-policy|add-member|remove-member)\b/)&&o.add("change-infrastructure"),r==="remote trigger"&&/\b(?:create|update|run)\b/.test(i)&&o.add("change-infrastructure"),[...o])}function wd(e,t){let r=t.trim();return!r||aoi.test(r)?!1:soi[e].test(r)}function loi(e,t){return e.capabilities.externalActions.overrides?.[t]??e.capabilities.externalActions.default}function Kd(e){return async(t,r)=>{let n=e.profile();if(!n)return r();for(let i of gd(t.toolName,t.input)){let o=loi(n,i);if(o==="deny")return{success:!1,output:"",error:`Tool call blocked by ${n.profile.displayName}: external action '${i}' is denied.`};if((o==="ask"||n.capabilities.externalActions.requireCurrentTurnApproval.includes(i))&&!wd(i,e.currentUserPrompt()))return{success:!1,output:"",error:[`Tool call blocked by ${n.profile.displayName}: '${i}' requires explicit approval in the current user turn.`,`Ask the user to name the exact ${i} action and target. Approval from an earlier turn is not sufficient.`].join(" ")}}return r()}}function coi(e){return e?.compiled.capabilities.skills}var ooi,soi,aoi,zu=ye(()=>{"use strict";Er();tx();ooi=/\b(?:bash|shell|power shell|powershell|terminal)\b/;soi={publish:/\b(?:publish|release\s+(?:it|the|this|package|sdk|cli)|ship\s+(?:it|the|this|package|sdk|cli))\b/i,deploy:/\b(?:deploy|roll\s*out|launch\s+(?:it|the|this|site|service)|upload\s+(?:it|the|this)\s+to\s+r2)\b/i,push:/\b(?:git\s+push|push\s+(?:it|the|this|branch|commit|changes|tag))\b/i,send:/\b(?:send|email|message|notify)\s+(?:it|the|this|them|him|her|customer|user|team|recipient)\b/i,purchase:/\b(?:purchase|buy|pay\s+for|charge)\b/i,sign:/\b(?:sign|notarize)\s+(?:it|the|this|artifact|binary|package|installer)\b/i,"file-legal":/\b(?:file|submit)\s+(?:it|the|this|claim|form|application|filing)\b/i,"change-infrastructure":/\b(?:apply|make|perform|proceed\s+with)\s+(?:the|this)?\s*(?:infrastructure|terraform|pulumi|cloud)\s+(?:change|changes|plan)?\b/i},aoi=/\b(?:do\s+not|don't|dont|never|must\s+not|without\s+(?:my|explicit)\s+approval)\b/i});var Wze={};$o(Wze,{grantTerminalFolders:()=>tP});import{existsSync as foi,statSync as hoi}from"node:fs";import{resolve as moi}from"node:path";async function tP(e,t){let r={granted:[],failed:[]},n=new Set;for(let i of t){if(!i)continue;let o=moi(i),s=process.platform==="win32"?o.toLowerCase():o;if(!n.has(s)&&(n.add(s),!(!foi(o)||!hoi(o).isDirectory())))try{let a=await e.grantWorkspaceAccess(o,"terminal-session");a.success&&a.path?r.granted.push(a.path):r.failed.push({path:o,error:a.error??"the host refused the grant"})}catch(a){r.failed.push({path:o,error:a instanceof Error?a.message:String(a)})}}return r}var YL=ye(()=>{"use strict"});function goi(e){let t=e instanceof Error?e.message:String(e);return/authentication failed/iu.test(t)?!1:/connection closed|not connected|ECONNRESET|ECONNREFUSED|EPIPE/iu.test(t)}function woi(){return globalThis.crypto?.randomUUID?.()||`agent-command-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}var Kge,Anr=ye(()=>{"use strict";SS();Kge=class{transport;identity;supportedProtocol;capabilities;handshake=null;sdkSessionListRevision;constructor(t){this.transport=t.transport,this.identity={...t.identity},this.capabilities=t.capabilities?{...t.capabilities}:void 0,this.supportedProtocol=t.supportedProtocol?{...t.supportedProtocol}:{min:CWt,max:xD}}get surface(){return this.identity.surface}get instanceId(){return this.identity.instanceId}get clientIdentity(){return{...this.identity}}get connection(){return this.handshake?structuredClone(this.handshake):null}get surfaceApplication(){let t=this.handshake?.surfaceApplication;return t?{...t}:void 0}async connect(){this.sdkSessionListRevision=void 0;let t;for(let r=0;r<5;r+=1)try{t=await this.transport.request("host.handshake",{identity:{...this.identity},supportedProtocol:{...this.supportedProtocol},capabilities:{...this.capabilities,supportsAccountStateEvents:!0}});break}catch(n){if(r>=4||!goi(n))throw n;await new Promise(i=>setTimeout(i,10*2**r))}if(!TWt(t))throw new Ta("invalid_handshake","Agent host returned an invalid handshake.");return OWt(t,this.identity,this.supportedProtocol),this.handshake=structuredClone(t),structuredClone(t)}async listProviders(t={}){this.requireConnection();let r=await this.transport.request("providers.list",{...t.includeUnavailable===void 0?{}:{includeUnavailable:t.includeUnavailable},client:{...this.identity}});if(!lQe(r))throw new Ta("invalid_response","Agent host returned an invalid provider catalog.");return structuredClone(r)}async refreshProviders(t={}){this.requireConnection();let r=await this.transport.request("providers.refresh",{...t.includeUnavailable===void 0?{}:{includeUnavailable:t.includeUnavailable},client:{...this.identity}});if(!lQe(r))throw new Ta("invalid_response","Agent host returned an invalid refreshed provider catalog.");return structuredClone(r)}async surfaceTools(t){this.requireConnection();let r=await this.transport.request("surface.tools.list",{mode:t,client:{...this.identity}});if(!r||typeof r!="object"||!Array.isArray(r.tools))throw new Ta("invalid_response","Agent host returned an invalid app tool list.");return structuredClone(r)}async listRuntimeEvents(t){this.requireConnection();let r=await this.transport.request("runtime.events.list",structuredClone(t));if(!RWt(r))throw new Ta("invalid_response","Agent host returned an invalid runtime-event page.");return structuredClone(r)}async createSubagentRun(t,r={}){return this.requireConnection(),await this.transport.request("subagent.run.create",{...structuredClone(t),command:this.createCommandContext(r,`subagent:create:${t.childConversationId}:${t.objective}`)})}async listSubagentRuns(t={}){return this.requireConnection(),await this.transport.request("subagent.run.list",structuredClone(t))}async cancelSubagentRun(t,r={}){return this.requireConnection(),await this.transport.request("subagent.run.cancel",{...structuredClone(t),command:this.createCommandContext(r,`subagent:cancel:${t.runId}`)})}async getSubagentSchedulerStatus(){return this.requireConnection(),await this.transport.request("subagent.scheduler.status",{})}async recoverSubagentRuns(t={}){return this.requireConnection(),await this.transport.request("subagent.scheduler.recover",{command:this.createCommandContext(t,"subagent:scheduler:recover")})}async steerTurn(t,r={}){return this.requireConnection(),await this.transport.request("turn.steer",{...structuredClone(t),command:this.createCommandContext(r,`turn:steer:${t.conversationId}:${t.requestId}`)})}async injectContext(t,r={}){return this.requireConnection(),await this.transport.request("context.inject",{...structuredClone(t),command:this.createCommandContext(r,"context:inject:"+t.conversationId+":"+(t.sourceNodeId??"inline"))})}async queueTurnInstruction(t,r={}){return this.requireConnection(),await this.transport.request("turn.queue",{...structuredClone(t),command:this.createCommandContext(r,`turn:queue:${t.conversationId}`)})}async listHeldMessages(t){return this.requireConnection(),structuredClone(await this.transport.request("coordination.held.list",structuredClone(t)))}async releaseHeldMessage(t,r={}){return this.requireConnection(),structuredClone(await this.transport.request("coordination.held.release",{...structuredClone(t),command:this.createCommandContext(r,`coordination:held:release:${t.runId}:${t.messageId}`)}))}async setInboundPolicy(t,r={}){return this.requireConnection(),structuredClone(await this.transport.request("coordination.policy.set",{...structuredClone(t),command:this.createCommandContext(r,`coordination:policy:set:${t.runId}:${t.policy??"derived"}`)}))}async getDevelopmentCoordinationState(t){return this.requireConnection(),structuredClone(await this.transport.request("coordination.state.get",{client:{...this.identity},sessionId:t}))}async executeDevelopmentCoordinationAction(t,r={}){return this.requireConnection(),structuredClone(await this.transport.request("coordination.action",{...structuredClone(t),command:this.createCommandContext(r,`coordination:${t.sessionId}:${t.action}`)}))}async listQueuedInstructions(t){return this.requireConnection(),structuredClone(await this.transport.request("turn.queue.list",structuredClone(t)))}async dropQueuedInstruction(t,r={}){return this.requireConnection(),structuredClone(await this.transport.request("turn.queue.drop",{...structuredClone(t),command:this.createCommandContext(r,t.instructionId?`turn:queue:drop:${t.conversationId}:${t.instructionId}`:`turn:queue:clear:${t.conversationId}`)}))}async resumeTurn(t,r={}){return this.requireConnection(),await this.transport.request("turn.resume",{...structuredClone(t),command:this.createCommandContext(r,`turn:resume:${t.conversationId}:${t.requestId}`)})}async listPermissionRules(){return this.requireConnection(),await this.transport.request("permissions.rules.list",{})}async revokePermissionRule(t){return this.requireConnection(),await this.transport.request("permissions.rules.revoke",{ruleId:t})}async grantWorkspaceAccess(t,r){return this.requireConnection(),structuredClone(await this.transport.request("workspace.access.grant",{path:t,source:r}))}async listWorkspaceAccessGrants(){return this.requireConnection(),structuredClone(await this.transport.request("workspace.access.list",{}))}async revokeWorkspaceAccessGrant(t){return this.requireConnection(),structuredClone(await this.transport.request("workspace.access.revoke",{path:t}))}async loadWorkspaces(){return this.requireConnection(),structuredClone(await this.transport.request("state.workspaces.load",{}))}async scheduleWorkspace(t){return this.requireConnection(),await this.transport.request("workspace.schedule",t)}async applyWorkspaceLifecycle(t){return this.requireConnection(),await this.transport.request("workspace.lifecycle.apply",{...t,command:this.createCommandContext({},"lifecycle:"+t.operationId)})}async backupWorkspace(t){return this.requireConnection(),await this.transport.request("workspace.backup",t)}async environmentWorkspace(t){return this.requireConnection(),this.transport.request("workspace.environment",t)}async accountRequest(t){return this.transport.request("account.request",{...t,client:{...this.identity}})}async workforceRequest(t){return this.requireConnection(),this.transport.request("workforce.request",t)}async notificationsWorkspace(t){return this.transport.request("workspace.notifications",t)}async workspaceRules(t){return this.transport.request("workspace.rules",t)}async workspaceBrowser(t){return this.requireConnection(),this.transport.request("workspace.browser",{...t,client:this.identity})}async workspaceBrowserSession(t){return this.requireConnection(),this.transport.request("workspace.browser.session",{...structuredClone(t),client:{...this.identity}})}async machineDevices(t){return this.requireConnection(),this.transport.request("workspace.machine.devices",{...t,client:this.identity})}async machineGrant(t){return this.requireConnection(),this.transport.request("workspace.machine.grant",{...structuredClone(t),client:{...this.identity}})}async machineGrants(t){return this.requireConnection(),this.transport.request("workspace.machine.grants",{...t,client:this.identity})}async machineRevoke(t){return this.requireConnection(),this.transport.request("workspace.machine.revoke",{...t,client:this.identity})}async machineAct(t){return this.requireConnection(),this.transport.request("workspace.machine.act",{...structuredClone(t),client:{...this.identity}})}async workspaceAudit(t){this.requireConnection();let r=await this.transport.request("workspace.audit",t);if(!JHt(r))throw new Error("Host returned an invalid scoped audit response.");return r}async inferenceRequest(t){this.requireConnection();let r=await this.transport.request("inference.request",t);if(!ZHt(r))throw new Error("Host returned an invalid inference response.");return r}async workspaceUsage(t){this.requireConnection();let r=await this.transport.request("workspace.usage",t);if(!VHt(r))throw new Error("Host returned an invalid scoped usage response.");return r}async saveWorkspaces(t,r){return this.requireConnection(),structuredClone(await this.transport.request("state.workspaces.save",{workspaces:structuredClone(t),...r!==void 0?{expectedRevision:r}:{}}))}async loadConversations(){return this.requireConnection(),structuredClone(await this.transport.request("state.conversations.load",{}))}async saveConversation(t){return this.requireConnection(),structuredClone(await this.transport.request("state.conversations.save",{conversation:structuredClone(t)}))}async deleteConversation(t){return this.requireConnection(),structuredClone(await this.transport.request("state.conversations.delete",{conversationId:t}))}async listWorkspaceDirectory(t){return this.requireConnection(),structuredClone(await this.transport.request("workspace.directory.list",{...structuredClone(t),client:{...this.identity}}))}async readWorkspaceFile(t){return this.requireConnection(),structuredClone(await this.transport.request("workspace.file.read",{...structuredClone(t),client:{...this.identity}}))}async writeWorkspaceFile(t){return this.requireConnection(),structuredClone(await this.transport.request("workspace.file.write",{...structuredClone(t),client:{...this.identity}}))}async runWorkspaceCommand(t){return this.requireConnection(),structuredClone(await this.transport.request("workspace.command.run",{...structuredClone(t),client:{...this.identity}}))}async startWorkspaceTerminal(t){return this.requireConnection(),structuredClone(await this.transport.request("workspace.terminal.start",{...structuredClone(t),client:{...this.identity}}))}async stopWorkspaceTerminal(t){return this.requireConnection(),structuredClone(await this.transport.request("workspace.terminal.stop",{...structuredClone(t),client:{...this.identity}}))}async startWorkspacePty(t){return this.requireConnection(),structuredClone(await this.transport.request("workspace.pty.start",{...structuredClone(t),client:{...this.identity}}))}async snapshotWorkspacePty(t){return this.requireConnection(),structuredClone(await this.transport.request("workspace.pty.snapshot",{...structuredClone(t),client:{...this.identity}}))}async inputWorkspacePty(t){return this.requireConnection(),structuredClone(await this.transport.request("workspace.pty.input",{...structuredClone(t),client:{...this.identity}}))}async resizeWorkspacePty(t){return this.requireConnection(),structuredClone(await this.transport.request("workspace.pty.resize",{...structuredClone(t),client:{...this.identity}}))}async clearWorkspacePty(t){return this.requireConnection(),structuredClone(await this.transport.request("workspace.pty.clear",{...structuredClone(t),client:{...this.identity}}))}async stopWorkspacePty(t){return this.requireConnection(),structuredClone(await this.transport.request("workspace.pty.stop",{...structuredClone(t),client:{...this.identity}}))}async forkConversation(t){return this.requireConnection(),structuredClone(await this.transport.request("conversation.fork",{...structuredClone(t),client:{...this.identity}}))}async annotateConversation(t){return this.requireConnection(),structuredClone(await this.transport.request("conversation.annotate",{...structuredClone(t),client:{...this.identity}}))}async readConversationAttachment(t){return this.requireConnection(),structuredClone(await this.transport.request("conversation.attachment.read",{...structuredClone(t),client:{...this.identity}}))}async selectConversationBranch(t){return this.requireConnection(),structuredClone(await this.transport.request("conversation.branch.select",{...structuredClone(t),client:{...this.identity}}))}async rewindConversation(t){return this.requireConnection(),structuredClone(await this.transport.request("conversation.rewind",{...structuredClone(t),client:{...this.identity}}))}async compactConversation(t,r={}){return this.requestProviderCommand("conversation.compact",t,r,`conversation:compact:${t.conversationId}:${globalThis.crypto.randomUUID()}`)}async conversationTranscript(t){return this.requireConnection(),structuredClone(await this.transport.request("conversation.transcript",{...structuredClone(t),client:{...this.identity}}))}async openConversation(t,r={}){return this.requestProviderCommand("conversation.open",t,r,`conversation:open:${t.conversationId??"new"}:${t.mode??"chat"}`)}async resumeConversation(t,r={}){return this.requestProviderCommand("conversation.resume",t,r,`conversation:resume:${t.conversationId}`)}async attachXenoTui(t,r={}){return this.requestProviderCommand("xeno.tui.attach",t,r,`xeno:tui:attach:${t.conversationId}`)}async listProviderLanes(t){return this.requireConnection(),structuredClone(await this.transport.request("provider.lanes.list",{...structuredClone(t),client:{...this.identity}}))}async getProviderLane(t){return this.requireConnection(),structuredClone(await this.transport.request("provider.lanes.get",{...structuredClone(t),client:{...this.identity}}))}async selectProviderLane(t,r={}){return this.requestProviderCommand("provider.lanes.select",t,r,`provider:select:${t.conversationId}:${t.providerId}:${t.laneId??"automatic"}`)}async attachProviderNative(t,r={}){return this.requestProviderCommand("provider.native.attach",t,r,`provider:native:attach:${t.conversationId}:${t.laneId}`)}async detachProviderNative(t,r={}){return this.requestProviderCommand("provider.native.detach",t,r,`provider:native:detach:${t.conversationId}:${t.laneId}`)}async reattachProviderNative(t,r={}){return this.requestProviderCommand("provider.native.reattach",t,r,`provider:native:reattach:${t.conversationId}:${t.laneId}:${t.terminalId}`)}async stopProviderNative(t,r={}){return this.requestProviderCommand("provider.native.stop",t,r,`provider:native:stop:${t.conversationId}:${t.laneId}:${t.terminalId??"active"}`)}async reconcileProviderLane(t,r={}){return this.requestProviderCommand("provider.reconcile",t,r,`provider:reconcile:${t.conversationId}:${t.laneId}:${t.expectedLaneRevision}`)}async startTurn(t,r={}){this.requireConnection();let n=await this.transport.request("turn.start",{...structuredClone(t),command:this.createCommandContext(r,`turn:start:${t.conversationId}:${t.requestId}`)});if(!_Wt(n))throw new Ta("invalid_response","Agent host returned an invalid turn-start result.");return structuredClone(n)}async cancelTurn(t,r={}){this.requireConnection();let n=await this.transport.request("turn.cancel",{...structuredClone(t),command:this.createCommandContext(r,`turn:cancel:${t.conversationId}:${t.requestId}`)});if(!PWt(n))throw new Ta("invalid_response","Agent host returned an invalid turn-cancel result.");return structuredClone(n)}async answerChooseDirectory(t){return this.requireConnection(),structuredClone(await this.transport.request("elicitation.choose-directory.answer",structuredClone(t)))}async answerWorkspacePlacement(t){return this.requireConnection(),structuredClone(await this.transport.request("elicitation.workspace-placement.answer",structuredClone(t)))}async answerPermission(t){return this.requireConnection(),structuredClone(await this.transport.request("elicitation.permission.answer",structuredClone(t)))}async answerAskUser(t){return this.requireConnection(),structuredClone(await this.transport.request("elicitation.ask-user.answer",structuredClone(t)))}async listSdkSessions(t={}){this.sdkSessionListRevision=void 0;let r=await this.requestSdkControl("sdk.sessions.list",t);return r.success&&Number.isSafeInteger(r.sessionListRevision)&&(this.sdkSessionListRevision=r.sessionListRevision),r}async showSdkSession(t){return this.requestSdkControl("sdk.sessions.show",t)}async attachSdkSession(t){return this.sdkSessionListRevision=void 0,this.requestSdkControl("sdk.sessions.attach",t)}async detachSdkSession(t){return this.sdkSessionListRevision=void 0,this.requestSdkControl("sdk.sessions.detach",t)}async deleteSdkSession(t){let r=this.sdkSessionListRevision??-1;return this.sdkSessionListRevision=void 0,this.requestSdkControl("sdk.sessions.delete",{...t,expectedSessionListRevision:r})}async cleanSdkSessions(t){let r=this.sdkSessionListRevision??-1;return this.sdkSessionListRevision=void 0,this.requestSdkControl("sdk.sessions.clean",{...t,expectedSessionListRevision:r})}async listSdkCheckpoints(t){return this.requestSdkControl("sdk.checkpoints.list",t)}async restoreSdkCheckpoint(t){return this.requestSdkControl("sdk.checkpoints.restore",t)}async deleteSdkCheckpoint(t){return this.requestSdkControl("sdk.checkpoints.delete",t)}async readSdkTaskOutput(t){return this.requestSdkControl("sdk.tasks.output",t)}async stopSdkTask(t){return this.requestSdkControl("sdk.tasks.stop",t)}async requestPluginMcp(t,r={}){return this.requireConnection(),structuredClone(await this.transport.request(t,{...structuredClone(r),client:{...this.identity}}))}async requestSkills(t,r={}){return this.requireConnection(),structuredClone(await this.transport.request(t,{...structuredClone(r),client:{...this.identity}}))}async requestMcpAuth(t,r={}){return this.requireConnection(),structuredClone(await this.transport.request(t,{...structuredClone(r),client:{...this.identity}}))}async requestWorkspaceReport(t,r={}){return this.requireConnection(),structuredClone(await this.transport.request(t,{...structuredClone(r),client:{...this.identity}}))}async requestEvals(t,r={}){return this.requireConnection(),structuredClone(await this.transport.request(t,{...structuredClone(r),client:{...this.identity}}))}async requestRecipes(t,r={}){return this.requireConnection(),structuredClone(await this.transport.request(t,{...structuredClone(r),client:{...this.identity}}))}async requestApprovals(t,r={}){return this.requireConnection(),structuredClone(await this.transport.request(t,{...structuredClone(r),client:{...this.identity}}))}async requestHooks(t,r={}){return this.requireConnection(),structuredClone(await this.transport.request(t,{...structuredClone(r),client:{...this.identity}}))}async requestRuns(t,r={}){return this.requireConnection(),structuredClone(await this.transport.request(t,{...structuredClone(r),client:{...this.identity}}))}async requestWorkflows(t,r={}){return this.requireConnection(),structuredClone(await this.transport.request(t,{...structuredClone(r),client:{...this.identity}}))}async requestArtifacts(t,r={}){return this.requireConnection(),structuredClone(await this.transport.request(t,{...structuredClone(r),client:{...this.identity}}))}async requestPeers(t,r={}){return this.requireConnection(),structuredClone(await this.transport.request(t,{...structuredClone(r),client:{...this.identity}}))}async requestAcp(t,r){return this.requireConnection(),structuredClone(await this.transport.request(t,{...structuredClone(r),client:{...this.identity}}))}async requestKnowledge(t,r){return this.requireConnection(),structuredClone(await this.transport.request(t,{...structuredClone(r),client:{...this.identity}}))}async requestIntake(t,r){return this.requireConnection(),structuredClone(await this.transport.request(t,{...structuredClone(r),client:{...this.identity}}))}async requestSession(t,r){return this.requireConnection(),structuredClone(await this.transport.request(t,{...structuredClone(r),client:{...this.identity}}))}async requestFleet(t,r){return this.requireConnection(),structuredClone(await this.transport.request(t,{...structuredClone(r),client:{...this.identity}}))}async requestRunObservation(t,r){return this.requireConnection(),structuredClone(await this.transport.request(t,{...structuredClone(r),client:{...this.identity}}))}async requestEngineering(t,r){return this.requireConnection(),structuredClone(await this.transport.request(t,{...structuredClone(r),client:{...this.identity}}))}subscribe(t){return this.transport.subscribe(t)}disconnect(){this.handshake=null,this.sdkSessionListRevision=void 0}requireConnection(){if(!this.handshake)throw new Ta("not_connected","Connect to the XENO Agent host before making this request.")}async requestSdkControl(t,r){return this.requireConnection(),structuredClone(await this.transport.request(t,{...structuredClone(r),client:{...this.identity}}))}async requestProviderCommand(t,r,n,i){return this.requireConnection(),structuredClone(await this.transport.request(t,{...structuredClone(r),command:this.createCommandContext(n,i)}))}createCommandContext(t,r){return{schemaVersion:1,commandId:t.commandId||woi(),idempotencyKey:t.idempotencyKey||r,client:{...this.identity}}}async getAcpCapabilitySnapshot(t){return this.requireConnection(),structuredClone(await this.transport.request("acp.capabilitySnapshot.get",t))}async invokeAcpCommand(t){return this.requireConnection(),structuredClone(await this.transport.request("acp.command.invoke",t))}}});function bnr(e){let{client:t,prompter:r}=e,n=t.subscribe(a=>{if(a.type==="elicitation.permission.requested"){i(a.payload);return}a.type==="elicitation.ask-user.requested"&&o(a.payload)});async function i(a){let l=Xz(a,"permissionId");if(!l)return;let c=Xz(a,"toolName")??"an action",d=Xz(a,"path"),u=!1;try{u=await r.confirm(`Allow ${c}?`,d)}catch(p){e.onError?.(p,"elicitation.permission.requested"),u=!1}try{await t.answerPermission({permissionId:l,granted:u})}catch(p){e.onError?.(p,"elicitation.permission.answer")}}async function o(a){let l=Xz(a,"askUserId");if(!l)return;let c=Xz(a,"question")??"The agent asked a question.",d=yoi(a,"options"),u=a&&typeof a=="object"?a.context:void 0,p=u&&typeof u=="object"&&u.kind==="plan-review"?u.plan:void 0;if(typeof p=="string"&&r.reviewPlan){let h;try{let m=await r.reviewPlan(p);h=m.decision==="approve"?{answer:zz.approve,selectedOption:zz.approve}:m.decision==="approve_with_edits"?{answer:m.plan,selectedOption:zz.edits}:{answer:m.feedback?.trim()||zz.keep,selectedOption:zz.keep}}catch(m){e.onError?.(m,"elicitation.ask-user.requested")}try{await t.answerAskUser({askUserId:l,...h??{answer:"",cancelled:!0}})}catch(m){e.onError?.(m,"elicitation.ask-user.answer")}return}let f;try{f=await r.ask(c,d)}catch(h){e.onError?.(h,"elicitation.ask-user.requested"),f=void 0}try{await t.answerAskUser({askUserId:l,...f===void 0?{answer:"",cancelled:!0}:{answer:f}})}catch(h){e.onError?.(h,"elicitation.ask-user.answer")}}let s=!1;return()=>{s||(s=!0,n())}}function Xz(e,t){if(!e||typeof e!="object")return;let r=e[t];return typeof r=="string"&&r.length>0?r:void 0}function yoi(e,t){if(!e||typeof e!="object")return;let r=e[t];if(!Array.isArray(r))return;let n=r.filter(i=>typeof i=="string");return n.length>0?n:void 0}var zz,vnr=ye(()=>{"use strict";zz={approve:"Approve",edits:"Approve with edits",keep:"Keep planning"}});var Inr={};$o(Inr,{startSharedHost:()=>boi});import{createRequire as Aoi}from"node:module";async function boi(e){let t=await import("@xenosystem/agent-interface-runtime"),r=Aoi(import.meta.url).resolve("@xenosystem/agent-interface-runtime/detached-entry"),n=await t.ensureSharedAgentHost({homeDirectory:e.homeDirectory,hostVersion:e.clientVersion,launcherInstanceId:e.instanceId,execPath:process.execPath,entryPath:r,...e.hostRootDirectory?{hostRootDirectory:e.hostRootDirectory}:{}});return{session:n.session,launched:n.launched}}var knr=ye(()=>{"use strict"});var Zge={};$o(Zge,{ATTACH_ENV_VAR:()=>pf,attachAsHeadlessClient:()=>rP,describeAttachRefusal:()=>nP,hostIsTheDefaultFor:()=>Yge,resolveAttachMode:()=>Qw});import{randomUUID as voi}from"node:crypto";import{homedir as Enr}from"node:os";function Yge(e){if(e.authBypassSource&&e.authBypassSource!=="none")return!1;try{return Ioi.has(new URL(e.baseURL).hostname)}catch{return!1}}function Qw(e,t){let r=e?.trim().toLowerCase();if(r===void 0||r==="")return t&&Yge(t)?"optional":"off";if(["0","off","false","no"].includes(r))return"off";if(["1","on","true","yes"].includes(r))return"optional";if(["require","required"].includes(r))return"required";throw new Error(`${pf}="${e}" is not a recognised value. Use 1 (attach, starting a host if none runs), require (attach or fail), or 0 (never attach).`)}async function rP(e){let t=TD({homeDirectory:e.homeDirectory??Enr(),...e.hostRootDirectory?{hostRootDirectory:e.hostRootDirectory}:{}}),r=e.instanceId??voi(),n=await fQe({rootDirectory:t,...e.connectTimeoutMs?{connectTimeoutMs:e.connectTimeoutMs}:{},...e.requestTimeoutMs?{requestTimeoutMs:e.requestTimeoutMs}:{}});if(!n.attached&&e.startIfAbsent&&(n.reason==="no-host"||n.reason==="host-gone"))try{let{startSharedHost:a}=await Promise.resolve().then(()=>(knr(),Inr));await(await a({homeDirectory:e.homeDirectory??Enr(),...e.hostRootDirectory?{hostRootDirectory:e.hostRootDirectory}:{},clientVersion:e.clientVersion,instanceId:r})).session.close().catch(()=>{}),n=await fQe({rootDirectory:t,...e.connectTimeoutMs?{connectTimeoutMs:e.connectTimeoutMs}:{},...e.requestTimeoutMs?{requestTimeoutMs:e.requestTimeoutMs}:{}})}catch(a){return{attached:!1,reason:"start-failed",detail:(a instanceof Error?a.message:String(a)).slice(0,500)}}if(!n.attached)return{attached:!1,reason:n.reason,detail:n.detail};let i=e.prompter!==void 0,o=new Kge({transport:n.session.transport,identity:{clientId:"xeno-agent-cli",clientVersion:e.clientVersion,instanceId:r,surface:"headless-client"},capabilities:{canPresentElicitations:i,...e.account?{providesAccount:{issuer:e.account.issuer,clientId:e.account.clientId}}:{}}});if(e.account){let a=e.account;n.session.transport.setAccountAuthorizer(async l=>{try{return await a.authorize(l.method,l.url)}catch{return null}})}let s=e.prompter?bnr({client:o,prompter:e.prompter,...e.onElicitationError?{onError:e.onElicitationError}:{}}):()=>{};return{attached:!0,host:{client:o,session:n.session,rootDirectory:t,canAnswerPrompts:i,stopRespondingToElicitations:s}}}function nP(e,t){switch(e){case"no-host":return`No XENO Agent host is running for this user (${t}).`;case"host-gone":return`The Agent host's lease is stale \u2014 it exited without releasing it (${t}).`;case"protocol-mismatch":return`This CLI and the running Agent host speak different protocol versions (${t}).`;case"unreachable":return`An Agent host holds the lease but did not answer (${t}).`;case"start-failed":return`No XENO Agent host was running, and this CLI could not start one (${t}).`}}var pf,Ioi,rx=ye(()=>{"use strict";Anr();pfe();vnr();pf="XENO_AGENT_ATTACH",Ioi=new Set(["api.xenosystem.ai","api.xenostudio.ai","direct-api.xenosystem.ai","direct-api.xenostudio.ai"])});var ZL={};$o(ZL,{withHostClient:()=>koi});async function koi(e,t){if(process.env.XENO_AGENT_ATTACH==="off")throw new Error(`${e.what} are managed by the XENO Agent host, and XENO_AGENT_ATTACH=off keeps this CLI from reaching it.`);let{attachAsHeadlessClient:r,describeAttachRefusal:n}=await Promise.resolve().then(()=>(rx(),Zge)),i=await r({clientVersion:e.clientVersion,startIfAbsent:!0,...process.env.XENO_AGENT_HOST_ROOT?{hostRootDirectory:process.env.XENO_AGENT_HOST_ROOT}:{}});if(!i.attached)throw new Error(`The XENO Agent host is not available: ${n(i.reason,i.detail)}`);try{return await i.host.client.connect(),await t(i.host.client)}finally{await i.host.session.close().catch(()=>{})}}var eF=ye(()=>{"use strict"});var Jz={};$o(Jz,{bindPluginMcpCall:()=>Snr,expectSuccess:()=>Cnr,recordingDecisionsInHost:()=>Vze,setPluginMcpHostOpenerForTests:()=>Eoi,withPluginMcpHost:()=>xnr});async function Snr(e,t){let r=await tP(e,[t.cwd,...t.directories??[]]);if(r.granted.length===0&&r.failed.length>0)throw new Error(`The Agent host did not accept this folder: ${r.failed[0].error}`);return async(n,i={})=>await e.requestPluginMcp(`pluginMcp.${n}`,{cwd:t.cwd,...i,caller:{allowedDirectories:[...r.granted]}})}function Eoi(e){Gze=e}async function xnr(e,t){if(Gze){let n=await Gze(e);try{return await t(n.call)}finally{await n.close()}}let{withHostClient:r}=await Promise.resolve().then(()=>(eF(),ZL));return r({clientVersion:e.clientVersion,what:"Plugins and MCP servers"},async n=>t(await Snr(n,e)))}function Cnr(e,t){if(!e.success)throw new Error(typeof e.error=="string"&&e.error?e.error:`${t} failed`);return e}function Vze(e,t){return async r=>{let n=await e(r);return xnr({cwd:t.cwd,clientVersion:t.clientVersion},async i=>Cnr(await i("setMcpApproval",{name:r.name,decision:n}),`Recording ${r.name}`)).catch(i=>t.onUnrecorded?.(r.name,i instanceof Error?i.message:String(i))),n}}var Gze,tF=ye(()=>{"use strict";YL()});import{resolve as Tnr}from"node:path";async function zze(e){let{resolveCliPluginStore:t}=await Promise.resolve().then(()=>(Hw(),Onr)),r=t();if(r.layout!=="extensions"&&r.layout!=="legacy")return!1;let n=i=>process.platform==="win32"?Tnr(i).toLowerCase():Tnr(i);return n(r.pluginDir)===n(e)}async function Xze(e,t){let{withPluginMcpHost:r,expectSuccess:n}=await Promise.resolve().then(()=>(tF(),Jz));return r({cwd:process.cwd(),clientVersion:Pe},async i=>n(await i(e,t),e))}async function _nr(e){return await zze(e.pluginDir)?(await Xze("trustPublisher",{keyId:e.keyId,publisher:e.publisher,publicKey:e.publicKey}),hw(e.pluginDir)):Wue(e)}async function Pnr(e,t){return await zze(e)?(await Xze("untrustPublisher",{keyId:t})).removed===!0:Gue(e,t)}async function $nr(e,t){return await zze(e)?(await Xze("setRequireSignedPlugins",{required:t}),hw(e)):Vue(e,t)}var ewe,Rnr,Jze=ye(()=>{"use strict";Er();Ao();Er();ewe=hw,Rnr=Hue});var Onr={};$o(Onr,{activateCliPluginRuntime:()=>nF,collectPluginOutputStyles:()=>Lnr,createCliPluginHost:()=>ol,createPluginPromptSections:()=>Dnr,getCliPluginDir:()=>il,getPluginOutputStyleImpacts:()=>tX,getPluginPromptImpacts:()=>eX,inspectCliPluginRuntime:()=>rF,installCliPlugin:()=>Yz,removeCliPlugin:()=>Zz,resolveCliPluginStore:()=>Zze,setCliPluginEnabled:()=>iP});import{existsSync as Soi,mkdirSync as xoi,readdirSync as Coi,statSync as Nnr}from"node:fs";import{homedir as Toi}from"node:os";import{join as Roi,resolve as Kz}from"node:path";function Mnr(e){try{return Nnr(e).isDirectory()&&Coi(e).length>0}catch{return!1}}function Zze(e=process.env,t=Toi()){let r=e.XENO_PLUGIN_DIR?.trim();if(r)return{pluginDir:Kz(r),layout:"override"};let n=XWt(t,e),i=Roi(Za(e),"plugins");return!Mnr(n.pluginDir)&&Mnr(i)?{pluginDir:Kz(i),layout:"cli-legacy"}:{pluginDir:Kz(n.pluginDir),layout:n.layout}}function il(e){return e?Kz(e):Zze().pluginDir}function ol(e={}){let t=il(e.pluginDir);xoi(t,{recursive:!0});let r=Rnr(t);return new Z6({pluginDir:t,autoActivate:e.autoActivate,host:{appName:"xeno-agent-cli",appVersion:Pe,platform:process.platform},trustedPublisherKeys:r.trustedPublisherKeys,requireSignedPlugins:r.store.requireSignedPlugins})}async function rF(e={}){let t=il(e.pluginDir),r=ol({pluginDir:t,autoActivate:!1});return{pluginDir:t,plugins:r.listInstalled(),trust:await ewe(t)}}function Bnr(e,t){let r=t.template?.trim();if(!r)return null;let n=t.description?.trim();return["","",`# Plugin Prompt: ${t.name}`,`Source: ${e.manifest.name}`,...n?[`Description: ${n}`]:[],"",r].join(`
5521
+ `)}}}function Jge(e,t=process.cwd()){let r=e.trim(),n=()=>typeof t=="function"?t():t;return async(i,o)=>{if(!r)return o();let s=uf(r,n());if(!s)return{success:!1,output:"",error:`Tool call blocked: XENO agent profile is unavailable: ${r}`};let a=oc(s.compiled.capabilities.tools);return a?a(i,o):o()}}function hnr(e){let t=[];for(let r of["command","action","operation","subcommand","method"])typeof e[r]=="string"&&t.push(e[r]);return typeof e.args=="string"&&t.push(e.args),Array.isArray(e.args)&&t.push(...e.args.filter(r=>typeof r=="string")),t.join(" ").trim().toLowerCase()}function ioi(e){return e.trim().replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().replace(/[^a-z0-9]+/g," ")}function mnr(e){return e.replace(/<<-?\s*(['"]?)([a-z_][a-z0-9_]*)\1[\s\S]*?\n[ \t]*\2(?![a-z0-9_])/g," ").replace(/\b((?:ba|z|da)?sh|pwsh|powershell)\s+(-[a-z]*c|-command)\s+(['"])([\s\S]*?)\3/g,"$1 ; $4 ;").replace(/'[^']*'|"(?:\\.|[^"\\])*"/g," ").replace(/\s+/g," ").trim()}function gd(e,t){let r=ioi(e),n=ooi.test(r),i=n?mnr(hnr(t)):hnr(t),o=new Set,s=c=>c.test(i)||c.test(r)||c.test(`${r} ${i}`),a=!/\b(?:get|list|status|inspect|show|plan|preview|validate|verify)\b/.test(r);return t.dryRun===!0||t.dry_run===!0||t.preview===!0||/\b(?:--dry-run|dry[ _-]?run|preview[ _-]?only)\b/.test(i)?[]:((a&&/\bpublish(?:er|ing)?\b/.test(r)||s(/\b(?:npm|pnpm|yarn)\s+(?:npm\s+)?publish\b|\bcargo\s+publish\b|\btwine\s+upload\b/))&&o.add("publish"),(a&&/\bdeploy(?:er|ment)?\b/.test(r)||s(/\b(?:wrangler|vercel|netlify|firebase|flyctl?|railway)\s+(?:deploy|publish)\b|\bkubectl\s+(?:apply|create|delete|patch|replace|rollout)\b|\bhelm\s+(?:install|upgrade|uninstall)\b|\bterraform\s+apply\b|\bpulumi\s+up\b|\baws\s+cloudformation\s+deploy\b/))&&o.add("deploy"),s(/\bgit\s+push\b|\bgithub\s+push\b|\bgitpush\b/)&&o.add("push"),(r==="push notification"||s(/\b(?:sendmail|mailx|mutt)\b|\bslack[ _-]?(?:send|post)\b/)||!n&&s(/\b(?:send|post)[ _-]?(?:email|message|notification)\b/))&&o.add("send"),!n&&s(/\b(?:purchase|checkout|buy|charge[ _-]?card|create[ _-]?payment)\b/)&&o.add("purchase"),s(/\b(?:signtool|codesign|notarytool)\b|\bcosign\s+sign\b|\b(?:artifact|binary|package)[ _-]?sign\b/)&&o.add("sign"),!n&&s(/\b(?:file|submit)[ _-]?(?:legal|court|claim|tax|trademark|patent)\b/)&&o.add("file-legal"),s(/\bterraform\s+(?:apply|destroy|import)\b|\bpulumi\s+(?:up|destroy|import)\b|\b(?:az|aws|gcloud)\s+[^;&|]*(?:create|update|delete|set-policy|add-member|remove-member)\b/)&&o.add("change-infrastructure"),r==="remote trigger"&&/\b(?:create|update|run)\b/.test(i)&&o.add("change-infrastructure"),[...o])}function wd(e,t){let r=t.trim();return!r||aoi.test(r)?!1:soi[e].test(r)}function loi(e,t){return e.capabilities.externalActions.overrides?.[t]??e.capabilities.externalActions.default}function Kd(e){return async(t,r)=>{let n=e.profile();if(!n)return r();for(let i of gd(t.toolName,t.input)){let o=loi(n,i);if(o==="deny")return{success:!1,output:"",error:`Tool call blocked by ${n.profile.displayName}: external action '${i}' is denied.`};if((o==="ask"||n.capabilities.externalActions.requireCurrentTurnApproval.includes(i))&&!wd(i,e.currentUserPrompt()))return{success:!1,output:"",error:[`Tool call blocked by ${n.profile.displayName}: '${i}' requires explicit approval in the current user turn.`,`Ask the user to name the exact ${i} action and target. Approval from an earlier turn is not sufficient.`].join(" ")}}return r()}}function coi(e){return e?.compiled.capabilities.skills}var ooi,soi,aoi,zu=ye(()=>{"use strict";Er();tx();ooi=/\b(?:bash|shell|power shell|powershell|terminal)\b/;soi={publish:/\b(?:publish|release\s+(?:it|the|this|package|sdk|cli)|ship\s+(?:it|the|this|package|sdk|cli))\b/i,deploy:/\b(?:deploy|roll\s*out|launch\s+(?:it|the|this|site|service)|upload\s+(?:it|the|this)\s+to\s+r2)\b/i,push:/\b(?:git\s+push|push\s+(?:it|the|this|branch|commit|changes|tag))\b/i,send:/\b(?:send|email|message|notify)\s+(?:it|the|this|them|him|her|customer|user|team|recipient)\b/i,purchase:/\b(?:purchase|buy|pay\s+for|charge)\b/i,sign:/\b(?:sign|notarize)\s+(?:it|the|this|artifact|binary|package|installer)\b/i,"file-legal":/\b(?:file|submit)\s+(?:it|the|this|claim|form|application|filing)\b/i,"change-infrastructure":/\b(?:apply|make|perform|proceed\s+with)\s+(?:the|this)?\s*(?:infrastructure|terraform|pulumi|cloud)\s+(?:change|changes|plan)?\b/i},aoi=/\b(?:do\s+not|don't|dont|never|must\s+not|without\s+(?:my|explicit)\s+approval)\b/i});var Wze={};$o(Wze,{grantTerminalFolders:()=>tP});import{existsSync as foi,statSync as hoi}from"node:fs";import{resolve as moi}from"node:path";async function tP(e,t){let r={granted:[],failed:[]},n=new Set;for(let i of t){if(!i)continue;let o=moi(i),s=process.platform==="win32"?o.toLowerCase():o;if(!n.has(s)&&(n.add(s),!(!foi(o)||!hoi(o).isDirectory())))try{let a=await e.grantWorkspaceAccess(o,"terminal-session");a.success&&a.path?r.granted.push(a.path):r.failed.push({path:o,error:a.error??"the host refused the grant"})}catch(a){r.failed.push({path:o,error:a instanceof Error?a.message:String(a)})}}return r}var YL=ye(()=>{"use strict"});function goi(e){let t=e instanceof Error?e.message:String(e);return/authentication failed/iu.test(t)?!1:/connection closed|not connected|ECONNRESET|ECONNREFUSED|EPIPE/iu.test(t)}function woi(){return globalThis.crypto?.randomUUID?.()||`agent-command-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}var Kge,Anr=ye(()=>{"use strict";SS();Kge=class{transport;identity;supportedProtocol;capabilities;handshake=null;sdkSessionListRevision;constructor(t){this.transport=t.transport,this.identity={...t.identity},this.capabilities=t.capabilities?{...t.capabilities}:void 0,this.supportedProtocol=t.supportedProtocol?{...t.supportedProtocol}:{min:CWt,max:xD}}get surface(){return this.identity.surface}get instanceId(){return this.identity.instanceId}get clientIdentity(){return{...this.identity}}get connection(){return this.handshake?structuredClone(this.handshake):null}get surfaceApplication(){let t=this.handshake?.surfaceApplication;return t?{...t}:void 0}async connect(){this.sdkSessionListRevision=void 0;let t;for(let r=0;r<5;r+=1)try{t=await this.transport.request("host.handshake",{identity:{...this.identity},supportedProtocol:{...this.supportedProtocol},capabilities:{...this.capabilities,supportsAccountStateEvents:!0}});break}catch(n){if(r>=4||!goi(n))throw n;await new Promise(i=>setTimeout(i,10*2**r))}if(!TWt(t))throw new Ta("invalid_handshake","Agent host returned an invalid handshake.");return OWt(t,this.identity,this.supportedProtocol),this.handshake=structuredClone(t),structuredClone(t)}async listProviders(t={}){this.requireConnection();let r=await this.transport.request("providers.list",{...t.includeUnavailable===void 0?{}:{includeUnavailable:t.includeUnavailable},client:{...this.identity}});if(!lQe(r))throw new Ta("invalid_response","Agent host returned an invalid provider catalog.");return structuredClone(r)}async refreshProviders(t={}){this.requireConnection();let r=await this.transport.request("providers.refresh",{...t.includeUnavailable===void 0?{}:{includeUnavailable:t.includeUnavailable},client:{...this.identity}});if(!lQe(r))throw new Ta("invalid_response","Agent host returned an invalid refreshed provider catalog.");return structuredClone(r)}async surfaceTools(t){this.requireConnection();let r=await this.transport.request("surface.tools.list",{mode:t,client:{...this.identity}});if(!r||typeof r!="object"||!Array.isArray(r.tools))throw new Ta("invalid_response","Agent host returned an invalid app tool list.");return structuredClone(r)}async listRuntimeEvents(t){this.requireConnection();let r=await this.transport.request("runtime.events.list",structuredClone(t));if(!RWt(r))throw new Ta("invalid_response","Agent host returned an invalid runtime-event page.");return structuredClone(r)}async createSubagentRun(t,r={}){return this.requireConnection(),await this.transport.request("subagent.run.create",{...structuredClone(t),command:this.createCommandContext(r,`subagent:create:${t.childConversationId}:${t.objective}`)})}async listSubagentRuns(t={}){return this.requireConnection(),await this.transport.request("subagent.run.list",structuredClone(t))}async cancelSubagentRun(t,r={}){return this.requireConnection(),await this.transport.request("subagent.run.cancel",{...structuredClone(t),command:this.createCommandContext(r,`subagent:cancel:${t.runId}`)})}async getSubagentSchedulerStatus(){return this.requireConnection(),await this.transport.request("subagent.scheduler.status",{})}async recoverSubagentRuns(t={}){return this.requireConnection(),await this.transport.request("subagent.scheduler.recover",{command:this.createCommandContext(t,"subagent:scheduler:recover")})}async steerTurn(t,r={}){return this.requireConnection(),await this.transport.request("turn.steer",{...structuredClone(t),command:this.createCommandContext(r,`turn:steer:${t.conversationId}:${t.requestId}`)})}async injectContext(t,r={}){return this.requireConnection(),await this.transport.request("context.inject",{...structuredClone(t),command:this.createCommandContext(r,"context:inject:"+t.conversationId+":"+(t.sourceNodeId??"inline"))})}async queueTurnInstruction(t,r={}){return this.requireConnection(),await this.transport.request("turn.queue",{...structuredClone(t),command:this.createCommandContext(r,`turn:queue:${t.conversationId}`)})}async listHeldMessages(t){return this.requireConnection(),structuredClone(await this.transport.request("coordination.held.list",structuredClone(t)))}async releaseHeldMessage(t,r={}){return this.requireConnection(),structuredClone(await this.transport.request("coordination.held.release",{...structuredClone(t),command:this.createCommandContext(r,`coordination:held:release:${t.runId}:${t.messageId}`)}))}async setInboundPolicy(t,r={}){return this.requireConnection(),structuredClone(await this.transport.request("coordination.policy.set",{...structuredClone(t),command:this.createCommandContext(r,`coordination:policy:set:${t.runId}:${t.policy??"derived"}`)}))}async getDevelopmentCoordinationState(t){return this.requireConnection(),structuredClone(await this.transport.request("coordination.state.get",{client:{...this.identity},sessionId:t}))}async executeDevelopmentCoordinationAction(t,r={}){return this.requireConnection(),structuredClone(await this.transport.request("coordination.action",{...structuredClone(t),command:this.createCommandContext(r,`coordination:${t.sessionId}:${t.action}`)}))}async listQueuedInstructions(t){return this.requireConnection(),structuredClone(await this.transport.request("turn.queue.list",structuredClone(t)))}async dropQueuedInstruction(t,r={}){return this.requireConnection(),structuredClone(await this.transport.request("turn.queue.drop",{...structuredClone(t),command:this.createCommandContext(r,t.instructionId?`turn:queue:drop:${t.conversationId}:${t.instructionId}`:`turn:queue:clear:${t.conversationId}`)}))}async resumeTurn(t,r={}){return this.requireConnection(),await this.transport.request("turn.resume",{...structuredClone(t),command:this.createCommandContext(r,`turn:resume:${t.conversationId}:${t.requestId}`)})}async listPermissionRules(){return this.requireConnection(),await this.transport.request("permissions.rules.list",{})}async revokePermissionRule(t){return this.requireConnection(),await this.transport.request("permissions.rules.revoke",{ruleId:t})}async grantWorkspaceAccess(t,r){return this.requireConnection(),structuredClone(await this.transport.request("workspace.access.grant",{path:t,source:r}))}async listWorkspaceAccessGrants(){return this.requireConnection(),structuredClone(await this.transport.request("workspace.access.list",{}))}async revokeWorkspaceAccessGrant(t){return this.requireConnection(),structuredClone(await this.transport.request("workspace.access.revoke",{path:t}))}async loadWorkspaces(){return this.requireConnection(),structuredClone(await this.transport.request("state.workspaces.load",{}))}async scheduleWorkspace(t){return this.requireConnection(),await this.transport.request("workspace.schedule",t)}async applyWorkspaceLifecycle(t){return this.requireConnection(),await this.transport.request("workspace.lifecycle.apply",{...t,command:this.createCommandContext({},"lifecycle:"+t.operationId)})}async backupWorkspace(t){return this.requireConnection(),await this.transport.request("workspace.backup",t)}async environmentWorkspace(t){return this.requireConnection(),this.transport.request("workspace.environment",t)}async accountRequest(t){return this.transport.request("account.request",{...t,client:{...this.identity}})}async workforceRequest(t){return this.requireConnection(),this.transport.request("workforce.request",t)}async notificationsWorkspace(t){return this.transport.request("workspace.notifications",t)}async workspaceRules(t){return this.transport.request("workspace.rules",t)}async workspaceBrowser(t){return this.requireConnection(),this.transport.request("workspace.browser",{...t,client:this.identity})}async workspaceBrowserSession(t){return this.requireConnection(),this.transport.request("workspace.browser.session",{...structuredClone(t),client:{...this.identity}})}async machineDevices(t){return this.requireConnection(),this.transport.request("workspace.machine.devices",{...t,client:this.identity})}async machineGrant(t){return this.requireConnection(),this.transport.request("workspace.machine.grant",{...structuredClone(t),client:{...this.identity}})}async machineGrants(t){return this.requireConnection(),this.transport.request("workspace.machine.grants",{...t,client:this.identity})}async machineRevoke(t){return this.requireConnection(),this.transport.request("workspace.machine.revoke",{...t,client:this.identity})}async machineAct(t){return this.requireConnection(),this.transport.request("workspace.machine.act",{...structuredClone(t),client:{...this.identity}})}async workspaceAudit(t){this.requireConnection();let r=await this.transport.request("workspace.audit",t);if(!JHt(r))throw new Error("Host returned an invalid scoped audit response.");return r}async inferenceRequest(t){this.requireConnection();let r=await this.transport.request("inference.request",t);if(!ZHt(r))throw new Error("Host returned an invalid inference response.");return r}async workspaceUsage(t){this.requireConnection();let r=await this.transport.request("workspace.usage",t);if(!VHt(r))throw new Error("Host returned an invalid scoped usage response.");return r}async saveWorkspaces(t,r){return this.requireConnection(),structuredClone(await this.transport.request("state.workspaces.save",{workspaces:structuredClone(t),...r!==void 0?{expectedRevision:r}:{}}))}async loadConversations(){return this.requireConnection(),structuredClone(await this.transport.request("state.conversations.load",{}))}async saveConversation(t){return this.requireConnection(),structuredClone(await this.transport.request("state.conversations.save",{conversation:structuredClone(t)}))}async deleteConversation(t){return this.requireConnection(),structuredClone(await this.transport.request("state.conversations.delete",{conversationId:t}))}async listWorkspaceDirectory(t){return this.requireConnection(),structuredClone(await this.transport.request("workspace.directory.list",{...structuredClone(t),client:{...this.identity}}))}async readWorkspaceFile(t){return this.requireConnection(),structuredClone(await this.transport.request("workspace.file.read",{...structuredClone(t),client:{...this.identity}}))}async writeWorkspaceFile(t){return this.requireConnection(),structuredClone(await this.transport.request("workspace.file.write",{...structuredClone(t),client:{...this.identity}}))}async runWorkspaceCommand(t){return this.requireConnection(),structuredClone(await this.transport.request("workspace.command.run",{...structuredClone(t),client:{...this.identity}}))}async startWorkspaceTerminal(t){return this.requireConnection(),structuredClone(await this.transport.request("workspace.terminal.start",{...structuredClone(t),client:{...this.identity}}))}async stopWorkspaceTerminal(t){return this.requireConnection(),structuredClone(await this.transport.request("workspace.terminal.stop",{...structuredClone(t),client:{...this.identity}}))}async startWorkspacePty(t){return this.requireConnection(),structuredClone(await this.transport.request("workspace.pty.start",{...structuredClone(t),client:{...this.identity}}))}async snapshotWorkspacePty(t){return this.requireConnection(),structuredClone(await this.transport.request("workspace.pty.snapshot",{...structuredClone(t),client:{...this.identity}}))}async inputWorkspacePty(t){return this.requireConnection(),structuredClone(await this.transport.request("workspace.pty.input",{...structuredClone(t),client:{...this.identity}}))}async resizeWorkspacePty(t){return this.requireConnection(),structuredClone(await this.transport.request("workspace.pty.resize",{...structuredClone(t),client:{...this.identity}}))}async clearWorkspacePty(t){return this.requireConnection(),structuredClone(await this.transport.request("workspace.pty.clear",{...structuredClone(t),client:{...this.identity}}))}async stopWorkspacePty(t){return this.requireConnection(),structuredClone(await this.transport.request("workspace.pty.stop",{...structuredClone(t),client:{...this.identity}}))}async forkConversation(t){return this.requireConnection(),structuredClone(await this.transport.request("conversation.fork",{...structuredClone(t),client:{...this.identity}}))}async annotateConversation(t){return this.requireConnection(),structuredClone(await this.transport.request("conversation.annotate",{...structuredClone(t),client:{...this.identity}}))}async readConversationAttachment(t){return this.requireConnection(),structuredClone(await this.transport.request("conversation.attachment.read",{...structuredClone(t),client:{...this.identity}}))}async selectConversationBranch(t){return this.requireConnection(),structuredClone(await this.transport.request("conversation.branch.select",{...structuredClone(t),client:{...this.identity}}))}async rewindConversation(t){return this.requireConnection(),structuredClone(await this.transport.request("conversation.rewind",{...structuredClone(t),client:{...this.identity}}))}async compactConversation(t,r={}){return this.requestProviderCommand("conversation.compact",t,r,`conversation:compact:${t.conversationId}:${globalThis.crypto.randomUUID()}`)}async conversationTranscript(t){return this.requireConnection(),structuredClone(await this.transport.request("conversation.transcript",{...structuredClone(t),client:{...this.identity}}))}async openConversation(t,r={}){return this.requestProviderCommand("conversation.open",t,r,`conversation:open:${t.conversationId??"new"}:${t.mode??"chat"}`)}async resumeConversation(t,r={}){return this.requestProviderCommand("conversation.resume",t,r,`conversation:resume:${t.conversationId}`)}async attachXenoTui(t,r={}){return this.requestProviderCommand("xeno.tui.attach",t,r,`xeno:tui:attach:${t.conversationId}`)}async listProviderLanes(t){return this.requireConnection(),structuredClone(await this.transport.request("provider.lanes.list",{...structuredClone(t),client:{...this.identity}}))}async getProviderLane(t){return this.requireConnection(),structuredClone(await this.transport.request("provider.lanes.get",{...structuredClone(t),client:{...this.identity}}))}async selectProviderLane(t,r={}){return this.requestProviderCommand("provider.lanes.select",t,r,`provider:select:${t.conversationId}:${t.providerId}:${t.laneId??"automatic"}`)}async attachProviderNative(t,r={}){return this.requestProviderCommand("provider.native.attach",t,r,`provider:native:attach:${t.conversationId}:${t.laneId}`)}async detachProviderNative(t,r={}){return this.requestProviderCommand("provider.native.detach",t,r,`provider:native:detach:${t.conversationId}:${t.laneId}`)}async reattachProviderNative(t,r={}){return this.requestProviderCommand("provider.native.reattach",t,r,`provider:native:reattach:${t.conversationId}:${t.laneId}:${t.terminalId}`)}async stopProviderNative(t,r={}){return this.requestProviderCommand("provider.native.stop",t,r,`provider:native:stop:${t.conversationId}:${t.laneId}:${t.terminalId??"active"}`)}async reconcileProviderLane(t,r={}){return this.requestProviderCommand("provider.reconcile",t,r,`provider:reconcile:${t.conversationId}:${t.laneId}:${t.expectedLaneRevision}`)}async startTurn(t,r={}){this.requireConnection();let n=await this.transport.request("turn.start",{...structuredClone(t),command:this.createCommandContext(r,`turn:start:${t.conversationId}:${t.requestId}`)});if(!_Wt(n))throw new Ta("invalid_response","Agent host returned an invalid turn-start result.");return structuredClone(n)}async cancelTurn(t,r={}){this.requireConnection();let n=await this.transport.request("turn.cancel",{...structuredClone(t),command:this.createCommandContext(r,`turn:cancel:${t.conversationId}:${t.requestId}`)});if(!PWt(n))throw new Ta("invalid_response","Agent host returned an invalid turn-cancel result.");return structuredClone(n)}async answerChooseDirectory(t){return this.requireConnection(),structuredClone(await this.transport.request("elicitation.choose-directory.answer",structuredClone(t)))}async answerWorkspacePlacement(t){return this.requireConnection(),structuredClone(await this.transport.request("elicitation.workspace-placement.answer",structuredClone(t)))}async answerPermission(t){return this.requireConnection(),structuredClone(await this.transport.request("elicitation.permission.answer",structuredClone(t)))}async answerAskUser(t){return this.requireConnection(),structuredClone(await this.transport.request("elicitation.ask-user.answer",structuredClone(t)))}async listSdkSessions(t={}){this.sdkSessionListRevision=void 0;let r=await this.requestSdkControl("sdk.sessions.list",t);return r.success&&Number.isSafeInteger(r.sessionListRevision)&&(this.sdkSessionListRevision=r.sessionListRevision),r}async showSdkSession(t){return this.requestSdkControl("sdk.sessions.show",t)}async attachSdkSession(t){return this.sdkSessionListRevision=void 0,this.requestSdkControl("sdk.sessions.attach",t)}async detachSdkSession(t){return this.sdkSessionListRevision=void 0,this.requestSdkControl("sdk.sessions.detach",t)}async deleteSdkSession(t){let r=this.sdkSessionListRevision??-1;return this.sdkSessionListRevision=void 0,this.requestSdkControl("sdk.sessions.delete",{...t,expectedSessionListRevision:r})}async cleanSdkSessions(t){let r=this.sdkSessionListRevision??-1;return this.sdkSessionListRevision=void 0,this.requestSdkControl("sdk.sessions.clean",{...t,expectedSessionListRevision:r})}async listSdkCheckpoints(t){return this.requestSdkControl("sdk.checkpoints.list",t)}async restoreSdkCheckpoint(t){return this.requestSdkControl("sdk.checkpoints.restore",t)}async deleteSdkCheckpoint(t){return this.requestSdkControl("sdk.checkpoints.delete",t)}async readSdkTaskOutput(t){return this.requestSdkControl("sdk.tasks.output",t)}async stopSdkTask(t){return this.requestSdkControl("sdk.tasks.stop",t)}async requestPluginMcp(t,r={}){return this.requireConnection(),structuredClone(await this.transport.request(t,{...structuredClone(r),client:{...this.identity}}))}async requestSkills(t,r={}){return this.requireConnection(),structuredClone(await this.transport.request(t,{...structuredClone(r),client:{...this.identity}}))}async requestMcpAuth(t,r={}){return this.requireConnection(),structuredClone(await this.transport.request(t,{...structuredClone(r),client:{...this.identity}}))}async requestWorkspaceReport(t,r={}){return this.requireConnection(),structuredClone(await this.transport.request(t,{...structuredClone(r),client:{...this.identity}}))}async requestEvals(t,r={}){return this.requireConnection(),structuredClone(await this.transport.request(t,{...structuredClone(r),client:{...this.identity}}))}async requestRecipes(t,r={}){return this.requireConnection(),structuredClone(await this.transport.request(t,{...structuredClone(r),client:{...this.identity}}))}async requestApprovals(t,r={}){return this.requireConnection(),structuredClone(await this.transport.request(t,{...structuredClone(r),client:{...this.identity}}))}async requestHooks(t,r={}){return this.requireConnection(),structuredClone(await this.transport.request(t,{...structuredClone(r),client:{...this.identity}}))}async requestRuns(t,r={}){return this.requireConnection(),structuredClone(await this.transport.request(t,{...structuredClone(r),client:{...this.identity}}))}async requestWorkflows(t,r={}){return this.requireConnection(),structuredClone(await this.transport.request(t,{...structuredClone(r),client:{...this.identity}}))}async requestArtifacts(t,r={}){return this.requireConnection(),structuredClone(await this.transport.request(t,{...structuredClone(r),client:{...this.identity}}))}async requestPeers(t,r={}){return this.requireConnection(),structuredClone(await this.transport.request(t,{...structuredClone(r),client:{...this.identity}}))}async requestAcp(t,r){return this.requireConnection(),structuredClone(await this.transport.request(t,{...structuredClone(r),client:{...this.identity}}))}async requestKnowledge(t,r){return this.requireConnection(),structuredClone(await this.transport.request(t,{...structuredClone(r),client:{...this.identity}}))}async requestIntake(t,r){return this.requireConnection(),structuredClone(await this.transport.request(t,{...structuredClone(r),client:{...this.identity}}))}async requestSession(t,r){return this.requireConnection(),structuredClone(await this.transport.request(t,{...structuredClone(r),client:{...this.identity}}))}async requestFleet(t,r){return this.requireConnection(),structuredClone(await this.transport.request(t,{...structuredClone(r),client:{...this.identity}}))}async requestRunObservation(t,r){return this.requireConnection(),structuredClone(await this.transport.request(t,{...structuredClone(r),client:{...this.identity}}))}async requestEngineering(t,r){return this.requireConnection(),structuredClone(await this.transport.request(t,{...structuredClone(r),client:{...this.identity}}))}subscribe(t){return this.transport.subscribe(t)}disconnect(){this.handshake=null,this.sdkSessionListRevision=void 0}requireConnection(){if(!this.handshake)throw new Ta("not_connected","Connect to the XENO Agent host before making this request.")}async requestSdkControl(t,r){return this.requireConnection(),structuredClone(await this.transport.request(t,{...structuredClone(r),client:{...this.identity}}))}async requestProviderCommand(t,r,n,i){return this.requireConnection(),structuredClone(await this.transport.request(t,{...structuredClone(r),command:this.createCommandContext(n,i)}))}createCommandContext(t,r){return{schemaVersion:1,commandId:t.commandId||woi(),idempotencyKey:t.idempotencyKey||r,client:{...this.identity}}}async getAcpCapabilitySnapshot(t){return this.requireConnection(),structuredClone(await this.transport.request("acp.capabilitySnapshot.get",t))}async invokeAcpCommand(t){return this.requireConnection(),structuredClone(await this.transport.request("acp.command.invoke",t))}}});function bnr(e){let{client:t,prompter:r}=e,n=t.subscribe(a=>{if(a.type==="elicitation.permission.requested"){i(a.payload);return}a.type==="elicitation.ask-user.requested"&&o(a.payload)});async function i(a){let l=Xz(a,"permissionId");if(!l)return;let c=Xz(a,"toolName")??"an action",d=Xz(a,"path"),u=!1;try{u=await r.confirm(`Allow ${c}?`,d)}catch(p){e.onError?.(p,"elicitation.permission.requested"),u=!1}try{await t.answerPermission({permissionId:l,granted:u})}catch(p){e.onError?.(p,"elicitation.permission.answer")}}async function o(a){let l=Xz(a,"askUserId");if(!l)return;let c=Xz(a,"question")??"The agent asked a question.",d=yoi(a,"options"),u=a&&typeof a=="object"?a.context:void 0,p=u&&typeof u=="object"&&u.kind==="plan-review"?u.plan:void 0;if(typeof p=="string"&&r.reviewPlan){let h;try{let m=await r.reviewPlan(p);h=m.decision==="approve"?{answer:zz.approve,selectedOption:zz.approve}:m.decision==="approve_with_edits"?{answer:m.plan,selectedOption:zz.edits}:{answer:m.feedback?.trim()||zz.keep,selectedOption:zz.keep}}catch(m){e.onError?.(m,"elicitation.ask-user.requested")}try{await t.answerAskUser({askUserId:l,...h??{answer:"",cancelled:!0}})}catch(m){e.onError?.(m,"elicitation.ask-user.answer")}return}let f;try{f=await r.ask(c,d)}catch(h){e.onError?.(h,"elicitation.ask-user.requested"),f=void 0}try{await t.answerAskUser({askUserId:l,...f===void 0?{answer:"",cancelled:!0}:{answer:f}})}catch(h){e.onError?.(h,"elicitation.ask-user.answer")}}let s=!1;return()=>{s||(s=!0,n())}}function Xz(e,t){if(!e||typeof e!="object")return;let r=e[t];return typeof r=="string"&&r.length>0?r:void 0}function yoi(e,t){if(!e||typeof e!="object")return;let r=e[t];if(!Array.isArray(r))return;let n=r.filter(i=>typeof i=="string");return n.length>0?n:void 0}var zz,vnr=ye(()=>{"use strict";zz={approve:"Approve",edits:"Approve with edits",keep:"Keep planning"}});var Inr={};$o(Inr,{startSharedHost:()=>boi});import{createRequire as Aoi}from"node:module";async function boi(e){let t=await import("@xenosystem/agent-interface-runtime"),r=Aoi(import.meta.url).resolve("@xenosystem/agent-interface-runtime/detached-entry"),n=await t.ensureSharedAgentHost({homeDirectory:e.homeDirectory,hostVersion:e.clientVersion,launcherInstanceId:e.instanceId,execPath:process.execPath,entryPath:r,...e.hostRootDirectory?{hostRootDirectory:e.hostRootDirectory}:{}});return{session:n.session,launched:n.launched}}var knr=ye(()=>{"use strict"});var Zge={};$o(Zge,{ATTACH_ENV_VAR:()=>pf,attachAsHeadlessClient:()=>rP,describeAttachRefusal:()=>nP,hostIsTheDefaultFor:()=>Yge,resolveAttachMode:()=>Qw});import{randomUUID as voi}from"node:crypto";import{homedir as Enr}from"node:os";function Yge(e){if(e.authBypassSource&&e.authBypassSource!=="none"||e.mcpEnabled)return!1;try{return Ioi.has(new URL(e.baseURL).hostname)}catch{return!1}}function Qw(e,t){let r=e?.trim().toLowerCase();if(r===void 0||r==="")return t&&Yge(t)?"optional":"off";if(["0","off","false","no"].includes(r))return"off";if(["1","on","true","yes"].includes(r))return"optional";if(["require","required"].includes(r))return"required";throw new Error(`${pf}="${e}" is not a recognised value. Use 1 (attach, starting a host if none runs), require (attach or fail), or 0 (never attach).`)}async function rP(e){let t=TD({homeDirectory:e.homeDirectory??Enr(),...e.hostRootDirectory?{hostRootDirectory:e.hostRootDirectory}:{}}),r=e.instanceId??voi(),n=await fQe({rootDirectory:t,...e.connectTimeoutMs?{connectTimeoutMs:e.connectTimeoutMs}:{},...e.requestTimeoutMs?{requestTimeoutMs:e.requestTimeoutMs}:{}});if(!n.attached&&e.startIfAbsent&&(n.reason==="no-host"||n.reason==="host-gone"))try{let{startSharedHost:a}=await Promise.resolve().then(()=>(knr(),Inr));await(await a({homeDirectory:e.homeDirectory??Enr(),...e.hostRootDirectory?{hostRootDirectory:e.hostRootDirectory}:{},clientVersion:e.clientVersion,instanceId:r})).session.close().catch(()=>{}),n=await fQe({rootDirectory:t,...e.connectTimeoutMs?{connectTimeoutMs:e.connectTimeoutMs}:{},...e.requestTimeoutMs?{requestTimeoutMs:e.requestTimeoutMs}:{}})}catch(a){return{attached:!1,reason:"start-failed",detail:(a instanceof Error?a.message:String(a)).slice(0,500)}}if(!n.attached)return{attached:!1,reason:n.reason,detail:n.detail};let i=e.prompter!==void 0,o=new Kge({transport:n.session.transport,identity:{clientId:"xeno-agent-cli",clientVersion:e.clientVersion,instanceId:r,surface:"headless-client"},capabilities:{canPresentElicitations:i,...e.account?{providesAccount:{issuer:e.account.issuer,clientId:e.account.clientId}}:{}}});if(e.account){let a=e.account;n.session.transport.setAccountAuthorizer(async l=>{try{return await a.authorize(l.method,l.url)}catch{return null}})}let s=e.prompter?bnr({client:o,prompter:e.prompter,...e.onElicitationError?{onError:e.onElicitationError}:{}}):()=>{};return{attached:!0,host:{client:o,session:n.session,rootDirectory:t,canAnswerPrompts:i,stopRespondingToElicitations:s}}}function nP(e,t){switch(e){case"no-host":return`No XENO Agent host is running for this user (${t}).`;case"host-gone":return`The Agent host's lease is stale \u2014 it exited without releasing it (${t}).`;case"protocol-mismatch":return`This CLI and the running Agent host speak different protocol versions (${t}).`;case"unreachable":return`An Agent host holds the lease but did not answer (${t}).`;case"start-failed":return`No XENO Agent host was running, and this CLI could not start one (${t}).`}}var pf,Ioi,rx=ye(()=>{"use strict";Anr();pfe();vnr();pf="XENO_AGENT_ATTACH",Ioi=new Set(["api.xenosystem.ai","api.xenostudio.ai","direct-api.xenosystem.ai","direct-api.xenostudio.ai"])});var ZL={};$o(ZL,{withHostClient:()=>koi});async function koi(e,t){if(process.env.XENO_AGENT_ATTACH==="off")throw new Error(`${e.what} are managed by the XENO Agent host, and XENO_AGENT_ATTACH=off keeps this CLI from reaching it.`);let{attachAsHeadlessClient:r,describeAttachRefusal:n}=await Promise.resolve().then(()=>(rx(),Zge)),i=await r({clientVersion:e.clientVersion,startIfAbsent:!0,...process.env.XENO_AGENT_HOST_ROOT?{hostRootDirectory:process.env.XENO_AGENT_HOST_ROOT}:{}});if(!i.attached)throw new Error(`The XENO Agent host is not available: ${n(i.reason,i.detail)}`);try{return await i.host.client.connect(),await t(i.host.client)}finally{await i.host.session.close().catch(()=>{})}}var eF=ye(()=>{"use strict"});var Jz={};$o(Jz,{bindPluginMcpCall:()=>Snr,expectSuccess:()=>Cnr,recordingDecisionsInHost:()=>Vze,setPluginMcpHostOpenerForTests:()=>Eoi,withPluginMcpHost:()=>xnr});async function Snr(e,t){let r=await tP(e,[t.cwd,...t.directories??[]]);if(r.granted.length===0&&r.failed.length>0)throw new Error(`The Agent host did not accept this folder: ${r.failed[0].error}`);return async(n,i={})=>await e.requestPluginMcp(`pluginMcp.${n}`,{cwd:t.cwd,...i,caller:{allowedDirectories:[...r.granted]}})}function Eoi(e){Gze=e}async function xnr(e,t){if(Gze){let n=await Gze(e);try{return await t(n.call)}finally{await n.close()}}let{withHostClient:r}=await Promise.resolve().then(()=>(eF(),ZL));return r({clientVersion:e.clientVersion,what:"Plugins and MCP servers"},async n=>t(await Snr(n,e)))}function Cnr(e,t){if(!e.success)throw new Error(typeof e.error=="string"&&e.error?e.error:`${t} failed`);return e}function Vze(e,t){return async r=>{let n=await e(r);return xnr({cwd:t.cwd,clientVersion:t.clientVersion},async i=>Cnr(await i("setMcpApproval",{name:r.name,decision:n}),`Recording ${r.name}`)).catch(i=>t.onUnrecorded?.(r.name,i instanceof Error?i.message:String(i))),n}}var Gze,tF=ye(()=>{"use strict";YL()});import{resolve as Tnr}from"node:path";async function zze(e){let{resolveCliPluginStore:t}=await Promise.resolve().then(()=>(Hw(),Onr)),r=t();if(r.layout!=="extensions"&&r.layout!=="legacy")return!1;let n=i=>process.platform==="win32"?Tnr(i).toLowerCase():Tnr(i);return n(r.pluginDir)===n(e)}async function Xze(e,t){let{withPluginMcpHost:r,expectSuccess:n}=await Promise.resolve().then(()=>(tF(),Jz));return r({cwd:process.cwd(),clientVersion:Pe},async i=>n(await i(e,t),e))}async function _nr(e){return await zze(e.pluginDir)?(await Xze("trustPublisher",{keyId:e.keyId,publisher:e.publisher,publicKey:e.publicKey}),hw(e.pluginDir)):Wue(e)}async function Pnr(e,t){return await zze(e)?(await Xze("untrustPublisher",{keyId:t})).removed===!0:Gue(e,t)}async function $nr(e,t){return await zze(e)?(await Xze("setRequireSignedPlugins",{required:t}),hw(e)):Vue(e,t)}var ewe,Rnr,Jze=ye(()=>{"use strict";Er();Ao();Er();ewe=hw,Rnr=Hue});var Onr={};$o(Onr,{activateCliPluginRuntime:()=>nF,collectPluginOutputStyles:()=>Lnr,createCliPluginHost:()=>ol,createPluginPromptSections:()=>Dnr,getCliPluginDir:()=>il,getPluginOutputStyleImpacts:()=>tX,getPluginPromptImpacts:()=>eX,inspectCliPluginRuntime:()=>rF,installCliPlugin:()=>Yz,removeCliPlugin:()=>Zz,resolveCliPluginStore:()=>Zze,setCliPluginEnabled:()=>iP});import{existsSync as Soi,mkdirSync as xoi,readdirSync as Coi,statSync as Nnr}from"node:fs";import{homedir as Toi}from"node:os";import{join as Roi,resolve as Kz}from"node:path";function Mnr(e){try{return Nnr(e).isDirectory()&&Coi(e).length>0}catch{return!1}}function Zze(e=process.env,t=Toi()){let r=e.XENO_PLUGIN_DIR?.trim();if(r)return{pluginDir:Kz(r),layout:"override"};let n=XWt(t,e),i=Roi(Za(e),"plugins");return!Mnr(n.pluginDir)&&Mnr(i)?{pluginDir:Kz(i),layout:"cli-legacy"}:{pluginDir:Kz(n.pluginDir),layout:n.layout}}function il(e){return e?Kz(e):Zze().pluginDir}function ol(e={}){let t=il(e.pluginDir);xoi(t,{recursive:!0});let r=Rnr(t);return new Z6({pluginDir:t,autoActivate:e.autoActivate,host:{appName:"xeno-agent-cli",appVersion:Pe,platform:process.platform},trustedPublisherKeys:r.trustedPublisherKeys,requireSignedPlugins:r.store.requireSignedPlugins})}async function rF(e={}){let t=il(e.pluginDir),r=ol({pluginDir:t,autoActivate:!1});return{pluginDir:t,plugins:r.listInstalled(),trust:await ewe(t)}}function Bnr(e,t){let r=t.template?.trim();if(!r)return null;let n=t.description?.trim();return["","",`# Plugin Prompt: ${t.name}`,`Source: ${e.manifest.name}`,...n?[`Description: ${n}`]:[],"",r].join(`
5522
5522
  `)}function Dnr(e){let t=[];for(let r of e)if(r.status==="active")for(let n of r.manifest.contributes?.prompts??[]){let i=Bnr(r,n);i&&t.push({name:`plugin:${r.manifest.name}:${n.name}`,order:350,provide:()=>i})}return t}function _oi(e,t){let r=t.name.trim().toLowerCase(),n=t.instruction.trim();return!r||!n?null:{name:r,...t.description?{description:t.description}:{},instruction:n,source:"plugin",pluginName:e.manifest.name}}function Lnr(e){let t=[],r=new Set;for(let n of e)if(n.status==="active")for(let i of n.manifest.contributes?.outputStyles??[]){let o=_oi(n,i);!o||r.has(o.name)||(r.add(o.name),t.push(o))}return t}async function nF(e={}){let t=il(e.pluginDir),r=ol({pluginDir:t,autoActivate:!1});for(let s of r.listInstalled())s.status==="active"&&r.setStatus(s.manifest.name,"installed");await r.activateAll();let n=r.getActiveTools();e.toolRegistry?.registerAll(n);let i=r.listInstalled(),o=i.filter(s=>s.status==="active");return{pluginDir:t,host:r,plugins:i,activePlugins:o,registeredTools:n.map(s=>s.definition.name).sort(),promptSections:Dnr(o),outputStyles:Lnr(o)}}function eXe(e){if(e)return!1;let t=Zze().layout;return t==="extensions"||t==="legacy"}async function tXe(e,t){let{withPluginMcpHost:r}=await Promise.resolve().then(()=>(tF(),Jz));return r({cwd:process.cwd(),directories:e,clientVersion:Pe},t)}function Yze(e){return ol({autoActivate:!1}).getPlugin(e)}async function Yz(e,t,r={}){let n=Kz(e),i=Soi(n)&&Nnr(n).isDirectory();if(!eXe(r.pluginDir)){let o=ol(r);return i?o.installLocal(n):o.install(e,t)}return tXe(i?[n]:[],async o=>{let s=i?await o("installLocalPlugin",{pluginPath:n}):await o("installPlugin",{packageName:e,...t?{version:t}:{}}),a=s.plugin?.name,l=typeof a=="string"?Yze(a):void 0;if(l&&s.success)return l;throw new Error(typeof s.error=="string"&&s.error?s.error:`Could not install ${e}`)})}async function Zz(e,t={}){return eXe(t.pluginDir)?tXe([],async r=>(await r("uninstallPlugin",{name:e,removeFiles:!1})).success):ol(t).uninstall(e,!1)}async function iP(e,t,r={}){if(!eXe(r.pluginDir)){let n=ol({...r,autoActivate:!1});return n.getPlugin(e)?t?(n.setStatus(e,"installed"),await n.activate(e),n.getPlugin(e)):(await n.deactivate(e),n.setStatus(e,"disabled"),n.getPlugin(e)):void 0}if(Yze(e))return tXe([],async n=>(t?(Kze(await n("setPluginTrust",{name:e,decision:"approved"}),`Trusting ${e}`),Kze(await n("activatePlugin",{name:e}),`Enabling ${e}`)):Kze(await n("deactivatePlugin",{name:e}),`Disabling ${e}`),Yze(e)))}function Kze(e,t){if(!e.success)throw new Error(e.error||`${t} failed`)}function eX(e){return(e.manifest.contributes?.prompts??[]).map(t=>{let r=Bnr(e,t)??"";return{name:t.name,...t.description?{description:t.description}:{},chars:r.length,estimatedTokens:Math.ceil(r.length/4)}}).filter(t=>t.chars>0)}function tX(e){return(e.manifest.contributes?.outputStyles??[]).map(t=>{let r=t.instruction?.trim()??"";return{name:t.name,...t.description?{description:t.description}:{},chars:r.length,estimatedTokens:Math.ceil(r.length/4)}}).filter(t=>t.chars>0)}var Hw=ye(()=>{"use strict";hQe();Er();Ao();Jze();xw()});import{homedir as Poi}from"node:os";import{resolve as $oi}from"node:path";function oP(e){let t=process.env.XENO_SKILLS_HOME?.trim();return{cwd:e,userSkillsHome:BB(),homeDirectory:t?$oi(t):Poi(),listPlugins:()=>ol({autoActivate:!1}).listInstalled(),pluginDirectory:il()}}function rX(){return uS({userSkillsHome:BB()})}function nX(e){return TR(e)}function Fnr(){return RR({userSkillsHome:BB()})}function Unr(e){return pS(e)}function jnr(){DB()}function qnr(e){return K0(oP(e))}function Qnr(e){return N5(oP(e))}function nx(e){return LB(e)}function nXe(e,t){return P6(rXe(e),t)}function Mc(e,t){return jde(rXe(e),t)}function iF(e,t){return B5(e,t)}function ix(e){return qde(e)}async function twe(e,t,r){return Qde(oP(e),t,r)}function Hnr(e){return $6(e)}function Xu(e){let{cwd:t,...r}=e;return Hde({...r,workspace:rXe(t)})}async function Wnr(e){let{cwd:t,...r}=e;return Wde({...r,workspace:oP(t)})}async function Gnr(e){return Gde(oP(e))}function Vnr(e){return Vde(e)}var rXe,Ww=ye(()=>{"use strict";Hw();Er();rXe=e=>typeof e=="function"?()=>oP(e()):oP(e)});var sx=ye(()=>{"use strict";rl();$a()});var ff=ye(()=>{"use strict";rl();$a()});var dx=ye(()=>{"use strict";rl();$a()});var For=ye(()=>{"use strict";rl();$a()});var GXe=ye(()=>{"use strict";rl();$a()});var ux=ye(()=>{"use strict";rl();$a()});import{createHash as qor}from"node:crypto";import{appendFileSync as Uli,closeSync as jli,existsSync as qli,fstatSync as Qli,mkdirSync as Uor,openSync as Hli,readSync as Wli}from"node:fs";import{dirname as Gli,join as wX}from"node:path";function vwe(e,t,r={}){return`notif_${qor("sha256").update(`${e.parentSessionId}\0${e.sessionId}\0${t}\0${r.dedupeKey??e.activeInboxMessageId??t}`).digest("hex").slice(0,32)}`}function yF(){let e=process.env.XENO_AGENT_NOTIFICATIONS?.trim().toLowerCase();return e!=="0"&&e!=="false"&&e!=="no"&&e!=="off"}function Iwe(e){let t=e.map(r=>r.notificationId).join("\0");return`msg_agent_notification_${qor("sha256").update(t).digest("hex").slice(0,32)}`}function gX(){return new Date().toISOString()}function Qor(e,t){if(!e)return;let r=e.trim();return r.length<=t?r:`${r.slice(0,t-3)}...`}function Xli(e){let t=e;return t=t.replace(/-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----[\s\S]*?-----END (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/giu,"[REDACTED PRIVATE KEY]"),t=t.replace(/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}\b/giu,"Bearer [REDACTED]"),t=t.replace(/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/gu,"[REDACTED JWT]"),t=t.replace(/\bAKIA[A-Z0-9]{16}\b/gu,"[REDACTED AWS KEY]"),t=t.replace(/\b(?:sk|xai|ghp|glpat|github_pat)[-_][A-Za-z0-9_-]{12,}\b/giu,"[REDACTED TOKEN]"),t=t.replace(/(\b(?:api[_ -]?key|access[_ -]?token|refresh[_ -]?token|password|secret|credential)\b\s*[:=]\s*)[^\s,;]{6,}/giu,"$1[REDACTED]"),{text:t,redacted:t!==e}}function yX(e,t,r=!1){if(!e)return{redacted:!1};let n=Xli(e),i=n.redacted&&r?`${n.text.trim()}
5523
5523
 
5524
5524
  ${zli}`:n.text;return{text:Qor(i,t),redacted:n.redacted}}function bwe(e){if(!qli(e))return[];let t=Hli(e,"r");try{let r=Qli(t).size;if(r>jor)throw new Error(`Notification journal exceeds the ${jor} byte full-read limit; use bounded notification listing or acknowledgement operations instead.`);let n=Buffer.alloc(r),i=0;for(;i<r;){let o=Wli(t,n,i,r-i,i);if(o===0)throw new Error("Notification journal changed during read; retry the operation.");i+=o}return n.toString("utf8").split(/\r?\n/).map(o=>o.trim()).filter(Boolean).map(o=>{try{return JSON.parse(o)}catch{return null}}).filter(o=>o!==null)}finally{jli(t)}}function Jli(e){return e.title??e.name??e.agentName??e.teamMember??e.sessionId}function Kli(e,t){let r=Jli(e);return t==="completed"?`Agent "${r}" completed.`:t==="failed"?`Agent "${r}" failed${e.statusReason?`: ${e.statusReason}`:"."}`:t==="stopped"?`Agent "${r}" stopped${e.statusReason?`: ${e.statusReason}`:"."}`:`Agent "${r}" needs input${e.statusReason?`: ${e.statusReason}`:"."}`}function Yli(e){let r=bwe(e.outboxPath).slice().reverse().find(n=>n.sender==="worker"&&typeof n.content=="string"&&n.content.trim());return yX(r?.content,Vli,!0)}function Zli(){return wX(Kn(),"agents","notifications")}function Vm(e){return[...e].filter(r=>{let n=r.codePointAt(0);return n===9||n===10||n===13||n>=32&&n!==127}).join("").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function AX(e,t=Date.now()){let r=Date.parse(e.createdAt),n=Number.isFinite(r)?Math.max(0,Math.round((t-r)/1e3)):0,i=e.title??e.name,o=e.status==="completed"?"finished":e.status==="needs_input"?"needs input":e.status;return`\u25A0 Agent "${i.replace(/[\r\n\t]+/g," ").trim()}" ${o} - ${n}s`}function bX(e){return["<xeno-agent-notifications>",...e.map(r=>[" <xeno-agent-notification>",` <notification_id>${Vm(r.notificationId)}</notification_id>`,` <parent_session_id>${Vm(r.parentSessionId)}</parent_session_id>`,` <session_id>${Vm(r.childSessionId)}</session_id>`,` <name>${Vm(r.name)}</name>`,r.title?` <title>${Vm(r.title)}</title>`:"",` <status>${Vm(r.status)}</status>`,r.model?` <model>${Vm(r.model)}</model>`:"",` <summary>${Vm(r.summary)}</summary>`,r.statusReason?` <status_reason>${Vm(r.statusReason)}</status_reason>`:"",r.resultExcerpt?` <result_excerpt>${Vm(r.resultExcerpt)}</result_excerpt>`:"",r.containsRedactions?" <redacted>true</redacted>":"",` <transcript_path>${Vm(r.transcriptPath)}</transcript_path>`,` <outbox_path>${Vm(r.outboxPath)}</outbox_path>`," </xeno-agent-notification>"].filter(Boolean).join(`
@@ -5812,7 +5812,7 @@ ${c.toString(16)}\r
5812
5812
  ${n.count} ${n.noun} ${n.is} pending:
5813
5813
 
5814
5814
  ${t.format(r)}
5815
- `.trim())}};WQr.exports=xft});var sZ=Be((jFs,JQr)=>{"use strict";var VQr=Symbol.for("undici.globalDispatcher.1"),{InvalidArgumentError:Ppo}=Ln(),$po=d3();XQr()===void 0&&zQr(new $po);function zQr(e){if(!e||typeof e.dispatch!="function")throw new Ppo("Argument agent must implement Agent");Object.defineProperty(globalThis,VQr,{value:e,writable:!0,enumerable:!1,configurable:!1})}function XQr(){return globalThis[VQr]}JQr.exports={setGlobalDispatcher:zQr,getGlobalDispatcher:XQr}});var Axe=Be((QFs,KQr)=>{"use strict";KQr.exports=class{#e;constructor(t){if(typeof t!="object"||t===null)throw new TypeError("handler must be an object");this.#e=t}onConnect(...t){return this.#e.onConnect?.(...t)}onError(...t){return this.#e.onError?.(...t)}onUpgrade(...t){return this.#e.onUpgrade?.(...t)}onResponseStarted(...t){return this.#e.onResponseStarted?.(...t)}onHeaders(...t){return this.#e.onHeaders?.(...t)}onData(...t){return this.#e.onData?.(...t)}onComplete(...t){return this.#e.onComplete?.(...t)}onBodySent(...t){return this.#e.onBodySent?.(...t)}}});var ZQr=Be((HFs,YQr)=>{"use strict";var Opo=YSe();YQr.exports=e=>{let t=e?.maxRedirections;return r=>function(i,o){let{maxRedirections:s=t,...a}=i;if(!s)return r(i,o);let l=new Opo(r,s,i,o);return r(a,l)}}});var tHr=Be((WFs,eHr)=>{"use strict";var Mpo=cxe();eHr.exports=e=>t=>function(n,i){return t(n,new Mpo({...n,retryOptions:{...e,...n.retryOptions}},{handler:i,dispatch:t}))}});var nHr=Be((GFs,rHr)=>{"use strict";var Npo=qr(),{InvalidArgumentError:Bpo,RequestAbortedError:Dpo}=Ln(),Lpo=Axe(),Cft=class extends Lpo{#e=1024*1024;#r=null;#n=!1;#i=!1;#o=0;#t=null;#s=null;constructor({maxSize:t},r){if(super(r),t!=null&&(!Number.isFinite(t)||t<1))throw new Bpo("maxSize must be a number greater than 0");this.#e=t??this.#e,this.#s=r}onConnect(t){this.#r=t,this.#s.onConnect(this.#a.bind(this))}#a(t){this.#i=!0,this.#t=t}onHeaders(t,r,n,i){let s=Npo.parseHeaders(r)["content-length"];if(s!=null&&s>this.#e)throw new Dpo(`Response size (${s}) larger than maxSize (${this.#e})`);return this.#i?!0:this.#s.onHeaders(t,r,n,i)}onError(t){this.#n||(t=this.#t??t,this.#s.onError(t))}onData(t){return this.#o=this.#o+t.length,this.#o>=this.#e&&(this.#n=!0,this.#i?this.#s.onError(this.#t):this.#s.onComplete([])),!0}onComplete(t){if(!this.#n){if(this.#i){this.#s.onError(this.reason);return}this.#s.onComplete(t)}}};function Fpo({maxSize:e}={maxSize:1024*1024}){return t=>function(n,i){let{dumpMaxSize:o=e}=n,s=new Cft({maxSize:o},i);return t(n,s)}}rHr.exports=Fpo});var sHr=Be((VFs,oHr)=>{"use strict";var{isIP:Upo}=Re("node:net"),{lookup:jpo}=Re("node:dns"),qpo=Axe(),{InvalidArgumentError:A3,InformationalError:Qpo}=Ln(),iHr=Math.pow(2,31)-1,Tft=class{#e=0;#r=0;#n=new Map;dualStack=!0;affinity=null;lookup=null;pick=null;constructor(t){this.#e=t.maxTTL,this.#r=t.maxItems,this.dualStack=t.dualStack,this.affinity=t.affinity,this.lookup=t.lookup??this.#i,this.pick=t.pick??this.#o}get full(){return this.#n.size===this.#r}runLookup(t,r,n){let i=this.#n.get(t.hostname);if(i==null&&this.full){n(null,t.origin);return}let o={affinity:this.affinity,dualStack:this.dualStack,lookup:this.lookup,pick:this.pick,...r.dns,maxTTL:this.#e,maxItems:this.#r};if(i==null)this.lookup(t,o,(s,a)=>{if(s||a==null||a.length===0){n(s??new Qpo("No DNS entries found"));return}this.setRecords(t,a);let l=this.#n.get(t.hostname),c=this.pick(t,l,o.affinity),d;typeof c.port=="number"?d=`:${c.port}`:t.port!==""?d=`:${t.port}`:d="",n(null,`${t.protocol}//${c.family===6?`[${c.address}]`:c.address}${d}`)});else{let s=this.pick(t,i,o.affinity);if(s==null){this.#n.delete(t.hostname),this.runLookup(t,r,n);return}let a;typeof s.port=="number"?a=`:${s.port}`:t.port!==""?a=`:${t.port}`:a="",n(null,`${t.protocol}//${s.family===6?`[${s.address}]`:s.address}${a}`)}}#i(t,r,n){jpo(t.hostname,{all:!0,family:this.dualStack===!1?this.affinity:0,order:"ipv4first"},(i,o)=>{if(i)return n(i);let s=new Map;for(let a of o)s.set(`${a.address}:${a.family}`,a);n(null,s.values())})}#o(t,r,n){let i=null,{records:o,offset:s}=r,a;if(this.dualStack?(n==null&&(s==null||s===iHr?(r.offset=0,n=4):(r.offset++,n=(r.offset&1)===1?6:4)),o[n]!=null&&o[n].ips.length>0?a=o[n]:a=o[n===4?6:4]):a=o[n],a==null||a.ips.length===0)return i;a.offset==null||a.offset===iHr?a.offset=0:a.offset++;let l=a.offset%a.ips.length;return i=a.ips[l]??null,i==null?i:Date.now()-i.timestamp>i.ttl?(a.ips.splice(l,1),this.pick(t,r,n)):i}setRecords(t,r){let n=Date.now(),i={records:{4:null,6:null}};for(let o of r){o.timestamp=n,typeof o.ttl=="number"?o.ttl=Math.min(o.ttl,this.#e):o.ttl=this.#e;let s=i.records[o.family]??{ips:[]};s.ips.push(o),i.records[o.family]=s}this.#n.set(t.hostname,i)}getHandler(t,r){return new Rft(this,t,r)}},Rft=class extends qpo{#e=null;#r=null;#n=null;#i=null;#o=null;constructor(t,{origin:r,handler:n,dispatch:i},o){super(n),this.#o=r,this.#i=n,this.#r={...o},this.#e=t,this.#n=i}onError(t){switch(t.code){case"ETIMEDOUT":case"ECONNREFUSED":{if(this.#e.dualStack){this.#e.runLookup(this.#o,this.#r,(r,n)=>{if(r)return this.#i.onError(r);let i={...this.#r,origin:n};this.#n(i,this)});return}this.#i.onError(t);return}case"ENOTFOUND":this.#e.deleteRecord(this.#o);default:this.#i.onError(t);break}}};oHr.exports=e=>{if(e?.maxTTL!=null&&(typeof e?.maxTTL!="number"||e?.maxTTL<0))throw new A3("Invalid maxTTL. Must be a positive number");if(e?.maxItems!=null&&(typeof e?.maxItems!="number"||e?.maxItems<1))throw new A3("Invalid maxItems. Must be a positive number and greater than zero");if(e?.affinity!=null&&e?.affinity!==4&&e?.affinity!==6)throw new A3("Invalid affinity. Must be either 4 or 6");if(e?.dualStack!=null&&typeof e?.dualStack!="boolean")throw new A3("Invalid dualStack. Must be a boolean");if(e?.lookup!=null&&typeof e?.lookup!="function")throw new A3("Invalid lookup. Must be a function");if(e?.pick!=null&&typeof e?.pick!="function")throw new A3("Invalid pick. Must be a function");let t=e?.dualStack??!0,r;t?r=e?.affinity??null:r=e?.affinity??4;let n={maxTTL:e?.maxTTL??1e4,lookup:e?.lookup??null,pick:e?.pick??null,dualStack:t,affinity:r,maxItems:e?.maxItems??1/0},i=new Tft(n);return o=>function(a,l){let c=a.origin.constructor===URL?a.origin:new URL(a.origin);return Upo(c.hostname)!==0?o(a,l):(i.runLookup(c,a,(d,u)=>{if(d)return l.onError(d);let p=null;p={...a,servername:c.hostname,origin:u,headers:{host:c.hostname,...a.headers}},o(p,i.getHandler({origin:c,dispatch:o,handler:l},a))}),!0)}}});var GO=Be((zFs,fHr)=>{"use strict";var{kConstruct:Hpo}=Ts(),{kEnumerableProperty:b3}=qr(),{iteratorMixin:Wpo,isValidHeaderName:aZ,isValidHeaderValue:lHr}=Kh(),{webidl:Sn}=Cd(),_ft=Re("node:assert"),bxe=Re("node:util"),jl=Symbol("headers map"),tm=Symbol("headers map sorted");function aHr(e){return e===10||e===13||e===9||e===32}function cHr(e){let t=0,r=e.length;for(;r>t&&aHr(e.charCodeAt(r-1));)--r;for(;r>t&&aHr(e.charCodeAt(t));)++t;return t===0&&r===e.length?e:e.substring(t,r)}function dHr(e,t){if(Array.isArray(t))for(let r=0;r<t.length;++r){let n=t[r];if(n.length!==2)throw Sn.errors.exception({header:"Headers constructor",message:`expected name/value pair to be length 2, found ${n.length}.`});Pft(e,n[0],n[1])}else if(typeof t=="object"&&t!==null){let r=Object.keys(t);for(let n=0;n<r.length;++n)Pft(e,r[n],t[r[n]])}else throw Sn.errors.conversionFailed({prefix:"Headers constructor",argument:"Argument 1",types:["sequence<sequence<ByteString>>","record<ByteString, ByteString>"]})}function Pft(e,t,r){if(r=cHr(r),aZ(t)){if(!lHr(r))throw Sn.errors.invalidArgument({prefix:"Headers.append",value:r,type:"header value"})}else throw Sn.errors.invalidArgument({prefix:"Headers.append",value:t,type:"header name"});if(pHr(e)==="immutable")throw new TypeError("immutable");return $ft(e).append(t,r,!1)}function uHr(e,t){return e[0]<t[0]?-1:1}var vxe=class e{cookies=null;constructor(t){t instanceof e?(this[jl]=new Map(t[jl]),this[tm]=t[tm],this.cookies=t.cookies===null?null:[...t.cookies]):(this[jl]=new Map(t),this[tm]=null)}contains(t,r){return this[jl].has(r?t:t.toLowerCase())}clear(){this[jl].clear(),this[tm]=null,this.cookies=null}append(t,r,n){this[tm]=null;let i=n?t:t.toLowerCase(),o=this[jl].get(i);if(o){let s=i==="cookie"?"; ":", ";this[jl].set(i,{name:o.name,value:`${o.value}${s}${r}`})}else this[jl].set(i,{name:t,value:r});i==="set-cookie"&&(this.cookies??=[]).push(r)}set(t,r,n){this[tm]=null;let i=n?t:t.toLowerCase();i==="set-cookie"&&(this.cookies=[r]),this[jl].set(i,{name:t,value:r})}delete(t,r){this[tm]=null,r||(t=t.toLowerCase()),t==="set-cookie"&&(this.cookies=null),this[jl].delete(t)}get(t,r){return this[jl].get(r?t:t.toLowerCase())?.value??null}*[Symbol.iterator](){for(let{0:t,1:{value:r}}of this[jl])yield[t,r]}get entries(){let t={};if(this[jl].size!==0)for(let{name:r,value:n}of this[jl].values())t[r]=n;return t}rawValues(){return this[jl].values()}get entriesList(){let t=[];if(this[jl].size!==0)for(let{0:r,1:{name:n,value:i}}of this[jl])if(r==="set-cookie")for(let o of this.cookies)t.push([n,o]);else t.push([n,i]);return t}toSortedArray(){let t=this[jl].size,r=new Array(t);if(t<=32){if(t===0)return r;let n=this[jl][Symbol.iterator](),i=n.next().value;r[0]=[i[0],i[1].value],_ft(i[1].value!==null);for(let o=1,s=0,a=0,l=0,c=0,d,u;o<t;++o){for(u=n.next().value,d=r[o]=[u[0],u[1].value],_ft(d[1]!==null),l=0,a=o;l<a;)c=l+(a-l>>1),r[c][0]<=d[0]?l=c+1:a=c;if(o!==c){for(s=o;s>l;)r[s]=r[--s];r[l]=d}}if(!n.next().done)throw new TypeError("Unreachable");return r}else{let n=0;for(let{0:i,1:{value:o}}of this[jl])r[n++]=[i,o],_ft(o!==null);return r.sort(uHr)}}},Py=class e{#e;#r;constructor(t=void 0){Sn.util.markAsUncloneable(this),t!==Hpo&&(this.#r=new vxe,this.#e="none",t!==void 0&&(t=Sn.converters.HeadersInit(t,"Headers contructor","init"),dHr(this,t)))}append(t,r){Sn.brandCheck(this,e),Sn.argumentLengthCheck(arguments,2,"Headers.append");let n="Headers.append";return t=Sn.converters.ByteString(t,n,"name"),r=Sn.converters.ByteString(r,n,"value"),Pft(this,t,r)}delete(t){if(Sn.brandCheck(this,e),Sn.argumentLengthCheck(arguments,1,"Headers.delete"),t=Sn.converters.ByteString(t,"Headers.delete","name"),!aZ(t))throw Sn.errors.invalidArgument({prefix:"Headers.delete",value:t,type:"header name"});if(this.#e==="immutable")throw new TypeError("immutable");this.#r.contains(t,!1)&&this.#r.delete(t,!1)}get(t){Sn.brandCheck(this,e),Sn.argumentLengthCheck(arguments,1,"Headers.get");let r="Headers.get";if(t=Sn.converters.ByteString(t,r,"name"),!aZ(t))throw Sn.errors.invalidArgument({prefix:r,value:t,type:"header name"});return this.#r.get(t,!1)}has(t){Sn.brandCheck(this,e),Sn.argumentLengthCheck(arguments,1,"Headers.has");let r="Headers.has";if(t=Sn.converters.ByteString(t,r,"name"),!aZ(t))throw Sn.errors.invalidArgument({prefix:r,value:t,type:"header name"});return this.#r.contains(t,!1)}set(t,r){Sn.brandCheck(this,e),Sn.argumentLengthCheck(arguments,2,"Headers.set");let n="Headers.set";if(t=Sn.converters.ByteString(t,n,"name"),r=Sn.converters.ByteString(r,n,"value"),r=cHr(r),aZ(t)){if(!lHr(r))throw Sn.errors.invalidArgument({prefix:n,value:r,type:"header value"})}else throw Sn.errors.invalidArgument({prefix:n,value:t,type:"header name"});if(this.#e==="immutable")throw new TypeError("immutable");this.#r.set(t,r,!1)}getSetCookie(){Sn.brandCheck(this,e);let t=this.#r.cookies;return t?[...t]:[]}get[tm](){if(this.#r[tm])return this.#r[tm];let t=[],r=this.#r.toSortedArray(),n=this.#r.cookies;if(n===null||n.length===1)return this.#r[tm]=r;for(let i=0;i<r.length;++i){let{0:o,1:s}=r[i];if(o==="set-cookie")for(let a=0;a<n.length;++a)t.push([o,n[a]]);else t.push([o,s])}return this.#r[tm]=t}[bxe.inspect.custom](t,r){return r.depth??=t,`Headers ${bxe.formatWithOptions(r,this.#r.entries)}`}static getHeadersGuard(t){return t.#e}static setHeadersGuard(t,r){t.#e=r}static getHeadersList(t){return t.#r}static setHeadersList(t,r){t.#r=r}},{getHeadersGuard:pHr,setHeadersGuard:Gpo,getHeadersList:$ft,setHeadersList:Vpo}=Py;Reflect.deleteProperty(Py,"getHeadersGuard");Reflect.deleteProperty(Py,"setHeadersGuard");Reflect.deleteProperty(Py,"getHeadersList");Reflect.deleteProperty(Py,"setHeadersList");Wpo("Headers",Py,tm,0,1);Object.defineProperties(Py.prototype,{append:b3,delete:b3,get:b3,has:b3,set:b3,getSetCookie:b3,[Symbol.toStringTag]:{value:"Headers",configurable:!0},[bxe.inspect.custom]:{enumerable:!1}});Sn.converters.HeadersInit=function(e,t,r){if(Sn.util.Type(e)==="Object"){let n=Reflect.get(e,Symbol.iterator);if(!bxe.types.isProxy(e)&&n===Py.prototype.entries)try{return $ft(e).entriesList}catch{}return typeof n=="function"?Sn.converters["sequence<sequence<ByteString>>"](e,t,r,n.bind(e)):Sn.converters["record<ByteString, ByteString>"](e,t,r)}throw Sn.errors.conversionFailed({prefix:"Headers constructor",argument:"Argument 1",types:["sequence<sequence<ByteString>>","record<ByteString, ByteString>"]})};fHr.exports={fill:dHr,compareHeaderName:uHr,Headers:Py,HeadersList:vxe,getHeadersGuard:pHr,setHeadersGuard:Gpo,setHeadersList:Vpo,getHeadersList:$ft}});var cZ=Be((XFs,SHr)=>{"use strict";var{Headers:AHr,HeadersList:hHr,fill:zpo,getHeadersGuard:Xpo,setHeadersGuard:bHr,setHeadersList:vHr}=GO(),{extractBody:mHr,cloneBody:Jpo,mixinBody:Kpo,hasFinalizationRegistry:IHr,streamRegistry:kHr,bodyUnusable:Ypo}=t3(),Oft=qr(),gHr=Re("node:util"),{kEnumerableProperty:rm}=Oft,{isValidReasonPhrase:Zpo,isCancelled:efo,isAborted:tfo,isBlobLike:rfo,serializeJavascriptValueToJSONString:nfo,isErrorLike:ifo,isomorphicEncode:ofo,environmentSettingsObject:sfo}=Kh(),{redirectStatusSet:afo,nullBodyStatus:lfo}=P7(),{kState:_s,kHeaders:yE}=zC(),{webidl:Or}=Cd(),{FormData:cfo}=D7(),{URLSerializer:wHr}=Nf(),{kConstruct:kxe}=Ts(),Mft=Re("node:assert"),{types:dfo}=Re("node:util"),ufo=new TextEncoder("utf-8"),VO=class e{static error(){return lZ(Exe(),"immutable")}static json(t,r={}){Or.argumentLengthCheck(arguments,1,"Response.json"),r!==null&&(r=Or.converters.ResponseInit(r));let n=ufo.encode(nfo(t)),i=mHr(n),o=lZ(v3({}),"response");return yHr(o,r,{body:i[0],type:"application/json"}),o}static redirect(t,r=302){Or.argumentLengthCheck(arguments,1,"Response.redirect"),t=Or.converters.USVString(t),r=Or.converters["unsigned short"](r);let n;try{n=new URL(t,sfo.settingsObject.baseUrl)}catch(s){throw new TypeError(`Failed to parse URL from ${t}`,{cause:s})}if(!afo.has(r))throw new RangeError(`Invalid status code ${r}`);let i=lZ(v3({}),"immutable");i[_s].status=r;let o=ofo(wHr(n));return i[_s].headersList.append("location",o,!0),i}constructor(t=null,r={}){if(Or.util.markAsUncloneable(this),t===kxe)return;t!==null&&(t=Or.converters.BodyInit(t)),r=Or.converters.ResponseInit(r),this[_s]=v3({}),this[yE]=new AHr(kxe),bHr(this[yE],"response"),vHr(this[yE],this[_s].headersList);let n=null;if(t!=null){let[i,o]=mHr(t);n={body:i,type:o}}yHr(this,r,n)}get type(){return Or.brandCheck(this,e),this[_s].type}get url(){Or.brandCheck(this,e);let t=this[_s].urlList,r=t[t.length-1]??null;return r===null?"":wHr(r,!0)}get redirected(){return Or.brandCheck(this,e),this[_s].urlList.length>1}get status(){return Or.brandCheck(this,e),this[_s].status}get ok(){return Or.brandCheck(this,e),this[_s].status>=200&&this[_s].status<=299}get statusText(){return Or.brandCheck(this,e),this[_s].statusText}get headers(){return Or.brandCheck(this,e),this[yE]}get body(){return Or.brandCheck(this,e),this[_s].body?this[_s].body.stream:null}get bodyUsed(){return Or.brandCheck(this,e),!!this[_s].body&&Oft.isDisturbed(this[_s].body.stream)}clone(){if(Or.brandCheck(this,e),Ypo(this))throw Or.errors.exception({header:"Response.clone",message:"Body has already been consumed."});let t=Nft(this[_s]);return IHr&&this[_s].body?.stream&&kHr.register(this,new WeakRef(this[_s].body.stream)),lZ(t,Xpo(this[yE]))}[gHr.inspect.custom](t,r){r.depth===null&&(r.depth=2),r.colors??=!0;let n={status:this.status,statusText:this.statusText,headers:this.headers,body:this.body,bodyUsed:this.bodyUsed,ok:this.ok,redirected:this.redirected,type:this.type,url:this.url};return`Response ${gHr.formatWithOptions(r,n)}`}};Kpo(VO);Object.defineProperties(VO.prototype,{type:rm,url:rm,status:rm,ok:rm,redirected:rm,statusText:rm,headers:rm,clone:rm,body:rm,bodyUsed:rm,[Symbol.toStringTag]:{value:"Response",configurable:!0}});Object.defineProperties(VO,{json:rm,redirect:rm,error:rm});function Nft(e){if(e.internalResponse)return EHr(Nft(e.internalResponse),e.type);let t=v3({...e,body:null});return e.body!=null&&(t.body=Jpo(t,e.body)),t}function v3(e){return{aborted:!1,rangeRequested:!1,timingAllowPassed:!1,requestIncludesCredentials:!1,type:"default",status:200,timingInfo:null,cacheState:"",statusText:"",...e,headersList:e?.headersList?new hHr(e?.headersList):new hHr,urlList:e?.urlList?[...e.urlList]:[]}}function Exe(e){let t=ifo(e);return v3({type:"error",status:0,error:t?e:new Error(e&&String(e)),aborted:e&&e.name==="AbortError"})}function pfo(e){return e.type==="error"&&e.status===0}function Ixe(e,t){return t={internalResponse:e,...t},new Proxy(e,{get(r,n){return n in t?t[n]:r[n]},set(r,n,i){return Mft(!(n in t)),r[n]=i,!0}})}function EHr(e,t){if(t==="basic")return Ixe(e,{type:"basic",headersList:e.headersList});if(t==="cors")return Ixe(e,{type:"cors",headersList:e.headersList});if(t==="opaque")return Ixe(e,{type:"opaque",urlList:Object.freeze([]),status:0,statusText:"",body:null});if(t==="opaqueredirect")return Ixe(e,{type:"opaqueredirect",status:0,statusText:"",headersList:[],body:null});Mft(!1)}function ffo(e,t=null){return Mft(efo(e)),tfo(e)?Exe(Object.assign(new DOMException("The operation was aborted.","AbortError"),{cause:t})):Exe(Object.assign(new DOMException("Request was cancelled."),{cause:t}))}function yHr(e,t,r){if(t.status!==null&&(t.status<200||t.status>599))throw new RangeError('init["status"] must be in the range of 200 to 599, inclusive.');if("statusText"in t&&t.statusText!=null&&!Zpo(String(t.statusText)))throw new TypeError("Invalid statusText");if("status"in t&&t.status!=null&&(e[_s].status=t.status),"statusText"in t&&t.statusText!=null&&(e[_s].statusText=t.statusText),"headers"in t&&t.headers!=null&&zpo(e[yE],t.headers),r){if(lfo.includes(e.status))throw Or.errors.exception({header:"Response constructor",message:`Invalid response status code ${e.status}`});e[_s].body=r.body,r.type!=null&&!e[_s].headersList.contains("content-type",!0)&&e[_s].headersList.append("content-type",r.type,!0)}}function lZ(e,t){let r=new VO(kxe);return r[_s]=e,r[yE]=new AHr(kxe),vHr(r[yE],e.headersList),bHr(r[yE],t),IHr&&e.body?.stream&&kHr.register(r,new WeakRef(e.body.stream)),r}Or.converters.ReadableStream=Or.interfaceConverter(ReadableStream);Or.converters.FormData=Or.interfaceConverter(cfo);Or.converters.URLSearchParams=Or.interfaceConverter(URLSearchParams);Or.converters.XMLHttpRequestBodyInit=function(e,t,r){return typeof e=="string"?Or.converters.USVString(e,t,r):rfo(e)?Or.converters.Blob(e,t,r,{strict:!1}):ArrayBuffer.isView(e)||dfo.isArrayBuffer(e)?Or.converters.BufferSource(e,t,r):Oft.isFormDataLike(e)?Or.converters.FormData(e,t,r,{strict:!1}):e instanceof URLSearchParams?Or.converters.URLSearchParams(e,t,r):Or.converters.DOMString(e,t,r)};Or.converters.BodyInit=function(e,t,r){return e instanceof ReadableStream?Or.converters.ReadableStream(e,t,r):e?.[Symbol.asyncIterator]?e:Or.converters.XMLHttpRequestBodyInit(e,t,r)};Or.converters.ResponseInit=Or.dictionaryConverter([{key:"status",converter:Or.converters["unsigned short"],defaultValue:()=>200},{key:"statusText",converter:Or.converters.ByteString,defaultValue:()=>""},{key:"headers",converter:Or.converters.HeadersInit}]);SHr.exports={isNetworkError:pfo,makeNetworkError:Exe,makeResponse:v3,makeAppropriateNetworkError:ffo,filterResponse:EHr,Response:VO,cloneResponse:Nft,fromInnerResponse:lZ}});var RHr=Be((JFs,THr)=>{"use strict";var{kConnected:xHr,kSize:CHr}=Ts(),Bft=class{constructor(t){this.value=t}deref(){return this.value[xHr]===0&&this.value[CHr]===0?void 0:this.value}},Dft=class{constructor(t){this.finalizer=t}register(t,r){t.on&&t.on("disconnect",()=>{t[xHr]===0&&t[CHr]===0&&this.finalizer(r)})}unregister(t){}};THr.exports=function(){return process.env.NODE_V8_COVERAGE&&process.version.startsWith("v18")?(process._rawDebug("Using compatibility WeakRef and FinalizationRegistry"),{WeakRef:Bft,FinalizationRegistry:Dft}):{WeakRef,FinalizationRegistry}}});var I3=Be((KFs,HHr)=>{"use strict";var{extractBody:hfo,mixinBody:mfo,cloneBody:gfo,bodyUnusable:_Hr}=t3(),{Headers:FHr,fill:wfo,HeadersList:Txe,setHeadersGuard:Fft,getHeadersGuard:yfo,setHeadersList:UHr,getHeadersList:PHr}=GO(),{FinalizationRegistry:Afo}=RHr()(),xxe=qr(),$Hr=Re("node:util"),{isValidHTTPToken:bfo,sameOrigin:OHr,environmentSettingsObject:Sxe}=Kh(),{forbiddenMethodsSet:vfo,corsSafeListedMethodsSet:Ifo,referrerPolicy:kfo,requestRedirect:Efo,requestMode:Sfo,requestCredentials:xfo,requestCache:Cfo,requestDuplex:Tfo}=P7(),{kEnumerableProperty:ql,normalizedMethodRecordsBase:Rfo,normalizedMethodRecords:_fo}=xxe,{kHeaders:nm,kSignal:Cxe,kState:Ko,kDispatcher:Lft}=zC(),{webidl:Vt}=Cd(),{URLSerializer:Pfo}=Nf(),{kConstruct:Rxe}=Ts(),$fo=Re("node:assert"),{getMaxListeners:MHr,setMaxListeners:NHr,getEventListeners:Ofo,defaultMaxListeners:BHr}=Re("node:events"),Mfo=Symbol("abortController"),jHr=new Afo(({signal:e,abort:t})=>{e.removeEventListener("abort",t)}),_xe=new WeakMap;function DHr(e){return t;function t(){let r=e.deref();if(r!==void 0){jHr.unregister(t),this.removeEventListener("abort",t),r.abort(this.reason);let n=_xe.get(r.signal);if(n!==void 0){if(n.size!==0){for(let i of n){let o=i.deref();o!==void 0&&o.abort(this.reason)}n.clear()}_xe.delete(r.signal)}}}}var LHr=!1,oT=class e{constructor(t,r={}){if(Vt.util.markAsUncloneable(this),t===Rxe)return;let n="Request constructor";Vt.argumentLengthCheck(arguments,1,n),t=Vt.converters.RequestInfo(t,n,"input"),r=Vt.converters.RequestInit(r,n,"init");let i=null,o=null,s=Sxe.settingsObject.baseUrl,a=null;if(typeof t=="string"){this[Lft]=r.dispatcher;let w;try{w=new URL(t,s)}catch(y){throw new TypeError("Failed to parse URL from "+t,{cause:y})}if(w.username||w.password)throw new TypeError("Request cannot be constructed from a URL that includes credentials: "+t);i=Pxe({urlList:[w]}),o="cors"}else this[Lft]=r.dispatcher||t[Lft],$fo(t instanceof e),i=t[Ko],a=t[Cxe];let l=Sxe.settingsObject.origin,c="client";if(i.window?.constructor?.name==="EnvironmentSettingsObject"&&OHr(i.window,l)&&(c=i.window),r.window!=null)throw new TypeError(`'window' option '${c}' must be null`);"window"in r&&(c="no-window"),i=Pxe({method:i.method,headersList:i.headersList,unsafeRequest:i.unsafeRequest,client:Sxe.settingsObject,window:c,priority:i.priority,origin:i.origin,referrer:i.referrer,referrerPolicy:i.referrerPolicy,mode:i.mode,credentials:i.credentials,cache:i.cache,redirect:i.redirect,integrity:i.integrity,keepalive:i.keepalive,reloadNavigation:i.reloadNavigation,historyNavigation:i.historyNavigation,urlList:[...i.urlList]});let d=Object.keys(r).length!==0;if(d&&(i.mode==="navigate"&&(i.mode="same-origin"),i.reloadNavigation=!1,i.historyNavigation=!1,i.origin="client",i.referrer="client",i.referrerPolicy="",i.url=i.urlList[i.urlList.length-1],i.urlList=[i.url]),r.referrer!==void 0){let w=r.referrer;if(w==="")i.referrer="no-referrer";else{let y;try{y=new URL(w,s)}catch(A){throw new TypeError(`Referrer "${w}" is not a valid URL.`,{cause:A})}y.protocol==="about:"&&y.hostname==="client"||l&&!OHr(y,Sxe.settingsObject.baseUrl)?i.referrer="client":i.referrer=y}}r.referrerPolicy!==void 0&&(i.referrerPolicy=r.referrerPolicy);let u;if(r.mode!==void 0?u=r.mode:u=o,u==="navigate")throw Vt.errors.exception({header:"Request constructor",message:"invalid request mode navigate."});if(u!=null&&(i.mode=u),r.credentials!==void 0&&(i.credentials=r.credentials),r.cache!==void 0&&(i.cache=r.cache),i.cache==="only-if-cached"&&i.mode!=="same-origin")throw new TypeError("'only-if-cached' can be set only with 'same-origin' mode");if(r.redirect!==void 0&&(i.redirect=r.redirect),r.integrity!=null&&(i.integrity=String(r.integrity)),r.keepalive!==void 0&&(i.keepalive=!!r.keepalive),r.method!==void 0){let w=r.method,y=_fo[w];if(y!==void 0)i.method=y;else{if(!bfo(w))throw new TypeError(`'${w}' is not a valid HTTP method.`);let A=w.toUpperCase();if(vfo.has(A))throw new TypeError(`'${w}' HTTP method is unsupported.`);w=Rfo[A]??w,i.method=w}!LHr&&i.method==="patch"&&(process.emitWarning("Using `patch` is highly likely to result in a `405 Method Not Allowed`. `PATCH` is much more likely to succeed.",{code:"UNDICI-FETCH-patch"}),LHr=!0)}r.signal!==void 0&&(a=r.signal),this[Ko]=i;let p=new AbortController;if(this[Cxe]=p.signal,a!=null){if(!a||typeof a.aborted!="boolean"||typeof a.addEventListener!="function")throw new TypeError("Failed to construct 'Request': member signal is not of type AbortSignal.");if(a.aborted)p.abort(a.reason);else{this[Mfo]=p;let w=new WeakRef(p),y=DHr(w);try{(typeof MHr=="function"&&MHr(a)===BHr||Ofo(a,"abort").length>=BHr)&&NHr(1500,a)}catch{}xxe.addAbortListener(a,y),jHr.register(p,{signal:a,abort:y},y)}}if(this[nm]=new FHr(Rxe),UHr(this[nm],i.headersList),Fft(this[nm],"request"),u==="no-cors"){if(!Ifo.has(i.method))throw new TypeError(`'${i.method} is unsupported in no-cors mode.`);Fft(this[nm],"request-no-cors")}if(d){let w=PHr(this[nm]),y=r.headers!==void 0?r.headers:new Txe(w);if(w.clear(),y instanceof Txe){for(let{name:A,value:b}of y.rawValues())w.append(A,b,!1);w.cookies=y.cookies}else wfo(this[nm],y)}let f=t instanceof e?t[Ko].body:null;if((r.body!=null||f!=null)&&(i.method==="GET"||i.method==="HEAD"))throw new TypeError("Request with GET/HEAD method cannot have body.");let h=null;if(r.body!=null){let[w,y]=hfo(r.body,i.keepalive);h=w,y&&!PHr(this[nm]).contains("content-type",!0)&&this[nm].append("content-type",y)}let m=h??f;if(m!=null&&m.source==null){if(h!=null&&r.duplex==null)throw new TypeError("RequestInit: duplex option is required when sending a body.");if(i.mode!=="same-origin"&&i.mode!=="cors")throw new TypeError('If request is made from ReadableStream, mode should be "same-origin" or "cors"');i.useCORSPreflightFlag=!0}let g=m;if(h==null&&f!=null){if(_Hr(t))throw new TypeError("Cannot construct a Request with a Request object that has already been used.");let w=new TransformStream;f.stream.pipeThrough(w),g={source:f.source,length:f.length,stream:w.readable}}this[Ko].body=g}get method(){return Vt.brandCheck(this,e),this[Ko].method}get url(){return Vt.brandCheck(this,e),Pfo(this[Ko].url)}get headers(){return Vt.brandCheck(this,e),this[nm]}get destination(){return Vt.brandCheck(this,e),this[Ko].destination}get referrer(){return Vt.brandCheck(this,e),this[Ko].referrer==="no-referrer"?"":this[Ko].referrer==="client"?"about:client":this[Ko].referrer.toString()}get referrerPolicy(){return Vt.brandCheck(this,e),this[Ko].referrerPolicy}get mode(){return Vt.brandCheck(this,e),this[Ko].mode}get credentials(){return this[Ko].credentials}get cache(){return Vt.brandCheck(this,e),this[Ko].cache}get redirect(){return Vt.brandCheck(this,e),this[Ko].redirect}get integrity(){return Vt.brandCheck(this,e),this[Ko].integrity}get keepalive(){return Vt.brandCheck(this,e),this[Ko].keepalive}get isReloadNavigation(){return Vt.brandCheck(this,e),this[Ko].reloadNavigation}get isHistoryNavigation(){return Vt.brandCheck(this,e),this[Ko].historyNavigation}get signal(){return Vt.brandCheck(this,e),this[Cxe]}get body(){return Vt.brandCheck(this,e),this[Ko].body?this[Ko].body.stream:null}get bodyUsed(){return Vt.brandCheck(this,e),!!this[Ko].body&&xxe.isDisturbed(this[Ko].body.stream)}get duplex(){return Vt.brandCheck(this,e),"half"}clone(){if(Vt.brandCheck(this,e),_Hr(this))throw new TypeError("unusable");let t=qHr(this[Ko]),r=new AbortController;if(this.signal.aborted)r.abort(this.signal.reason);else{let n=_xe.get(this.signal);n===void 0&&(n=new Set,_xe.set(this.signal,n));let i=new WeakRef(r);n.add(i),xxe.addAbortListener(r.signal,DHr(i))}return QHr(t,r.signal,yfo(this[nm]))}[$Hr.inspect.custom](t,r){r.depth===null&&(r.depth=2),r.colors??=!0;let n={method:this.method,url:this.url,headers:this.headers,destination:this.destination,referrer:this.referrer,referrerPolicy:this.referrerPolicy,mode:this.mode,credentials:this.credentials,cache:this.cache,redirect:this.redirect,integrity:this.integrity,keepalive:this.keepalive,isReloadNavigation:this.isReloadNavigation,isHistoryNavigation:this.isHistoryNavigation,signal:this.signal};return`Request ${$Hr.formatWithOptions(r,n)}`}};mfo(oT);function Pxe(e){return{method:e.method??"GET",localURLsOnly:e.localURLsOnly??!1,unsafeRequest:e.unsafeRequest??!1,body:e.body??null,client:e.client??null,reservedClient:e.reservedClient??null,replacesClientId:e.replacesClientId??"",window:e.window??"client",keepalive:e.keepalive??!1,serviceWorkers:e.serviceWorkers??"all",initiator:e.initiator??"",destination:e.destination??"",priority:e.priority??null,origin:e.origin??"client",policyContainer:e.policyContainer??"client",referrer:e.referrer??"client",referrerPolicy:e.referrerPolicy??"",mode:e.mode??"no-cors",useCORSPreflightFlag:e.useCORSPreflightFlag??!1,credentials:e.credentials??"same-origin",useCredentials:e.useCredentials??!1,cache:e.cache??"default",redirect:e.redirect??"follow",integrity:e.integrity??"",cryptoGraphicsNonceMetadata:e.cryptoGraphicsNonceMetadata??"",parserMetadata:e.parserMetadata??"",reloadNavigation:e.reloadNavigation??!1,historyNavigation:e.historyNavigation??!1,userActivation:e.userActivation??!1,taintedOrigin:e.taintedOrigin??!1,redirectCount:e.redirectCount??0,responseTainting:e.responseTainting??"basic",preventNoCacheCacheControlHeaderModification:e.preventNoCacheCacheControlHeaderModification??!1,done:e.done??!1,timingAllowFailed:e.timingAllowFailed??!1,urlList:e.urlList,url:e.urlList[0],headersList:e.headersList?new Txe(e.headersList):new Txe}}function qHr(e){let t=Pxe({...e,body:null});return e.body!=null&&(t.body=gfo(t,e.body)),t}function QHr(e,t,r){let n=new oT(Rxe);return n[Ko]=e,n[Cxe]=t,n[nm]=new FHr(Rxe),UHr(n[nm],e.headersList),Fft(n[nm],r),n}Object.defineProperties(oT.prototype,{method:ql,url:ql,headers:ql,redirect:ql,clone:ql,signal:ql,duplex:ql,destination:ql,body:ql,bodyUsed:ql,isHistoryNavigation:ql,isReloadNavigation:ql,keepalive:ql,integrity:ql,cache:ql,credentials:ql,attribute:ql,referrerPolicy:ql,referrer:ql,mode:ql,[Symbol.toStringTag]:{value:"Request",configurable:!0}});Vt.converters.Request=Vt.interfaceConverter(oT);Vt.converters.RequestInfo=function(e,t,r){return typeof e=="string"?Vt.converters.USVString(e,t,r):e instanceof oT?Vt.converters.Request(e,t,r):Vt.converters.USVString(e,t,r)};Vt.converters.AbortSignal=Vt.interfaceConverter(AbortSignal);Vt.converters.RequestInit=Vt.dictionaryConverter([{key:"method",converter:Vt.converters.ByteString},{key:"headers",converter:Vt.converters.HeadersInit},{key:"body",converter:Vt.nullableConverter(Vt.converters.BodyInit)},{key:"referrer",converter:Vt.converters.USVString},{key:"referrerPolicy",converter:Vt.converters.DOMString,allowedValues:kfo},{key:"mode",converter:Vt.converters.DOMString,allowedValues:Sfo},{key:"credentials",converter:Vt.converters.DOMString,allowedValues:xfo},{key:"cache",converter:Vt.converters.DOMString,allowedValues:Cfo},{key:"redirect",converter:Vt.converters.DOMString,allowedValues:Efo},{key:"integrity",converter:Vt.converters.DOMString},{key:"keepalive",converter:Vt.converters.boolean},{key:"signal",converter:Vt.nullableConverter(e=>Vt.converters.AbortSignal(e,"RequestInit","signal",{strict:!1}))},{key:"window",converter:Vt.converters.any},{key:"duplex",converter:Vt.converters.DOMString,allowedValues:Tfo},{key:"dispatcher",converter:Vt.converters.any}]);HHr.exports={Request:oT,makeRequest:Pxe,fromInnerRequest:QHr,cloneRequest:qHr}});var uZ=Be((YFs,oWr)=>{"use strict";var{makeNetworkError:Ni,makeAppropriateNetworkError:$xe,filterResponse:Uft,makeResponse:Oxe,fromInnerResponse:Nfo}=cZ(),{HeadersList:WHr}=GO(),{Request:Bfo,cloneRequest:Dfo}=I3(),sT=Re("node:zlib"),{bytesMatch:Lfo,makePolicyContainer:Ffo,clonePolicyContainer:Ufo,requestBadPort:jfo,TAOCheck:qfo,appendRequestOriginHeader:Qfo,responseLocationURL:Hfo,requestCurrentURL:mv,setRequestReferrerPolicyOnRedirect:Wfo,tryUpgradeRequestToAPotentiallyTrustworthyURL:Gfo,createOpaqueTimingInfo:Wft,appendFetchMetadata:Vfo,corsCheck:zfo,crossOriginResourcePolicyCheck:Xfo,determineRequestsReferrer:Jfo,coarsenedSharedCurrentTime:dZ,createDeferredPromise:Kfo,isBlobLike:Yfo,sameOrigin:Hft,isCancelled:zO,isAborted:GHr,isErrorLike:Zfo,fullyReadBody:eho,readableStreamClose:tho,isomorphicEncode:Mxe,urlIsLocal:rho,urlIsHttpHttpsScheme:Gft,urlHasHttpsScheme:nho,clampAndCoarsenConnectionTimingInfo:iho,simpleRangeHeaderValue:oho,buildContentRange:sho,createInflate:aho,extractMimeType:lho}=Kh(),{kState:JHr,kDispatcher:cho}=zC(),XO=Re("node:assert"),{safelyExtractBody:Vft,extractBody:VHr}=t3(),{redirectStatusSet:KHr,nullBodyStatus:YHr,safeMethodsSet:dho,requestBodyHeader:uho,subresourceSet:pho}=P7(),fho=Re("node:events"),{Readable:hho,pipeline:mho,finished:gho}=Re("node:stream"),{addAbortListener:who,isErrored:yho,isReadable:Nxe,bufferToLowerCasedHeaderName:zHr}=qr(),{dataURLProcessor:Aho,serializeAMimeType:bho,minimizeSupportedMimeType:vho}=Nf(),{getGlobalDispatcher:Iho}=sZ(),{webidl:kho}=Cd(),{STATUS_CODES:Eho}=Re("node:http"),Sho=["GET","HEAD"],xho=typeof __UNDICI_IS_NODE__<"u"||typeof esbuildDetection<"u"?"node":"undici",jft,Bxe=class extends fho{constructor(t){super(),this.dispatcher=t,this.connection=null,this.dump=!1,this.state="ongoing"}terminate(t){this.state==="ongoing"&&(this.state="terminated",this.connection?.destroy(t),this.emit("terminated",t))}abort(t){this.state==="ongoing"&&(this.state="aborted",t||(t=new DOMException("The operation was aborted.","AbortError")),this.serializedAbortReason=t,this.connection?.destroy(t),this.emit("terminated",t))}};function Cho(e){ZHr(e,"fetch")}function Tho(e,t=void 0){kho.argumentLengthCheck(arguments,1,"globalThis.fetch");let r=Kfo(),n;try{n=new Bfo(e,t)}catch(d){return r.reject(d),r.promise}let i=n[JHr];if(n.signal.aborted)return qft(r,i,null,n.signal.reason),r.promise;i.client.globalObject?.constructor?.name==="ServiceWorkerGlobalScope"&&(i.serviceWorkers="none");let s=null,a=!1,l=null;return who(n.signal,()=>{a=!0,XO(l!=null),l.abort(n.signal.reason);let d=s?.deref();qft(r,i,d,n.signal.reason)}),l=tWr({request:i,processResponseEndOfBody:Cho,processResponse:d=>{if(!a){if(d.aborted){qft(r,i,s,l.serializedAbortReason);return}if(d.type==="error"){r.reject(new TypeError("fetch failed",{cause:d.error}));return}s=new WeakRef(Nfo(d,"immutable")),r.resolve(s.deref()),r=null}},dispatcher:n[cho]}),r.promise}function ZHr(e,t="other"){if(e.type==="error"&&e.aborted||!e.urlList?.length)return;let r=e.urlList[0],n=e.timingInfo,i=e.cacheState;Gft(r)&&n!==null&&(e.timingAllowPassed||(n=Wft({startTime:n.startTime}),i=""),n.endTime=dZ(),e.timingInfo=n,eWr(n,r.href,t,globalThis,i))}var eWr=performance.markResourceTiming;function qft(e,t,r,n){if(e&&e.reject(n),t.body!=null&&Nxe(t.body?.stream)&&t.body.stream.cancel(n).catch(o=>{if(o.code!=="ERR_INVALID_STATE")throw o}),r==null)return;let i=r[JHr];i.body!=null&&Nxe(i.body?.stream)&&i.body.stream.cancel(n).catch(o=>{if(o.code!=="ERR_INVALID_STATE")throw o})}function tWr({request:e,processRequestBodyChunkLength:t,processRequestEndOfBody:r,processResponse:n,processResponseEndOfBody:i,processResponseConsumeBody:o,useParallelQueue:s=!1,dispatcher:a=Iho()}){XO(a);let l=null,c=!1;e.client!=null&&(l=e.client.globalObject,c=e.client.crossOriginIsolatedCapability);let d=dZ(c),u=Wft({startTime:d}),p={controller:new Bxe(a),request:e,timingInfo:u,processRequestBodyChunkLength:t,processRequestEndOfBody:r,processResponse:n,processResponseConsumeBody:o,processResponseEndOfBody:i,taskDestination:l,crossOriginIsolatedCapability:c};return XO(!e.body||e.body.stream),e.window==="client"&&(e.window=e.client?.globalObject?.constructor?.name==="Window"?e.client:"no-window"),e.origin==="client"&&(e.origin=e.client.origin),e.policyContainer==="client"&&(e.client!=null?e.policyContainer=Ufo(e.client.policyContainer):e.policyContainer=Ffo()),e.headersList.contains("accept",!0)||e.headersList.append("accept","*/*",!0),e.headersList.contains("accept-language",!0)||e.headersList.append("accept-language","*",!0),e.priority,pho.has(e.destination),rWr(p).catch(f=>{p.controller.terminate(f)}),p.controller}async function rWr(e,t=!1){let r=e.request,n=null;if(r.localURLsOnly&&!rho(mv(r))&&(n=Ni("local URLs only")),Gfo(r),jfo(r)==="blocked"&&(n=Ni("bad port")),r.referrerPolicy===""&&(r.referrerPolicy=r.policyContainer.referrerPolicy),r.referrer!=="no-referrer"&&(r.referrer=Jfo(r)),n===null&&(n=await(async()=>{let o=mv(r);return Hft(o,r.url)&&r.responseTainting==="basic"||o.protocol==="data:"||r.mode==="navigate"||r.mode==="websocket"?(r.responseTainting="basic",await XHr(e)):r.mode==="same-origin"?Ni('request mode cannot be "same-origin"'):r.mode==="no-cors"?r.redirect!=="follow"?Ni('redirect mode cannot be "follow" for "no-cors" request'):(r.responseTainting="opaque",await XHr(e)):Gft(mv(r))?(r.responseTainting="cors",await nWr(e)):Ni("URL scheme must be a HTTP(S) scheme")})()),t)return n;n.status!==0&&!n.internalResponse&&(r.responseTainting,r.responseTainting==="basic"?n=Uft(n,"basic"):r.responseTainting==="cors"?n=Uft(n,"cors"):r.responseTainting==="opaque"?n=Uft(n,"opaque"):XO(!1));let i=n.status===0?n:n.internalResponse;if(i.urlList.length===0&&i.urlList.push(...r.urlList),r.timingAllowFailed||(n.timingAllowPassed=!0),n.type==="opaque"&&i.status===206&&i.rangeRequested&&!r.headers.contains("range",!0)&&(n=i=Ni()),n.status!==0&&(r.method==="HEAD"||r.method==="CONNECT"||YHr.includes(i.status))&&(i.body=null,e.controller.dump=!0),r.integrity){let o=a=>Qft(e,Ni(a));if(r.responseTainting==="opaque"||n.body==null){o(n.error);return}let s=a=>{if(!Lfo(a,r.integrity)){o("integrity mismatch");return}n.body=Vft(a)[0],Qft(e,n)};await eho(n.body,s,o)}else Qft(e,n)}function XHr(e){if(zO(e)&&e.request.redirectCount===0)return Promise.resolve($xe(e));let{request:t}=e,{protocol:r}=mv(t);switch(r){case"about:":return Promise.resolve(Ni("about scheme is not supported"));case"blob:":{jft||(jft=Re("node:buffer").resolveObjectURL);let n=mv(t);if(n.search.length!==0)return Promise.resolve(Ni("NetworkError when attempting to fetch resource."));let i=jft(n.toString());if(t.method!=="GET"||!Yfo(i))return Promise.resolve(Ni("invalid method"));let o=Oxe(),s=i.size,a=Mxe(`${s}`),l=i.type;if(t.headersList.contains("range",!0)){o.rangeRequested=!0;let c=t.headersList.get("range",!0),d=oho(c,!0);if(d==="failure")return Promise.resolve(Ni("failed to fetch the data URL"));let{rangeStartValue:u,rangeEndValue:p}=d;if(u===null)u=s-p,p=u+p-1;else{if(u>=s)return Promise.resolve(Ni("Range start is greater than the blob's size."));(p===null||p>=s)&&(p=s-1)}let f=i.slice(u,p,l),h=VHr(f);o.body=h[0];let m=Mxe(`${f.size}`),g=sho(u,p,s);o.status=206,o.statusText="Partial Content",o.headersList.set("content-length",m,!0),o.headersList.set("content-type",l,!0),o.headersList.set("content-range",g,!0)}else{let c=VHr(i);o.statusText="OK",o.body=c[0],o.headersList.set("content-length",a,!0),o.headersList.set("content-type",l,!0)}return Promise.resolve(o)}case"data:":{let n=mv(t),i=Aho(n);if(i==="failure")return Promise.resolve(Ni("failed to fetch the data URL"));let o=bho(i.mimeType);return Promise.resolve(Oxe({statusText:"OK",headersList:[["content-type",{name:"Content-Type",value:o}]],body:Vft(i.body)[0]}))}case"file:":return Promise.resolve(Ni("not implemented... yet..."));case"http:":case"https:":return nWr(e).catch(n=>Ni(n));default:return Promise.resolve(Ni("unknown scheme"))}}function Rho(e,t){e.request.done=!0,e.processResponseDone!=null&&queueMicrotask(()=>e.processResponseDone(t))}function Qft(e,t){let r=e.timingInfo,n=()=>{let o=Date.now();e.request.destination==="document"&&(e.controller.fullTimingInfo=r),e.controller.reportTimingSteps=()=>{if(e.request.url.protocol!=="https:")return;r.endTime=o;let a=t.cacheState,l=t.bodyInfo;t.timingAllowPassed||(r=Wft(r),a="");let c=0;if(e.request.mode!=="navigator"||!t.hasCrossOriginRedirects){c=t.status;let d=lho(t.headersList);d!=="failure"&&(l.contentType=vho(d))}e.request.initiatorType!=null&&eWr(r,e.request.url.href,e.request.initiatorType,globalThis,a,l,c)};let s=()=>{e.request.done=!0,e.processResponseEndOfBody!=null&&queueMicrotask(()=>e.processResponseEndOfBody(t)),e.request.initiatorType!=null&&e.controller.reportTimingSteps()};queueMicrotask(()=>s())};e.processResponse!=null&&queueMicrotask(()=>{e.processResponse(t),e.processResponse=null});let i=t.type==="error"?t:t.internalResponse??t;i.body==null?n():gho(i.body.stream,()=>{n()})}async function nWr(e){let t=e.request,r=null,n=null,i=e.timingInfo;if(t.serviceWorkers,r===null){if(t.redirect==="follow"&&(t.serviceWorkers="none"),n=r=await iWr(e),t.responseTainting==="cors"&&zfo(t,r)==="failure")return Ni("cors failure");qfo(t,r)==="failure"&&(t.timingAllowFailed=!0)}return(t.responseTainting==="opaque"||r.type==="opaque")&&Xfo(t.origin,t.client,t.destination,n)==="blocked"?Ni("blocked"):(KHr.has(n.status)&&(t.redirect!=="manual"&&e.controller.connection.destroy(void 0,!1),t.redirect==="error"?r=Ni("unexpected redirect"):t.redirect==="manual"?r=n:t.redirect==="follow"?r=await _ho(e,r):XO(!1)),r.timingInfo=i,r)}function _ho(e,t){let r=e.request,n=t.internalResponse?t.internalResponse:t,i;try{if(i=Hfo(n,mv(r).hash),i==null)return t}catch(s){return Promise.resolve(Ni(s))}if(!Gft(i))return Promise.resolve(Ni("URL scheme must be a HTTP(S) scheme"));if(r.redirectCount===20)return Promise.resolve(Ni("redirect count exceeded"));if(r.redirectCount+=1,r.mode==="cors"&&(i.username||i.password)&&!Hft(r,i))return Promise.resolve(Ni('cross origin not allowed for request mode "cors"'));if(r.responseTainting==="cors"&&(i.username||i.password))return Promise.resolve(Ni('URL cannot contain credentials for request mode "cors"'));if(n.status!==303&&r.body!=null&&r.body.source==null)return Promise.resolve(Ni());if([301,302].includes(n.status)&&r.method==="POST"||n.status===303&&!Sho.includes(r.method)){r.method="GET",r.body=null;for(let s of uho)r.headersList.delete(s)}Hft(mv(r),i)||(r.headersList.delete("authorization",!0),r.headersList.delete("proxy-authorization",!0),r.headersList.delete("cookie",!0),r.headersList.delete("host",!0)),r.body!=null&&(XO(r.body.source!=null),r.body=Vft(r.body.source)[0]);let o=e.timingInfo;return o.redirectEndTime=o.postRedirectStartTime=dZ(e.crossOriginIsolatedCapability),o.redirectStartTime===0&&(o.redirectStartTime=o.startTime),r.urlList.push(i),Wfo(r,n),rWr(e,!0)}async function iWr(e,t=!1,r=!1){let n=e.request,i=null,o=null,s=null,a=null,l=!1;n.window==="no-window"&&n.redirect==="error"?(i=e,o=n):(o=Dfo(n),i={...e},i.request=o);let c=n.credentials==="include"||n.credentials==="same-origin"&&n.responseTainting==="basic",d=o.body?o.body.length:null,u=null;if(o.body==null&&["POST","PUT"].includes(o.method)&&(u="0"),d!=null&&(u=Mxe(`${d}`)),u!=null&&o.headersList.append("content-length",u,!0),d!=null&&o.keepalive,o.referrer instanceof URL&&o.headersList.append("referer",Mxe(o.referrer.href),!0),Qfo(o),Vfo(o),o.headersList.contains("user-agent",!0)||o.headersList.append("user-agent",xho),o.cache==="default"&&(o.headersList.contains("if-modified-since",!0)||o.headersList.contains("if-none-match",!0)||o.headersList.contains("if-unmodified-since",!0)||o.headersList.contains("if-match",!0)||o.headersList.contains("if-range",!0))&&(o.cache="no-store"),o.cache==="no-cache"&&!o.preventNoCacheCacheControlHeaderModification&&!o.headersList.contains("cache-control",!0)&&o.headersList.append("cache-control","max-age=0",!0),(o.cache==="no-store"||o.cache==="reload")&&(o.headersList.contains("pragma",!0)||o.headersList.append("pragma","no-cache",!0),o.headersList.contains("cache-control",!0)||o.headersList.append("cache-control","no-cache",!0)),o.headersList.contains("range",!0)&&o.headersList.append("accept-encoding","identity",!0),o.headersList.contains("accept-encoding",!0)||(nho(mv(o))?o.headersList.append("accept-encoding","br, gzip, deflate",!0):o.headersList.append("accept-encoding","gzip, deflate",!0)),o.headersList.delete("host",!0),a==null&&(o.cache="no-store"),o.cache!=="no-store"&&o.cache,s==null){if(o.cache==="only-if-cached")return Ni("only if cached");let p=await Pho(i,c,r);!dho.has(o.method)&&p.status>=200&&p.status<=399,l&&p.status,s==null&&(s=p)}if(s.urlList=[...o.urlList],o.headersList.contains("range",!0)&&(s.rangeRequested=!0),s.requestIncludesCredentials=c,s.status===407)return n.window==="no-window"?Ni():zO(e)?$xe(e):Ni("proxy authentication required");if(s.status===421&&!r&&(n.body==null||n.body.source!=null)){if(zO(e))return $xe(e);e.controller.connection.destroy(),s=await iWr(e,t,!0)}return s}async function Pho(e,t=!1,r=!1){XO(!e.controller.connection||e.controller.connection.destroyed),e.controller.connection={abort:null,destroyed:!1,destroy(h,m=!0){this.destroyed||(this.destroyed=!0,m&&this.abort?.(h??new DOMException("The operation was aborted.","AbortError")))}};let n=e.request,i=null,o=e.timingInfo;null==null&&(n.cache="no-store");let a=r?"yes":"no";n.mode;let l=null;if(n.body==null&&e.processRequestEndOfBody)queueMicrotask(()=>e.processRequestEndOfBody());else if(n.body!=null){let h=async function*(w){zO(e)||(yield w,e.processRequestBodyChunkLength?.(w.byteLength))},m=()=>{zO(e)||e.processRequestEndOfBody&&e.processRequestEndOfBody()},g=w=>{zO(e)||(w.name==="AbortError"?e.controller.abort():e.controller.terminate(w))};l=(async function*(){try{for await(let w of n.body.stream)yield*h(w);m()}catch(w){g(w)}})()}try{let{body:h,status:m,statusText:g,headersList:w,socket:y}=await f({body:l});if(y)i=Oxe({status:m,statusText:g,headersList:w,socket:y});else{let A=h[Symbol.asyncIterator]();e.controller.next=()=>A.next(),i=Oxe({status:m,statusText:g,headersList:w})}}catch(h){return h.name==="AbortError"?(e.controller.connection.destroy(),$xe(e,h)):Ni(h)}let c=async()=>{await e.controller.resume()},d=h=>{zO(e)||e.controller.abort(h)},u=new ReadableStream({async start(h){e.controller.controller=h},async pull(h){await c(h)},async cancel(h){await d(h)},type:"bytes"});i.body={stream:u,source:null,length:null},e.controller.resume||e.controller.on("terminated",p),e.controller.resume=async()=>{for(;;){let h,m;try{let{done:w,value:y}=await e.controller.next();if(GHr(e))break;h=w?void 0:y}catch(w){e.controller.ended&&!o.encodedBodySize?h=void 0:(h=w,m=!0)}if(h===void 0){tho(e.controller.controller),Rho(e,i);return}if(o.decodedBodySize+=h?.byteLength??0,m){e.controller.terminate(h);return}let g=new Uint8Array(h);if(g.byteLength&&e.controller.controller.enqueue(g),yho(u)){e.controller.terminate();return}if(e.controller.controller.desiredSize<=0)return}};function p(h){GHr(e)?(i.aborted=!0,Nxe(u)&&e.controller.controller.error(e.controller.serializedAbortReason)):Nxe(u)&&e.controller.controller.error(new TypeError("terminated",{cause:Zfo(h)?h:void 0})),e.controller.connection.destroy()}return i;function f({body:h}){let m=mv(n),g=e.controller.dispatcher;return new Promise((w,y)=>g.dispatch({path:m.pathname+m.search,origin:m.origin,method:n.method,body:g.isMockActive?n.body&&(n.body.source||n.body.stream):h,headers:n.headersList.entries,maxRedirections:0,upgrade:n.mode==="websocket"?"websocket":void 0},{body:null,abort:null,onConnect(A){let{connection:b}=e.controller;o.finalConnectionTimingInfo=iho(void 0,o.postRedirectStartTime,e.crossOriginIsolatedCapability),b.destroyed?A(new DOMException("The operation was aborted.","AbortError")):(e.controller.on("terminated",A),this.abort=b.abort=A),o.finalNetworkRequestStartTime=dZ(e.crossOriginIsolatedCapability)},onResponseStarted(){o.finalNetworkResponseStartTime=dZ(e.crossOriginIsolatedCapability)},onHeaders(A,b,I,v){if(A<200)return;let k="",S=new WHr;for(let _=0;_<b.length;_+=2)S.append(zHr(b[_]),b[_+1].toString("latin1"),!0);k=S.get("location",!0);let x=[],E=k&&n.redirect==="follow"&&KHr.has(A);if(n.method!=="HEAD"&&n.method!=="CONNECT"&&!YHr.includes(A)&&!E){let _=S.get("content-encoding",!0),P=_?_.toLowerCase().split(","):[],R=5;if(P.length>R)return this.abort(new Error(`too many content-encodings in response: ${P.length}, maximum allowed is ${R}`)),!0;for(let $=P.length-1;$>=0;--$){let O=P[$].trim();if(O==="x-gzip"||O==="gzip")x.push(sT.createGunzip({flush:sT.constants.Z_SYNC_FLUSH,finishFlush:sT.constants.Z_SYNC_FLUSH}));else if(O==="deflate")x.push(aho({flush:sT.constants.Z_SYNC_FLUSH,finishFlush:sT.constants.Z_SYNC_FLUSH}));else if(O==="br")x.push(sT.createBrotliDecompress({flush:sT.constants.BROTLI_OPERATION_FLUSH,finishFlush:sT.constants.BROTLI_OPERATION_FLUSH}));else{x.length=0;break}}}this.body=new hho({read:I});let C=this.onError.bind(this);return w({status:A,statusText:v,headersList:S,body:x.length?mho(this.body,...x,_=>{_&&this.onError(_)}).on("error",C):this.body.on("error",C)}),!0},onData(A){if(e.controller.dump)return;let b=A;return o.encodedBodySize+=b.byteLength,this.body.push(b)},onComplete(){this.abort&&e.controller.off("terminated",this.abort),e.controller.ended=!0,this.body.push(null)},onError(A){this.abort&&e.controller.off("terminated",this.abort),this.body?.destroy(A),e.controller.terminate(A),y(A)},onUpgrade(A,b,I){if(A!==101)return;let v=new WHr;for(let k=0;k<b.length;k+=2)v.append(zHr(b[k]),b[k+1].toString("latin1"),!0);return w({status:A,statusText:Eho[A],headersList:v,socket:I}),!0}}))}}oWr.exports={fetch:Tho,Fetch:Bxe,fetching:tWr,finalizeAndReportTiming:ZHr}});var zft=Be((ZFs,sWr)=>{"use strict";sWr.exports={kState:Symbol("FileReader state"),kResult:Symbol("FileReader result"),kError:Symbol("FileReader error"),kLastProgressEventFired:Symbol("FileReader last progress event fired timestamp"),kEvents:Symbol("FileReader events"),kAborted:Symbol("FileReader aborted")}});var lWr=Be((eUs,aWr)=>{"use strict";var{webidl:im}=Cd(),Dxe=Symbol("ProgressEvent state"),Xft=class e extends Event{constructor(t,r={}){t=im.converters.DOMString(t,"ProgressEvent constructor","type"),r=im.converters.ProgressEventInit(r??{}),super(t,r),this[Dxe]={lengthComputable:r.lengthComputable,loaded:r.loaded,total:r.total}}get lengthComputable(){return im.brandCheck(this,e),this[Dxe].lengthComputable}get loaded(){return im.brandCheck(this,e),this[Dxe].loaded}get total(){return im.brandCheck(this,e),this[Dxe].total}};im.converters.ProgressEventInit=im.dictionaryConverter([{key:"lengthComputable",converter:im.converters.boolean,defaultValue:()=>!1},{key:"loaded",converter:im.converters["unsigned long long"],defaultValue:()=>0},{key:"total",converter:im.converters["unsigned long long"],defaultValue:()=>0},{key:"bubbles",converter:im.converters.boolean,defaultValue:()=>!1},{key:"cancelable",converter:im.converters.boolean,defaultValue:()=>!1},{key:"composed",converter:im.converters.boolean,defaultValue:()=>!1}]);aWr.exports={ProgressEvent:Xft}});var dWr=Be((tUs,cWr)=>{"use strict";function $ho(e){if(!e)return"failure";switch(e.trim().toLowerCase()){case"unicode-1-1-utf-8":case"unicode11utf8":case"unicode20utf8":case"utf-8":case"utf8":case"x-unicode20utf8":return"UTF-8";case"866":case"cp866":case"csibm866":case"ibm866":return"IBM866";case"csisolatin2":case"iso-8859-2":case"iso-ir-101":case"iso8859-2":case"iso88592":case"iso_8859-2":case"iso_8859-2:1987":case"l2":case"latin2":return"ISO-8859-2";case"csisolatin3":case"iso-8859-3":case"iso-ir-109":case"iso8859-3":case"iso88593":case"iso_8859-3":case"iso_8859-3:1988":case"l3":case"latin3":return"ISO-8859-3";case"csisolatin4":case"iso-8859-4":case"iso-ir-110":case"iso8859-4":case"iso88594":case"iso_8859-4":case"iso_8859-4:1988":case"l4":case"latin4":return"ISO-8859-4";case"csisolatincyrillic":case"cyrillic":case"iso-8859-5":case"iso-ir-144":case"iso8859-5":case"iso88595":case"iso_8859-5":case"iso_8859-5:1988":return"ISO-8859-5";case"arabic":case"asmo-708":case"csiso88596e":case"csiso88596i":case"csisolatinarabic":case"ecma-114":case"iso-8859-6":case"iso-8859-6-e":case"iso-8859-6-i":case"iso-ir-127":case"iso8859-6":case"iso88596":case"iso_8859-6":case"iso_8859-6:1987":return"ISO-8859-6";case"csisolatingreek":case"ecma-118":case"elot_928":case"greek":case"greek8":case"iso-8859-7":case"iso-ir-126":case"iso8859-7":case"iso88597":case"iso_8859-7":case"iso_8859-7:1987":case"sun_eu_greek":return"ISO-8859-7";case"csiso88598e":case"csisolatinhebrew":case"hebrew":case"iso-8859-8":case"iso-8859-8-e":case"iso-ir-138":case"iso8859-8":case"iso88598":case"iso_8859-8":case"iso_8859-8:1988":case"visual":return"ISO-8859-8";case"csiso88598i":case"iso-8859-8-i":case"logical":return"ISO-8859-8-I";case"csisolatin6":case"iso-8859-10":case"iso-ir-157":case"iso8859-10":case"iso885910":case"l6":case"latin6":return"ISO-8859-10";case"iso-8859-13":case"iso8859-13":case"iso885913":return"ISO-8859-13";case"iso-8859-14":case"iso8859-14":case"iso885914":return"ISO-8859-14";case"csisolatin9":case"iso-8859-15":case"iso8859-15":case"iso885915":case"iso_8859-15":case"l9":return"ISO-8859-15";case"iso-8859-16":return"ISO-8859-16";case"cskoi8r":case"koi":case"koi8":case"koi8-r":case"koi8_r":return"KOI8-R";case"koi8-ru":case"koi8-u":return"KOI8-U";case"csmacintosh":case"mac":case"macintosh":case"x-mac-roman":return"macintosh";case"iso-8859-11":case"iso8859-11":case"iso885911":case"tis-620":case"windows-874":return"windows-874";case"cp1250":case"windows-1250":case"x-cp1250":return"windows-1250";case"cp1251":case"windows-1251":case"x-cp1251":return"windows-1251";case"ansi_x3.4-1968":case"ascii":case"cp1252":case"cp819":case"csisolatin1":case"ibm819":case"iso-8859-1":case"iso-ir-100":case"iso8859-1":case"iso88591":case"iso_8859-1":case"iso_8859-1:1987":case"l1":case"latin1":case"us-ascii":case"windows-1252":case"x-cp1252":return"windows-1252";case"cp1253":case"windows-1253":case"x-cp1253":return"windows-1253";case"cp1254":case"csisolatin5":case"iso-8859-9":case"iso-ir-148":case"iso8859-9":case"iso88599":case"iso_8859-9":case"iso_8859-9:1989":case"l5":case"latin5":case"windows-1254":case"x-cp1254":return"windows-1254";case"cp1255":case"windows-1255":case"x-cp1255":return"windows-1255";case"cp1256":case"windows-1256":case"x-cp1256":return"windows-1256";case"cp1257":case"windows-1257":case"x-cp1257":return"windows-1257";case"cp1258":case"windows-1258":case"x-cp1258":return"windows-1258";case"x-mac-cyrillic":case"x-mac-ukrainian":return"x-mac-cyrillic";case"chinese":case"csgb2312":case"csiso58gb231280":case"gb2312":case"gb_2312":case"gb_2312-80":case"gbk":case"iso-ir-58":case"x-gbk":return"GBK";case"gb18030":return"gb18030";case"big5":case"big5-hkscs":case"cn-big5":case"csbig5":case"x-x-big5":return"Big5";case"cseucpkdfmtjapanese":case"euc-jp":case"x-euc-jp":return"EUC-JP";case"csiso2022jp":case"iso-2022-jp":return"ISO-2022-JP";case"csshiftjis":case"ms932":case"ms_kanji":case"shift-jis":case"shift_jis":case"sjis":case"windows-31j":case"x-sjis":return"Shift_JIS";case"cseuckr":case"csksc56011987":case"euc-kr":case"iso-ir-149":case"korean":case"ks_c_5601-1987":case"ks_c_5601-1989":case"ksc5601":case"ksc_5601":case"windows-949":return"EUC-KR";case"csiso2022kr":case"hz-gb-2312":case"iso-2022-cn":case"iso-2022-cn-ext":case"iso-2022-kr":case"replacement":return"replacement";case"unicodefffe":case"utf-16be":return"UTF-16BE";case"csunicode":case"iso-10646-ucs-2":case"ucs-2":case"unicode":case"unicodefeff":case"utf-16":case"utf-16le":return"UTF-16LE";case"x-user-defined":return"x-user-defined";default:return"failure"}}cWr.exports={getEncoding:$ho}});var yWr=Be((rUs,wWr)=>{"use strict";var{kState:k3,kError:Jft,kResult:uWr,kAborted:pZ,kLastProgressEventFired:Kft}=zft(),{ProgressEvent:Oho}=lWr(),{getEncoding:pWr}=dWr(),{serializeAMimeType:Mho,parseMIMEType:fWr}=Nf(),{types:Nho}=Re("node:util"),{StringDecoder:hWr}=Re("string_decoder"),{btoa:mWr}=Re("node:buffer"),Bho={enumerable:!0,writable:!1,configurable:!1};function Dho(e,t,r,n){if(e[k3]==="loading")throw new DOMException("Invalid state","InvalidStateError");e[k3]="loading",e[uWr]=null,e[Jft]=null;let o=t.stream().getReader(),s=[],a=o.read(),l=!0;(async()=>{for(;!e[pZ];)try{let{done:c,value:d}=await a;if(l&&!e[pZ]&&queueMicrotask(()=>{aT("loadstart",e)}),l=!1,!c&&Nho.isUint8Array(d))s.push(d),(e[Kft]===void 0||Date.now()-e[Kft]>=50)&&!e[pZ]&&(e[Kft]=Date.now(),queueMicrotask(()=>{aT("progress",e)})),a=o.read();else if(c){queueMicrotask(()=>{e[k3]="done";try{let u=Lho(s,r,t.type,n);if(e[pZ])return;e[uWr]=u,aT("load",e)}catch(u){e[Jft]=u,aT("error",e)}e[k3]!=="loading"&&aT("loadend",e)});break}}catch(c){if(e[pZ])return;queueMicrotask(()=>{e[k3]="done",e[Jft]=c,aT("error",e),e[k3]!=="loading"&&aT("loadend",e)});break}})()}function aT(e,t){let r=new Oho(e,{bubbles:!1,cancelable:!1});t.dispatchEvent(r)}function Lho(e,t,r,n){switch(t){case"DataURL":{let i="data:",o=fWr(r||"application/octet-stream");o!=="failure"&&(i+=Mho(o)),i+=";base64,";let s=new hWr("latin1");for(let a of e)i+=mWr(s.write(a));return i+=mWr(s.end()),i}case"Text":{let i="failure";if(n&&(i=pWr(n)),i==="failure"&&r){let o=fWr(r);o!=="failure"&&(i=pWr(o.parameters.get("charset")))}return i==="failure"&&(i="UTF-8"),Fho(e,i)}case"ArrayBuffer":return gWr(e).buffer;case"BinaryString":{let i="",o=new hWr("latin1");for(let s of e)i+=o.write(s);return i+=o.end(),i}}}function Fho(e,t){let r=gWr(e),n=Uho(r),i=0;n!==null&&(t=n,i=n==="UTF-8"?3:2);let o=r.slice(i);return new TextDecoder(t).decode(o)}function Uho(e){let[t,r,n]=e;return t===239&&r===187&&n===191?"UTF-8":t===254&&r===255?"UTF-16BE":t===255&&r===254?"UTF-16LE":null}function gWr(e){let t=e.reduce((n,i)=>n+i.byteLength,0),r=0;return e.reduce((n,i)=>(n.set(i,r),r+=i.byteLength,n),new Uint8Array(t))}wWr.exports={staticPropertyDescriptors:Bho,readOperation:Dho,fireAProgressEvent:aT}});var IWr=Be((nUs,vWr)=>{"use strict";var{staticPropertyDescriptors:E3,readOperation:Lxe,fireAProgressEvent:AWr}=yWr(),{kState:JO,kError:bWr,kResult:Fxe,kEvents:ei,kAborted:jho}=zft(),{webidl:Vi}=Cd(),{kEnumerableProperty:Lf}=qr(),$y=class e extends EventTarget{constructor(){super(),this[JO]="empty",this[Fxe]=null,this[bWr]=null,this[ei]={loadend:null,error:null,abort:null,load:null,progress:null,loadstart:null}}readAsArrayBuffer(t){Vi.brandCheck(this,e),Vi.argumentLengthCheck(arguments,1,"FileReader.readAsArrayBuffer"),t=Vi.converters.Blob(t,{strict:!1}),Lxe(this,t,"ArrayBuffer")}readAsBinaryString(t){Vi.brandCheck(this,e),Vi.argumentLengthCheck(arguments,1,"FileReader.readAsBinaryString"),t=Vi.converters.Blob(t,{strict:!1}),Lxe(this,t,"BinaryString")}readAsText(t,r=void 0){Vi.brandCheck(this,e),Vi.argumentLengthCheck(arguments,1,"FileReader.readAsText"),t=Vi.converters.Blob(t,{strict:!1}),r!==void 0&&(r=Vi.converters.DOMString(r,"FileReader.readAsText","encoding")),Lxe(this,t,"Text",r)}readAsDataURL(t){Vi.brandCheck(this,e),Vi.argumentLengthCheck(arguments,1,"FileReader.readAsDataURL"),t=Vi.converters.Blob(t,{strict:!1}),Lxe(this,t,"DataURL")}abort(){if(this[JO]==="empty"||this[JO]==="done"){this[Fxe]=null;return}this[JO]==="loading"&&(this[JO]="done",this[Fxe]=null),this[jho]=!0,AWr("abort",this),this[JO]!=="loading"&&AWr("loadend",this)}get readyState(){switch(Vi.brandCheck(this,e),this[JO]){case"empty":return this.EMPTY;case"loading":return this.LOADING;case"done":return this.DONE}}get result(){return Vi.brandCheck(this,e),this[Fxe]}get error(){return Vi.brandCheck(this,e),this[bWr]}get onloadend(){return Vi.brandCheck(this,e),this[ei].loadend}set onloadend(t){Vi.brandCheck(this,e),this[ei].loadend&&this.removeEventListener("loadend",this[ei].loadend),typeof t=="function"?(this[ei].loadend=t,this.addEventListener("loadend",t)):this[ei].loadend=null}get onerror(){return Vi.brandCheck(this,e),this[ei].error}set onerror(t){Vi.brandCheck(this,e),this[ei].error&&this.removeEventListener("error",this[ei].error),typeof t=="function"?(this[ei].error=t,this.addEventListener("error",t)):this[ei].error=null}get onloadstart(){return Vi.brandCheck(this,e),this[ei].loadstart}set onloadstart(t){Vi.brandCheck(this,e),this[ei].loadstart&&this.removeEventListener("loadstart",this[ei].loadstart),typeof t=="function"?(this[ei].loadstart=t,this.addEventListener("loadstart",t)):this[ei].loadstart=null}get onprogress(){return Vi.brandCheck(this,e),this[ei].progress}set onprogress(t){Vi.brandCheck(this,e),this[ei].progress&&this.removeEventListener("progress",this[ei].progress),typeof t=="function"?(this[ei].progress=t,this.addEventListener("progress",t)):this[ei].progress=null}get onload(){return Vi.brandCheck(this,e),this[ei].load}set onload(t){Vi.brandCheck(this,e),this[ei].load&&this.removeEventListener("load",this[ei].load),typeof t=="function"?(this[ei].load=t,this.addEventListener("load",t)):this[ei].load=null}get onabort(){return Vi.brandCheck(this,e),this[ei].abort}set onabort(t){Vi.brandCheck(this,e),this[ei].abort&&this.removeEventListener("abort",this[ei].abort),typeof t=="function"?(this[ei].abort=t,this.addEventListener("abort",t)):this[ei].abort=null}};$y.EMPTY=$y.prototype.EMPTY=0;$y.LOADING=$y.prototype.LOADING=1;$y.DONE=$y.prototype.DONE=2;Object.defineProperties($y.prototype,{EMPTY:E3,LOADING:E3,DONE:E3,readAsArrayBuffer:Lf,readAsBinaryString:Lf,readAsText:Lf,readAsDataURL:Lf,abort:Lf,readyState:Lf,result:Lf,error:Lf,onloadstart:Lf,onprogress:Lf,onload:Lf,onabort:Lf,onerror:Lf,onloadend:Lf,[Symbol.toStringTag]:{value:"FileReader",writable:!1,enumerable:!1,configurable:!0}});Object.defineProperties($y,{EMPTY:E3,LOADING:E3,DONE:E3});vWr.exports={FileReader:$y}});var Uxe=Be((iUs,kWr)=>{"use strict";kWr.exports={kConstruct:Ts().kConstruct}});var xWr=Be((oUs,SWr)=>{"use strict";var qho=Re("node:assert"),{URLSerializer:EWr}=Nf(),{isValidHeaderName:Qho}=Kh();function Hho(e,t,r=!1){let n=EWr(e,r),i=EWr(t,r);return n===i}function Who(e){qho(e!==null);let t=[];for(let r of e.split(","))r=r.trim(),Qho(r)&&t.push(r);return t}SWr.exports={urlEquals:Hho,getFieldValues:Who}});var RWr=Be((sUs,TWr)=>{"use strict";var{kConstruct:Gho}=Uxe(),{urlEquals:Vho,getFieldValues:Yft}=xWr(),{kEnumerableProperty:KO,isDisturbed:zho}=qr(),{webidl:Mt}=Cd(),{Response:Xho,cloneResponse:Jho,fromInnerResponse:Kho}=cZ(),{Request:AE,fromInnerRequest:Yho}=I3(),{kState:Oy}=zC(),{fetching:Zho}=uZ(),{urlIsHttpHttpsScheme:jxe,createDeferredPromise:S3,readAllBytes:emo}=Kh(),Zft=Re("node:assert"),qxe=class e{#e;constructor(){arguments[0]!==Gho&&Mt.illegalConstructor(),Mt.util.markAsUncloneable(this),this.#e=arguments[1]}async match(t,r={}){Mt.brandCheck(this,e);let n="Cache.match";Mt.argumentLengthCheck(arguments,1,n),t=Mt.converters.RequestInfo(t,n,"request"),r=Mt.converters.CacheQueryOptions(r,n,"options");let i=this.#o(t,r,1);if(i.length!==0)return i[0]}async matchAll(t=void 0,r={}){Mt.brandCheck(this,e);let n="Cache.matchAll";return t!==void 0&&(t=Mt.converters.RequestInfo(t,n,"request")),r=Mt.converters.CacheQueryOptions(r,n,"options"),this.#o(t,r)}async add(t){Mt.brandCheck(this,e);let r="Cache.add";Mt.argumentLengthCheck(arguments,1,r),t=Mt.converters.RequestInfo(t,r,"request");let n=[t];return await this.addAll(n)}async addAll(t){Mt.brandCheck(this,e);let r="Cache.addAll";Mt.argumentLengthCheck(arguments,1,r);let n=[],i=[];for(let p of t){if(p===void 0)throw Mt.errors.conversionFailed({prefix:r,argument:"Argument 1",types:["undefined is not allowed"]});if(p=Mt.converters.RequestInfo(p),typeof p=="string")continue;let f=p[Oy];if(!jxe(f.url)||f.method!=="GET")throw Mt.errors.exception({header:r,message:"Expected http/s scheme when method is not GET."})}let o=[];for(let p of t){let f=new AE(p)[Oy];if(!jxe(f.url))throw Mt.errors.exception({header:r,message:"Expected http/s scheme."});f.initiator="fetch",f.destination="subresource",i.push(f);let h=S3();o.push(Zho({request:f,processResponse(m){if(m.type==="error"||m.status===206||m.status<200||m.status>299)h.reject(Mt.errors.exception({header:"Cache.addAll",message:"Received an invalid status code or the request failed."}));else if(m.headersList.contains("vary")){let g=Yft(m.headersList.get("vary"));for(let w of g)if(w==="*"){h.reject(Mt.errors.exception({header:"Cache.addAll",message:"invalid vary field value"}));for(let y of o)y.abort();return}}},processResponseEndOfBody(m){if(m.aborted){h.reject(new DOMException("aborted","AbortError"));return}h.resolve(m)}})),n.push(h.promise)}let a=await Promise.all(n),l=[],c=0;for(let p of a){let f={type:"put",request:i[c],response:p};l.push(f),c++}let d=S3(),u=null;try{this.#r(l)}catch(p){u=p}return queueMicrotask(()=>{u===null?d.resolve(void 0):d.reject(u)}),d.promise}async put(t,r){Mt.brandCheck(this,e);let n="Cache.put";Mt.argumentLengthCheck(arguments,2,n),t=Mt.converters.RequestInfo(t,n,"request"),r=Mt.converters.Response(r,n,"response");let i=null;if(t instanceof AE?i=t[Oy]:i=new AE(t)[Oy],!jxe(i.url)||i.method!=="GET")throw Mt.errors.exception({header:n,message:"Expected an http/s scheme when method is not GET"});let o=r[Oy];if(o.status===206)throw Mt.errors.exception({header:n,message:"Got 206 status"});if(o.headersList.contains("vary")){let f=Yft(o.headersList.get("vary"));for(let h of f)if(h==="*")throw Mt.errors.exception({header:n,message:"Got * vary field value"})}if(o.body&&(zho(o.body.stream)||o.body.stream.locked))throw Mt.errors.exception({header:n,message:"Response body is locked or disturbed"});let s=Jho(o),a=S3();if(o.body!=null){let h=o.body.stream.getReader();emo(h).then(a.resolve,a.reject)}else a.resolve(void 0);let l=[],c={type:"put",request:i,response:s};l.push(c);let d=await a.promise;s.body!=null&&(s.body.source=d);let u=S3(),p=null;try{this.#r(l)}catch(f){p=f}return queueMicrotask(()=>{p===null?u.resolve():u.reject(p)}),u.promise}async delete(t,r={}){Mt.brandCheck(this,e);let n="Cache.delete";Mt.argumentLengthCheck(arguments,1,n),t=Mt.converters.RequestInfo(t,n,"request"),r=Mt.converters.CacheQueryOptions(r,n,"options");let i=null;if(t instanceof AE){if(i=t[Oy],i.method!=="GET"&&!r.ignoreMethod)return!1}else Zft(typeof t=="string"),i=new AE(t)[Oy];let o=[],s={type:"delete",request:i,options:r};o.push(s);let a=S3(),l=null,c;try{c=this.#r(o)}catch(d){l=d}return queueMicrotask(()=>{l===null?a.resolve(!!c?.length):a.reject(l)}),a.promise}async keys(t=void 0,r={}){Mt.brandCheck(this,e);let n="Cache.keys";t!==void 0&&(t=Mt.converters.RequestInfo(t,n,"request")),r=Mt.converters.CacheQueryOptions(r,n,"options");let i=null;if(t!==void 0)if(t instanceof AE){if(i=t[Oy],i.method!=="GET"&&!r.ignoreMethod)return[]}else typeof t=="string"&&(i=new AE(t)[Oy]);let o=S3(),s=[];if(t===void 0)for(let a of this.#e)s.push(a[0]);else{let a=this.#n(i,r);for(let l of a)s.push(l[0])}return queueMicrotask(()=>{let a=[];for(let l of s){let c=Yho(l,new AbortController().signal,"immutable");a.push(c)}o.resolve(Object.freeze(a))}),o.promise}#r(t){let r=this.#e,n=[...r],i=[],o=[];try{for(let s of t){if(s.type!=="delete"&&s.type!=="put")throw Mt.errors.exception({header:"Cache.#batchCacheOperations",message:'operation type does not match "delete" or "put"'});if(s.type==="delete"&&s.response!=null)throw Mt.errors.exception({header:"Cache.#batchCacheOperations",message:"delete operation should not have an associated response"});if(this.#n(s.request,s.options,i).length)throw new DOMException("???","InvalidStateError");let a;if(s.type==="delete"){if(a=this.#n(s.request,s.options),a.length===0)return[];for(let l of a){let c=r.indexOf(l);Zft(c!==-1),r.splice(c,1)}}else if(s.type==="put"){if(s.response==null)throw Mt.errors.exception({header:"Cache.#batchCacheOperations",message:"put operation should have an associated response"});let l=s.request;if(!jxe(l.url))throw Mt.errors.exception({header:"Cache.#batchCacheOperations",message:"expected http or https scheme"});if(l.method!=="GET")throw Mt.errors.exception({header:"Cache.#batchCacheOperations",message:"not get method"});if(s.options!=null)throw Mt.errors.exception({header:"Cache.#batchCacheOperations",message:"options must not be defined"});a=this.#n(s.request);for(let c of a){let d=r.indexOf(c);Zft(d!==-1),r.splice(d,1)}r.push([s.request,s.response]),i.push([s.request,s.response])}o.push([s.request,s.response])}return o}catch(s){throw this.#e.length=0,this.#e=n,s}}#n(t,r,n){let i=[],o=n??this.#e;for(let s of o){let[a,l]=s;this.#i(t,a,l,r)&&i.push(s)}return i}#i(t,r,n=null,i){let o=new URL(t.url),s=new URL(r.url);if(i?.ignoreSearch&&(s.search="",o.search=""),!Vho(o,s,!0))return!1;if(n==null||i?.ignoreVary||!n.headersList.contains("vary"))return!0;let a=Yft(n.headersList.get("vary"));for(let l of a){if(l==="*")return!1;let c=r.headersList.get(l),d=t.headersList.get(l);if(c!==d)return!1}return!0}#o(t,r,n=1/0){let i=null;if(t!==void 0)if(t instanceof AE){if(i=t[Oy],i.method!=="GET"&&!r.ignoreMethod)return[]}else typeof t=="string"&&(i=new AE(t)[Oy]);let o=[];if(t===void 0)for(let a of this.#e)o.push(a[1]);else{let a=this.#n(i,r);for(let l of a)o.push(l[1])}let s=[];for(let a of o){let l=Kho(a,"immutable");if(s.push(l.clone()),s.length>=n)break}return Object.freeze(s)}};Object.defineProperties(qxe.prototype,{[Symbol.toStringTag]:{value:"Cache",configurable:!0},match:KO,matchAll:KO,add:KO,addAll:KO,put:KO,delete:KO,keys:KO});var CWr=[{key:"ignoreSearch",converter:Mt.converters.boolean,defaultValue:()=>!1},{key:"ignoreMethod",converter:Mt.converters.boolean,defaultValue:()=>!1},{key:"ignoreVary",converter:Mt.converters.boolean,defaultValue:()=>!1}];Mt.converters.CacheQueryOptions=Mt.dictionaryConverter(CWr);Mt.converters.MultiCacheQueryOptions=Mt.dictionaryConverter([...CWr,{key:"cacheName",converter:Mt.converters.DOMString}]);Mt.converters.Response=Mt.interfaceConverter(Xho);Mt.converters["sequence<RequestInfo>"]=Mt.sequenceConverter(Mt.converters.RequestInfo);TWr.exports={Cache:qxe}});var PWr=Be((aUs,_Wr)=>{"use strict";var{kConstruct:fZ}=Uxe(),{Cache:Qxe}=RWr(),{webidl:uu}=Cd(),{kEnumerableProperty:hZ}=qr(),Hxe=class e{#e=new Map;constructor(){arguments[0]!==fZ&&uu.illegalConstructor(),uu.util.markAsUncloneable(this)}async match(t,r={}){if(uu.brandCheck(this,e),uu.argumentLengthCheck(arguments,1,"CacheStorage.match"),t=uu.converters.RequestInfo(t),r=uu.converters.MultiCacheQueryOptions(r),r.cacheName!=null){if(this.#e.has(r.cacheName)){let n=this.#e.get(r.cacheName);return await new Qxe(fZ,n).match(t,r)}}else for(let n of this.#e.values()){let o=await new Qxe(fZ,n).match(t,r);if(o!==void 0)return o}}async has(t){uu.brandCheck(this,e);let r="CacheStorage.has";return uu.argumentLengthCheck(arguments,1,r),t=uu.converters.DOMString(t,r,"cacheName"),this.#e.has(t)}async open(t){uu.brandCheck(this,e);let r="CacheStorage.open";if(uu.argumentLengthCheck(arguments,1,r),t=uu.converters.DOMString(t,r,"cacheName"),this.#e.has(t)){let i=this.#e.get(t);return new Qxe(fZ,i)}let n=[];return this.#e.set(t,n),new Qxe(fZ,n)}async delete(t){uu.brandCheck(this,e);let r="CacheStorage.delete";return uu.argumentLengthCheck(arguments,1,r),t=uu.converters.DOMString(t,r,"cacheName"),this.#e.delete(t)}async keys(){return uu.brandCheck(this,e),[...this.#e.keys()]}};Object.defineProperties(Hxe.prototype,{[Symbol.toStringTag]:{value:"CacheStorage",configurable:!0},match:hZ,has:hZ,open:hZ,delete:hZ,keys:hZ});_Wr.exports={CacheStorage:Hxe}});var OWr=Be((lUs,$Wr)=>{"use strict";$Wr.exports={maxAttributeValueSize:1024,maxNameValuePairSize:4096}});var rht=Be((cUs,DWr)=>{"use strict";function tmo(e){for(let t=0;t<e.length;++t){let r=e.charCodeAt(t);if(r>=0&&r<=8||r>=10&&r<=31||r===127)return!0}return!1}function eht(e){for(let t=0;t<e.length;++t){let r=e.charCodeAt(t);if(r<33||r>126||r===34||r===40||r===41||r===60||r===62||r===64||r===44||r===59||r===58||r===92||r===47||r===91||r===93||r===63||r===61||r===123||r===125)throw new Error("Invalid cookie name")}}function tht(e){let t=e.length,r=0;if(e[0]==='"'){if(t===1||e[t-1]!=='"')throw new Error("Invalid cookie value");--t,++r}for(;r<t;){let n=e.charCodeAt(r++);if(n<33||n>126||n===34||n===44||n===59||n===92)throw new Error("Invalid cookie value")}}function NWr(e){for(let t=0;t<e.length;++t){let r=e.charCodeAt(t);if(r<32||r>126||r===59)throw new Error("Invalid cookie path")}}function MWr(e){return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122}function rmo(e){if(e===" ")return;if(e.length>255)throw new Error("Invalid cookie domain");let t=0;for(let r=0;r<e.length;++r){let n=e.charCodeAt(r);if(n===46){if(t===0)throw new Error("Invalid cookie domain");if(e.charCodeAt(r-1)===45)throw new Error("Invalid cookie domain");t=0;continue}if(t===0&&!MWr(n))throw new Error("Invalid cookie domain");if(!MWr(n)&&n!==45)throw new Error("Invalid cookie domain");if(++t>63)throw new Error("Invalid cookie domain")}if(t===0||e.charCodeAt(e.length-1)===45)throw new Error("Invalid cookie domain")}var nmo=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],imo=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Wxe=Array(61).fill(0).map((e,t)=>t.toString().padStart(2,"0"));function BWr(e){return typeof e=="number"&&(e=new Date(e)),`${nmo[e.getUTCDay()]}, ${Wxe[e.getUTCDate()]} ${imo[e.getUTCMonth()]} ${e.getUTCFullYear()} ${Wxe[e.getUTCHours()]}:${Wxe[e.getUTCMinutes()]}:${Wxe[e.getUTCSeconds()]} GMT`}function omo(e){if(e<0)throw new Error("Invalid cookie max-age")}function smo(e){if(e.name.length===0)return null;eht(e.name),tht(e.value);let t=[`${e.name}=${e.value}`];e.name.startsWith("__Secure-")&&(e.secure=!0),e.name.startsWith("__Host-")&&(e.secure=!0,e.domain=null,e.path="/"),e.secure&&t.push("Secure"),e.httpOnly&&t.push("HttpOnly"),typeof e.maxAge=="number"&&(omo(e.maxAge),t.push(`Max-Age=${e.maxAge}`)),e.domain&&(rmo(e.domain),t.push(`Domain=${e.domain}`)),e.path&&(NWr(e.path),t.push(`Path=${e.path}`)),e.expires&&e.expires.toString()!=="Invalid Date"&&t.push(`Expires=${BWr(e.expires)}`),e.sameSite&&t.push(`SameSite=${e.sameSite}`);for(let r of e.unparsed){if(!r.includes("="))throw new Error("Invalid unparsed");let[n,...i]=r.split("="),o=n.trim(),s=i.join("=");eht(o),tht(s),t.push(`${o}=${s}`)}return t.join("; ")}DWr.exports={isCTLExcludingHtab:tmo,validateCookieName:eht,validateCookiePath:NWr,validateCookieValue:tht,toIMFDate:BWr,stringify:smo}});var FWr=Be((dUs,LWr)=>{"use strict";var{maxNameValuePairSize:amo,maxAttributeValueSize:lmo}=OWr(),{isCTLExcludingHtab:cmo}=rht(),{collectASequenceOfCodePointsFast:Gxe}=Nf(),dmo=Re("node:assert");function umo(e){if(cmo(e))return null;let t="",r="",n="",i="";if(e.includes(";")){let o={position:0};t=Gxe(";",e,o),r=e.slice(o.position)}else t=e;if(!t.includes("="))i=t;else{let o={position:0};n=Gxe("=",t,o),i=t.slice(o.position+1)}return n=n.trim(),i=i.trim(),n.length+i.length>amo?null:{name:n,value:i,...x3(r)}}function x3(e,t={}){if(e.length===0)return t;dmo(e[0]===";"),e=e.slice(1);let r="";e.includes(";")?(r=Gxe(";",e,{position:0}),e=e.slice(r.length)):(r=e,e="");let n="",i="";if(r.includes("=")){let s={position:0};n=Gxe("=",r,s),i=r.slice(s.position+1)}else n=r;if(n=n.trim(),i=i.trim(),i.length>lmo)return x3(e,t);let o=n.toLowerCase();if(o==="expires"){let s=new Date(i);t.expires=s}else if(o==="max-age"){let s=i.charCodeAt(0);if((s<48||s>57)&&i[0]!=="-"||!/^\d+$/.test(i))return x3(e,t);let a=Number(i);t.maxAge=a}else if(o==="domain"){let s=i;s[0]==="."&&(s=s.slice(1)),s=s.toLowerCase(),t.domain=s}else if(o==="path"){let s="";i.length===0||i[0]!=="/"?s="/":s=i,t.path=s}else if(o==="secure")t.secure=!0;else if(o==="httponly")t.httpOnly=!0;else if(o==="samesite"){let s=i.toLowerCase();s==="none"?t.sameSite="None":s==="strict"?t.sameSite="Strict":s==="lax"&&(t.sameSite="Lax")}else t.unparsed??=[],t.unparsed.push(`${n}=${i}`);return x3(e,t)}LWr.exports={parseSetCookie:umo,parseUnparsedAttributes:x3}});var qWr=Be((uUs,jWr)=>{"use strict";var{parseSetCookie:pmo}=FWr(),{stringify:fmo}=rht(),{webidl:ln}=Cd(),{Headers:Vxe}=GO();function hmo(e){ln.argumentLengthCheck(arguments,1,"getCookies"),ln.brandCheck(e,Vxe,{strict:!1});let t=e.get("cookie"),r={};if(!t)return r;for(let n of t.split(";")){let[i,...o]=n.split("=");r[i.trim()]=o.join("=")}return r}function mmo(e,t,r){ln.brandCheck(e,Vxe,{strict:!1});let n="deleteCookie";ln.argumentLengthCheck(arguments,2,n),t=ln.converters.DOMString(t,n,"name"),r=ln.converters.DeleteCookieAttributes(r),UWr(e,{name:t,value:"",expires:new Date(0),...r})}function gmo(e){ln.argumentLengthCheck(arguments,1,"getSetCookies"),ln.brandCheck(e,Vxe,{strict:!1});let t=e.getSetCookie();return t?t.map(r=>pmo(r)):[]}function UWr(e,t){ln.argumentLengthCheck(arguments,2,"setCookie"),ln.brandCheck(e,Vxe,{strict:!1}),t=ln.converters.Cookie(t);let r=fmo(t);r&&e.append("Set-Cookie",r)}ln.converters.DeleteCookieAttributes=ln.dictionaryConverter([{converter:ln.nullableConverter(ln.converters.DOMString),key:"path",defaultValue:()=>null},{converter:ln.nullableConverter(ln.converters.DOMString),key:"domain",defaultValue:()=>null}]);ln.converters.Cookie=ln.dictionaryConverter([{converter:ln.converters.DOMString,key:"name"},{converter:ln.converters.DOMString,key:"value"},{converter:ln.nullableConverter(e=>typeof e=="number"?ln.converters["unsigned long long"](e):new Date(e)),key:"expires",defaultValue:()=>null},{converter:ln.nullableConverter(ln.converters["long long"]),key:"maxAge",defaultValue:()=>null},{converter:ln.nullableConverter(ln.converters.DOMString),key:"domain",defaultValue:()=>null},{converter:ln.nullableConverter(ln.converters.DOMString),key:"path",defaultValue:()=>null},{converter:ln.nullableConverter(ln.converters.boolean),key:"secure",defaultValue:()=>null},{converter:ln.nullableConverter(ln.converters.boolean),key:"httpOnly",defaultValue:()=>null},{converter:ln.converters.USVString,key:"sameSite",allowedValues:["Strict","Lax","None"]},{converter:ln.sequenceConverter(ln.converters.DOMString),key:"unparsed",defaultValue:()=>new Array(0)}]);jWr.exports={getCookies:hmo,deleteCookie:mmo,getSetCookies:gmo,setCookie:UWr}});var T3=Be((pUs,HWr)=>{"use strict";var{webidl:Ct}=Cd(),{kEnumerableProperty:Ff}=qr(),{kConstruct:QWr}=Ts(),{MessagePort:wmo}=Re("node:worker_threads"),C3=class e extends Event{#e;constructor(t,r={}){if(t===QWr){super(arguments[1],arguments[2]),Ct.util.markAsUncloneable(this);return}let n="MessageEvent constructor";Ct.argumentLengthCheck(arguments,1,n),t=Ct.converters.DOMString(t,n,"type"),r=Ct.converters.MessageEventInit(r,n,"eventInitDict"),super(t,r),this.#e=r,Ct.util.markAsUncloneable(this)}get data(){return Ct.brandCheck(this,e),this.#e.data}get origin(){return Ct.brandCheck(this,e),this.#e.origin}get lastEventId(){return Ct.brandCheck(this,e),this.#e.lastEventId}get source(){return Ct.brandCheck(this,e),this.#e.source}get ports(){return Ct.brandCheck(this,e),Object.isFrozen(this.#e.ports)||Object.freeze(this.#e.ports),this.#e.ports}initMessageEvent(t,r=!1,n=!1,i=null,o="",s="",a=null,l=[]){return Ct.brandCheck(this,e),Ct.argumentLengthCheck(arguments,1,"MessageEvent.initMessageEvent"),new e(t,{bubbles:r,cancelable:n,data:i,origin:o,lastEventId:s,source:a,ports:l})}static createFastMessageEvent(t,r){let n=new e(QWr,t,r);return n.#e=r,n.#e.data??=null,n.#e.origin??="",n.#e.lastEventId??="",n.#e.source??=null,n.#e.ports??=[],n}},{createFastMessageEvent:ymo}=C3;delete C3.createFastMessageEvent;var zxe=class e extends Event{#e;constructor(t,r={}){let n="CloseEvent constructor";Ct.argumentLengthCheck(arguments,1,n),t=Ct.converters.DOMString(t,n,"type"),r=Ct.converters.CloseEventInit(r),super(t,r),this.#e=r,Ct.util.markAsUncloneable(this)}get wasClean(){return Ct.brandCheck(this,e),this.#e.wasClean}get code(){return Ct.brandCheck(this,e),this.#e.code}get reason(){return Ct.brandCheck(this,e),this.#e.reason}},Xxe=class e extends Event{#e;constructor(t,r){let n="ErrorEvent constructor";Ct.argumentLengthCheck(arguments,1,n),super(t,r),Ct.util.markAsUncloneable(this),t=Ct.converters.DOMString(t,n,"type"),r=Ct.converters.ErrorEventInit(r??{}),this.#e=r}get message(){return Ct.brandCheck(this,e),this.#e.message}get filename(){return Ct.brandCheck(this,e),this.#e.filename}get lineno(){return Ct.brandCheck(this,e),this.#e.lineno}get colno(){return Ct.brandCheck(this,e),this.#e.colno}get error(){return Ct.brandCheck(this,e),this.#e.error}};Object.defineProperties(C3.prototype,{[Symbol.toStringTag]:{value:"MessageEvent",configurable:!0},data:Ff,origin:Ff,lastEventId:Ff,source:Ff,ports:Ff,initMessageEvent:Ff});Object.defineProperties(zxe.prototype,{[Symbol.toStringTag]:{value:"CloseEvent",configurable:!0},reason:Ff,code:Ff,wasClean:Ff});Object.defineProperties(Xxe.prototype,{[Symbol.toStringTag]:{value:"ErrorEvent",configurable:!0},message:Ff,filename:Ff,lineno:Ff,colno:Ff,error:Ff});Ct.converters.MessagePort=Ct.interfaceConverter(wmo);Ct.converters["sequence<MessagePort>"]=Ct.sequenceConverter(Ct.converters.MessagePort);var nht=[{key:"bubbles",converter:Ct.converters.boolean,defaultValue:()=>!1},{key:"cancelable",converter:Ct.converters.boolean,defaultValue:()=>!1},{key:"composed",converter:Ct.converters.boolean,defaultValue:()=>!1}];Ct.converters.MessageEventInit=Ct.dictionaryConverter([...nht,{key:"data",converter:Ct.converters.any,defaultValue:()=>null},{key:"origin",converter:Ct.converters.USVString,defaultValue:()=>""},{key:"lastEventId",converter:Ct.converters.DOMString,defaultValue:()=>""},{key:"source",converter:Ct.nullableConverter(Ct.converters.MessagePort),defaultValue:()=>null},{key:"ports",converter:Ct.converters["sequence<MessagePort>"],defaultValue:()=>new Array(0)}]);Ct.converters.CloseEventInit=Ct.dictionaryConverter([...nht,{key:"wasClean",converter:Ct.converters.boolean,defaultValue:()=>!1},{key:"code",converter:Ct.converters["unsigned short"],defaultValue:()=>0},{key:"reason",converter:Ct.converters.USVString,defaultValue:()=>""}]);Ct.converters.ErrorEventInit=Ct.dictionaryConverter([...nht,{key:"message",converter:Ct.converters.DOMString,defaultValue:()=>""},{key:"filename",converter:Ct.converters.USVString,defaultValue:()=>""},{key:"lineno",converter:Ct.converters["unsigned long"],defaultValue:()=>0},{key:"colno",converter:Ct.converters["unsigned long"],defaultValue:()=>0},{key:"error",converter:Ct.converters.any}]);HWr.exports={MessageEvent:C3,CloseEvent:zxe,ErrorEvent:Xxe,createFastMessageEvent:ymo}});var YO=Be((fUs,WWr)=>{"use strict";var Amo="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",bmo={enumerable:!0,writable:!1,configurable:!1},vmo={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3},Imo={NOT_SENT:0,PROCESSING:1,SENT:2},kmo={CONTINUATION:0,TEXT:1,BINARY:2,CLOSE:8,PING:9,PONG:10},Emo=2**16-1,Smo={INFO:0,PAYLOADLENGTH_16:2,PAYLOADLENGTH_64:3,READ_DATA:4},xmo=Buffer.allocUnsafe(0),Cmo={string:1,typedArray:2,arrayBuffer:3,blob:4};WWr.exports={uid:Amo,sentCloseFrameState:Imo,staticPropertyDescriptors:bmo,states:vmo,opcodes:kmo,maxUnsigned16Bit:Emo,parserStates:Smo,emptyBuffer:xmo,sendHints:Cmo}});var mZ=Be((hUs,GWr)=>{"use strict";GWr.exports={kWebSocketURL:Symbol("url"),kReadyState:Symbol("ready state"),kController:Symbol("controller"),kResponse:Symbol("response"),kBinaryType:Symbol("binary type"),kSentClose:Symbol("sent close"),kReceivedClose:Symbol("received close"),kByteParser:Symbol("byte parser")}});var yZ=Be((mUs,t6r)=>{"use strict";var{kReadyState:gZ,kController:Tmo,kResponse:Rmo,kBinaryType:_mo,kWebSocketURL:Pmo}=mZ(),{states:wZ,opcodes:lT}=YO(),{ErrorEvent:$mo,createFastMessageEvent:Omo}=T3(),{isUtf8:Mmo}=Re("node:buffer"),{collectASequenceOfCodePointsFast:Nmo,removeHTTPWhitespace:VWr}=Nf();function Bmo(e){return e[gZ]===wZ.CONNECTING}function Dmo(e){return e[gZ]===wZ.OPEN}function Lmo(e){return e[gZ]===wZ.CLOSING}function Fmo(e){return e[gZ]===wZ.CLOSED}function iht(e,t,r=(i,o)=>new Event(i,o),n={}){let i=r(e,n);t.dispatchEvent(i)}function Umo(e,t,r){if(e[gZ]!==wZ.OPEN)return;let n;if(t===lT.TEXT)try{n=e6r(r)}catch{XWr(e,"Received invalid UTF-8 in text frame.");return}else t===lT.BINARY&&(e[_mo]==="blob"?n=new Blob([r]):n=jmo(r));iht("message",e,Omo,{origin:e[Pmo].origin,data:n})}function jmo(e){return e.byteLength===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}function qmo(e){if(e.length===0)return!1;for(let t=0;t<e.length;++t){let r=e.charCodeAt(t);if(r<33||r>126||r===34||r===40||r===41||r===44||r===47||r===58||r===59||r===60||r===61||r===62||r===63||r===64||r===91||r===92||r===93||r===123||r===125)return!1}return!0}function Qmo(e){return e>=1e3&&e<1015?e!==1004&&e!==1005&&e!==1006:e>=3e3&&e<=4999}function XWr(e,t){let{[Tmo]:r,[Rmo]:n}=e;r.abort(),n?.socket&&!n.socket.destroyed&&n.socket.destroy(),t&&iht("error",e,(i,o)=>new $mo(i,o),{error:new Error(t),message:t})}function JWr(e){return e===lT.CLOSE||e===lT.PING||e===lT.PONG}function KWr(e){return e===lT.CONTINUATION}function YWr(e){return e===lT.TEXT||e===lT.BINARY}function Hmo(e){return YWr(e)||KWr(e)||JWr(e)}function Wmo(e){let t={position:0},r=new Map;for(;t.position<e.length;){let n=Nmo(";",e,t),[i,o=""]=n.split("=");r.set(VWr(i,!0,!1),VWr(o,!1,!0)),t.position++}return r}function Gmo(e){if(e.length===0)return!1;for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n<48||n>57)return!1}let t=Number.parseInt(e,10);return t>=8&&t<=15}var ZWr=typeof process.versions.icu=="string",zWr=ZWr?new TextDecoder("utf-8",{fatal:!0}):void 0,e6r=ZWr?zWr.decode.bind(zWr):function(e){if(Mmo(e))return e.toString("utf-8");throw new TypeError("Invalid utf-8 received.")};t6r.exports={isConnecting:Bmo,isEstablished:Dmo,isClosing:Lmo,isClosed:Fmo,fireEvent:iht,isValidSubprotocol:qmo,isValidStatusCode:Qmo,failWebsocketConnection:XWr,websocketMessageReceived:Umo,utf8Decode:e6r,isControlFrame:JWr,isContinuationFrame:KWr,isTextBinaryFrame:YWr,isValidOpcode:Hmo,parseExtensions:Wmo,isValidClientWindowBits:Gmo}});var Kxe=Be((gUs,r6r)=>{"use strict";var{maxUnsigned16Bit:Vmo}=YO(),Jxe=16386,oht,AZ=null,R3=Jxe;try{oht=Re("node:crypto")}catch{oht={randomFillSync:function(t,r,n){for(let i=0;i<t.length;++i)t[i]=Math.random()*255|0;return t}}}function zmo(){return R3===Jxe&&(R3=0,oht.randomFillSync(AZ??=Buffer.allocUnsafe(Jxe),0,Jxe)),[AZ[R3++],AZ[R3++],AZ[R3++],AZ[R3++]]}var sht=class{constructor(t){this.frameData=t}createFrame(t){let r=this.frameData,n=zmo(),i=r?.byteLength??0,o=i,s=6;i>Vmo?(s+=8,o=127):i>125&&(s+=2,o=126);let a=Buffer.allocUnsafe(i+s);a[0]=a[1]=0,a[0]|=128,a[0]=(a[0]&240)+t;a[s-4]=n[0],a[s-3]=n[1],a[s-2]=n[2],a[s-1]=n[3],a[1]=o,o===126?a.writeUInt16BE(i,2):o===127&&(a[2]=a[3]=0,a.writeUIntBE(i,4,6)),a[1]|=128;for(let l=0;l<i;++l)a[s+l]=r[l]^n[l&3];return a}};r6r.exports={WebsocketFrameSend:sht}});var lht=Be((wUs,c6r)=>{"use strict";var{uid:Xmo,states:bZ,sentCloseFrameState:Yxe,emptyBuffer:Jmo,opcodes:Kmo}=YO(),{kReadyState:vZ,kSentClose:Zxe,kByteParser:i6r,kReceivedClose:n6r,kResponse:o6r}=mZ(),{fireEvent:Ymo,failWebsocketConnection:cT,isClosing:Zmo,isClosed:ego,isEstablished:tgo,parseExtensions:rgo}=yZ(),{channels:_3}=q4(),{CloseEvent:ngo}=T3(),{makeRequest:igo}=I3(),{fetching:ogo}=uZ(),{Headers:sgo,getHeadersList:ago}=GO(),{getDecodeSplit:lgo}=Kh(),{WebsocketFrameSend:cgo}=Kxe(),aht;try{aht=Re("node:crypto")}catch{}function dgo(e,t,r,n,i,o){let s=e;s.protocol=e.protocol==="ws:"?"http:":"https:";let a=igo({urlList:[s],client:r,serviceWorkers:"none",referrer:"no-referrer",mode:"websocket",credentials:"include",cache:"no-store",redirect:"error"});if(o.headers){let u=ago(new sgo(o.headers));a.headersList=u}let l=aht.randomBytes(16).toString("base64");a.headersList.append("sec-websocket-key",l),a.headersList.append("sec-websocket-version","13");for(let u of t)a.headersList.append("sec-websocket-protocol",u);return a.headersList.append("sec-websocket-extensions","permessage-deflate; client_max_window_bits"),ogo({request:a,useParallelQueue:!0,dispatcher:o.dispatcher,processResponse(u){if(u.type==="error"||u.status!==101){cT(n,"Received network error or non-101 status code.");return}if(t.length!==0&&!u.headersList.get("Sec-WebSocket-Protocol")){cT(n,"Server did not respond with sent protocols.");return}if(u.headersList.get("Upgrade")?.toLowerCase()!=="websocket"){cT(n,'Server did not set Upgrade header to "websocket".');return}if(u.headersList.get("Connection")?.toLowerCase()!=="upgrade"){cT(n,'Server did not set Connection header to "upgrade".');return}let p=u.headersList.get("Sec-WebSocket-Accept"),f=aht.createHash("sha1").update(l+Xmo).digest("base64");if(p!==f){cT(n,"Incorrect hash received in Sec-WebSocket-Accept header.");return}let h=u.headersList.get("Sec-WebSocket-Extensions"),m;if(h!==null&&(m=rgo(h),!m.has("permessage-deflate"))){cT(n,"Sec-WebSocket-Extensions header does not match.");return}let g=u.headersList.get("Sec-WebSocket-Protocol");if(g!==null){let w=lgo("sec-websocket-protocol",a.headersList);if(w===null||!w.includes(g)){cT(n,"Protocol was not set in the opening handshake.");return}}u.socket.on("data",s6r),u.socket.on("close",a6r),u.socket.on("error",l6r),_3.open.hasSubscribers&&_3.open.publish({address:u.socket.address(),protocol:g,extensions:h}),i(u,m)}})}function ugo(e,t,r,n){if(!(Zmo(e)||ego(e)))if(!tgo(e))cT(e,"Connection was closed before it was established."),e[vZ]=bZ.CLOSING;else if(e[Zxe]===Yxe.NOT_SENT){e[Zxe]=Yxe.PROCESSING;let i=new cgo;t!==void 0&&r===void 0?(i.frameData=Buffer.allocUnsafe(2),i.frameData.writeUInt16BE(t,0)):t!==void 0&&r!==void 0?(i.frameData=Buffer.allocUnsafe(2+n),i.frameData.writeUInt16BE(t,0),i.frameData.write(r,2,"utf-8")):i.frameData=Jmo,e[o6r].socket.write(i.createFrame(Kmo.CLOSE)),e[Zxe]=Yxe.SENT,e[vZ]=bZ.CLOSING}else e[vZ]=bZ.CLOSING}function s6r(e){this.ws[i6r].write(e)||this.pause()}function a6r(){let{ws:e}=this,{[o6r]:t}=e;t.socket.off("data",s6r),t.socket.off("close",a6r),t.socket.off("error",l6r);let r=e[Zxe]===Yxe.SENT&&e[n6r],n=1005,i="",o=e[i6r].closingInfo;o&&!o.error?(n=o.code??1005,i=o.reason):e[n6r]||(n=1006),e[vZ]=bZ.CLOSED,Ymo("close",e,(s,a)=>new ngo(s,a),{wasClean:r,code:n,reason:i}),_3.close.hasSubscribers&&_3.close.publish({websocket:e,code:n,reason:i})}function l6r(e){let{ws:t}=this;t[vZ]=bZ.CLOSING,_3.socketError.hasSubscribers&&_3.socketError.publish(e),this.destroy()}c6r.exports={establishWebSocketConnection:dgo,closeWebSocketConnection:ugo}});var u6r=Be((yUs,d6r)=>{"use strict";var{createInflateRaw:pgo,Z_DEFAULT_WINDOWBITS:fgo}=Re("node:zlib"),{isValidClientWindowBits:hgo}=yZ(),{MessageSizeExceededError:mgo}=Ln(),ggo=Buffer.from([0,0,255,255]),eCe=Symbol("kBuffer"),IZ=Symbol("kLength"),cht=class{#e;#r={};#n=0;constructor(t,r){this.#r.serverNoContextTakeover=t.has("server_no_context_takeover"),this.#r.serverMaxWindowBits=t.get("server_max_window_bits"),this.#n=r.maxPayloadSize}decompress(t,r,n){if(!this.#e){let i=fgo;if(this.#r.serverMaxWindowBits){if(!hgo(this.#r.serverMaxWindowBits)){n(new Error("Invalid server_max_window_bits"));return}i=Number.parseInt(this.#r.serverMaxWindowBits)}try{this.#e=pgo({windowBits:i})}catch(o){n(o);return}this.#e[eCe]=[],this.#e[IZ]=0,this.#e.on("data",o=>{if(this.#e[IZ]+=o.length,this.#n>0&&this.#e[IZ]>this.#n){n(new mgo),this.#e.removeAllListeners(),this.#e.destroy(),this.#e=null;return}this.#e[eCe].push(o)}),this.#e.on("error",o=>{this.#e=null,n(o)})}this.#e.write(t),r&&this.#e.write(ggo),this.#e.flush(()=>{if(!this.#e)return;let i=Buffer.concat(this.#e[eCe],this.#e[IZ]);this.#e[eCe].length=0,this.#e[IZ]=0,n(null,i)})}};d6r.exports={PerMessageDeflate:cht}});var b6r=Be((AUs,A6r)=>{"use strict";var{Writable:wgo}=Re("node:stream"),ygo=Re("node:assert"),{parserStates:Uf,opcodes:P3,states:Ago,emptyBuffer:p6r,sentCloseFrameState:f6r}=YO(),{kReadyState:bgo,kSentClose:h6r,kResponse:dht,kReceivedClose:m6r}=mZ(),{channels:tCe}=q4(),{isValidStatusCode:vgo,isValidOpcode:Igo,failWebsocketConnection:om,websocketMessageReceived:g6r,utf8Decode:kgo,isControlFrame:uht,isTextBinaryFrame:pht,isContinuationFrame:Ego}=yZ(),{WebsocketFrameSend:w6r}=Kxe(),{closeWebSocketConnection:y6r}=lht(),{PerMessageDeflate:Sgo}=u6r(),{MessageSizeExceededError:fht}=Ln();function kZ(e,t,r){y6r(e,t,r,Buffer.byteLength(r)),om(e,r)}var hht=class extends wgo{#e=[];#r=0;#n=0;#i=!1;#o=Uf.INFO;#t={};#s=[];#a;#c;#l;constructor(t,r,n={}){super(),this.ws=t,this.#a=r??new Map,this.#c=n.maxFragments??0,this.#l=n.maxPayloadSize??0,this.#a.has("permessage-deflate")&&this.#a.set("permessage-deflate",new Sgo(r,n))}_write(t,r,n){this.#e.push(t),this.#n+=t.length,this.#i=!0,this.run(n)}#d(){return this.#l>0&&!uht(this.#t.opcode)&&this.#t.payloadLength+this.#r>this.#l?(kZ(this.ws,1009,"Payload size exceeds maximum allowed size"),!1):!0}run(t){for(;this.#i;)if(this.#o===Uf.INFO){if(this.#n<2)return t();let r=this.consume(2),n=(r[0]&128)!==0,i=r[0]&15,o=(r[1]&128)===128,s=!n&&i!==P3.CONTINUATION,a=r[1]&127,l=r[0]&64,c=r[0]&32,d=r[0]&16;if(!Igo(i))return om(this.ws,"Invalid opcode received"),t();if(o)return om(this.ws,"Frame cannot be masked"),t();if(l!==0&&!this.#a.has("permessage-deflate")){om(this.ws,"Expected RSV1 to be clear.");return}if(c!==0||d!==0){om(this.ws,"RSV1, RSV2, RSV3 must be clear");return}if(s&&!pht(i)){om(this.ws,"Invalid frame type was fragmented.");return}if(pht(i)&&this.#s.length>0){om(this.ws,"Expected continuation frame");return}if(this.#t.fragmented&&s){om(this.ws,"Fragmented frame exceeded 125 bytes.");return}if((a>125||s)&&uht(i)){om(this.ws,"Control frame either too large or fragmented");return}if(Ego(i)&&this.#s.length===0&&!this.#t.compressed){om(this.ws,"Unexpected continuation frame");return}if(a<=125){if(this.#t.payloadLength=a,this.#o=Uf.READ_DATA,!this.#d())return}else a===126?this.#o=Uf.PAYLOADLENGTH_16:a===127&&(this.#o=Uf.PAYLOADLENGTH_64);pht(i)&&(this.#t.binaryType=i,this.#t.compressed=l!==0),this.#t.opcode=i,this.#t.masked=o,this.#t.fin=n,this.#t.fragmented=s}else if(this.#o===Uf.PAYLOADLENGTH_16){if(this.#n<2)return t();let r=this.consume(2);if(this.#t.payloadLength=r.readUInt16BE(0),this.#o=Uf.READ_DATA,!this.#d())return}else if(this.#o===Uf.PAYLOADLENGTH_64){if(this.#n<8)return t();let r=this.consume(8),n=r.readUInt32BE(0),i=r.readUInt32BE(4);if(n!==0||i>2**31-1){om(this.ws,"Received payload length > 2^31 bytes.");return}if(this.#t.payloadLength=i,this.#o=Uf.READ_DATA,!this.#d())return}else if(this.#o===Uf.READ_DATA){if(this.#n<this.#t.payloadLength)return t();let r=this.consume(this.#t.payloadLength);if(uht(this.#t.opcode)){this.#i=this.parseControlFrame(r),this.#o=Uf.INFO;let n=this.ws[dht].socket;if(this.#i&&n.writableNeedDrain){this.#i=!1,n.once("drain",()=>{this.destroyed||(this.#i=!0,this.run(t))});return}}else if(this.#t.compressed){this.#a.get("permessage-deflate").decompress(r,this.#t.fin,(n,i)=>{if(n){let o=n instanceof fht?1009:1007;kZ(this.ws,o,n.message);return}if(this.writeFragments(i)){if(this.#l>0&&this.#r>this.#l){kZ(this.ws,1009,new fht().message);return}if(!this.#t.fin){this.#o=Uf.INFO,this.#i=!0,this.run(t);return}g6r(this.ws,this.#t.binaryType,this.consumeFragments()),this.#i=!0,this.#o=Uf.INFO,this.run(t)}}),this.#i=!1;break}else{if(!this.writeFragments(r))return;if(this.#l>0&&this.#r>this.#l){kZ(this.ws,1009,new fht().message);return}!this.#t.fragmented&&this.#t.fin&&g6r(this.ws,this.#t.binaryType,this.consumeFragments()),this.#o=Uf.INFO}}}consume(t){if(t>this.#n)throw new Error("Called consume() before buffers satiated.");if(t===0)return p6r;if(this.#e[0].length===t)return this.#n-=this.#e[0].length,this.#e.shift();let r=Buffer.allocUnsafe(t),n=0;for(;n!==t;){let i=this.#e[0],{length:o}=i;if(o+n===t){r.set(this.#e.shift(),n);break}else if(o+n>t){r.set(i.subarray(0,t-n),n),this.#e[0]=i.subarray(t-n);break}else r.set(this.#e.shift(),n),n+=i.length}return this.#n-=t,r}writeFragments(t){return this.#c>0&&this.#s.length===this.#c?(kZ(this.ws,1008,"Too many message fragments"),!1):(this.#r+=t.length,this.#s.push(t),!0)}consumeFragments(){let t=this.#s;if(t.length===1)return this.#r=0,t.shift();let r=Buffer.concat(t,this.#r);return this.#s=[],this.#r=0,r}parseCloseBody(t){ygo(t.length!==1);let r;if(t.length>=2&&(r=t.readUInt16BE(0)),r!==void 0&&!vgo(r))return{code:1002,reason:"Invalid status code",error:!0};let n=t.subarray(2);n[0]===239&&n[1]===187&&n[2]===191&&(n=n.subarray(3));try{n=kgo(n)}catch{return{code:1007,reason:"Invalid UTF-8",error:!0}}return{code:r,reason:n,error:!1}}parseControlFrame(t){let{opcode:r,payloadLength:n}=this.#t;if(r===P3.CLOSE){if(n===1)return om(this.ws,"Received close frame with a 1-byte body."),!1;if(this.#t.closeInfo=this.parseCloseBody(t),this.#t.closeInfo.error){let{code:i,reason:o}=this.#t.closeInfo;return y6r(this.ws,i,o,o.length),om(this.ws,o),!1}if(this.ws[h6r]!==f6r.SENT){let i=p6r;this.#t.closeInfo.code&&(i=Buffer.allocUnsafe(2),i.writeUInt16BE(this.#t.closeInfo.code,0));let o=new w6r(i);this.ws[dht].socket.write(o.createFrame(P3.CLOSE),s=>{s||(this.ws[h6r]=f6r.SENT)})}return this.ws[bgo]=Ago.CLOSING,this.ws[m6r]=!0,!1}else if(r===P3.PING){if(!this.ws[m6r]){let i=new w6r(t);this.ws[dht].socket.write(i.createFrame(P3.PONG)),tCe.ping.hasSubscribers&&tCe.ping.publish({payload:t})}}else r===P3.PONG&&tCe.pong.hasSubscribers&&tCe.pong.publish({payload:t});return!0}get closingInfo(){return this.#t.closeInfo}};A6r.exports={ByteParser:hht}});var S6r=Be((bUs,E6r)=>{"use strict";var{WebsocketFrameSend:xgo}=Kxe(),{opcodes:v6r,sendHints:$3}=YO(),Cgo=Apt(),I6r=Buffer[Symbol.species],mht=class{#e=new Cgo;#r=!1;#n;constructor(t){this.#n=t}add(t,r,n){if(n!==$3.blob){let o=k6r(t,n);if(!this.#r)this.#n.write(o,r);else{let s={promise:null,callback:r,frame:o};this.#e.push(s)}return}let i={promise:t.arrayBuffer().then(o=>{i.promise=null,i.frame=k6r(o,n)}),callback:r,frame:null};this.#e.push(i),this.#r||this.#i()}async#i(){this.#r=!0;let t=this.#e;for(;!t.isEmpty();){let r=t.shift();r.promise!==null&&await r.promise,this.#n.write(r.frame,r.callback),r.callback=r.frame=null}this.#r=!1}};function k6r(e,t){return new xgo(Tgo(e,t)).createFrame(t===$3.string?v6r.TEXT:v6r.BINARY)}function Tgo(e,t){switch(t){case $3.string:return Buffer.from(e);case $3.arrayBuffer:case $3.blob:return new I6r(e);case $3.typedArray:return new I6r(e.buffer,e.byteOffset,e.byteLength)}}E6r.exports={SendQueue:mht}});var N6r=Be((vUs,M6r)=>{"use strict";var{webidl:sr}=Cd(),{URLSerializer:Rgo}=Nf(),{environmentSettingsObject:x6r}=Kh(),{staticPropertyDescriptors:dT,states:EZ,sentCloseFrameState:_go,sendHints:rCe}=YO(),{kWebSocketURL:C6r,kReadyState:ght,kController:T6r,kBinaryType:nCe,kResponse:R6r,kSentClose:Pgo,kByteParser:$go}=mZ(),{isConnecting:Ogo,isEstablished:Mgo,isClosing:Ngo,isValidSubprotocol:Bgo,fireEvent:_6r}=yZ(),{establishWebSocketConnection:Dgo,closeWebSocketConnection:P6r}=lht(),{ByteParser:Lgo}=b6r(),{kEnumerableProperty:Ag,isBlobLike:$6r}=qr(),{getGlobalDispatcher:Fgo}=sZ(),{types:O6r}=Re("node:util"),{ErrorEvent:Ugo,CloseEvent:jgo}=T3(),{SendQueue:qgo}=S6r(),sm=class e extends EventTarget{#e={open:null,error:null,close:null,message:null};#r=0;#n="";#i="";#o;constructor(t,r=[]){super(),sr.util.markAsUncloneable(this);let n="WebSocket constructor";sr.argumentLengthCheck(arguments,1,n);let i=sr.converters["DOMString or sequence<DOMString> or WebSocketInit"](r,n,"options");t=sr.converters.USVString(t,n,"url"),r=i.protocols;let o=x6r.settingsObject.baseUrl,s;try{s=new URL(t,o)}catch(l){throw new DOMException(l,"SyntaxError")}if(s.protocol==="http:"?s.protocol="ws:":s.protocol==="https:"&&(s.protocol="wss:"),s.protocol!=="ws:"&&s.protocol!=="wss:")throw new DOMException(`Expected a ws: or wss: protocol, got ${s.protocol}`,"SyntaxError");if(s.hash||s.href.endsWith("#"))throw new DOMException("Got fragment","SyntaxError");if(typeof r=="string"&&(r=[r]),r.length!==new Set(r.map(l=>l.toLowerCase())).size)throw new DOMException("Invalid Sec-WebSocket-Protocol value","SyntaxError");if(r.length>0&&!r.every(l=>Bgo(l)))throw new DOMException("Invalid Sec-WebSocket-Protocol value","SyntaxError");this[C6r]=new URL(s.href);let a=x6r.settingsObject;this[T6r]=Dgo(s,r,a,this,(l,c)=>this.#t(l,c),i),this[ght]=e.CONNECTING,this[Pgo]=_go.NOT_SENT,this[nCe]="blob"}close(t=void 0,r=void 0){sr.brandCheck(this,e);let n="WebSocket.close";if(t!==void 0&&(t=sr.converters["unsigned short"](t,n,"code",{clamp:!0})),r!==void 0&&(r=sr.converters.USVString(r,n,"reason")),t!==void 0&&t!==1e3&&(t<3e3||t>4999))throw new DOMException("invalid code","InvalidAccessError");let i=0;if(r!==void 0&&(i=Buffer.byteLength(r),i>123))throw new DOMException(`Reason must be less than 123 bytes; received ${i}`,"SyntaxError");P6r(this,t,r,i)}send(t){sr.brandCheck(this,e);let r="WebSocket.send";if(sr.argumentLengthCheck(arguments,1,r),t=sr.converters.WebSocketSendData(t,r,"data"),Ogo(this))throw new DOMException("Sent before connected.","InvalidStateError");if(!(!Mgo(this)||Ngo(this)))if(typeof t=="string"){let n=Buffer.byteLength(t);this.#r+=n,this.#o.add(t,()=>{this.#r-=n},rCe.string)}else O6r.isArrayBuffer(t)?(this.#r+=t.byteLength,this.#o.add(t,()=>{this.#r-=t.byteLength},rCe.arrayBuffer)):ArrayBuffer.isView(t)?(this.#r+=t.byteLength,this.#o.add(t,()=>{this.#r-=t.byteLength},rCe.typedArray)):$6r(t)&&(this.#r+=t.size,this.#o.add(t,()=>{this.#r-=t.size},rCe.blob))}get readyState(){return sr.brandCheck(this,e),this[ght]}get bufferedAmount(){return sr.brandCheck(this,e),this.#r}get url(){return sr.brandCheck(this,e),Rgo(this[C6r])}get extensions(){return sr.brandCheck(this,e),this.#i}get protocol(){return sr.brandCheck(this,e),this.#n}get onopen(){return sr.brandCheck(this,e),this.#e.open}set onopen(t){sr.brandCheck(this,e),this.#e.open&&this.removeEventListener("open",this.#e.open),typeof t=="function"?(this.#e.open=t,this.addEventListener("open",t)):this.#e.open=null}get onerror(){return sr.brandCheck(this,e),this.#e.error}set onerror(t){sr.brandCheck(this,e),this.#e.error&&this.removeEventListener("error",this.#e.error),typeof t=="function"?(this.#e.error=t,this.addEventListener("error",t)):this.#e.error=null}get onclose(){return sr.brandCheck(this,e),this.#e.close}set onclose(t){sr.brandCheck(this,e),this.#e.close&&this.removeEventListener("close",this.#e.close),typeof t=="function"?(this.#e.close=t,this.addEventListener("close",t)):this.#e.close=null}get onmessage(){return sr.brandCheck(this,e),this.#e.message}set onmessage(t){sr.brandCheck(this,e),this.#e.message&&this.removeEventListener("message",this.#e.message),typeof t=="function"?(this.#e.message=t,this.addEventListener("message",t)):this.#e.message=null}get binaryType(){return sr.brandCheck(this,e),this[nCe]}set binaryType(t){sr.brandCheck(this,e),t!=="blob"&&t!=="arraybuffer"?this[nCe]="blob":this[nCe]=t}#t(t,r){this[R6r]=t;let n=this[T6r]?.dispatcher?.webSocketOptions,i=n?.maxFragments,o=n?.maxPayloadSize,s=new Lgo(this,r,{maxFragments:i,maxPayloadSize:o});s.on("drain",Qgo),s.on("error",Hgo.bind(this)),t.socket.ws=this,this[$go]=s,this.#o=new qgo(t.socket),this[ght]=EZ.OPEN;let a=t.headersList.get("sec-websocket-extensions");a!==null&&(this.#i=a);let l=t.headersList.get("sec-websocket-protocol");l!==null&&(this.#n=l),_6r("open",this)}};sm.CONNECTING=sm.prototype.CONNECTING=EZ.CONNECTING;sm.OPEN=sm.prototype.OPEN=EZ.OPEN;sm.CLOSING=sm.prototype.CLOSING=EZ.CLOSING;sm.CLOSED=sm.prototype.CLOSED=EZ.CLOSED;Object.defineProperties(sm.prototype,{CONNECTING:dT,OPEN:dT,CLOSING:dT,CLOSED:dT,url:Ag,readyState:Ag,bufferedAmount:Ag,onopen:Ag,onerror:Ag,onclose:Ag,close:Ag,onmessage:Ag,binaryType:Ag,send:Ag,extensions:Ag,protocol:Ag,[Symbol.toStringTag]:{value:"WebSocket",writable:!1,enumerable:!1,configurable:!0}});Object.defineProperties(sm,{CONNECTING:dT,OPEN:dT,CLOSING:dT,CLOSED:dT});sr.converters["sequence<DOMString>"]=sr.sequenceConverter(sr.converters.DOMString);sr.converters["DOMString or sequence<DOMString>"]=function(e,t,r){return sr.util.Type(e)==="Object"&&Symbol.iterator in e?sr.converters["sequence<DOMString>"](e):sr.converters.DOMString(e,t,r)};sr.converters.WebSocketInit=sr.dictionaryConverter([{key:"protocols",converter:sr.converters["DOMString or sequence<DOMString>"],defaultValue:()=>new Array(0)},{key:"dispatcher",converter:sr.converters.any,defaultValue:()=>Fgo()},{key:"headers",converter:sr.nullableConverter(sr.converters.HeadersInit)}]);sr.converters["DOMString or sequence<DOMString> or WebSocketInit"]=function(e){return sr.util.Type(e)==="Object"&&!(Symbol.iterator in e)?sr.converters.WebSocketInit(e):{protocols:sr.converters["DOMString or sequence<DOMString>"](e)}};sr.converters.WebSocketSendData=function(e){if(sr.util.Type(e)==="Object"){if($6r(e))return sr.converters.Blob(e,{strict:!1});if(ArrayBuffer.isView(e)||O6r.isArrayBuffer(e))return sr.converters.BufferSource(e)}return sr.converters.USVString(e)};function Qgo(){this.ws[R6r].socket.resume()}function Hgo(e){let t,r;e instanceof jgo?(t=e.reason,r=e.code):t=e.message,_6r("error",this,()=>new Ugo("error",{error:e,message:t})),P6r(this,r)}M6r.exports={WebSocket:sm}});var wht=Be((IUs,B6r)=>{"use strict";function Wgo(e){return e.indexOf("\0")===-1}function Ggo(e){if(e.length===0)return!1;for(let t=0;t<e.length;t++)if(e.charCodeAt(t)<48||e.charCodeAt(t)>57)return!1;return!0}function Vgo(e){return new Promise(t=>{setTimeout(t,e).unref()})}B6r.exports={isValidLastEventId:Wgo,isASCIINumber:Ggo,delay:Vgo}});var L6r=Be((kUs,D6r)=>{"use strict";var zgo=Re("node:buffer"),{Transform:Xgo}=Re("node:stream"),{isASCIINumber:Jgo,isValidLastEventId:Kgo}=wht(),O3=[239,187,191],iCe=10,SZ=13,Ygo=58,Zgo=32,ewo=zgo.kStringMaxLength,two=Buffer.from("data"),rwo=Buffer.from("event"),nwo=Buffer.from("id"),iwo=Buffer.from("retry"),owo=1024,swo=131072,awo=128;function lwo(e,t){if(t>=e.length)return!1;for(let r=t;r<e.length;r++)if(e[r]<48||e[r]>57)return!1;return!0}function cwo(e,t){for(let r=t;r<e.length;r++)if(e[r]===0)return!1;return!0}function oCe(e,t,r){if(t!==r.length)return!1;for(let n=0;n<t;n++)if(e[n]!==r[n])return!1;return!0}function sCe(){let e=new Error("EventSource message size exceeded");return e.aborted=!1,e}var yht=class extends Xgo{state=null;checkBOM=!0;crlfCheck=!1;eventEndCheck=!1;chunks=[];chunkIndex=0;pos=0;lineChunkIndex=0;linePos=0;lineLength=0;eventSize=0;eventFieldSizes={data:0,event:0,id:0,retry:0};dataLineCount=0;maxEventSize;maxDataLines;maxBufferedChunks;event={data:void 0,event:void 0,id:void 0,retry:void 0};constructor(t={}){t.readableObjectMode=!0,super(t),this.state=t.eventSourceSettings||{},this.maxEventSize=t.maxEventSize??ewo;let r=this.maxEventSize>0?Math.min(swo,Math.max(owo,Math.floor(this.maxEventSize/awo))):0;this.maxDataLines=r,this.maxBufferedChunks=r,t.push&&(this.push=t.push)}_transform(t,r,n){if(t.length===0){n();return}if(this.maxEventSize>0&&this.chunks.length>=this.maxBufferedChunks&&t[0]!==iCe&&t[0]!==SZ){n(sCe());return}if(this.chunks.push(t),this.checkBOM&&this.handleBOM()){n();return}for(;this.hasCurrentByte();){let i=this.currentByte();if(this.eventEndCheck){if(this.crlfCheck){if(i===iCe){this.crlfCheck=!1,this.consumeCurrentByte();continue}this.crlfCheck=!1}if(i===iCe||i===SZ){i===SZ&&(this.crlfCheck=!0),this.consumeCurrentByte(),this.hasPendingEvent()&&this.processEvent(this.event),this.clearEvent();continue}this.eventEndCheck=!1;continue}if(i===iCe||i===SZ){i===SZ&&(this.crlfCheck=!0);try{this.parseLine(this.readLine(),this.event)}catch(o){n(o);return}this.consumeCurrentByte(),this.eventEndCheck=!0;continue}if(this.maxEventSize>0&&++this.lineLength>this.maxEventSize+7){n(sCe());return}this.advanceCursor()}n()}_destroy(t,r){this.chunks.length=0,this.clearEvent(),super._destroy(t,r)}parseLine(t,r){if(t.length===0)return;let n=t.indexOf(Ygo);if(n===0)return;let i=t.length,o=t.length;if(n!==-1&&(i=n,o=n+1,t[o]===Zgo&&++o),oCe(t,i,two)){if(this.maxEventSize>0&&this.dataLineCount>=this.maxDataLines)throw sCe();let s=t.length-o,a=this.eventFieldSizes.data+(r.data===void 0?0:1)+s;this.setEventFieldSize("data",a);let l=t.toString("utf8",o);r.data===void 0?r.data=l:r.data+=`
5815
+ `.trim())}};WQr.exports=xft});var sZ=Be((jFs,JQr)=>{"use strict";var VQr=Symbol.for("undici.globalDispatcher.1"),{InvalidArgumentError:Ppo}=Ln(),$po=d3();XQr()===void 0&&zQr(new $po);function zQr(e){if(!e||typeof e.dispatch!="function")throw new Ppo("Argument agent must implement Agent");Object.defineProperty(globalThis,VQr,{value:e,writable:!0,enumerable:!1,configurable:!1})}function XQr(){return globalThis[VQr]}JQr.exports={setGlobalDispatcher:zQr,getGlobalDispatcher:XQr}});var Axe=Be((QFs,KQr)=>{"use strict";KQr.exports=class{#e;constructor(t){if(typeof t!="object"||t===null)throw new TypeError("handler must be an object");this.#e=t}onConnect(...t){return this.#e.onConnect?.(...t)}onError(...t){return this.#e.onError?.(...t)}onUpgrade(...t){return this.#e.onUpgrade?.(...t)}onResponseStarted(...t){return this.#e.onResponseStarted?.(...t)}onHeaders(...t){return this.#e.onHeaders?.(...t)}onData(...t){return this.#e.onData?.(...t)}onComplete(...t){return this.#e.onComplete?.(...t)}onBodySent(...t){return this.#e.onBodySent?.(...t)}}});var ZQr=Be((HFs,YQr)=>{"use strict";var Opo=YSe();YQr.exports=e=>{let t=e?.maxRedirections;return r=>function(i,o){let{maxRedirections:s=t,...a}=i;if(!s)return r(i,o);let l=new Opo(r,s,i,o);return r(a,l)}}});var tHr=Be((WFs,eHr)=>{"use strict";var Mpo=cxe();eHr.exports=e=>t=>function(n,i){return t(n,new Mpo({...n,retryOptions:{...e,...n.retryOptions}},{handler:i,dispatch:t}))}});var nHr=Be((GFs,rHr)=>{"use strict";var Npo=qr(),{InvalidArgumentError:Bpo,RequestAbortedError:Dpo}=Ln(),Lpo=Axe(),Cft=class extends Lpo{#e=1024*1024;#r=null;#n=!1;#i=!1;#o=0;#t=null;#s=null;constructor({maxSize:t},r){if(super(r),t!=null&&(!Number.isFinite(t)||t<1))throw new Bpo("maxSize must be a number greater than 0");this.#e=t??this.#e,this.#s=r}onConnect(t){this.#r=t,this.#s.onConnect(this.#a.bind(this))}#a(t){this.#i=!0,this.#t=t}onHeaders(t,r,n,i){let s=Npo.parseHeaders(r)["content-length"];if(s!=null&&s>this.#e)throw new Dpo(`Response size (${s}) larger than maxSize (${this.#e})`);return this.#i?!0:this.#s.onHeaders(t,r,n,i)}onError(t){this.#n||(t=this.#t??t,this.#s.onError(t))}onData(t){return this.#o=this.#o+t.length,this.#o>=this.#e&&(this.#n=!0,this.#i?this.#s.onError(this.#t):this.#s.onComplete([])),!0}onComplete(t){if(!this.#n){if(this.#i){this.#s.onError(this.reason);return}this.#s.onComplete(t)}}};function Fpo({maxSize:e}={maxSize:1024*1024}){return t=>function(n,i){let{dumpMaxSize:o=e}=n,s=new Cft({maxSize:o},i);return t(n,s)}}rHr.exports=Fpo});var sHr=Be((VFs,oHr)=>{"use strict";var{isIP:Upo}=Re("node:net"),{lookup:jpo}=Re("node:dns"),qpo=Axe(),{InvalidArgumentError:A3,InformationalError:Qpo}=Ln(),iHr=Math.pow(2,31)-1,Tft=class{#e=0;#r=0;#n=new Map;dualStack=!0;affinity=null;lookup=null;pick=null;constructor(t){this.#e=t.maxTTL,this.#r=t.maxItems,this.dualStack=t.dualStack,this.affinity=t.affinity,this.lookup=t.lookup??this.#i,this.pick=t.pick??this.#o}get full(){return this.#n.size===this.#r}runLookup(t,r,n){let i=this.#n.get(t.hostname);if(i==null&&this.full){n(null,t.origin);return}let o={affinity:this.affinity,dualStack:this.dualStack,lookup:this.lookup,pick:this.pick,...r.dns,maxTTL:this.#e,maxItems:this.#r};if(i==null)this.lookup(t,o,(s,a)=>{if(s||a==null||a.length===0){n(s??new Qpo("No DNS entries found"));return}this.setRecords(t,a);let l=this.#n.get(t.hostname),c=this.pick(t,l,o.affinity),d;typeof c.port=="number"?d=`:${c.port}`:t.port!==""?d=`:${t.port}`:d="",n(null,`${t.protocol}//${c.family===6?`[${c.address}]`:c.address}${d}`)});else{let s=this.pick(t,i,o.affinity);if(s==null){this.#n.delete(t.hostname),this.runLookup(t,r,n);return}let a;typeof s.port=="number"?a=`:${s.port}`:t.port!==""?a=`:${t.port}`:a="",n(null,`${t.protocol}//${s.family===6?`[${s.address}]`:s.address}${a}`)}}#i(t,r,n){jpo(t.hostname,{all:!0,family:this.dualStack===!1?this.affinity:0,order:"ipv4first"},(i,o)=>{if(i)return n(i);let s=new Map;for(let a of o)s.set(`${a.address}:${a.family}`,a);n(null,s.values())})}#o(t,r,n){let i=null,{records:o,offset:s}=r,a;if(this.dualStack?(n==null&&(s==null||s===iHr?(r.offset=0,n=4):(r.offset++,n=(r.offset&1)===1?6:4)),o[n]!=null&&o[n].ips.length>0?a=o[n]:a=o[n===4?6:4]):a=o[n],a==null||a.ips.length===0)return i;a.offset==null||a.offset===iHr?a.offset=0:a.offset++;let l=a.offset%a.ips.length;return i=a.ips[l]??null,i==null?i:Date.now()-i.timestamp>i.ttl?(a.ips.splice(l,1),this.pick(t,r,n)):i}setRecords(t,r){let n=Date.now(),i={records:{4:null,6:null}};for(let o of r){o.timestamp=n,typeof o.ttl=="number"?o.ttl=Math.min(o.ttl,this.#e):o.ttl=this.#e;let s=i.records[o.family]??{ips:[]};s.ips.push(o),i.records[o.family]=s}this.#n.set(t.hostname,i)}getHandler(t,r){return new Rft(this,t,r)}},Rft=class extends qpo{#e=null;#r=null;#n=null;#i=null;#o=null;constructor(t,{origin:r,handler:n,dispatch:i},o){super(n),this.#o=r,this.#i=n,this.#r={...o},this.#e=t,this.#n=i}onError(t){switch(t.code){case"ETIMEDOUT":case"ECONNREFUSED":{if(this.#e.dualStack){this.#e.runLookup(this.#o,this.#r,(r,n)=>{if(r)return this.#i.onError(r);let i={...this.#r,origin:n};this.#n(i,this)});return}this.#i.onError(t);return}case"ENOTFOUND":this.#e.deleteRecord(this.#o);default:this.#i.onError(t);break}}};oHr.exports=e=>{if(e?.maxTTL!=null&&(typeof e?.maxTTL!="number"||e?.maxTTL<0))throw new A3("Invalid maxTTL. Must be a positive number");if(e?.maxItems!=null&&(typeof e?.maxItems!="number"||e?.maxItems<1))throw new A3("Invalid maxItems. Must be a positive number and greater than zero");if(e?.affinity!=null&&e?.affinity!==4&&e?.affinity!==6)throw new A3("Invalid affinity. Must be either 4 or 6");if(e?.dualStack!=null&&typeof e?.dualStack!="boolean")throw new A3("Invalid dualStack. Must be a boolean");if(e?.lookup!=null&&typeof e?.lookup!="function")throw new A3("Invalid lookup. Must be a function");if(e?.pick!=null&&typeof e?.pick!="function")throw new A3("Invalid pick. Must be a function");let t=e?.dualStack??!0,r;t?r=e?.affinity??null:r=e?.affinity??4;let n={maxTTL:e?.maxTTL??1e4,lookup:e?.lookup??null,pick:e?.pick??null,dualStack:t,affinity:r,maxItems:e?.maxItems??1/0},i=new Tft(n);return o=>function(a,l){let c=a.origin.constructor===URL?a.origin:new URL(a.origin);return Upo(c.hostname)!==0?o(a,l):(i.runLookup(c,a,(d,u)=>{if(d)return l.onError(d);let p=null;p={...a,servername:c.hostname,origin:u,headers:{host:c.hostname,...a.headers}},o(p,i.getHandler({origin:c,dispatch:o,handler:l},a))}),!0)}}});var GO=Be((zFs,fHr)=>{"use strict";var{kConstruct:Hpo}=Ts(),{kEnumerableProperty:b3}=qr(),{iteratorMixin:Wpo,isValidHeaderName:aZ,isValidHeaderValue:lHr}=Kh(),{webidl:Sn}=Cd(),_ft=Re("node:assert"),bxe=Re("node:util"),jl=Symbol("headers map"),tm=Symbol("headers map sorted");function aHr(e){return e===10||e===13||e===9||e===32}function cHr(e){let t=0,r=e.length;for(;r>t&&aHr(e.charCodeAt(r-1));)--r;for(;r>t&&aHr(e.charCodeAt(t));)++t;return t===0&&r===e.length?e:e.substring(t,r)}function dHr(e,t){if(Array.isArray(t))for(let r=0;r<t.length;++r){let n=t[r];if(n.length!==2)throw Sn.errors.exception({header:"Headers constructor",message:`expected name/value pair to be length 2, found ${n.length}.`});Pft(e,n[0],n[1])}else if(typeof t=="object"&&t!==null){let r=Object.keys(t);for(let n=0;n<r.length;++n)Pft(e,r[n],t[r[n]])}else throw Sn.errors.conversionFailed({prefix:"Headers constructor",argument:"Argument 1",types:["sequence<sequence<ByteString>>","record<ByteString, ByteString>"]})}function Pft(e,t,r){if(r=cHr(r),aZ(t)){if(!lHr(r))throw Sn.errors.invalidArgument({prefix:"Headers.append",value:r,type:"header value"})}else throw Sn.errors.invalidArgument({prefix:"Headers.append",value:t,type:"header name"});if(pHr(e)==="immutable")throw new TypeError("immutable");return $ft(e).append(t,r,!1)}function uHr(e,t){return e[0]<t[0]?-1:1}var vxe=class e{cookies=null;constructor(t){t instanceof e?(this[jl]=new Map(t[jl]),this[tm]=t[tm],this.cookies=t.cookies===null?null:[...t.cookies]):(this[jl]=new Map(t),this[tm]=null)}contains(t,r){return this[jl].has(r?t:t.toLowerCase())}clear(){this[jl].clear(),this[tm]=null,this.cookies=null}append(t,r,n){this[tm]=null;let i=n?t:t.toLowerCase(),o=this[jl].get(i);if(o){let s=i==="cookie"?"; ":", ";this[jl].set(i,{name:o.name,value:`${o.value}${s}${r}`})}else this[jl].set(i,{name:t,value:r});i==="set-cookie"&&(this.cookies??=[]).push(r)}set(t,r,n){this[tm]=null;let i=n?t:t.toLowerCase();i==="set-cookie"&&(this.cookies=[r]),this[jl].set(i,{name:t,value:r})}delete(t,r){this[tm]=null,r||(t=t.toLowerCase()),t==="set-cookie"&&(this.cookies=null),this[jl].delete(t)}get(t,r){return this[jl].get(r?t:t.toLowerCase())?.value??null}*[Symbol.iterator](){for(let{0:t,1:{value:r}}of this[jl])yield[t,r]}get entries(){let t={};if(this[jl].size!==0)for(let{name:r,value:n}of this[jl].values())t[r]=n;return t}rawValues(){return this[jl].values()}get entriesList(){let t=[];if(this[jl].size!==0)for(let{0:r,1:{name:n,value:i}}of this[jl])if(r==="set-cookie")for(let o of this.cookies)t.push([n,o]);else t.push([n,i]);return t}toSortedArray(){let t=this[jl].size,r=new Array(t);if(t<=32){if(t===0)return r;let n=this[jl][Symbol.iterator](),i=n.next().value;r[0]=[i[0],i[1].value],_ft(i[1].value!==null);for(let o=1,s=0,a=0,l=0,c=0,d,u;o<t;++o){for(u=n.next().value,d=r[o]=[u[0],u[1].value],_ft(d[1]!==null),l=0,a=o;l<a;)c=l+(a-l>>1),r[c][0]<=d[0]?l=c+1:a=c;if(o!==c){for(s=o;s>l;)r[s]=r[--s];r[l]=d}}if(!n.next().done)throw new TypeError("Unreachable");return r}else{let n=0;for(let{0:i,1:{value:o}}of this[jl])r[n++]=[i,o],_ft(o!==null);return r.sort(uHr)}}},Py=class e{#e;#r;constructor(t=void 0){Sn.util.markAsUncloneable(this),t!==Hpo&&(this.#r=new vxe,this.#e="none",t!==void 0&&(t=Sn.converters.HeadersInit(t,"Headers contructor","init"),dHr(this,t)))}append(t,r){Sn.brandCheck(this,e),Sn.argumentLengthCheck(arguments,2,"Headers.append");let n="Headers.append";return t=Sn.converters.ByteString(t,n,"name"),r=Sn.converters.ByteString(r,n,"value"),Pft(this,t,r)}delete(t){if(Sn.brandCheck(this,e),Sn.argumentLengthCheck(arguments,1,"Headers.delete"),t=Sn.converters.ByteString(t,"Headers.delete","name"),!aZ(t))throw Sn.errors.invalidArgument({prefix:"Headers.delete",value:t,type:"header name"});if(this.#e==="immutable")throw new TypeError("immutable");this.#r.contains(t,!1)&&this.#r.delete(t,!1)}get(t){Sn.brandCheck(this,e),Sn.argumentLengthCheck(arguments,1,"Headers.get");let r="Headers.get";if(t=Sn.converters.ByteString(t,r,"name"),!aZ(t))throw Sn.errors.invalidArgument({prefix:r,value:t,type:"header name"});return this.#r.get(t,!1)}has(t){Sn.brandCheck(this,e),Sn.argumentLengthCheck(arguments,1,"Headers.has");let r="Headers.has";if(t=Sn.converters.ByteString(t,r,"name"),!aZ(t))throw Sn.errors.invalidArgument({prefix:r,value:t,type:"header name"});return this.#r.contains(t,!1)}set(t,r){Sn.brandCheck(this,e),Sn.argumentLengthCheck(arguments,2,"Headers.set");let n="Headers.set";if(t=Sn.converters.ByteString(t,n,"name"),r=Sn.converters.ByteString(r,n,"value"),r=cHr(r),aZ(t)){if(!lHr(r))throw Sn.errors.invalidArgument({prefix:n,value:r,type:"header value"})}else throw Sn.errors.invalidArgument({prefix:n,value:t,type:"header name"});if(this.#e==="immutable")throw new TypeError("immutable");this.#r.set(t,r,!1)}getSetCookie(){Sn.brandCheck(this,e);let t=this.#r.cookies;return t?[...t]:[]}get[tm](){if(this.#r[tm])return this.#r[tm];let t=[],r=this.#r.toSortedArray(),n=this.#r.cookies;if(n===null||n.length===1)return this.#r[tm]=r;for(let i=0;i<r.length;++i){let{0:o,1:s}=r[i];if(o==="set-cookie")for(let a=0;a<n.length;++a)t.push([o,n[a]]);else t.push([o,s])}return this.#r[tm]=t}[bxe.inspect.custom](t,r){return r.depth??=t,`Headers ${bxe.formatWithOptions(r,this.#r.entries)}`}static getHeadersGuard(t){return t.#e}static setHeadersGuard(t,r){t.#e=r}static getHeadersList(t){return t.#r}static setHeadersList(t,r){t.#r=r}},{getHeadersGuard:pHr,setHeadersGuard:Gpo,getHeadersList:$ft,setHeadersList:Vpo}=Py;Reflect.deleteProperty(Py,"getHeadersGuard");Reflect.deleteProperty(Py,"setHeadersGuard");Reflect.deleteProperty(Py,"getHeadersList");Reflect.deleteProperty(Py,"setHeadersList");Wpo("Headers",Py,tm,0,1);Object.defineProperties(Py.prototype,{append:b3,delete:b3,get:b3,has:b3,set:b3,getSetCookie:b3,[Symbol.toStringTag]:{value:"Headers",configurable:!0},[bxe.inspect.custom]:{enumerable:!1}});Sn.converters.HeadersInit=function(e,t,r){if(Sn.util.Type(e)==="Object"){let n=Reflect.get(e,Symbol.iterator);if(!bxe.types.isProxy(e)&&n===Py.prototype.entries)try{return $ft(e).entriesList}catch{}return typeof n=="function"?Sn.converters["sequence<sequence<ByteString>>"](e,t,r,n.bind(e)):Sn.converters["record<ByteString, ByteString>"](e,t,r)}throw Sn.errors.conversionFailed({prefix:"Headers constructor",argument:"Argument 1",types:["sequence<sequence<ByteString>>","record<ByteString, ByteString>"]})};fHr.exports={fill:dHr,compareHeaderName:uHr,Headers:Py,HeadersList:vxe,getHeadersGuard:pHr,setHeadersGuard:Gpo,setHeadersList:Vpo,getHeadersList:$ft}});var cZ=Be((XFs,SHr)=>{"use strict";var{Headers:AHr,HeadersList:hHr,fill:zpo,getHeadersGuard:Xpo,setHeadersGuard:bHr,setHeadersList:vHr}=GO(),{extractBody:mHr,cloneBody:Jpo,mixinBody:Kpo,hasFinalizationRegistry:IHr,streamRegistry:kHr,bodyUnusable:Ypo}=t3(),Oft=qr(),gHr=Re("node:util"),{kEnumerableProperty:rm}=Oft,{isValidReasonPhrase:Zpo,isCancelled:efo,isAborted:tfo,isBlobLike:rfo,serializeJavascriptValueToJSONString:nfo,isErrorLike:ifo,isomorphicEncode:ofo,environmentSettingsObject:sfo}=Kh(),{redirectStatusSet:afo,nullBodyStatus:lfo}=P7(),{kState:_s,kHeaders:yE}=zC(),{webidl:Or}=Cd(),{FormData:cfo}=D7(),{URLSerializer:wHr}=Nf(),{kConstruct:kxe}=Ts(),Mft=Re("node:assert"),{types:dfo}=Re("node:util"),ufo=new TextEncoder("utf-8"),VO=class e{static error(){return lZ(Exe(),"immutable")}static json(t,r={}){Or.argumentLengthCheck(arguments,1,"Response.json"),r!==null&&(r=Or.converters.ResponseInit(r));let n=ufo.encode(nfo(t)),i=mHr(n),o=lZ(v3({}),"response");return yHr(o,r,{body:i[0],type:"application/json"}),o}static redirect(t,r=302){Or.argumentLengthCheck(arguments,1,"Response.redirect"),t=Or.converters.USVString(t),r=Or.converters["unsigned short"](r);let n;try{n=new URL(t,sfo.settingsObject.baseUrl)}catch(s){throw new TypeError(`Failed to parse URL from ${t}`,{cause:s})}if(!afo.has(r))throw new RangeError(`Invalid status code ${r}`);let i=lZ(v3({}),"immutable");i[_s].status=r;let o=ofo(wHr(n));return i[_s].headersList.append("location",o,!0),i}constructor(t=null,r={}){if(Or.util.markAsUncloneable(this),t===kxe)return;t!==null&&(t=Or.converters.BodyInit(t)),r=Or.converters.ResponseInit(r),this[_s]=v3({}),this[yE]=new AHr(kxe),bHr(this[yE],"response"),vHr(this[yE],this[_s].headersList);let n=null;if(t!=null){let[i,o]=mHr(t);n={body:i,type:o}}yHr(this,r,n)}get type(){return Or.brandCheck(this,e),this[_s].type}get url(){Or.brandCheck(this,e);let t=this[_s].urlList,r=t[t.length-1]??null;return r===null?"":wHr(r,!0)}get redirected(){return Or.brandCheck(this,e),this[_s].urlList.length>1}get status(){return Or.brandCheck(this,e),this[_s].status}get ok(){return Or.brandCheck(this,e),this[_s].status>=200&&this[_s].status<=299}get statusText(){return Or.brandCheck(this,e),this[_s].statusText}get headers(){return Or.brandCheck(this,e),this[yE]}get body(){return Or.brandCheck(this,e),this[_s].body?this[_s].body.stream:null}get bodyUsed(){return Or.brandCheck(this,e),!!this[_s].body&&Oft.isDisturbed(this[_s].body.stream)}clone(){if(Or.brandCheck(this,e),Ypo(this))throw Or.errors.exception({header:"Response.clone",message:"Body has already been consumed."});let t=Nft(this[_s]);return IHr&&this[_s].body?.stream&&kHr.register(this,new WeakRef(this[_s].body.stream)),lZ(t,Xpo(this[yE]))}[gHr.inspect.custom](t,r){r.depth===null&&(r.depth=2),r.colors??=!0;let n={status:this.status,statusText:this.statusText,headers:this.headers,body:this.body,bodyUsed:this.bodyUsed,ok:this.ok,redirected:this.redirected,type:this.type,url:this.url};return`Response ${gHr.formatWithOptions(r,n)}`}};Kpo(VO);Object.defineProperties(VO.prototype,{type:rm,url:rm,status:rm,ok:rm,redirected:rm,statusText:rm,headers:rm,clone:rm,body:rm,bodyUsed:rm,[Symbol.toStringTag]:{value:"Response",configurable:!0}});Object.defineProperties(VO,{json:rm,redirect:rm,error:rm});function Nft(e){if(e.internalResponse)return EHr(Nft(e.internalResponse),e.type);let t=v3({...e,body:null});return e.body!=null&&(t.body=Jpo(t,e.body)),t}function v3(e){return{aborted:!1,rangeRequested:!1,timingAllowPassed:!1,requestIncludesCredentials:!1,type:"default",status:200,timingInfo:null,cacheState:"",statusText:"",...e,headersList:e?.headersList?new hHr(e?.headersList):new hHr,urlList:e?.urlList?[...e.urlList]:[]}}function Exe(e){let t=ifo(e);return v3({type:"error",status:0,error:t?e:new Error(e&&String(e)),aborted:e&&e.name==="AbortError"})}function pfo(e){return e.type==="error"&&e.status===0}function Ixe(e,t){return t={internalResponse:e,...t},new Proxy(e,{get(r,n){return n in t?t[n]:r[n]},set(r,n,i){return Mft(!(n in t)),r[n]=i,!0}})}function EHr(e,t){if(t==="basic")return Ixe(e,{type:"basic",headersList:e.headersList});if(t==="cors")return Ixe(e,{type:"cors",headersList:e.headersList});if(t==="opaque")return Ixe(e,{type:"opaque",urlList:Object.freeze([]),status:0,statusText:"",body:null});if(t==="opaqueredirect")return Ixe(e,{type:"opaqueredirect",status:0,statusText:"",headersList:[],body:null});Mft(!1)}function ffo(e,t=null){return Mft(efo(e)),tfo(e)?Exe(Object.assign(new DOMException("The operation was aborted.","AbortError"),{cause:t})):Exe(Object.assign(new DOMException("Request was cancelled."),{cause:t}))}function yHr(e,t,r){if(t.status!==null&&(t.status<200||t.status>599))throw new RangeError('init["status"] must be in the range of 200 to 599, inclusive.');if("statusText"in t&&t.statusText!=null&&!Zpo(String(t.statusText)))throw new TypeError("Invalid statusText");if("status"in t&&t.status!=null&&(e[_s].status=t.status),"statusText"in t&&t.statusText!=null&&(e[_s].statusText=t.statusText),"headers"in t&&t.headers!=null&&zpo(e[yE],t.headers),r){if(lfo.includes(e.status))throw Or.errors.exception({header:"Response constructor",message:`Invalid response status code ${e.status}`});e[_s].body=r.body,r.type!=null&&!e[_s].headersList.contains("content-type",!0)&&e[_s].headersList.append("content-type",r.type,!0)}}function lZ(e,t){let r=new VO(kxe);return r[_s]=e,r[yE]=new AHr(kxe),vHr(r[yE],e.headersList),bHr(r[yE],t),IHr&&e.body?.stream&&kHr.register(r,new WeakRef(e.body.stream)),r}Or.converters.ReadableStream=Or.interfaceConverter(ReadableStream);Or.converters.FormData=Or.interfaceConverter(cfo);Or.converters.URLSearchParams=Or.interfaceConverter(URLSearchParams);Or.converters.XMLHttpRequestBodyInit=function(e,t,r){return typeof e=="string"?Or.converters.USVString(e,t,r):rfo(e)?Or.converters.Blob(e,t,r,{strict:!1}):ArrayBuffer.isView(e)||dfo.isArrayBuffer(e)?Or.converters.BufferSource(e,t,r):Oft.isFormDataLike(e)?Or.converters.FormData(e,t,r,{strict:!1}):e instanceof URLSearchParams?Or.converters.URLSearchParams(e,t,r):Or.converters.DOMString(e,t,r)};Or.converters.BodyInit=function(e,t,r){return e instanceof ReadableStream?Or.converters.ReadableStream(e,t,r):e?.[Symbol.asyncIterator]?e:Or.converters.XMLHttpRequestBodyInit(e,t,r)};Or.converters.ResponseInit=Or.dictionaryConverter([{key:"status",converter:Or.converters["unsigned short"],defaultValue:()=>200},{key:"statusText",converter:Or.converters.ByteString,defaultValue:()=>""},{key:"headers",converter:Or.converters.HeadersInit}]);SHr.exports={isNetworkError:pfo,makeNetworkError:Exe,makeResponse:v3,makeAppropriateNetworkError:ffo,filterResponse:EHr,Response:VO,cloneResponse:Nft,fromInnerResponse:lZ}});var RHr=Be((JFs,THr)=>{"use strict";var{kConnected:xHr,kSize:CHr}=Ts(),Bft=class{constructor(t){this.value=t}deref(){return this.value[xHr]===0&&this.value[CHr]===0?void 0:this.value}},Dft=class{constructor(t){this.finalizer=t}register(t,r){t.on&&t.on("disconnect",()=>{t[xHr]===0&&t[CHr]===0&&this.finalizer(r)})}unregister(t){}};THr.exports=function(){return process.env.NODE_V8_COVERAGE&&process.version.startsWith("v18")?(process._rawDebug("Using compatibility WeakRef and FinalizationRegistry"),{WeakRef:Bft,FinalizationRegistry:Dft}):{WeakRef,FinalizationRegistry}}});var I3=Be((KFs,HHr)=>{"use strict";var{extractBody:hfo,mixinBody:mfo,cloneBody:gfo,bodyUnusable:_Hr}=t3(),{Headers:FHr,fill:wfo,HeadersList:Txe,setHeadersGuard:Fft,getHeadersGuard:yfo,setHeadersList:UHr,getHeadersList:PHr}=GO(),{FinalizationRegistry:Afo}=RHr()(),xxe=qr(),$Hr=Re("node:util"),{isValidHTTPToken:bfo,sameOrigin:OHr,environmentSettingsObject:Sxe}=Kh(),{forbiddenMethodsSet:vfo,corsSafeListedMethodsSet:Ifo,referrerPolicy:kfo,requestRedirect:Efo,requestMode:Sfo,requestCredentials:xfo,requestCache:Cfo,requestDuplex:Tfo}=P7(),{kEnumerableProperty:ql,normalizedMethodRecordsBase:Rfo,normalizedMethodRecords:_fo}=xxe,{kHeaders:nm,kSignal:Cxe,kState:Ko,kDispatcher:Lft}=zC(),{webidl:zt}=Cd(),{URLSerializer:Pfo}=Nf(),{kConstruct:Rxe}=Ts(),$fo=Re("node:assert"),{getMaxListeners:MHr,setMaxListeners:NHr,getEventListeners:Ofo,defaultMaxListeners:BHr}=Re("node:events"),Mfo=Symbol("abortController"),jHr=new Afo(({signal:e,abort:t})=>{e.removeEventListener("abort",t)}),_xe=new WeakMap;function DHr(e){return t;function t(){let r=e.deref();if(r!==void 0){jHr.unregister(t),this.removeEventListener("abort",t),r.abort(this.reason);let n=_xe.get(r.signal);if(n!==void 0){if(n.size!==0){for(let i of n){let o=i.deref();o!==void 0&&o.abort(this.reason)}n.clear()}_xe.delete(r.signal)}}}}var LHr=!1,oT=class e{constructor(t,r={}){if(zt.util.markAsUncloneable(this),t===Rxe)return;let n="Request constructor";zt.argumentLengthCheck(arguments,1,n),t=zt.converters.RequestInfo(t,n,"input"),r=zt.converters.RequestInit(r,n,"init");let i=null,o=null,s=Sxe.settingsObject.baseUrl,a=null;if(typeof t=="string"){this[Lft]=r.dispatcher;let w;try{w=new URL(t,s)}catch(y){throw new TypeError("Failed to parse URL from "+t,{cause:y})}if(w.username||w.password)throw new TypeError("Request cannot be constructed from a URL that includes credentials: "+t);i=Pxe({urlList:[w]}),o="cors"}else this[Lft]=r.dispatcher||t[Lft],$fo(t instanceof e),i=t[Ko],a=t[Cxe];let l=Sxe.settingsObject.origin,c="client";if(i.window?.constructor?.name==="EnvironmentSettingsObject"&&OHr(i.window,l)&&(c=i.window),r.window!=null)throw new TypeError(`'window' option '${c}' must be null`);"window"in r&&(c="no-window"),i=Pxe({method:i.method,headersList:i.headersList,unsafeRequest:i.unsafeRequest,client:Sxe.settingsObject,window:c,priority:i.priority,origin:i.origin,referrer:i.referrer,referrerPolicy:i.referrerPolicy,mode:i.mode,credentials:i.credentials,cache:i.cache,redirect:i.redirect,integrity:i.integrity,keepalive:i.keepalive,reloadNavigation:i.reloadNavigation,historyNavigation:i.historyNavigation,urlList:[...i.urlList]});let d=Object.keys(r).length!==0;if(d&&(i.mode==="navigate"&&(i.mode="same-origin"),i.reloadNavigation=!1,i.historyNavigation=!1,i.origin="client",i.referrer="client",i.referrerPolicy="",i.url=i.urlList[i.urlList.length-1],i.urlList=[i.url]),r.referrer!==void 0){let w=r.referrer;if(w==="")i.referrer="no-referrer";else{let y;try{y=new URL(w,s)}catch(A){throw new TypeError(`Referrer "${w}" is not a valid URL.`,{cause:A})}y.protocol==="about:"&&y.hostname==="client"||l&&!OHr(y,Sxe.settingsObject.baseUrl)?i.referrer="client":i.referrer=y}}r.referrerPolicy!==void 0&&(i.referrerPolicy=r.referrerPolicy);let u;if(r.mode!==void 0?u=r.mode:u=o,u==="navigate")throw zt.errors.exception({header:"Request constructor",message:"invalid request mode navigate."});if(u!=null&&(i.mode=u),r.credentials!==void 0&&(i.credentials=r.credentials),r.cache!==void 0&&(i.cache=r.cache),i.cache==="only-if-cached"&&i.mode!=="same-origin")throw new TypeError("'only-if-cached' can be set only with 'same-origin' mode");if(r.redirect!==void 0&&(i.redirect=r.redirect),r.integrity!=null&&(i.integrity=String(r.integrity)),r.keepalive!==void 0&&(i.keepalive=!!r.keepalive),r.method!==void 0){let w=r.method,y=_fo[w];if(y!==void 0)i.method=y;else{if(!bfo(w))throw new TypeError(`'${w}' is not a valid HTTP method.`);let A=w.toUpperCase();if(vfo.has(A))throw new TypeError(`'${w}' HTTP method is unsupported.`);w=Rfo[A]??w,i.method=w}!LHr&&i.method==="patch"&&(process.emitWarning("Using `patch` is highly likely to result in a `405 Method Not Allowed`. `PATCH` is much more likely to succeed.",{code:"UNDICI-FETCH-patch"}),LHr=!0)}r.signal!==void 0&&(a=r.signal),this[Ko]=i;let p=new AbortController;if(this[Cxe]=p.signal,a!=null){if(!a||typeof a.aborted!="boolean"||typeof a.addEventListener!="function")throw new TypeError("Failed to construct 'Request': member signal is not of type AbortSignal.");if(a.aborted)p.abort(a.reason);else{this[Mfo]=p;let w=new WeakRef(p),y=DHr(w);try{(typeof MHr=="function"&&MHr(a)===BHr||Ofo(a,"abort").length>=BHr)&&NHr(1500,a)}catch{}xxe.addAbortListener(a,y),jHr.register(p,{signal:a,abort:y},y)}}if(this[nm]=new FHr(Rxe),UHr(this[nm],i.headersList),Fft(this[nm],"request"),u==="no-cors"){if(!Ifo.has(i.method))throw new TypeError(`'${i.method} is unsupported in no-cors mode.`);Fft(this[nm],"request-no-cors")}if(d){let w=PHr(this[nm]),y=r.headers!==void 0?r.headers:new Txe(w);if(w.clear(),y instanceof Txe){for(let{name:A,value:b}of y.rawValues())w.append(A,b,!1);w.cookies=y.cookies}else wfo(this[nm],y)}let f=t instanceof e?t[Ko].body:null;if((r.body!=null||f!=null)&&(i.method==="GET"||i.method==="HEAD"))throw new TypeError("Request with GET/HEAD method cannot have body.");let h=null;if(r.body!=null){let[w,y]=hfo(r.body,i.keepalive);h=w,y&&!PHr(this[nm]).contains("content-type",!0)&&this[nm].append("content-type",y)}let m=h??f;if(m!=null&&m.source==null){if(h!=null&&r.duplex==null)throw new TypeError("RequestInit: duplex option is required when sending a body.");if(i.mode!=="same-origin"&&i.mode!=="cors")throw new TypeError('If request is made from ReadableStream, mode should be "same-origin" or "cors"');i.useCORSPreflightFlag=!0}let g=m;if(h==null&&f!=null){if(_Hr(t))throw new TypeError("Cannot construct a Request with a Request object that has already been used.");let w=new TransformStream;f.stream.pipeThrough(w),g={source:f.source,length:f.length,stream:w.readable}}this[Ko].body=g}get method(){return zt.brandCheck(this,e),this[Ko].method}get url(){return zt.brandCheck(this,e),Pfo(this[Ko].url)}get headers(){return zt.brandCheck(this,e),this[nm]}get destination(){return zt.brandCheck(this,e),this[Ko].destination}get referrer(){return zt.brandCheck(this,e),this[Ko].referrer==="no-referrer"?"":this[Ko].referrer==="client"?"about:client":this[Ko].referrer.toString()}get referrerPolicy(){return zt.brandCheck(this,e),this[Ko].referrerPolicy}get mode(){return zt.brandCheck(this,e),this[Ko].mode}get credentials(){return this[Ko].credentials}get cache(){return zt.brandCheck(this,e),this[Ko].cache}get redirect(){return zt.brandCheck(this,e),this[Ko].redirect}get integrity(){return zt.brandCheck(this,e),this[Ko].integrity}get keepalive(){return zt.brandCheck(this,e),this[Ko].keepalive}get isReloadNavigation(){return zt.brandCheck(this,e),this[Ko].reloadNavigation}get isHistoryNavigation(){return zt.brandCheck(this,e),this[Ko].historyNavigation}get signal(){return zt.brandCheck(this,e),this[Cxe]}get body(){return zt.brandCheck(this,e),this[Ko].body?this[Ko].body.stream:null}get bodyUsed(){return zt.brandCheck(this,e),!!this[Ko].body&&xxe.isDisturbed(this[Ko].body.stream)}get duplex(){return zt.brandCheck(this,e),"half"}clone(){if(zt.brandCheck(this,e),_Hr(this))throw new TypeError("unusable");let t=qHr(this[Ko]),r=new AbortController;if(this.signal.aborted)r.abort(this.signal.reason);else{let n=_xe.get(this.signal);n===void 0&&(n=new Set,_xe.set(this.signal,n));let i=new WeakRef(r);n.add(i),xxe.addAbortListener(r.signal,DHr(i))}return QHr(t,r.signal,yfo(this[nm]))}[$Hr.inspect.custom](t,r){r.depth===null&&(r.depth=2),r.colors??=!0;let n={method:this.method,url:this.url,headers:this.headers,destination:this.destination,referrer:this.referrer,referrerPolicy:this.referrerPolicy,mode:this.mode,credentials:this.credentials,cache:this.cache,redirect:this.redirect,integrity:this.integrity,keepalive:this.keepalive,isReloadNavigation:this.isReloadNavigation,isHistoryNavigation:this.isHistoryNavigation,signal:this.signal};return`Request ${$Hr.formatWithOptions(r,n)}`}};mfo(oT);function Pxe(e){return{method:e.method??"GET",localURLsOnly:e.localURLsOnly??!1,unsafeRequest:e.unsafeRequest??!1,body:e.body??null,client:e.client??null,reservedClient:e.reservedClient??null,replacesClientId:e.replacesClientId??"",window:e.window??"client",keepalive:e.keepalive??!1,serviceWorkers:e.serviceWorkers??"all",initiator:e.initiator??"",destination:e.destination??"",priority:e.priority??null,origin:e.origin??"client",policyContainer:e.policyContainer??"client",referrer:e.referrer??"client",referrerPolicy:e.referrerPolicy??"",mode:e.mode??"no-cors",useCORSPreflightFlag:e.useCORSPreflightFlag??!1,credentials:e.credentials??"same-origin",useCredentials:e.useCredentials??!1,cache:e.cache??"default",redirect:e.redirect??"follow",integrity:e.integrity??"",cryptoGraphicsNonceMetadata:e.cryptoGraphicsNonceMetadata??"",parserMetadata:e.parserMetadata??"",reloadNavigation:e.reloadNavigation??!1,historyNavigation:e.historyNavigation??!1,userActivation:e.userActivation??!1,taintedOrigin:e.taintedOrigin??!1,redirectCount:e.redirectCount??0,responseTainting:e.responseTainting??"basic",preventNoCacheCacheControlHeaderModification:e.preventNoCacheCacheControlHeaderModification??!1,done:e.done??!1,timingAllowFailed:e.timingAllowFailed??!1,urlList:e.urlList,url:e.urlList[0],headersList:e.headersList?new Txe(e.headersList):new Txe}}function qHr(e){let t=Pxe({...e,body:null});return e.body!=null&&(t.body=gfo(t,e.body)),t}function QHr(e,t,r){let n=new oT(Rxe);return n[Ko]=e,n[Cxe]=t,n[nm]=new FHr(Rxe),UHr(n[nm],e.headersList),Fft(n[nm],r),n}Object.defineProperties(oT.prototype,{method:ql,url:ql,headers:ql,redirect:ql,clone:ql,signal:ql,duplex:ql,destination:ql,body:ql,bodyUsed:ql,isHistoryNavigation:ql,isReloadNavigation:ql,keepalive:ql,integrity:ql,cache:ql,credentials:ql,attribute:ql,referrerPolicy:ql,referrer:ql,mode:ql,[Symbol.toStringTag]:{value:"Request",configurable:!0}});zt.converters.Request=zt.interfaceConverter(oT);zt.converters.RequestInfo=function(e,t,r){return typeof e=="string"?zt.converters.USVString(e,t,r):e instanceof oT?zt.converters.Request(e,t,r):zt.converters.USVString(e,t,r)};zt.converters.AbortSignal=zt.interfaceConverter(AbortSignal);zt.converters.RequestInit=zt.dictionaryConverter([{key:"method",converter:zt.converters.ByteString},{key:"headers",converter:zt.converters.HeadersInit},{key:"body",converter:zt.nullableConverter(zt.converters.BodyInit)},{key:"referrer",converter:zt.converters.USVString},{key:"referrerPolicy",converter:zt.converters.DOMString,allowedValues:kfo},{key:"mode",converter:zt.converters.DOMString,allowedValues:Sfo},{key:"credentials",converter:zt.converters.DOMString,allowedValues:xfo},{key:"cache",converter:zt.converters.DOMString,allowedValues:Cfo},{key:"redirect",converter:zt.converters.DOMString,allowedValues:Efo},{key:"integrity",converter:zt.converters.DOMString},{key:"keepalive",converter:zt.converters.boolean},{key:"signal",converter:zt.nullableConverter(e=>zt.converters.AbortSignal(e,"RequestInit","signal",{strict:!1}))},{key:"window",converter:zt.converters.any},{key:"duplex",converter:zt.converters.DOMString,allowedValues:Tfo},{key:"dispatcher",converter:zt.converters.any}]);HHr.exports={Request:oT,makeRequest:Pxe,fromInnerRequest:QHr,cloneRequest:qHr}});var uZ=Be((YFs,oWr)=>{"use strict";var{makeNetworkError:Ni,makeAppropriateNetworkError:$xe,filterResponse:Uft,makeResponse:Oxe,fromInnerResponse:Nfo}=cZ(),{HeadersList:WHr}=GO(),{Request:Bfo,cloneRequest:Dfo}=I3(),sT=Re("node:zlib"),{bytesMatch:Lfo,makePolicyContainer:Ffo,clonePolicyContainer:Ufo,requestBadPort:jfo,TAOCheck:qfo,appendRequestOriginHeader:Qfo,responseLocationURL:Hfo,requestCurrentURL:mv,setRequestReferrerPolicyOnRedirect:Wfo,tryUpgradeRequestToAPotentiallyTrustworthyURL:Gfo,createOpaqueTimingInfo:Wft,appendFetchMetadata:Vfo,corsCheck:zfo,crossOriginResourcePolicyCheck:Xfo,determineRequestsReferrer:Jfo,coarsenedSharedCurrentTime:dZ,createDeferredPromise:Kfo,isBlobLike:Yfo,sameOrigin:Hft,isCancelled:zO,isAborted:GHr,isErrorLike:Zfo,fullyReadBody:eho,readableStreamClose:tho,isomorphicEncode:Mxe,urlIsLocal:rho,urlIsHttpHttpsScheme:Gft,urlHasHttpsScheme:nho,clampAndCoarsenConnectionTimingInfo:iho,simpleRangeHeaderValue:oho,buildContentRange:sho,createInflate:aho,extractMimeType:lho}=Kh(),{kState:JHr,kDispatcher:cho}=zC(),XO=Re("node:assert"),{safelyExtractBody:Vft,extractBody:VHr}=t3(),{redirectStatusSet:KHr,nullBodyStatus:YHr,safeMethodsSet:dho,requestBodyHeader:uho,subresourceSet:pho}=P7(),fho=Re("node:events"),{Readable:hho,pipeline:mho,finished:gho}=Re("node:stream"),{addAbortListener:who,isErrored:yho,isReadable:Nxe,bufferToLowerCasedHeaderName:zHr}=qr(),{dataURLProcessor:Aho,serializeAMimeType:bho,minimizeSupportedMimeType:vho}=Nf(),{getGlobalDispatcher:Iho}=sZ(),{webidl:kho}=Cd(),{STATUS_CODES:Eho}=Re("node:http"),Sho=["GET","HEAD"],xho=typeof __UNDICI_IS_NODE__<"u"||typeof esbuildDetection<"u"?"node":"undici",jft,Bxe=class extends fho{constructor(t){super(),this.dispatcher=t,this.connection=null,this.dump=!1,this.state="ongoing"}terminate(t){this.state==="ongoing"&&(this.state="terminated",this.connection?.destroy(t),this.emit("terminated",t))}abort(t){this.state==="ongoing"&&(this.state="aborted",t||(t=new DOMException("The operation was aborted.","AbortError")),this.serializedAbortReason=t,this.connection?.destroy(t),this.emit("terminated",t))}};function Cho(e){ZHr(e,"fetch")}function Tho(e,t=void 0){kho.argumentLengthCheck(arguments,1,"globalThis.fetch");let r=Kfo(),n;try{n=new Bfo(e,t)}catch(d){return r.reject(d),r.promise}let i=n[JHr];if(n.signal.aborted)return qft(r,i,null,n.signal.reason),r.promise;i.client.globalObject?.constructor?.name==="ServiceWorkerGlobalScope"&&(i.serviceWorkers="none");let s=null,a=!1,l=null;return who(n.signal,()=>{a=!0,XO(l!=null),l.abort(n.signal.reason);let d=s?.deref();qft(r,i,d,n.signal.reason)}),l=tWr({request:i,processResponseEndOfBody:Cho,processResponse:d=>{if(!a){if(d.aborted){qft(r,i,s,l.serializedAbortReason);return}if(d.type==="error"){r.reject(new TypeError("fetch failed",{cause:d.error}));return}s=new WeakRef(Nfo(d,"immutable")),r.resolve(s.deref()),r=null}},dispatcher:n[cho]}),r.promise}function ZHr(e,t="other"){if(e.type==="error"&&e.aborted||!e.urlList?.length)return;let r=e.urlList[0],n=e.timingInfo,i=e.cacheState;Gft(r)&&n!==null&&(e.timingAllowPassed||(n=Wft({startTime:n.startTime}),i=""),n.endTime=dZ(),e.timingInfo=n,eWr(n,r.href,t,globalThis,i))}var eWr=performance.markResourceTiming;function qft(e,t,r,n){if(e&&e.reject(n),t.body!=null&&Nxe(t.body?.stream)&&t.body.stream.cancel(n).catch(o=>{if(o.code!=="ERR_INVALID_STATE")throw o}),r==null)return;let i=r[JHr];i.body!=null&&Nxe(i.body?.stream)&&i.body.stream.cancel(n).catch(o=>{if(o.code!=="ERR_INVALID_STATE")throw o})}function tWr({request:e,processRequestBodyChunkLength:t,processRequestEndOfBody:r,processResponse:n,processResponseEndOfBody:i,processResponseConsumeBody:o,useParallelQueue:s=!1,dispatcher:a=Iho()}){XO(a);let l=null,c=!1;e.client!=null&&(l=e.client.globalObject,c=e.client.crossOriginIsolatedCapability);let d=dZ(c),u=Wft({startTime:d}),p={controller:new Bxe(a),request:e,timingInfo:u,processRequestBodyChunkLength:t,processRequestEndOfBody:r,processResponse:n,processResponseConsumeBody:o,processResponseEndOfBody:i,taskDestination:l,crossOriginIsolatedCapability:c};return XO(!e.body||e.body.stream),e.window==="client"&&(e.window=e.client?.globalObject?.constructor?.name==="Window"?e.client:"no-window"),e.origin==="client"&&(e.origin=e.client.origin),e.policyContainer==="client"&&(e.client!=null?e.policyContainer=Ufo(e.client.policyContainer):e.policyContainer=Ffo()),e.headersList.contains("accept",!0)||e.headersList.append("accept","*/*",!0),e.headersList.contains("accept-language",!0)||e.headersList.append("accept-language","*",!0),e.priority,pho.has(e.destination),rWr(p).catch(f=>{p.controller.terminate(f)}),p.controller}async function rWr(e,t=!1){let r=e.request,n=null;if(r.localURLsOnly&&!rho(mv(r))&&(n=Ni("local URLs only")),Gfo(r),jfo(r)==="blocked"&&(n=Ni("bad port")),r.referrerPolicy===""&&(r.referrerPolicy=r.policyContainer.referrerPolicy),r.referrer!=="no-referrer"&&(r.referrer=Jfo(r)),n===null&&(n=await(async()=>{let o=mv(r);return Hft(o,r.url)&&r.responseTainting==="basic"||o.protocol==="data:"||r.mode==="navigate"||r.mode==="websocket"?(r.responseTainting="basic",await XHr(e)):r.mode==="same-origin"?Ni('request mode cannot be "same-origin"'):r.mode==="no-cors"?r.redirect!=="follow"?Ni('redirect mode cannot be "follow" for "no-cors" request'):(r.responseTainting="opaque",await XHr(e)):Gft(mv(r))?(r.responseTainting="cors",await nWr(e)):Ni("URL scheme must be a HTTP(S) scheme")})()),t)return n;n.status!==0&&!n.internalResponse&&(r.responseTainting,r.responseTainting==="basic"?n=Uft(n,"basic"):r.responseTainting==="cors"?n=Uft(n,"cors"):r.responseTainting==="opaque"?n=Uft(n,"opaque"):XO(!1));let i=n.status===0?n:n.internalResponse;if(i.urlList.length===0&&i.urlList.push(...r.urlList),r.timingAllowFailed||(n.timingAllowPassed=!0),n.type==="opaque"&&i.status===206&&i.rangeRequested&&!r.headers.contains("range",!0)&&(n=i=Ni()),n.status!==0&&(r.method==="HEAD"||r.method==="CONNECT"||YHr.includes(i.status))&&(i.body=null,e.controller.dump=!0),r.integrity){let o=a=>Qft(e,Ni(a));if(r.responseTainting==="opaque"||n.body==null){o(n.error);return}let s=a=>{if(!Lfo(a,r.integrity)){o("integrity mismatch");return}n.body=Vft(a)[0],Qft(e,n)};await eho(n.body,s,o)}else Qft(e,n)}function XHr(e){if(zO(e)&&e.request.redirectCount===0)return Promise.resolve($xe(e));let{request:t}=e,{protocol:r}=mv(t);switch(r){case"about:":return Promise.resolve(Ni("about scheme is not supported"));case"blob:":{jft||(jft=Re("node:buffer").resolveObjectURL);let n=mv(t);if(n.search.length!==0)return Promise.resolve(Ni("NetworkError when attempting to fetch resource."));let i=jft(n.toString());if(t.method!=="GET"||!Yfo(i))return Promise.resolve(Ni("invalid method"));let o=Oxe(),s=i.size,a=Mxe(`${s}`),l=i.type;if(t.headersList.contains("range",!0)){o.rangeRequested=!0;let c=t.headersList.get("range",!0),d=oho(c,!0);if(d==="failure")return Promise.resolve(Ni("failed to fetch the data URL"));let{rangeStartValue:u,rangeEndValue:p}=d;if(u===null)u=s-p,p=u+p-1;else{if(u>=s)return Promise.resolve(Ni("Range start is greater than the blob's size."));(p===null||p>=s)&&(p=s-1)}let f=i.slice(u,p,l),h=VHr(f);o.body=h[0];let m=Mxe(`${f.size}`),g=sho(u,p,s);o.status=206,o.statusText="Partial Content",o.headersList.set("content-length",m,!0),o.headersList.set("content-type",l,!0),o.headersList.set("content-range",g,!0)}else{let c=VHr(i);o.statusText="OK",o.body=c[0],o.headersList.set("content-length",a,!0),o.headersList.set("content-type",l,!0)}return Promise.resolve(o)}case"data:":{let n=mv(t),i=Aho(n);if(i==="failure")return Promise.resolve(Ni("failed to fetch the data URL"));let o=bho(i.mimeType);return Promise.resolve(Oxe({statusText:"OK",headersList:[["content-type",{name:"Content-Type",value:o}]],body:Vft(i.body)[0]}))}case"file:":return Promise.resolve(Ni("not implemented... yet..."));case"http:":case"https:":return nWr(e).catch(n=>Ni(n));default:return Promise.resolve(Ni("unknown scheme"))}}function Rho(e,t){e.request.done=!0,e.processResponseDone!=null&&queueMicrotask(()=>e.processResponseDone(t))}function Qft(e,t){let r=e.timingInfo,n=()=>{let o=Date.now();e.request.destination==="document"&&(e.controller.fullTimingInfo=r),e.controller.reportTimingSteps=()=>{if(e.request.url.protocol!=="https:")return;r.endTime=o;let a=t.cacheState,l=t.bodyInfo;t.timingAllowPassed||(r=Wft(r),a="");let c=0;if(e.request.mode!=="navigator"||!t.hasCrossOriginRedirects){c=t.status;let d=lho(t.headersList);d!=="failure"&&(l.contentType=vho(d))}e.request.initiatorType!=null&&eWr(r,e.request.url.href,e.request.initiatorType,globalThis,a,l,c)};let s=()=>{e.request.done=!0,e.processResponseEndOfBody!=null&&queueMicrotask(()=>e.processResponseEndOfBody(t)),e.request.initiatorType!=null&&e.controller.reportTimingSteps()};queueMicrotask(()=>s())};e.processResponse!=null&&queueMicrotask(()=>{e.processResponse(t),e.processResponse=null});let i=t.type==="error"?t:t.internalResponse??t;i.body==null?n():gho(i.body.stream,()=>{n()})}async function nWr(e){let t=e.request,r=null,n=null,i=e.timingInfo;if(t.serviceWorkers,r===null){if(t.redirect==="follow"&&(t.serviceWorkers="none"),n=r=await iWr(e),t.responseTainting==="cors"&&zfo(t,r)==="failure")return Ni("cors failure");qfo(t,r)==="failure"&&(t.timingAllowFailed=!0)}return(t.responseTainting==="opaque"||r.type==="opaque")&&Xfo(t.origin,t.client,t.destination,n)==="blocked"?Ni("blocked"):(KHr.has(n.status)&&(t.redirect!=="manual"&&e.controller.connection.destroy(void 0,!1),t.redirect==="error"?r=Ni("unexpected redirect"):t.redirect==="manual"?r=n:t.redirect==="follow"?r=await _ho(e,r):XO(!1)),r.timingInfo=i,r)}function _ho(e,t){let r=e.request,n=t.internalResponse?t.internalResponse:t,i;try{if(i=Hfo(n,mv(r).hash),i==null)return t}catch(s){return Promise.resolve(Ni(s))}if(!Gft(i))return Promise.resolve(Ni("URL scheme must be a HTTP(S) scheme"));if(r.redirectCount===20)return Promise.resolve(Ni("redirect count exceeded"));if(r.redirectCount+=1,r.mode==="cors"&&(i.username||i.password)&&!Hft(r,i))return Promise.resolve(Ni('cross origin not allowed for request mode "cors"'));if(r.responseTainting==="cors"&&(i.username||i.password))return Promise.resolve(Ni('URL cannot contain credentials for request mode "cors"'));if(n.status!==303&&r.body!=null&&r.body.source==null)return Promise.resolve(Ni());if([301,302].includes(n.status)&&r.method==="POST"||n.status===303&&!Sho.includes(r.method)){r.method="GET",r.body=null;for(let s of uho)r.headersList.delete(s)}Hft(mv(r),i)||(r.headersList.delete("authorization",!0),r.headersList.delete("proxy-authorization",!0),r.headersList.delete("cookie",!0),r.headersList.delete("host",!0)),r.body!=null&&(XO(r.body.source!=null),r.body=Vft(r.body.source)[0]);let o=e.timingInfo;return o.redirectEndTime=o.postRedirectStartTime=dZ(e.crossOriginIsolatedCapability),o.redirectStartTime===0&&(o.redirectStartTime=o.startTime),r.urlList.push(i),Wfo(r,n),rWr(e,!0)}async function iWr(e,t=!1,r=!1){let n=e.request,i=null,o=null,s=null,a=null,l=!1;n.window==="no-window"&&n.redirect==="error"?(i=e,o=n):(o=Dfo(n),i={...e},i.request=o);let c=n.credentials==="include"||n.credentials==="same-origin"&&n.responseTainting==="basic",d=o.body?o.body.length:null,u=null;if(o.body==null&&["POST","PUT"].includes(o.method)&&(u="0"),d!=null&&(u=Mxe(`${d}`)),u!=null&&o.headersList.append("content-length",u,!0),d!=null&&o.keepalive,o.referrer instanceof URL&&o.headersList.append("referer",Mxe(o.referrer.href),!0),Qfo(o),Vfo(o),o.headersList.contains("user-agent",!0)||o.headersList.append("user-agent",xho),o.cache==="default"&&(o.headersList.contains("if-modified-since",!0)||o.headersList.contains("if-none-match",!0)||o.headersList.contains("if-unmodified-since",!0)||o.headersList.contains("if-match",!0)||o.headersList.contains("if-range",!0))&&(o.cache="no-store"),o.cache==="no-cache"&&!o.preventNoCacheCacheControlHeaderModification&&!o.headersList.contains("cache-control",!0)&&o.headersList.append("cache-control","max-age=0",!0),(o.cache==="no-store"||o.cache==="reload")&&(o.headersList.contains("pragma",!0)||o.headersList.append("pragma","no-cache",!0),o.headersList.contains("cache-control",!0)||o.headersList.append("cache-control","no-cache",!0)),o.headersList.contains("range",!0)&&o.headersList.append("accept-encoding","identity",!0),o.headersList.contains("accept-encoding",!0)||(nho(mv(o))?o.headersList.append("accept-encoding","br, gzip, deflate",!0):o.headersList.append("accept-encoding","gzip, deflate",!0)),o.headersList.delete("host",!0),a==null&&(o.cache="no-store"),o.cache!=="no-store"&&o.cache,s==null){if(o.cache==="only-if-cached")return Ni("only if cached");let p=await Pho(i,c,r);!dho.has(o.method)&&p.status>=200&&p.status<=399,l&&p.status,s==null&&(s=p)}if(s.urlList=[...o.urlList],o.headersList.contains("range",!0)&&(s.rangeRequested=!0),s.requestIncludesCredentials=c,s.status===407)return n.window==="no-window"?Ni():zO(e)?$xe(e):Ni("proxy authentication required");if(s.status===421&&!r&&(n.body==null||n.body.source!=null)){if(zO(e))return $xe(e);e.controller.connection.destroy(),s=await iWr(e,t,!0)}return s}async function Pho(e,t=!1,r=!1){XO(!e.controller.connection||e.controller.connection.destroyed),e.controller.connection={abort:null,destroyed:!1,destroy(h,m=!0){this.destroyed||(this.destroyed=!0,m&&this.abort?.(h??new DOMException("The operation was aborted.","AbortError")))}};let n=e.request,i=null,o=e.timingInfo;null==null&&(n.cache="no-store");let a=r?"yes":"no";n.mode;let l=null;if(n.body==null&&e.processRequestEndOfBody)queueMicrotask(()=>e.processRequestEndOfBody());else if(n.body!=null){let h=async function*(w){zO(e)||(yield w,e.processRequestBodyChunkLength?.(w.byteLength))},m=()=>{zO(e)||e.processRequestEndOfBody&&e.processRequestEndOfBody()},g=w=>{zO(e)||(w.name==="AbortError"?e.controller.abort():e.controller.terminate(w))};l=(async function*(){try{for await(let w of n.body.stream)yield*h(w);m()}catch(w){g(w)}})()}try{let{body:h,status:m,statusText:g,headersList:w,socket:y}=await f({body:l});if(y)i=Oxe({status:m,statusText:g,headersList:w,socket:y});else{let A=h[Symbol.asyncIterator]();e.controller.next=()=>A.next(),i=Oxe({status:m,statusText:g,headersList:w})}}catch(h){return h.name==="AbortError"?(e.controller.connection.destroy(),$xe(e,h)):Ni(h)}let c=async()=>{await e.controller.resume()},d=h=>{zO(e)||e.controller.abort(h)},u=new ReadableStream({async start(h){e.controller.controller=h},async pull(h){await c(h)},async cancel(h){await d(h)},type:"bytes"});i.body={stream:u,source:null,length:null},e.controller.resume||e.controller.on("terminated",p),e.controller.resume=async()=>{for(;;){let h,m;try{let{done:w,value:y}=await e.controller.next();if(GHr(e))break;h=w?void 0:y}catch(w){e.controller.ended&&!o.encodedBodySize?h=void 0:(h=w,m=!0)}if(h===void 0){tho(e.controller.controller),Rho(e,i);return}if(o.decodedBodySize+=h?.byteLength??0,m){e.controller.terminate(h);return}let g=new Uint8Array(h);if(g.byteLength&&e.controller.controller.enqueue(g),yho(u)){e.controller.terminate();return}if(e.controller.controller.desiredSize<=0)return}};function p(h){GHr(e)?(i.aborted=!0,Nxe(u)&&e.controller.controller.error(e.controller.serializedAbortReason)):Nxe(u)&&e.controller.controller.error(new TypeError("terminated",{cause:Zfo(h)?h:void 0})),e.controller.connection.destroy()}return i;function f({body:h}){let m=mv(n),g=e.controller.dispatcher;return new Promise((w,y)=>g.dispatch({path:m.pathname+m.search,origin:m.origin,method:n.method,body:g.isMockActive?n.body&&(n.body.source||n.body.stream):h,headers:n.headersList.entries,maxRedirections:0,upgrade:n.mode==="websocket"?"websocket":void 0},{body:null,abort:null,onConnect(A){let{connection:b}=e.controller;o.finalConnectionTimingInfo=iho(void 0,o.postRedirectStartTime,e.crossOriginIsolatedCapability),b.destroyed?A(new DOMException("The operation was aborted.","AbortError")):(e.controller.on("terminated",A),this.abort=b.abort=A),o.finalNetworkRequestStartTime=dZ(e.crossOriginIsolatedCapability)},onResponseStarted(){o.finalNetworkResponseStartTime=dZ(e.crossOriginIsolatedCapability)},onHeaders(A,b,I,v){if(A<200)return;let k="",S=new WHr;for(let _=0;_<b.length;_+=2)S.append(zHr(b[_]),b[_+1].toString("latin1"),!0);k=S.get("location",!0);let x=[],E=k&&n.redirect==="follow"&&KHr.has(A);if(n.method!=="HEAD"&&n.method!=="CONNECT"&&!YHr.includes(A)&&!E){let _=S.get("content-encoding",!0),P=_?_.toLowerCase().split(","):[],R=5;if(P.length>R)return this.abort(new Error(`too many content-encodings in response: ${P.length}, maximum allowed is ${R}`)),!0;for(let $=P.length-1;$>=0;--$){let O=P[$].trim();if(O==="x-gzip"||O==="gzip")x.push(sT.createGunzip({flush:sT.constants.Z_SYNC_FLUSH,finishFlush:sT.constants.Z_SYNC_FLUSH}));else if(O==="deflate")x.push(aho({flush:sT.constants.Z_SYNC_FLUSH,finishFlush:sT.constants.Z_SYNC_FLUSH}));else if(O==="br")x.push(sT.createBrotliDecompress({flush:sT.constants.BROTLI_OPERATION_FLUSH,finishFlush:sT.constants.BROTLI_OPERATION_FLUSH}));else{x.length=0;break}}}this.body=new hho({read:I});let C=this.onError.bind(this);return w({status:A,statusText:v,headersList:S,body:x.length?mho(this.body,...x,_=>{_&&this.onError(_)}).on("error",C):this.body.on("error",C)}),!0},onData(A){if(e.controller.dump)return;let b=A;return o.encodedBodySize+=b.byteLength,this.body.push(b)},onComplete(){this.abort&&e.controller.off("terminated",this.abort),e.controller.ended=!0,this.body.push(null)},onError(A){this.abort&&e.controller.off("terminated",this.abort),this.body?.destroy(A),e.controller.terminate(A),y(A)},onUpgrade(A,b,I){if(A!==101)return;let v=new WHr;for(let k=0;k<b.length;k+=2)v.append(zHr(b[k]),b[k+1].toString("latin1"),!0);return w({status:A,statusText:Eho[A],headersList:v,socket:I}),!0}}))}}oWr.exports={fetch:Tho,Fetch:Bxe,fetching:tWr,finalizeAndReportTiming:ZHr}});var zft=Be((ZFs,sWr)=>{"use strict";sWr.exports={kState:Symbol("FileReader state"),kResult:Symbol("FileReader result"),kError:Symbol("FileReader error"),kLastProgressEventFired:Symbol("FileReader last progress event fired timestamp"),kEvents:Symbol("FileReader events"),kAborted:Symbol("FileReader aborted")}});var lWr=Be((eUs,aWr)=>{"use strict";var{webidl:im}=Cd(),Dxe=Symbol("ProgressEvent state"),Xft=class e extends Event{constructor(t,r={}){t=im.converters.DOMString(t,"ProgressEvent constructor","type"),r=im.converters.ProgressEventInit(r??{}),super(t,r),this[Dxe]={lengthComputable:r.lengthComputable,loaded:r.loaded,total:r.total}}get lengthComputable(){return im.brandCheck(this,e),this[Dxe].lengthComputable}get loaded(){return im.brandCheck(this,e),this[Dxe].loaded}get total(){return im.brandCheck(this,e),this[Dxe].total}};im.converters.ProgressEventInit=im.dictionaryConverter([{key:"lengthComputable",converter:im.converters.boolean,defaultValue:()=>!1},{key:"loaded",converter:im.converters["unsigned long long"],defaultValue:()=>0},{key:"total",converter:im.converters["unsigned long long"],defaultValue:()=>0},{key:"bubbles",converter:im.converters.boolean,defaultValue:()=>!1},{key:"cancelable",converter:im.converters.boolean,defaultValue:()=>!1},{key:"composed",converter:im.converters.boolean,defaultValue:()=>!1}]);aWr.exports={ProgressEvent:Xft}});var dWr=Be((tUs,cWr)=>{"use strict";function $ho(e){if(!e)return"failure";switch(e.trim().toLowerCase()){case"unicode-1-1-utf-8":case"unicode11utf8":case"unicode20utf8":case"utf-8":case"utf8":case"x-unicode20utf8":return"UTF-8";case"866":case"cp866":case"csibm866":case"ibm866":return"IBM866";case"csisolatin2":case"iso-8859-2":case"iso-ir-101":case"iso8859-2":case"iso88592":case"iso_8859-2":case"iso_8859-2:1987":case"l2":case"latin2":return"ISO-8859-2";case"csisolatin3":case"iso-8859-3":case"iso-ir-109":case"iso8859-3":case"iso88593":case"iso_8859-3":case"iso_8859-3:1988":case"l3":case"latin3":return"ISO-8859-3";case"csisolatin4":case"iso-8859-4":case"iso-ir-110":case"iso8859-4":case"iso88594":case"iso_8859-4":case"iso_8859-4:1988":case"l4":case"latin4":return"ISO-8859-4";case"csisolatincyrillic":case"cyrillic":case"iso-8859-5":case"iso-ir-144":case"iso8859-5":case"iso88595":case"iso_8859-5":case"iso_8859-5:1988":return"ISO-8859-5";case"arabic":case"asmo-708":case"csiso88596e":case"csiso88596i":case"csisolatinarabic":case"ecma-114":case"iso-8859-6":case"iso-8859-6-e":case"iso-8859-6-i":case"iso-ir-127":case"iso8859-6":case"iso88596":case"iso_8859-6":case"iso_8859-6:1987":return"ISO-8859-6";case"csisolatingreek":case"ecma-118":case"elot_928":case"greek":case"greek8":case"iso-8859-7":case"iso-ir-126":case"iso8859-7":case"iso88597":case"iso_8859-7":case"iso_8859-7:1987":case"sun_eu_greek":return"ISO-8859-7";case"csiso88598e":case"csisolatinhebrew":case"hebrew":case"iso-8859-8":case"iso-8859-8-e":case"iso-ir-138":case"iso8859-8":case"iso88598":case"iso_8859-8":case"iso_8859-8:1988":case"visual":return"ISO-8859-8";case"csiso88598i":case"iso-8859-8-i":case"logical":return"ISO-8859-8-I";case"csisolatin6":case"iso-8859-10":case"iso-ir-157":case"iso8859-10":case"iso885910":case"l6":case"latin6":return"ISO-8859-10";case"iso-8859-13":case"iso8859-13":case"iso885913":return"ISO-8859-13";case"iso-8859-14":case"iso8859-14":case"iso885914":return"ISO-8859-14";case"csisolatin9":case"iso-8859-15":case"iso8859-15":case"iso885915":case"iso_8859-15":case"l9":return"ISO-8859-15";case"iso-8859-16":return"ISO-8859-16";case"cskoi8r":case"koi":case"koi8":case"koi8-r":case"koi8_r":return"KOI8-R";case"koi8-ru":case"koi8-u":return"KOI8-U";case"csmacintosh":case"mac":case"macintosh":case"x-mac-roman":return"macintosh";case"iso-8859-11":case"iso8859-11":case"iso885911":case"tis-620":case"windows-874":return"windows-874";case"cp1250":case"windows-1250":case"x-cp1250":return"windows-1250";case"cp1251":case"windows-1251":case"x-cp1251":return"windows-1251";case"ansi_x3.4-1968":case"ascii":case"cp1252":case"cp819":case"csisolatin1":case"ibm819":case"iso-8859-1":case"iso-ir-100":case"iso8859-1":case"iso88591":case"iso_8859-1":case"iso_8859-1:1987":case"l1":case"latin1":case"us-ascii":case"windows-1252":case"x-cp1252":return"windows-1252";case"cp1253":case"windows-1253":case"x-cp1253":return"windows-1253";case"cp1254":case"csisolatin5":case"iso-8859-9":case"iso-ir-148":case"iso8859-9":case"iso88599":case"iso_8859-9":case"iso_8859-9:1989":case"l5":case"latin5":case"windows-1254":case"x-cp1254":return"windows-1254";case"cp1255":case"windows-1255":case"x-cp1255":return"windows-1255";case"cp1256":case"windows-1256":case"x-cp1256":return"windows-1256";case"cp1257":case"windows-1257":case"x-cp1257":return"windows-1257";case"cp1258":case"windows-1258":case"x-cp1258":return"windows-1258";case"x-mac-cyrillic":case"x-mac-ukrainian":return"x-mac-cyrillic";case"chinese":case"csgb2312":case"csiso58gb231280":case"gb2312":case"gb_2312":case"gb_2312-80":case"gbk":case"iso-ir-58":case"x-gbk":return"GBK";case"gb18030":return"gb18030";case"big5":case"big5-hkscs":case"cn-big5":case"csbig5":case"x-x-big5":return"Big5";case"cseucpkdfmtjapanese":case"euc-jp":case"x-euc-jp":return"EUC-JP";case"csiso2022jp":case"iso-2022-jp":return"ISO-2022-JP";case"csshiftjis":case"ms932":case"ms_kanji":case"shift-jis":case"shift_jis":case"sjis":case"windows-31j":case"x-sjis":return"Shift_JIS";case"cseuckr":case"csksc56011987":case"euc-kr":case"iso-ir-149":case"korean":case"ks_c_5601-1987":case"ks_c_5601-1989":case"ksc5601":case"ksc_5601":case"windows-949":return"EUC-KR";case"csiso2022kr":case"hz-gb-2312":case"iso-2022-cn":case"iso-2022-cn-ext":case"iso-2022-kr":case"replacement":return"replacement";case"unicodefffe":case"utf-16be":return"UTF-16BE";case"csunicode":case"iso-10646-ucs-2":case"ucs-2":case"unicode":case"unicodefeff":case"utf-16":case"utf-16le":return"UTF-16LE";case"x-user-defined":return"x-user-defined";default:return"failure"}}cWr.exports={getEncoding:$ho}});var yWr=Be((rUs,wWr)=>{"use strict";var{kState:k3,kError:Jft,kResult:uWr,kAborted:pZ,kLastProgressEventFired:Kft}=zft(),{ProgressEvent:Oho}=lWr(),{getEncoding:pWr}=dWr(),{serializeAMimeType:Mho,parseMIMEType:fWr}=Nf(),{types:Nho}=Re("node:util"),{StringDecoder:hWr}=Re("string_decoder"),{btoa:mWr}=Re("node:buffer"),Bho={enumerable:!0,writable:!1,configurable:!1};function Dho(e,t,r,n){if(e[k3]==="loading")throw new DOMException("Invalid state","InvalidStateError");e[k3]="loading",e[uWr]=null,e[Jft]=null;let o=t.stream().getReader(),s=[],a=o.read(),l=!0;(async()=>{for(;!e[pZ];)try{let{done:c,value:d}=await a;if(l&&!e[pZ]&&queueMicrotask(()=>{aT("loadstart",e)}),l=!1,!c&&Nho.isUint8Array(d))s.push(d),(e[Kft]===void 0||Date.now()-e[Kft]>=50)&&!e[pZ]&&(e[Kft]=Date.now(),queueMicrotask(()=>{aT("progress",e)})),a=o.read();else if(c){queueMicrotask(()=>{e[k3]="done";try{let u=Lho(s,r,t.type,n);if(e[pZ])return;e[uWr]=u,aT("load",e)}catch(u){e[Jft]=u,aT("error",e)}e[k3]!=="loading"&&aT("loadend",e)});break}}catch(c){if(e[pZ])return;queueMicrotask(()=>{e[k3]="done",e[Jft]=c,aT("error",e),e[k3]!=="loading"&&aT("loadend",e)});break}})()}function aT(e,t){let r=new Oho(e,{bubbles:!1,cancelable:!1});t.dispatchEvent(r)}function Lho(e,t,r,n){switch(t){case"DataURL":{let i="data:",o=fWr(r||"application/octet-stream");o!=="failure"&&(i+=Mho(o)),i+=";base64,";let s=new hWr("latin1");for(let a of e)i+=mWr(s.write(a));return i+=mWr(s.end()),i}case"Text":{let i="failure";if(n&&(i=pWr(n)),i==="failure"&&r){let o=fWr(r);o!=="failure"&&(i=pWr(o.parameters.get("charset")))}return i==="failure"&&(i="UTF-8"),Fho(e,i)}case"ArrayBuffer":return gWr(e).buffer;case"BinaryString":{let i="",o=new hWr("latin1");for(let s of e)i+=o.write(s);return i+=o.end(),i}}}function Fho(e,t){let r=gWr(e),n=Uho(r),i=0;n!==null&&(t=n,i=n==="UTF-8"?3:2);let o=r.slice(i);return new TextDecoder(t).decode(o)}function Uho(e){let[t,r,n]=e;return t===239&&r===187&&n===191?"UTF-8":t===254&&r===255?"UTF-16BE":t===255&&r===254?"UTF-16LE":null}function gWr(e){let t=e.reduce((n,i)=>n+i.byteLength,0),r=0;return e.reduce((n,i)=>(n.set(i,r),r+=i.byteLength,n),new Uint8Array(t))}wWr.exports={staticPropertyDescriptors:Bho,readOperation:Dho,fireAProgressEvent:aT}});var IWr=Be((nUs,vWr)=>{"use strict";var{staticPropertyDescriptors:E3,readOperation:Lxe,fireAProgressEvent:AWr}=yWr(),{kState:JO,kError:bWr,kResult:Fxe,kEvents:ei,kAborted:jho}=zft(),{webidl:Vi}=Cd(),{kEnumerableProperty:Lf}=qr(),$y=class e extends EventTarget{constructor(){super(),this[JO]="empty",this[Fxe]=null,this[bWr]=null,this[ei]={loadend:null,error:null,abort:null,load:null,progress:null,loadstart:null}}readAsArrayBuffer(t){Vi.brandCheck(this,e),Vi.argumentLengthCheck(arguments,1,"FileReader.readAsArrayBuffer"),t=Vi.converters.Blob(t,{strict:!1}),Lxe(this,t,"ArrayBuffer")}readAsBinaryString(t){Vi.brandCheck(this,e),Vi.argumentLengthCheck(arguments,1,"FileReader.readAsBinaryString"),t=Vi.converters.Blob(t,{strict:!1}),Lxe(this,t,"BinaryString")}readAsText(t,r=void 0){Vi.brandCheck(this,e),Vi.argumentLengthCheck(arguments,1,"FileReader.readAsText"),t=Vi.converters.Blob(t,{strict:!1}),r!==void 0&&(r=Vi.converters.DOMString(r,"FileReader.readAsText","encoding")),Lxe(this,t,"Text",r)}readAsDataURL(t){Vi.brandCheck(this,e),Vi.argumentLengthCheck(arguments,1,"FileReader.readAsDataURL"),t=Vi.converters.Blob(t,{strict:!1}),Lxe(this,t,"DataURL")}abort(){if(this[JO]==="empty"||this[JO]==="done"){this[Fxe]=null;return}this[JO]==="loading"&&(this[JO]="done",this[Fxe]=null),this[jho]=!0,AWr("abort",this),this[JO]!=="loading"&&AWr("loadend",this)}get readyState(){switch(Vi.brandCheck(this,e),this[JO]){case"empty":return this.EMPTY;case"loading":return this.LOADING;case"done":return this.DONE}}get result(){return Vi.brandCheck(this,e),this[Fxe]}get error(){return Vi.brandCheck(this,e),this[bWr]}get onloadend(){return Vi.brandCheck(this,e),this[ei].loadend}set onloadend(t){Vi.brandCheck(this,e),this[ei].loadend&&this.removeEventListener("loadend",this[ei].loadend),typeof t=="function"?(this[ei].loadend=t,this.addEventListener("loadend",t)):this[ei].loadend=null}get onerror(){return Vi.brandCheck(this,e),this[ei].error}set onerror(t){Vi.brandCheck(this,e),this[ei].error&&this.removeEventListener("error",this[ei].error),typeof t=="function"?(this[ei].error=t,this.addEventListener("error",t)):this[ei].error=null}get onloadstart(){return Vi.brandCheck(this,e),this[ei].loadstart}set onloadstart(t){Vi.brandCheck(this,e),this[ei].loadstart&&this.removeEventListener("loadstart",this[ei].loadstart),typeof t=="function"?(this[ei].loadstart=t,this.addEventListener("loadstart",t)):this[ei].loadstart=null}get onprogress(){return Vi.brandCheck(this,e),this[ei].progress}set onprogress(t){Vi.brandCheck(this,e),this[ei].progress&&this.removeEventListener("progress",this[ei].progress),typeof t=="function"?(this[ei].progress=t,this.addEventListener("progress",t)):this[ei].progress=null}get onload(){return Vi.brandCheck(this,e),this[ei].load}set onload(t){Vi.brandCheck(this,e),this[ei].load&&this.removeEventListener("load",this[ei].load),typeof t=="function"?(this[ei].load=t,this.addEventListener("load",t)):this[ei].load=null}get onabort(){return Vi.brandCheck(this,e),this[ei].abort}set onabort(t){Vi.brandCheck(this,e),this[ei].abort&&this.removeEventListener("abort",this[ei].abort),typeof t=="function"?(this[ei].abort=t,this.addEventListener("abort",t)):this[ei].abort=null}};$y.EMPTY=$y.prototype.EMPTY=0;$y.LOADING=$y.prototype.LOADING=1;$y.DONE=$y.prototype.DONE=2;Object.defineProperties($y.prototype,{EMPTY:E3,LOADING:E3,DONE:E3,readAsArrayBuffer:Lf,readAsBinaryString:Lf,readAsText:Lf,readAsDataURL:Lf,abort:Lf,readyState:Lf,result:Lf,error:Lf,onloadstart:Lf,onprogress:Lf,onload:Lf,onabort:Lf,onerror:Lf,onloadend:Lf,[Symbol.toStringTag]:{value:"FileReader",writable:!1,enumerable:!1,configurable:!0}});Object.defineProperties($y,{EMPTY:E3,LOADING:E3,DONE:E3});vWr.exports={FileReader:$y}});var Uxe=Be((iUs,kWr)=>{"use strict";kWr.exports={kConstruct:Ts().kConstruct}});var xWr=Be((oUs,SWr)=>{"use strict";var qho=Re("node:assert"),{URLSerializer:EWr}=Nf(),{isValidHeaderName:Qho}=Kh();function Hho(e,t,r=!1){let n=EWr(e,r),i=EWr(t,r);return n===i}function Who(e){qho(e!==null);let t=[];for(let r of e.split(","))r=r.trim(),Qho(r)&&t.push(r);return t}SWr.exports={urlEquals:Hho,getFieldValues:Who}});var RWr=Be((sUs,TWr)=>{"use strict";var{kConstruct:Gho}=Uxe(),{urlEquals:Vho,getFieldValues:Yft}=xWr(),{kEnumerableProperty:KO,isDisturbed:zho}=qr(),{webidl:Mt}=Cd(),{Response:Xho,cloneResponse:Jho,fromInnerResponse:Kho}=cZ(),{Request:AE,fromInnerRequest:Yho}=I3(),{kState:Oy}=zC(),{fetching:Zho}=uZ(),{urlIsHttpHttpsScheme:jxe,createDeferredPromise:S3,readAllBytes:emo}=Kh(),Zft=Re("node:assert"),qxe=class e{#e;constructor(){arguments[0]!==Gho&&Mt.illegalConstructor(),Mt.util.markAsUncloneable(this),this.#e=arguments[1]}async match(t,r={}){Mt.brandCheck(this,e);let n="Cache.match";Mt.argumentLengthCheck(arguments,1,n),t=Mt.converters.RequestInfo(t,n,"request"),r=Mt.converters.CacheQueryOptions(r,n,"options");let i=this.#o(t,r,1);if(i.length!==0)return i[0]}async matchAll(t=void 0,r={}){Mt.brandCheck(this,e);let n="Cache.matchAll";return t!==void 0&&(t=Mt.converters.RequestInfo(t,n,"request")),r=Mt.converters.CacheQueryOptions(r,n,"options"),this.#o(t,r)}async add(t){Mt.brandCheck(this,e);let r="Cache.add";Mt.argumentLengthCheck(arguments,1,r),t=Mt.converters.RequestInfo(t,r,"request");let n=[t];return await this.addAll(n)}async addAll(t){Mt.brandCheck(this,e);let r="Cache.addAll";Mt.argumentLengthCheck(arguments,1,r);let n=[],i=[];for(let p of t){if(p===void 0)throw Mt.errors.conversionFailed({prefix:r,argument:"Argument 1",types:["undefined is not allowed"]});if(p=Mt.converters.RequestInfo(p),typeof p=="string")continue;let f=p[Oy];if(!jxe(f.url)||f.method!=="GET")throw Mt.errors.exception({header:r,message:"Expected http/s scheme when method is not GET."})}let o=[];for(let p of t){let f=new AE(p)[Oy];if(!jxe(f.url))throw Mt.errors.exception({header:r,message:"Expected http/s scheme."});f.initiator="fetch",f.destination="subresource",i.push(f);let h=S3();o.push(Zho({request:f,processResponse(m){if(m.type==="error"||m.status===206||m.status<200||m.status>299)h.reject(Mt.errors.exception({header:"Cache.addAll",message:"Received an invalid status code or the request failed."}));else if(m.headersList.contains("vary")){let g=Yft(m.headersList.get("vary"));for(let w of g)if(w==="*"){h.reject(Mt.errors.exception({header:"Cache.addAll",message:"invalid vary field value"}));for(let y of o)y.abort();return}}},processResponseEndOfBody(m){if(m.aborted){h.reject(new DOMException("aborted","AbortError"));return}h.resolve(m)}})),n.push(h.promise)}let a=await Promise.all(n),l=[],c=0;for(let p of a){let f={type:"put",request:i[c],response:p};l.push(f),c++}let d=S3(),u=null;try{this.#r(l)}catch(p){u=p}return queueMicrotask(()=>{u===null?d.resolve(void 0):d.reject(u)}),d.promise}async put(t,r){Mt.brandCheck(this,e);let n="Cache.put";Mt.argumentLengthCheck(arguments,2,n),t=Mt.converters.RequestInfo(t,n,"request"),r=Mt.converters.Response(r,n,"response");let i=null;if(t instanceof AE?i=t[Oy]:i=new AE(t)[Oy],!jxe(i.url)||i.method!=="GET")throw Mt.errors.exception({header:n,message:"Expected an http/s scheme when method is not GET"});let o=r[Oy];if(o.status===206)throw Mt.errors.exception({header:n,message:"Got 206 status"});if(o.headersList.contains("vary")){let f=Yft(o.headersList.get("vary"));for(let h of f)if(h==="*")throw Mt.errors.exception({header:n,message:"Got * vary field value"})}if(o.body&&(zho(o.body.stream)||o.body.stream.locked))throw Mt.errors.exception({header:n,message:"Response body is locked or disturbed"});let s=Jho(o),a=S3();if(o.body!=null){let h=o.body.stream.getReader();emo(h).then(a.resolve,a.reject)}else a.resolve(void 0);let l=[],c={type:"put",request:i,response:s};l.push(c);let d=await a.promise;s.body!=null&&(s.body.source=d);let u=S3(),p=null;try{this.#r(l)}catch(f){p=f}return queueMicrotask(()=>{p===null?u.resolve():u.reject(p)}),u.promise}async delete(t,r={}){Mt.brandCheck(this,e);let n="Cache.delete";Mt.argumentLengthCheck(arguments,1,n),t=Mt.converters.RequestInfo(t,n,"request"),r=Mt.converters.CacheQueryOptions(r,n,"options");let i=null;if(t instanceof AE){if(i=t[Oy],i.method!=="GET"&&!r.ignoreMethod)return!1}else Zft(typeof t=="string"),i=new AE(t)[Oy];let o=[],s={type:"delete",request:i,options:r};o.push(s);let a=S3(),l=null,c;try{c=this.#r(o)}catch(d){l=d}return queueMicrotask(()=>{l===null?a.resolve(!!c?.length):a.reject(l)}),a.promise}async keys(t=void 0,r={}){Mt.brandCheck(this,e);let n="Cache.keys";t!==void 0&&(t=Mt.converters.RequestInfo(t,n,"request")),r=Mt.converters.CacheQueryOptions(r,n,"options");let i=null;if(t!==void 0)if(t instanceof AE){if(i=t[Oy],i.method!=="GET"&&!r.ignoreMethod)return[]}else typeof t=="string"&&(i=new AE(t)[Oy]);let o=S3(),s=[];if(t===void 0)for(let a of this.#e)s.push(a[0]);else{let a=this.#n(i,r);for(let l of a)s.push(l[0])}return queueMicrotask(()=>{let a=[];for(let l of s){let c=Yho(l,new AbortController().signal,"immutable");a.push(c)}o.resolve(Object.freeze(a))}),o.promise}#r(t){let r=this.#e,n=[...r],i=[],o=[];try{for(let s of t){if(s.type!=="delete"&&s.type!=="put")throw Mt.errors.exception({header:"Cache.#batchCacheOperations",message:'operation type does not match "delete" or "put"'});if(s.type==="delete"&&s.response!=null)throw Mt.errors.exception({header:"Cache.#batchCacheOperations",message:"delete operation should not have an associated response"});if(this.#n(s.request,s.options,i).length)throw new DOMException("???","InvalidStateError");let a;if(s.type==="delete"){if(a=this.#n(s.request,s.options),a.length===0)return[];for(let l of a){let c=r.indexOf(l);Zft(c!==-1),r.splice(c,1)}}else if(s.type==="put"){if(s.response==null)throw Mt.errors.exception({header:"Cache.#batchCacheOperations",message:"put operation should have an associated response"});let l=s.request;if(!jxe(l.url))throw Mt.errors.exception({header:"Cache.#batchCacheOperations",message:"expected http or https scheme"});if(l.method!=="GET")throw Mt.errors.exception({header:"Cache.#batchCacheOperations",message:"not get method"});if(s.options!=null)throw Mt.errors.exception({header:"Cache.#batchCacheOperations",message:"options must not be defined"});a=this.#n(s.request);for(let c of a){let d=r.indexOf(c);Zft(d!==-1),r.splice(d,1)}r.push([s.request,s.response]),i.push([s.request,s.response])}o.push([s.request,s.response])}return o}catch(s){throw this.#e.length=0,this.#e=n,s}}#n(t,r,n){let i=[],o=n??this.#e;for(let s of o){let[a,l]=s;this.#i(t,a,l,r)&&i.push(s)}return i}#i(t,r,n=null,i){let o=new URL(t.url),s=new URL(r.url);if(i?.ignoreSearch&&(s.search="",o.search=""),!Vho(o,s,!0))return!1;if(n==null||i?.ignoreVary||!n.headersList.contains("vary"))return!0;let a=Yft(n.headersList.get("vary"));for(let l of a){if(l==="*")return!1;let c=r.headersList.get(l),d=t.headersList.get(l);if(c!==d)return!1}return!0}#o(t,r,n=1/0){let i=null;if(t!==void 0)if(t instanceof AE){if(i=t[Oy],i.method!=="GET"&&!r.ignoreMethod)return[]}else typeof t=="string"&&(i=new AE(t)[Oy]);let o=[];if(t===void 0)for(let a of this.#e)o.push(a[1]);else{let a=this.#n(i,r);for(let l of a)o.push(l[1])}let s=[];for(let a of o){let l=Kho(a,"immutable");if(s.push(l.clone()),s.length>=n)break}return Object.freeze(s)}};Object.defineProperties(qxe.prototype,{[Symbol.toStringTag]:{value:"Cache",configurable:!0},match:KO,matchAll:KO,add:KO,addAll:KO,put:KO,delete:KO,keys:KO});var CWr=[{key:"ignoreSearch",converter:Mt.converters.boolean,defaultValue:()=>!1},{key:"ignoreMethod",converter:Mt.converters.boolean,defaultValue:()=>!1},{key:"ignoreVary",converter:Mt.converters.boolean,defaultValue:()=>!1}];Mt.converters.CacheQueryOptions=Mt.dictionaryConverter(CWr);Mt.converters.MultiCacheQueryOptions=Mt.dictionaryConverter([...CWr,{key:"cacheName",converter:Mt.converters.DOMString}]);Mt.converters.Response=Mt.interfaceConverter(Xho);Mt.converters["sequence<RequestInfo>"]=Mt.sequenceConverter(Mt.converters.RequestInfo);TWr.exports={Cache:qxe}});var PWr=Be((aUs,_Wr)=>{"use strict";var{kConstruct:fZ}=Uxe(),{Cache:Qxe}=RWr(),{webidl:uu}=Cd(),{kEnumerableProperty:hZ}=qr(),Hxe=class e{#e=new Map;constructor(){arguments[0]!==fZ&&uu.illegalConstructor(),uu.util.markAsUncloneable(this)}async match(t,r={}){if(uu.brandCheck(this,e),uu.argumentLengthCheck(arguments,1,"CacheStorage.match"),t=uu.converters.RequestInfo(t),r=uu.converters.MultiCacheQueryOptions(r),r.cacheName!=null){if(this.#e.has(r.cacheName)){let n=this.#e.get(r.cacheName);return await new Qxe(fZ,n).match(t,r)}}else for(let n of this.#e.values()){let o=await new Qxe(fZ,n).match(t,r);if(o!==void 0)return o}}async has(t){uu.brandCheck(this,e);let r="CacheStorage.has";return uu.argumentLengthCheck(arguments,1,r),t=uu.converters.DOMString(t,r,"cacheName"),this.#e.has(t)}async open(t){uu.brandCheck(this,e);let r="CacheStorage.open";if(uu.argumentLengthCheck(arguments,1,r),t=uu.converters.DOMString(t,r,"cacheName"),this.#e.has(t)){let i=this.#e.get(t);return new Qxe(fZ,i)}let n=[];return this.#e.set(t,n),new Qxe(fZ,n)}async delete(t){uu.brandCheck(this,e);let r="CacheStorage.delete";return uu.argumentLengthCheck(arguments,1,r),t=uu.converters.DOMString(t,r,"cacheName"),this.#e.delete(t)}async keys(){return uu.brandCheck(this,e),[...this.#e.keys()]}};Object.defineProperties(Hxe.prototype,{[Symbol.toStringTag]:{value:"CacheStorage",configurable:!0},match:hZ,has:hZ,open:hZ,delete:hZ,keys:hZ});_Wr.exports={CacheStorage:Hxe}});var OWr=Be((lUs,$Wr)=>{"use strict";$Wr.exports={maxAttributeValueSize:1024,maxNameValuePairSize:4096}});var rht=Be((cUs,DWr)=>{"use strict";function tmo(e){for(let t=0;t<e.length;++t){let r=e.charCodeAt(t);if(r>=0&&r<=8||r>=10&&r<=31||r===127)return!0}return!1}function eht(e){for(let t=0;t<e.length;++t){let r=e.charCodeAt(t);if(r<33||r>126||r===34||r===40||r===41||r===60||r===62||r===64||r===44||r===59||r===58||r===92||r===47||r===91||r===93||r===63||r===61||r===123||r===125)throw new Error("Invalid cookie name")}}function tht(e){let t=e.length,r=0;if(e[0]==='"'){if(t===1||e[t-1]!=='"')throw new Error("Invalid cookie value");--t,++r}for(;r<t;){let n=e.charCodeAt(r++);if(n<33||n>126||n===34||n===44||n===59||n===92)throw new Error("Invalid cookie value")}}function NWr(e){for(let t=0;t<e.length;++t){let r=e.charCodeAt(t);if(r<32||r>126||r===59)throw new Error("Invalid cookie path")}}function MWr(e){return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122}function rmo(e){if(e===" ")return;if(e.length>255)throw new Error("Invalid cookie domain");let t=0;for(let r=0;r<e.length;++r){let n=e.charCodeAt(r);if(n===46){if(t===0)throw new Error("Invalid cookie domain");if(e.charCodeAt(r-1)===45)throw new Error("Invalid cookie domain");t=0;continue}if(t===0&&!MWr(n))throw new Error("Invalid cookie domain");if(!MWr(n)&&n!==45)throw new Error("Invalid cookie domain");if(++t>63)throw new Error("Invalid cookie domain")}if(t===0||e.charCodeAt(e.length-1)===45)throw new Error("Invalid cookie domain")}var nmo=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],imo=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Wxe=Array(61).fill(0).map((e,t)=>t.toString().padStart(2,"0"));function BWr(e){return typeof e=="number"&&(e=new Date(e)),`${nmo[e.getUTCDay()]}, ${Wxe[e.getUTCDate()]} ${imo[e.getUTCMonth()]} ${e.getUTCFullYear()} ${Wxe[e.getUTCHours()]}:${Wxe[e.getUTCMinutes()]}:${Wxe[e.getUTCSeconds()]} GMT`}function omo(e){if(e<0)throw new Error("Invalid cookie max-age")}function smo(e){if(e.name.length===0)return null;eht(e.name),tht(e.value);let t=[`${e.name}=${e.value}`];e.name.startsWith("__Secure-")&&(e.secure=!0),e.name.startsWith("__Host-")&&(e.secure=!0,e.domain=null,e.path="/"),e.secure&&t.push("Secure"),e.httpOnly&&t.push("HttpOnly"),typeof e.maxAge=="number"&&(omo(e.maxAge),t.push(`Max-Age=${e.maxAge}`)),e.domain&&(rmo(e.domain),t.push(`Domain=${e.domain}`)),e.path&&(NWr(e.path),t.push(`Path=${e.path}`)),e.expires&&e.expires.toString()!=="Invalid Date"&&t.push(`Expires=${BWr(e.expires)}`),e.sameSite&&t.push(`SameSite=${e.sameSite}`);for(let r of e.unparsed){if(!r.includes("="))throw new Error("Invalid unparsed");let[n,...i]=r.split("="),o=n.trim(),s=i.join("=");eht(o),tht(s),t.push(`${o}=${s}`)}return t.join("; ")}DWr.exports={isCTLExcludingHtab:tmo,validateCookieName:eht,validateCookiePath:NWr,validateCookieValue:tht,toIMFDate:BWr,stringify:smo}});var FWr=Be((dUs,LWr)=>{"use strict";var{maxNameValuePairSize:amo,maxAttributeValueSize:lmo}=OWr(),{isCTLExcludingHtab:cmo}=rht(),{collectASequenceOfCodePointsFast:Gxe}=Nf(),dmo=Re("node:assert");function umo(e){if(cmo(e))return null;let t="",r="",n="",i="";if(e.includes(";")){let o={position:0};t=Gxe(";",e,o),r=e.slice(o.position)}else t=e;if(!t.includes("="))i=t;else{let o={position:0};n=Gxe("=",t,o),i=t.slice(o.position+1)}return n=n.trim(),i=i.trim(),n.length+i.length>amo?null:{name:n,value:i,...x3(r)}}function x3(e,t={}){if(e.length===0)return t;dmo(e[0]===";"),e=e.slice(1);let r="";e.includes(";")?(r=Gxe(";",e,{position:0}),e=e.slice(r.length)):(r=e,e="");let n="",i="";if(r.includes("=")){let s={position:0};n=Gxe("=",r,s),i=r.slice(s.position+1)}else n=r;if(n=n.trim(),i=i.trim(),i.length>lmo)return x3(e,t);let o=n.toLowerCase();if(o==="expires"){let s=new Date(i);t.expires=s}else if(o==="max-age"){let s=i.charCodeAt(0);if((s<48||s>57)&&i[0]!=="-"||!/^\d+$/.test(i))return x3(e,t);let a=Number(i);t.maxAge=a}else if(o==="domain"){let s=i;s[0]==="."&&(s=s.slice(1)),s=s.toLowerCase(),t.domain=s}else if(o==="path"){let s="";i.length===0||i[0]!=="/"?s="/":s=i,t.path=s}else if(o==="secure")t.secure=!0;else if(o==="httponly")t.httpOnly=!0;else if(o==="samesite"){let s=i.toLowerCase();s==="none"?t.sameSite="None":s==="strict"?t.sameSite="Strict":s==="lax"&&(t.sameSite="Lax")}else t.unparsed??=[],t.unparsed.push(`${n}=${i}`);return x3(e,t)}LWr.exports={parseSetCookie:umo,parseUnparsedAttributes:x3}});var qWr=Be((uUs,jWr)=>{"use strict";var{parseSetCookie:pmo}=FWr(),{stringify:fmo}=rht(),{webidl:ln}=Cd(),{Headers:Vxe}=GO();function hmo(e){ln.argumentLengthCheck(arguments,1,"getCookies"),ln.brandCheck(e,Vxe,{strict:!1});let t=e.get("cookie"),r={};if(!t)return r;for(let n of t.split(";")){let[i,...o]=n.split("=");r[i.trim()]=o.join("=")}return r}function mmo(e,t,r){ln.brandCheck(e,Vxe,{strict:!1});let n="deleteCookie";ln.argumentLengthCheck(arguments,2,n),t=ln.converters.DOMString(t,n,"name"),r=ln.converters.DeleteCookieAttributes(r),UWr(e,{name:t,value:"",expires:new Date(0),...r})}function gmo(e){ln.argumentLengthCheck(arguments,1,"getSetCookies"),ln.brandCheck(e,Vxe,{strict:!1});let t=e.getSetCookie();return t?t.map(r=>pmo(r)):[]}function UWr(e,t){ln.argumentLengthCheck(arguments,2,"setCookie"),ln.brandCheck(e,Vxe,{strict:!1}),t=ln.converters.Cookie(t);let r=fmo(t);r&&e.append("Set-Cookie",r)}ln.converters.DeleteCookieAttributes=ln.dictionaryConverter([{converter:ln.nullableConverter(ln.converters.DOMString),key:"path",defaultValue:()=>null},{converter:ln.nullableConverter(ln.converters.DOMString),key:"domain",defaultValue:()=>null}]);ln.converters.Cookie=ln.dictionaryConverter([{converter:ln.converters.DOMString,key:"name"},{converter:ln.converters.DOMString,key:"value"},{converter:ln.nullableConverter(e=>typeof e=="number"?ln.converters["unsigned long long"](e):new Date(e)),key:"expires",defaultValue:()=>null},{converter:ln.nullableConverter(ln.converters["long long"]),key:"maxAge",defaultValue:()=>null},{converter:ln.nullableConverter(ln.converters.DOMString),key:"domain",defaultValue:()=>null},{converter:ln.nullableConverter(ln.converters.DOMString),key:"path",defaultValue:()=>null},{converter:ln.nullableConverter(ln.converters.boolean),key:"secure",defaultValue:()=>null},{converter:ln.nullableConverter(ln.converters.boolean),key:"httpOnly",defaultValue:()=>null},{converter:ln.converters.USVString,key:"sameSite",allowedValues:["Strict","Lax","None"]},{converter:ln.sequenceConverter(ln.converters.DOMString),key:"unparsed",defaultValue:()=>new Array(0)}]);jWr.exports={getCookies:hmo,deleteCookie:mmo,getSetCookies:gmo,setCookie:UWr}});var T3=Be((pUs,HWr)=>{"use strict";var{webidl:Ct}=Cd(),{kEnumerableProperty:Ff}=qr(),{kConstruct:QWr}=Ts(),{MessagePort:wmo}=Re("node:worker_threads"),C3=class e extends Event{#e;constructor(t,r={}){if(t===QWr){super(arguments[1],arguments[2]),Ct.util.markAsUncloneable(this);return}let n="MessageEvent constructor";Ct.argumentLengthCheck(arguments,1,n),t=Ct.converters.DOMString(t,n,"type"),r=Ct.converters.MessageEventInit(r,n,"eventInitDict"),super(t,r),this.#e=r,Ct.util.markAsUncloneable(this)}get data(){return Ct.brandCheck(this,e),this.#e.data}get origin(){return Ct.brandCheck(this,e),this.#e.origin}get lastEventId(){return Ct.brandCheck(this,e),this.#e.lastEventId}get source(){return Ct.brandCheck(this,e),this.#e.source}get ports(){return Ct.brandCheck(this,e),Object.isFrozen(this.#e.ports)||Object.freeze(this.#e.ports),this.#e.ports}initMessageEvent(t,r=!1,n=!1,i=null,o="",s="",a=null,l=[]){return Ct.brandCheck(this,e),Ct.argumentLengthCheck(arguments,1,"MessageEvent.initMessageEvent"),new e(t,{bubbles:r,cancelable:n,data:i,origin:o,lastEventId:s,source:a,ports:l})}static createFastMessageEvent(t,r){let n=new e(QWr,t,r);return n.#e=r,n.#e.data??=null,n.#e.origin??="",n.#e.lastEventId??="",n.#e.source??=null,n.#e.ports??=[],n}},{createFastMessageEvent:ymo}=C3;delete C3.createFastMessageEvent;var zxe=class e extends Event{#e;constructor(t,r={}){let n="CloseEvent constructor";Ct.argumentLengthCheck(arguments,1,n),t=Ct.converters.DOMString(t,n,"type"),r=Ct.converters.CloseEventInit(r),super(t,r),this.#e=r,Ct.util.markAsUncloneable(this)}get wasClean(){return Ct.brandCheck(this,e),this.#e.wasClean}get code(){return Ct.brandCheck(this,e),this.#e.code}get reason(){return Ct.brandCheck(this,e),this.#e.reason}},Xxe=class e extends Event{#e;constructor(t,r){let n="ErrorEvent constructor";Ct.argumentLengthCheck(arguments,1,n),super(t,r),Ct.util.markAsUncloneable(this),t=Ct.converters.DOMString(t,n,"type"),r=Ct.converters.ErrorEventInit(r??{}),this.#e=r}get message(){return Ct.brandCheck(this,e),this.#e.message}get filename(){return Ct.brandCheck(this,e),this.#e.filename}get lineno(){return Ct.brandCheck(this,e),this.#e.lineno}get colno(){return Ct.brandCheck(this,e),this.#e.colno}get error(){return Ct.brandCheck(this,e),this.#e.error}};Object.defineProperties(C3.prototype,{[Symbol.toStringTag]:{value:"MessageEvent",configurable:!0},data:Ff,origin:Ff,lastEventId:Ff,source:Ff,ports:Ff,initMessageEvent:Ff});Object.defineProperties(zxe.prototype,{[Symbol.toStringTag]:{value:"CloseEvent",configurable:!0},reason:Ff,code:Ff,wasClean:Ff});Object.defineProperties(Xxe.prototype,{[Symbol.toStringTag]:{value:"ErrorEvent",configurable:!0},message:Ff,filename:Ff,lineno:Ff,colno:Ff,error:Ff});Ct.converters.MessagePort=Ct.interfaceConverter(wmo);Ct.converters["sequence<MessagePort>"]=Ct.sequenceConverter(Ct.converters.MessagePort);var nht=[{key:"bubbles",converter:Ct.converters.boolean,defaultValue:()=>!1},{key:"cancelable",converter:Ct.converters.boolean,defaultValue:()=>!1},{key:"composed",converter:Ct.converters.boolean,defaultValue:()=>!1}];Ct.converters.MessageEventInit=Ct.dictionaryConverter([...nht,{key:"data",converter:Ct.converters.any,defaultValue:()=>null},{key:"origin",converter:Ct.converters.USVString,defaultValue:()=>""},{key:"lastEventId",converter:Ct.converters.DOMString,defaultValue:()=>""},{key:"source",converter:Ct.nullableConverter(Ct.converters.MessagePort),defaultValue:()=>null},{key:"ports",converter:Ct.converters["sequence<MessagePort>"],defaultValue:()=>new Array(0)}]);Ct.converters.CloseEventInit=Ct.dictionaryConverter([...nht,{key:"wasClean",converter:Ct.converters.boolean,defaultValue:()=>!1},{key:"code",converter:Ct.converters["unsigned short"],defaultValue:()=>0},{key:"reason",converter:Ct.converters.USVString,defaultValue:()=>""}]);Ct.converters.ErrorEventInit=Ct.dictionaryConverter([...nht,{key:"message",converter:Ct.converters.DOMString,defaultValue:()=>""},{key:"filename",converter:Ct.converters.USVString,defaultValue:()=>""},{key:"lineno",converter:Ct.converters["unsigned long"],defaultValue:()=>0},{key:"colno",converter:Ct.converters["unsigned long"],defaultValue:()=>0},{key:"error",converter:Ct.converters.any}]);HWr.exports={MessageEvent:C3,CloseEvent:zxe,ErrorEvent:Xxe,createFastMessageEvent:ymo}});var YO=Be((fUs,WWr)=>{"use strict";var Amo="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",bmo={enumerable:!0,writable:!1,configurable:!1},vmo={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3},Imo={NOT_SENT:0,PROCESSING:1,SENT:2},kmo={CONTINUATION:0,TEXT:1,BINARY:2,CLOSE:8,PING:9,PONG:10},Emo=2**16-1,Smo={INFO:0,PAYLOADLENGTH_16:2,PAYLOADLENGTH_64:3,READ_DATA:4},xmo=Buffer.allocUnsafe(0),Cmo={string:1,typedArray:2,arrayBuffer:3,blob:4};WWr.exports={uid:Amo,sentCloseFrameState:Imo,staticPropertyDescriptors:bmo,states:vmo,opcodes:kmo,maxUnsigned16Bit:Emo,parserStates:Smo,emptyBuffer:xmo,sendHints:Cmo}});var mZ=Be((hUs,GWr)=>{"use strict";GWr.exports={kWebSocketURL:Symbol("url"),kReadyState:Symbol("ready state"),kController:Symbol("controller"),kResponse:Symbol("response"),kBinaryType:Symbol("binary type"),kSentClose:Symbol("sent close"),kReceivedClose:Symbol("received close"),kByteParser:Symbol("byte parser")}});var yZ=Be((mUs,t6r)=>{"use strict";var{kReadyState:gZ,kController:Tmo,kResponse:Rmo,kBinaryType:_mo,kWebSocketURL:Pmo}=mZ(),{states:wZ,opcodes:lT}=YO(),{ErrorEvent:$mo,createFastMessageEvent:Omo}=T3(),{isUtf8:Mmo}=Re("node:buffer"),{collectASequenceOfCodePointsFast:Nmo,removeHTTPWhitespace:VWr}=Nf();function Bmo(e){return e[gZ]===wZ.CONNECTING}function Dmo(e){return e[gZ]===wZ.OPEN}function Lmo(e){return e[gZ]===wZ.CLOSING}function Fmo(e){return e[gZ]===wZ.CLOSED}function iht(e,t,r=(i,o)=>new Event(i,o),n={}){let i=r(e,n);t.dispatchEvent(i)}function Umo(e,t,r){if(e[gZ]!==wZ.OPEN)return;let n;if(t===lT.TEXT)try{n=e6r(r)}catch{XWr(e,"Received invalid UTF-8 in text frame.");return}else t===lT.BINARY&&(e[_mo]==="blob"?n=new Blob([r]):n=jmo(r));iht("message",e,Omo,{origin:e[Pmo].origin,data:n})}function jmo(e){return e.byteLength===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}function qmo(e){if(e.length===0)return!1;for(let t=0;t<e.length;++t){let r=e.charCodeAt(t);if(r<33||r>126||r===34||r===40||r===41||r===44||r===47||r===58||r===59||r===60||r===61||r===62||r===63||r===64||r===91||r===92||r===93||r===123||r===125)return!1}return!0}function Qmo(e){return e>=1e3&&e<1015?e!==1004&&e!==1005&&e!==1006:e>=3e3&&e<=4999}function XWr(e,t){let{[Tmo]:r,[Rmo]:n}=e;r.abort(),n?.socket&&!n.socket.destroyed&&n.socket.destroy(),t&&iht("error",e,(i,o)=>new $mo(i,o),{error:new Error(t),message:t})}function JWr(e){return e===lT.CLOSE||e===lT.PING||e===lT.PONG}function KWr(e){return e===lT.CONTINUATION}function YWr(e){return e===lT.TEXT||e===lT.BINARY}function Hmo(e){return YWr(e)||KWr(e)||JWr(e)}function Wmo(e){let t={position:0},r=new Map;for(;t.position<e.length;){let n=Nmo(";",e,t),[i,o=""]=n.split("=");r.set(VWr(i,!0,!1),VWr(o,!1,!0)),t.position++}return r}function Gmo(e){if(e.length===0)return!1;for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n<48||n>57)return!1}let t=Number.parseInt(e,10);return t>=8&&t<=15}var ZWr=typeof process.versions.icu=="string",zWr=ZWr?new TextDecoder("utf-8",{fatal:!0}):void 0,e6r=ZWr?zWr.decode.bind(zWr):function(e){if(Mmo(e))return e.toString("utf-8");throw new TypeError("Invalid utf-8 received.")};t6r.exports={isConnecting:Bmo,isEstablished:Dmo,isClosing:Lmo,isClosed:Fmo,fireEvent:iht,isValidSubprotocol:qmo,isValidStatusCode:Qmo,failWebsocketConnection:XWr,websocketMessageReceived:Umo,utf8Decode:e6r,isControlFrame:JWr,isContinuationFrame:KWr,isTextBinaryFrame:YWr,isValidOpcode:Hmo,parseExtensions:Wmo,isValidClientWindowBits:Gmo}});var Kxe=Be((gUs,r6r)=>{"use strict";var{maxUnsigned16Bit:Vmo}=YO(),Jxe=16386,oht,AZ=null,R3=Jxe;try{oht=Re("node:crypto")}catch{oht={randomFillSync:function(t,r,n){for(let i=0;i<t.length;++i)t[i]=Math.random()*255|0;return t}}}function zmo(){return R3===Jxe&&(R3=0,oht.randomFillSync(AZ??=Buffer.allocUnsafe(Jxe),0,Jxe)),[AZ[R3++],AZ[R3++],AZ[R3++],AZ[R3++]]}var sht=class{constructor(t){this.frameData=t}createFrame(t){let r=this.frameData,n=zmo(),i=r?.byteLength??0,o=i,s=6;i>Vmo?(s+=8,o=127):i>125&&(s+=2,o=126);let a=Buffer.allocUnsafe(i+s);a[0]=a[1]=0,a[0]|=128,a[0]=(a[0]&240)+t;a[s-4]=n[0],a[s-3]=n[1],a[s-2]=n[2],a[s-1]=n[3],a[1]=o,o===126?a.writeUInt16BE(i,2):o===127&&(a[2]=a[3]=0,a.writeUIntBE(i,4,6)),a[1]|=128;for(let l=0;l<i;++l)a[s+l]=r[l]^n[l&3];return a}};r6r.exports={WebsocketFrameSend:sht}});var lht=Be((wUs,c6r)=>{"use strict";var{uid:Xmo,states:bZ,sentCloseFrameState:Yxe,emptyBuffer:Jmo,opcodes:Kmo}=YO(),{kReadyState:vZ,kSentClose:Zxe,kByteParser:i6r,kReceivedClose:n6r,kResponse:o6r}=mZ(),{fireEvent:Ymo,failWebsocketConnection:cT,isClosing:Zmo,isClosed:ego,isEstablished:tgo,parseExtensions:rgo}=yZ(),{channels:_3}=q4(),{CloseEvent:ngo}=T3(),{makeRequest:igo}=I3(),{fetching:ogo}=uZ(),{Headers:sgo,getHeadersList:ago}=GO(),{getDecodeSplit:lgo}=Kh(),{WebsocketFrameSend:cgo}=Kxe(),aht;try{aht=Re("node:crypto")}catch{}function dgo(e,t,r,n,i,o){let s=e;s.protocol=e.protocol==="ws:"?"http:":"https:";let a=igo({urlList:[s],client:r,serviceWorkers:"none",referrer:"no-referrer",mode:"websocket",credentials:"include",cache:"no-store",redirect:"error"});if(o.headers){let u=ago(new sgo(o.headers));a.headersList=u}let l=aht.randomBytes(16).toString("base64");a.headersList.append("sec-websocket-key",l),a.headersList.append("sec-websocket-version","13");for(let u of t)a.headersList.append("sec-websocket-protocol",u);return a.headersList.append("sec-websocket-extensions","permessage-deflate; client_max_window_bits"),ogo({request:a,useParallelQueue:!0,dispatcher:o.dispatcher,processResponse(u){if(u.type==="error"||u.status!==101){cT(n,"Received network error or non-101 status code.");return}if(t.length!==0&&!u.headersList.get("Sec-WebSocket-Protocol")){cT(n,"Server did not respond with sent protocols.");return}if(u.headersList.get("Upgrade")?.toLowerCase()!=="websocket"){cT(n,'Server did not set Upgrade header to "websocket".');return}if(u.headersList.get("Connection")?.toLowerCase()!=="upgrade"){cT(n,'Server did not set Connection header to "upgrade".');return}let p=u.headersList.get("Sec-WebSocket-Accept"),f=aht.createHash("sha1").update(l+Xmo).digest("base64");if(p!==f){cT(n,"Incorrect hash received in Sec-WebSocket-Accept header.");return}let h=u.headersList.get("Sec-WebSocket-Extensions"),m;if(h!==null&&(m=rgo(h),!m.has("permessage-deflate"))){cT(n,"Sec-WebSocket-Extensions header does not match.");return}let g=u.headersList.get("Sec-WebSocket-Protocol");if(g!==null){let w=lgo("sec-websocket-protocol",a.headersList);if(w===null||!w.includes(g)){cT(n,"Protocol was not set in the opening handshake.");return}}u.socket.on("data",s6r),u.socket.on("close",a6r),u.socket.on("error",l6r),_3.open.hasSubscribers&&_3.open.publish({address:u.socket.address(),protocol:g,extensions:h}),i(u,m)}})}function ugo(e,t,r,n){if(!(Zmo(e)||ego(e)))if(!tgo(e))cT(e,"Connection was closed before it was established."),e[vZ]=bZ.CLOSING;else if(e[Zxe]===Yxe.NOT_SENT){e[Zxe]=Yxe.PROCESSING;let i=new cgo;t!==void 0&&r===void 0?(i.frameData=Buffer.allocUnsafe(2),i.frameData.writeUInt16BE(t,0)):t!==void 0&&r!==void 0?(i.frameData=Buffer.allocUnsafe(2+n),i.frameData.writeUInt16BE(t,0),i.frameData.write(r,2,"utf-8")):i.frameData=Jmo,e[o6r].socket.write(i.createFrame(Kmo.CLOSE)),e[Zxe]=Yxe.SENT,e[vZ]=bZ.CLOSING}else e[vZ]=bZ.CLOSING}function s6r(e){this.ws[i6r].write(e)||this.pause()}function a6r(){let{ws:e}=this,{[o6r]:t}=e;t.socket.off("data",s6r),t.socket.off("close",a6r),t.socket.off("error",l6r);let r=e[Zxe]===Yxe.SENT&&e[n6r],n=1005,i="",o=e[i6r].closingInfo;o&&!o.error?(n=o.code??1005,i=o.reason):e[n6r]||(n=1006),e[vZ]=bZ.CLOSED,Ymo("close",e,(s,a)=>new ngo(s,a),{wasClean:r,code:n,reason:i}),_3.close.hasSubscribers&&_3.close.publish({websocket:e,code:n,reason:i})}function l6r(e){let{ws:t}=this;t[vZ]=bZ.CLOSING,_3.socketError.hasSubscribers&&_3.socketError.publish(e),this.destroy()}c6r.exports={establishWebSocketConnection:dgo,closeWebSocketConnection:ugo}});var u6r=Be((yUs,d6r)=>{"use strict";var{createInflateRaw:pgo,Z_DEFAULT_WINDOWBITS:fgo}=Re("node:zlib"),{isValidClientWindowBits:hgo}=yZ(),{MessageSizeExceededError:mgo}=Ln(),ggo=Buffer.from([0,0,255,255]),eCe=Symbol("kBuffer"),IZ=Symbol("kLength"),cht=class{#e;#r={};#n=0;constructor(t,r){this.#r.serverNoContextTakeover=t.has("server_no_context_takeover"),this.#r.serverMaxWindowBits=t.get("server_max_window_bits"),this.#n=r.maxPayloadSize}decompress(t,r,n){if(!this.#e){let i=fgo;if(this.#r.serverMaxWindowBits){if(!hgo(this.#r.serverMaxWindowBits)){n(new Error("Invalid server_max_window_bits"));return}i=Number.parseInt(this.#r.serverMaxWindowBits)}try{this.#e=pgo({windowBits:i})}catch(o){n(o);return}this.#e[eCe]=[],this.#e[IZ]=0,this.#e.on("data",o=>{if(this.#e[IZ]+=o.length,this.#n>0&&this.#e[IZ]>this.#n){n(new mgo),this.#e.removeAllListeners(),this.#e.destroy(),this.#e=null;return}this.#e[eCe].push(o)}),this.#e.on("error",o=>{this.#e=null,n(o)})}this.#e.write(t),r&&this.#e.write(ggo),this.#e.flush(()=>{if(!this.#e)return;let i=Buffer.concat(this.#e[eCe],this.#e[IZ]);this.#e[eCe].length=0,this.#e[IZ]=0,n(null,i)})}};d6r.exports={PerMessageDeflate:cht}});var b6r=Be((AUs,A6r)=>{"use strict";var{Writable:wgo}=Re("node:stream"),ygo=Re("node:assert"),{parserStates:Uf,opcodes:P3,states:Ago,emptyBuffer:p6r,sentCloseFrameState:f6r}=YO(),{kReadyState:bgo,kSentClose:h6r,kResponse:dht,kReceivedClose:m6r}=mZ(),{channels:tCe}=q4(),{isValidStatusCode:vgo,isValidOpcode:Igo,failWebsocketConnection:om,websocketMessageReceived:g6r,utf8Decode:kgo,isControlFrame:uht,isTextBinaryFrame:pht,isContinuationFrame:Ego}=yZ(),{WebsocketFrameSend:w6r}=Kxe(),{closeWebSocketConnection:y6r}=lht(),{PerMessageDeflate:Sgo}=u6r(),{MessageSizeExceededError:fht}=Ln();function kZ(e,t,r){y6r(e,t,r,Buffer.byteLength(r)),om(e,r)}var hht=class extends wgo{#e=[];#r=0;#n=0;#i=!1;#o=Uf.INFO;#t={};#s=[];#a;#c;#l;constructor(t,r,n={}){super(),this.ws=t,this.#a=r??new Map,this.#c=n.maxFragments??0,this.#l=n.maxPayloadSize??0,this.#a.has("permessage-deflate")&&this.#a.set("permessage-deflate",new Sgo(r,n))}_write(t,r,n){this.#e.push(t),this.#n+=t.length,this.#i=!0,this.run(n)}#d(){return this.#l>0&&!uht(this.#t.opcode)&&this.#t.payloadLength+this.#r>this.#l?(kZ(this.ws,1009,"Payload size exceeds maximum allowed size"),!1):!0}run(t){for(;this.#i;)if(this.#o===Uf.INFO){if(this.#n<2)return t();let r=this.consume(2),n=(r[0]&128)!==0,i=r[0]&15,o=(r[1]&128)===128,s=!n&&i!==P3.CONTINUATION,a=r[1]&127,l=r[0]&64,c=r[0]&32,d=r[0]&16;if(!Igo(i))return om(this.ws,"Invalid opcode received"),t();if(o)return om(this.ws,"Frame cannot be masked"),t();if(l!==0&&!this.#a.has("permessage-deflate")){om(this.ws,"Expected RSV1 to be clear.");return}if(c!==0||d!==0){om(this.ws,"RSV1, RSV2, RSV3 must be clear");return}if(s&&!pht(i)){om(this.ws,"Invalid frame type was fragmented.");return}if(pht(i)&&this.#s.length>0){om(this.ws,"Expected continuation frame");return}if(this.#t.fragmented&&s){om(this.ws,"Fragmented frame exceeded 125 bytes.");return}if((a>125||s)&&uht(i)){om(this.ws,"Control frame either too large or fragmented");return}if(Ego(i)&&this.#s.length===0&&!this.#t.compressed){om(this.ws,"Unexpected continuation frame");return}if(a<=125){if(this.#t.payloadLength=a,this.#o=Uf.READ_DATA,!this.#d())return}else a===126?this.#o=Uf.PAYLOADLENGTH_16:a===127&&(this.#o=Uf.PAYLOADLENGTH_64);pht(i)&&(this.#t.binaryType=i,this.#t.compressed=l!==0),this.#t.opcode=i,this.#t.masked=o,this.#t.fin=n,this.#t.fragmented=s}else if(this.#o===Uf.PAYLOADLENGTH_16){if(this.#n<2)return t();let r=this.consume(2);if(this.#t.payloadLength=r.readUInt16BE(0),this.#o=Uf.READ_DATA,!this.#d())return}else if(this.#o===Uf.PAYLOADLENGTH_64){if(this.#n<8)return t();let r=this.consume(8),n=r.readUInt32BE(0),i=r.readUInt32BE(4);if(n!==0||i>2**31-1){om(this.ws,"Received payload length > 2^31 bytes.");return}if(this.#t.payloadLength=i,this.#o=Uf.READ_DATA,!this.#d())return}else if(this.#o===Uf.READ_DATA){if(this.#n<this.#t.payloadLength)return t();let r=this.consume(this.#t.payloadLength);if(uht(this.#t.opcode)){this.#i=this.parseControlFrame(r),this.#o=Uf.INFO;let n=this.ws[dht].socket;if(this.#i&&n.writableNeedDrain){this.#i=!1,n.once("drain",()=>{this.destroyed||(this.#i=!0,this.run(t))});return}}else if(this.#t.compressed){this.#a.get("permessage-deflate").decompress(r,this.#t.fin,(n,i)=>{if(n){let o=n instanceof fht?1009:1007;kZ(this.ws,o,n.message);return}if(this.writeFragments(i)){if(this.#l>0&&this.#r>this.#l){kZ(this.ws,1009,new fht().message);return}if(!this.#t.fin){this.#o=Uf.INFO,this.#i=!0,this.run(t);return}g6r(this.ws,this.#t.binaryType,this.consumeFragments()),this.#i=!0,this.#o=Uf.INFO,this.run(t)}}),this.#i=!1;break}else{if(!this.writeFragments(r))return;if(this.#l>0&&this.#r>this.#l){kZ(this.ws,1009,new fht().message);return}!this.#t.fragmented&&this.#t.fin&&g6r(this.ws,this.#t.binaryType,this.consumeFragments()),this.#o=Uf.INFO}}}consume(t){if(t>this.#n)throw new Error("Called consume() before buffers satiated.");if(t===0)return p6r;if(this.#e[0].length===t)return this.#n-=this.#e[0].length,this.#e.shift();let r=Buffer.allocUnsafe(t),n=0;for(;n!==t;){let i=this.#e[0],{length:o}=i;if(o+n===t){r.set(this.#e.shift(),n);break}else if(o+n>t){r.set(i.subarray(0,t-n),n),this.#e[0]=i.subarray(t-n);break}else r.set(this.#e.shift(),n),n+=i.length}return this.#n-=t,r}writeFragments(t){return this.#c>0&&this.#s.length===this.#c?(kZ(this.ws,1008,"Too many message fragments"),!1):(this.#r+=t.length,this.#s.push(t),!0)}consumeFragments(){let t=this.#s;if(t.length===1)return this.#r=0,t.shift();let r=Buffer.concat(t,this.#r);return this.#s=[],this.#r=0,r}parseCloseBody(t){ygo(t.length!==1);let r;if(t.length>=2&&(r=t.readUInt16BE(0)),r!==void 0&&!vgo(r))return{code:1002,reason:"Invalid status code",error:!0};let n=t.subarray(2);n[0]===239&&n[1]===187&&n[2]===191&&(n=n.subarray(3));try{n=kgo(n)}catch{return{code:1007,reason:"Invalid UTF-8",error:!0}}return{code:r,reason:n,error:!1}}parseControlFrame(t){let{opcode:r,payloadLength:n}=this.#t;if(r===P3.CLOSE){if(n===1)return om(this.ws,"Received close frame with a 1-byte body."),!1;if(this.#t.closeInfo=this.parseCloseBody(t),this.#t.closeInfo.error){let{code:i,reason:o}=this.#t.closeInfo;return y6r(this.ws,i,o,o.length),om(this.ws,o),!1}if(this.ws[h6r]!==f6r.SENT){let i=p6r;this.#t.closeInfo.code&&(i=Buffer.allocUnsafe(2),i.writeUInt16BE(this.#t.closeInfo.code,0));let o=new w6r(i);this.ws[dht].socket.write(o.createFrame(P3.CLOSE),s=>{s||(this.ws[h6r]=f6r.SENT)})}return this.ws[bgo]=Ago.CLOSING,this.ws[m6r]=!0,!1}else if(r===P3.PING){if(!this.ws[m6r]){let i=new w6r(t);this.ws[dht].socket.write(i.createFrame(P3.PONG)),tCe.ping.hasSubscribers&&tCe.ping.publish({payload:t})}}else r===P3.PONG&&tCe.pong.hasSubscribers&&tCe.pong.publish({payload:t});return!0}get closingInfo(){return this.#t.closeInfo}};A6r.exports={ByteParser:hht}});var S6r=Be((bUs,E6r)=>{"use strict";var{WebsocketFrameSend:xgo}=Kxe(),{opcodes:v6r,sendHints:$3}=YO(),Cgo=Apt(),I6r=Buffer[Symbol.species],mht=class{#e=new Cgo;#r=!1;#n;constructor(t){this.#n=t}add(t,r,n){if(n!==$3.blob){let o=k6r(t,n);if(!this.#r)this.#n.write(o,r);else{let s={promise:null,callback:r,frame:o};this.#e.push(s)}return}let i={promise:t.arrayBuffer().then(o=>{i.promise=null,i.frame=k6r(o,n)}),callback:r,frame:null};this.#e.push(i),this.#r||this.#i()}async#i(){this.#r=!0;let t=this.#e;for(;!t.isEmpty();){let r=t.shift();r.promise!==null&&await r.promise,this.#n.write(r.frame,r.callback),r.callback=r.frame=null}this.#r=!1}};function k6r(e,t){return new xgo(Tgo(e,t)).createFrame(t===$3.string?v6r.TEXT:v6r.BINARY)}function Tgo(e,t){switch(t){case $3.string:return Buffer.from(e);case $3.arrayBuffer:case $3.blob:return new I6r(e);case $3.typedArray:return new I6r(e.buffer,e.byteOffset,e.byteLength)}}E6r.exports={SendQueue:mht}});var N6r=Be((vUs,M6r)=>{"use strict";var{webidl:sr}=Cd(),{URLSerializer:Rgo}=Nf(),{environmentSettingsObject:x6r}=Kh(),{staticPropertyDescriptors:dT,states:EZ,sentCloseFrameState:_go,sendHints:rCe}=YO(),{kWebSocketURL:C6r,kReadyState:ght,kController:T6r,kBinaryType:nCe,kResponse:R6r,kSentClose:Pgo,kByteParser:$go}=mZ(),{isConnecting:Ogo,isEstablished:Mgo,isClosing:Ngo,isValidSubprotocol:Bgo,fireEvent:_6r}=yZ(),{establishWebSocketConnection:Dgo,closeWebSocketConnection:P6r}=lht(),{ByteParser:Lgo}=b6r(),{kEnumerableProperty:Ag,isBlobLike:$6r}=qr(),{getGlobalDispatcher:Fgo}=sZ(),{types:O6r}=Re("node:util"),{ErrorEvent:Ugo,CloseEvent:jgo}=T3(),{SendQueue:qgo}=S6r(),sm=class e extends EventTarget{#e={open:null,error:null,close:null,message:null};#r=0;#n="";#i="";#o;constructor(t,r=[]){super(),sr.util.markAsUncloneable(this);let n="WebSocket constructor";sr.argumentLengthCheck(arguments,1,n);let i=sr.converters["DOMString or sequence<DOMString> or WebSocketInit"](r,n,"options");t=sr.converters.USVString(t,n,"url"),r=i.protocols;let o=x6r.settingsObject.baseUrl,s;try{s=new URL(t,o)}catch(l){throw new DOMException(l,"SyntaxError")}if(s.protocol==="http:"?s.protocol="ws:":s.protocol==="https:"&&(s.protocol="wss:"),s.protocol!=="ws:"&&s.protocol!=="wss:")throw new DOMException(`Expected a ws: or wss: protocol, got ${s.protocol}`,"SyntaxError");if(s.hash||s.href.endsWith("#"))throw new DOMException("Got fragment","SyntaxError");if(typeof r=="string"&&(r=[r]),r.length!==new Set(r.map(l=>l.toLowerCase())).size)throw new DOMException("Invalid Sec-WebSocket-Protocol value","SyntaxError");if(r.length>0&&!r.every(l=>Bgo(l)))throw new DOMException("Invalid Sec-WebSocket-Protocol value","SyntaxError");this[C6r]=new URL(s.href);let a=x6r.settingsObject;this[T6r]=Dgo(s,r,a,this,(l,c)=>this.#t(l,c),i),this[ght]=e.CONNECTING,this[Pgo]=_go.NOT_SENT,this[nCe]="blob"}close(t=void 0,r=void 0){sr.brandCheck(this,e);let n="WebSocket.close";if(t!==void 0&&(t=sr.converters["unsigned short"](t,n,"code",{clamp:!0})),r!==void 0&&(r=sr.converters.USVString(r,n,"reason")),t!==void 0&&t!==1e3&&(t<3e3||t>4999))throw new DOMException("invalid code","InvalidAccessError");let i=0;if(r!==void 0&&(i=Buffer.byteLength(r),i>123))throw new DOMException(`Reason must be less than 123 bytes; received ${i}`,"SyntaxError");P6r(this,t,r,i)}send(t){sr.brandCheck(this,e);let r="WebSocket.send";if(sr.argumentLengthCheck(arguments,1,r),t=sr.converters.WebSocketSendData(t,r,"data"),Ogo(this))throw new DOMException("Sent before connected.","InvalidStateError");if(!(!Mgo(this)||Ngo(this)))if(typeof t=="string"){let n=Buffer.byteLength(t);this.#r+=n,this.#o.add(t,()=>{this.#r-=n},rCe.string)}else O6r.isArrayBuffer(t)?(this.#r+=t.byteLength,this.#o.add(t,()=>{this.#r-=t.byteLength},rCe.arrayBuffer)):ArrayBuffer.isView(t)?(this.#r+=t.byteLength,this.#o.add(t,()=>{this.#r-=t.byteLength},rCe.typedArray)):$6r(t)&&(this.#r+=t.size,this.#o.add(t,()=>{this.#r-=t.size},rCe.blob))}get readyState(){return sr.brandCheck(this,e),this[ght]}get bufferedAmount(){return sr.brandCheck(this,e),this.#r}get url(){return sr.brandCheck(this,e),Rgo(this[C6r])}get extensions(){return sr.brandCheck(this,e),this.#i}get protocol(){return sr.brandCheck(this,e),this.#n}get onopen(){return sr.brandCheck(this,e),this.#e.open}set onopen(t){sr.brandCheck(this,e),this.#e.open&&this.removeEventListener("open",this.#e.open),typeof t=="function"?(this.#e.open=t,this.addEventListener("open",t)):this.#e.open=null}get onerror(){return sr.brandCheck(this,e),this.#e.error}set onerror(t){sr.brandCheck(this,e),this.#e.error&&this.removeEventListener("error",this.#e.error),typeof t=="function"?(this.#e.error=t,this.addEventListener("error",t)):this.#e.error=null}get onclose(){return sr.brandCheck(this,e),this.#e.close}set onclose(t){sr.brandCheck(this,e),this.#e.close&&this.removeEventListener("close",this.#e.close),typeof t=="function"?(this.#e.close=t,this.addEventListener("close",t)):this.#e.close=null}get onmessage(){return sr.brandCheck(this,e),this.#e.message}set onmessage(t){sr.brandCheck(this,e),this.#e.message&&this.removeEventListener("message",this.#e.message),typeof t=="function"?(this.#e.message=t,this.addEventListener("message",t)):this.#e.message=null}get binaryType(){return sr.brandCheck(this,e),this[nCe]}set binaryType(t){sr.brandCheck(this,e),t!=="blob"&&t!=="arraybuffer"?this[nCe]="blob":this[nCe]=t}#t(t,r){this[R6r]=t;let n=this[T6r]?.dispatcher?.webSocketOptions,i=n?.maxFragments,o=n?.maxPayloadSize,s=new Lgo(this,r,{maxFragments:i,maxPayloadSize:o});s.on("drain",Qgo),s.on("error",Hgo.bind(this)),t.socket.ws=this,this[$go]=s,this.#o=new qgo(t.socket),this[ght]=EZ.OPEN;let a=t.headersList.get("sec-websocket-extensions");a!==null&&(this.#i=a);let l=t.headersList.get("sec-websocket-protocol");l!==null&&(this.#n=l),_6r("open",this)}};sm.CONNECTING=sm.prototype.CONNECTING=EZ.CONNECTING;sm.OPEN=sm.prototype.OPEN=EZ.OPEN;sm.CLOSING=sm.prototype.CLOSING=EZ.CLOSING;sm.CLOSED=sm.prototype.CLOSED=EZ.CLOSED;Object.defineProperties(sm.prototype,{CONNECTING:dT,OPEN:dT,CLOSING:dT,CLOSED:dT,url:Ag,readyState:Ag,bufferedAmount:Ag,onopen:Ag,onerror:Ag,onclose:Ag,close:Ag,onmessage:Ag,binaryType:Ag,send:Ag,extensions:Ag,protocol:Ag,[Symbol.toStringTag]:{value:"WebSocket",writable:!1,enumerable:!1,configurable:!0}});Object.defineProperties(sm,{CONNECTING:dT,OPEN:dT,CLOSING:dT,CLOSED:dT});sr.converters["sequence<DOMString>"]=sr.sequenceConverter(sr.converters.DOMString);sr.converters["DOMString or sequence<DOMString>"]=function(e,t,r){return sr.util.Type(e)==="Object"&&Symbol.iterator in e?sr.converters["sequence<DOMString>"](e):sr.converters.DOMString(e,t,r)};sr.converters.WebSocketInit=sr.dictionaryConverter([{key:"protocols",converter:sr.converters["DOMString or sequence<DOMString>"],defaultValue:()=>new Array(0)},{key:"dispatcher",converter:sr.converters.any,defaultValue:()=>Fgo()},{key:"headers",converter:sr.nullableConverter(sr.converters.HeadersInit)}]);sr.converters["DOMString or sequence<DOMString> or WebSocketInit"]=function(e){return sr.util.Type(e)==="Object"&&!(Symbol.iterator in e)?sr.converters.WebSocketInit(e):{protocols:sr.converters["DOMString or sequence<DOMString>"](e)}};sr.converters.WebSocketSendData=function(e){if(sr.util.Type(e)==="Object"){if($6r(e))return sr.converters.Blob(e,{strict:!1});if(ArrayBuffer.isView(e)||O6r.isArrayBuffer(e))return sr.converters.BufferSource(e)}return sr.converters.USVString(e)};function Qgo(){this.ws[R6r].socket.resume()}function Hgo(e){let t,r;e instanceof jgo?(t=e.reason,r=e.code):t=e.message,_6r("error",this,()=>new Ugo("error",{error:e,message:t})),P6r(this,r)}M6r.exports={WebSocket:sm}});var wht=Be((IUs,B6r)=>{"use strict";function Wgo(e){return e.indexOf("\0")===-1}function Ggo(e){if(e.length===0)return!1;for(let t=0;t<e.length;t++)if(e.charCodeAt(t)<48||e.charCodeAt(t)>57)return!1;return!0}function Vgo(e){return new Promise(t=>{setTimeout(t,e).unref()})}B6r.exports={isValidLastEventId:Wgo,isASCIINumber:Ggo,delay:Vgo}});var L6r=Be((kUs,D6r)=>{"use strict";var zgo=Re("node:buffer"),{Transform:Xgo}=Re("node:stream"),{isASCIINumber:Jgo,isValidLastEventId:Kgo}=wht(),O3=[239,187,191],iCe=10,SZ=13,Ygo=58,Zgo=32,ewo=zgo.kStringMaxLength,two=Buffer.from("data"),rwo=Buffer.from("event"),nwo=Buffer.from("id"),iwo=Buffer.from("retry"),owo=1024,swo=131072,awo=128;function lwo(e,t){if(t>=e.length)return!1;for(let r=t;r<e.length;r++)if(e[r]<48||e[r]>57)return!1;return!0}function cwo(e,t){for(let r=t;r<e.length;r++)if(e[r]===0)return!1;return!0}function oCe(e,t,r){if(t!==r.length)return!1;for(let n=0;n<t;n++)if(e[n]!==r[n])return!1;return!0}function sCe(){let e=new Error("EventSource message size exceeded");return e.aborted=!1,e}var yht=class extends Xgo{state=null;checkBOM=!0;crlfCheck=!1;eventEndCheck=!1;chunks=[];chunkIndex=0;pos=0;lineChunkIndex=0;linePos=0;lineLength=0;eventSize=0;eventFieldSizes={data:0,event:0,id:0,retry:0};dataLineCount=0;maxEventSize;maxDataLines;maxBufferedChunks;event={data:void 0,event:void 0,id:void 0,retry:void 0};constructor(t={}){t.readableObjectMode=!0,super(t),this.state=t.eventSourceSettings||{},this.maxEventSize=t.maxEventSize??ewo;let r=this.maxEventSize>0?Math.min(swo,Math.max(owo,Math.floor(this.maxEventSize/awo))):0;this.maxDataLines=r,this.maxBufferedChunks=r,t.push&&(this.push=t.push)}_transform(t,r,n){if(t.length===0){n();return}if(this.maxEventSize>0&&this.chunks.length>=this.maxBufferedChunks&&t[0]!==iCe&&t[0]!==SZ){n(sCe());return}if(this.chunks.push(t),this.checkBOM&&this.handleBOM()){n();return}for(;this.hasCurrentByte();){let i=this.currentByte();if(this.eventEndCheck){if(this.crlfCheck){if(i===iCe){this.crlfCheck=!1,this.consumeCurrentByte();continue}this.crlfCheck=!1}if(i===iCe||i===SZ){i===SZ&&(this.crlfCheck=!0),this.consumeCurrentByte(),this.hasPendingEvent()&&this.processEvent(this.event),this.clearEvent();continue}this.eventEndCheck=!1;continue}if(i===iCe||i===SZ){i===SZ&&(this.crlfCheck=!0);try{this.parseLine(this.readLine(),this.event)}catch(o){n(o);return}this.consumeCurrentByte(),this.eventEndCheck=!0;continue}if(this.maxEventSize>0&&++this.lineLength>this.maxEventSize+7){n(sCe());return}this.advanceCursor()}n()}_destroy(t,r){this.chunks.length=0,this.clearEvent(),super._destroy(t,r)}parseLine(t,r){if(t.length===0)return;let n=t.indexOf(Ygo);if(n===0)return;let i=t.length,o=t.length;if(n!==-1&&(i=n,o=n+1,t[o]===Zgo&&++o),oCe(t,i,two)){if(this.maxEventSize>0&&this.dataLineCount>=this.maxDataLines)throw sCe();let s=t.length-o,a=this.eventFieldSizes.data+(r.data===void 0?0:1)+s;this.setEventFieldSize("data",a);let l=t.toString("utf8",o);r.data===void 0?r.data=l:r.data+=`
5816
5816
  ${l}`,this.dataLineCount++;return}if(oCe(t,i,iwo)){lwo(t,o)&&(this.setEventFieldSize("retry",t.length-o),r.retry=t.toString("utf8",o));return}if(oCe(t,i,nwo)){cwo(t,o)&&(this.setEventFieldSize("id",t.length-o),r.id=t.toString("utf8",o));return}oCe(t,i,rwo)&&o<t.length&&(this.setEventFieldSize("event",t.length-o),r.event=t.toString("utf8",o))}setEventFieldSize(t,r){let n=this.eventSize-this.eventFieldSizes[t]+r;if(this.maxEventSize>0&&n>this.maxEventSize)throw sCe();this.eventSize=n,this.eventFieldSizes[t]=r}processEvent(t){t.retry&&Jgo(t.retry)&&(this.state.reconnectionTime=parseInt(t.retry,10)),t.id&&Kgo(t.id)&&(this.state.lastEventId=t.id),t.data!==void 0&&this.push({type:t.event||"message",options:{data:t.data,lastEventId:this.state.lastEventId,origin:this.state.origin}})}clearEvent(){this.event.data=void 0,this.event.event=void 0,this.event.id=void 0,this.event.retry=void 0,this.eventSize=0,this.dataLineCount=0,this.eventFieldSizes.data=0,this.eventFieldSizes.event=0,this.eventFieldSizes.id=0,this.eventFieldSizes.retry=0}hasPendingEvent(){return this.event.data!==void 0||this.event.event!==void 0||this.event.id!==void 0||this.event.retry!==void 0}hasCurrentByte(){return this.chunkIndex<this.chunks.length&&this.pos<this.chunks[this.chunkIndex].length}currentByte(){return this.chunks[this.chunkIndex][this.pos]}consumeCurrentByte(){this.advanceCursor(),this.syncLineStartToCursor()}advanceCursor(){for(this.pos++;this.chunkIndex<this.chunks.length&&this.pos>=this.chunks[this.chunkIndex].length;)this.chunkIndex++,this.pos=0}syncLineStartToCursor(){this.lineChunkIndex=this.chunkIndex,this.linePos=this.pos,this.lineLength=0,this.dropConsumedChunks()}dropConsumedChunks(){if(this.lineChunkIndex>0){let t=this.lineChunkIndex;this.chunks.splice(0,t),this.lineChunkIndex=0,this.chunkIndex-=t}this.chunkIndex===this.chunks.length&&(this.chunks.length=0,this.chunkIndex=0,this.pos=0,this.lineChunkIndex=0,this.linePos=0)}readLine(){if(this.lineChunkIndex===this.chunkIndex)return this.chunks[this.chunkIndex].subarray(this.linePos,this.pos);let t=[],r=0;for(let n=this.lineChunkIndex;n<=this.chunkIndex;n++){let i=this.chunks[n],o=n===this.lineChunkIndex?this.linePos:0,s=n===this.chunkIndex?this.pos:i.length,a=i.subarray(o,s);r+=a.length,t.push(a)}return Buffer.concat(t,r)}peekBufferedByte(t){let r=this.lineChunkIndex,n=this.linePos;for(;r<this.chunks.length;){let i=this.chunks[r],o=i.length-n;if(t<o)return i[n+t];t-=o,r++,n=0}}discardLeadingBytes(t){for(;t>0&&this.lineChunkIndex<this.chunks.length;){let n=this.chunks[this.lineChunkIndex].length-this.linePos;t<n?(this.linePos+=t,t=0):(t-=n,this.lineChunkIndex++,this.linePos=0)}this.chunkIndex=this.lineChunkIndex,this.pos=this.linePos,this.dropConsumedChunks()}handleBOM(){let t=this.peekBufferedByte(0),r=this.peekBufferedByte(1),n=this.peekBufferedByte(2);return r===void 0?(t===O3[0]||(this.checkBOM=!1),!0):n===void 0?t===O3[0]&&r===O3[1]?!0:(this.checkBOM=!1,!1):(t===O3[0]&&r===O3[1]&&n===O3[2]&&this.discardLeadingBytes(3),this.checkBOM=!1,!this.hasCurrentByte())}};D6r.exports={EventSourceStream:yht}});var G6r=Be((EUs,W6r)=>{"use strict";var{pipeline:dwo}=Re("node:stream"),{fetching:uwo}=uZ(),{makeRequest:pwo}=I3(),{webidl:bE}=Cd(),{EventSourceStream:fwo}=L6r(),{parseMIMEType:hwo}=Nf(),{createFastMessageEvent:mwo}=T3(),{isNetworkError:F6r}=cZ(),{delay:gwo}=wht(),{kEnumerableProperty:ZO}=qr(),{environmentSettingsObject:U6r}=Kh(),{getGlobalDispatcher:wwo}=sZ(),j6r=!1,q6r=3e3,xZ=0,Q6r=1,CZ=2,ywo="anonymous",Awo="use-credentials",M3=class e extends EventTarget{#e={open:null,error:null,message:null};#r=null;#n=!1;#i=xZ;#o=null;#t=null;#s;#a;constructor(t,r={}){super(),bE.util.markAsUncloneable(this);let n="EventSource constructor";bE.argumentLengthCheck(arguments,1,n),j6r||(j6r=!0,process.emitWarning("EventSource is experimental, expect them to change at any time.",{code:"UNDICI-ES"})),t=bE.converters.USVString(t,n,"url"),r=bE.converters.EventSourceInitDict(r,n,"eventSourceInitDict"),this.#s=r.dispatcher,this.#a={lastEventId:"",reconnectionTime:q6r};let i=U6r,o;try{o=new URL(t,i.settingsObject.baseUrl),this.#a.origin=o.origin}catch(l){throw new DOMException(l,"SyntaxError")}this.#r=o.href;let s=ywo;r.withCredentials&&(s=Awo,this.#n=!0);let a={redirect:"follow",keepalive:!0,mode:"cors",credentials:s==="anonymous"?"same-origin":"omit",referrer:"no-referrer"};a.client=U6r.settingsObject,a.headersList=[["accept",{name:"accept",value:"text/event-stream"}]],a.cache="no-store",a.initiator="other",a.urlList=[new URL(this.#r)],this.#o=pwo(a),this.#c()}get readyState(){return this.#i}get url(){return this.#r}get withCredentials(){return this.#n}#c(){if(this.#i===CZ)return;this.#i=xZ;let t={request:this.#o,dispatcher:this.#s},r=n=>{F6r(n)&&(this.dispatchEvent(new Event("error")),this.close()),this.#l()};t.processResponseEndOfBody=r,t.processResponse=n=>{if(F6r(n))if(n.aborted){this.close(),this.dispatchEvent(new Event("error"));return}else{this.#l();return}let i=n.headersList.get("content-type",!0),o=i!==null?hwo(i):"failure",s=o!=="failure"&&o.essence==="text/event-stream";if(n.status!==200||s===!1){this.close(),this.dispatchEvent(new Event("error"));return}this.#i=Q6r,this.dispatchEvent(new Event("open")),this.#a.origin=n.urlList[n.urlList.length-1].origin;let a=new fwo({eventSourceSettings:this.#a,maxEventSize:this.#s.eventSourceOptions?.maxEventSize,push:l=>{this.dispatchEvent(mwo(l.type,l.options))}});dwo(n.body.stream,a,l=>{l?.aborted===!1&&(this.close(),this.dispatchEvent(new Event("error")))})},this.#t=uwo(t)}async#l(){this.#i!==CZ&&(this.#i=xZ,this.dispatchEvent(new Event("error")),await gwo(this.#a.reconnectionTime),this.#i===xZ&&(this.#a.lastEventId.length&&this.#o.headersList.set("last-event-id",this.#a.lastEventId,!0),this.#c()))}close(){bE.brandCheck(this,e),this.#i!==CZ&&(this.#i=CZ,this.#t.abort(),this.#o=null)}get onopen(){return this.#e.open}set onopen(t){this.#e.open&&this.removeEventListener("open",this.#e.open),typeof t=="function"?(this.#e.open=t,this.addEventListener("open",t)):this.#e.open=null}get onmessage(){return this.#e.message}set onmessage(t){this.#e.message&&this.removeEventListener("message",this.#e.message),typeof t=="function"?(this.#e.message=t,this.addEventListener("message",t)):this.#e.message=null}get onerror(){return this.#e.error}set onerror(t){this.#e.error&&this.removeEventListener("error",this.#e.error),typeof t=="function"?(this.#e.error=t,this.addEventListener("error",t)):this.#e.error=null}},H6r={CONNECTING:{__proto__:null,configurable:!1,enumerable:!0,value:xZ,writable:!1},OPEN:{__proto__:null,configurable:!1,enumerable:!0,value:Q6r,writable:!1},CLOSED:{__proto__:null,configurable:!1,enumerable:!0,value:CZ,writable:!1}};Object.defineProperties(M3,H6r);Object.defineProperties(M3.prototype,H6r);Object.defineProperties(M3.prototype,{close:ZO,onerror:ZO,onmessage:ZO,onopen:ZO,readyState:ZO,url:ZO,withCredentials:ZO});bE.converters.EventSourceInitDict=bE.dictionaryConverter([{key:"withCredentials",converter:bE.converters.boolean,defaultValue:()=>!1},{key:"dispatcher",converter:bE.converters.any,defaultValue:()=>wwo()}]);W6r.exports={EventSource:M3,defaultReconnectionTime:q6r}});var J6r=Be((SUs,Xt)=>{"use strict";var bwo=l3(),V6r=T7(),vwo=c3(),Iwo=Vqr(),kwo=d3(),Ewo=Fpt(),Swo=w8r(),xwo=E8r(),z6r=Ln(),lCe=qr(),{InvalidArgumentError:aCe}=z6r,N3=dQr(),Cwo=_7(),Two=bft(),Rwo=GQr(),_wo=kft(),Pwo=aft(),$wo=cxe(),{getGlobalDispatcher:X6r,setGlobalDispatcher:Owo}=sZ(),Mwo=Axe(),Nwo=YSe(),Bwo=ZSe();Object.assign(V6r.prototype,N3);Xt.exports.Dispatcher=V6r;Xt.exports.Client=bwo;Xt.exports.Pool=vwo;Xt.exports.BalancedPool=Iwo;Xt.exports.Agent=kwo;Xt.exports.ProxyAgent=Ewo;Xt.exports.EnvHttpProxyAgent=Swo;Xt.exports.RetryAgent=xwo;Xt.exports.RetryHandler=$wo;Xt.exports.DecoratorHandler=Mwo;Xt.exports.RedirectHandler=Nwo;Xt.exports.createRedirectInterceptor=Bwo;Xt.exports.interceptors={redirect:ZQr(),retry:tHr(),dump:nHr(),dns:sHr()};Xt.exports.buildConnector=Cwo;Xt.exports.errors=z6r;Xt.exports.util={parseHeaders:lCe.parseHeaders,headerNameToString:lCe.headerNameToString};function TZ(e){return(t,r,n)=>{if(typeof r=="function"&&(n=r,r=null),!t||typeof t!="string"&&typeof t!="object"&&!(t instanceof URL))throw new aCe("invalid url");if(r!=null&&typeof r!="object")throw new aCe("invalid opts");if(r&&r.path!=null){if(typeof r.path!="string")throw new aCe("invalid opts.path");let s=r.path;r.path.startsWith("/")||(s=`/${s}`),t=new URL(lCe.parseOrigin(t).origin+s)}else r||(r=typeof t=="object"?t:{}),t=lCe.parseURL(t);let{agent:i,dispatcher:o=X6r()}=r;if(i)throw new aCe("unsupported opts.agent. Did you mean opts.client?");return e.call(o,{...r,origin:t.origin,path:t.search?`${t.pathname}${t.search}`:t.pathname,method:r.method||(r.body?"PUT":"GET")},n)}}Xt.exports.setGlobalDispatcher=Owo;Xt.exports.getGlobalDispatcher=X6r;var Dwo=uZ().fetch;Xt.exports.fetch=async function(t,r=void 0){try{return await Dwo(t,r)}catch(n){throw n&&typeof n=="object"&&Error.captureStackTrace(n),n}};Xt.exports.Headers=GO().Headers;Xt.exports.Response=cZ().Response;Xt.exports.Request=I3().Request;Xt.exports.FormData=D7().FormData;Xt.exports.File=globalThis.File??Re("node:buffer").File;Xt.exports.FileReader=IWr().FileReader;var{setGlobalOrigin:Lwo,getGlobalOrigin:Fwo}=Lut();Xt.exports.setGlobalOrigin=Lwo;Xt.exports.getGlobalOrigin=Fwo;var{CacheStorage:Uwo}=PWr(),{kConstruct:jwo}=Uxe();Xt.exports.caches=new Uwo(jwo);var{deleteCookie:qwo,getCookies:Qwo,getSetCookies:Hwo,setCookie:Wwo}=qWr();Xt.exports.deleteCookie=qwo;Xt.exports.getCookies=Qwo;Xt.exports.getSetCookies=Hwo;Xt.exports.setCookie=Wwo;var{parseMIMEType:Gwo,serializeAMimeType:Vwo}=Nf();Xt.exports.parseMIMEType=Gwo;Xt.exports.serializeAMimeType=Vwo;var{CloseEvent:zwo,ErrorEvent:Xwo,MessageEvent:Jwo}=T3();Xt.exports.WebSocket=N6r().WebSocket;Xt.exports.CloseEvent=zwo;Xt.exports.ErrorEvent=Xwo;Xt.exports.MessageEvent=Jwo;Xt.exports.request=TZ(N3.request);Xt.exports.stream=TZ(N3.stream);Xt.exports.pipeline=TZ(N3.pipeline);Xt.exports.connect=TZ(N3.connect);Xt.exports.upgrade=TZ(N3.upgrade);Xt.exports.MockClient=Two;Xt.exports.MockPool=_wo;Xt.exports.MockAgent=Rwo;Xt.exports.mockErrors=Pwo;var{EventSource:Kwo}=G6r();Xt.exports.EventSource=Kwo});var Oln={};$o(Oln,{buildHostStatusReport:()=>H4o,renderHostStatusReport:()=>W4o});import{homedir as Q4o}from"node:os";async function H4o(e){let t=Qw(e.attachEnv),r=e.chatContext?Qw(e.attachEnv,e.chatContext):t,n=TD({homeDirectory:e.homeDirectory??Q4o(),...e.hostRootDirectory?{hostRootDirectory:e.hostRootDirectory}:{}}),i=await ufe(n),o=i?dfe({heartbeatAt:i.heartbeatAt,pid:i.pid,at:Date.now()}):null;if(!e.probe)return{schemaVersion:"xeno.cli.host-status.v1",mode:t,chatMode:r,rootDirectory:n,lease:i,leaseOwnerGone:o,attach:{attempted:!1,because:"status is a read; pass --probe to actually connect"},providers:null};let s=await rP({clientVersion:e.clientVersion,...e.homeDirectory?{homeDirectory:e.homeDirectory}:{},...e.hostRootDirectory?{hostRootDirectory:e.hostRootDirectory}:{},...e.connectTimeoutMs?{connectTimeoutMs:e.connectTimeoutMs}:{}});if(s.attached){let a=null,l;try{await s.host.client.connect(),a=((await s.host.client.listProviders()).providers??[]).map(d=>({id:d.id,kind:String(d.kind),displayName:d.displayName,availability:String(d.availability),...d.safeUnavailableReason?{unavailableReason:d.safeUnavailableReason}:{},modelCount:d.models?.length??0}))}catch(c){l=c instanceof Error?c.message:String(c),a=null}return await s.host.session.close(),{schemaVersion:"xeno.cli.host-status.v1",mode:t,chatMode:r,rootDirectory:n,lease:i,leaseOwnerGone:o,attach:{attempted:!0,attached:!0},providers:a,...l?{providersError:l}:{}}}return{schemaVersion:"xeno.cli.host-status.v1",mode:t,chatMode:r,rootDirectory:n,lease:i,leaseOwnerGone:o,attach:{attempted:!0,attached:!1,reason:s.reason,detail:s.detail,message:nP(s.reason,s.detail)},providers:null}}function W4o(e){let t=["XENO Agent host"];if(t.push(` attach mode ${e.mode} (${pf}; xeno run)`),t.push(` chat ${e.chatMode==="off"?"runs in this process":e.chatMode==="required"?"runs on the host, or fails":"runs on the host, starting one if none runs"}`),t.push(` lease root ${e.rootDirectory}`),e.lease){let r=e.leaseOwnerGone,n=`instance ${e.lease.instanceId}, pid ${e.lease.pid}, protocol ${e.lease.protocolVersion}`;t.push(r?` host STALE LEASE \u2014 ${n} is not running; it exited without releasing`:` host running \u2014 ${n}`)}else t.push(e.chatMode==="off"?" host none running (the CLI's own agent loop is what runs)":" host none running (a chat starts one when it needs it)");return e.attach.attempted?t.push(e.attach.attached?" attach connected and detached cleanly":` attach refused \u2014 ${e.attach.message}`):t.push(` attach not attempted (${e.attach.because})`),e.providersError?t.push(` lanes could not be read - ${e.providersError}`):e.providers&&(e.providers.length===0?t.push(" lanes none \u2014 the host offers no runtime providers"):(t.push(" lanes"),e.providers.forEach((r,n)=>{let i=n===0?"*":" ";t.push(` ${i} ${r.id} ${r.availability} (${r.kind}, ${r.modelCount} model${r.modelCount===1?"":"s"})`),r.unavailableReason&&t.push(` ${r.unavailableReason}`)}),t.push(" * the lane an attached run uses when it names no provider"),t.push(" a blocked lane reflects the HOST's environment - its credentials and sign-in,"),t.push(" not this CLI's. A host started with an isolated credential root blocks them all."))),t.join(`
5817
5817
  `)}var Mln=ye(()=>{"use strict";pfe();rx()});var Ecn={low:!0,medium:!0,high:!0,xhigh:!0,max:!0},t1=Object.keys(Ecn),Su="ultracode";Yt();import{randomUUID as vte}from"node:crypto";import{existsSync as Lln,mkdirSync as G4o,realpathSync as $vt,statSync as V4o,writeFileSync as z4o}from"node:fs";import{dirname as X4o,isAbsolute as Nln,join as o_e,relative as J4o,resolve as Tg}from"node:path";import{fileURLToPath as K4o}from"node:url";function d0t(e){if(!e.invokedPath)return!1;let t;try{t=e.fileUrlToPath(e.moduleUrl)}catch{return!1}let r=n=>{try{return e.realpath(n)}catch{return n}};return r(e.invokedPath)===r(t)}function u0t(e){return e==="default"?"acceptEdits":e}import{writeFileSync as Fcn}from"node:fs";import{tmpdir as Ucn}from"node:os";import{join as jcn}from"node:path";import{performance as E_e}from"node:perf_hooks";var Nte=process.env.XENO_STARTUP_TRACE==="1",x_e=[];function p0t(){return Nte}function ya(e){Nte&&(x_e.push({phase:e,atMs:S_e(E_e.now())}),C_e())}async function n1(e,t){if(!Nte)return await t();let r=E_e.now();try{return await t()}finally{let n=E_e.now();x_e.push({phase:e,atMs:S_e(n),durationMs:S_e(n-r)}),C_e()}}function f0t(){if(Nte)return C_e(),h0t()}function h0t(){return process.env.XENO_STARTUP_TRACE_FILE?.trim()||jcn(Ucn(),`xeno-startup-trace-${process.pid}.json`)}function C_e(){Fcn(h0t(),`${JSON.stringify({pid:process.pid,node:process.version,marks:x_e},null,2)}
5818
5818
  `)}function S_e(e){return Math.round(e*10)/10}Yp();kw();ec();Yp();kw();import{existsSync as K9o,mkdirSync as $Un,readFileSync as Y9o,rmSync as Z9o,writeFileSync as OUn}from"node:fs";import{homedir as hG}from"node:os";import{dirname as MUn,join as $8t}from"node:path";var xUn="XENO account sign-in is not available on this operating system yet (Windows and Linux only). Use `xeno auth login --api-key`, or set XENO_API_KEY for unattended use.",CUn=new Set(["win32","linux"]);function wS(e=process.platform){return CUn.has(e)?void 0:xUn}var cpe="No system keyring is available, so this sign-in lasts until this process exits. To stay signed in to chat, run a Secret Service keyring (for example gnome-keyring). For unattended API-key execution, use `xeno run`.";fG();function NUn(e){return typeof e=="string"&&/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(e.trim())}function BUn(e){if(!(!NUn(e)||e.length>16384))try{let t=JSON.parse(Buffer.from(e.split(".")[1],"base64url").toString("utf8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}}function DUn(e){let t=BUn(e)?.exp;return typeof t=="number"&&Number.isSafeInteger(t)&&t>0?new Date(t*1e3):void 0}function O8t(e,t=Date.now(),r=6e4){let n=DUn(e);return n?n.getTime()<=t+r:!1}function M8t(e=hG()){return $8t(e,".xeno","credentials.json")}function LUn(e){return $8t(e,".xeno","logout.json")}function tD(e=hG()){let t=LUn(e);$Un(MUn(t),{recursive:!0}),OUn(t,`${JSON.stringify({loggedOutAt:new Date().toISOString()})}
@@ -6612,7 +6612,7 @@ ${n}`}}import{execFileSync as Fdr}from"node:child_process";function qgi(){let e=
6612
6612
  `),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)
6613
6613
  `),r.onOutput(`
6614
6614
  `),{handled:!0}}function xx(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 Jdr(e){let t=["Last Session Summary",`- model: ${e.model}`,`- mode: ${e.mode??"unknown"}`,`- status: ${e.status??"unknown"}`,`- started: ${e.startedAt}`,`- ended: ${e.endedAt}`,`- duration: ${xx(e.durationMs)}`,`- tokens: ${e.tokenUsage.input.toLocaleString()} in / ${e.tokenUsage.output.toLocaleString()} out / ${e.tokenUsage.total.toLocaleString()} total`,`- estimated cost: ${FR(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(`
6615
- `)}function Awi(e){let t=e.replace(/\s+/g," ").trim();return t.length>72?`${t.slice(0,69)}...`:t}async function aAe(e){if(!e.checkpointManager||e.messages.length===0)return null;let t=`Branch before rewind to "${Awi(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}Uo();Ao();var bwi={"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 sKe(e=Pe){return bwi[e]??[]}function vwi(e=Pe){let t=Pt().lastReleaseNotesSeen;return sKe(e).length>0&&t!==e}function iU(e=Pe){go({lastReleaseNotesSeen:e})}function lAe(e){let t=e??Pe,r=sKe(t);return r.length===0?`No release notes available for version ${t}.`:[`Release notes for version ${t}`,"",...r.map(n=>`- ${n}`)].join(`
6615
+ `)}function Awi(e){let t=e.replace(/\s+/g," ").trim();return t.length>72?`${t.slice(0,69)}...`:t}async function aAe(e){if(!e.checkpointManager||e.messages.length===0)return null;let t=`Branch before rewind to "${Awi(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}Uo();Ao();var bwi={"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 sKe(e=Pe){return bwi[e]??[]}function vwi(e=Pe){let t=Pt().lastReleaseNotesSeen;return sKe(e).length>0&&t!==e}function iU(e=Pe){go({lastReleaseNotesSeen:e})}function lAe(e){let t=e??Pe,r=sKe(t);return r.length===0?`No release notes available for version ${t}.`:[`Release notes for version ${t}`,"",...r.map(n=>`- ${n}`)].join(`
6616
6616
  `)}var Iwi=4;function Kdr(e=Pe){if(!vwi(e))return;let t=sKe(e),r=t.slice(0,Iwi),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(`
6617
6617
  `)}Yt();$h();eu();Bz();import{spawn as Swi}from"node:child_process";import{setTimeout as lKe}from"node:timers/promises";import{resolve as pAe}from"node:path";rl();$a();var Zdr="cancel",wf={name:"WorkflowCancel",command:`workflows ${Zdr}`,nativeVerb:Zdr,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 oU(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 eur(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 tur=()=>[wf.description,`Mode: ${wf.mode}; requiresDisplay: ${wf.requiresDisplay}; reversibility: ${wf.reversibility}. Read back with ${wf.readingTools.join(" or ")}.`,"Returns JSON: "+Object.entries(wf.replyFields).map(([e,t])=>`${e}: ${t}`).join(" "),"Cancellation progress: "+Object.entries(wf.cancellationFields).map(([e,t])=>`${e}: ${t}`).join(" ")].join(" ");YL();var dAe=class extends Error{constructor(r,n){super(r);this.code=n;this.name="WorkflowHostRefusal"}code};function cAe(e){throw new dAe(e.error??"The Agent host refused the workflow change.",e.code)}function sU(e){return e.success?e.run??null:e.code==="NOT_FOUND"?null:cAe(e)}function kwi(e){let t=new Set,r=async i=>{if(t.has(i))return;let o=await tP(e,[i]);if(o.granted.length===0&&o.failed.length>0)throw new dAe(`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?cAe(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?cAe(l):l.run},pause:async i=>sU(await n("workflows.pause",{workflowRunId:i})),resume:async i=>sU(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=sU(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)=>sU(await n("workflows.retryChild",{workflowRunId:i,childRunId:o})),skipChild:async(i,o)=>sU(await n("workflows.skipChild",{workflowRunId:i,childRunId:o})),async rerun(i,o){return await r(o),sU(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:cAe(s)}}}function Ewi(){return process.env.XENO_TEST_HOOKS==="1"&&process.env.XENO_TEST_WORKFLOWS==="store"}async function uAe(e,t){if(Ewi())return t(e.local());let{withHostClient:r}=await Promise.resolve().then(()=>(eF(),ZL));return r({clientVersion:e.clientVersion,what:"Workflows"},async n=>t(kwi(n)))}Ao();function Ku(e){process.stdout.write(JSON.stringify(e,null,2)+`
6618
6618
  `)}function xwi(e,t){if(t){Ku(e);return}if(e.ok&&e.definition){process.stdout.write(`Workflow valid: ${e.definition.name}
@@ -10389,25 +10389,25 @@ ${t}`:e.question)}}}function YCr(e){return!!e&&typeof e=="object"&&!Array.isArra
10389
10389
  `),!0):(process.stderr.write(yo("XENO sign-in did not establish current request authority.")),process.exitCode=1,!1)}async function wqi(e){try{if((await Ew()).authenticated)return!0}catch{}return process.stderr.write("XENO account sign-in is required for chat. Run `xeno` in an interactive terminal to sign in, or `xeno login --device`. For unattended API-key execution, use `xeno run`.\n"),process.exitCode=1,!1}async function YTr(e,t,r,n,i,o){let s=qX(e.executionAuthority);if(s){if(e.executionOwnerId)throw new Error("--execution-owner cannot be combined with an execution authority: the authority names the owner from this host's executor token.");return await Nlr(s,t,{...i?{claimHandoffId:i}:{},...o?{onOwnershipLost:o}:{},readContext:()=>yye(Ze.getSessionDir(t))})}return new n_({sessionId:r,...e.executionOwnerId??n?{ownerId:e.executionOwnerId??n}:{},...i?{claimHandoffId:i}:{}})}async function ZTr(e){let t=k8e(),r=process.cwd(),n=e.agentName?.trim()?Wi(e.agentName,r).compiled:e.agentProfile??Wi("assistant",r).compiled,i=e.role??n?.memory.role,o=n?.memory.scope,s=n?Ka(n.capabilities.permissionProfile)??void 0:void 0,a="";yG(r);let l=vit(e.accessibilityMode);$Cr(l),e.accessibilityMode=l;let c=Dpe();if(!process.stdin.isTTY){await tTr(e);return}let d=l==="plain"||!!e.lineInput||process.env.XENO_LINE_INPUT==="1"||!e.rawTui&&c.recommendedInputMode==="line",u=zrr(),p=!d&&!u&&!!e.peerLaunch&&!$Qt()&&(await QI()).available,f;if(upe()&&!wS(process.platform))p||(await uG().catch(()=>{}),f=Ew().then(Ut=>Ut.authenticated,()=>!1),await new Promise(Ut=>setImmediate(Ut)));else if(!await n1("auth-sign-in-check",()=>Nit(e)))return;if(d){if(f&&!await f&&!await n1("auth-sign-in-check",()=>Nit(e)))return;await tTr(e);return}if(!q0(r)){if(!(await Yrr(r)).trusted){process.stderr.write(pD()),process.exitCode=0;return}nae(r,!0)}if(p&&e.peerLaunch){await t(),await sI(),await Jrr({cwd:r,...e.peerLaunch,apiKey:e.apiKey,initialSessionId:typeof e.resume=="string"?e.resume:void 0});return}let h=u?new Nge(u):void 0,m,g=!1,w=()=>{},y=new Promise(Ut=>{w=Ut}),A=Promise.resolve(),b=0,I=Date.now(),v,k,S,x,E,C,_,P,R,$=null,O,N=()=>{},j=()=>{},D=async()=>{},B=async()=>{},q,L={},U=!1,re,ce={},ne=new Set,ie=oit(bt),he=async(Ut,Wa)=>{let ki=`session-${Ut.meta.id}`;if(re?.sessionId===ki&&!Wa){await re.assertOwned();return}let Rr=await YTr(e,Ut.meta.id,ki,re?.ownerId,Wa,qe=>{if(re===Rr)try{ce.current?.(qe)}catch{}});try{await n1("execution-lease",()=>Rr.start())}catch(qe){throw await Rr.stop(),qe}let Hr=re;re=Rr,await Hr?.stop()},Se=!1,we=null,Te=null,Ee=null,Ke,De,yt,Ve=null,nt,ze=new Promise(Ut=>{nt=Ut}),Qr=iit(),Ms,ua,ti=()=>(Ms??=Promise.resolve().then(vc),Ms),vc=async()=>{Se=!0,f&&await Promise.race([f.catch(()=>!1),new Promise(Ut=>setTimeout(Ut,1e4).unref())]);try{await _j(ait({peerRuntime:()=>Ke?.stop(),artifactRuntime:()=>De?.stop(),stopHooks:async()=>{L.current&&await lb(L.current,void 0,{command:"chat",mode:"tui"})},timers:()=>{we&&clearInterval(we),we=null,Te&&clearInterval(Te),Te=null,yt&&clearInterval(yt),yt=void 0},directShell:()=>Ee?.interrupt(),backgroundProcesses:()=>ie.cleanup(),imagePreviews:[...ne].map(Ut=>()=>sit(Ut,yB)),agentCredential:()=>Ve?.close(),mcp:()=>j(),providerCockpit:()=>q?.close(),executionLease:()=>re?.stop(),sessionRuntime:()=>DR({sessionManager:k,auditLogger:C,modelUsage:ua?.()}),computerHost:t,accountHost:sI,terminal:()=>v?.cleanup(),processListeners:()=>{h?.close(),Qr.dispose()}}))}catch(Ut){throw process.exitCode=1,process.stderr.write(`${Yxr(Ut)}
10390
10390
  `),Ut}finally{nt()}},bl=0,Jf=1500;Qr.on("beforeExit",()=>{ti().catch(()=>{process.exitCode=1})}),Qr.on("SIGINT",async()=>{let Ut=Date.now();if(Ut-bl>Jf){bl=Ut,process.stderr.write(G.dim(`
10391
10391
  Press Ctrl+C again to exit.
10392
- `));return}try{await ti(),process.exit(130)}catch{process.exit(1)}}),Qr.on("SIGTERM",async()=>{try{await ti(),process.exit(143)}catch{process.exit(1)}}),process.platform==="win32"&&Qr.on("SIGBREAK",async()=>{try{await ti(),process.exit(0)}catch{process.exit(1)}});try{let Ut=new xt;ya("before-screen"),v=new kD({model:e.model,safeMode:e.safeMode,effort:e.effort,permissionMode:e.resume?"plan":e.permissionMode,executionMode:e.executionMode??"agent",delegationEnabled:!1,...n?{agentProfile:{label:n.profile.presentation.label,glyph:n.profile.presentation.glyph}}:{},maxContextTokens:0,statusLineCommand:process.env.XENO_STATUS_LINE_COMMAND,statusLineStartedAtMs:I,mentionCompletions:()=>JTr(O),workflowCompletions:()=>Ut.listDefinitions(process.cwd()).slice(0,50).map(T=>({name:T.name,description:T.description||"Saved workflow"})),onToggleDelegation:T=>{fa(T),Bg()},onPasteImage:async()=>{if(!P)throw new Error("A session directory is required for private clipboard attachments.");return lCr({directory:my(P,"attachments","clipboard")})},onVoiceDictation:()=>cJ(),onOpenRewind:async()=>{await YM()},onOpenAgentSession:T=>h_e(T),onAttachAgentSession:T=>Xvt(T),onOpenDelegationAgent:T=>Vvt(T),onStopDelegationAgent:T=>{let F=Rg.get(T);!F||F.finished||Kf.cancel(F.taskId,"stopped from the delegation dock")&&v.showTransientActivityNotice(`Stopping ${T}`)},onStopAgentSession:T=>lcn(T),onOpenWorkflow:T=>ccn(T),onStopWorkflow:T=>dcn(T),onOutputAction:async T=>{if(T.action==="restore"){let z=Yq(T.userMessageOrdinal);if(z<0){v.showTransientActivityNotice("Could not find that user turn");return}let ae=GT(),xe=ae?await ae.inspectAtOrAfter(z):null,Ae=[],V=Ie.messages.length-z;if(Ae.push(`${G.dim("Messages to remove:")} ${V}`),Ae.push(""),!xe?.hadRestorePoints)Ae.push(`${G.dim("Workspace:")} conversation only (no file restore points)`);else{Ae.push(`${G.dim("Workspace:")} ${xe.exactWorkspaceRestore?"exact restore available":"partial restore (some tools untracked)"}`),xe.unsupportedTools.length>0&&Ae.push(`${G.dim("Untracked tools:")} ${xe.unsupportedTools.join(", ")}`);let oe=[],ue=[];for(let ct of xe.points)for(let Gt of ct.mutations)Gt.existedBefore?oe.includes(Gt.relativePath)||oe.push(Gt.relativePath):ue.includes(Gt.relativePath)||ue.push(Gt.relativePath);if(oe.length>0){Ae.push(""),Ae.push(G.accent("Files to revert:"));for(let ct of oe)Ae.push(` ${G.dim("~")} ${ct}`)}if(ue.length>0){Ae.push(""),Ae.push(G.accent("Files to remove (created during turn):"));for(let ct of ue)Ae.push(` ${G.dim("+")} ${ct}`)}oe.length===0&&ue.length===0&&(Ae.push(""),Ae.push(G.dim("No tracked file changes.")));let pt=xe.filePreviews??[];if(pt.length>0){Ae.push(""),Ae.push(G.accent("Diff preview:"));for(let ct of pt.slice(0,3)){let Gt=ct.action==="remove"?"remove":"revert";Ae.push(`${G.dim(Gt)} ${ct.relativePath}${ct.truncated?" (truncated)":""}`);for(let ft of ct.lines.slice(0,24))Ae.push(` ${ft}`);ct.lines.length>24&&Ae.push(` ...and ${ct.lines.length-24} more diff lines`)}pt.length>3&&Ae.push(`...and ${pt.length-3} more file diff previews`)}}await v.infoPanel({title:"Restore Details",subtitle:`Rewind to before: ${T.text}`,lines:Ae,footerHint:"Enter to restore \u2022 Esc to cancel"}),(await YE(T.userMessageOrdinal)).ok&&Qe(`Restored to before "${T.text}"`);return}if(!(await YE(T.userMessageOrdinal)).ok)return;let H=T.action==="edit"?"Edit":"Retry";if(Qe(`${H}: restored to before "${T.text}"`),T.action==="edit"){v.setInputText(T.text,{cursor:"end",escCancelable:!0});return}v.setInputText(T.text,{cursor:"end",escCancelable:!1}),v.handleEnter()},onFixTypo:T=>H3i(T,e.apiKey),onRewriteAs:(T,F,H)=>W3i(T,F,H,e.apiKey),onSubmit:nTr.bind(T=>{b++;let F=async()=>{if(/^\/(?:new-subchat|subchats)(?:\s|$)/i.test(T)){if(!h){v.writeError("Peer sessions require the fullscreen terminal cockpit.");return}let V=T.match(/^\/subchats\s+limit\s+(\d+)\s*$/i);V?(await h.request("limit",{limit:Number(V[1])}),v.writeInfo(`Peer turn concurrency set to ${V[1]}.`)):await h.request(/^\/new-subchat\s*$/i.test(T)?"new":"menu");return}if(!/^\/(?:exit|quit)(?:\s|$)/i.test(T)&&!/^\/handoff\s+(?:status|cancel|claim)(?:\s|$)/i.test(T))try{await re?.assertOwned()}catch(V){v.writeError(`Execution is detached: ${V instanceof Error?V.message:String(V)}`);return}let ae=$ge(T);if(ae!==null){if(!ae.trim()||!await t8())return;if(!Ee){v.writeError("Direct shell runtime is not initialized");return}let V=await Ee.run(ae);V.denied&&v.writeError(V.denied);let J=v.takeQueuedMessage();J&&setTimeout(()=>{v.setInputText(J,{cursor:"end",escCancelable:!1}),v.handleEnter()},50);return}if(UKe(T)&&Iit(T)===void 0){if((/^\/(?:goal|loop|rename)(?:\s|$)/i.test(T)||/^\/compact\s*$/i.test(T))&&!await t8())return;let V=await OKe(T,{cwd:r,model:e.model,reasoningEffort:e.effort,permissionMode:e.permissionMode,executionMode:qe,sessionId:k?.meta.id,sessionName:k?.meta.name,onRenameSession:async J=>{if(q?.routesTurnsThroughHost)throw new Error("Rename this provider session from its owning host.");await re?.assertOwned();let oe=await hze(k,J);return v.setSessionName(oe),hr.syncPresence(),oe},peerRuntime:hr,artifactRuntime:wu,costDisplay:v.getCostDisplay(),safeMode:e.safeMode,sessionDir:k?Ze.getSessionDir(k.meta.id):void 0,parentSessionId:k?.meta.id??Xr,memoryManager:x,checkpointManager:S,sessionManager:k,auditLogger:C,mcpManager:O,refreshMcpTools:N,messages:g?Ie.messages:[],onOutput:J=>v.writeOutput(J),onContextCompacted:async J=>{if(!k)throw new Error("A durable CLI session is required to compact context.");await k.transcript.append({type:"context_compressed",data:J})},onAttachProcess:async J=>{if(!zn){v.writeError("ATTACH_REQUIRES_TTY: terminal attach runtime is not initialized");return}let oe=await zn.attach(J);oe.ok||v.writeError(oe.message)},reloadConfig:It,onHelp:async()=>{await v.helpPanel()},onPanel:async J=>{await v.infoPanel(J)},onActionPicker:async J=>await v.actionPicker(J),buildSystemPrompt:Pp,toolDefinitions:()=>xi.getDefinitions(),requestToolDefinitions:()=>qe==="chatOnly"?[]:xi.getDefinitionsForRequest(),maxContextTokens:g?Ie.modelContextWindow:0,contextBudgetSource:HK?.source,hookRuntime:L.current,outputStyles:Fv,turnRestoreManager:$,providerCockpit:q,executionLeaseSession:re,onBeforeExecutionHandoff:ncn,onClaimExecutionHandoff:async J=>{if(!k)throw new Error("No durable session to reclaim");await Jy(k.meta.id,J)},onExecutionHandoffCancelled:async()=>{if(!k)throw new Error("No durable session to resume");await Jy(k.meta.id,void 0,!0)},onProviderCockpitChanged:J=>{let oe=J.kind==="selected"||J.kind==="reconciled"?J.lane:J.kind==="status"?J.activeLane:J.kind==="sessions"?J.lanes.find(ue=>ue.laneId===J.activeLaneId):void 0;if(oe){let ue=oe.modelDisplayName??oe.modelId;v.setModel(`${oe.providerDisplayName??oe.runtimeProviderId}${ue?` / ${ue}`:""}`),v.setProviderSessionStatus({provider:oe.providerDisplayName??oe.runtimeProviderId,...ue?{model:ue}:{},mode:oe.workspaceEpoch.wireMode,scope:oe.workspaceEpoch.kind,laneId:oe.laneId,state:oe.status})}}});if(V.handled){if(V.messages&&(Ie.messages=V.messages,await k?.updateMessageCount(V.messages.length)),V.resumeSessionId){await Jy(V.resumeSessionId);return}V.triggerTurnPrompt&&setTimeout(()=>{v.setInputText(V.triggerTurnPrompt,{cursor:"end",escCancelable:!1}),v.handleEnter()},50);return}}if(T==="/login"||T.startsWith("/login ")){let J=T.slice(6).trim().split(/\s+/).filter(Boolean)[0]?.toLowerCase();if(J==="status"){let oe=await Sw({validate:!0});v.writeInfo(aI(oe).trimEnd());return}if(J==="api-key"){v.writeOutput(yo("Credential paste is retired. Set XENO_API_KEY before starting unattended execution, or use XENO sign-in."));return}if(J==="help"){v.writeInfo("Xeno auth\nUse `/login` to launch the sign-in welcome screen.\nUse `/login status` to inspect local auth.\nUse XENO_API_KEY for nonpersisted unattended execution.");return}if(!J){let oe=await v.actionPicker({title:"Xeno Sign In",description:"Choose a sign-in method. The chat UI stays attached while Xeno waits for completion.",options:[{value:"browser",label:"Browser Login",detail:"Open xenostudio.ai and authorize this CLI session"},{value:"device-code",label:"Device Code",detail:"Use a one-time code for remote/headless terminals"},{value:"status",label:"Auth Status",detail:"Inspect the current local auth state"}],selectedIndex:0});if(!oe){v.writeInfo("Sign-in cancelled.");return}if(oe==="status"){let ft=await Sw({validate:!0});v.writeInfo(aI(ft).trimEnd());return}let ue=ft=>new Promise(fe=>{if(ft.aborted){fe("complete");return}ft.addEventListener("abort",()=>fe("complete"),{once:!0})});v.writeInfo(oe==="browser"?"Starting browser sign-in...":"Starting device-code sign-in...");let{runBrowserFlow:pt,runDeviceCodeFlow:ct}=await Promise.resolve().then(()=>(UK(),SIe)),Gt=oe==="browser"?await pt({authBaseURL:li,apiBaseURL:e.baseURL,silent:!0,waitForCancel:ue,onStarted:ft=>{v.writeInfo(["Browser sign-in started.",`Open: ${ft.auth_url}`,`Local callback: ${ft.redirect_uri}`].join(`
10392
+ `));return}try{await ti(),process.exit(130)}catch{process.exit(1)}}),Qr.on("SIGTERM",async()=>{try{await ti(),process.exit(143)}catch{process.exit(1)}}),process.platform==="win32"&&Qr.on("SIGBREAK",async()=>{try{await ti(),process.exit(0)}catch{process.exit(1)}});try{let Ut=new xt;ya("before-screen"),v=new kD({model:e.model,safeMode:e.safeMode,effort:e.effort,permissionMode:e.resume?"plan":e.permissionMode,executionMode:e.executionMode??"agent",delegationEnabled:!1,...n?{agentProfile:{label:n.profile.presentation.label,glyph:n.profile.presentation.glyph}}:{},maxContextTokens:0,statusLineCommand:process.env.XENO_STATUS_LINE_COMMAND,statusLineStartedAtMs:I,mentionCompletions:()=>JTr(O),workflowCompletions:()=>Ut.listDefinitions(process.cwd()).slice(0,50).map(T=>({name:T.name,description:T.description||"Saved workflow"})),onToggleDelegation:T=>{fa(T),Bg()},onPasteImage:async()=>{if(!P)throw new Error("A session directory is required for private clipboard attachments.");return lCr({directory:my(P,"attachments","clipboard")})},onVoiceDictation:()=>cJ(),onOpenRewind:async()=>{await YM()},onOpenAgentSession:T=>h_e(T),onAttachAgentSession:T=>Xvt(T),onOpenDelegationAgent:T=>Vvt(T),onStopDelegationAgent:T=>{let F=Rg.get(T);!F||F.finished||Kf.cancel(F.taskId,"stopped from the delegation dock")&&v.showTransientActivityNotice(`Stopping ${T}`)},onStopAgentSession:T=>lcn(T),onOpenWorkflow:T=>ccn(T),onStopWorkflow:T=>dcn(T),onOutputAction:async T=>{if(T.action==="restore"){let z=Yq(T.userMessageOrdinal);if(z<0){v.showTransientActivityNotice("Could not find that user turn");return}let ae=GT(),xe=ae?await ae.inspectAtOrAfter(z):null,Ae=[],V=Ie.messages.length-z;if(Ae.push(`${G.dim("Messages to remove:")} ${V}`),Ae.push(""),!xe?.hadRestorePoints)Ae.push(`${G.dim("Workspace:")} conversation only (no file restore points)`);else{Ae.push(`${G.dim("Workspace:")} ${xe.exactWorkspaceRestore?"exact restore available":"partial restore (some tools untracked)"}`),xe.unsupportedTools.length>0&&Ae.push(`${G.dim("Untracked tools:")} ${xe.unsupportedTools.join(", ")}`);let oe=[],ue=[];for(let ct of xe.points)for(let Vt of ct.mutations)Vt.existedBefore?oe.includes(Vt.relativePath)||oe.push(Vt.relativePath):ue.includes(Vt.relativePath)||ue.push(Vt.relativePath);if(oe.length>0){Ae.push(""),Ae.push(G.accent("Files to revert:"));for(let ct of oe)Ae.push(` ${G.dim("~")} ${ct}`)}if(ue.length>0){Ae.push(""),Ae.push(G.accent("Files to remove (created during turn):"));for(let ct of ue)Ae.push(` ${G.dim("+")} ${ct}`)}oe.length===0&&ue.length===0&&(Ae.push(""),Ae.push(G.dim("No tracked file changes.")));let pt=xe.filePreviews??[];if(pt.length>0){Ae.push(""),Ae.push(G.accent("Diff preview:"));for(let ct of pt.slice(0,3)){let Vt=ct.action==="remove"?"remove":"revert";Ae.push(`${G.dim(Vt)} ${ct.relativePath}${ct.truncated?" (truncated)":""}`);for(let ft of ct.lines.slice(0,24))Ae.push(` ${ft}`);ct.lines.length>24&&Ae.push(` ...and ${ct.lines.length-24} more diff lines`)}pt.length>3&&Ae.push(`...and ${pt.length-3} more file diff previews`)}}await v.infoPanel({title:"Restore Details",subtitle:`Rewind to before: ${T.text}`,lines:Ae,footerHint:"Enter to restore \u2022 Esc to cancel"}),(await YE(T.userMessageOrdinal)).ok&&Qe(`Restored to before "${T.text}"`);return}if(!(await YE(T.userMessageOrdinal)).ok)return;let H=T.action==="edit"?"Edit":"Retry";if(Qe(`${H}: restored to before "${T.text}"`),T.action==="edit"){v.setInputText(T.text,{cursor:"end",escCancelable:!0});return}v.setInputText(T.text,{cursor:"end",escCancelable:!1}),v.handleEnter()},onFixTypo:T=>H3i(T,e.apiKey),onRewriteAs:(T,F,H)=>W3i(T,F,H,e.apiKey),onSubmit:nTr.bind(T=>{b++;let F=async()=>{if(/^\/(?:new-subchat|subchats)(?:\s|$)/i.test(T)){if(!h){v.writeError("Peer sessions require the fullscreen terminal cockpit.");return}let V=T.match(/^\/subchats\s+limit\s+(\d+)\s*$/i);V?(await h.request("limit",{limit:Number(V[1])}),v.writeInfo(`Peer turn concurrency set to ${V[1]}.`)):await h.request(/^\/new-subchat\s*$/i.test(T)?"new":"menu");return}if(!/^\/(?:exit|quit)(?:\s|$)/i.test(T)&&!/^\/handoff\s+(?:status|cancel|claim)(?:\s|$)/i.test(T))try{await re?.assertOwned()}catch(V){v.writeError(`Execution is detached: ${V instanceof Error?V.message:String(V)}`);return}let ae=$ge(T);if(ae!==null){if(!ae.trim()||!await t8())return;if(!Ee){v.writeError("Direct shell runtime is not initialized");return}let V=await Ee.run(ae);V.denied&&v.writeError(V.denied);let J=v.takeQueuedMessage();J&&setTimeout(()=>{v.setInputText(J,{cursor:"end",escCancelable:!1}),v.handleEnter()},50);return}if(UKe(T)&&Iit(T)===void 0){if((/^\/(?:goal|loop|rename)(?:\s|$)/i.test(T)||/^\/compact\s*$/i.test(T))&&!await t8())return;let V=await OKe(T,{cwd:r,model:e.model,reasoningEffort:e.effort,permissionMode:e.permissionMode,executionMode:qe,sessionId:k?.meta.id,sessionName:k?.meta.name,onRenameSession:async J=>{if(q?.routesTurnsThroughHost)throw new Error("Rename this provider session from its owning host.");await re?.assertOwned();let oe=await hze(k,J);return v.setSessionName(oe),hr.syncPresence(),oe},peerRuntime:hr,artifactRuntime:wu,costDisplay:v.getCostDisplay(),safeMode:e.safeMode,sessionDir:k?Ze.getSessionDir(k.meta.id):void 0,parentSessionId:k?.meta.id??Xr,memoryManager:x,checkpointManager:S,sessionManager:k,auditLogger:C,mcpManager:O,refreshMcpTools:N,messages:g?Ie.messages:[],onOutput:J=>v.writeOutput(J),onContextCompacted:async J=>{if(!k)throw new Error("A durable CLI session is required to compact context.");await k.transcript.append({type:"context_compressed",data:J})},onAttachProcess:async J=>{if(!zn){v.writeError("ATTACH_REQUIRES_TTY: terminal attach runtime is not initialized");return}let oe=await zn.attach(J);oe.ok||v.writeError(oe.message)},reloadConfig:It,onHelp:async()=>{await v.helpPanel()},onPanel:async J=>{await v.infoPanel(J)},onActionPicker:async J=>await v.actionPicker(J),buildSystemPrompt:Pp,toolDefinitions:()=>xi.getDefinitions(),requestToolDefinitions:()=>qe==="chatOnly"?[]:xi.getDefinitionsForRequest(),maxContextTokens:g?Ie.modelContextWindow:0,contextBudgetSource:HK?.source,hookRuntime:L.current,outputStyles:Fv,turnRestoreManager:$,providerCockpit:q,executionLeaseSession:re,onBeforeExecutionHandoff:ncn,onClaimExecutionHandoff:async J=>{if(!k)throw new Error("No durable session to reclaim");await Jy(k.meta.id,J)},onExecutionHandoffCancelled:async()=>{if(!k)throw new Error("No durable session to resume");await Jy(k.meta.id,void 0,!0)},onProviderCockpitChanged:J=>{let oe=J.kind==="selected"||J.kind==="reconciled"?J.lane:J.kind==="status"?J.activeLane:J.kind==="sessions"?J.lanes.find(ue=>ue.laneId===J.activeLaneId):void 0;if(oe){let ue=oe.modelDisplayName??oe.modelId;v.setModel(`${oe.providerDisplayName??oe.runtimeProviderId}${ue?` / ${ue}`:""}`),v.setProviderSessionStatus({provider:oe.providerDisplayName??oe.runtimeProviderId,...ue?{model:ue}:{},mode:oe.workspaceEpoch.wireMode,scope:oe.workspaceEpoch.kind,laneId:oe.laneId,state:oe.status})}}});if(V.handled){if(V.messages&&(Ie.messages=V.messages,await k?.updateMessageCount(V.messages.length)),V.resumeSessionId){await Jy(V.resumeSessionId);return}V.triggerTurnPrompt&&setTimeout(()=>{v.setInputText(V.triggerTurnPrompt,{cursor:"end",escCancelable:!1}),v.handleEnter()},50);return}}if(T==="/login"||T.startsWith("/login ")){let J=T.slice(6).trim().split(/\s+/).filter(Boolean)[0]?.toLowerCase();if(J==="status"){let oe=await Sw({validate:!0});v.writeInfo(aI(oe).trimEnd());return}if(J==="api-key"){v.writeOutput(yo("Credential paste is retired. Set XENO_API_KEY before starting unattended execution, or use XENO sign-in."));return}if(J==="help"){v.writeInfo("Xeno auth\nUse `/login` to launch the sign-in welcome screen.\nUse `/login status` to inspect local auth.\nUse XENO_API_KEY for nonpersisted unattended execution.");return}if(!J){let oe=await v.actionPicker({title:"Xeno Sign In",description:"Choose a sign-in method. The chat UI stays attached while Xeno waits for completion.",options:[{value:"browser",label:"Browser Login",detail:"Open xenostudio.ai and authorize this CLI session"},{value:"device-code",label:"Device Code",detail:"Use a one-time code for remote/headless terminals"},{value:"status",label:"Auth Status",detail:"Inspect the current local auth state"}],selectedIndex:0});if(!oe){v.writeInfo("Sign-in cancelled.");return}if(oe==="status"){let ft=await Sw({validate:!0});v.writeInfo(aI(ft).trimEnd());return}let ue=ft=>new Promise(fe=>{if(ft.aborted){fe("complete");return}ft.addEventListener("abort",()=>fe("complete"),{once:!0})});v.writeInfo(oe==="browser"?"Starting browser sign-in...":"Starting device-code sign-in...");let{runBrowserFlow:pt,runDeviceCodeFlow:ct}=await Promise.resolve().then(()=>(UK(),SIe)),Vt=oe==="browser"?await pt({authBaseURL:li,apiBaseURL:e.baseURL,silent:!0,waitForCancel:ue,onStarted:ft=>{v.writeInfo(["Browser sign-in started.",`Open: ${ft.auth_url}`,`Local callback: ${ft.redirect_uri}`].join(`
10393
10393
  `))},log:ft=>v.writeOutput(ft)}):await ct({authBaseURL:li,apiBaseURL:e.baseURL,silent:!0,waitForCancel:ue,onStarted:ft=>{v.writeInfo(["Device-code sign-in started.",`Open: ${ft.verification_url}`,`Code: ${ft.formattedUserCode}`,"Do not share this code."].join(`
10394
- `))},log:ft=>v.writeOutput(ft)});if(Gt.kind==="success"){e.apiKey="",Lit(Ie,"");let ft=Gt.user?.email;v.writeInfo(ft?`Signed in as ${ft}.`:"Signed in to XENO.")}else Gt.kind==="error"||Gt.kind==="timeout"?v.writeOutput(yo(Gt.message)):v.writeInfo("Sign-in cancelled.");return}v.writeOutput(yo("Usage: /login [status|api-key <key>]"));return}if((T==="/logout"||T.startsWith("/logout "))&&(await(await Cl()).signOutLocal(),mG(),rD(),tD(),go({apiKey:void 0}),e.apiKey=void 0,Lit(Ie,void 0),await ti(),v.cleanup(),process.stdout.write("Signed out. Run `xeno` to sign in again.\n"),process.exit(0)),T==="/bg"||T.startsWith("/bg ")){let V=T.slice(3).trim(),J=V?ud(V,{surface:"background"}):null;if(J){v.writeError(J.message);return}try{if(!await t8())return;if(!k)throw new Error("The foreground session is not available for background transfer.");await k.transcript.flush();let oe=k.meta.id,ue=await k.transcript.read(),pt=await Oxr({sessionId:oe,transcriptEvents:ue,...V?{prompt:V}:{},cwd:r,model:e.model,...e.effort?{effort:e.effort}:{},permissionMode:e.permissionMode,executionMode:qe,...e.executionSecurity?{executionSecurity:e.executionSecurity}:{},name:e.agentName??"Background"});await ti(),v.cleanup(),await Ze.delete(oe),process.stdout.write(`Backgrounded current session ${pt.record.sessionId}${V?" with queued input":""}.
10394
+ `))},log:ft=>v.writeOutput(ft)});if(Vt.kind==="success"){e.apiKey="",Lit(Ie,"");let ft=Vt.user?.email;v.writeInfo(ft?`Signed in as ${ft}.`:"Signed in to XENO.")}else Vt.kind==="error"||Vt.kind==="timeout"?v.writeOutput(yo(Vt.message)):v.writeInfo("Sign-in cancelled.");return}v.writeOutput(yo("Usage: /login [status|api-key <key>]"));return}if((T==="/logout"||T.startsWith("/logout "))&&(await(await Cl()).signOutLocal(),mG(),rD(),tD(),go({apiKey:void 0}),e.apiKey=void 0,Lit(Ie,void 0),await ti(),v.cleanup(),process.stdout.write("Signed out. Run `xeno` to sign in again.\n"),process.exit(0)),T==="/bg"||T.startsWith("/bg ")){let V=T.slice(3).trim(),J=V?ud(V,{surface:"background"}):null;if(J){v.writeError(J.message);return}try{if(!await t8())return;if(!k)throw new Error("The foreground session is not available for background transfer.");await k.transcript.flush();let oe=k.meta.id,ue=await k.transcript.read(),pt=await Oxr({sessionId:oe,transcriptEvents:ue,...V?{prompt:V}:{},cwd:r,model:e.model,...e.effort?{effort:e.effort}:{},permissionMode:e.permissionMode,executionMode:qe,...e.executionSecurity?{executionSecurity:e.executionSecurity}:{},name:e.agentName??"Background"});await ti(),v.cleanup(),await Ze.delete(oe),process.stdout.write(`Backgrounded current session ${pt.record.sessionId}${V?" with queued input":""}.
10395
10395
  `),process.stdout.write(`Attach: xeno attach ${pt.record.sessionId}
10396
10396
  `),process.exit(0)}catch(oe){v.writeOutput(yo(oe instanceof Error?oe.message:String(oe)))}return}if(T==="/attach"||T.startsWith("/attach ")){let V=T.slice(7).trim();if(!V){v.focusAgentSessionDock()||v.writeInfo("No background agents to open. Start one, then use /attach <name or number>.");return}await Xvt(V);return}if(T==="/open"||T.startsWith("/open ")){let V=T.slice(5).trim(),J=V?vC(r,V):r,oe=process.platform==="win32"?"Explorer":process.platform==="darwin"?"Finder":"file manager";Qe(`Opening ${J} in ${oe}...`);try{let ue=await _Tr(J);nr(T,`Opened ${J} in ${ue}`)}catch(ue){v.writeOutput(yo(`Failed to open folder: ${ue instanceof Error?ue.message:String(ue)}`))}return}if(T==="/exit"||T==="/quit"){await ti(),v.cleanup(),process.stderr.write(pD()),process.exitCode=0;return}if(T==="/clear"){et.cancelContinuationsForOwner(Pd()),Ie.clearHistory(),v.clear(),v.writeOutput(XR(Pe,Uj(e),void 0,e.executionMode==="chatOnly"?"chat":"agent")),Qe("Cleared chat history"),await pe.discardPending("the conversation was cleared");return}if(T==="/tokens"||T==="/cost"){v.writeInfo(jv());return}if(T==="/help"){await v.helpPanel();return}if(T==="/export"||T.startsWith("/export ")){let V=T.slice(8).trim(),J=Ie.messages;if(!V)await Zln();else if(V==="json"){let oe=JSON.stringify(J,null,2);v.writeOutput(`
10397
10397
  `+oe+`
10398
10398
  `)}else if(V&&V!=="md"){let oe=await import("node:fs"),ue=Bj(J,e.model);oe.writeFileSync(V,ue,"utf-8"),v.writeInfo(`Exported to: ${V}`)}else{let oe=Bj(J,e.model);v.writeOutput(`
10399
10399
  `+oe+`
10400
- `)}return}if(T==="/save"){let V=rh(),J=C6(null,Ie.messages,e.model,V.total);v.writeInfo(`Session saved: ${J}`);return}if(T.trim()==="/sessions purge"){try{await Qv()}catch(V){let J=V instanceof Error?V.message:String(V);v.writeInfo(G.red(`? Failed to purge sessions: ${J}`))}return}if(T==="/sessions"){try{let V=await qv();if(!V)return;V==="list"?await Bp():await Qv()}catch(V){let J=V instanceof Error?V.message:String(V);v.writeInfo(G.red(`? Failed to load sessions: ${J}`))}return}if(T==="/resume"){try{let V=await Qt({workingDirectory:r,allRoles:!0});if(V.length===0){v.writeInfo("No sessions found in this workspace");return}let J=V.map(ue=>({value:ue.meta.id,title:ue.preview,meta:ue.metaLine})),oe=await v.sessionPicker({title:"Resume Session",description:"Search sessions...",options:J,confirmLabel:"Enter to resume"});oe&&await Jy(oe)}catch(V){let J=V instanceof Error?V.message:String(V);v.writeInfo(G.red(`? Failed to resume session: ${J}`))}return}if(T.startsWith("/resume ")){let V=T.slice(8).trim();if(!V){v.writeInfo(G.red("Usage: /resume <session-id>"));return}await Jy(V);return}let xe=Iit(T);if(xe!==void 0){let V=xe,J=Pt(),oe,ue=0,pt=!0;try{if(oe=LIe("git rev-parse --abbrev-ref HEAD",{stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim()||void 0,oe){try{let Cn=LIe(`git rev-list --left-right --count origin/${oe}...${oe}`,{stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim(),[,Od]=Cn.split(/\s+/).map(Number);ue=Od||0}catch{}pt=LIe("git status --porcelain",{stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim().length===0}}catch{oe=void 0}let ct;try{let ur=LIe("git diff --shortstat HEAD~1 HEAD",{stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim(),Cn=ur.match(/(\d+)\s+files? changed/),Od=ur.match(/(\d+)\s+insertions?\(\+\)/),Ky=ur.match(/(\d+)\s+deletions?\(-\)/);ct={filesChanged:Cn?parseInt(Cn[1],10):0,insertions:Od?parseInt(Od[1],10):0,deletions:Ky?parseInt(Ky[1],10):0}}catch{ct=void 0}let Gt=await ywe().catch(()=>null),ft=I||Date.now(),fe=Math.max(0,Date.now()-ft),St=ur=>{let Cn=Math.floor(ur/1e3);if(Cn<60)return`${Cn}s`;let Od=Math.floor(Cn/60),Ky=Cn%60;if(Od<60)return`${Od}m ${Ky}s`;let nh=Math.floor(Od/60),ZM=Od%60;return`${nh}h ${ZM}m`},ot=oe?`${oe}${ue>0?` (ahead ${ue}, ${pt?"clean":"modified"})`:` (${pt?"clean":"modified"})`}`:void 0,Tt=J,pn=[{key:"autoCompact",label:"Auto-compact",value:Tt.autoCompact??!0,type:"boolean",description:"Automatically compress conversation history when reaching limit"},{key:"continueAtUsageLimit",label:"Continue automatically at usage limit",value:Tt.continueAtUsageLimit??!0,type:"boolean",description:"Prompt to continue when token budget approaches threshold"},{key:"switchOnFlagged",label:"Switch models when a message is flagged",value:Tt.switchOnFlagged??!0,type:"boolean",description:"Fallback to resilient backup model when provider flags prompt"},{key:"thinkingMode",label:"Thinking mode",value:Tt.thinkingMode??!0,type:"boolean",description:"Show real-time reasoning and deliberation traces"},{key:"promptSuggestions",label:"Prompt suggestions",value:Tt.promptSuggestions??!0,type:"boolean",description:"Generate contextual next-prompt suggestions at turn ends"},{key:"sessionRecap",label:"Session recap",value:Tt.sessionRecap??!0,type:"boolean",description:"Show a narrative recap on session resume"},{key:"checkpoints",label:"Rewind code (checkpoints)",value:Tt.checkpoints??!0,type:"boolean",description:"Record granular turn checkpoints for code rollback"},{key:"dynamicWorkflows",label:"Dynamic workflows",value:Tt.dynamicWorkflows??!0,type:"boolean",description:"Allow agent to orchestrate multi-phase workflows"},{key:"ultracodeKeyword",label:"Ultracode keyword trigger",value:Tt.ultracodeKeyword??!0,type:"boolean",description:"Enable ultracode trigger keywords for autonomous loops"},{key:"artifacts",label:"Artifacts",value:Tt.artifacts??!0,type:"boolean",description:"Enable durable side-by-side artifact reviews and diffs"},{key:"verboseOutput",label:"Verbose output",value:Tt.verboseOutput??!1,type:"boolean",description:"Print low-level tool execution and stream diagnostics"},{key:"terminalProgressBar",label:"Terminal progress bar",value:Tt.terminalProgressBar??!0,type:"boolean",description:"Display animated status bar and spinner during operations"},{key:"showTurnDuration",label:"Show turn duration",value:Tt.showTurnDuration??!0,type:"boolean",description:"Display accurate timing and token metrics in divider receipts"},{key:"respectGitignore",label:"Respect .gitignore in file picker",value:Tt.respectGitignore??!0,type:"boolean",description:"Filter out gitignored files in quick open and search"},{key:"delegationMode",label:"Delegation mode",value:Tt.delegationMode??!1,type:"boolean",description:"Enable planner/explorer/executor/reviewer multi-agent turns"}],wa=rh(),Iu=wa,ku=new Map;for(let ur of O?.listServers()??[])ku.set(ur.status,(ku.get(ur.status)??0)+1);let qn=[`Node ${process.versions.node} \xB7 ${process.platform}/${process.arch}`,`Context capacity source: ${HK?.source??"fallback (not model-confirmed)"}`,Gt?`History statistics cover at most 1,000 recent session records (${Gt.sessions} returned).`:"Session history could not be read.","Account quota/limits: not fetched by this local snapshot."];for(let ur of pn)ur.key==="delegationMode"?(ur.value=jt.enabled,ur.readOnly=qe==="chatOnly",ur.label="Delegation (current session)"):ur.key==="showTurnDuration"?(ur.value=v.getTurnDurationVisible(),ur.label="Turn duration (current session)",ur.description="Show elapsed time in future turn receipts; interruption, tokens and background status remain visible."):(ur.value="control not wired",ur.readOnly=!0);pn.unshift({key:"mcpEnabled",label:"MCP startup default (next session)",value:J.mcpEnabled??!1,type:"boolean"});for(let ur of["AGENTS.md","CLAUDE.md","xeno-main.md"])try{let Cn=UIe(my(r,ur)).size;qn.push(`${ur}: ${Cn.toLocaleString()} bytes${Cn>15e4?" \u2014 large instruction file; review context cost":""}`)}catch{}let Va={executionLines:Pwe(await _we(k?.meta.id)),version:Pe,sessionId:k?.meta.id??Xr,sessionName:k?.meta.name??"Unnamed session",sessionKind:e.executionMode==="chatOnly"?"interactive Chat":"interactive Agent",cwd:r,authStatus:e.apiKey?"model credential configured; not validated by this snapshot":"no explicit model credential; provider/account status not queried",diagnostics:qn,model:e.model??Gr,effort:e.effort,permissionMode:e.permissionMode,mcpServers:O?.listServers().map(ur=>ur.config.name),mcpSummary:Array.from(ku,([ur,Cn])=>`${Cn} ${ur}`).join(", ")||"No active server records",bgTasksCount:bt.list().length,gitBranch:ot,tokensTotal:wa.total,tokensInput:wa.input,tokensOutput:wa.output,tokensCacheRead:Iu.cacheRead??0,tokensCacheWrite:Iu.cacheWrite??0,maxBudget:Ie.modelContextWindow,contextBudgetSource:HK?.source??"fallback",totalCost:v.getCostDisplay()||void 0,apiDuration:St(JM),wallDuration:St(fe),codeDiff:ct,historyNote:Gt?.note??"Session history unavailable.",dailyActivity:Gt?.dailyActivity,activeDaysCount:Gt?.activeDays,lifetimeTokens:Gt?.totalTokens??void 0,favoriteModel:Gt?.favoriteModel??void 0,totalSessionsCount:Gt?.sessions};await v.statusPanel({initialTab:V,sessionData:Va,configItems:pn,onToggleConfig:(ur,Cn)=>{if(ur==="showTurnDuration"&&typeof Cn=="boolean"){v.setTurnDurationVisible(Cn);return}if(ur==="mcpEnabled"&&typeof Cn=="boolean"){go({mcpEnabled:Cn});return}if(ur==="delegationMode"&&typeof Cn=="boolean"){if(qe==="chatOnly")throw new Error("Delegation requires Agent mode.");fa(Cn);return}throw new Error("This setting has no runtime owner.")}});return}if(T==="/as"||T.startsWith("/as ")){let V=Ve;if(!V){v.writeInfo(G.dim("XENO agents are not ready yet; try /as again in a moment."));return}let J=T.slice(3).trim();v.startSpinner(J?"Switching who this session acts as...":"Loading your agents...");let oe;try{oe=await V.command(J,{model:e.model,...e.effort?{effort:e.effort}:{}})}finally{v.stopSpinner()}if(!J&&oe.choices){let pt=await v.sessionPicker({title:"Act as a XENO agent",description:"Search your account agents by name, division or ID",options:oe.choices,currentValue:oe.currentValue,confirmLabel:"Enter to switch identity \xB7 Esc to cancel"});if(!pt||pt===oe.currentValue)return;v.startSpinner("Switching who this session acts as...");try{oe=await V.command(pt,{model:e.model,...e.effort?{effort:e.effort}:{}})}finally{v.stopSpinner()}}if(!oe.changed){v.writeInfo(oe.lines.join(`
10401
- `));return}oe.model&&oe.model!==e.model&&(await lg(k,oe.model),e.agentModelManaged=!1,e.model=oe.model,await au(Ie,oe.model),L.current?.setModel(oe.model),v.setModel(oe.model),v.setContextBudgetTokens(Ie.modelContextWindow));let ue=oe.effort?Fj(oe.effort):null;ue&&(e.effort=ue,Ie.effort=ue,L.current?.setEffort(ue),v.setEffort(ue)),Ie.systemPrompt=await Pp(),v.setActingAs(V.label()??void 0),nr(T,oe.lines[0]??"Switched");return}if(T==="/model"){try{v.startSpinner("Loading models...");let V;try{V=await sG({apiKey:e.apiKey,forceRefresh:!0})}finally{v.stopSpinner()}let J=V.filter(K1),oe=!J.some(fe=>fe.source==="xeno"&&fe.owned_by!=="fallback"),ue=oe?J.filter(fe=>fe.source==="local"):J;oe&&v.writeInfo(G.red("\u2717 Couldn't load the model list from the XENO API. Check your connection and sign-in, then try /model again."));let pt=Array.from(new Map(ue.map(fe=>[fe.id,fe])).values());if(pt.length===0){oe||v.writeInfo("No models available");return}let ct=fe=>fe.available===!1;pt.sort((fe,St)=>fe.id===e.model?-1:St.id===e.model?1:ct(fe)!==ct(St)?ct(fe)?1:-1:fe.id===Gr?-1:St.id===Gr?1:fe.source!==St.source?fe.source==="xeno"?-1:1:fe.id.localeCompare(St.id));let Gt=fe=>(fe.availability&&fe.availability!=="unknown"?fe.availability:"unavailable").replace(/_/g," ")+(fe.availabilityFailureCode?` \xB7 ${fe.availabilityFailureCode}`:""),ft=await v.modelPicker({title:"Select model",description:"Type to filter models",currentValue:e.model,options:pt.map(fe=>({value:fe.id,label:fe.id,detail:ct(fe)?`(${Gt(fe)})`:fe.id===Gr?"(recommended default)":fe.source==="local"?"(local model)":"(Xeno API)"}))});if(ft&&ft!==e.model){let fe=pt.find(Tt=>Tt.id===ft);if(fe&&ct(fe)){v.writeInfo(G.red(`\u2717 ${ft} is not available right now (${Gt(fe)}). Kept ${e.model}.`));return}let St=fe?.source==="xeno"&&fe.owned_by!=="fallback";v.startSpinner("Checking model...");let ot=St?{ok:!0,metadata:fe}:await q$(ft,e.apiKey);if(v.stopSpinner(),!ot.ok){v.writeInfo(G.red(`\u2717 ${ot.error}`));return}await lg(k,ft),e.agentModelManaged=!1,e.model=ft,go({model:ft}),await au(Ie,ft,ot.metadata),v.setContextBudgetTokens(Ie.modelContextWindow),L.current?.setModel(ft),Ie.systemPrompt=await Pp(),v.setModel(ft),nr("/model",`Switched model to ${ft}`),ot.warning&&v.writeInfo(G.dim(ot.warning))}else nr("/model",`Kept model as ${e.model}`)}catch(V){v.stopSpinner();let J=V instanceof Error?V.message:String(V);v.writeInfo(G.red(`\u2717 Failed to load models: ${J}`))}return}if(T.startsWith("/model ")){let V=T.slice(7).trim();if(V==="--all"){nr("/model --all",`Listed models (current: ${e.model})`);let J=await aG(e.apiKey,!0,!0);v.writeInfo(`Available models:
10402
- ${J}`)}else if(V){if(V===e.model){nr(T,`Kept model as ${e.model}`);return}v.startSpinner("Checking model...");let J=await q$(V,e.apiKey);if(v.stopSpinner(),!J.ok){v.writeInfo(G.red(`\u2717 ${J.error}`));return}await lg(k,V),e.agentModelManaged=!1,e.model=V,go({model:V}),await au(Ie,V,J.metadata),L.current?.setModel(V),Ie.systemPrompt=await Pp(),v.setModel(V),v.setContextBudgetTokens(Ie.modelContextWindow),nr(T,`Switched model to ${V}`),J.warning&&v.writeInfo(G.dim(J.warning))}return}if(T==="/effort"||T.startsWith("/effort ")){let V=T.slice(7).trim();if(!V){nr(T,`Effort: ${e.effort??"medium"} (available: ${mTr()})`);return}if(Ub(V)){e.effort="max",e.orchestrationMode="ultracode",Ie.effort="max",L.current?.setEffort("max"),v.setEffort("max"),nr(T,"Ultracode orchestration enabled");return}let J=Fj(V);if(!J){v.writeInfo(G.red(`Usage: /effort ${[...GK,Su].join("|")}`));return}e.effort=J,delete e.orchestrationMode,Ie.effort=J,L.current?.setEffort(J),v.setEffort(J),nr(T,`Effort set to ${J}`);return}if(T==="/fast"){e.effort=Bk,delete e.orchestrationMode,Ie.effort=Bk,L.current?.setEffort(Bk),v.setEffort(Bk),nr("/fast",`Fast profile enabled (${e.model}/${Bk})`);return}if(T==="/mode"){let V=me(),J=await v.modelPicker({title:"Select mode",description:"Switch runtime mode",currentValue:V,options:[{value:"chat",label:`${Mit("chat")} Chat`,detail:"(read-only behavior, ask before edits/commands)"},{value:"agent",label:`${Mit("agent")} Agent`,detail:"(default behavior: edits allowed, ask before commands)"},{value:"fullAccess",label:`${Mit("fullAccess")} Full Access`,detail:"(no per-action prompts; trusted workspaces only)"}]});J==="chat"||J==="agent"||J==="fullAccess"?(await He(J),go({executionMode:qe,...V_(e.permissionMode)?{permissionMode:e.permissionMode}:{}}),nr("/mode",`Switched mode to ${Dj(me())}`)):nr("/mode",`Kept mode as ${Dj(V)}`);return}if(T.startsWith("/mode ")){let V=T.slice(6).trim(),J=DTr(V);if(!J){v.writeInfo(G.red("Usage: /mode <chat|agent|full-access>"));return}let oe=me();if(J===oe){nr(T,`Kept mode as ${Dj(oe)}`);return}await He(J),go({executionMode:qe,...V_(e.permissionMode)?{permissionMode:e.permissionMode}:{}}),nr(T,`Switched mode to ${Dj(me())}`);return}if(T==="/delegate"||T.startsWith("/delegate ")){if(qe==="chatOnly"){v.writeInfo(G.dim("Delegation is an Agent capability. Switch to Agent mode and select a local workspace first."));return}let V=T.slice(9).trim();if(!V){let oe=await v.modelPicker({title:"Delegation mode",description:"Planner/explorer/executor/reviewer workflow",currentValue:jt.enabled?"on":"off",options:[{value:"off",label:"Off",detail:"(default single-agent turns)"},{value:"on",label:"On",detail:"(delegated multi-agent turns)"}]});oe==="on"||oe==="off"?(fa(oe==="on"),nr("/delegate",`Delegation ${oe==="on"?"enabled":"disabled"}`)):nr("/delegate",`Kept delegation ${jt.enabled?"enabled":"disabled"}`);return}let J=FTr(V);if(J==="status"){nr(T,ra(jt));return}if(J==="on"||J==="off"){fa(J==="on"),nr(T,`Delegation ${J==="on"?"enabled":"disabled"}`);return}if(V.toLowerCase().startsWith("precedence ")){let oe=V.slice(11).trim();if(oe.toLowerCase()==="default"){jt={...jt,rolePrecedence:void 0},nr(T,ra(jt));return}let ue=oe.split(",").map(pt=>pt.trim()).filter(pt=>pt.length>0);if(ue.length===0){v.writeInfo(G.red("Usage: /delegate precedence <role1,role2,role3>"));return}jt={...jt,rolePrecedence:ue},nr(T,ra(jt));return}if(V.toLowerCase().startsWith("mode ")){let oe=V.slice(5).trim(),ue=UTr(oe);if(!ue){v.writeInfo(G.red("Usage: /delegate mode <staged|parallel>"));return}jt={...jt,mode:ue},nr(T,ra(jt));return}if(V.toLowerCase().startsWith("team ")){let oe=V.slice(5).trim();if(oe.toLowerCase()==="default"||oe.toLowerCase()==="balanced"){jt={...jt,teamPreset:zp},nr(T,ra(jt));return}let ue=qTr(oe);if(!ue){v.writeInfo(G.red("Usage: /delegate team <balanced|explore|build|review|default>"));return}jt={...jt,teamPreset:ue},nr(T,ra(jt));return}if(V.toLowerCase().startsWith("roles ")){let oe=V.slice(6).trim();if(oe.toLowerCase()==="default"||oe.toLowerCase()==="all"){jt={...jt,roles:void 0},nr(T,ra(jt));return}let ue=jTr(oe);if(!ue){v.writeInfo(G.red("Usage: /delegate roles <planner,explorer,executor,reviewer|default>"));return}jt={...jt,teamPreset:void 0,roles:ue},nr(T,ra(jt));return}if(V.toLowerCase().startsWith("concurrency ")){let oe=V.slice(12).trim(),ue=QTr(oe);if(ue===null){v.writeInfo(G.red("Usage: /delegate concurrency <n|auto>"));return}jt={...jt,maxConcurrentBranches:ue},nr(T,ra(jt));return}if(V.toLowerCase().startsWith("remote ")){let oe=V.slice(7).trim(),ue=HTr(oe);if(ue===null){v.writeInfo(G.red("Usage: /delegate remote <none|prompts|resources|context|all|role=policy,...|default>"));return}jt={...jt,remoteMcpByRole:ue},nr(T,ra(jt));return}v.writeInfo(G.red("Usage: /delegate [on|off|status|team <balanced|explore|build|review|default>|mode <staged|parallel>|roles <csv|default>|concurrency <n|auto>|precedence <csv|default>|remote <policy|role=policy,...|default>]"));return}if(T==="/plan"||T.startsWith("/plan ")){await kge(T.slice(5),pe,{write:V=>v.writeInfo(V)});return}if(T==="/approvals"||T.startsWith("/approvals ")||T==="/permissions"||T.startsWith("/permissions ")){let V=T.startsWith("/permissions")?"/permissions":"/approvals",J=T.slice(V.length).trim();if(!J){let pt=GTr(e.permissionMode),ct=await v.modelPicker({title:"Update XENO Approvals",description:"Choose how XENO asks for permission",currentValue:pt,options:[{value:"plan",label:"Plan",detail:"XENO can read and search only. Edits and commands are refused until you approve a plan."},{value:"readOnly",label:"Read Only",detail:"XENO can read files in this workspace. XENO asks before edits or commands."},{value:"auto",label:"Auto",detail:"XENO allows low-risk reads and local checks, blocks dangerous actions, and asks for ambiguous work."},{value:"default",label:"Default",detail:"XENO can read and edit files in this workspace. XENO asks before running commands."},{value:"fullAccess",label:"Full Access",detail:"XENO can read, edit, and run commands with no per-action prompts. Use only in trusted workspaces."}]});if(!ct||!sqi(ct)||ct===pt){nr(V,`Kept approvals as ${Q$(pt)}`);return}let Gt=qit(ct);Q(Gt),Gt!=="plan"&&go({permissionMode:Gt}),nr(V,`Set approvals to ${Q$(ct)}`);return}let oe=VTr(J);if(!oe){v.writeInfo(G.red(`Usage: ${V} <plan|read-only|auto|default|full-access>`));return}let ue=qit(oe);if(ue===e.permissionMode){nr(T,`Kept approvals as ${Q$(oe)}`);return}Q(ue),ue!=="plan"&&go({permissionMode:ue}),nr(T,`Set approvals to ${Q$(oe)}`);return}if(T==="/color"||T.startsWith("/color ")||T==="/theme"||T.startsWith("/theme ")){let V=T.startsWith("/theme")?"/theme":"/color",J=T.slice(V.length).trim();if(!J){let ue=wG(),pt=await _Cr(v);if(!pt||!Bm(pt)||pt===ue){nr(V,`Kept UI color as ${ue}`);return}jit(pt),HR(pt),v.refreshTheme(),nr(V,`Switched UI color to ${pt}`);return}let oe=LTr(J);if(!oe){v.writeInfo(G.red(`Usage: ${V} <theme|#RRGGBB>`));return}jit(oe),HR(oe),v.refreshTheme(),nr(T,`Switched UI color to ${oe}`);return}if(T==="/alien"||T.startsWith("/alien ")){let V=T.slice(6).trim().toLowerCase(),J=V?xa.find(ue=>ue.id===V||ue.name.toLowerCase()===V)?.id??null:await v.modelPicker({title:"Choose your alien",description:"Shown when you sign in; its detail follows /color",currentValue:kh(),options:xa.map(ue=>({value:ue.id,label:ue.name,detail:ue.blurb}))}),oe=xa.find(ue=>ue.id===J);if(!oe){V?v.writeInfo(G.red(`Usage: /alien <${xa.map(ue=>ue.name.toLowerCase()).join("|")}>`)):nr("/alien",`Kept ${xa.find(ue=>ue.id===kh())?.name}`);return}kG(oe.id),nr(T,`Your alien is now ${oe.name}`);return}if(T==="/vim"||T.startsWith("/vim ")){let V=T.slice(4).trim().toLowerCase();U=V==="on"?!0:V==="off"?!1:!U,v.setVimMode(U),nr(T,`Vim input ${U?"enabled":"disabled"}`);return}let Ae=ud(T,{surface:"tui",hostedProviderLane:q?.routesTurnsThroughHost===!0});if(Ae){v.writeError(Ae.message);return}await Hv(T)};if(g&&v.busy&&T.trimStart().startsWith("/")){let ae=cHt(T);if(ae){v.writeError(ae.message);return}return F()}if(!g&&A3i.test(T.trimStart()))return F();let H=A;g||v.showTransientActivityNotice("Starting\u2026");let z=(g?H:y.then(()=>H)).then(F);return A=z.catch(()=>{}),z}),onExitRequest:async()=>{try{await ti()}catch{process.exitCode=1}v.cleanup(),process.stderr.write(G.dim(`
10400
+ `)}return}if(T==="/save"){let V=rh(),J=C6(null,Ie.messages,e.model,V.total);v.writeInfo(`Session saved: ${J}`);return}if(T.trim()==="/sessions purge"){try{await Qv()}catch(V){let J=V instanceof Error?V.message:String(V);v.writeInfo(G.red(`? Failed to purge sessions: ${J}`))}return}if(T==="/sessions"){try{let V=await qv();if(!V)return;V==="list"?await Bp():await Qv()}catch(V){let J=V instanceof Error?V.message:String(V);v.writeInfo(G.red(`? Failed to load sessions: ${J}`))}return}if(T==="/resume"){try{let V=await Qt({workingDirectory:r,allRoles:!0});if(V.length===0){v.writeInfo("No sessions found in this workspace");return}let J=V.map(ue=>({value:ue.meta.id,title:ue.preview,meta:ue.metaLine})),oe=await v.sessionPicker({title:"Resume Session",description:"Search sessions...",options:J,confirmLabel:"Enter to resume"});oe&&await Jy(oe)}catch(V){let J=V instanceof Error?V.message:String(V);v.writeInfo(G.red(`? Failed to resume session: ${J}`))}return}if(T.startsWith("/resume ")){let V=T.slice(8).trim();if(!V){v.writeInfo(G.red("Usage: /resume <session-id>"));return}await Jy(V);return}let xe=Iit(T);if(xe!==void 0){let V=xe,J=Pt(),oe,ue=0,pt=!0;try{if(oe=LIe("git rev-parse --abbrev-ref HEAD",{stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim()||void 0,oe){try{let Cn=LIe(`git rev-list --left-right --count origin/${oe}...${oe}`,{stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim(),[,Od]=Cn.split(/\s+/).map(Number);ue=Od||0}catch{}pt=LIe("git status --porcelain",{stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim().length===0}}catch{oe=void 0}let ct;try{let ur=LIe("git diff --shortstat HEAD~1 HEAD",{stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim(),Cn=ur.match(/(\d+)\s+files? changed/),Od=ur.match(/(\d+)\s+insertions?\(\+\)/),Ky=ur.match(/(\d+)\s+deletions?\(-\)/);ct={filesChanged:Cn?parseInt(Cn[1],10):0,insertions:Od?parseInt(Od[1],10):0,deletions:Ky?parseInt(Ky[1],10):0}}catch{ct=void 0}let Vt=await ywe().catch(()=>null),ft=I||Date.now(),fe=Math.max(0,Date.now()-ft),St=ur=>{let Cn=Math.floor(ur/1e3);if(Cn<60)return`${Cn}s`;let Od=Math.floor(Cn/60),Ky=Cn%60;if(Od<60)return`${Od}m ${Ky}s`;let nh=Math.floor(Od/60),ZM=Od%60;return`${nh}h ${ZM}m`},ot=oe?`${oe}${ue>0?` (ahead ${ue}, ${pt?"clean":"modified"})`:` (${pt?"clean":"modified"})`}`:void 0,Tt=J,pn=[{key:"autoCompact",label:"Auto-compact",value:Tt.autoCompact??!0,type:"boolean",description:"Automatically compress conversation history when reaching limit"},{key:"continueAtUsageLimit",label:"Continue automatically at usage limit",value:Tt.continueAtUsageLimit??!0,type:"boolean",description:"Prompt to continue when token budget approaches threshold"},{key:"switchOnFlagged",label:"Switch models when a message is flagged",value:Tt.switchOnFlagged??!0,type:"boolean",description:"Fallback to resilient backup model when provider flags prompt"},{key:"thinkingMode",label:"Thinking mode",value:Tt.thinkingMode??!0,type:"boolean",description:"Show real-time reasoning and deliberation traces"},{key:"promptSuggestions",label:"Prompt suggestions",value:Tt.promptSuggestions??!0,type:"boolean",description:"Generate contextual next-prompt suggestions at turn ends"},{key:"sessionRecap",label:"Session recap",value:Tt.sessionRecap??!0,type:"boolean",description:"Show a narrative recap on session resume"},{key:"checkpoints",label:"Rewind code (checkpoints)",value:Tt.checkpoints??!0,type:"boolean",description:"Record granular turn checkpoints for code rollback"},{key:"dynamicWorkflows",label:"Dynamic workflows",value:Tt.dynamicWorkflows??!0,type:"boolean",description:"Allow agent to orchestrate multi-phase workflows"},{key:"ultracodeKeyword",label:"Ultracode keyword trigger",value:Tt.ultracodeKeyword??!0,type:"boolean",description:"Enable ultracode trigger keywords for autonomous loops"},{key:"artifacts",label:"Artifacts",value:Tt.artifacts??!0,type:"boolean",description:"Enable durable side-by-side artifact reviews and diffs"},{key:"verboseOutput",label:"Verbose output",value:Tt.verboseOutput??!1,type:"boolean",description:"Print low-level tool execution and stream diagnostics"},{key:"terminalProgressBar",label:"Terminal progress bar",value:Tt.terminalProgressBar??!0,type:"boolean",description:"Display animated status bar and spinner during operations"},{key:"showTurnDuration",label:"Show turn duration",value:Tt.showTurnDuration??!0,type:"boolean",description:"Display accurate timing and token metrics in divider receipts"},{key:"respectGitignore",label:"Respect .gitignore in file picker",value:Tt.respectGitignore??!0,type:"boolean",description:"Filter out gitignored files in quick open and search"},{key:"delegationMode",label:"Delegation mode",value:Tt.delegationMode??!1,type:"boolean",description:"Enable planner/explorer/executor/reviewer multi-agent turns"}],wa=rh(),Iu=wa,ku=new Map;for(let ur of O?.listServers()??[])ku.set(ur.status,(ku.get(ur.status)??0)+1);let qn=[`Node ${process.versions.node} \xB7 ${process.platform}/${process.arch}`,`Context capacity source: ${HK?.source??"fallback (not model-confirmed)"}`,Vt?`History statistics cover at most 1,000 recent session records (${Vt.sessions} returned).`:"Session history could not be read.","Account quota/limits: not fetched by this local snapshot."];for(let ur of pn)ur.key==="delegationMode"?(ur.value=jt.enabled,ur.readOnly=qe==="chatOnly",ur.label="Delegation (current session)"):ur.key==="showTurnDuration"?(ur.value=v.getTurnDurationVisible(),ur.label="Turn duration (current session)",ur.description="Show elapsed time in future turn receipts; interruption, tokens and background status remain visible."):(ur.value="control not wired",ur.readOnly=!0);pn.unshift({key:"mcpEnabled",label:"MCP startup default (next session)",value:J.mcpEnabled??!1,type:"boolean"});for(let ur of["AGENTS.md","CLAUDE.md","xeno-main.md"])try{let Cn=UIe(my(r,ur)).size;qn.push(`${ur}: ${Cn.toLocaleString()} bytes${Cn>15e4?" \u2014 large instruction file; review context cost":""}`)}catch{}let Va={executionLines:Pwe(await _we(k?.meta.id)),version:Pe,sessionId:k?.meta.id??Xr,sessionName:k?.meta.name??"Unnamed session",sessionKind:e.executionMode==="chatOnly"?"interactive Chat":"interactive Agent",cwd:r,authStatus:e.apiKey?"model credential configured; not validated by this snapshot":"no explicit model credential; provider/account status not queried",diagnostics:qn,model:e.model??Gr,effort:e.effort,permissionMode:e.permissionMode,mcpServers:O?.listServers().map(ur=>ur.config.name),mcpSummary:Array.from(ku,([ur,Cn])=>`${Cn} ${ur}`).join(", ")||"No active server records",bgTasksCount:bt.list().length,gitBranch:ot,tokensTotal:wa.total,tokensInput:wa.input,tokensOutput:wa.output,tokensCacheRead:Iu.cacheRead??0,tokensCacheWrite:Iu.cacheWrite??0,maxBudget:Ie.modelContextWindow,contextBudgetSource:HK?.source??"fallback",totalCost:v.getCostDisplay()||void 0,apiDuration:St(JM),wallDuration:St(fe),codeDiff:ct,historyNote:Vt?.note??"Session history unavailable.",dailyActivity:Vt?.dailyActivity,activeDaysCount:Vt?.activeDays,lifetimeTokens:Vt?.totalTokens??void 0,favoriteModel:Vt?.favoriteModel??void 0,totalSessionsCount:Vt?.sessions};await v.statusPanel({initialTab:V,sessionData:Va,configItems:pn,onToggleConfig:(ur,Cn)=>{if(ur==="showTurnDuration"&&typeof Cn=="boolean"){v.setTurnDurationVisible(Cn);return}if(ur==="mcpEnabled"&&typeof Cn=="boolean"){go({mcpEnabled:Cn});return}if(ur==="delegationMode"&&typeof Cn=="boolean"){if(qe==="chatOnly")throw new Error("Delegation requires Agent mode.");fa(Cn);return}throw new Error("This setting has no runtime owner.")}});return}if(T==="/as"||T.startsWith("/as ")){let V=Ve;if(!V){v.writeInfo(G.dim("XENO agents are not ready yet; try /as again in a moment."));return}let J=T.slice(3).trim();v.startSpinner(J?"Switching who this session acts as...":"Loading your agents...");let oe;try{oe=await V.command(J,{model:e.model,...e.effort?{effort:e.effort}:{}})}finally{v.stopSpinner()}if(!J&&oe.choices){let pt=await v.sessionPicker({title:"Act as a XENO agent",description:"Search your account agents by name, division or ID",options:oe.choices,currentValue:oe.currentValue,confirmLabel:"Enter to switch identity \xB7 Esc to cancel"});if(!pt||pt===oe.currentValue)return;v.startSpinner("Switching who this session acts as...");try{oe=await V.command(pt,{model:e.model,...e.effort?{effort:e.effort}:{}})}finally{v.stopSpinner()}}if(!oe.changed){v.writeInfo(oe.lines.join(`
10401
+ `));return}oe.model&&oe.model!==e.model&&(await lg(k,oe.model),e.agentModelManaged=!1,e.model=oe.model,await au(Ie,oe.model),L.current?.setModel(oe.model),v.setModel(oe.model),v.setContextBudgetTokens(Ie.modelContextWindow));let ue=oe.effort?Fj(oe.effort):null;ue&&(e.effort=ue,Ie.effort=ue,L.current?.setEffort(ue),v.setEffort(ue)),Ie.systemPrompt=await Pp(),v.setActingAs(V.label()??void 0),nr(T,oe.lines[0]??"Switched");return}if(T==="/model"){try{v.startSpinner("Loading models...");let V;try{V=await sG({apiKey:e.apiKey,forceRefresh:!0})}finally{v.stopSpinner()}let J=V.filter(K1),oe=!J.some(fe=>fe.source==="xeno"&&fe.owned_by!=="fallback"),ue=oe?J.filter(fe=>fe.source==="local"):J;oe&&v.writeInfo(G.red("\u2717 Couldn't load the model list from the XENO API. Check your connection and sign-in, then try /model again."));let pt=Array.from(new Map(ue.map(fe=>[fe.id,fe])).values());if(pt.length===0){oe||v.writeInfo("No models available");return}let ct=fe=>fe.available===!1;pt.sort((fe,St)=>fe.id===e.model?-1:St.id===e.model?1:ct(fe)!==ct(St)?ct(fe)?1:-1:fe.id===Gr?-1:St.id===Gr?1:fe.source!==St.source?fe.source==="xeno"?-1:1:fe.id.localeCompare(St.id));let Vt=fe=>(fe.availability&&fe.availability!=="unknown"?fe.availability:"unavailable").replace(/_/g," ")+(fe.availabilityFailureCode?` \xB7 ${fe.availabilityFailureCode}`:""),ft=await v.modelPicker({title:"Select model",description:"Type to filter models",currentValue:e.model,options:pt.map(fe=>({value:fe.id,label:fe.id,detail:ct(fe)?`(${Vt(fe)})`:fe.id===Gr?"(recommended default)":fe.source==="local"?"(local model)":"(Xeno API)"}))});if(ft&&ft!==e.model){let fe=pt.find(Tt=>Tt.id===ft);if(fe&&ct(fe)){v.writeInfo(G.red(`\u2717 ${ft} is not available right now (${Vt(fe)}). Kept ${e.model}.`));return}let St=fe?.source==="xeno"&&fe.owned_by!=="fallback";v.startSpinner("Checking model...");let ot=St?{ok:!0,metadata:fe}:await q$(ft,e.apiKey);if(v.stopSpinner(),!ot.ok){v.writeInfo(G.red(`\u2717 ${ot.error}`));return}await lg(k,ft),e.agentModelManaged=!1,e.model=ft,go({model:ft}),await au(Ie,ft,ot.metadata),v.setContextBudgetTokens(Ie.modelContextWindow),L.current?.setModel(ft),Ie.systemPrompt=await Pp(),v.setModel(ft),nr("/model",`Switched model to ${ft}`),ot.warning&&v.writeInfo(G.dim(ot.warning))}else nr("/model",`Kept model as ${e.model}`)}catch(V){v.stopSpinner();let J=V instanceof Error?V.message:String(V);v.writeInfo(G.red(`\u2717 Failed to load models: ${J}`))}return}if(T.startsWith("/model ")){let V=T.slice(7).trim();if(V==="--all"){nr("/model --all",`Listed models (current: ${e.model})`);let J=await aG(e.apiKey,!0,!0);v.writeInfo(`Available models:
10402
+ ${J}`)}else if(V){if(V===e.model){nr(T,`Kept model as ${e.model}`);return}v.startSpinner("Checking model...");let J=await q$(V,e.apiKey);if(v.stopSpinner(),!J.ok){v.writeInfo(G.red(`\u2717 ${J.error}`));return}await lg(k,V),e.agentModelManaged=!1,e.model=V,go({model:V}),await au(Ie,V,J.metadata),L.current?.setModel(V),Ie.systemPrompt=await Pp(),v.setModel(V),v.setContextBudgetTokens(Ie.modelContextWindow),nr(T,`Switched model to ${V}`),J.warning&&v.writeInfo(G.dim(J.warning))}return}if(T==="/effort"||T.startsWith("/effort ")){let V=T.slice(7).trim();if(!V){nr(T,`Effort: ${e.effort??"medium"} (available: ${mTr()})`);return}if(Ub(V)){e.effort="max",e.orchestrationMode="ultracode",Ie.effort="max",L.current?.setEffort("max"),v.setEffort("max"),nr(T,"Ultracode orchestration enabled");return}let J=Fj(V);if(!J){v.writeInfo(G.red(`Usage: /effort ${[...GK,Su].join("|")}`));return}e.effort=J,delete e.orchestrationMode,Ie.effort=J,L.current?.setEffort(J),v.setEffort(J),nr(T,`Effort set to ${J}`);return}if(T==="/fast"){e.effort=Bk,delete e.orchestrationMode,Ie.effort=Bk,L.current?.setEffort(Bk),v.setEffort(Bk),nr("/fast",`Fast profile enabled (${e.model}/${Bk})`);return}if(T==="/mode"){let V=me(),J=await v.modelPicker({title:"Select mode",description:"Switch runtime mode",currentValue:V,options:[{value:"chat",label:`${Mit("chat")} Chat`,detail:"(read-only behavior, ask before edits/commands)"},{value:"agent",label:`${Mit("agent")} Agent`,detail:"(default behavior: edits allowed, ask before commands)"},{value:"fullAccess",label:`${Mit("fullAccess")} Full Access`,detail:"(no per-action prompts; trusted workspaces only)"}]});J==="chat"||J==="agent"||J==="fullAccess"?(await He(J),go({executionMode:qe,...V_(e.permissionMode)?{permissionMode:e.permissionMode}:{}}),nr("/mode",`Switched mode to ${Dj(me())}`)):nr("/mode",`Kept mode as ${Dj(V)}`);return}if(T.startsWith("/mode ")){let V=T.slice(6).trim(),J=DTr(V);if(!J){v.writeInfo(G.red("Usage: /mode <chat|agent|full-access>"));return}let oe=me();if(J===oe){nr(T,`Kept mode as ${Dj(oe)}`);return}await He(J),go({executionMode:qe,...V_(e.permissionMode)?{permissionMode:e.permissionMode}:{}}),nr(T,`Switched mode to ${Dj(me())}`);return}if(T==="/delegate"||T.startsWith("/delegate ")){if(qe==="chatOnly"){v.writeInfo(G.dim("Delegation is an Agent capability. Switch to Agent mode and select a local workspace first."));return}let V=T.slice(9).trim();if(!V){let oe=await v.modelPicker({title:"Delegation mode",description:"Planner/explorer/executor/reviewer workflow",currentValue:jt.enabled?"on":"off",options:[{value:"off",label:"Off",detail:"(default single-agent turns)"},{value:"on",label:"On",detail:"(delegated multi-agent turns)"}]});oe==="on"||oe==="off"?(fa(oe==="on"),nr("/delegate",`Delegation ${oe==="on"?"enabled":"disabled"}`)):nr("/delegate",`Kept delegation ${jt.enabled?"enabled":"disabled"}`);return}let J=FTr(V);if(J==="status"){nr(T,ra(jt));return}if(J==="on"||J==="off"){fa(J==="on"),nr(T,`Delegation ${J==="on"?"enabled":"disabled"}`);return}if(V.toLowerCase().startsWith("precedence ")){let oe=V.slice(11).trim();if(oe.toLowerCase()==="default"){jt={...jt,rolePrecedence:void 0},nr(T,ra(jt));return}let ue=oe.split(",").map(pt=>pt.trim()).filter(pt=>pt.length>0);if(ue.length===0){v.writeInfo(G.red("Usage: /delegate precedence <role1,role2,role3>"));return}jt={...jt,rolePrecedence:ue},nr(T,ra(jt));return}if(V.toLowerCase().startsWith("mode ")){let oe=V.slice(5).trim(),ue=UTr(oe);if(!ue){v.writeInfo(G.red("Usage: /delegate mode <staged|parallel>"));return}jt={...jt,mode:ue},nr(T,ra(jt));return}if(V.toLowerCase().startsWith("team ")){let oe=V.slice(5).trim();if(oe.toLowerCase()==="default"||oe.toLowerCase()==="balanced"){jt={...jt,teamPreset:zp},nr(T,ra(jt));return}let ue=qTr(oe);if(!ue){v.writeInfo(G.red("Usage: /delegate team <balanced|explore|build|review|default>"));return}jt={...jt,teamPreset:ue},nr(T,ra(jt));return}if(V.toLowerCase().startsWith("roles ")){let oe=V.slice(6).trim();if(oe.toLowerCase()==="default"||oe.toLowerCase()==="all"){jt={...jt,roles:void 0},nr(T,ra(jt));return}let ue=jTr(oe);if(!ue){v.writeInfo(G.red("Usage: /delegate roles <planner,explorer,executor,reviewer|default>"));return}jt={...jt,teamPreset:void 0,roles:ue},nr(T,ra(jt));return}if(V.toLowerCase().startsWith("concurrency ")){let oe=V.slice(12).trim(),ue=QTr(oe);if(ue===null){v.writeInfo(G.red("Usage: /delegate concurrency <n|auto>"));return}jt={...jt,maxConcurrentBranches:ue},nr(T,ra(jt));return}if(V.toLowerCase().startsWith("remote ")){let oe=V.slice(7).trim(),ue=HTr(oe);if(ue===null){v.writeInfo(G.red("Usage: /delegate remote <none|prompts|resources|context|all|role=policy,...|default>"));return}jt={...jt,remoteMcpByRole:ue},nr(T,ra(jt));return}v.writeInfo(G.red("Usage: /delegate [on|off|status|team <balanced|explore|build|review|default>|mode <staged|parallel>|roles <csv|default>|concurrency <n|auto>|precedence <csv|default>|remote <policy|role=policy,...|default>]"));return}if(T==="/plan"||T.startsWith("/plan ")){await kge(T.slice(5),pe,{write:V=>v.writeInfo(V)});return}if(T==="/approvals"||T.startsWith("/approvals ")||T==="/permissions"||T.startsWith("/permissions ")){let V=T.startsWith("/permissions")?"/permissions":"/approvals",J=T.slice(V.length).trim();if(!J){let pt=GTr(e.permissionMode),ct=await v.modelPicker({title:"Update XENO Approvals",description:"Choose how XENO asks for permission",currentValue:pt,options:[{value:"plan",label:"Plan",detail:"XENO can read and search only. Edits and commands are refused until you approve a plan."},{value:"readOnly",label:"Read Only",detail:"XENO can read files in this workspace. XENO asks before edits or commands."},{value:"auto",label:"Auto",detail:"XENO allows low-risk reads and local checks, blocks dangerous actions, and asks for ambiguous work."},{value:"default",label:"Default",detail:"XENO can read and edit files in this workspace. XENO asks before running commands."},{value:"fullAccess",label:"Full Access",detail:"XENO can read, edit, and run commands with no per-action prompts. Use only in trusted workspaces."}]});if(!ct||!sqi(ct)||ct===pt){nr(V,`Kept approvals as ${Q$(pt)}`);return}let Vt=qit(ct);Q(Vt),Vt!=="plan"&&go({permissionMode:Vt}),nr(V,`Set approvals to ${Q$(ct)}`);return}let oe=VTr(J);if(!oe){v.writeInfo(G.red(`Usage: ${V} <plan|read-only|auto|default|full-access>`));return}let ue=qit(oe);if(ue===e.permissionMode){nr(T,`Kept approvals as ${Q$(oe)}`);return}Q(ue),ue!=="plan"&&go({permissionMode:ue}),nr(T,`Set approvals to ${Q$(oe)}`);return}if(T==="/color"||T.startsWith("/color ")||T==="/theme"||T.startsWith("/theme ")){let V=T.startsWith("/theme")?"/theme":"/color",J=T.slice(V.length).trim();if(!J){let ue=wG(),pt=await _Cr(v);if(!pt||!Bm(pt)||pt===ue){nr(V,`Kept UI color as ${ue}`);return}jit(pt),HR(pt),v.refreshTheme(),nr(V,`Switched UI color to ${pt}`);return}let oe=LTr(J);if(!oe){v.writeInfo(G.red(`Usage: ${V} <theme|#RRGGBB>`));return}jit(oe),HR(oe),v.refreshTheme(),nr(T,`Switched UI color to ${oe}`);return}if(T==="/alien"||T.startsWith("/alien ")){let V=T.slice(6).trim().toLowerCase(),J=V?xa.find(ue=>ue.id===V||ue.name.toLowerCase()===V)?.id??null:await v.modelPicker({title:"Choose your alien",description:"Shown when you sign in; its detail follows /color",currentValue:kh(),options:xa.map(ue=>({value:ue.id,label:ue.name,detail:ue.blurb}))}),oe=xa.find(ue=>ue.id===J);if(!oe){V?v.writeInfo(G.red(`Usage: /alien <${xa.map(ue=>ue.name.toLowerCase()).join("|")}>`)):nr("/alien",`Kept ${xa.find(ue=>ue.id===kh())?.name}`);return}kG(oe.id),nr(T,`Your alien is now ${oe.name}`);return}if(T==="/vim"||T.startsWith("/vim ")){let V=T.slice(4).trim().toLowerCase();U=V==="on"?!0:V==="off"?!1:!U,v.setVimMode(U),nr(T,`Vim input ${U?"enabled":"disabled"}`);return}let Ae=ud(T,{surface:"tui",hostedProviderLane:q?.routesTurnsThroughHost===!0});if(Ae){v.writeError(Ae.message);return}await Hv(T)};if(g&&v.busy&&T.trimStart().startsWith("/")){let ae=cHt(T);if(ae){v.writeError(ae.message);return}return F()}if(!g&&A3i.test(T.trimStart()))return F();let H=A;g||v.showTransientActivityNotice("Starting\u2026");let z=(g?H:y.then(()=>H)).then(F);return A=z.catch(()=>{}),z}),onExitRequest:async()=>{try{await ti()}catch{process.exitCode=1}v.cleanup(),process.stderr.write(G.dim(`
10403
10403
  Goodbye.
10404
10404
  `)),process.exit(process.exitCode===1?1:130)},onInterrupt:()=>{if(b++,m?.abort(),Ee?.activeTaskId){Ee.interrupt();return}!v.busy||Li||(Li=!0,et.cancelContinuationsForOwner(Pd()),v.stopSpinner(),uo?.abort(),yu?.cancelCurrentTurn(),Ga?.abort(),Ie.cancelCurrentTurn())},onOpenArtifact:T=>{wu.open(T).then(F=>v.showTransientActivityNotice(`Opened "${F.title}" in the browser.`)).catch(F=>v.showTransientActivityNotice(F instanceof Error?F.message:String(F)))},onCloseArtifact:T=>{wu.close(T).catch(F=>v.showTransientActivityNotice(F instanceof Error?F.message:String(F)))},onBackgroundRequest:async()=>{if(!v.busy)return;if(Ee?.activeTaskId){Ee.promote()||v.showTransientActivityNotice("Could not move shell command to background");return}let T=v.activePromotableOperationId;if(!T){v.showTransientActivityNotice("No promotable foreground command is active");return}let{requestBackground:F}=await Promise.resolve().then(()=>(st(),cd)),H=F(T);v.showTransientActivityNotice(H.ok?"Moving the same command to background...":"Could not move this operation to background")}}),h&&(h.onVisibility=T=>v.setPeerCockpitVisible(T),h.onDisconnect=()=>{ti().then(()=>{process.exitCode=1}).catch(()=>{process.exitCode=1})}),ya("before-banner"),v.writeOutput(XR(Pe,Uj(e),CTr(),e.executionMode==="chatOnly"?"chat":"agent")),e.executionSecurity&&e.executionSecurityStatus&&(v.writeInfo(GL(e.executionSecurity,e.executionSecurityStatus)),e.executionSecurity.level==="process-hardened"&&v.writeInfo("Trusted workspace only: process hardening does not isolate filesystem reads or network access.")),xTr(r,T=>v.writeOutput(T)),ya("first-frame"),v.setStartupLoading(!0);try{ya("trust-and-lease");let T=await Z0({cwd:r,...i?{role:i}:{},...o?{memoryScope:o}:{},model:e.model,resume:e.resume,checkpoint:e.checkpoint,projectSessionContext:qj(e),loadRestorableMessages:qIe});k=T.sessionManager,S=T.checkpointManager,x=T.memoryManager,E=T.identityResolver,C=T.auditLogger,_=T.restoredMessages,P=T.sessionDir,R=T.sessionHistoryPath,$=T.turnRestoreManager??null,k&&(await he(k,e.claimHandoffId),await Pw(k,e.executionMode??"agent"),wze(k.meta)&&(e.permissionMode="plan"))}catch(T){v.cleanup();let F=T instanceof Error?T.message:String(T);return process.stderr.write(G.red(`\u2717 Error resuming session: ${F}
10405
10405
  `)),jK(T,()=>_j([Vo("execution lease",()=>re?.stop()),Vo("session store",()=>DR({sessionManager:k,auditLogger:C,modelUsage:ua?.()})),Vo("computer host",t),Vo("account host",sI)]))}v.setSessionName(k?.meta.name),zxr(T=>v?.setUpdateNotice(T),{configEnabled:Xxr(Pt())}),await RTr(C,n,"tui");let Wa;k&&(S=S??k.checkpoints,Wa=new CR(S));let ki=E?await E.resolve({role:i}):void 0;ya("session-runtime");let Rr=await Y0(x,k?.meta.id),Hr=HB(Rr);v.setPromptContextBreakdown(Hr);let qe=e.executionMode??"agent";e.executionMode=qe;let jt={enabled:qe!=="chatOnly"&&!!e.delegationEnabled,maxTotalTokens:e.delegationMaxTotalTokens??Math.max(e.maxTokens*3,1200),timeoutMs:e.delegationTimeoutMs??12e4,teamPreset:e.delegationTeamPreset??zp,mode:e.delegationMode??R0.mode,roles:e.delegationRoles?.length?[...e.delegationRoles]:void 0,rolePrecedence:e.delegationRolePrecedence?.length?[...e.delegationRolePrecedence]:void 0,maxConcurrentBranches:e.delegationMaxConcurrentBranches,remoteMcpByRole:e.delegationRemoteMcpByRole?{...e.delegationRemoteMcpByRole}:void 0};v.setDelegationEnabled(jt.enabled);let _p=new Date().toISOString().split("T")[0],Pp=async()=>`${await F0({cwd:r,model:e.model,date:_p,identity:ki,memory:Rr.merged,executionMode:qe})}${Ve?.systemPromptSuffix()??""}`;ya("prompt-memory-and-identity");let Nv=await Pp(),Ie,gu=async(T,F)=>Ga?await q?.steerActiveTurn(`${F}:
10406
10406
  ${T}`)?{status:"injected",pendingCount:po.length}:(po.push(`${F}:
10407
- ${T}`),{status:"deferred",pendingCount:po.length}):Ie.injectContext({content:T,label:F}),hr=new RP({surface:"cli",workspace:()=>r,session:()=>k&&!k.detachedForHandoff?{id:k.meta.id,...k.meta.name?{name:k.meta.name}:{}}:void 0,permissionMode:()=>e.permissionMode,state:()=>v?.awaitingHumanPrompt?"awaiting-approval":un||v?.busy?"busy":"idle",canStartTurn:()=>!!v&&!Se&&!un&&v.canAcceptExternalInput&&!v.hasQueuedMessage,runTurn:(T,F)=>Hv(T,{requestId:F}),injectContext:gu,interruptTurn:()=>{v?.busy&&!Li&&(Li=!0,Ie.cancelCurrentTurn())},lastAssistantText:()=>u9e(Ie.messages),assertOwned:async()=>re?.assertOwned(),notice:T=>v?.showTransientActivityNotice(T),info:T=>v?.writeInfo(T),transcriptRow:(T,F)=>{if(!F){v?.writeInfo(T);return}v?.writeCollapsibleInfo(F.truncated?`${T} ${G.dim("(ctrl+o)")}`:T,F.expandedText,{updateKey:F.updateKey})}});Ke=hr;let pm=new Db,XE=new Set,JE=async(T,F,H)=>{let z=await new Yn().getActive(Wh(k?.meta.id));if(z?.maxTokens===void 0)return;let ae=await pm.prepare(z,{cwd:r,model:F,maxOutputTokens:H,agent:T});T.configureModelExecution({provider:ae.provider})},wu=new MK({workspace:()=>r,session:()=>k&&!k.detachedForHandoff?{id:k.meta.id,...k.meta.name?{name:k.meta.name}:{}}:void 0,state:()=>v?.awaitingHumanPrompt?"awaiting-approval":un||v?.busy?"busy":"idle",canStartTurn:()=>!!v&&!Se&&!un&&v.canAcceptExternalInput&&!v.hasQueuedMessage,runTurn:(T,F)=>Hv(T,{requestId:F}),injectContext:gu,openUrl:T=>NK(T),notice:T=>v?.showTransientActivityNotice(T),info:T=>v?.writeInfo(T),onArtifactsChanged:T=>v?.setArtifactFooterItems(T.map(F=>({artifactId:F.artifactId,title:F.title,url:F.url,revision:F.revision,comments:F.comments,home:F.home})))},{cloud:sTr()});De=wu;let yu=null,Rg=new Map,$p=new Map,Kf=V0(),Xe=0,Di=(T,F,H,z)=>{Xe+=1;let ae=`dispatch-${Xe}-${T}`;return $p.set(ae,{name:T,agent:F,parentAgentId:H,startedAt:Date.now(),...z?{childId:z}:{}}),lr(),xe=>{let Ae=$p.get(ae);Ae&&Ae.endedAt===void 0&&(Ae.endedAt=Date.now(),Ae.outcome=xe),lr()}},uo=null,Yf=null,Bv=null,_g=new Set,Rd=new Map,Zf=null,rr=k?.meta.id;ce.current=T=>{v?.writeError(`Execution ownership lost; this terminal stopped writing: ${T instanceof Error?T.message:String(T)}`);let F=k?.meta.id,H=ent(Zrt(bt,{owners:[F],childOwnerRoots:[F,rr]}));H&&v?.writeError(H),ant(F).then(z=>{for(let ae of z)v?.writeError(ae)},()=>{}),v?.busy&&(Ee?.interrupt(),uo?.abort(),Kf.cancelAll("execution ownership lost"),yu?.cancelCurrentTurn(),Ie?.cancelCurrentTurn())};let zn=null,Rt=null,Jt={input:0,output:0,total:0},Au=null,Op=0,Pg=0,$g=()=>{Au=Ie.tokenUsage.total,Op=Au,Pg=0,v.setBusyTokenCount(null)},Gy=T=>{Au!==null&&v.setBusyTokenCount(Math.max(0,T-Au))},Ga=null,po=[],eh=!1,fm=async()=>{if(eh||!q||e.agentName?.trim())return;let T={baseURL:e.baseURL,...e.authBypassSource?{authBypassSource:e.authBypassSource}:{}},F=Qw(process.env[pf],T);if(!(F==="off"||!Yge(T)))try{await q.useDefaultLane(Ie.model)}catch(H){if(F==="required")throw H;eh=!0,v.writeInfo(`The Agent host is not available, so this chat is running here: ${H instanceof Error?H.message:String(H)}`)}},_d={input:0,output:0,total:0},Kc=T=>{T.type==="turn.started"&&typeof T.contextBudgetTokens=="number"&&T.contextBudgetTokens>0&&v.setContextBudgetTokens(T.contextBudgetTokens),(T.type==="context.pressure"||T.type==="turn.completed")&&typeof T.contextTokens=="number"&&v.setContextTokens(T.contextTokens);let F=T.type==="provider.event"?T.event:void 0;F?.type==="usage.updated"&&typeof F.inputTokens=="number"&&typeof F.outputTokens=="number"&&Gy(Op+F.inputTokens+F.outputTokens)},bu=()=>{Au=null,Op=0},Gl=dqi(()=>v),Dv=cqi(()=>v);q=zTr({sessionManager:()=>k,cwd:()=>r,executionMode:()=>qe,permissionMode:()=>e.permissionMode,executionSecurity:()=>e.executionSecurity,prompter:{confirm:async(T,F)=>(v.stopSpinner(),await v.actionPicker({title:T,...F?{description:F}:{},options:[{value:"deny",label:"Deny"},{value:"allow",label:"Allow once"}],selectedIndex:0})==="allow"),reviewPlan:async T=>(v.stopSpinner(),await pe.reviewPlan({plan:T})),ask:async(T,F)=>(v.stopSpinner(),F?.length?await v.actionPicker({title:T,options:F.map(z=>({value:z,label:z})),selectedIndex:0})??void 0:(await v.prompt(T)).trim()||void 0)},onElicitationError:(T,F)=>{v.writeError(`${F}: ${T instanceof Error?T.message:String(T)}`)},attachNativeTerminal:async({host:T,binding:F,terminalId:H})=>{if(!Rt)throw new Error("NATIVE_TUI_REQUIRES_TTY: terminal takeover is not initialized.");return Rt.attach({host:T,conversationId:F.conversationId,terminalId:H,allowedDirectories:qe==="chatOnly"?[]:[r]})}});let Vl=NR({mode:e.permissionMode,cwd:()=>r,...s?{permissionProfile:s}:{},promptFn:T=>(v.stopSpinner(),v.permissionPrompt(T)),auditLogger:C,fallbackTraceId:`session-${k?.meta.id??"unknown"}`,decisionHook:async T=>{L.current&&await aF(L.current,T)}});X_(Vl);let Xr=k?.meta.id??`chat-${Date.now()}`,Og=EJ({cwd:()=>r,profile:()=>n,runId:Xr,agentId:"agent-main",...k?.meta.id?{sessionId:k.meta.id}:{},surface:"cli",securityPolicy:()=>e.securityPolicy,...e.executionSecurityStatus?{securityStatus:e.executionSecurityStatus}:{},safeMode:e.safeMode,onAudit:dS(C)}),Vy=new v0e({cwd:r,sessionId:Xr}),qT=new AK;L.current=Vw({cwd:r,sessionId:Xr,runId:Xr,rootRunId:Xr,transcriptPath:R,permissionMode:e.permissionMode,model:e.model,...e.effort?{effort:e.effort}:{},...e.agentName?{agentName:e.agentName}:{},...n?.capabilities.hooks.length?{requiredHookNames:n.capabilities.hooks}:{},disabled:e.safeMode,humanGate:Dv}),ya("before-session-start-hooks"),await Gw(L.current);let _e=(T="agent-main",F,H,z,ae)=>T==="agent-main"&&!F&&L.current?L.current:Vw({cwd:r,sessionId:Xr,runId:Xr,rootRunId:Xr,agentId:T,...H?{agentName:H}:{},...z?{agentColor:z}:{},...ae!==void 0?{requiredHookNames:ae}:H&&uf(H,r)?.compiled.capabilities.hooks.length?{requiredHookNames:uf(H,r)?.compiled.capabilities.hooks??[]}:{},...F?{parentAgentId:F}:{},transcriptPath:R,permissionMode:e.permissionMode,model:e.model,...e.effort?{effort:e.effort}:{},disabled:e.safeMode,humanGate:Dv}),Mp=(T="agent-main",F,H,z,ae)=>WI(_e(T,F,H,z,ae)),pa=Mp(),zy=kJ(Xr),Ei=e.agentName?Xge(e.agentName,()=>r):n?.promptSection,th=[...Ei?[Ei]:[],...e.promptSections??[],cit(),eke(()=>e.orchestrationMode),z_(()=>e.permissionMode==="plan"),pJ(),hC(),znt(hr),Gwe(),...zy?[zy]:[]],Lv=null,Fv=[],Si=(T=0,F="agent-main",H=()=>ks(e,r),z=()=>Ic?.active()??[])=>async({agent:ae,prompt:xe,signal:Ae,dispatchId:V})=>{if(T>=2)throw new Error("Nested dispatch_agent depth limit reached.");if(ae?.trim()){if(e.safeMode)throw new Error("Custom agents are disabled in safe mode.");let ot=STr(ae,r,H()),Tt=ot.definition,pn=xf(Xr,"dispatch",Tt.name);ie.register(pn);let wa=ax(ot.compiled,pn),Iu=await ab.create({profile:ot.compiled,cwd:r,...wa?{sessionDir:wa.sessionDir}:{}}).catch(()=>null),ku=await QIe(Iu,xe,()=>{}),qn=nl({cwd:r,askUser:Gl,memoryManager:x,sandbox:e.securityPolicy,ownerSessionId:pn,dispatchAgent:Si(T+1,Tt.name,()=>sb(ot.compiled,r,H()),()=>Va.active()),childController:Kf}),Va=Xu({cwd:()=>r,policy:ot.compiled.capabilities.skills,outerExternalActions:ot.compiled.capabilities.externalActions.default,classifyExternalActions:gd,isExternalActionApproved:gm=>wd(gm,a),onAudit:gm=>bC(C,gm,"branch"),inheritedActivations:z()});qn.register(Va.tool),Ym(qn,r,{runId:Xr,agentId:Tt.name}),ro(qn,ot.compiled.capabilities.tools);let ur=oc(ot.compiled.capabilities.tools),Cn=Kd({profile:()=>ot.compiled,currentUserPrompt:()=>a}),Od=Mp(Tt.name,F,Tt.name,Tt.color,ot.compiled.capabilities.hooks),Ky=zw({cwd:r,registry:qn,mcpManager:O,profile:ot.compiled,beforeStep:()=>D(),getParentProfile:H,hooks:_e(Tt.name,F,Tt.name,Tt.color,ot.compiled.capabilities.hooks)}),{agent:nh}=await Mh({cwd:r,sandbox:e.securityPolicy,apiKey:e.apiKey,baseURL:e.baseURL,model:GIe(Tt,e.model),...e.fallbackModels?{fallbackModels:e.fallbackModels}:{},...e.effort?{effort:e.effort}:{},maxTokens:Math.max(512,Math.min(e.maxTokens,4096)),maxIterations:Math.max(10,Math.min(e.maxIterations,100)),...Tt.budget?.maxTokens!==void 0?{turnTokenBudget:Tt.budget.maxTokens}:{},requesterLabel:`Agent:${Tt.name}`,role:ot.compiled.memory.role,executionMode:qe,permissionEngine:Vl,askUser:Gl,memory:wa,session:{auditLogger:C},promptSections:[ot.compiled.promptSection,...Iu?[Iu.promptSection]:[],...Mc(()=>r,ot.compiled.capabilities.skills).promptSections,...zy?[zy]:[]],toolMiddleware:[Va.middleware,Ky.middleware,Od,Cn,...ur?[ur]:[]],toolRegistry:qn,runAuthority:Ky.runAuthority,continuationCheckpoints:!1});if(Ae?.aborted)throw Iu?.clear(),new ji;yu=nh;let ZM=Di(Tt.name,nh,F,V),m_e=nh.messages.length,Yy="success",xte=!0;try{await JE(nh,GIe(Tt,e.model),Math.max(512,Math.min(e.maxTokens,4096)));let gm=await jA({agent:nh,prompt:xe,signal:Ae,ownerSessionId:pn,lifecycle:Ky,run:()=>ZS(nh,Tt.budget?.deadlineMs,()=>nh.run(xe))});return xte=!1,fI(gm.termination)||(Yy="partial"),gm}catch(gm){throw Yy=Ae?.aborted?"partial":"failure",gm}finally{await HIe({soul:Iu,prepared:ku,task:xe,messages:nh.messages,startIndex:m_e,outcome:Yy,onError:()=>{}}),yu=null,ZM(SQe({threw:xte,stopRequested:Ae?.aborted===!0,termination:nh.lastRunTermination}))}}let J=e.safeMode?null:Xu({cwd:()=>r,policy:()=>H()?.capabilities.skills,outerExternalActions:()=>H()?.capabilities.externalActions.default??"ask",classifyExternalActions:gd,isExternalActionApproved:ot=>wd(ot,a),onAudit:ot=>bC(C,ot,"branch"),inheritedActivations:z()}),oe=xf(Xr,"dispatch");ie.register(oe);let ue=nl({cwd:r,sandbox:e.securityPolicy,ownerSessionId:oe});J&&ue.register(J.tool),ro(ue,H()?.capabilities.tools);let pt=oc(H()?.capabilities.tools),ct=Kd({profile:H,currentUserPrompt:()=>a}),Gt=zw({cwd:r,registry:ue,mcpManager:O,profile:H(),beforeStep:()=>D(),getParentProfile:H,hooks:_e("explorer",F,void 0,void 0,H()?.capabilities.hooks)}),ft=(await qL({cwd:r,sandbox:e.securityPolicy,apiKey:e.apiKey,baseURL:e.baseURL,model:e.model,...e.fallbackModels?{fallbackModels:e.fallbackModels}:{},...e.effort?{effort:e.effort}:{},maxTokens:Math.max(512,Math.min(e.maxTokens,4096)),maxIterations:Math.max(10,Math.min(e.maxIterations,100)),parentSystemPrompt:await Xw({cwd:r,model:e.model,executionMode:qe,profile:H(),ownerSessionId:oe}),parentExecutionMode:qe,subagentRole:"explorer",permissionEngine:Vl,toolRegistry:ue,runAuthority:Gt.runAuthority,toolMiddleware:[Gt.middleware,...J?[J.middleware]:[],Mp("explorer",F,void 0,void 0,H()?.capabilities.hooks),ct,...pt?[pt]:[]]})).agent;await JE(ft,e.model,Math.max(512,Math.min(e.maxTokens,4096)));let fe=Di("explorer",ft,F,V),St=!0;try{let ot=await jA({agent:ft,prompt:xe,signal:Ae,ownerSessionId:oe,lifecycle:Gt});return St=!1,ot}finally{fe(SQe({threw:St,stopRequested:Ae?.aborted===!0,termination:ft.lastRunTermination}))}},XM=Si();ya("before-pty-adapter"),await QI();let KE,Yc,Pd=()=>{let T=KE??k?.meta.id??Xr;return ne.add(T),ie.register(T),T},zl=W0(r,{askUser:Gl,dispatchAgent:XM,memoryManager:x,ownerSessionId:Xr,getOwnerSessionId:Pd}),hm=new oS,Mg=vB(),xi=nl({runtime:zl,childController:Kf,backgroundDispatch:Mg,memoryManager:x,taskListManager:hm,...s?{permissionProfile:s}:{},sandbox:e.securityPolicy});Ve=Rit({registry:xi,onWarning:T=>v?.writeInfo(G.dim(T.message))}),ya("before-automation"),await eK(Og,xi);let Ic=e.safeMode?null:Xu({cwd:()=>r,policy:()=>ks(e,r)?.capabilities.skills,outerExternalActions:()=>ks(e,r)?.capabilities.externalActions.default??"allow",classifyExternalActions:gd,isExternalActionApproved:T=>wd(T,a),onAudit:T=>bC(C,T,"tui")});Ic&&xi.register(Ic.tool);let Uv=new Wz(xi),HT=()=>e.agentName?ks(e,r)?.capabilities.tools:e.agentToolPolicy,lr=()=>{},mm=new Map,WT=T=>{Ym(xi,T,{runId:Xr,agentId:"agent-main"}),fJ(xi,{cwd:T,model:e.model,getModel:()=>e.model,getOrchestrationMode:()=>e.orchestrationMode??"workflow",cliVersion:Pe,parentSessionId:()=>k?.meta.id??Xr,onWorkflowStarted:()=>lr(),getParentOrigin:()=>Yc}),D$(xi,{cwd:T,model:e.model,getModel:()=>e.model,...e.effort?{effort:e.effort}:{},permissionMode:e.permissionMode,getPermissionMode:()=>e.permissionMode,cliVersion:Pe,parentSessionId:()=>k?.meta.id??Xr,getParentOrigin:()=>Yc,onSessionStarted:F=>{mm.set(F.sessionId,{record:F,addedAt:Date.now()}),lr()},getParentProfile:()=>ks(e,r),getExecutionSecurity:()=>e.executionSecurity,getParentSkills:()=>Ic?.active()??[],safeMode:e.safeMode,onSessionsChanged:()=>lr()}),jnt(xi,{cwd:()=>r})};WT(r),fnt(xi,Vy),mnt(xi,qT),Lnt(xi,Bnt(()=>r)),Vnt(xi,hr),Wwe(xi,wu);let Xy=new $K(r,async T=>{let F=new gw({cwd:T,...i?{role:i}:{},...o?{scope:o}:{},sessionDir:P,projectSessionContext:qj(e)}),H=new OA(new $A({cwd:T})),z=await H.resolve({role:i});process.chdir(T),r=T,zl.setCwd(T),zl.setMemoryManager(F),x=F,E=H,ki=z,Vl.setWorkingDirectory(T);let ae=Hi(T);Vl.loadPersistentState({allowedTools:ae.allowedTools,allowedDirectories:ae.allowedDirectories}),L.current?.setWorkingDirectory(T),Rr=await Y0(x,k?.meta.id),Hr=HB(Rr),WT(T),await B(T),v&&v.setPromptContextBreakdown(Hr),Ie&&(Ie.systemPrompt=await Pp())});if(Qnt(xi,Xy),n?.execution.isolation==="container")throw new Error(`Agent profile ${n.profile.id} requires container isolation, which is unavailable in interactive CLI mode.`);n?.execution.isolation==="worktree"&&!YS(r)&&await Xy.enter({name:`profile-${n.profile.id}`});try{Lv=await ab.create({profile:n,cwd:r,...P?{sessionDir:P}:{}}),Lv&&th.push(Lv.promptSection)}catch(T){process.stderr.write(G.dim(`Agent Soul unavailable for this session: ${T instanceof Error?T.message:String(T)}
10407
+ ${T}`),{status:"deferred",pendingCount:po.length}):Ie.injectContext({content:T,label:F}),hr=new RP({surface:"cli",workspace:()=>r,session:()=>k&&!k.detachedForHandoff?{id:k.meta.id,...k.meta.name?{name:k.meta.name}:{}}:void 0,permissionMode:()=>e.permissionMode,state:()=>v?.awaitingHumanPrompt?"awaiting-approval":un||v?.busy?"busy":"idle",canStartTurn:()=>!!v&&!Se&&!un&&v.canAcceptExternalInput&&!v.hasQueuedMessage,runTurn:(T,F)=>Hv(T,{requestId:F}),injectContext:gu,interruptTurn:()=>{v?.busy&&!Li&&(Li=!0,Ie.cancelCurrentTurn())},lastAssistantText:()=>u9e(Ie.messages),assertOwned:async()=>re?.assertOwned(),notice:T=>v?.showTransientActivityNotice(T),info:T=>v?.writeInfo(T),transcriptRow:(T,F)=>{if(!F){v?.writeInfo(T);return}v?.writeCollapsibleInfo(F.truncated?`${T} ${G.dim("(ctrl+o)")}`:T,F.expandedText,{updateKey:F.updateKey})}});Ke=hr;let pm=new Db,XE=new Set,JE=async(T,F,H)=>{let z=await new Yn().getActive(Wh(k?.meta.id));if(z?.maxTokens===void 0)return;let ae=await pm.prepare(z,{cwd:r,model:F,maxOutputTokens:H,agent:T});T.configureModelExecution({provider:ae.provider})},wu=new MK({workspace:()=>r,session:()=>k&&!k.detachedForHandoff?{id:k.meta.id,...k.meta.name?{name:k.meta.name}:{}}:void 0,state:()=>v?.awaitingHumanPrompt?"awaiting-approval":un||v?.busy?"busy":"idle",canStartTurn:()=>!!v&&!Se&&!un&&v.canAcceptExternalInput&&!v.hasQueuedMessage,runTurn:(T,F)=>Hv(T,{requestId:F}),injectContext:gu,openUrl:T=>NK(T),notice:T=>v?.showTransientActivityNotice(T),info:T=>v?.writeInfo(T),onArtifactsChanged:T=>v?.setArtifactFooterItems(T.map(F=>({artifactId:F.artifactId,title:F.title,url:F.url,revision:F.revision,comments:F.comments,home:F.home})))},{cloud:sTr()});De=wu;let yu=null,Rg=new Map,$p=new Map,Kf=V0(),Xe=0,Di=(T,F,H,z)=>{Xe+=1;let ae=`dispatch-${Xe}-${T}`;return $p.set(ae,{name:T,agent:F,parentAgentId:H,startedAt:Date.now(),...z?{childId:z}:{}}),lr(),xe=>{let Ae=$p.get(ae);Ae&&Ae.endedAt===void 0&&(Ae.endedAt=Date.now(),Ae.outcome=xe),lr()}},uo=null,Yf=null,Bv=null,_g=new Set,Rd=new Map,Zf=null,rr=k?.meta.id;ce.current=T=>{v?.writeError(`Execution ownership lost; this terminal stopped writing: ${T instanceof Error?T.message:String(T)}`);let F=k?.meta.id,H=ent(Zrt(bt,{owners:[F],childOwnerRoots:[F,rr]}));H&&v?.writeError(H),ant(F).then(z=>{for(let ae of z)v?.writeError(ae)},()=>{}),v?.busy&&(Ee?.interrupt(),uo?.abort(),Kf.cancelAll("execution ownership lost"),yu?.cancelCurrentTurn(),Ie?.cancelCurrentTurn())};let zn=null,Rt=null,Jt={input:0,output:0,total:0},Au=null,Op=0,Pg=0,$g=()=>{Au=Ie.tokenUsage.total,Op=Au,Pg=0,v.setBusyTokenCount(null)},Gy=T=>{Au!==null&&v.setBusyTokenCount(Math.max(0,T-Au))},Ga=null,po=[],eh=!1,fm=async()=>{if(eh||!q||e.agentName?.trim())return;let T={baseURL:e.baseURL,...e.authBypassSource?{authBypassSource:e.authBypassSource}:{},mcpEnabled:!!(e.mcpEnabled&&!e.safeMode)},F=Qw(process.env[pf],T);if(!(F==="off"||!Yge(T)))try{await q.useDefaultLane(Ie.model)}catch(H){if(F==="required")throw H;eh=!0,v.writeInfo(`The Agent host is not available, so this chat is running here: ${H instanceof Error?H.message:String(H)}`)}},_d={input:0,output:0,total:0},Kc=T=>{T.type==="turn.started"&&typeof T.contextBudgetTokens=="number"&&T.contextBudgetTokens>0&&v.setContextBudgetTokens(T.contextBudgetTokens),(T.type==="context.pressure"||T.type==="turn.completed")&&typeof T.contextTokens=="number"&&v.setContextTokens(T.contextTokens);let F=T.type==="provider.event"?T.event:void 0;F?.type==="usage.updated"&&typeof F.inputTokens=="number"&&typeof F.outputTokens=="number"&&Gy(Op+F.inputTokens+F.outputTokens)},bu=()=>{Au=null,Op=0},Gl=dqi(()=>v),Dv=cqi(()=>v);q=zTr({sessionManager:()=>k,cwd:()=>r,executionMode:()=>qe,permissionMode:()=>e.permissionMode,executionSecurity:()=>e.executionSecurity,prompter:{confirm:async(T,F)=>(v.stopSpinner(),await v.actionPicker({title:T,...F?{description:F}:{},options:[{value:"deny",label:"Deny"},{value:"allow",label:"Allow once"}],selectedIndex:0})==="allow"),reviewPlan:async T=>(v.stopSpinner(),await pe.reviewPlan({plan:T})),ask:async(T,F)=>(v.stopSpinner(),F?.length?await v.actionPicker({title:T,options:F.map(z=>({value:z,label:z})),selectedIndex:0})??void 0:(await v.prompt(T)).trim()||void 0)},onElicitationError:(T,F)=>{v.writeError(`${F}: ${T instanceof Error?T.message:String(T)}`)},attachNativeTerminal:async({host:T,binding:F,terminalId:H})=>{if(!Rt)throw new Error("NATIVE_TUI_REQUIRES_TTY: terminal takeover is not initialized.");return Rt.attach({host:T,conversationId:F.conversationId,terminalId:H,allowedDirectories:qe==="chatOnly"?[]:[r]})}});let Vl=NR({mode:e.permissionMode,cwd:()=>r,...s?{permissionProfile:s}:{},promptFn:T=>(v.stopSpinner(),v.permissionPrompt(T)),auditLogger:C,fallbackTraceId:`session-${k?.meta.id??"unknown"}`,decisionHook:async T=>{L.current&&await aF(L.current,T)}});X_(Vl);let Xr=k?.meta.id??`chat-${Date.now()}`,Og=EJ({cwd:()=>r,profile:()=>n,runId:Xr,agentId:"agent-main",...k?.meta.id?{sessionId:k.meta.id}:{},surface:"cli",securityPolicy:()=>e.securityPolicy,...e.executionSecurityStatus?{securityStatus:e.executionSecurityStatus}:{},safeMode:e.safeMode,onAudit:dS(C)}),Vy=new v0e({cwd:r,sessionId:Xr}),qT=new AK;L.current=Vw({cwd:r,sessionId:Xr,runId:Xr,rootRunId:Xr,transcriptPath:R,permissionMode:e.permissionMode,model:e.model,...e.effort?{effort:e.effort}:{},...e.agentName?{agentName:e.agentName}:{},...n?.capabilities.hooks.length?{requiredHookNames:n.capabilities.hooks}:{},disabled:e.safeMode,humanGate:Dv}),ya("before-session-start-hooks"),await Gw(L.current);let _e=(T="agent-main",F,H,z,ae)=>T==="agent-main"&&!F&&L.current?L.current:Vw({cwd:r,sessionId:Xr,runId:Xr,rootRunId:Xr,agentId:T,...H?{agentName:H}:{},...z?{agentColor:z}:{},...ae!==void 0?{requiredHookNames:ae}:H&&uf(H,r)?.compiled.capabilities.hooks.length?{requiredHookNames:uf(H,r)?.compiled.capabilities.hooks??[]}:{},...F?{parentAgentId:F}:{},transcriptPath:R,permissionMode:e.permissionMode,model:e.model,...e.effort?{effort:e.effort}:{},disabled:e.safeMode,humanGate:Dv}),Mp=(T="agent-main",F,H,z,ae)=>WI(_e(T,F,H,z,ae)),pa=Mp(),zy=kJ(Xr),Ei=e.agentName?Xge(e.agentName,()=>r):n?.promptSection,th=[...Ei?[Ei]:[],...e.promptSections??[],cit(),eke(()=>e.orchestrationMode),z_(()=>e.permissionMode==="plan"),pJ(),hC(),znt(hr),Gwe(),...zy?[zy]:[]],Lv=null,Fv=[],Si=(T=0,F="agent-main",H=()=>ks(e,r),z=()=>Ic?.active()??[])=>async({agent:ae,prompt:xe,signal:Ae,dispatchId:V})=>{if(T>=2)throw new Error("Nested dispatch_agent depth limit reached.");if(ae?.trim()){if(e.safeMode)throw new Error("Custom agents are disabled in safe mode.");let ot=STr(ae,r,H()),Tt=ot.definition,pn=xf(Xr,"dispatch",Tt.name);ie.register(pn);let wa=ax(ot.compiled,pn),Iu=await ab.create({profile:ot.compiled,cwd:r,...wa?{sessionDir:wa.sessionDir}:{}}).catch(()=>null),ku=await QIe(Iu,xe,()=>{}),qn=nl({cwd:r,askUser:Gl,memoryManager:x,sandbox:e.securityPolicy,ownerSessionId:pn,dispatchAgent:Si(T+1,Tt.name,()=>sb(ot.compiled,r,H()),()=>Va.active()),childController:Kf}),Va=Xu({cwd:()=>r,policy:ot.compiled.capabilities.skills,outerExternalActions:ot.compiled.capabilities.externalActions.default,classifyExternalActions:gd,isExternalActionApproved:gm=>wd(gm,a),onAudit:gm=>bC(C,gm,"branch"),inheritedActivations:z()});qn.register(Va.tool),Ym(qn,r,{runId:Xr,agentId:Tt.name}),ro(qn,ot.compiled.capabilities.tools);let ur=oc(ot.compiled.capabilities.tools),Cn=Kd({profile:()=>ot.compiled,currentUserPrompt:()=>a}),Od=Mp(Tt.name,F,Tt.name,Tt.color,ot.compiled.capabilities.hooks),Ky=zw({cwd:r,registry:qn,mcpManager:O,profile:ot.compiled,beforeStep:()=>D(),getParentProfile:H,hooks:_e(Tt.name,F,Tt.name,Tt.color,ot.compiled.capabilities.hooks)}),{agent:nh}=await Mh({cwd:r,sandbox:e.securityPolicy,apiKey:e.apiKey,baseURL:e.baseURL,model:GIe(Tt,e.model),...e.fallbackModels?{fallbackModels:e.fallbackModels}:{},...e.effort?{effort:e.effort}:{},maxTokens:Math.max(512,Math.min(e.maxTokens,4096)),maxIterations:Math.max(10,Math.min(e.maxIterations,100)),...Tt.budget?.maxTokens!==void 0?{turnTokenBudget:Tt.budget.maxTokens}:{},requesterLabel:`Agent:${Tt.name}`,role:ot.compiled.memory.role,executionMode:qe,permissionEngine:Vl,askUser:Gl,memory:wa,session:{auditLogger:C},promptSections:[ot.compiled.promptSection,...Iu?[Iu.promptSection]:[],...Mc(()=>r,ot.compiled.capabilities.skills).promptSections,...zy?[zy]:[]],toolMiddleware:[Va.middleware,Ky.middleware,Od,Cn,...ur?[ur]:[]],toolRegistry:qn,runAuthority:Ky.runAuthority,continuationCheckpoints:!1});if(Ae?.aborted)throw Iu?.clear(),new ji;yu=nh;let ZM=Di(Tt.name,nh,F,V),m_e=nh.messages.length,Yy="success",xte=!0;try{await JE(nh,GIe(Tt,e.model),Math.max(512,Math.min(e.maxTokens,4096)));let gm=await jA({agent:nh,prompt:xe,signal:Ae,ownerSessionId:pn,lifecycle:Ky,run:()=>ZS(nh,Tt.budget?.deadlineMs,()=>nh.run(xe))});return xte=!1,fI(gm.termination)||(Yy="partial"),gm}catch(gm){throw Yy=Ae?.aborted?"partial":"failure",gm}finally{await HIe({soul:Iu,prepared:ku,task:xe,messages:nh.messages,startIndex:m_e,outcome:Yy,onError:()=>{}}),yu=null,ZM(SQe({threw:xte,stopRequested:Ae?.aborted===!0,termination:nh.lastRunTermination}))}}let J=e.safeMode?null:Xu({cwd:()=>r,policy:()=>H()?.capabilities.skills,outerExternalActions:()=>H()?.capabilities.externalActions.default??"ask",classifyExternalActions:gd,isExternalActionApproved:ot=>wd(ot,a),onAudit:ot=>bC(C,ot,"branch"),inheritedActivations:z()}),oe=xf(Xr,"dispatch");ie.register(oe);let ue=nl({cwd:r,sandbox:e.securityPolicy,ownerSessionId:oe});J&&ue.register(J.tool),ro(ue,H()?.capabilities.tools);let pt=oc(H()?.capabilities.tools),ct=Kd({profile:H,currentUserPrompt:()=>a}),Vt=zw({cwd:r,registry:ue,mcpManager:O,profile:H(),beforeStep:()=>D(),getParentProfile:H,hooks:_e("explorer",F,void 0,void 0,H()?.capabilities.hooks)}),ft=(await qL({cwd:r,sandbox:e.securityPolicy,apiKey:e.apiKey,baseURL:e.baseURL,model:e.model,...e.fallbackModels?{fallbackModels:e.fallbackModels}:{},...e.effort?{effort:e.effort}:{},maxTokens:Math.max(512,Math.min(e.maxTokens,4096)),maxIterations:Math.max(10,Math.min(e.maxIterations,100)),parentSystemPrompt:await Xw({cwd:r,model:e.model,executionMode:qe,profile:H(),ownerSessionId:oe}),parentExecutionMode:qe,subagentRole:"explorer",permissionEngine:Vl,toolRegistry:ue,runAuthority:Vt.runAuthority,toolMiddleware:[Vt.middleware,...J?[J.middleware]:[],Mp("explorer",F,void 0,void 0,H()?.capabilities.hooks),ct,...pt?[pt]:[]]})).agent;await JE(ft,e.model,Math.max(512,Math.min(e.maxTokens,4096)));let fe=Di("explorer",ft,F,V),St=!0;try{let ot=await jA({agent:ft,prompt:xe,signal:Ae,ownerSessionId:oe,lifecycle:Vt});return St=!1,ot}finally{fe(SQe({threw:St,stopRequested:Ae?.aborted===!0,termination:ft.lastRunTermination}))}},XM=Si();ya("before-pty-adapter"),await QI();let KE,Yc,Pd=()=>{let T=KE??k?.meta.id??Xr;return ne.add(T),ie.register(T),T},zl=W0(r,{askUser:Gl,dispatchAgent:XM,memoryManager:x,ownerSessionId:Xr,getOwnerSessionId:Pd}),hm=new oS,Mg=vB(),xi=nl({runtime:zl,childController:Kf,backgroundDispatch:Mg,memoryManager:x,taskListManager:hm,...s?{permissionProfile:s}:{},sandbox:e.securityPolicy});Ve=Rit({registry:xi,onWarning:T=>v?.writeInfo(G.dim(T.message))}),ya("before-automation"),await eK(Og,xi);let Ic=e.safeMode?null:Xu({cwd:()=>r,policy:()=>ks(e,r)?.capabilities.skills,outerExternalActions:()=>ks(e,r)?.capabilities.externalActions.default??"allow",classifyExternalActions:gd,isExternalActionApproved:T=>wd(T,a),onAudit:T=>bC(C,T,"tui")});Ic&&xi.register(Ic.tool);let Uv=new Wz(xi),HT=()=>e.agentName?ks(e,r)?.capabilities.tools:e.agentToolPolicy,lr=()=>{},mm=new Map,WT=T=>{Ym(xi,T,{runId:Xr,agentId:"agent-main"}),fJ(xi,{cwd:T,model:e.model,getModel:()=>e.model,getOrchestrationMode:()=>e.orchestrationMode??"workflow",cliVersion:Pe,parentSessionId:()=>k?.meta.id??Xr,onWorkflowStarted:()=>lr(),getParentOrigin:()=>Yc}),D$(xi,{cwd:T,model:e.model,getModel:()=>e.model,...e.effort?{effort:e.effort}:{},permissionMode:e.permissionMode,getPermissionMode:()=>e.permissionMode,cliVersion:Pe,parentSessionId:()=>k?.meta.id??Xr,getParentOrigin:()=>Yc,onSessionStarted:F=>{mm.set(F.sessionId,{record:F,addedAt:Date.now()}),lr()},getParentProfile:()=>ks(e,r),getExecutionSecurity:()=>e.executionSecurity,getParentSkills:()=>Ic?.active()??[],safeMode:e.safeMode,onSessionsChanged:()=>lr()}),jnt(xi,{cwd:()=>r})};WT(r),fnt(xi,Vy),mnt(xi,qT),Lnt(xi,Bnt(()=>r)),Vnt(xi,hr),Wwe(xi,wu);let Xy=new $K(r,async T=>{let F=new gw({cwd:T,...i?{role:i}:{},...o?{scope:o}:{},sessionDir:P,projectSessionContext:qj(e)}),H=new OA(new $A({cwd:T})),z=await H.resolve({role:i});process.chdir(T),r=T,zl.setCwd(T),zl.setMemoryManager(F),x=F,E=H,ki=z,Vl.setWorkingDirectory(T);let ae=Hi(T);Vl.loadPersistentState({allowedTools:ae.allowedTools,allowedDirectories:ae.allowedDirectories}),L.current?.setWorkingDirectory(T),Rr=await Y0(x,k?.meta.id),Hr=HB(Rr),WT(T),await B(T),v&&v.setPromptContextBreakdown(Hr),Ie&&(Ie.systemPrompt=await Pp())});if(Qnt(xi,Xy),n?.execution.isolation==="container")throw new Error(`Agent profile ${n.profile.id} requires container isolation, which is unavailable in interactive CLI mode.`);n?.execution.isolation==="worktree"&&!YS(r)&&await Xy.enter({name:`profile-${n.profile.id}`});try{Lv=await ab.create({profile:n,cwd:r,...P?{sessionDir:P}:{}}),Lv&&th.push(Lv.promptSection)}catch(T){process.stderr.write(G.dim(`Agent Soul unavailable for this session: ${T instanceof Error?T.message:String(T)}
10408
10408
  `))}if(e.safeMode){let T=LP(Pt().outputStyle);T&&th.push(T)}else{ya("before-plugins");let T=await nF({toolRegistry:xi});ya("plugins-activated");let F=nXe(()=>r,()=>ks(e,r)?.capabilities.skills);Fv=T.outputStyles;let H=LP(Pt().outputStyle,Fv);H&&th.push(H),th.push(...T.promptSections,...F)}let JM=0,rh=()=>{let T=Ie.tokenUsage;return{input:T.input+Jt.input+_d.input,output:T.output+Jt.output+_d.output,total:T.total+Jt.total+_d.total}},jv=()=>{let T=rh(),F=rG(Ie.modelUsage,T),H=k?Date.parse(k.meta.createdAt):I,z=Math.max(0,Date.now()-(Number.isFinite(H)?H:I));return $pe(T.input,T.output)+G.dim(` | cost: ${FR(F)} | duration: ${xx(z)}`)},Ng=()=>{let T=jt.rolePrecedence?.join(", ")??U0.join(" > ");return`Delegation: ${jt.enabled?"On":"Off"} \xB7 budget ${jt.maxTotalTokens} \xB7 timeout ${jt.timeoutMs}ms \xB7 precedence ${T}`},Bg=()=>{v.showTransientActivityNotice(ra(jt))},Qe=T=>{v.showTransientActivityNotice(T)},nr=(T,F)=>{Qe(F)},fa=T=>{let F=qe!=="chatOnly"&&T;jt={...jt,enabled:F},v.setDelegationEnabled(F)},Fr=async T=>{if(qe===T){await Pw(k,T);return}qe=T,e.executionMode=T,Ie.executionMode=T,Ie.systemPrompt=await Pp(),v.setExecutionMode(T),T==="chatOnly"&&fa(!1),await Pw(k,T)},Q=T=>{if(e.permissionMode===T)return;let F=e.permissionMode;e.permissionMode=T,Vl.setMode(T),L.current?.setPermissionMode(T),v.setPermissionMode(T),pe.modeChanged(F,T)},le=Pt().permissionMode,pe=new Dz({currentMode:()=>e.permissionMode,applyMode:Q,session:()=>k&&!k.detachedForHandoff?k:void 0,notice:T=>v.writeInfo(T),submitTurn:T=>{v.echoUserPrompt(T,!0),setTimeout(()=>{Hv(T)},0)},planApproved:T=>fTr(Ie,i8,T),promptApproval:async({plan:T,previousMode:F,resumed:H})=>{v.stopSpinner(),v.writeOutput(P3i(T));let z=await v.actionPicker({title:"Approve this plan?",description:H?"This session stopped while a plan was waiting for your decision.":"XENO proposed the plan above and is waiting for your decision.",options:Prr(F),selectedIndex:0});return z==="approve"||z==="edit"||z==="keep"?z:null},editPlan:async T=>{let F=v.editTextExternally(T);return F!==void 0?F:v.prompt("Your version of the plan (Enter approves it; empty cancels):",T)},askFeedback:async()=>(await v.prompt("What should change? (Enter to keep planning without a note)")).trim()||null},V_(le)?le:"default");PR(xi,yze(pe,Vl));let me=()=>BTr(qe,e.permissionMode),He=async T=>{T==="chat"?(await Fr("chatOnly"),Q("default")):T==="agent"?(await Fr("agent"),Q("acceptEdits")):(await Fr("agent"),Q("bypassPermissions"))},It=async()=>{let T=Pt(),F=[],H=[],z=[],ae=!1,xe=e.agentName?hTr(uf(e.agentName,r)?.definition):void 0,Ae=!!(e.agentModelManaged&&xe),V=typeof T.model=="string"?T.model.trim():"";if(V&&V!==e.model&&!Ae){let ct=await q$(V,e.apiKey);ct.ok?(await lg(k,V),e.model=V,await au(Ie,V,ct.metadata),L.current?.setModel(V),v.setModel(V),v.setContextBudgetTokens(Ie.modelContextWindow),F.push(`model=${V}`),ae=!0,ct.warning&&H.push(ct.warning)):H.push(`model not applied: ${ct.error}`)}let J=Fj(T.effort);J&&J!==e.effort&&(e.effort=J,Ie.effort=J,L.current?.setEffort(J),v.setEffort(J),F.push(`effort=${J}`));let oe=ATr(T.executionMode);oe&&oe!==qe&&(await Fr(oe),F.push(`executionMode=${oe}`));let ue=yTr(T.permissionMode);ue&&ue!==e.permissionMode&&e.permissionMode!=="plan"&&(Q(ue),F.push(`permissionMode=${ue}`));let pt=gTr(T.fallbackModels);if(T.fallbackModels!==void 0&&!wTr(pt,e.fallbackModels)&&(e.fallbackModels=pt,F.push(`fallbackModels=${Git(e.fallbackModels)}`)),e.agentModelManaged&&xe&&xe!==e.model){let ct=await q$(xe,e.apiKey);ct.ok?(await lg(k,xe),e.model=xe,await au(Ie,xe),L.current?.setModel(xe),v.setModel(xe),v.setContextBudgetTokens(Ie.modelContextWindow),F.push(`customAgentModel=${xe}`),ae=!0,ct.warning&&H.push(ct.warning)):H.push(`custom agent model not applied: ${ct.error}`)}return ae&&(Ie.systemPrompt=await Pp()),{applied:F,...H.length>0?{warnings:H}:{},...z.length>0?{restartRequired:z}:{}}},ut=!1,Jr="",ri=()=>{ut=!0,Jr=""},Li=!1,jn,un=!1,Ci=null,Fi=!1,ni=!1,yn,ha,es=!1,de=new HI(T=>{if(es){if(!lit(T))return;es=!1,v.trimTrailingOutputNewlines(1),v.writeOutput(`
10409
10409
  ${G.accent("\u25A0")} `,{forceNewBlock:!0,selectable:!0,blockKind:"assistant"})}v.writeOutput(T,{selectable:!0,blockKind:"assistant"})}," ",void 0,T=>v.setStreamingPreview(T&&lit(T)?es?`
10410
- ${G.accent("\u25A0")} ${T}`:T:null)),ge=de.reset.bind(de);de.reset=()=>{es=!1,ge()};let Ne=new CIe,at=new Map,vr=new Map,Kr=2*1024*1024,kc=T=>typeof T?.file_path=="string"?vC(zl.getCwd(),T.file_path):null,Dg=(T,F)=>{if(T!=="Write")return;let H=kc(F);if(H){vr.delete(H);try{let z=UIe(H);z.isFile()&&z.size<=Kr&&vr.set(H,Hit(H,"utf8"))}catch{}}},Np=(T,F)=>{if(T!=="Write")return;let H=kc(F);if(!H)return;let z=vr.get(H);return vr.delete(H),z===void 0?void 0:{previousContent:z}},ma=new Hge,ts=new Map,rs=0,$d=null,An=(T,F)=>{let H=nnr(T.entries,{active:F}),z=`${H.summaryText}\0${H.expandedText}`;ts.get(T.updateKey)!==z&&(ts.set(T.updateKey,z),v.writeCollapsibleInfo(H.summaryText,H.expandedText,{updateKey:T.updateKey,trailingNewlines:1,selectable:!0,blockKind:"tool-activity",activeAnimation:F}))},zi=(T=Date.now())=>{let F=ma.takeEligible(T);for(let H of F)An(H,!1),ts.delete(H.updateKey);ma.pendingCount===0&&$d&&(clearTimeout($d),$d=null)},Lg=()=>{ma.sealCompletedGroup(),zi()},se=()=>{if($d||ma.pendingCount===0)return;let T=ma.nextDelayMs(Date.now());T!==null&&($d=setTimeout(()=>{$d=null,zi(),se()},Math.max(1,T)),$d.unref?.())},Ge=async()=>{for(Lg(),$d&&(clearTimeout($d),$d=null);ma.pendingCount>0;){let T=ma.nextDelayMs(Date.now());if(T===null)break;T>0&&await new Promise(F=>{setTimeout(F,T)}),zi()}},Ue=(T,F,H,z)=>{zi(),ma.begin(T,F,H,z,Date.now())},lt=(T,F,H)=>{let z=ma.complete(T,F,H);return z?(An(z.group,!0),zi(),se(),!0):!1},Kt=async(T,F)=>{if(!KL(T.toolName))return F();Pg+=1,Ue(T.toolCallId,T.toolName,T.input,H$(T.toolName,T.input));try{let H=await F();return lt(T.toolCallId,H.success,zIe(H.success,H.output,H.error)),H}catch(H){throw lt(T.toolCallId,!1,H instanceof Error?H.message:String(H)),H}},it=T=>iqi(T,{cwd:r,model:e.model,...e.fallbackModels?{fallbackModels:e.fallbackModels}:{},...e.effort?{effort:e.effort}:{},apiKey:e.apiKey,baseURL:e.baseURL,maxTokens:e.maxTokens,maxIterations:e.maxIterations,memoryManager:x}),qt=T=>{let F=new Date(T).getTime(),H=Date.now(),z=Math.max(0,H-F),ae=Math.floor(z/(60*1e3)),xe=Math.floor(z/(3600*1e3)),Ae=Math.floor(z/(1440*60*1e3));return ae<1?"just now":ae<60?`${ae}m ago`:xe<24?`${xe}h ago`:Ae<30?`${Ae}d ago`:`${Math.floor(Ae/30)}mo ago`},At=T=>T<1024?`${T} B`:T<1024*1024?`${(T/1024).toFixed(1)} KB`:`${(T/(1024*1024)).toFixed(1)} MB`,cr=(T,F)=>T.length<=F?T:F<=1?"\u2026":T.slice(0,F-1)+"\u2026",Ns=T=>{let F=T.find(z=>z.role==="user"&&typeof z.content=="string");if(F&&typeof F.content=="string"&&F.content.trim().length>0)return cr(F.content.trim().replace(/\s+/g," "),120);let H=T.find(z=>z.role==="assistant"&&typeof z.content=="string");return H&&typeof H.content=="string"&&H.content.trim().length>0?cr(H.content.trim().replace(/\s+/g," "),120):"(session)"},Qt=async T=>{let F=new Set(T?.excludeSessionIds??[]),H=await Ze.list({role:T?.allRoles?void 0:i,workingDirectory:T?.workingDirectory,limit:60});return(await Promise.all(H.map(async ae=>{if(F.has(ae.id))return null;let xe=Ze.getSessionDir(ae.id),Ae=[];try{Ae=(await QB(xe,{metadataMessageCount:ae.messageCount})).messages}catch{}let V=0;try{V=UIe(my(xe,"transcript.jsonl")).size}catch{}let J=Ns(Ae),oe=Ae.length,ue=ae.status==="active"?"HEAD":ae.status.toUpperCase(),pt=`${qt(ae.lastActivity)} \xB7 ${ue} \xB7 ${oe} msgs \xB7 ${At(V)}`;return{meta:ae,preview:J,metaLine:pt}}))).filter(ae=>!!ae)},Ur=T=>{let F=T.replace(/[\\/]+$/,"");return process.platform==="win32"?F.toLowerCase():F},xn=()=>{if(k)return Ur(k.meta.workingDirectory)===Ur(r)?k.meta.id:void 0},Ti=async()=>{let T=await Ze.list({workingDirectory:r}),F=xn(),H=F?T.filter(z=>z.id===F).map(z=>z.id):[];return{matchingCount:T.length,purgeableCount:T.length-H.length,skippedIds:H}},ga=T=>{let F=`Purged ${T.deletedIds.length} session${T.deletedIds.length===1?"":"s"} for ${r}`;if(T.skippedIds.length===0)return F;let H=T.skippedIds.length===1?`Skipped active session: ${T.skippedIds[0]}`:`Skipped ${T.skippedIds.length} active sessions`;return`${F}. ${H}.`},fo=async()=>{let T=xn(),F=await Ze.purgeWorkingDirectory(r,{excludeSessionIds:T?[T]:void 0});for(let H of F.deletedIds)ZE.markParentOrphaned(H,"Parent session was purged.");return F},Br=async T=>{ZE.markParentOrphaned(T,"Parent session was deleted."),await Ze.delete(T);let F=my(r,".xeno","sessions",`${T}.md`);try{let H=await import("node:fs");H.existsSync(F)&&H.rmSync(F,{force:!0})}catch{}},qv=async()=>{let T=await v.actionPicker({title:"Sessions",description:"Choose action:",options:[{value:"list",label:"List",detail:"Browse, resume, export, or inspect saved sessions"},{value:"purge",label:"Purge",detail:"Delete saved sessions linked to this folder"}]});return T==="list"||T==="purge"?T:null},vu=async()=>{let T=await v.actionPicker({title:"Purge Sessions",description:"Choose purge mode:",options:[{value:"all",label:"Purge all",detail:"Delete all saved sessions linked to this folder"},{value:"selected",label:"Select from list",detail:"Choose specific sessions from this folder to delete"}]});return T==="all"||T==="selected"?T:null},Bp=async()=>{let T=await Qt({workingDirectory:r,allRoles:!0});if(T.length===0){v.writeInfo(`No sessions found for ${r}`);return}let F=T.map(xe=>({value:xe.meta.id,title:xe.preview,meta:xe.metaLine})),H=await v.sessionPicker({title:"Sessions",description:"Search sessions in this folder...",options:F,confirmLabel:"Enter to view"});if(!H)return;let z=T.find(xe=>xe.meta.id===H);if(!z)return;let ae=await ecn();if(ae){if(ae==="view"){await Xln(z);return}if(ae==="resume"){await Jy(z.meta.id);return}if(ae==="export-md"||ae==="export-json"){let xe=await Jln(z,ae==="export-md"?"md":"json");await Lvt({title:"Export Session",content:xe.content,defaultPath:xe.defaultPath,subject:xe.subject});return}ae==="delete"&&await v.modelPicker({title:"Delete session",description:"Type to filter",options:[{value:"cancel",label:"Cancel",detail:"(keep session)"},{value:"delete",label:`Delete ${z.meta.id}`,detail:"(permanent)"}],currentValue:"cancel"})==="delete"&&(await Ze.delete(z.meta.id),v.writeInfo(`Deleted session: ${z.meta.id}`))}},Qv=async()=>{let T=await vu();if(!T)return;if(T==="all"){let Ae=await Ti();if(Ae.matchingCount===0){v.writeInfo(`No sessions found for ${r}`);return}if(Ae.purgeableCount===0){v.writeInfo(`No purgeable sessions found for ${r}. Active session is still open.`);return}if(await v.actionPicker({title:"Purge Workspace Sessions",description:`Delete ${Ae.purgeableCount} saved session${Ae.purgeableCount===1?"":"s"} for ${r}?`,options:[{value:"cancel",label:"Cancel",detail:"Keep the saved sessions for this folder"},{value:"purge",label:"Purge sessions",detail:"Delete the saved sessions linked to this folder"}]})!=="purge")return;let J=await fo();v.writeInfo(ga(J));return}let F=xn(),H=await Qt({workingDirectory:r,excludeSessionIds:F?[F]:void 0,allRoles:!0});if(H.length===0){v.writeInfo(`No purgeable sessions found for ${r}`);return}let z=await v.sessionMultiPicker({title:"Purge Sessions",description:"Select sessions to delete",options:H.map(Ae=>({value:Ae.meta.id,title:Ae.preview,meta:Ae.metaLine})),confirmLabel:"Enter confirm"});if(!z||z.length===0)return;let ae=H.filter(Ae=>z.includes(Ae.meta.id));if(await v.actionPicker({title:"Delete Sessions",description:`Delete ${z.length} selected session${z.length===1?"":"s"}?`,options:[{value:"cancel",label:"Cancel",detail:"Keep the selected saved sessions"},{value:"delete",label:"Delete selected",detail:"Permanently remove the selected saved sessions"}]})==="delete"){for(let Ae of ae)await Br(Ae.meta.id);v.writeInfo(`Deleted ${ae.length} session${ae.length===1?"":"s"} from ${r}`)}},Jy=async(T,F,H=!1)=>{let z;try{if(H&&(!k?.detachedForHandoff||!re?.active))throw new Error("This terminal has no withdrawn offer to resume from.");if(F&&(!k?.detachedForHandoff||re?.active||q?.routesTurnsThroughHost))throw new Error("Only a detached local SDK cockpit can claim this handoff.");F&&!qX(e.executionAuthority)&&await gQe(T,F,e.executionOwnerId??re.ownerId);let ue=await QX(e.executionAuthority,T,F,r);ue&&v.writeInfo(ue),z=await DG({sessionId:T,cwd:r,currentSessionId:k?.meta.id,reclaimDetachedSession:!!F||H,bindExecutionLease:pt=>he(pt,F)})}catch(ue){if(v.writeInfo(G.red(`\u2717 Failed to resume session ${T}: ${ue instanceof Error?ue.message:String(ue)}`)),F||H)throw ue;return}if(!z){v.showTransientActivityNotice(`Session ${T} is already active.`);return}let{manager:ae,messages:xe}=z,Ae=ae.meta,V=Lm(Ae),J=k;k=ae,v.setSessionName(ae.meta.name),hr.syncPresence(),await wu.restoreSession().catch(ue=>{v.showTransientActivityNotice(`Artifact tray unavailable: ${ue instanceof Error?ue.message:String(ue)}`,8e3)}),P=Ze.getSessionDir(T),R=my(P,"history.jsonl"),S=ae.checkpoints,$=new NA(P,r),Ie.attachSessionIntegration({transcript:ae.transcript,checkpoints:S,sessionManager:ae,historyMarkdownPath:R,auditLogger:C}),await J?.detachForHandoff().catch(ue=>{v.writeInfo(G.red(`Previous session cleanup failed: ${ue instanceof Error?ue.message:String(ue)}`))}),Ie.messages=xe,F&&D0(zl,"execution-handoff-return"),k&&await k.updateMessageCount(xe.length),Ae.model&&Ae.model!==e.model&&(e.agentModelManaged=!1,e.model=Ae.model,await au(Ie,Ae.model),L.current?.setModel(Ae.model),Ie.systemPrompt=await Pp(),v.setModel(Ae.model)),await au(Ie,Ie.model),v.setContextBudgetTokens(Ie.modelContextWindow),V!==void 0&&await Fr(V),Pit(v,xe,it),v.showTransientActivityNotice(`Resumed session ${T.slice(0,8)} (${xe.length} messages)`);let oe=pe.restoreFromSession(Ae);oe.restored&&!oe.invalid&&v.writeInfo(Sge),oe.pending&&pe.presentPendingApproval()},Yq=T=>{let F=0;for(let H=0;H<Ie.messages.length;H++){let z=Ie.messages[H];if(!(z.role!=="user"||typeof z.content!="string"||z.synthetic==="self_review")){if(F===T)return H;F+=1}}return-1},GT=()=>P?($||($=new NA(P,r)),$):null,a_e=async T=>{let F=GT();if(Zf=null,!F)return;Zf=(await F.create({id:Lj(),restoreMessageCount:Ie.messages.length,userPrompt:T})).id},KM=async(T,F)=>{let H=GT();!H||!Zf||await H.recordToolExecution(Zf,T,F)},Zq=()=>{Zf=null},YE=async(T,F)=>{let H=Yq(T);if(H<0)return v.showTransientActivityNotice("Could not find that user turn to restore"),{ok:!1,exactWorkspaceRestore:!1,hadRestorePoint:!1,unsupportedTools:[],branchCheckpointId:null};let z=GT(),ae=z?await z.inspectAtOrAfter(H):null;if(F?.requireExactWorkspace){if(!ae?.hadRestorePoints)return v.showTransientActivityNotice("No safe workspace restore point for that turn"),{ok:!1,exactWorkspaceRestore:!1,hadRestorePoint:!1,unsupportedTools:[],branchCheckpointId:null};if(!ae.exactWorkspaceRestore){let V=ae.unsupportedTools.length>0?` because it used ${ae.unsupportedTools.join(", ")}`:"";return v.showTransientActivityNotice(`Exact workspace restore unavailable${V}`),{ok:!1,exactWorkspaceRestore:!1,hadRestorePoint:!0,unsupportedTools:ae.unsupportedTools,branchCheckpointId:null}}}let xe=F?.mode??"both";if(xe==="code")return ae?.hadRestorePoints&&await z.restoreAtOrAfter(H),{ok:!!ae?.hadRestorePoints,exactWorkspaceRestore:ae?.exactWorkspaceRestore??!1,hadRestorePoint:ae?.hadRestorePoints??!1,unsupportedTools:ae?.unsupportedTools??[],branchCheckpointId:null};let Ae=null;try{Ae=await aAe({checkpointManager:S,sessionManager:k,messages:Ie.messages,targetPrompt:typeof Ie.messages[H]?.content=="string"?Ie.messages[H].content:`message ${H+1}`})}catch(V){let J=V instanceof Error?V.message:String(V);return v.showTransientActivityNotice(`Could not save rewind branch: ${J}`),{ok:!1,exactWorkspaceRestore:!1,hadRestorePoint:ae?.hadRestorePoints??!1,unsupportedTools:ae?.unsupportedTools??[],branchCheckpointId:null}}return ae?.hadRestorePoints&&xe==="both"&&await z.restoreAtOrAfter(H),et.cancelContinuationsForOwner(Pd()),Zq(),Ie.messages=Ie.messages.slice(0,H),k&&(await k.updateMessageCount(Ie.messages.length),await k.transcript.truncateAfterMessageCount(H)),await Fvt(),v.clear(),v.writeOutput(XR(Pe,Uj(e),void 0,e.executionMode==="chatOnly"?"chat":"agent")),Pit(v,Ie.messages,it),{ok:!0,exactWorkspaceRestore:ae?.exactWorkspaceRestore??!1,hadRestorePoint:ae?.hadRestorePoints??!1,unsupportedTools:ae?.unsupportedTools??[],branchCheckpointId:Ae}},e8=0,YM=async()=>{let T=++e8,F=[...Ie.messages],H=GT(),z=Ie.messages.map((fe,St)=>({message:fe,index:St})).filter(({message:fe})=>fe.role==="user"&&typeof fe.content=="string"&&fe.synthetic!=="self_review").map(({message:fe,index:St},ot)=>({userOrdinal:ot,messageIndex:St,text:String(fe.content)}));if(z.length===0){v.showTransientActivityNotice("Nothing to rewind");return}let ae=await v.rewindPicker({entries:[...z.map(fe=>({value:String(fe.userOrdinal),text:fe.text,changes:null,...H?{changesState:"pending"}:{}})),{value:"__current__",text:"(current)",changes:null,current:!0}],loadChanges:H?async fe=>{let St=z.find(Tt=>Tt.userOrdinal===Number(fe));if(!St)return null;let ot=await H.inspectAtOrAfter(St.messageIndex);if(ot.gitInspectionError)throw new Error(ot.gitInspectionError.message);return HQt(ot.filePreviews,[...ot.gitChangedPaths,...ot.points.flatMap(Tt=>Tt.mutations.map(pn=>pn.relativePath))])}:void 0});if(!ae||ae==="__current__")return;let xe=Number(ae),Ae=z.find(fe=>fe.userOrdinal===xe);if(!Ae)return;H&&v.showTransientActivityNotice("Checking selected restore point\u2026");let V=H?await H.inspectAtOrAfter(Ae.messageIndex):null;if(T!==e8||v.busy||Ie.messages.length!==F.length||F.some((fe,St)=>Ie.messages[St]!==fe))return;let J=!!V?.hadRestorePoints,oe=await v.actionPicker({title:"Rewind",description:`Restore to before: ${Bpe(Ae.text)}`,options:[...J?[{value:"both",label:"Restore code and conversation",detail:"Files return to that point and the conversation is cut there"}]:[],{value:"conversation",label:"Restore conversation",detail:"Cut the conversation there; files stay as they are"},...J?[{value:"code",label:"Restore code",detail:"Files return to that point; the conversation stays"}]:[],{value:"cancel",label:"Never mind",detail:"Stay where you are"}],selectedIndex:0});if(!oe||oe==="cancel")return;let ue=oe==="code"?"code":oe==="conversation"?"conversation":"both",pt=await YE(xe,{mode:ue});if(!pt.ok){ue==="code"&&v.showTransientActivityNotice("No safe workspace restore point for that turn");return}let ct=Bpe(Ae.text),Gt=ue==="code"?`Restored code to before: ${ct}`:ue==="conversation"?`Restored conversation before: ${ct}`:`Restored to before: ${ct}`;ue!=="code"&&v.setInputText(Ae.text,{cursor:"end",escCancelable:!0});let ft=ue!=="conversation"&&pt.hadRestorePoint&&!pt.exactWorkspaceRestore&&pt.unsupportedTools.length>0?` Workspace restore stayed safe; exact rollback was blocked by ${pt.unsupportedTools.join(", ")}.`:"";v.showTransientActivityNotice(ft?`${ft.trim()} ${Gt}`:Gt,ft?12e3:4e3)},Fg=T=>T.every(F=>WCr(F)!==null),Vln=T=>{if(!T)return["Delegation summary: none recorded"];let F=[`Selected role: ${T.selectedRole??"-"}`,`Elapsed: ${Math.max(0,Math.round(T.elapsedMs/1e3))}s`,`Branches: ${T.okBranches}/${T.totalBranches} ok`,`Tokens: ${T.totalTokens}`];for(let[H,z]of Object.entries(T.roleSummaries))F.push(`${H}: ${z.status} \xB7 ${z.tokensUsed} tok${z.outputPreview?` \xB7 ${z.outputPreview}`:""}`);return F},l_e=T=>T.length===0?"(no restorable messages)":T.map(F=>{if(F.metadata?.source==="direct_shell"){let ae=F.metadata.directShell,xe=`${ae.status}${ae.exitCode===null?"":` (exit ${ae.exitCode})`}`;return[`[direct-shell:${ae.taskId}]`,`! ${ae.command}`,`${xe} | ${ae.cwd}`,ae.output].join(`
10410
+ ${G.accent("\u25A0")} ${T}`:T:null)),ge=de.reset.bind(de);de.reset=()=>{es=!1,ge()};let Ne=new CIe,at=new Map,vr=new Map,Kr=2*1024*1024,kc=T=>typeof T?.file_path=="string"?vC(zl.getCwd(),T.file_path):null,Dg=(T,F)=>{if(T!=="Write")return;let H=kc(F);if(H){vr.delete(H);try{let z=UIe(H);z.isFile()&&z.size<=Kr&&vr.set(H,Hit(H,"utf8"))}catch{}}},Np=(T,F)=>{if(T!=="Write")return;let H=kc(F);if(!H)return;let z=vr.get(H);return vr.delete(H),z===void 0?void 0:{previousContent:z}},ma=new Hge,ts=new Map,rs=0,$d=null,An=(T,F)=>{let H=nnr(T.entries,{active:F}),z=`${H.summaryText}\0${H.expandedText}`;ts.get(T.updateKey)!==z&&(ts.set(T.updateKey,z),v.writeCollapsibleInfo(H.summaryText,H.expandedText,{updateKey:T.updateKey,trailingNewlines:1,selectable:!0,blockKind:"tool-activity",activeAnimation:F}))},zi=(T=Date.now())=>{let F=ma.takeEligible(T);for(let H of F)An(H,!1),ts.delete(H.updateKey);ma.pendingCount===0&&$d&&(clearTimeout($d),$d=null)},Lg=()=>{ma.sealCompletedGroup(),zi()},se=()=>{if($d||ma.pendingCount===0)return;let T=ma.nextDelayMs(Date.now());T!==null&&($d=setTimeout(()=>{$d=null,zi(),se()},Math.max(1,T)),$d.unref?.())},Ge=async()=>{for(Lg(),$d&&(clearTimeout($d),$d=null);ma.pendingCount>0;){let T=ma.nextDelayMs(Date.now());if(T===null)break;T>0&&await new Promise(F=>{setTimeout(F,T)}),zi()}},Ue=(T,F,H,z)=>{zi(),ma.begin(T,F,H,z,Date.now())},lt=(T,F,H)=>{let z=ma.complete(T,F,H);return z?(An(z.group,!0),zi(),se(),!0):!1},Kt=async(T,F)=>{if(!KL(T.toolName))return F();Pg+=1,Ue(T.toolCallId,T.toolName,T.input,H$(T.toolName,T.input));try{let H=await F();return lt(T.toolCallId,H.success,zIe(H.success,H.output,H.error)),H}catch(H){throw lt(T.toolCallId,!1,H instanceof Error?H.message:String(H)),H}},it=T=>iqi(T,{cwd:r,model:e.model,...e.fallbackModels?{fallbackModels:e.fallbackModels}:{},...e.effort?{effort:e.effort}:{},apiKey:e.apiKey,baseURL:e.baseURL,maxTokens:e.maxTokens,maxIterations:e.maxIterations,memoryManager:x}),qt=T=>{let F=new Date(T).getTime(),H=Date.now(),z=Math.max(0,H-F),ae=Math.floor(z/(60*1e3)),xe=Math.floor(z/(3600*1e3)),Ae=Math.floor(z/(1440*60*1e3));return ae<1?"just now":ae<60?`${ae}m ago`:xe<24?`${xe}h ago`:Ae<30?`${Ae}d ago`:`${Math.floor(Ae/30)}mo ago`},At=T=>T<1024?`${T} B`:T<1024*1024?`${(T/1024).toFixed(1)} KB`:`${(T/(1024*1024)).toFixed(1)} MB`,cr=(T,F)=>T.length<=F?T:F<=1?"\u2026":T.slice(0,F-1)+"\u2026",Ns=T=>{let F=T.find(z=>z.role==="user"&&typeof z.content=="string");if(F&&typeof F.content=="string"&&F.content.trim().length>0)return cr(F.content.trim().replace(/\s+/g," "),120);let H=T.find(z=>z.role==="assistant"&&typeof z.content=="string");return H&&typeof H.content=="string"&&H.content.trim().length>0?cr(H.content.trim().replace(/\s+/g," "),120):"(session)"},Qt=async T=>{let F=new Set(T?.excludeSessionIds??[]),H=await Ze.list({role:T?.allRoles?void 0:i,workingDirectory:T?.workingDirectory,limit:60});return(await Promise.all(H.map(async ae=>{if(F.has(ae.id))return null;let xe=Ze.getSessionDir(ae.id),Ae=[];try{Ae=(await QB(xe,{metadataMessageCount:ae.messageCount})).messages}catch{}let V=0;try{V=UIe(my(xe,"transcript.jsonl")).size}catch{}let J=Ns(Ae),oe=Ae.length,ue=ae.status==="active"?"HEAD":ae.status.toUpperCase(),pt=`${qt(ae.lastActivity)} \xB7 ${ue} \xB7 ${oe} msgs \xB7 ${At(V)}`;return{meta:ae,preview:J,metaLine:pt}}))).filter(ae=>!!ae)},Ur=T=>{let F=T.replace(/[\\/]+$/,"");return process.platform==="win32"?F.toLowerCase():F},xn=()=>{if(k)return Ur(k.meta.workingDirectory)===Ur(r)?k.meta.id:void 0},Ti=async()=>{let T=await Ze.list({workingDirectory:r}),F=xn(),H=F?T.filter(z=>z.id===F).map(z=>z.id):[];return{matchingCount:T.length,purgeableCount:T.length-H.length,skippedIds:H}},ga=T=>{let F=`Purged ${T.deletedIds.length} session${T.deletedIds.length===1?"":"s"} for ${r}`;if(T.skippedIds.length===0)return F;let H=T.skippedIds.length===1?`Skipped active session: ${T.skippedIds[0]}`:`Skipped ${T.skippedIds.length} active sessions`;return`${F}. ${H}.`},fo=async()=>{let T=xn(),F=await Ze.purgeWorkingDirectory(r,{excludeSessionIds:T?[T]:void 0});for(let H of F.deletedIds)ZE.markParentOrphaned(H,"Parent session was purged.");return F},Br=async T=>{ZE.markParentOrphaned(T,"Parent session was deleted."),await Ze.delete(T);let F=my(r,".xeno","sessions",`${T}.md`);try{let H=await import("node:fs");H.existsSync(F)&&H.rmSync(F,{force:!0})}catch{}},qv=async()=>{let T=await v.actionPicker({title:"Sessions",description:"Choose action:",options:[{value:"list",label:"List",detail:"Browse, resume, export, or inspect saved sessions"},{value:"purge",label:"Purge",detail:"Delete saved sessions linked to this folder"}]});return T==="list"||T==="purge"?T:null},vu=async()=>{let T=await v.actionPicker({title:"Purge Sessions",description:"Choose purge mode:",options:[{value:"all",label:"Purge all",detail:"Delete all saved sessions linked to this folder"},{value:"selected",label:"Select from list",detail:"Choose specific sessions from this folder to delete"}]});return T==="all"||T==="selected"?T:null},Bp=async()=>{let T=await Qt({workingDirectory:r,allRoles:!0});if(T.length===0){v.writeInfo(`No sessions found for ${r}`);return}let F=T.map(xe=>({value:xe.meta.id,title:xe.preview,meta:xe.metaLine})),H=await v.sessionPicker({title:"Sessions",description:"Search sessions in this folder...",options:F,confirmLabel:"Enter to view"});if(!H)return;let z=T.find(xe=>xe.meta.id===H);if(!z)return;let ae=await ecn();if(ae){if(ae==="view"){await Xln(z);return}if(ae==="resume"){await Jy(z.meta.id);return}if(ae==="export-md"||ae==="export-json"){let xe=await Jln(z,ae==="export-md"?"md":"json");await Lvt({title:"Export Session",content:xe.content,defaultPath:xe.defaultPath,subject:xe.subject});return}ae==="delete"&&await v.modelPicker({title:"Delete session",description:"Type to filter",options:[{value:"cancel",label:"Cancel",detail:"(keep session)"},{value:"delete",label:`Delete ${z.meta.id}`,detail:"(permanent)"}],currentValue:"cancel"})==="delete"&&(await Ze.delete(z.meta.id),v.writeInfo(`Deleted session: ${z.meta.id}`))}},Qv=async()=>{let T=await vu();if(!T)return;if(T==="all"){let Ae=await Ti();if(Ae.matchingCount===0){v.writeInfo(`No sessions found for ${r}`);return}if(Ae.purgeableCount===0){v.writeInfo(`No purgeable sessions found for ${r}. Active session is still open.`);return}if(await v.actionPicker({title:"Purge Workspace Sessions",description:`Delete ${Ae.purgeableCount} saved session${Ae.purgeableCount===1?"":"s"} for ${r}?`,options:[{value:"cancel",label:"Cancel",detail:"Keep the saved sessions for this folder"},{value:"purge",label:"Purge sessions",detail:"Delete the saved sessions linked to this folder"}]})!=="purge")return;let J=await fo();v.writeInfo(ga(J));return}let F=xn(),H=await Qt({workingDirectory:r,excludeSessionIds:F?[F]:void 0,allRoles:!0});if(H.length===0){v.writeInfo(`No purgeable sessions found for ${r}`);return}let z=await v.sessionMultiPicker({title:"Purge Sessions",description:"Select sessions to delete",options:H.map(Ae=>({value:Ae.meta.id,title:Ae.preview,meta:Ae.metaLine})),confirmLabel:"Enter confirm"});if(!z||z.length===0)return;let ae=H.filter(Ae=>z.includes(Ae.meta.id));if(await v.actionPicker({title:"Delete Sessions",description:`Delete ${z.length} selected session${z.length===1?"":"s"}?`,options:[{value:"cancel",label:"Cancel",detail:"Keep the selected saved sessions"},{value:"delete",label:"Delete selected",detail:"Permanently remove the selected saved sessions"}]})==="delete"){for(let Ae of ae)await Br(Ae.meta.id);v.writeInfo(`Deleted ${ae.length} session${ae.length===1?"":"s"} from ${r}`)}},Jy=async(T,F,H=!1)=>{let z;try{if(H&&(!k?.detachedForHandoff||!re?.active))throw new Error("This terminal has no withdrawn offer to resume from.");if(F&&(!k?.detachedForHandoff||re?.active||q?.routesTurnsThroughHost))throw new Error("Only a detached local SDK cockpit can claim this handoff.");F&&!qX(e.executionAuthority)&&await gQe(T,F,e.executionOwnerId??re.ownerId);let ue=await QX(e.executionAuthority,T,F,r);ue&&v.writeInfo(ue),z=await DG({sessionId:T,cwd:r,currentSessionId:k?.meta.id,reclaimDetachedSession:!!F||H,bindExecutionLease:pt=>he(pt,F)})}catch(ue){if(v.writeInfo(G.red(`\u2717 Failed to resume session ${T}: ${ue instanceof Error?ue.message:String(ue)}`)),F||H)throw ue;return}if(!z){v.showTransientActivityNotice(`Session ${T} is already active.`);return}let{manager:ae,messages:xe}=z,Ae=ae.meta,V=Lm(Ae),J=k;k=ae,v.setSessionName(ae.meta.name),hr.syncPresence(),await wu.restoreSession().catch(ue=>{v.showTransientActivityNotice(`Artifact tray unavailable: ${ue instanceof Error?ue.message:String(ue)}`,8e3)}),P=Ze.getSessionDir(T),R=my(P,"history.jsonl"),S=ae.checkpoints,$=new NA(P,r),Ie.attachSessionIntegration({transcript:ae.transcript,checkpoints:S,sessionManager:ae,historyMarkdownPath:R,auditLogger:C}),await J?.detachForHandoff().catch(ue=>{v.writeInfo(G.red(`Previous session cleanup failed: ${ue instanceof Error?ue.message:String(ue)}`))}),Ie.messages=xe,F&&D0(zl,"execution-handoff-return"),k&&await k.updateMessageCount(xe.length),Ae.model&&Ae.model!==e.model&&(e.agentModelManaged=!1,e.model=Ae.model,await au(Ie,Ae.model),L.current?.setModel(Ae.model),Ie.systemPrompt=await Pp(),v.setModel(Ae.model)),await au(Ie,Ie.model),v.setContextBudgetTokens(Ie.modelContextWindow),V!==void 0&&await Fr(V),Pit(v,xe,it),v.showTransientActivityNotice(`Resumed session ${T.slice(0,8)} (${xe.length} messages)`);let oe=pe.restoreFromSession(Ae);oe.restored&&!oe.invalid&&v.writeInfo(Sge),oe.pending&&pe.presentPendingApproval()},Yq=T=>{let F=0;for(let H=0;H<Ie.messages.length;H++){let z=Ie.messages[H];if(!(z.role!=="user"||typeof z.content!="string"||z.synthetic==="self_review")){if(F===T)return H;F+=1}}return-1},GT=()=>P?($||($=new NA(P,r)),$):null,a_e=async T=>{let F=GT();if(Zf=null,!F)return;Zf=(await F.create({id:Lj(),restoreMessageCount:Ie.messages.length,userPrompt:T})).id},KM=async(T,F)=>{let H=GT();!H||!Zf||await H.recordToolExecution(Zf,T,F)},Zq=()=>{Zf=null},YE=async(T,F)=>{let H=Yq(T);if(H<0)return v.showTransientActivityNotice("Could not find that user turn to restore"),{ok:!1,exactWorkspaceRestore:!1,hadRestorePoint:!1,unsupportedTools:[],branchCheckpointId:null};let z=GT(),ae=z?await z.inspectAtOrAfter(H):null;if(F?.requireExactWorkspace){if(!ae?.hadRestorePoints)return v.showTransientActivityNotice("No safe workspace restore point for that turn"),{ok:!1,exactWorkspaceRestore:!1,hadRestorePoint:!1,unsupportedTools:[],branchCheckpointId:null};if(!ae.exactWorkspaceRestore){let V=ae.unsupportedTools.length>0?` because it used ${ae.unsupportedTools.join(", ")}`:"";return v.showTransientActivityNotice(`Exact workspace restore unavailable${V}`),{ok:!1,exactWorkspaceRestore:!1,hadRestorePoint:!0,unsupportedTools:ae.unsupportedTools,branchCheckpointId:null}}}let xe=F?.mode??"both";if(xe==="code")return ae?.hadRestorePoints&&await z.restoreAtOrAfter(H),{ok:!!ae?.hadRestorePoints,exactWorkspaceRestore:ae?.exactWorkspaceRestore??!1,hadRestorePoint:ae?.hadRestorePoints??!1,unsupportedTools:ae?.unsupportedTools??[],branchCheckpointId:null};let Ae=null;try{Ae=await aAe({checkpointManager:S,sessionManager:k,messages:Ie.messages,targetPrompt:typeof Ie.messages[H]?.content=="string"?Ie.messages[H].content:`message ${H+1}`})}catch(V){let J=V instanceof Error?V.message:String(V);return v.showTransientActivityNotice(`Could not save rewind branch: ${J}`),{ok:!1,exactWorkspaceRestore:!1,hadRestorePoint:ae?.hadRestorePoints??!1,unsupportedTools:ae?.unsupportedTools??[],branchCheckpointId:null}}return ae?.hadRestorePoints&&xe==="both"&&await z.restoreAtOrAfter(H),et.cancelContinuationsForOwner(Pd()),Zq(),Ie.messages=Ie.messages.slice(0,H),k&&(await k.updateMessageCount(Ie.messages.length),await k.transcript.truncateAfterMessageCount(H)),await Fvt(),v.clear(),v.writeOutput(XR(Pe,Uj(e),void 0,e.executionMode==="chatOnly"?"chat":"agent")),Pit(v,Ie.messages,it),{ok:!0,exactWorkspaceRestore:ae?.exactWorkspaceRestore??!1,hadRestorePoint:ae?.hadRestorePoints??!1,unsupportedTools:ae?.unsupportedTools??[],branchCheckpointId:Ae}},e8=0,YM=async()=>{let T=++e8,F=[...Ie.messages],H=GT(),z=Ie.messages.map((fe,St)=>({message:fe,index:St})).filter(({message:fe})=>fe.role==="user"&&typeof fe.content=="string"&&fe.synthetic!=="self_review").map(({message:fe,index:St},ot)=>({userOrdinal:ot,messageIndex:St,text:String(fe.content)}));if(z.length===0){v.showTransientActivityNotice("Nothing to rewind");return}let ae=await v.rewindPicker({entries:[...z.map(fe=>({value:String(fe.userOrdinal),text:fe.text,changes:null,...H?{changesState:"pending"}:{}})),{value:"__current__",text:"(current)",changes:null,current:!0}],loadChanges:H?async fe=>{let St=z.find(Tt=>Tt.userOrdinal===Number(fe));if(!St)return null;let ot=await H.inspectAtOrAfter(St.messageIndex);if(ot.gitInspectionError)throw new Error(ot.gitInspectionError.message);return HQt(ot.filePreviews,[...ot.gitChangedPaths,...ot.points.flatMap(Tt=>Tt.mutations.map(pn=>pn.relativePath))])}:void 0});if(!ae||ae==="__current__")return;let xe=Number(ae),Ae=z.find(fe=>fe.userOrdinal===xe);if(!Ae)return;H&&v.showTransientActivityNotice("Checking selected restore point\u2026");let V=H?await H.inspectAtOrAfter(Ae.messageIndex):null;if(T!==e8||v.busy||Ie.messages.length!==F.length||F.some((fe,St)=>Ie.messages[St]!==fe))return;let J=!!V?.hadRestorePoints,oe=await v.actionPicker({title:"Rewind",description:`Restore to before: ${Bpe(Ae.text)}`,options:[...J?[{value:"both",label:"Restore code and conversation",detail:"Files return to that point and the conversation is cut there"}]:[],{value:"conversation",label:"Restore conversation",detail:"Cut the conversation there; files stay as they are"},...J?[{value:"code",label:"Restore code",detail:"Files return to that point; the conversation stays"}]:[],{value:"cancel",label:"Never mind",detail:"Stay where you are"}],selectedIndex:0});if(!oe||oe==="cancel")return;let ue=oe==="code"?"code":oe==="conversation"?"conversation":"both",pt=await YE(xe,{mode:ue});if(!pt.ok){ue==="code"&&v.showTransientActivityNotice("No safe workspace restore point for that turn");return}let ct=Bpe(Ae.text),Vt=ue==="code"?`Restored code to before: ${ct}`:ue==="conversation"?`Restored conversation before: ${ct}`:`Restored to before: ${ct}`;ue!=="code"&&v.setInputText(Ae.text,{cursor:"end",escCancelable:!0});let ft=ue!=="conversation"&&pt.hadRestorePoint&&!pt.exactWorkspaceRestore&&pt.unsupportedTools.length>0?` Workspace restore stayed safe; exact rollback was blocked by ${pt.unsupportedTools.join(", ")}.`:"";v.showTransientActivityNotice(ft?`${ft.trim()} ${Vt}`:Vt,ft?12e3:4e3)},Fg=T=>T.every(F=>WCr(F)!==null),Vln=T=>{if(!T)return["Delegation summary: none recorded"];let F=[`Selected role: ${T.selectedRole??"-"}`,`Elapsed: ${Math.max(0,Math.round(T.elapsedMs/1e3))}s`,`Branches: ${T.okBranches}/${T.totalBranches} ok`,`Tokens: ${T.totalTokens}`];for(let[H,z]of Object.entries(T.roleSummaries))F.push(`${H}: ${z.status} \xB7 ${z.tokensUsed} tok${z.outputPreview?` \xB7 ${z.outputPreview}`:""}`);return F},l_e=T=>T.length===0?"(no restorable messages)":T.map(F=>{if(F.metadata?.source==="direct_shell"){let ae=F.metadata.directShell,xe=`${ae.status}${ae.exitCode===null?"":` (exit ${ae.exitCode})`}`;return[`[direct-shell:${ae.taskId}]`,`! ${ae.command}`,`${xe} | ${ae.cwd}`,ae.output].join(`
10411
10411
  `).trimEnd()}let H=F.role==="assistant"?"assistant":"user",z=WCr(F)??"";return[`[${H}]`,z].join(`
10412
10412
  `)}).join(`
10413
10413
 
@@ -10417,16 +10417,16 @@ ${G.accent("\u25A0")} ${T}`:T:null)),ge=de.reset.bind(de);de.reset=()=>{es=!1,ge
10417
10417
  `).slice(1).join(`
10418
10418
  `);if(xe.join(`
10419
10419
  `).trimEnd()!==ue)throw new Error("Direct-shell records are read-only");return oe}if(Ae!=="[user]"&&Ae!=="[assistant]")throw new Error("Invalid session conversation format");let J=xe.join(`
10420
- `).trimEnd();return{role:Ae==="[assistant]"?"assistant":"user",content:J}})},Xln=async T=>{let F=await qIe(T.meta.id),H=F.slice(-6),ae=await new xl(Ze.getSessionDir(T.meta.id)).read({types:["delegation_summary"]}),xe=ae.length>0?ae[ae.length-1]?.data:null;await v.infoPanel({title:"Session details",subtitle:T.metaLine,lines:[],layout:"viewport",focusPane:"content",footerHint:"\u2190/\u2192 focus \xB7 \u2191/\u2193 scroll pane \xB7 Enter edit \xB7 Esc close",cards:[{title:"Messages",value:String(F.length)},{title:"Status",value:T.meta.status.toUpperCase()},{title:"Role",value:T.meta.role},{title:"Model",value:T.meta.model},{title:"Delegations",value:String(ae.length)}],split:{left:{title:"Details",summary:`${F.length} messages`,lines:[`ID: ${T.meta.id}`,`Model: ${T.meta.model}`,`Role: ${T.meta.role}`,`Status: ${T.meta.status}`,`Messages: ${F.length}`,`Last activity: ${new Date(T.meta.lastActivity).toLocaleString()}`,`Working directory: ${T.meta.workingDirectory}`,"",...Vln(xe)]},right:{title:"Conversation History",summary:H.length>0?`${H.length} recent messages`:"preview only",lines:gy(l_e(F)),editable:Fg(F)?{label:"Conversation History",value:l_e(F),initialCursor:"start",previewLines:Ae=>gy(Ae),onSave:async Ae=>{let V=zln(Ae,F);if(V.length!==F.length)throw new Error("Message count must stay the same");return await new xl(Ze.getSessionDir(T.meta.id)).replaceMessages(V),{summary:`${V.length} messages`}}}:void 0}}})},Jln=async(T,F)=>{let H=await qIe(T.meta.id),z=`session-${T.meta.id}`;return F==="json"?{content:JSON.stringify(H,null,2),defaultPath:my(process.cwd(),`${z}.json`),subject:"session JSON"}:{content:Bj(H,T.meta.model),defaultPath:my(process.cwd(),`${z}.md`),subject:"session markdown"}},Kln=()=>new Date().toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"").replace("T","-"),Yln=()=>my(process.cwd(),`conversation-${k?.meta.id??Kln()}.md`),Zln=async()=>{await Lvt({title:"Export Conversation",content:Bj(Ie.messages,e.model),defaultPath:Yln(),subject:"conversation"})},Lvt=async T=>{let F=await v.actionPicker({title:T.title,description:"Select export method:",options:[{value:"copy",label:"Copy to clipboard",detail:`Copy the ${T.subject} to your system clipboard`},{value:"file",label:"Save to file",detail:"Save the export to a file in the current directory"}]});if(!F)return;if(F==="copy"){nG(T.content),v.writeInfo(`Copied ${T.subject} to clipboard`);return}(await import("node:fs")).writeFileSync(T.defaultPath,T.content,"utf-8"),v.writeInfo(`Saved ${T.subject}: ${T.defaultPath}`)},ecn=async()=>{let T=await v.modelPicker({title:"Session action",description:"Choose action",options:[{value:"view",label:"View details",detail:"(preview and metadata)"},{value:"resume",label:"Resume session",detail:"(restore conversation)"},{value:"export-md",label:"Export markdown",detail:"(opens export method picker)"},{value:"export-json",label:"Export JSON",detail:"(opens export method picker)"},{value:"delete",label:"Delete session",detail:"(remove permanently)"}]});return T&&(T==="view"||T==="resume"||T==="export-md"||T==="export-json"||T==="delete")?T:null},tcn=()=>{if(Yf)throw new Error("A delegated turn is already active in this terminal.");_g=new Set,Rd=new Map,Yf=new Promise(T=>{Bv=T})},rcn=()=>{Bv?.(),Bv=null,Yf=null},ncn=async()=>{await Yf,await Ee?.waitForSafePoint();let T=et.list({ownerSessionId:Pd(),terminal:!1});for(let F of T){for(;!et.get(F.operationId)?.terminal;)await et.waitForTerminal(F.operationId,{timeoutMs:6e4});Rd.set(F.operationId,{operationId:F.operationId,kind:F.toolName==="Bash"?"command":"tool",status:"completed",sideEffecting:!0,recovery:"waited"})}return{agentIds:[..._g],operations:[...Rd.values()]}},icn=async T=>{tcn();try{let F=`session-${k?.meta.id??"unknown"}-${Date.now().toString(36)}`,H=zit(jt),z=[...H.roles],ae=Date.now(),xe=new AbortController;uo=xe;let Ae,V=Qw(process.env[pf]);if(V!=="off"&&e.permissionMode!=="plan")try{let{host:fe,binding:St}=await q.delegationHost(),ot=k?`session-${k.meta.id}`:St.conversationId;if(ot!==St.conversationId){let Tt=await fe.client.openConversation({conversationId:ot,mode:"development",workingDirectory:r});if(!Tt.success)throw new Error(Tt.error??"The Agent host refused to bind the delegated parent workspace.")}Ae={client:fe.client,parentConversationId:ot,parentAgentId:"agent-main",workspaceId:r,teamId:H.teamPreset??"delegation"},v.appendDelegationEvent("system","Delegated branches are owned by the shared Agent host")}catch(fe){if(V==="required")throw fe;v.appendDelegationEvent("system",`Agent host unavailable; branches remain local (${fe instanceof Error?fe.message:String(fe)})`)}let J=new Map;Rg.clear(),v.startDelegationView(z),v.appendDelegationEvent("system",`Workflow started (${H.mode}, max ${H.maxConcurrentBranches??z.length} concurrent)`);let oe;try{oe=await Nz({userPrompt:T,cwd:r,apiKey:e.apiKey,baseURL:e.baseURL,model:e.model,...e.fallbackModels?{fallbackModels:e.fallbackModels}:{},...e.effort?{effort:e.effort}:{},maxIterations:e.maxIterations,maxTotalTokens:jt.maxTotalTokens,timeoutMs:jt.timeoutMs,rolePrecedence:jt.rolePrecedence,branchPolicy:WTr(jt),parentSystemPrompt:await Xw({cwd:r,model:e.model,executionMode:qe,profile:ks(e,r),ownerSessionId:Xr}),parentExecutionMode:qe,auditLogger:C,rootTraceId:F,signal:xe.signal,skipAuditCompletion:!0,childController:Kf,...Ae?{hostDelegation:Ae}:{},onBranchStart:async fe=>{if(Li)throw new ji;let St=`branch:${F}:${fe.id}`;_g.add(St),Rd.set(St,{operationId:St,kind:"subagent",status:"running",sideEffecting:!0,recovery:"waited"}),J.set(fe.id,0),v.updateDelegationAgent(fe.role,{status:"running",phase:"thinking",activity:"Starting delegated branch"}),v.appendDelegationEvent(fe.role,"started"),Ae&&await cb(_e(`branch-${fe.id}`,"agent-main"),{taskId:fe.id,role:fe.role,prompt:fe.prompt,maxTokens:fe.maxTokens,maxIterations:fe.maxIterations})},...Ae?{}:{createBranchAgent:async({task:fe})=>{let St=xf(Xr,"branch",fe.role);ie.register(St);let ot=ks(e,r),Tt=sP({registry:XTr(r,fe.role,H,Gl,O,e.securityPolicy,St,ot),cwd:r,profile:ot,safeMode:e.safeMode,currentUserPrompt:()=>a,hookMiddleware:Mp(`branch-${fe.id}`,"agent-main",void 0,void 0,ot?.capabilities.hooks),onSkillAudit:qn=>bC(C,qn,"branch"),inheritedActivations:Ic?.active()}),pn=zw({cwd:r,registry:Tt.registry,mcpManager:O,profile:ot,beforeStep:()=>D(),getParentProfile:()=>ks(e,r),metadata:{kind:"branch",taskId:fe.id,role:fe.role},mcpFilter:qn=>WB(qn,kR(H,fe.role)),hooks:_e(`branch-${fe.id}`,"agent-main",void 0,void 0,ot?.capabilities.hooks)}),wa=0,Iu=new bR({cwd:r}),ku=(await qL({cwd:r,sandbox:e.securityPolicy,apiKey:e.apiKey,baseURL:e.baseURL,model:e.model,...e.fallbackModels?{fallbackModels:e.fallbackModels}:{},...e.effort?{effort:e.effort}:{},maxTokens:hS(fe.maxTokens,e.maxTokens),turnTokenBudget:fe.maxTokens,maxIterations:fe.maxIterations,parentSystemPrompt:await Xw({cwd:r,model:e.model,executionMode:qe,profile:ot,ownerSessionId:St}),parentExecutionMode:qe,subagentRole:fe.role,permissionEngine:Vl,toolRegistry:Tt.registry,runAuthority:pn.runAuthority,toolMiddleware:[...Tt.toolMiddleware,pn.middleware],promptSections:Tt.promptSections,...C?{session:{auditLogger:C}}:{},turnDiffTracker:Iu,onTurnDiff:async qn=>{await xye({cwd:r,summary:qn,producer:{kind:"agent",id:`branch-${fe.id}`},...k?.meta.id?{sessionId:k.meta.id}:{},runId:F})},onIteration:(qn,Va)=>{wa=Va,v.updateDelegationAgent(fe.role,{phase:"thinking",activity:`Iteration ${qn}`,tokenCount:Va})},onRuntimeEvent:qn=>{qn.type!=="provider.event"||qn.event.type!=="usage.updated"||v.updateDelegationAgent(fe.role,{tokenCount:wa+qn.event.inputTokens+qn.event.outputTokens})},onToolStart:(qn,Va)=>{let ur=(J.get(fe.id)??0)+1;J.set(fe.id,ur);let Cn=D3i(qn,Va);v.updateDelegationAgent(fe.role,{phase:"tool",activity:Cn,toolCount:ur,tokenCount:ku.tokenUsage.total,currentTool:qn}),v.appendDelegationEvent(fe.role,`${Cn} started`)},onToolWillExecute:async(qn,Va)=>{await re?.assertOwned(),await KM(qn,Va)},onToolEnd:(qn,Va)=>{let ur=Va.success?"completed":"failed";v.updateDelegationAgent(fe.role,{phase:Va.success?"thinking":"failed",activity:`${qn} ${ur}`,toolCount:J.get(fe.id)??0,tokenCount:ku.tokenUsage.total,currentTool:void 0}),v.appendDelegationEvent(fe.role,`${qn} ${ur}`)}})).agent;return await JE(ku,e.model,fe.maxTokens),yu=ku,Rg.set(fe.role,{agent:ku,finished:!1,taskId:fe.id}),WG(l_(ku,St),pn)}},onBranchComplete:async(fe,St)=>{let ot=`branch:${F}:${fe.id}`,Tt=St.traceId??ot;_g.delete(ot),_g.add(Tt),Rd.set(ot,{operationId:ot,kind:"subagent",status:"completed",sideEffecting:!0,recovery:"waited"});let pn=Rg.get(fe.role)?.agent.lastRunTermination,wa=fI(pn);v.updateDelegationAgent(fe.role,wa?{status:"done",phase:"done",activity:"Completed",toolCount:J.get(fe.id)??0,tokenCount:St.tokenUsage.total,currentTool:void 0,outputPreview:Fit(St.output)}:{status:"unfinished",phase:"unfinished",activity:`Stopped before finishing (${pn?.reason??"unknown"})`,toolCount:J.get(fe.id)??0,tokenCount:St.tokenUsage.total,currentTool:void 0}),v.appendDelegationEvent(fe.role,wa?"completed":`stopped before finishing (${pn?.reason??"unknown"})`);{let Iu=Rg.get(fe.role);Iu&&(Iu.finished=!0)}if(yu=null,Ae)try{await Gm(_e(`branch-${fe.id}`,"agent-main"),{taskId:fe.id,role:fe.role,status:"completed",traceId:St.traceId,tokenUsage:St.tokenUsage})}catch{}},onBranchError:async(fe,St,ot)=>{let Tt=`branch:${F}:${fe.id}`;Rd.set(Tt,{operationId:Tt,kind:"subagent",status:"interrupted",sideEffecting:!0,recovery:"retry"});let pn=St instanceof ji||St instanceof aw;v.updateDelegationAgent(fe.role,{status:pn?"interrupted":"failed",phase:pn?"interrupted":"failed",activity:pn?St instanceof aw?"Stopped":"Interrupted":St instanceof Error?St.message:String(St),toolCount:J.get(fe.id)??0,tokenCount:ot.tokenUsage.total,currentTool:void 0}),v.appendDelegationEvent(fe.role,pn?"interrupted":"failed");{let wa=Rg.get(fe.role);wa&&(wa.finished=!0)}if(yu=null,Ae)try{await Gm(_e(`branch-${fe.id}`,"agent-main"),{taskId:fe.id,role:fe.role,status:pn?"interrupted":"failed",error:St instanceof Error?St.message:String(St),tokenUsage:ot.tokenUsage})}catch{}}})}catch(fe){throw v.appendDelegationEvent("system",fe instanceof ji?"Workflow interrupted":`Workflow failed: ${fe instanceof Error?fe.message:String(fe)}`),fe}finally{uo===xe&&(uo=null),yu=null}let ue=PTr(oe.workflow,oe.tokenUsage.total,Date.now()-ae),pt=oe.answer,ct=oe.selectedTraceId;Jt.input+=oe.tokenUsage.input,Jt.output+=oe.tokenUsage.output,Jt.total+=oe.tokenUsage.total;let Gt=[...Ie.messages,{role:"user",content:T},{role:"assistant",content:pt}];Ie.messages=Gt,k&&(await k.recordUserMessage(T),await k.recordAssistantMessage(pt),await k.recordTokenUsage(oe.tokenUsage.input,oe.tokenUsage.output),await k.recordDelegationSummary(ue)),await C?.append({trace_id:ct??F,event_type:"delegation_completed",actor:"system",risk_level:"none",status:"ok",metadata:{selected_from:oe.workflow.reduced.selectedFrom,subagents:oe.summary,branch_policy:{mode:H.mode,roles:H.roles,max_concurrent_branches:H.maxConcurrentBranches},delegation_summary:ue,recent_activity:oe.workflow.results.map(fe=>({role:fe.role,status:fe.status,preview:fe.status==="ok"?Fit(fe.output):fe.error}))}}),v.appendDelegationEvent("system",L3i(ue));let ft=VG(oe);ft&&(v.appendDelegationEvent("system",ft),v.writeError(ft)),v.trimTrailingOutputNewlines(1),v.writeOutput(`
10420
+ `).trimEnd();return{role:Ae==="[assistant]"?"assistant":"user",content:J}})},Xln=async T=>{let F=await qIe(T.meta.id),H=F.slice(-6),ae=await new xl(Ze.getSessionDir(T.meta.id)).read({types:["delegation_summary"]}),xe=ae.length>0?ae[ae.length-1]?.data:null;await v.infoPanel({title:"Session details",subtitle:T.metaLine,lines:[],layout:"viewport",focusPane:"content",footerHint:"\u2190/\u2192 focus \xB7 \u2191/\u2193 scroll pane \xB7 Enter edit \xB7 Esc close",cards:[{title:"Messages",value:String(F.length)},{title:"Status",value:T.meta.status.toUpperCase()},{title:"Role",value:T.meta.role},{title:"Model",value:T.meta.model},{title:"Delegations",value:String(ae.length)}],split:{left:{title:"Details",summary:`${F.length} messages`,lines:[`ID: ${T.meta.id}`,`Model: ${T.meta.model}`,`Role: ${T.meta.role}`,`Status: ${T.meta.status}`,`Messages: ${F.length}`,`Last activity: ${new Date(T.meta.lastActivity).toLocaleString()}`,`Working directory: ${T.meta.workingDirectory}`,"",...Vln(xe)]},right:{title:"Conversation History",summary:H.length>0?`${H.length} recent messages`:"preview only",lines:gy(l_e(F)),editable:Fg(F)?{label:"Conversation History",value:l_e(F),initialCursor:"start",previewLines:Ae=>gy(Ae),onSave:async Ae=>{let V=zln(Ae,F);if(V.length!==F.length)throw new Error("Message count must stay the same");return await new xl(Ze.getSessionDir(T.meta.id)).replaceMessages(V),{summary:`${V.length} messages`}}}:void 0}}})},Jln=async(T,F)=>{let H=await qIe(T.meta.id),z=`session-${T.meta.id}`;return F==="json"?{content:JSON.stringify(H,null,2),defaultPath:my(process.cwd(),`${z}.json`),subject:"session JSON"}:{content:Bj(H,T.meta.model),defaultPath:my(process.cwd(),`${z}.md`),subject:"session markdown"}},Kln=()=>new Date().toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"").replace("T","-"),Yln=()=>my(process.cwd(),`conversation-${k?.meta.id??Kln()}.md`),Zln=async()=>{await Lvt({title:"Export Conversation",content:Bj(Ie.messages,e.model),defaultPath:Yln(),subject:"conversation"})},Lvt=async T=>{let F=await v.actionPicker({title:T.title,description:"Select export method:",options:[{value:"copy",label:"Copy to clipboard",detail:`Copy the ${T.subject} to your system clipboard`},{value:"file",label:"Save to file",detail:"Save the export to a file in the current directory"}]});if(!F)return;if(F==="copy"){nG(T.content),v.writeInfo(`Copied ${T.subject} to clipboard`);return}(await import("node:fs")).writeFileSync(T.defaultPath,T.content,"utf-8"),v.writeInfo(`Saved ${T.subject}: ${T.defaultPath}`)},ecn=async()=>{let T=await v.modelPicker({title:"Session action",description:"Choose action",options:[{value:"view",label:"View details",detail:"(preview and metadata)"},{value:"resume",label:"Resume session",detail:"(restore conversation)"},{value:"export-md",label:"Export markdown",detail:"(opens export method picker)"},{value:"export-json",label:"Export JSON",detail:"(opens export method picker)"},{value:"delete",label:"Delete session",detail:"(remove permanently)"}]});return T&&(T==="view"||T==="resume"||T==="export-md"||T==="export-json"||T==="delete")?T:null},tcn=()=>{if(Yf)throw new Error("A delegated turn is already active in this terminal.");_g=new Set,Rd=new Map,Yf=new Promise(T=>{Bv=T})},rcn=()=>{Bv?.(),Bv=null,Yf=null},ncn=async()=>{await Yf,await Ee?.waitForSafePoint();let T=et.list({ownerSessionId:Pd(),terminal:!1});for(let F of T){for(;!et.get(F.operationId)?.terminal;)await et.waitForTerminal(F.operationId,{timeoutMs:6e4});Rd.set(F.operationId,{operationId:F.operationId,kind:F.toolName==="Bash"?"command":"tool",status:"completed",sideEffecting:!0,recovery:"waited"})}return{agentIds:[..._g],operations:[...Rd.values()]}},icn=async T=>{tcn();try{let F=`session-${k?.meta.id??"unknown"}-${Date.now().toString(36)}`,H=zit(jt),z=[...H.roles],ae=Date.now(),xe=new AbortController;uo=xe;let Ae,V=Qw(process.env[pf]);if(V!=="off"&&e.permissionMode!=="plan")try{let{host:fe,binding:St}=await q.delegationHost(),ot=k?`session-${k.meta.id}`:St.conversationId;if(ot!==St.conversationId){let Tt=await fe.client.openConversation({conversationId:ot,mode:"development",workingDirectory:r});if(!Tt.success)throw new Error(Tt.error??"The Agent host refused to bind the delegated parent workspace.")}Ae={client:fe.client,parentConversationId:ot,parentAgentId:"agent-main",workspaceId:r,teamId:H.teamPreset??"delegation"},v.appendDelegationEvent("system","Delegated branches are owned by the shared Agent host")}catch(fe){if(V==="required")throw fe;v.appendDelegationEvent("system",`Agent host unavailable; branches remain local (${fe instanceof Error?fe.message:String(fe)})`)}let J=new Map;Rg.clear(),v.startDelegationView(z),v.appendDelegationEvent("system",`Workflow started (${H.mode}, max ${H.maxConcurrentBranches??z.length} concurrent)`);let oe;try{oe=await Nz({userPrompt:T,cwd:r,apiKey:e.apiKey,baseURL:e.baseURL,model:e.model,...e.fallbackModels?{fallbackModels:e.fallbackModels}:{},...e.effort?{effort:e.effort}:{},maxIterations:e.maxIterations,maxTotalTokens:jt.maxTotalTokens,timeoutMs:jt.timeoutMs,rolePrecedence:jt.rolePrecedence,branchPolicy:WTr(jt),parentSystemPrompt:await Xw({cwd:r,model:e.model,executionMode:qe,profile:ks(e,r),ownerSessionId:Xr}),parentExecutionMode:qe,auditLogger:C,rootTraceId:F,signal:xe.signal,skipAuditCompletion:!0,childController:Kf,...Ae?{hostDelegation:Ae}:{},onBranchStart:async fe=>{if(Li)throw new ji;let St=`branch:${F}:${fe.id}`;_g.add(St),Rd.set(St,{operationId:St,kind:"subagent",status:"running",sideEffecting:!0,recovery:"waited"}),J.set(fe.id,0),v.updateDelegationAgent(fe.role,{status:"running",phase:"thinking",activity:"Starting delegated branch"}),v.appendDelegationEvent(fe.role,"started"),Ae&&await cb(_e(`branch-${fe.id}`,"agent-main"),{taskId:fe.id,role:fe.role,prompt:fe.prompt,maxTokens:fe.maxTokens,maxIterations:fe.maxIterations})},...Ae?{}:{createBranchAgent:async({task:fe})=>{let St=xf(Xr,"branch",fe.role);ie.register(St);let ot=ks(e,r),Tt=sP({registry:XTr(r,fe.role,H,Gl,O,e.securityPolicy,St,ot),cwd:r,profile:ot,safeMode:e.safeMode,currentUserPrompt:()=>a,hookMiddleware:Mp(`branch-${fe.id}`,"agent-main",void 0,void 0,ot?.capabilities.hooks),onSkillAudit:qn=>bC(C,qn,"branch"),inheritedActivations:Ic?.active()}),pn=zw({cwd:r,registry:Tt.registry,mcpManager:O,profile:ot,beforeStep:()=>D(),getParentProfile:()=>ks(e,r),metadata:{kind:"branch",taskId:fe.id,role:fe.role},mcpFilter:qn=>WB(qn,kR(H,fe.role)),hooks:_e(`branch-${fe.id}`,"agent-main",void 0,void 0,ot?.capabilities.hooks)}),wa=0,Iu=new bR({cwd:r}),ku=(await qL({cwd:r,sandbox:e.securityPolicy,apiKey:e.apiKey,baseURL:e.baseURL,model:e.model,...e.fallbackModels?{fallbackModels:e.fallbackModels}:{},...e.effort?{effort:e.effort}:{},maxTokens:hS(fe.maxTokens,e.maxTokens),turnTokenBudget:fe.maxTokens,maxIterations:fe.maxIterations,parentSystemPrompt:await Xw({cwd:r,model:e.model,executionMode:qe,profile:ot,ownerSessionId:St}),parentExecutionMode:qe,subagentRole:fe.role,permissionEngine:Vl,toolRegistry:Tt.registry,runAuthority:pn.runAuthority,toolMiddleware:[...Tt.toolMiddleware,pn.middleware],promptSections:Tt.promptSections,...C?{session:{auditLogger:C}}:{},turnDiffTracker:Iu,onTurnDiff:async qn=>{await xye({cwd:r,summary:qn,producer:{kind:"agent",id:`branch-${fe.id}`},...k?.meta.id?{sessionId:k.meta.id}:{},runId:F})},onIteration:(qn,Va)=>{wa=Va,v.updateDelegationAgent(fe.role,{phase:"thinking",activity:`Iteration ${qn}`,tokenCount:Va})},onRuntimeEvent:qn=>{qn.type!=="provider.event"||qn.event.type!=="usage.updated"||v.updateDelegationAgent(fe.role,{tokenCount:wa+qn.event.inputTokens+qn.event.outputTokens})},onToolStart:(qn,Va)=>{let ur=(J.get(fe.id)??0)+1;J.set(fe.id,ur);let Cn=D3i(qn,Va);v.updateDelegationAgent(fe.role,{phase:"tool",activity:Cn,toolCount:ur,tokenCount:ku.tokenUsage.total,currentTool:qn}),v.appendDelegationEvent(fe.role,`${Cn} started`)},onToolWillExecute:async(qn,Va)=>{await re?.assertOwned(),await KM(qn,Va)},onToolEnd:(qn,Va)=>{let ur=Va.success?"completed":"failed";v.updateDelegationAgent(fe.role,{phase:Va.success?"thinking":"failed",activity:`${qn} ${ur}`,toolCount:J.get(fe.id)??0,tokenCount:ku.tokenUsage.total,currentTool:void 0}),v.appendDelegationEvent(fe.role,`${qn} ${ur}`)}})).agent;return await JE(ku,e.model,fe.maxTokens),yu=ku,Rg.set(fe.role,{agent:ku,finished:!1,taskId:fe.id}),WG(l_(ku,St),pn)}},onBranchComplete:async(fe,St)=>{let ot=`branch:${F}:${fe.id}`,Tt=St.traceId??ot;_g.delete(ot),_g.add(Tt),Rd.set(ot,{operationId:ot,kind:"subagent",status:"completed",sideEffecting:!0,recovery:"waited"});let pn=Rg.get(fe.role)?.agent.lastRunTermination,wa=fI(pn);v.updateDelegationAgent(fe.role,wa?{status:"done",phase:"done",activity:"Completed",toolCount:J.get(fe.id)??0,tokenCount:St.tokenUsage.total,currentTool:void 0,outputPreview:Fit(St.output)}:{status:"unfinished",phase:"unfinished",activity:`Stopped before finishing (${pn?.reason??"unknown"})`,toolCount:J.get(fe.id)??0,tokenCount:St.tokenUsage.total,currentTool:void 0}),v.appendDelegationEvent(fe.role,wa?"completed":`stopped before finishing (${pn?.reason??"unknown"})`);{let Iu=Rg.get(fe.role);Iu&&(Iu.finished=!0)}if(yu=null,Ae)try{await Gm(_e(`branch-${fe.id}`,"agent-main"),{taskId:fe.id,role:fe.role,status:"completed",traceId:St.traceId,tokenUsage:St.tokenUsage})}catch{}},onBranchError:async(fe,St,ot)=>{let Tt=`branch:${F}:${fe.id}`;Rd.set(Tt,{operationId:Tt,kind:"subagent",status:"interrupted",sideEffecting:!0,recovery:"retry"});let pn=St instanceof ji||St instanceof aw;v.updateDelegationAgent(fe.role,{status:pn?"interrupted":"failed",phase:pn?"interrupted":"failed",activity:pn?St instanceof aw?"Stopped":"Interrupted":St instanceof Error?St.message:String(St),toolCount:J.get(fe.id)??0,tokenCount:ot.tokenUsage.total,currentTool:void 0}),v.appendDelegationEvent(fe.role,pn?"interrupted":"failed");{let wa=Rg.get(fe.role);wa&&(wa.finished=!0)}if(yu=null,Ae)try{await Gm(_e(`branch-${fe.id}`,"agent-main"),{taskId:fe.id,role:fe.role,status:pn?"interrupted":"failed",error:St instanceof Error?St.message:String(St),tokenUsage:ot.tokenUsage})}catch{}}})}catch(fe){throw v.appendDelegationEvent("system",fe instanceof ji?"Workflow interrupted":`Workflow failed: ${fe instanceof Error?fe.message:String(fe)}`),fe}finally{uo===xe&&(uo=null),yu=null}let ue=PTr(oe.workflow,oe.tokenUsage.total,Date.now()-ae),pt=oe.answer,ct=oe.selectedTraceId;Jt.input+=oe.tokenUsage.input,Jt.output+=oe.tokenUsage.output,Jt.total+=oe.tokenUsage.total;let Vt=[...Ie.messages,{role:"user",content:T},{role:"assistant",content:pt}];Ie.messages=Vt,k&&(await k.recordUserMessage(T),await k.recordAssistantMessage(pt),await k.recordTokenUsage(oe.tokenUsage.input,oe.tokenUsage.output),await k.recordDelegationSummary(ue)),await C?.append({trace_id:ct??F,event_type:"delegation_completed",actor:"system",risk_level:"none",status:"ok",metadata:{selected_from:oe.workflow.reduced.selectedFrom,subagents:oe.summary,branch_policy:{mode:H.mode,roles:H.roles,max_concurrent_branches:H.maxConcurrentBranches},delegation_summary:ue,recent_activity:oe.workflow.results.map(fe=>({role:fe.role,status:fe.status,preview:fe.status==="ok"?Fit(fe.output):fe.error}))}}),v.appendDelegationEvent("system",L3i(ue));let ft=VG(oe);ft&&(v.appendDelegationEvent("system",ft),v.writeError(ft)),v.trimTrailingOutputNewlines(1),v.writeOutput(`
10421
10421
  ${G.accent("\u25A0")} `,{forceNewBlock:!0,selectable:!0,blockKind:"assistant"}),de.reset(),de.markLineStarted(),de.write(pt),de.flush(),v.writeOutput(`
10422
- `,{selectable:!0,blockKind:"assistant"})}finally{rcn()}},Fvt=async()=>{Rr=await Y0(x,k?.meta.id),Hr=HB(Rr),v&&v.setPromptContextBreakdown(Hr),Ie&&(Ie.systemPrompt=await Pp())},Uvt=async()=>{if(k)return await Pw(k,qe),!0;try{let T=await BR({sessionManager:k,checkpointManager:S,memoryManager:x,identityResolver:E,auditLogger:C,restoredMessages:_,sessionDir:P,sessionHistoryPath:R,turnRestoreManager:$},{cwd:r,...i?{role:i}:{},...o?{memoryScope:o}:{},model:e.model,projectSessionContext:qj(e)});k=T.sessionManager,S=T.checkpointManager,x=T.memoryManager,E=T.identityResolver,C=T.auditLogger,_=T.restoredMessages,P=T.sessionDir,R=T.sessionHistoryPath,$=T.turnRestoreManager??null,Wa=S?new CR(S):void 0;let F=T.sessionManager;if(!F)throw new Error("Session activation succeeded without a session manager");return await he(F),await Pw(F,qe),await pe.persist(),Ie.attachSessionIntegration({transcript:F.transcript,checkpoints:S,sessionManager:F,historyMarkdownPath:R,auditLogger:C}),v.setSessionName(F.meta.name),hr.syncPresence(),await Fvt(),!0}catch(T){let F=T instanceof Error?T.message:String(T);return v.writeInfo(G.red(`? Error creating session: ${F}`)),!1}},c_e,t8=()=>k?Uvt():(c_e??=Uvt().finally(()=>{c_e=void 0}),c_e),Ug=new tt,ZE=new ms,d_e=!1,u_e=!1,p_e=!1,r8,jvt=et;lr=()=>{if(!v)return;let T=k?.meta.id??Xr,F=Ut.listRuns().filter(J=>E3i(J,Ut)).map(C3i),H=Ug.list({cwd:r}).filter(J=>J.parentSessionId===T).filter(jCr),z=new Set(H.map(J=>J.sessionId));for(let[J,oe]of mm)(z.has(J)||Date.now()-oe.addedAt>1e4||!jCr(oe.record))&&mm.delete(J);let ae=[...Array.from(mm.values()).map(J=>J.record),...H.filter(J=>!mm.has(J.sessionId))],xe=bt.list().filter(J=>J.origin!=="user_direct_shell"&&(J.ownerSessionId===T||!J.ownerSessionId)).filter(J=>J.status==="running"||J.endedAt&&Date.now()-J.endedAt<3e4).map(J=>{let oe=J.status==="running",ue=J.endedAt?J.endedAt-J.startedAt:Date.now()-J.startedAt;return{id:J.id,name:J.id,title:J.command?J.command.replace(/\r?\n/g," ").slice(0,40):void 0,status:J.status,terminal:!oe,elapsedMs:ue}}),Ae=Array.from($p.entries()).filter(([,J])=>J.endedAt===void 0||Date.now()-J.endedAt<6e4).map(([J,oe])=>{let ue=kHt(oe,oe.childId!==void 0?Mg.get(oe.childId):void 0);return{id:J,name:oe.name,title:"dispatched",status:ue.status,terminal:ue.terminal,elapsedMs:(oe.endedAt??Date.now())-oe.startedAt,tokenCount:oe.agent.tokenUsage.total}}),V=[...F,...ae.map(I3i),...Ae,...xe];v.setAgentSessionFooterItems(V),v.setPendingAgentSessionNotifications(yF()?ZE.listPending(T).map(AX):[])};let n8,qvt=new Map;async function Qvt(T){if(Se||!v.canAcceptExternalInput||v.hasQueuedMessage||un||!k)return;let F=k.meta.id;try{let H=JSON.stringify([T.kind,F]),z=qvt.get(H)??{};qvt.set(H,z);let ae=await DSr({kind:T.kind,parentSessionId:F,items:T.read(F),limit:T.limit,render:T.render,store:new Yn,scan:z});if(!ae||Se||k?.meta.id!==F||un||!v.canAcceptExternalInput||v.hasQueuedMessage)return;if(ae.kind==="hold"){n8!==ae.reason&&v.showTransientActivityNotice(`Result delivery held: ${ae.reason}`),n8=ae.reason;return}if(ae.kind==="suppress"){for(let Ae of ae.members)T.suppress(Ae,ae.reason);return}if(ae.kind==="ack"){for(let Ae of ae.members)T.acknowledge(Ae);return}if(await re?.assertOwned(),Se||k?.meta.id!==F||un||!v.canAcceptExternalInput||v.hasQueuedMessage)return;for(let Ae of ae.members){let V=T.claim(Ae,ae.batch);if(!V||V.acknowledgedAt||V.orphanedAt||V.automaticSuppressedAt||!V.deliveredAt&&!FL(V.lastDelivery,ae.batch))throw new Error("Notification delivery claim is unconfirmed or changed; inspect pending results before retrying")}let xe=await Hv(ae.input,{requestId:ae.batch.messageId,goal:ae.goal});if(xe==="completed"||xe==="suspended")for(let Ae of ae.members)T.acknowledge(Ae);n8=void 0}catch(H){let z=H instanceof Error?H.message:String(H);n8!==z&&v.showTransientActivityNotice(`Result delivery held: ${AC(z)}`),n8=z}finally{lr()}}let ocn=async()=>{if(!(!yF()||d_e)){d_e=!0;try{await Qvt({kind:"agent",limit:aTr,read:T=>ZE.list({parentSessionId:T}),render:bX,claim:(T,F)=>ZE.markDeliveryAttempt(T.notificationId,F),acknowledge:T=>ZE.markDelivered(T.notificationId),suppress:(T,F)=>ZE.suppressAutomaticDelivery(T.notificationId,F)})}finally{d_e=!1}}},scn=async()=>{if(!(kTr()||u_e)){u_e=!0;try{await Qvt({kind:"workflow",limit:lTr,read:T=>Ut.listRuns().filter(F=>F.parentSessionId===T).flatMap(F=>Ut.readNotifications(F.workflowRunId)),render:ETr,claim:(T,F)=>Ut.markNotificationAttempt(T.workflowRunId,T.notificationId,F),acknowledge:T=>Ut.markNotificationDelivered(T.workflowRunId,T.notificationId),suppress:(T,F)=>Ut.suppressAutomaticNotification(T.workflowRunId,T.notificationId,F)})}finally{u_e=!1}}},Hvt=async()=>{if(process.env.XENO_AUTO_TOOL_CONTINUATION==="0"||Se||!v||!v.canAcceptExternalInput||v.hasQueuedMessage||un||p_e)return;let T=Pd(),F=et.listContinuations(T,"ready")[0];if(!F)return;p_e=!0;let H=k?.meta.id,z=null;try{let ae=await MSr(new Yn,F,Wh(H));if(H!==k?.meta.id||Se||un||!v.canAcceptExternalInput||v.hasQueuedMessage)return;if(ae.kind==="cancel"||ae.kind==="delivered"){ae.kind==="cancel"?et.cancelContinuation(F.continuationId):et.markContinuationCompleted(F.continuationId);return}if(ae.kind!=="run"){r8!==ae.reason&&v.showTransientActivityNotice(`Tool continuation held: ${ae.reason}`),r8=ae.reason;return}if(jt.enabled||q?.routesTurnsThroughHost)throw new Error("Pending local SDK results require their local execution lane; no provider handoff was authorized.");let xe=`tool-continuation-${F.continuationId}-${F.continuationTurns+1}`;z=jvt.markContinuationRunning(F.continuationId,{messageId:xe});let Ae=et.list({ownerSessionId:T}).filter(J=>F.operationIds.includes(J.operationId)||J.turnId===F.sourceTurnId).filter(J=>J.terminal);if(z?.status==="exhausted"){v.writeInfo(mB(z,Ae));return}if(z?.status!=="running")return;let V=await Hv(WW(z,Ae),{requestId:xe,goal:ae.goal,toolContinuation:z});V==="completed"||V==="suspended"?et.markContinuationCompleted(F.continuationId):et.retryContinuation(F.continuationId),r8=void 0}catch(ae){z?.status==="running"&&et.retryContinuation(F.continuationId);let xe=ae instanceof Error?ae.message:String(ae);r8!==xe&&v.showTransientActivityNotice(`Tool continuation held: ${AC(xe)}`),r8=xe}finally{p_e=!1}},f_e=async()=>{await Hvt(),await ocn(),await scn(),await Wvt()};async function Wvt(){if(Se||!Fi||ni||un||v.busy||v.hasQueuedMessage||!k)return;ni=!0;let T=k.meta.id,F=b,H=new Yn;try{let z=await H.getActive(Wh(T));if(k?.meta.id!==T||b!==F||un||v.busy||!z||z.status!=="active"||z.continuationLoop?.status!=="running")return;if(e.permissionMode==="plan"){yn!==Cge&&v.showTransientActivityNotice(Cge),yn=Cge;return}if(z.continuationLoop.iterationStatus==="running"&&z.continuationLoop.canRecover){if(await re?.assertOwned(),k?.meta.id!==T||b!==F)return;await H.recoverTurn(z),yn=void 0,v.showTransientActivityNotice("Recovered a goal turn after its original local executor exited; persisted work will be inspected before continuing.");return}if(NSr(z,et.listContinuations(Pd())))return;let ae=ue=>LSr(z,T,ue);if(Ug.list({parentSessionId:T}).some(ue=>(!Dit(ue)||!ue.notificationEnqueuedAt)&&ae(ue.activeInboxMessageId?ue.activeParentOrigin:ue.initialParentOrigin))||ZE.listPending(T).some(ue=>eIe(ue)&&ae(ue.parentOrigin))||Ut.listRuns().filter(ue=>ue.parentSessionId===T).some(ue=>(!["completed","failed","cancelled"].includes(ue.status)||Ut.readNotifications(ue.workflowRunId).some(eIe))&&ae(ue.parentOrigin)))return;let V=z.maxTokens===void 0?void 0:await pm.remainingTokens(z);if(!dnt(z)||!Z0e(z,Date.now(),V))return;let J=z.lastVerifierResult??{satisfied:!1,confidence:"low",reason:"The requested goal loop has not yet verified completion.",evidence:[]},oe=vj(z,{...J,...z.continuationLoop.iterationStatus==="interrupted"?{requiredNextAction:"Inspect the latest transcript and persisted operation results before retrying interrupted work."}:{}},(z.admittedTurns??z.accountedTurns??0)+1);await CSr({expected:z,readActive:()=>H.getActive(Wh(T)),readRemainingTokens:ue=>pm.remainingTokens(ue),isCurrent:()=>!Se&&k?.meta.id===T&&b===F,canSubmit:()=>!Se&&!un&&!v.busy&&!v.hasQueuedMessage,submit:()=>{Hv(oe,{goal:z,requestId:`goal-turn-${Lj()}`})}}),yn=void 0}catch(z){let ae=z instanceof Error?z.message:String(z);ae!==yn&&v.showTransientActivityNotice(`Goal continuation unavailable: ${ae}`),yn=ae}finally{ni=!1}}let acn=T=>{let F=og(T.sessionId,{cliVersion:Pe,store:Ug});F.status==="held"&&v.showTransientActivityNotice(`Input queued; worker wake held: ${F.reason}`)},h_e=async T=>{if(zvt(T))return;let F=bt.get(T);if(F){let V=bt.getOutput(T)?.output??"(no output yet)";await v.infoPanel({title:`Background Shell: ${T}`,lines:[`Command: ${F.command}`,`Status: ${F.status}${F.exitCode!==null?` (exit ${F.exitCode})`:""}`,`Duration: ${bt.formatDuration((F.endedAt??Date.now())-F.startedAt)}`,"","Output:",V]}),lr();return}let H=Ug.get(T);if(!H){v.writeInfo(G.red(`Agent session not found: ${T}`)),lr();return}v.setActiveAgentSessionFooterId(T);let z=()=>{let V=Ug.get(T);return V?HCr(V):""},ae=V=>`${V.status}${V.model?` \xB7 ${V.model}`:""}`,xe=()=>{let V=Ug.get(T);v.updateAgentSessionChatView(z(),V?ae(V):void 0,V?QCr(V):void 0),lr()},Ae=setInterval(xe,1e3);Ae.unref?.(),v.openAgentSessionChatView({sessionId:T,title:H.name,subtitle:ae(H),placeholder:"Message this agent session...",historyText:HCr(H),...QCr(H),onSubmit:V=>{let J=Ug.get(T);if(!J)throw new Error(`Agent session not found: ${T}`);if(J.status==="failed"||J.status==="stopped")throw new Error(`Agent session is ${J.status}.`);Ug.appendUserInput(T,V),acn(J),lr(),xe()},onClose:()=>{clearInterval(Ae),v.setActiveAgentSessionFooterId(null),lr()},reopen:()=>h_e(T)}),xe()},Gvt=T=>{let F=()=>$3i(T.agent.messages),H=()=>T.finished()?"finished \xB7 read-only":"running \xB7 messages reach it at its next step",z=setInterval(()=>v.updateAgentSessionChatView(F(),H()),1e3);z.unref?.(),T.footerId&&v.setActiveAgentSessionFooterId(T.footerId),v.openAgentSessionChatView({sessionId:T.viewId,title:T.title,subtitle:H(),placeholder:T.finished()?`The ${T.name} has finished; its conversation is read-only.`:`Message the ${T.name}...`,historyText:F(),onSubmit:async ae=>{if(T.finished())throw new Error(`The ${T.name} has finished; its conversation is read-only.`);await T.agent.injectContext({content:ae,label:"message from the user"}),v.updateAgentSessionChatView(F(),H())},onClose:()=>{clearInterval(z),T.footerId&&(v.setActiveAgentSessionFooterId(null),lr())},reopen:T.reopen})},Vvt=T=>{let F=Rg.get(T);return F?(Gvt({viewId:`delegation:${T}`,title:`${T} (delegation)`,name:T,agent:F.agent,finished:()=>F.finished,reopen:()=>{Vvt(T)}}),!0):!1},zvt=T=>{let F=$p.get(T);return F?(Gvt({viewId:T,title:`${F.name} (dispatched)`,name:F.name,agent:F.agent,finished:()=>F.endedAt!==void 0,reopen:()=>{zvt(T)},footerId:T}),!0):!1},Xvt=async T=>{let F=v.currentAgentSessionChatViewId()??k?.meta.id??Xr,H=EKe(Ug.list({cwd:r}),F);if(!v.currentAgentSessionChatViewId())for(let[ae,xe]of $p)xe.parentAgentId==="agent-main"&&H.push({sessionId:ae,shortId:ae,name:xe.name});let z=SKe(T,H);if(z.kind!=="found"){v.showTransientActivityNotice(z.message),v.currentAgentSessionChatViewId()||v.writeInfo(z.message);return}await h_e(z.sessionId)},lcn=async T=>{let F=$p.get(T);if(F){F.endedAt===void 0?(F.childId!==void 0&&Kf.cancel(F.childId,"stopped from the agent dock")||F.agent.cancelCurrentTurn(),v.showTransientActivityNotice(`Stopping ${F.name}`)):($p.delete(T),v.showTransientActivityNotice(`Cleared ${F.name}`)),lr();return}let H=bt.get(T);if(H){if(H.status==="running"){let xe=bt.stop(T);v.showTransientActivityNotice(xe?`Stopped ${T}`:`Failed to stop ${T}`)}else bt.cleanup?.(T),v.showTransientActivityNotice(`Cleared ${T}`);lr();return}let z=Ug.get(T);if(z&&Dit(z)){let xe=Ug.markCleared(T);v.showTransientActivityNotice(xe?`Cleared ${xe.name}`:`Failed to clear ${T}`),lr();return}let ae=ou(T);ae.stopped?v.showTransientActivityNotice(`Stopped ${ae.record?.name??T}`):v.showTransientActivityNotice(ae.error??`Failed to stop ${T}`),lr()},ccn=async T=>{if(!Ut.getRun(T)){v.writeInfo(G.red(`Workflow run not found: ${T}`)),lr();return}await v.infoPanel(AJ(process.cwd(),T)),lr()},dcn=async T=>{let F=Ut.getRun(T);if(F&&Vit(F.status)){let z=S3i(T,Ut);v.showTransientActivityNotice(z>0?`Cleared ${F.workflowName}`:`No pending workflow update: ${F.workflowName}`),lr();return}let H=JS(Ut,T);v.showTransientActivityNotice(oU(H,T)),lr()};async function Hv(T,F){if(Se||un||F?.goal&&F.goal.runId!==Wh(k?.meta.id))return"not-started";un=!0,b++,v.busy=!0;let H=new Yn,z=null,ae,xe=!1,Ae="interrupted",V=!1,J="not-started",oe=F?.requestId??`goal-turn-${Lj()}`,ue=!1,pt=OSr(T,F!==void 0),ct;try{if(h&&(m=new AbortController,v.showTransientActivityNotice("Waiting for a peer turn slot; Ctrl+] switches sessions."),await h.acquire(oe,m.signal),ue=!0,m.signal.throwIfAborted(),m=void 0),!await t8())return"not-started";ct=k?.meta.id;let Gt=await re?.assertOwned();KE=ct,ha=zl.getCwd();let ft=jt.enabled,fe=(F?.goal??await H.getActive(Wh(ct)))?.maxTokens!==void 0;!ft&&!fe&&await fm();let St=q?.routesTurnsThroughHost===!0;if(ft&&e.permissionMode==="plan"&&Qw(process.env[pf])==="required")throw new Error(xge);let ot=F&&!F.goal?null:F?.goal??await H.getActive(Wh(ct));if(e.permissionMode==="plan"&&ot?.status==="active")throw new Error(Aze);if(pe.pending&&!pe.awaitingDecision&&await pe.discardPending("a new message was sent before it was decided"),ot?.maxTokens!==void 0){if(St)throw new Error("The host-attached execution lane does not share the goal token budget yet. Run this goal in the CLI directly.");if(ft)throw new Error("Top-level delegated turns do not yet share the goal token quota; disable delegation before resuming this bounded goal.");ae=await pm.prepare(ot,{cwd:zl.getCwd(),model:e.model,maxOutputTokens:e.maxTokens,agent:Ie}),XE.has(ot.goalId)||(XE.add(ot.goalId),v.writeInfo(`Goal budget: ${G0e(ot.maxTokens,ae.enforcement)}.`))}if(z=F&&!F.goal?null:await H.admitTurn(Wh(ct),T,oe,F?.goal,St?"external":"local-sdk",Gt,ae),z&&jvt.continuationOriginVersion!==1)throw new Error("SDK goal continuation origin support is required before executing this goal.");if(z&&!z.admitted)return v.showTransientActivityNotice("This goal turn is already recorded; no duplicate execution was started."),z=null,"not-started";z&&ae&&(Ie.configureModelExecution({provider:ae.provider}),xe=!0),F&&z&&v.writeOutput(PSr(z.goal,z.admittedTurns,z.goal.maxTurns),{forceNewBlock:!0,selectable:!0,blockKind:"system"}),ct&&(Yc={schemaVersion:1,parentSessionId:ct,parentMessageId:oe,goalTurn:z?{sessionId:z.goal.runId,goalId:z.goal.goalId,requestId:oe}:null});let Tt=JIe(T),pn=Tt.input,wa=e.effort,Iu=e.orchestrationMode,ku;Tt.requested&&(e.effort="max",e.orchestrationMode="ultracode",Ie.effort="max",L.current?.setEffort("max"),v.setEffort("max"),ku=()=>{e.effort=wa,e.orchestrationMode=Iu,Ie.effort=wa,L.current?.setEffort(wa),v.setEffort(wa)});try{if(!L.current)throw new Error("Hook runtime is not initialized");pt.runUserPromptHooks&&(pn=await lF(L.current,pn,{command:"chat",mode:"tui"}))}catch(Ui){let Zc=Ui instanceof Error?Ui.message:String(Ui);return v.writeOutput(yo(Zc)),"not-started"}await a_e(pn);let qn=Tt.requested?KIe(pn):YIe(pn)?ZIe(pn):pn,Va;try{Va=k?.meta.id?await A9e({cwd:r,sessionId:k.meta.id}):void 0}catch(Ui){v.showTransientActivityNotice(`Artifact feedback unavailable: ${Ui instanceof Error?Ui.message:String(Ui)}`)}let ur=Va?`${qn}
10422
+ `,{selectable:!0,blockKind:"assistant"})}finally{rcn()}},Fvt=async()=>{Rr=await Y0(x,k?.meta.id),Hr=HB(Rr),v&&v.setPromptContextBreakdown(Hr),Ie&&(Ie.systemPrompt=await Pp())},Uvt=async()=>{if(k)return await Pw(k,qe),!0;try{let T=await BR({sessionManager:k,checkpointManager:S,memoryManager:x,identityResolver:E,auditLogger:C,restoredMessages:_,sessionDir:P,sessionHistoryPath:R,turnRestoreManager:$},{cwd:r,...i?{role:i}:{},...o?{memoryScope:o}:{},model:e.model,projectSessionContext:qj(e)});k=T.sessionManager,S=T.checkpointManager,x=T.memoryManager,E=T.identityResolver,C=T.auditLogger,_=T.restoredMessages,P=T.sessionDir,R=T.sessionHistoryPath,$=T.turnRestoreManager??null,Wa=S?new CR(S):void 0;let F=T.sessionManager;if(!F)throw new Error("Session activation succeeded without a session manager");return await he(F),await Pw(F,qe),await pe.persist(),Ie.attachSessionIntegration({transcript:F.transcript,checkpoints:S,sessionManager:F,historyMarkdownPath:R,auditLogger:C}),v.setSessionName(F.meta.name),hr.syncPresence(),await Fvt(),!0}catch(T){let F=T instanceof Error?T.message:String(T);return v.writeInfo(G.red(`? Error creating session: ${F}`)),!1}},c_e,t8=()=>k?Uvt():(c_e??=Uvt().finally(()=>{c_e=void 0}),c_e),Ug=new tt,ZE=new ms,d_e=!1,u_e=!1,p_e=!1,r8,jvt=et;lr=()=>{if(!v)return;let T=k?.meta.id??Xr,F=Ut.listRuns().filter(J=>E3i(J,Ut)).map(C3i),H=Ug.list({cwd:r}).filter(J=>J.parentSessionId===T).filter(jCr),z=new Set(H.map(J=>J.sessionId));for(let[J,oe]of mm)(z.has(J)||Date.now()-oe.addedAt>1e4||!jCr(oe.record))&&mm.delete(J);let ae=[...Array.from(mm.values()).map(J=>J.record),...H.filter(J=>!mm.has(J.sessionId))],xe=bt.list().filter(J=>J.origin!=="user_direct_shell"&&(J.ownerSessionId===T||!J.ownerSessionId)).filter(J=>J.status==="running"||J.endedAt&&Date.now()-J.endedAt<3e4).map(J=>{let oe=J.status==="running",ue=J.endedAt?J.endedAt-J.startedAt:Date.now()-J.startedAt;return{id:J.id,name:J.id,title:J.command?J.command.replace(/\r?\n/g," ").slice(0,40):void 0,status:J.status,terminal:!oe,elapsedMs:ue}}),Ae=Array.from($p.entries()).filter(([,J])=>J.endedAt===void 0||Date.now()-J.endedAt<6e4).map(([J,oe])=>{let ue=kHt(oe,oe.childId!==void 0?Mg.get(oe.childId):void 0);return{id:J,name:oe.name,title:"dispatched",status:ue.status,terminal:ue.terminal,elapsedMs:(oe.endedAt??Date.now())-oe.startedAt,tokenCount:oe.agent.tokenUsage.total}}),V=[...F,...ae.map(I3i),...Ae,...xe];v.setAgentSessionFooterItems(V),v.setPendingAgentSessionNotifications(yF()?ZE.listPending(T).map(AX):[])};let n8,qvt=new Map;async function Qvt(T){if(Se||!v.canAcceptExternalInput||v.hasQueuedMessage||un||!k)return;let F=k.meta.id;try{let H=JSON.stringify([T.kind,F]),z=qvt.get(H)??{};qvt.set(H,z);let ae=await DSr({kind:T.kind,parentSessionId:F,items:T.read(F),limit:T.limit,render:T.render,store:new Yn,scan:z});if(!ae||Se||k?.meta.id!==F||un||!v.canAcceptExternalInput||v.hasQueuedMessage)return;if(ae.kind==="hold"){n8!==ae.reason&&v.showTransientActivityNotice(`Result delivery held: ${ae.reason}`),n8=ae.reason;return}if(ae.kind==="suppress"){for(let Ae of ae.members)T.suppress(Ae,ae.reason);return}if(ae.kind==="ack"){for(let Ae of ae.members)T.acknowledge(Ae);return}if(await re?.assertOwned(),Se||k?.meta.id!==F||un||!v.canAcceptExternalInput||v.hasQueuedMessage)return;for(let Ae of ae.members){let V=T.claim(Ae,ae.batch);if(!V||V.acknowledgedAt||V.orphanedAt||V.automaticSuppressedAt||!V.deliveredAt&&!FL(V.lastDelivery,ae.batch))throw new Error("Notification delivery claim is unconfirmed or changed; inspect pending results before retrying")}let xe=await Hv(ae.input,{requestId:ae.batch.messageId,goal:ae.goal});if(xe==="completed"||xe==="suspended")for(let Ae of ae.members)T.acknowledge(Ae);n8=void 0}catch(H){let z=H instanceof Error?H.message:String(H);n8!==z&&v.showTransientActivityNotice(`Result delivery held: ${AC(z)}`),n8=z}finally{lr()}}let ocn=async()=>{if(!(!yF()||d_e)){d_e=!0;try{await Qvt({kind:"agent",limit:aTr,read:T=>ZE.list({parentSessionId:T}),render:bX,claim:(T,F)=>ZE.markDeliveryAttempt(T.notificationId,F),acknowledge:T=>ZE.markDelivered(T.notificationId),suppress:(T,F)=>ZE.suppressAutomaticDelivery(T.notificationId,F)})}finally{d_e=!1}}},scn=async()=>{if(!(kTr()||u_e)){u_e=!0;try{await Qvt({kind:"workflow",limit:lTr,read:T=>Ut.listRuns().filter(F=>F.parentSessionId===T).flatMap(F=>Ut.readNotifications(F.workflowRunId)),render:ETr,claim:(T,F)=>Ut.markNotificationAttempt(T.workflowRunId,T.notificationId,F),acknowledge:T=>Ut.markNotificationDelivered(T.workflowRunId,T.notificationId),suppress:(T,F)=>Ut.suppressAutomaticNotification(T.workflowRunId,T.notificationId,F)})}finally{u_e=!1}}},Hvt=async()=>{if(process.env.XENO_AUTO_TOOL_CONTINUATION==="0"||Se||!v||!v.canAcceptExternalInput||v.hasQueuedMessage||un||p_e)return;let T=Pd(),F=et.listContinuations(T,"ready")[0];if(!F)return;p_e=!0;let H=k?.meta.id,z=null;try{let ae=await MSr(new Yn,F,Wh(H));if(H!==k?.meta.id||Se||un||!v.canAcceptExternalInput||v.hasQueuedMessage)return;if(ae.kind==="cancel"||ae.kind==="delivered"){ae.kind==="cancel"?et.cancelContinuation(F.continuationId):et.markContinuationCompleted(F.continuationId);return}if(ae.kind!=="run"){r8!==ae.reason&&v.showTransientActivityNotice(`Tool continuation held: ${ae.reason}`),r8=ae.reason;return}if(jt.enabled||q?.routesTurnsThroughHost)throw new Error("Pending local SDK results require their local execution lane; no provider handoff was authorized.");let xe=`tool-continuation-${F.continuationId}-${F.continuationTurns+1}`;z=jvt.markContinuationRunning(F.continuationId,{messageId:xe});let Ae=et.list({ownerSessionId:T}).filter(J=>F.operationIds.includes(J.operationId)||J.turnId===F.sourceTurnId).filter(J=>J.terminal);if(z?.status==="exhausted"){v.writeInfo(mB(z,Ae));return}if(z?.status!=="running")return;let V=await Hv(WW(z,Ae),{requestId:xe,goal:ae.goal,toolContinuation:z});V==="completed"||V==="suspended"?et.markContinuationCompleted(F.continuationId):et.retryContinuation(F.continuationId),r8=void 0}catch(ae){z?.status==="running"&&et.retryContinuation(F.continuationId);let xe=ae instanceof Error?ae.message:String(ae);r8!==xe&&v.showTransientActivityNotice(`Tool continuation held: ${AC(xe)}`),r8=xe}finally{p_e=!1}},f_e=async()=>{await Hvt(),await ocn(),await scn(),await Wvt()};async function Wvt(){if(Se||!Fi||ni||un||v.busy||v.hasQueuedMessage||!k)return;ni=!0;let T=k.meta.id,F=b,H=new Yn;try{let z=await H.getActive(Wh(T));if(k?.meta.id!==T||b!==F||un||v.busy||!z||z.status!=="active"||z.continuationLoop?.status!=="running")return;if(e.permissionMode==="plan"){yn!==Cge&&v.showTransientActivityNotice(Cge),yn=Cge;return}if(z.continuationLoop.iterationStatus==="running"&&z.continuationLoop.canRecover){if(await re?.assertOwned(),k?.meta.id!==T||b!==F)return;await H.recoverTurn(z),yn=void 0,v.showTransientActivityNotice("Recovered a goal turn after its original local executor exited; persisted work will be inspected before continuing.");return}if(NSr(z,et.listContinuations(Pd())))return;let ae=ue=>LSr(z,T,ue);if(Ug.list({parentSessionId:T}).some(ue=>(!Dit(ue)||!ue.notificationEnqueuedAt)&&ae(ue.activeInboxMessageId?ue.activeParentOrigin:ue.initialParentOrigin))||ZE.listPending(T).some(ue=>eIe(ue)&&ae(ue.parentOrigin))||Ut.listRuns().filter(ue=>ue.parentSessionId===T).some(ue=>(!["completed","failed","cancelled"].includes(ue.status)||Ut.readNotifications(ue.workflowRunId).some(eIe))&&ae(ue.parentOrigin)))return;let V=z.maxTokens===void 0?void 0:await pm.remainingTokens(z);if(!dnt(z)||!Z0e(z,Date.now(),V))return;let J=z.lastVerifierResult??{satisfied:!1,confidence:"low",reason:"The requested goal loop has not yet verified completion.",evidence:[]},oe=vj(z,{...J,...z.continuationLoop.iterationStatus==="interrupted"?{requiredNextAction:"Inspect the latest transcript and persisted operation results before retrying interrupted work."}:{}},(z.admittedTurns??z.accountedTurns??0)+1);await CSr({expected:z,readActive:()=>H.getActive(Wh(T)),readRemainingTokens:ue=>pm.remainingTokens(ue),isCurrent:()=>!Se&&k?.meta.id===T&&b===F,canSubmit:()=>!Se&&!un&&!v.busy&&!v.hasQueuedMessage,submit:()=>{Hv(oe,{goal:z,requestId:`goal-turn-${Lj()}`})}}),yn=void 0}catch(z){let ae=z instanceof Error?z.message:String(z);ae!==yn&&v.showTransientActivityNotice(`Goal continuation unavailable: ${ae}`),yn=ae}finally{ni=!1}}let acn=T=>{let F=og(T.sessionId,{cliVersion:Pe,store:Ug});F.status==="held"&&v.showTransientActivityNotice(`Input queued; worker wake held: ${F.reason}`)},h_e=async T=>{if(zvt(T))return;let F=bt.get(T);if(F){let V=bt.getOutput(T)?.output??"(no output yet)";await v.infoPanel({title:`Background Shell: ${T}`,lines:[`Command: ${F.command}`,`Status: ${F.status}${F.exitCode!==null?` (exit ${F.exitCode})`:""}`,`Duration: ${bt.formatDuration((F.endedAt??Date.now())-F.startedAt)}`,"","Output:",V]}),lr();return}let H=Ug.get(T);if(!H){v.writeInfo(G.red(`Agent session not found: ${T}`)),lr();return}v.setActiveAgentSessionFooterId(T);let z=()=>{let V=Ug.get(T);return V?HCr(V):""},ae=V=>`${V.status}${V.model?` \xB7 ${V.model}`:""}`,xe=()=>{let V=Ug.get(T);v.updateAgentSessionChatView(z(),V?ae(V):void 0,V?QCr(V):void 0),lr()},Ae=setInterval(xe,1e3);Ae.unref?.(),v.openAgentSessionChatView({sessionId:T,title:H.name,subtitle:ae(H),placeholder:"Message this agent session...",historyText:HCr(H),...QCr(H),onSubmit:V=>{let J=Ug.get(T);if(!J)throw new Error(`Agent session not found: ${T}`);if(J.status==="failed"||J.status==="stopped")throw new Error(`Agent session is ${J.status}.`);Ug.appendUserInput(T,V),acn(J),lr(),xe()},onClose:()=>{clearInterval(Ae),v.setActiveAgentSessionFooterId(null),lr()},reopen:()=>h_e(T)}),xe()},Gvt=T=>{let F=()=>$3i(T.agent.messages),H=()=>T.finished()?"finished \xB7 read-only":"running \xB7 messages reach it at its next step",z=setInterval(()=>v.updateAgentSessionChatView(F(),H()),1e3);z.unref?.(),T.footerId&&v.setActiveAgentSessionFooterId(T.footerId),v.openAgentSessionChatView({sessionId:T.viewId,title:T.title,subtitle:H(),placeholder:T.finished()?`The ${T.name} has finished; its conversation is read-only.`:`Message the ${T.name}...`,historyText:F(),onSubmit:async ae=>{if(T.finished())throw new Error(`The ${T.name} has finished; its conversation is read-only.`);await T.agent.injectContext({content:ae,label:"message from the user"}),v.updateAgentSessionChatView(F(),H())},onClose:()=>{clearInterval(z),T.footerId&&(v.setActiveAgentSessionFooterId(null),lr())},reopen:T.reopen})},Vvt=T=>{let F=Rg.get(T);return F?(Gvt({viewId:`delegation:${T}`,title:`${T} (delegation)`,name:T,agent:F.agent,finished:()=>F.finished,reopen:()=>{Vvt(T)}}),!0):!1},zvt=T=>{let F=$p.get(T);return F?(Gvt({viewId:T,title:`${F.name} (dispatched)`,name:F.name,agent:F.agent,finished:()=>F.endedAt!==void 0,reopen:()=>{zvt(T)},footerId:T}),!0):!1},Xvt=async T=>{let F=v.currentAgentSessionChatViewId()??k?.meta.id??Xr,H=EKe(Ug.list({cwd:r}),F);if(!v.currentAgentSessionChatViewId())for(let[ae,xe]of $p)xe.parentAgentId==="agent-main"&&H.push({sessionId:ae,shortId:ae,name:xe.name});let z=SKe(T,H);if(z.kind!=="found"){v.showTransientActivityNotice(z.message),v.currentAgentSessionChatViewId()||v.writeInfo(z.message);return}await h_e(z.sessionId)},lcn=async T=>{let F=$p.get(T);if(F){F.endedAt===void 0?(F.childId!==void 0&&Kf.cancel(F.childId,"stopped from the agent dock")||F.agent.cancelCurrentTurn(),v.showTransientActivityNotice(`Stopping ${F.name}`)):($p.delete(T),v.showTransientActivityNotice(`Cleared ${F.name}`)),lr();return}let H=bt.get(T);if(H){if(H.status==="running"){let xe=bt.stop(T);v.showTransientActivityNotice(xe?`Stopped ${T}`:`Failed to stop ${T}`)}else bt.cleanup?.(T),v.showTransientActivityNotice(`Cleared ${T}`);lr();return}let z=Ug.get(T);if(z&&Dit(z)){let xe=Ug.markCleared(T);v.showTransientActivityNotice(xe?`Cleared ${xe.name}`:`Failed to clear ${T}`),lr();return}let ae=ou(T);ae.stopped?v.showTransientActivityNotice(`Stopped ${ae.record?.name??T}`):v.showTransientActivityNotice(ae.error??`Failed to stop ${T}`),lr()},ccn=async T=>{if(!Ut.getRun(T)){v.writeInfo(G.red(`Workflow run not found: ${T}`)),lr();return}await v.infoPanel(AJ(process.cwd(),T)),lr()},dcn=async T=>{let F=Ut.getRun(T);if(F&&Vit(F.status)){let z=S3i(T,Ut);v.showTransientActivityNotice(z>0?`Cleared ${F.workflowName}`:`No pending workflow update: ${F.workflowName}`),lr();return}let H=JS(Ut,T);v.showTransientActivityNotice(oU(H,T)),lr()};async function Hv(T,F){if(Se||un||F?.goal&&F.goal.runId!==Wh(k?.meta.id))return"not-started";un=!0,b++,v.busy=!0;let H=new Yn,z=null,ae,xe=!1,Ae="interrupted",V=!1,J="not-started",oe=F?.requestId??`goal-turn-${Lj()}`,ue=!1,pt=OSr(T,F!==void 0),ct;try{if(h&&(m=new AbortController,v.showTransientActivityNotice("Waiting for a peer turn slot; Ctrl+] switches sessions."),await h.acquire(oe,m.signal),ue=!0,m.signal.throwIfAborted(),m=void 0),!await t8())return"not-started";ct=k?.meta.id;let Vt=await re?.assertOwned();KE=ct,ha=zl.getCwd();let ft=jt.enabled,fe=(F?.goal??await H.getActive(Wh(ct)))?.maxTokens!==void 0;!ft&&!fe&&await fm();let St=q?.routesTurnsThroughHost===!0;if(ft&&e.permissionMode==="plan"&&Qw(process.env[pf])==="required")throw new Error(xge);let ot=F&&!F.goal?null:F?.goal??await H.getActive(Wh(ct));if(e.permissionMode==="plan"&&ot?.status==="active")throw new Error(Aze);if(pe.pending&&!pe.awaitingDecision&&await pe.discardPending("a new message was sent before it was decided"),ot?.maxTokens!==void 0){if(St)throw new Error("The host-attached execution lane does not share the goal token budget yet. Run this goal in the CLI directly.");if(ft)throw new Error("Top-level delegated turns do not yet share the goal token quota; disable delegation before resuming this bounded goal.");ae=await pm.prepare(ot,{cwd:zl.getCwd(),model:e.model,maxOutputTokens:e.maxTokens,agent:Ie}),XE.has(ot.goalId)||(XE.add(ot.goalId),v.writeInfo(`Goal budget: ${G0e(ot.maxTokens,ae.enforcement)}.`))}if(z=F&&!F.goal?null:await H.admitTurn(Wh(ct),T,oe,F?.goal,St?"external":"local-sdk",Vt,ae),z&&jvt.continuationOriginVersion!==1)throw new Error("SDK goal continuation origin support is required before executing this goal.");if(z&&!z.admitted)return v.showTransientActivityNotice("This goal turn is already recorded; no duplicate execution was started."),z=null,"not-started";z&&ae&&(Ie.configureModelExecution({provider:ae.provider}),xe=!0),F&&z&&v.writeOutput(PSr(z.goal,z.admittedTurns,z.goal.maxTurns),{forceNewBlock:!0,selectable:!0,blockKind:"system"}),ct&&(Yc={schemaVersion:1,parentSessionId:ct,parentMessageId:oe,goalTurn:z?{sessionId:z.goal.runId,goalId:z.goal.goalId,requestId:oe}:null});let Tt=JIe(T),pn=Tt.input,wa=e.effort,Iu=e.orchestrationMode,ku;Tt.requested&&(e.effort="max",e.orchestrationMode="ultracode",Ie.effort="max",L.current?.setEffort("max"),v.setEffort("max"),ku=()=>{e.effort=wa,e.orchestrationMode=Iu,Ie.effort=wa,L.current?.setEffort(wa),v.setEffort(wa)});try{if(!L.current)throw new Error("Hook runtime is not initialized");pt.runUserPromptHooks&&(pn=await lF(L.current,pn,{command:"chat",mode:"tui"}))}catch(Ui){let Zc=Ui instanceof Error?Ui.message:String(Ui);return v.writeOutput(yo(Zc)),"not-started"}await a_e(pn);let qn=Tt.requested?KIe(pn):YIe(pn)?ZIe(pn):pn,Va;try{Va=k?.meta.id?await A9e({cwd:r,sessionId:k.meta.id}):void 0}catch(Ui){v.showTransientActivityNotice(`Artifact feedback unavailable: ${Ui instanceof Error?Ui.message:String(Ui)}`)}let ur=Va?`${qn}
10423
10423
 
10424
10424
  ${Va.text}`:qn,Cn=null,Od=!1,Ky=Date.now(),nh=rh().total;v.busy=!0,v.trimTrailingOutputNewlines(1);let ZM=uTr(v.getRenderCols());ZM&&v.writeOutput(ZM,{forceNewBlock:!0,selectable:!0,blockKind:"system"}),$g(),a=pt.approvalPrompt;let m_e=Ie.messages.length,Yy="success",xte=await QIe(Lv,pn,Ui=>v.showTransientActivityNotice(`Agent Soul recall skipped: ${Ui}`));try{if(z)try{await H.confirmTurn(z)}catch(ih){throw V=!0,ih}await re?.assertOwned(),Li=!1,ri(),de.reset();let Ui=Ie.tokenUsage;if(J="failed",ft)v.startSpinner("Delegating..."),await icn(ur);else if(St&&q){v.startSpinner("Thinking...");let ih=new AbortController;Ga=ih;let e1=[...po.splice(0),ur].join(`
10425
10425
 
10426
10426
  `),Eu;try{Eu=await q.runTurn({prompt:e1,...e.effort?{reasoningOptionId:e.effort}:{},history:hKe(Ie.messages),signal:ih.signal,onText:Zy=>Ete.onText(Zy),onToolAnnounced:Zy=>v.startSpinner(zR(Zy)),onToolStart:(Zy,g_e)=>Ete.onToolStart(Zy,g_e??{}),onToolEnd:(Zy,g_e,w_e)=>Ete.onToolEnd(Zy,{success:g_e,output:w_e?.output??"",...w_e?.error?{error:w_e.error}:{}}),onRuntimeEvent:Kc})}finally{Ga=null}if(!Eu.ok&&Eu.reason==="cancelled")throw Ie.messages.push({role:"user",content:e1},{role:"assistant",content:Eu.partialText??""}),new ji;if(!Eu.ok)throw new Error(`${Eu.reason}: ${Eu.detail}`);Eu.tokenUsage&&(_d.input+=Eu.tokenUsage.input,_d.output+=Eu.tokenUsage.output,_d.total+=Eu.tokenUsage.total),Ie.messages.push({role:"user",content:e1},{role:"assistant",content:Eu.text}),k&&await k.updateMessageCount(Ie.messages.length),de.flush()}else{v.startSpinner("Thinking...");let ih=pTr(Ie,i8,pn);try{let e1={messageId:oe,...F?.toolContinuation?{continuationId:F.toolContinuation.continuationId}:{},...z?{goalTurn:{sessionId:z.goal.runId,goalId:z.goal.goalId,requestId:oe}}:{}};Ci=null,await Ie.run(ur,e1)}finally{ih()}if(k){let e1=Ie.tokenUsage,Eu=Math.max(0,e1.input-Ui.input),Zy=Math.max(0,e1.output-Ui.output);await k.updateMessageCount(Ie.messages.length),(Eu>0||Zy>0)&&await k.recordTokenUsage(Eu,Zy)}de.flush()}let Zc=!ft&&!St?Ie.lastRunTermination:null;if(J=Zc?.status==="suspended"?"suspended":Zc?.status==="incomplete"?"failed":"completed",Zc?.status==="incomplete"&&(v.writeInfo(`Incomplete turn: ${Zc.message}`),Yy="partial"),Va&&await Va.acknowledge().catch(ih=>{v.showTransientActivityNotice(`Artifact feedback acknowledgement deferred: ${ih instanceof Error?ih.message:String(ih)}`)}),Wa)try{await Wa.checkInterval(Ie.messages)&&v.showTransientActivityNotice("Auto-checkpoint created")}catch(ih){console.error("[AutoCheckpoint] Failed to create interval checkpoint:",ih)}v.stopSpinner();let Zvt=rh(),gcn=FR(rG(Ie.modelUsage,Zvt));v.updateTokens(Zvt.total,gcn)}catch(Ui){if(v.stopSpinner(),Ui instanceof ji||Li||V)Od=!0,Yy="partial",de.flush(),V&&v.showTransientActivityNotice("Goal or loop changed; the admitted turn was interrupted before model execution."),!V&&!v.hasQueuedMessage&&v.showTransientActivityNotice("Interrupted \xB7 When idle, clear input and press Esc twice to rewind");else{Yy="failure";let Zc=Ui instanceof Error?Ui.message:String(Ui);Cn=rCr(Zc,Pg),Cn?v.writeOutput(`
10427
10427
  ${G.accent("\u26A0")} ${Cn.notice}
10428
10428
  ${G.dim(Cn.retryHint)}
10429
- `,{forceNewBlock:!0,selectable:!0,blockKind:"system"}):v.writeOutput(yo(AC(wQe(Ui))))}}finally{await Ge(),await HIe({soul:Lv,prepared:xte,task:pn,messages:Ie.messages,startIndex:m_e,outcome:Yy,onError:Ui=>v.showTransientActivityNotice(`Agent Soul learning skipped: ${Ui}`)}),bu(),a="",Zq(),ku?.()}Ae=Od?"interrupted":Yy==="success"?"completed":"failed";let gm=Date.now()-Ky;JM+=gm;let Yvt=Math.max(0,rh().total-nh);for(let Ui=Ie.messages.length-1;Ui>=0;Ui--)if(Ie.messages[Ui].role==="assistant"){let Zc=Ie.messages[Ui];Zc.metadata={...Zc.metadata,elapsedMs:gm,tokenUsage:{total:Yvt}};break}let mcn=await dTr({elapsedMs:gm,showDuration:v.getTurnDurationVisible(),tokenCount:Yvt,columns:v.getRenderCols(),interrupted:Od,ownerSessionId:Pd(),taskListManager:hm,sessionManager:k});v.trimTrailingOutputNewlines(1),v.writeOutput(WIe(mcn,v.getRenderCols()),{forceNewBlock:!0,selectable:!0,blockKind:"system"}),Ci&&(U3i(v,Ci),Ci=null),z&&J==="completed"&&!Od&&Yy==="success"&&k?.meta.id===ct&&(jn=(await cTr({agent:Ie,admission:z,...C?{auditLogger:C}:{},tracker:jn,writeOutput:Zc=>v.writeOutput(Zc,{forceNewBlock:!0,selectable:!0,blockKind:"system"}),showNotice:Zc=>v.showTransientActivityNotice(Zc),readRemainingTokens:Zc=>pm.remainingTokens(Zc)})).tracker),z||(Cn?v.setPromptSuggestion(Cn.suggestion):Aqi(Ie.messages).then(Ui=>v.setPromptSuggestion(Ui)).catch(()=>{}))}catch(Gt){v.writeOutput(yo(Gt instanceof Error?Gt.message:String(Gt)))}finally{if(m=void 0,xe&&Ie.configureModelExecution({}),z)try{await H.finishTurn(z,Ae)}catch(ft){J="failed",v.showTransientActivityNotice(`Goal settlement is unconfirmed: ${ft instanceof Error?ft.message:String(ft)}`)}if(KE=void 0,Yc=void 0,ha=void 0,ue)try{await h.release(oe)}catch(ft){J="failed",v.writeError(`Peer turn settlement failed: ${ft instanceof Error?ft.message:String(ft)}`)}un=!1,v.busy=!1;let Gt=Se?null:v.takeQueuedMessage();Gt?(v.echoUserPrompt(Gt,!0),k?.meta.id!==ct?v.showTransientActivityNotice("Queued prompt was not sent because the session changed; it remains visible above for explicit resubmission."):$ge(Gt)!==null?setTimeout(()=>{v.submitInput(Gt)},0):setTimeout(()=>{Hv(Gt)},0)):Se||f_e()}return J}lr(),we=setInterval(()=>{lr(),f_e()},1e3),we.unref?.(),hr.start(),await wu.start().catch(T=>{v.showTransientActivityNotice(`Artifact tray unavailable: ${T instanceof Error?T.message:String(T)}`,8e3)}),Te=setInterval(()=>{(async()=>{let T=(F,H)=>{v.showTransientActivityNotice(`Scheduled prompt ${H.id} is due`),v.enqueueMessage(F)};await Vy.dispatchDue({isIdle:()=>v.canAcceptExternalInput,dispatch:T}),await qT.dispatchDue({isIdle:()=>v.canAcceptExternalInput,dispatch:T})})().catch(T=>{e2r(T,F=>v.showTransientActivityNotice(F))})},1e3),Te.unref?.(),B=async T=>{Uv.restore(),j();let F=await KTr({cwd:T,enabled:e.safeMode?!1:e.mcpEnabled,toolRegistry:xi,askUser:Gl,getProfile:()=>ks(e,T),onServerStateChanged:H=>{v.showTransientActivityNotice(H)},promptForApproval:Vze(async H=>(v.stopSpinner(),await v.actionPicker({title:"Approve MCP server",description:`${H.name} (${H.scope}) from ${H.sourcePath}`,options:[{value:"approve",label:"Approve",detail:"(save approval for this workspace)"},{value:"deny",label:"Deny",detail:"(skip this server)"}],selectedIndex:0})==="approve"?"approved":"denied"),{cwd:T,clientVersion:Pe,onUnrecorded:(H,z)=>v.showTransientActivityNotice(`The Agent host did not record your decision for ${H}: ${z}`)})});return O=F.mcpManager,N=F.refreshMcpTools,D=F.reconcile,j=F.dispose,Uv.apply(HT()),F.summary};let Jvt=await B(r);ya("mcp-rebind"),Jvt&&v.writeInfo(Jvt);let Kvt=e.agentName?Jge(e.agentName,()=>r):oc(e.agentToolPolicy),ucn=Kd({profile:()=>ks(e,r),currentUserPrompt:()=>a}),i8=new bit(e.webResearchBudget),pcn=new bR({cwd:r}),fcn=T=>{let F=q8e(Q8e(T,Mg.get(T.dispatchId)));v?.writeCollapsibleInfo(F.summaryText,F.expandedText,{updateKey:`dispatch-${T.dispatchId}`}),H8e(T)&&v&&!Se&&!un&&v.canAcceptExternalInput&&!v.hasQueuedMessage&&!q?.routesTurnsThroughHost&&Hv(W8e,{requestId:`dispatch-${T.dispatchId}`})};process.env.XENO_TEST_HOOKS==="1"&&process.env.XENO_TEST_AGENT_DELAY_MS&&await new Promise(T=>setTimeout(T,Number(process.env.XENO_TEST_AGENT_DELAY_MS)));let hcn=Zxr(),Ete={onText:T=>{let F=T;if(ut){let H=Pj(Jr,T);if(Jr=H.pending,H.renderable===null)return;F=H.renderable}ut&&Lg(),ut&&(v.startSpinner("Streaming model response..."),ut=!1,Jr="",es=!0,de.markLineStarted()),de.write(F)},onToolStart:(T,F)=>{Jr="";let H=KL(T),z=RG(T)&&!Ga;(!H||rs===0)&&v.stopSpinner(),de.flush(),v.trimTrailingOutputNewlines(1),H||Lg(),Wa&&!Ga&&Wa.checkBeforeDangerous(T,F,Ie.messages).catch(J=>console.error("[AutoCheckpoint] Failed to create pre-dangerous checkpoint:",J));let ae=H$(T,F),xe=H?ma.activeGroupKey??void 0:void 0;if(xe||(Pg+=1),at.set(T,F),xe){rs+=1,ma.markVisible(xe,Date.now());let J=ma.activeActivity;J&&An(J,!0),rs===1&&v.startSpinner(zR(T));return}if(eTr(T)){v.startSpinner(zR(T));return}if(z){v.startSpinner(iHt(T,F,hm.list()));return}let Ae=T==="Write"?kc(F):null,V=Ae!==null&&Qit(Ae);$Tr(v,T,ae,F,V?"Update":void 0),v.startSpinner(zR(T))},onToolEnd:(T,F)=>{let H=RG(T)&&!Ga,z=KL(T)&&rs>0;z?(rs-=1,rs===0&&v.stopSpinner()):v.stopSpinner(),Ga||Gy(Ie.tokenUsage.total);let ae=rh(),xe=FR(rG(Ie.modelUsage,ae));v.updateTokens(ae.total,xe);let Ae=zIe(F.success,F.output,F.error);if(z){ri();return}if(eTr(T)&&F.success){ri();return}if(H){v.setTaskProgressItems(hm.list()),F.success||(v.trimTrailingOutputNewlines(1),Uit(v,T,!1,Ae,at.get(T),!0,it)),ri();return}v.trimTrailingOutputNewlines(1);let V=at.get(T);Uit(v,T,F.success,Ae,V,!0,it,Np(T,V)),ri(),T==="Bash"&&Promise.resolve().then(()=>(st(),cd)).then(({backgroundProcessManager:J})=>{let oe=J.list().filter(ue=>ue.status==="running").length;v.setBackgroundTaskCount(oe)}).catch(()=>{})}};Ie=(await Mh({cwd:r,sandbox:e.securityPolicy,apiKey:e.apiKey,baseURL:e.baseURL,model:e.model,...e.fallbackModels?{fallbackModels:e.fallbackModels}:{},...e.effort?{effort:e.effort}:{},maxTokens:e.maxTokens,maxIterations:e.maxIterations,reserveFinalSynthesisTurn:!0,systemPrompt:Nv,role:i,memory:o==="none"?!1:{scope:o,sessionDir:P,includeProjectSessionContext:!1},promptSections:[...th,i8.promptSection],requesterLabel:"Agent",ownerSessionId:Xr,getOwnerSessionId:Pd,executionMode:qe,permissionEngine:Vl,toolRegistry:xi,externalActions:LG(ks(e,r),T=>v.actionPicker({title:T.title,description:T.description,options:[...T.options],selectedIndex:0})),toolMiddleware:[Kt,i8.toolMiddleware,...Ic?[Ic.middleware]:[],pa,ucn,...Kvt?[Kvt]:[]],completionGuards:[i8.completionGuard,...Ve?[Ve.inboxGuard]:[]],session:{transcript:k?.transcript,checkpoints:S,sessionManager:k,historyMarkdownPath:R,auditLogger:C},turnDiffTracker:pcn,onTurnDiff:async T=>{let F=await xye({cwd:r,summary:T,producer:{kind:"agent",id:e.agentName??"agent-main"},...k?.meta.id?{sessionId:k.meta.id}:{},runId:Xr});F&&v.showTransientActivityNotice(`Review artifact ready: ${F.artifact.artifactId}`)},onRuntimeEvent:T=>{qG(T)&&(Ci=QG(T)),T.type==="provider.attempt"&&un&&v.setModelRequestTiming(T);let F=hcn(T);if(F&&un&&v.startSpinner(F),T.type==="dispatch.settled"&&fcn(T),T.type==="turn.started"&&typeof T.contextBudgetTokens=="number"&&T.contextBudgetTokens>0&&(HK={tokens:Ie.modelContextWindow,source:T.contextBudgetSource??"fallback"},v.setContextBudgetTokens(Ie.modelContextWindow)),T.type==="context.pressure"&&typeof T.contextTokens=="number"&&v.setContextTokens(T.contextTokens),T.type==="turn.completed"&&typeof T.contextTokens=="number"&&v.setContextTokens(T.contextTokens),T.type==="provider.event"&&T.event.type==="usage.updated"&&Gy(Op+T.event.inputTokens+T.event.outputTokens),"operation"in T&&T.type.startsWith("tool.operation.")){let H=T.operation,z=Ne.apply(H,v.activeToolOperationId);z==="set"?v.setActiveToolOperation({operationId:H.operationId,toolName:H.toolName,state:H.state,presentation:H.presentation,completionPolicy:H.completionPolicy,promotable:H.promotable,startedAt:H.startedAt,deadlineAt:H.deadlineAt,idleMs:H.idleMs,outputBytes:H.outputBytes,suggestedNextAction:H.suggestedNextAction}):z==="clear"&&v.setActiveToolOperation(null)}(T.type==="turn.suspended"||T.type==="turn.completed")&&v.setActiveToolOperation(null),T.type==="turn.suspended"&&v.showTransientActivityNotice(T.message),T.type==="turn.continuation_enqueued"&&setTimeout(()=>{Hvt()},75).unref?.()},onModeSwitchRequest:async T=>{v.stopSpinner();let F=T.requestedTools.length>0?T.requestedTools.join(", "):"tool access";return await v.modelPicker({title:"Switch to agent mode?",description:`Requested: ${F}`,currentValue:"switch",options:[{value:"switch",label:"Switch to agent",detail:"(allow tools for this and future turns)"},{value:"stay",label:"Stay in Chat",detail:"(continue without running tools)"}]})==="switch"?(await Fr("agent"),!0):!1},onExecutionModeChanged:T=>{qe=T,e.executionMode=T,v.setExecutionMode(T)},...Ete,onToolWillExecute:async(T,F)=>{await re?.assertOwned();let H=tCr({expectedSessionId:KE,currentSessionId:k?.meta.id,expectedCwd:ha,currentCwd:zl.getCwd()});if(H.action==="adopt-cwd")ha=H.cwd;else if(H.action==="scope-changed")throw new Error("The main conversation scope changed during this turn; no tool action was started in the new scope.");await KM(T,F),Dg(T,F)},onIteration:(T,F)=>{if(Op=F,Au!==null&&F>Au&&Gy(F),zi(),T>1){ri();let H=jpe(hm.list());v.startSpinner(H?`${H} (iteration ${T})...`:`Thinking (iteration ${T})...`)}}})).agent,await lg(k,Ie.model),await au(Ie,Ie.model),v.setContextBudgetTokens(Ie.modelContextWindow),ya("agent-awaited"),Ie.attachBackgroundDispatch(Mg),ua=()=>Ie.modelUsage,ie.register(Xr),Ee=new Lz({screen:v,cwd:()=>zl.getCwd(),ownerSessionId:()=>Xr,appendMessage:T=>Ie.messages.push(T),persistResult:async T=>k?k.recordDirectShellResult(T):eS(T),invalidateObservedFiles:T=>D0(zl,T),onLifecycle:T=>TTr(C,Xr,T),renderCommand:T=>`
10429
+ `,{forceNewBlock:!0,selectable:!0,blockKind:"system"}):v.writeOutput(yo(AC(wQe(Ui))))}}finally{await Ge(),await HIe({soul:Lv,prepared:xte,task:pn,messages:Ie.messages,startIndex:m_e,outcome:Yy,onError:Ui=>v.showTransientActivityNotice(`Agent Soul learning skipped: ${Ui}`)}),bu(),a="",Zq(),ku?.()}Ae=Od?"interrupted":Yy==="success"?"completed":"failed";let gm=Date.now()-Ky;JM+=gm;let Yvt=Math.max(0,rh().total-nh);for(let Ui=Ie.messages.length-1;Ui>=0;Ui--)if(Ie.messages[Ui].role==="assistant"){let Zc=Ie.messages[Ui];Zc.metadata={...Zc.metadata,elapsedMs:gm,tokenUsage:{total:Yvt}};break}let mcn=await dTr({elapsedMs:gm,showDuration:v.getTurnDurationVisible(),tokenCount:Yvt,columns:v.getRenderCols(),interrupted:Od,ownerSessionId:Pd(),taskListManager:hm,sessionManager:k});v.trimTrailingOutputNewlines(1),v.writeOutput(WIe(mcn,v.getRenderCols()),{forceNewBlock:!0,selectable:!0,blockKind:"system"}),Ci&&(U3i(v,Ci),Ci=null),z&&J==="completed"&&!Od&&Yy==="success"&&k?.meta.id===ct&&(jn=(await cTr({agent:Ie,admission:z,...C?{auditLogger:C}:{},tracker:jn,writeOutput:Zc=>v.writeOutput(Zc,{forceNewBlock:!0,selectable:!0,blockKind:"system"}),showNotice:Zc=>v.showTransientActivityNotice(Zc),readRemainingTokens:Zc=>pm.remainingTokens(Zc)})).tracker),z||(Cn?v.setPromptSuggestion(Cn.suggestion):Aqi(Ie.messages).then(Ui=>v.setPromptSuggestion(Ui)).catch(()=>{}))}catch(Vt){v.writeOutput(yo(Vt instanceof Error?Vt.message:String(Vt)))}finally{if(m=void 0,xe&&Ie.configureModelExecution({}),z)try{await H.finishTurn(z,Ae)}catch(ft){J="failed",v.showTransientActivityNotice(`Goal settlement is unconfirmed: ${ft instanceof Error?ft.message:String(ft)}`)}if(KE=void 0,Yc=void 0,ha=void 0,ue)try{await h.release(oe)}catch(ft){J="failed",v.writeError(`Peer turn settlement failed: ${ft instanceof Error?ft.message:String(ft)}`)}un=!1,v.busy=!1;let Vt=Se?null:v.takeQueuedMessage();Vt?(v.echoUserPrompt(Vt,!0),k?.meta.id!==ct?v.showTransientActivityNotice("Queued prompt was not sent because the session changed; it remains visible above for explicit resubmission."):$ge(Vt)!==null?setTimeout(()=>{v.submitInput(Vt)},0):setTimeout(()=>{Hv(Vt)},0)):Se||f_e()}return J}lr(),we=setInterval(()=>{lr(),f_e()},1e3),we.unref?.(),hr.start(),await wu.start().catch(T=>{v.showTransientActivityNotice(`Artifact tray unavailable: ${T instanceof Error?T.message:String(T)}`,8e3)}),Te=setInterval(()=>{(async()=>{let T=(F,H)=>{v.showTransientActivityNotice(`Scheduled prompt ${H.id} is due`),v.enqueueMessage(F)};await Vy.dispatchDue({isIdle:()=>v.canAcceptExternalInput,dispatch:T}),await qT.dispatchDue({isIdle:()=>v.canAcceptExternalInput,dispatch:T})})().catch(T=>{e2r(T,F=>v.showTransientActivityNotice(F))})},1e3),Te.unref?.(),B=async T=>{Uv.restore(),j();let F=await KTr({cwd:T,enabled:e.safeMode?!1:e.mcpEnabled,toolRegistry:xi,askUser:Gl,getProfile:()=>ks(e,T),onServerStateChanged:H=>{v.showTransientActivityNotice(H)},promptForApproval:Vze(async H=>(v.stopSpinner(),await v.actionPicker({title:"Approve MCP server",description:`${H.name} (${H.scope}) from ${H.sourcePath}`,options:[{value:"approve",label:"Approve",detail:"(save approval for this workspace)"},{value:"deny",label:"Deny",detail:"(skip this server)"}],selectedIndex:0})==="approve"?"approved":"denied"),{cwd:T,clientVersion:Pe,onUnrecorded:(H,z)=>v.showTransientActivityNotice(`The Agent host did not record your decision for ${H}: ${z}`)})});return O=F.mcpManager,N=F.refreshMcpTools,D=F.reconcile,j=F.dispose,Uv.apply(HT()),F.summary};let Jvt=await B(r);ya("mcp-rebind"),Jvt&&v.writeInfo(Jvt);let Kvt=e.agentName?Jge(e.agentName,()=>r):oc(e.agentToolPolicy),ucn=Kd({profile:()=>ks(e,r),currentUserPrompt:()=>a}),i8=new bit(e.webResearchBudget),pcn=new bR({cwd:r}),fcn=T=>{let F=q8e(Q8e(T,Mg.get(T.dispatchId)));v?.writeCollapsibleInfo(F.summaryText,F.expandedText,{updateKey:`dispatch-${T.dispatchId}`}),H8e(T)&&v&&!Se&&!un&&v.canAcceptExternalInput&&!v.hasQueuedMessage&&!q?.routesTurnsThroughHost&&Hv(W8e,{requestId:`dispatch-${T.dispatchId}`})};process.env.XENO_TEST_HOOKS==="1"&&process.env.XENO_TEST_AGENT_DELAY_MS&&await new Promise(T=>setTimeout(T,Number(process.env.XENO_TEST_AGENT_DELAY_MS)));let hcn=Zxr(),Ete={onText:T=>{let F=T;if(ut){let H=Pj(Jr,T);if(Jr=H.pending,H.renderable===null)return;F=H.renderable}ut&&Lg(),ut&&(v.startSpinner("Streaming model response..."),ut=!1,Jr="",es=!0,de.markLineStarted()),de.write(F)},onToolStart:(T,F)=>{Jr="";let H=KL(T),z=RG(T)&&!Ga;(!H||rs===0)&&v.stopSpinner(),de.flush(),v.trimTrailingOutputNewlines(1),H||Lg(),Wa&&!Ga&&Wa.checkBeforeDangerous(T,F,Ie.messages).catch(J=>console.error("[AutoCheckpoint] Failed to create pre-dangerous checkpoint:",J));let ae=H$(T,F),xe=H?ma.activeGroupKey??void 0:void 0;if(xe||(Pg+=1),at.set(T,F),xe){rs+=1,ma.markVisible(xe,Date.now());let J=ma.activeActivity;J&&An(J,!0),rs===1&&v.startSpinner(zR(T));return}if(eTr(T)){v.startSpinner(zR(T));return}if(z){v.startSpinner(iHt(T,F,hm.list()));return}let Ae=T==="Write"?kc(F):null,V=Ae!==null&&Qit(Ae);$Tr(v,T,ae,F,V?"Update":void 0),v.startSpinner(zR(T))},onToolEnd:(T,F)=>{let H=RG(T)&&!Ga,z=KL(T)&&rs>0;z?(rs-=1,rs===0&&v.stopSpinner()):v.stopSpinner(),Ga||Gy(Ie.tokenUsage.total);let ae=rh(),xe=FR(rG(Ie.modelUsage,ae));v.updateTokens(ae.total,xe);let Ae=zIe(F.success,F.output,F.error);if(z){ri();return}if(eTr(T)&&F.success){ri();return}if(H){v.setTaskProgressItems(hm.list()),F.success||(v.trimTrailingOutputNewlines(1),Uit(v,T,!1,Ae,at.get(T),!0,it)),ri();return}v.trimTrailingOutputNewlines(1);let V=at.get(T);Uit(v,T,F.success,Ae,V,!0,it,Np(T,V)),ri(),T==="Bash"&&Promise.resolve().then(()=>(st(),cd)).then(({backgroundProcessManager:J})=>{let oe=J.list().filter(ue=>ue.status==="running").length;v.setBackgroundTaskCount(oe)}).catch(()=>{})}};Ie=(await Mh({cwd:r,sandbox:e.securityPolicy,apiKey:e.apiKey,baseURL:e.baseURL,model:e.model,...e.fallbackModels?{fallbackModels:e.fallbackModels}:{},...e.effort?{effort:e.effort}:{},maxTokens:e.maxTokens,maxIterations:e.maxIterations,reserveFinalSynthesisTurn:!0,systemPrompt:Nv,role:i,memory:o==="none"?!1:{scope:o,sessionDir:P,includeProjectSessionContext:!1},promptSections:[...th,i8.promptSection],requesterLabel:"Agent",ownerSessionId:Xr,getOwnerSessionId:Pd,executionMode:qe,permissionEngine:Vl,toolRegistry:xi,externalActions:LG(ks(e,r),T=>v.actionPicker({title:T.title,description:T.description,options:[...T.options],selectedIndex:0})),toolMiddleware:[Kt,i8.toolMiddleware,...Ic?[Ic.middleware]:[],pa,ucn,...Kvt?[Kvt]:[]],completionGuards:[i8.completionGuard,...Ve?[Ve.inboxGuard]:[]],session:{transcript:k?.transcript,checkpoints:S,sessionManager:k,historyMarkdownPath:R,auditLogger:C},turnDiffTracker:pcn,onTurnDiff:async T=>{let F=await xye({cwd:r,summary:T,producer:{kind:"agent",id:e.agentName??"agent-main"},...k?.meta.id?{sessionId:k.meta.id}:{},runId:Xr});F&&v.showTransientActivityNotice(`Review artifact ready: ${F.artifact.artifactId}`)},onRuntimeEvent:T=>{qG(T)&&(Ci=QG(T)),T.type==="provider.attempt"&&un&&v.setModelRequestTiming(T);let F=hcn(T);if(F&&un&&v.startSpinner(F),T.type==="dispatch.settled"&&fcn(T),T.type==="turn.started"&&typeof T.contextBudgetTokens=="number"&&T.contextBudgetTokens>0&&(HK={tokens:Ie.modelContextWindow,source:T.contextBudgetSource??"fallback"},v.setContextBudgetTokens(Ie.modelContextWindow)),T.type==="context.pressure"&&typeof T.contextTokens=="number"&&v.setContextTokens(T.contextTokens),T.type==="turn.completed"&&typeof T.contextTokens=="number"&&v.setContextTokens(T.contextTokens),T.type==="provider.event"&&T.event.type==="usage.updated"&&Gy(Op+T.event.inputTokens+T.event.outputTokens),"operation"in T&&T.type.startsWith("tool.operation.")){let H=T.operation,z=Ne.apply(H,v.activeToolOperationId);z==="set"?v.setActiveToolOperation({operationId:H.operationId,toolName:H.toolName,state:H.state,presentation:H.presentation,completionPolicy:H.completionPolicy,promotable:H.promotable,startedAt:H.startedAt,deadlineAt:H.deadlineAt,idleMs:H.idleMs,outputBytes:H.outputBytes,suggestedNextAction:H.suggestedNextAction}):z==="clear"&&v.setActiveToolOperation(null)}(T.type==="turn.suspended"||T.type==="turn.completed")&&v.setActiveToolOperation(null),T.type==="turn.suspended"&&v.showTransientActivityNotice(T.message),T.type==="turn.continuation_enqueued"&&setTimeout(()=>{Hvt()},75).unref?.()},onModeSwitchRequest:async T=>{v.stopSpinner();let F=T.requestedTools.length>0?T.requestedTools.join(", "):"tool access";return await v.modelPicker({title:"Switch to agent mode?",description:`Requested: ${F}`,currentValue:"switch",options:[{value:"switch",label:"Switch to agent",detail:"(allow tools for this and future turns)"},{value:"stay",label:"Stay in Chat",detail:"(continue without running tools)"}]})==="switch"?(await Fr("agent"),!0):!1},onExecutionModeChanged:T=>{qe=T,e.executionMode=T,v.setExecutionMode(T)},...Ete,onToolWillExecute:async(T,F)=>{await re?.assertOwned();let H=tCr({expectedSessionId:KE,currentSessionId:k?.meta.id,expectedCwd:ha,currentCwd:zl.getCwd()});if(H.action==="adopt-cwd")ha=H.cwd;else if(H.action==="scope-changed")throw new Error("The main conversation scope changed during this turn; no tool action was started in the new scope.");await KM(T,F),Dg(T,F)},onIteration:(T,F)=>{if(Op=F,Au!==null&&F>Au&&Gy(F),zi(),T>1){ri();let H=jpe(hm.list());v.startSpinner(H?`${H} (iteration ${T})...`:`Thinking (iteration ${T})...`)}}})).agent,await lg(k,Ie.model),await au(Ie,Ie.model),v.setContextBudgetTokens(Ie.modelContextWindow),ya("agent-awaited"),Ie.attachBackgroundDispatch(Mg),ua=()=>Ie.modelUsage,ie.register(Xr),Ee=new Lz({screen:v,cwd:()=>zl.getCwd(),ownerSessionId:()=>Xr,appendMessage:T=>Ie.messages.push(T),persistResult:async T=>k?k.recordDirectShellResult(T):eS(T),invalidateObservedFiles:T=>D0(zl,T),onLifecycle:T=>TTr(C,Xr,T),renderCommand:T=>`
10430
10430
  ${Cw("Shell",T)}
10431
10431
  `}),zn=new Oge({screen:v,ownerSessionId:()=>Xr,safeMode:e.safeMode}),Rt=new zL({screen:v,safeMode:e.safeMode});{let T=Ie;T.config&&(T.config.onContextCompressed=(F,H,z)=>{let ae=z?.accounting?.beforeTokens,xe=z?.accounting?.afterTokens;typeof xe=="number"&&v.setContextTokens(xe,z?.accounting?.source==="estimated"),v.showTransientActivityNotice(vHt({messagesRemoved:F,tokensSaved:H,beforeTokens:ae,afterTokens:xe,accountingSource:z?.accounting?.source}))})}{let{backgroundProcessManager:T}=await Promise.resolve().then(()=>(st(),cd));T.onTaskComplete(F=>{if(F.origin==="user_direct_shell")return;let H=F.status==="completed"?"completed":`failed (exit ${F.exitCode})`;v.showTransientActivityNotice(`Background task ${F.displayName?`${F.displayName} (${F.id})`:F.id} ${H}`);let z=T.list().filter(ae=>ae.status==="running").length;v.setBackgroundTaskCount(z),lr?.(),setTimeout(()=>{f_e()},75)}),T.onTaskEvent(()=>{lr?.()})}if(_&&_.length>0){let T=await t_(_,k??void 0);_=T.messages,Ie.messages=_,k&&await k.updateMessageCount(_.length),Pit(v,_,it);let F=G8e(T);F&&v.writeOutput(`${G.dim(F)}
10432
10432
  `)}Fi=!0,Wvt();let Ste=pe.restoreFromSession(k?.meta);if(e.permissionMode==="plan"&&!Ste.invalid&&v.writeInfo(Ste.restored?Sge:Ege),Ste.pending&&pe.presentPendingApproval(),v.setPermissionMode(e.permissionMode),v.setStartupLoading(!1),!Ste.pending&&_&&_.length>0&&IHt(_,{ask:T=>Gl(T),notice:T=>v.showTransientActivityNotice(T),submit:T=>{let F=v;F.setInputText(T,{cursor:"end",escCancelable:!1}),F.handleEnter()}}),f&&!await n1("auth-sign-in-check",()=>f)){let T=v.suspendForTerminalAttach();if(!await Nit(e).catch(()=>!1)){try{await ti()}catch{}v.cleanup(),process.exit(process.exitCode??1)}T&&v.resumeFromTerminalAttach()}if(g=!0,h){if(!await t8()||!k)throw new Error("Peer session activation failed.");await h.ready(k.meta.id,k.meta.name),v.writeInfo("Ctrl+] switches independent peer sessions. /new-subchat creates another.")}ya("agent-ready"),w(),Se||(yt=setInterval(()=>{},3600*1e3)),await ze,await Ms}catch(Ut){await jK(Ut,ti)}}async function tTr(e){let t=k8e(),r=process.cwd(),n=e.agentName?.trim()?Wi(e.agentName,r).compiled:e.agentProfile??Wi("assistant",r).compiled,i=e.role??n?.memory.role,o=n?.memory.scope,s=n?Ka(n.capabilities.permissionProfile)??void 0:void 0,a="",l=vit(e.accessibilityMode);if(!await wqi(e))return;let c=new IG,d=new HI(De=>process.stdout.write(De)," "),u=uqi();l==="plain"?process.stderr.write(OCr({version:Pe,model:Uj(e),cwd:r})):(process.stderr.write("\x1B[2J\x1B[3J\x1B[H"),process.stderr.write(XR(Pe,Uj(e),CTr(),e.executionMode==="chatOnly"?"chat":"agent"))),e.executionSecurity&&e.executionSecurityStatus&&(process.stderr.write(`${GL(e.executionSecurity,e.executionSecurityStatus)}
@@ -17243,7 +17243,7 @@ _xeno() {
17243
17243
  compdef _xeno xeno
17244
17244
  `}function $ln(e){let t=Svt(e),r=["# xeno fish completions","# Run once:","# xeno completions fish | source","","# Disable file completions","complete -c xeno -f","","# Subcommands"];for(let n of t.subcommands)r.push(`complete -c xeno -n '__fish_use_subcommand' -a '${n.name}' -d '${n.description.replace(/'/g,"\\'")}'`);r.push("","# Workflows subcommands");for(let n of t.workflowSubcommands)r.push(`complete -c xeno -n '__fish_seen_subcommand_from workflows' -a '${n.name}' -d '${n.description.replace(/'/g,"\\'")}'`);r.push("","# Completions subcommand shells");for(let n of["bash","zsh","fish"])r.push(`complete -c xeno -n '__fish_seen_subcommand_from completions' -a '${n}' -d '${n} completions'`);r.push("","# Flags");for(let n of t.flags){let i=n.replace(/^--/,"");r.push(`complete -c xeno -l '${i}'`)}r.push("","# Model names for --model");for(let n of xvt)r.push(`complete -c xeno -n '__fish_seen_subcommand_from chat run review' -l model -xa '${n}'`);return r.push("","# Mode values"),r.push("complete -c xeno -l mode -xa 'agent chat'"),r.push("","# Effort values"),r.push(`complete -c xeno -l effort -xa '${Cvt.join(" ")}'`),r.push("","# Permission mode values"),r.push("complete -c xeno -l permission-mode -xa 'default plan auto acceptEdits bypassPermissions'"),r.push("","# Agent status values"),r.push("complete -c xeno -l status -xa 'queued starting running waiting_for_tool waiting_for_user waiting_for_hook waiting_for_permission paused blocked completed failed cancelled interrupted detached'"),r.push("","# Scope values"),r.push("complete -c xeno -l scope -xa 'project user'"),r.push("","# Usage grouping values"),r.push("complete -c xeno -l by -xa 'agent model effort status workflow subagent tool mcp hook'"),r.push("","# Color values"),r.push("complete -c xeno -l color -xa 'blue green red yellow magenta cyan white'"),r.push("","# Focus values"),r.push("complete -c xeno -l focus -xa 'security performance'"),r.push(""),r.join(`
17245
17245
  `)}Ao();rx();$w();Yp();EIe();tit();var Ite=8192,s_e=50,Y4o=3,Z4o=1e3;async function Bln(e,t=Z4o){e.destroyed||!e.writable||await new Promise(r=>{let n=!1,i=null,o=()=>{n||(n=!0,i&&(clearTimeout(i),i=null),r())};i=setTimeout(o,t);try{e.write("",o)}catch{o()}})}function t_e(e,t,r=0){let n=process.env[e],i=n?Number.parseInt(n,10):Number.NaN;return Number.isFinite(i)?Math.max(r,i):t}function e3o(e,t){if(e===void 0)return;let r=Number.parseInt(String(e),10);return(!Number.isInteger(r)||r<1)&&(console.error(`Invalid ${t}: ${e}. Expected integer >= 1.`),process.exit(1)),r}function Tvt(e,t=[]){let r=e.trim();return r.length===0||t.includes(r)?t:[...t,r]}function Rvt(e){let t=Array.isArray(e)?e:typeof e=="string"?[e]:[],r=new Set,n=[];for(let i of t){if(typeof i!="string")continue;let o=i.trim();!o||r.has(o)||(r.add(o),n.push(o))}return n.length>0?n:void 0}function t3o(e){let t=Rvt(e.playbook),r=Rvt(e.knowledge),n=Rvt(e.secret);if(!(!t&&!r&&!n))return{...t?{playbooks:t}:{},...r?{knowledge:r}:{},...n?{secrets:n}:{}}}function _vt(e){let t=Array.isArray(e)?e:typeof e=="string"?e.split(","):[],r=new Set,n=[];for(let i of t){if(typeof i!="string")continue;let o=i.trim();!o||r.has(o)||(r.add(o),n.push(o))}return n}function Fln(e,t){let r=_vt(e);if(r.length>0)return r;let n=_vt(process.env.XENO_FALLBACK_MODELS);if(n.length>0)return n;let i=_vt(t);return i.length>0?i:void 0}var Bvt=t1;function r_e(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return Bvt.includes(t)?t:void 0}function Uln(e,t){return r_e(e)??(Ub(e)?"max":void 0)??r_e(process.env.XENO_EFFORT)??(Ub(process.env.XENO_EFFORT)?"max":void 0)??r_e(t)??(Ub(t)?"max":void 0)??"medium"}function jln(e,t){if(Ub(e)||e===void 0&&Ub(process.env.XENO_EFFORT)||e===void 0&&process.env.XENO_EFFORT===void 0&&Ub(t))return"ultracode"}function Ovt(e){return r_e(e)!==void 0||Ub(e)}function Pvt(e){return new Promise(t=>setTimeout(t,e))}function r3o(e){let t=e.match(/retry-after-ms=(\d+)/i);if(!t)return;let r=Number.parseInt(t[1]??"",10);if(!(!Number.isFinite(r)||r<=0))return r}function n3o(){let t=t_e("XENO_RUN_RESTART_BASE_DELAY_MS",1e3,100),r=t_e("XENO_RUN_RESTART_MAX_DELAY_MS",3e4,t);return{maxAttempts:t_e("XENO_RUN_RESTART_MAX_ATTEMPTS",1,0),baseDelayMs:t,maxDelayMs:Math.max(t,r)}}function i3o(e){return e==="ok"?"completed":e==="interrupted"?"interrupted":"failed"}function o3o(e,t,r){let n=r3o(t);return n&&n>0?Math.min(n,r.maxDelayMs):Math.min(r.baseDelayMs*Math.pow(2,e),r.maxDelayMs)}function qln(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();if(t==="staged"||t==="stage")return"staged";if(t==="parallel")return"parallel"}function Qln(e){if(typeof e=="string")return EB(e)}function Hln(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();if(t==="auto"||t==="default")return;let r=Number.parseInt(t,10);return Number.isInteger(r)?r:void 0}function Wln(e){if(typeof e!="string")return;let t=SB(e);return t===null?void 0:t}function Gln(e){if(typeof e=="string")return IR(e)??void 0}function s3o(e){let t=String(e??"deterministic").trim().toLowerCase();if(t==="deterministic"||t==="llm"||t==="auto")return t;throw new Error(`Invalid goal verifier: ${e}. Expected deterministic, llm, or auto.`)}function kte(e){return!!(e.safeMode||Oe.opts().safeMode)}function Mvt(e){return{name:e.name,scope:e.scope,path:e.path,...e.description?{description:e.description}:{},...e.model?{model:e.model}:{},...e.color?{color:e.color}:{},...e.memory?{memory:e.memory}:{},...e.isolation?{isolation:e.isolation}:{},...e.skills.length>0?{skills:e.skills}:{},...e.hooks.length>0?{hooks:e.hooks}:{}}}function n_e(e,t){let r=e?.model?.trim();return!r||r.toLowerCase()==="auto"?t:r}function i_e(e,t){let r=typeof e=="string"?e.trim():"";if(!r){let i=Wi("assistant",t).compiled;return{profile:i,promptSections:[i.promptSection]}}let n;try{n=Wi(r,t)}catch(i){console.error(i instanceof Error?i.message:String(i)),process.exit(1)}return{name:n.definition.name,definition:n.definition,profile:n.compiled,runRef:Mvt(n.definition),promptSections:[n.compiled.promptSection]}}function Dln(e,t){let r=new Set,n=i=>{let o=i?.trim().replace(/^[({[]+/,"").replace(/[)}\].,;:!?]+$/,"");if(!o||o.length>260||o.includes(`
17246
- `)||!/[\\/]/.test(o)&&!/\.[A-Za-z0-9]{1,12}$/.test(o))return;let s=Nln(o)?Tg(o):Tg(t,o),a=J4o(t,s);!a||a.startsWith("..")||Nln(a)||Lln(s)&&r.add(a.replace(/\\/g,"/"))};for(let i of e.matchAll(/`([^`\n]+)`/g))n(i[1]);for(let i of e.matchAll(/["']([^"'\n]+)["']/g))n(i[1]);for(let i of e.matchAll(/(?:^|\s)([^\s"'`]+[\\/][^\s"'`]+|[A-Za-z0-9_.-]+\.[A-Za-z0-9]{1,12})(?=\s|$)/g))n(i[1]);return[...r].sort()}var zt=Pt(),Kq=zt;{let e=process.env.XENO_SEARCH_API_KEY||zt.searchApiKey,t=zt.searchProvider??"duckduckgo",r=Ka(zt.permissionProfile??"default")??void 0;XW({provider:e?t:"duckduckgo",apiKey:e,searxngUrl:zt.searxngUrl,googleCx:zt.googleCx,...r?{permissionProfile:r}:{}})}function zM(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}async function a3o(){return aI(await Sw())}async function l3o(e={}){let t=await Sw({validate:e.validate!==!1}),r=["Xeno auth doctor",""];return r.push(aI(t).trimEnd()),r.push(""),r.push(`Auth base URL: ${e.authBaseURL??t.authBaseURL??li}`),r.push(`Model API base URL: ${e.apiBaseURL??t.apiBaseURL??ai}`),t.expired?r.push("Action: session is expired; run `xeno login` again."):t.signedIn?!t.hasApiKey&&!t.hasAccountToken?r.push("Action: no model request authority is configured; run `xeno login`."):t.valid===!1?r.push("Action: model API credential validation failed; run `xeno login --api-key <key>`."):r.push("Action: auth state looks usable."):r.push("Action: run `xeno login`."),`${r.join(`
17246
+ `)||!/[\\/]/.test(o)&&!/\.[A-Za-z0-9]{1,12}$/.test(o))return;let s=Nln(o)?Tg(o):Tg(t,o),a=J4o(t,s);!a||a.startsWith("..")||Nln(a)||Lln(s)&&r.add(a.replace(/\\/g,"/"))};for(let i of e.matchAll(/`([^`\n]+)`/g))n(i[1]);for(let i of e.matchAll(/["']([^"'\n]+)["']/g))n(i[1]);for(let i of e.matchAll(/(?:^|\s)([^\s"'`]+[\\/][^\s"'`]+|[A-Za-z0-9_.-]+\.[A-Za-z0-9]{1,12})(?=\s|$)/g))n(i[1]);return[...r].sort()}var Gt=Pt(),Kq=Gt;{let e=process.env.XENO_SEARCH_API_KEY||Gt.searchApiKey,t=Gt.searchProvider??"duckduckgo",r=Ka(Gt.permissionProfile??"default")??void 0;XW({provider:e?t:"duckduckgo",apiKey:e,searxngUrl:Gt.searxngUrl,googleCx:Gt.googleCx,...r?{permissionProfile:r}:{}})}function zM(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}async function a3o(){return aI(await Sw())}async function l3o(e={}){let t=await Sw({validate:e.validate!==!1}),r=["Xeno auth doctor",""];return r.push(aI(t).trimEnd()),r.push(""),r.push(`Auth base URL: ${e.authBaseURL??t.authBaseURL??li}`),r.push(`Model API base URL: ${e.apiBaseURL??t.apiBaseURL??ai}`),t.expired?r.push("Action: session is expired; run `xeno login` again."):t.signedIn?!t.hasApiKey&&!t.hasAccountToken?r.push("Action: no model request authority is configured; run `xeno login`."):t.valid===!1?r.push("Action: model API credential validation failed; run `xeno login --api-key <key>`."):r.push("Action: auth state looks usable."):r.push("Action: run `xeno login`."),`${r.join(`
17247
17247
  `)}
17248
17248
  `}Oe.name("xeno").description("XENO AGENT - AI-powered terminal agent by Xeno Corporation").version(Pe).option("--safe-mode","Disable user/project customizations for troubleshooting").addHelpText("after",["","Default chat/background options:"," --resume [id] Resume the latest session or an exact session ID"," --interface Open XENO Agent Interface and resume this workspace's session"," --bg [prompt] Start an interactive background agent session and print its session ID"," --exec <command> With --bg, start a background shell session for this command",""].join(`
17249
17249
  `));Oe.command("login").description("Sign in to Xeno through system-browser PKCE or device authorization").option("--device","Use device authorization for a remote or headless terminal").option("--auth-base-url <url>","Authentication API base URL",li).option("--api-base-url <url>","Model API base URL").option("--status","Show current auth status instead of signing in").option("--no-validate","Skip live validation after storing credentials").option("--json","Emit machine-readable JSON output").action(async e=>{let t=zM(e.authBaseUrl)??li,r=zM(e.apiBaseUrl);if(e.status){let i=await Sw({validate:e.validate!==!1});process.stdout.write(e.json?JSON.stringify(i,null,2)+`
@@ -17295,7 +17295,7 @@ ${r}
17295
17295
  `),process.exitCode=1)});Oe.command("app-server").description("Start the Xeno JSON-RPC app server over stdio").option("--cwd <path>","Working directory for thread.run requests").option("--model <model>","Default model for thread.run requests").option("--base-url <url>","Override Xeno API base URL").option("--max-tokens <count>","Default max output tokens").option("--max-iterations <count>","Default max agent iterations").option("--http","Expose the app server over token-protected local HTTP instead of stdio").option("--host <host>","HTTP bind host when --http is set","127.0.0.1").option("--port <port>","HTTP bind port when --http is set; 0 chooses a free port","0").option("--token-env <name>","Environment variable containing the HTTP bearer token",bnt()).option("--allow-origin <origin>","Optional CORS origin for browser clients").option("--allow-remote","Allow an authenticated non-loopback HTTP bind").option("--state-dir <path>","Durable App Server v2 state directory").option("--open","Open the built-in browser client after the HTTP bridge starts").option("--openapi <path>","Write the app-server OpenAPI schema to a file and exit").option("--json","Emit machine-readable startup metadata in HTTP mode").option("--execution-authority","With --http: be the one place that decides which enrolled host owns each session (see xeno executors)").option("--execution-lease-ms <ms>","With --execution-authority: how long a host that stops renewing keeps a session (3000-600000; default 30000)").action(async e=>{if(typeof e.openapi=="string"&&e.openapi.trim().length>0){let c=Tg(e.openapi.trim());G4o(X4o(c),{recursive:!0});let d=Ant();z4o(c,`${JSON.stringify(d,null,2)}
17296
17296
  `,"utf8");let u={code:"app_server_openapi_written",path:c,methods:d["x-xeno-rpc-methods"]};e.json?process.stdout.write(`${JSON.stringify(u,null,2)}
17297
17297
  `):process.stdout.write(`Wrote app-server OpenAPI schema: ${c}
17298
- `);return}let t=typeof e.cwd=="string"?Tg(e.cwd):process.cwd(),r=typeof e.model=="string"&&e.model.trim().length>0?e.model.trim():zt.model??Gr,n=bw({explicitBaseURL:typeof e.baseUrl=="string"?e.baseUrl:void 0,configuredBaseURL:zt.baseURL}),i=Number.parseInt(String(e.maxTokens??zt.maxTokens??Ite),10),o=Number.parseInt(String(e.maxIterations??zt.maxIterations??s_e),10);if(e.executionLeaseMs!==void 0&&e.executionAuthority!==!0){process.stderr.write(`--execution-lease-ms needs --execution-authority.
17298
+ `);return}let t=typeof e.cwd=="string"?Tg(e.cwd):process.cwd(),r=typeof e.model=="string"&&e.model.trim().length>0?e.model.trim():Gt.model??Gr,n=bw({explicitBaseURL:typeof e.baseUrl=="string"?e.baseUrl:void 0,configuredBaseURL:Gt.baseURL}),i=Number.parseInt(String(e.maxTokens??Gt.maxTokens??Ite),10),o=Number.parseInt(String(e.maxIterations??Gt.maxIterations??s_e),10);if(e.executionLeaseMs!==void 0&&e.executionAuthority!==!0){process.stderr.write(`--execution-lease-ms needs --execution-authority.
17299
17299
  `),process.exitCode=1;return}let s;try{s=Clr(e.executionLeaseMs)}catch(c){process.stderr.write(`${c instanceof Error?c.message:String(c)}
17300
17300
  `),process.exitCode=1;return}await QI();let a={id:"local-app-server",tenantId:"local",workspaceRoots:[t],capabilities:["thread.delete.permanent","integrations.read"]},l=new mue({refuseSlashCommands:{isKnownCommand:Wpe},defaultAgentOptions:{cwd:t,model:r,baseURL:n,apiKey:yS(void 0,process.env.XENO_API_KEY),maxTokens:Number.isFinite(i)?i:Ite,maxIterations:Number.isFinite(o)?o:s_e},v2:{...typeof e.stateDir=="string"&&e.stateDir.trim()?{stateDir:Tg(e.stateDir.trim())}:{},...e.executionAuthority===!0?{executionHandoff:Olr({leaseMs:s})}:{},defaultPrincipal:a,integrations:()=>UUr(t)}});if(e.http===!0){let c=Number.parseInt(String(e.port??"0"),10),d=await VSr(l,{host:typeof e.host=="string"?e.host:void 0,port:Number.isFinite(c)?c:0,tokenEnv:typeof e.tokenEnv=="string"?e.tokenEnv:void 0,allowOrigin:typeof e.allowOrigin=="string"?e.allowOrigin:void 0,allowRemote:e.allowRemote===!0,principal:a,...e.executionAuthority===!0?{executionAuthority:{workspaceRoot:t,leaseMs:s}}:{}}),u=oIe(d.url),p=u.map(m=>`${m}/`),f={code:"app_server_http_ready",url:d.url,urls:u,app:p[0],appUrls:p,rpc:`${u[0]}/rpc`,health:`${u[0]}/health`,manifest:`${u[0]}/manifest`,handoff:{app:p[0],manifest:`${u[0]}/manifest`,remoteAttachCommandTemplate:"xeno remote attach <run-id> --follow",remoteAttachVia:"exec.start"},tokenSource:d.tokenSource,tokenEnv:typeof e.tokenEnv=="string"?e.tokenEnv:bnt(),...d.tokenSource==="generated"?{token:d.token}:{},...e.open===!0?{opened:!0}:{}},h;if(e.allowRemote!==!0)try{h=WUr({url:d.url,token:d.token,rpc:f.rpc,manifest:f.manifest});let m=()=>h?.dispose();process.once("exit",m),process.once("SIGINT",m),process.once("SIGTERM",m)}catch{}if(e.open===!0&&N$(f.app??`${d.url}/`),e.json)process.stdout.write(`${JSON.stringify(f,null,2)}
17301
17301
  `);else{process.stdout.write(`XENO app server HTTP bridge ready: ${f.rpc}
@@ -17321,7 +17321,7 @@ ${r}
17321
17321
  `),t.enforceThresholds&&n.status==="fail"&&(process.exitCode=1)});Oe.command("doctor").description("Inspect local runtime, config, trust, and MCP health").option("--json","Emit machine-readable JSON output").option("--no-mcp","Skip MCP connectivity checks").option("--safe-mode","Disable user/project customizations while inspecting").action(async e=>{let t=kte(e),r=await QI(),n=await XF({cwd:process.cwd(),connectMcp:e.mcp&&!t,safeMode:t,ptyCapability:r});if(e.json){process.stdout.write(JSON.stringify(n,null,2)+`
17322
17322
  `);return}process.stdout.write(Zye(n)+`
17323
17323
  `)});Oe.command("host [action]").description("Inspect the per-user XENO Agent host and whether this CLI would attach to it").option("--json","Emit machine-readable JSON output").option("--probe","Actually connect, then detach - status is a read by default").action(async(e,t)=>{if(String(e??"status").trim().toLowerCase()!=="status"){process.stderr.write(`Usage: xeno host [status] [--probe] [--json]
17324
- `),process.exitCode=1;return}let{buildHostStatusReport:n,renderHostStatusReport:i}=await Promise.resolve().then(()=>(Mln(),Oln)),o;try{o=await n({clientVersion:Pe,attachEnv:process.env.XENO_AGENT_ATTACH,chatContext:{baseURL:bw({configuredBaseURL:zt.baseURL}),authBypassSource:process.env.XENO_API_KEY?.trim()?"env-api-key":zt.apiKey?.trim()?"config-api-key":"none"},probe:!!t.probe,...process.env.XENO_AGENT_HOST_ROOT?{hostRootDirectory:process.env.XENO_AGENT_HOST_ROOT}:{}})}catch(s){process.stderr.write(`${s instanceof Error?s.message:String(s)}
17324
+ `),process.exitCode=1;return}let{buildHostStatusReport:n,renderHostStatusReport:i}=await Promise.resolve().then(()=>(Mln(),Oln)),o;try{o=await n({clientVersion:Pe,attachEnv:process.env.XENO_AGENT_ATTACH,chatContext:{baseURL:bw({configuredBaseURL:Gt.baseURL}),authBypassSource:process.env.XENO_API_KEY?.trim()?"env-api-key":Gt.apiKey?.trim()?"config-api-key":"none",mcpEnabled:!!Gt.mcpEnabled},probe:!!t.probe,...process.env.XENO_AGENT_HOST_ROOT?{hostRootDirectory:process.env.XENO_AGENT_HOST_ROOT}:{}})}catch(s){process.stderr.write(`${s instanceof Error?s.message:String(s)}
17325
17325
  `),process.exitCode=1;return}if(t.json){process.stdout.write(JSON.stringify(o,null,2)+`
17326
17326
  `);return}process.stdout.write(i(o)+`
17327
17327
  `)});Oe.command("security [action]").description("Inspect the installed containment adapter and candidate-bound release certification").option("--json","Emit machine-readable JSON output").action((e,t)=>{if(String(e??"status").trim().toLowerCase()!=="status"){process.stderr.write(`Usage: xeno security [status] [--json]
@@ -17371,7 +17371,7 @@ ${r}
17371
17371
  `)});Oe.command("terminal-setup").description("Install Shift+Enter terminal integration for supported terminals").option("--status","Inspect current terminal integration status").option("--vscode","Target VS Code terminal integration explicitly").option("--iterm","Target iTerm2 integration explicitly").action(e=>{let t=e.vscode?"vscode":e.iterm?"iterm2":rU();if(e.status){let r=sAe(t);process.stdout.write(`${r.detail}${r.configPath?` (${r.configPath})`:""}
17372
17372
  `);return}rKe({cwd:process.cwd(),target:t,onOutput:r=>process.stdout.write(r)})});Oe.command("listen").description("Start system dictation / voice typing on supported platforms").action(()=>{let e=cJ();process.stdout.write(e.message+`
17373
17373
  `),e.supported||(process.exitCode=1)});Oe.command("pr-comments [selector]").description("Fetch and render GitHub PR comments via gh").action(e=>{try{oKe({cwd:process.cwd(),selector:e,onOutput:t=>process.stdout.write(t)})}catch(t){process.stderr.write(`Error: ${t instanceof Error?t.message:String(t)}
17374
- `),process.exitCode=1}});Oe.command("ctx-viz").description("Inspect system prompt, tool definitions, and message-context usage").option("--cwd <path>","Workspace path to inspect").option("--date <yyyy-mm-dd>","Override the prompt date").option("--model <model>","Override the inspected model name").option("--mode <mode>","Execution mode: agent or chat").option("--role <name>","Resolve role-specific identity").option("--json","Emit machine-readable JSON output").option("--tools","List the bounded live XENO runtime registry").option("--limit <n>","Maximum inventory items (1-100)").option("--cursor <cursor>","Continue a preceding --tools response").option("--audit","Report unreachable, duplicate and dangling tools, plus each tool's permission and test mapping").option("--no-memory","Exclude persisted memory from the inspected prompt").option("--no-identity","Exclude identity layers from the inspected prompt").action(async e=>{let t=String(e.mode||zt.executionMode||"agent").toLowerCase(),r=t==="chat"||t==="chatonly"?"chatOnly":t==="agent"?"agent":void 0;if(!r){process.stderr.write(`Invalid execution mode: ${e.mode}. Expected agent or chat.
17374
+ `),process.exitCode=1}});Oe.command("ctx-viz").description("Inspect system prompt, tool definitions, and message-context usage").option("--cwd <path>","Workspace path to inspect").option("--date <yyyy-mm-dd>","Override the prompt date").option("--model <model>","Override the inspected model name").option("--mode <mode>","Execution mode: agent or chat").option("--role <name>","Resolve role-specific identity").option("--json","Emit machine-readable JSON output").option("--tools","List the bounded live XENO runtime registry").option("--limit <n>","Maximum inventory items (1-100)").option("--cursor <cursor>","Continue a preceding --tools response").option("--audit","Report unreachable, duplicate and dangling tools, plus each tool's permission and test mapping").option("--no-memory","Exclude persisted memory from the inspected prompt").option("--no-identity","Exclude identity layers from the inspected prompt").action(async e=>{let t=String(e.mode||Gt.executionMode||"agent").toLowerCase(),r=t==="chat"||t==="chatonly"?"chatOnly":t==="agent"?"agent":void 0;if(!r){process.stderr.write(`Invalid execution mode: ${e.mode}. Expected agent or chat.
17375
17375
  `),process.exitCode=1;return}let n=Tg(e.cwd||process.cwd());if(e.audit){let a=o_e(n,"apps","xeno-agent-cli","src");if(!Lln(a)){process.stderr.write(`--audit reads the CLI source; run it from an xeno-agent-cli checkout (no ${a}).
17376
17376
  `),process.exitCode=1;return}let l=SUr(a),c=await RUr(o_e(n,"tests"),[{prefix:"cli",root:a}]),d=l.unreachable.length+l.duplicates.length+l.danglingAliases.length+l.unclaimedRuntime.length;e.json?process.stdout.write(JSON.stringify({schemaVersion:1,reachability:l,mapping:c})+`
17377
17377
  `):process.stdout.write(`${xUr(l)}
@@ -17380,10 +17380,10 @@ ${d===0?"No reachability findings.":`${d} finding(s).`}
17380
17380
  `):process.stdout.write(["XENO runtime registry (not the native-provider catalogue; no permission granted)",`Registered: ${c.data.registeredCount}; request-loaded: ${c.data.requestLoadedCount}`,...c.data.items.map(d=>`${JSON.stringify(d.name)} \xB7 ${d.requestLoaded?"request-loaded":"not request-loaded"}`),c.data.nextCursor?`Next: xeno ctx-viz --tools --cursor ${c.data.nextCursor}`:"End of inventory."].join(`
17381
17381
  `)+`
17382
17382
  `)}catch(a){process.stderr.write(JSON.stringify({schemaVersion:1,ok:!1,provenance:"trusted",error:{code:a instanceof Dh?a.code:"internal",message:a instanceof Error?a.message:String(a),retryable:!1}})+`
17383
- `),process.exitCode=1}return}let i=await MR({cwd:n,model:e.model||zt.model||Gr,date:e.date,role:e.role,executionMode:r,identity:e.identity===!1?!1:void 0,memory:e.memory===!1?!1:void 0}),o=Ym(nl({cwd:n}),n).getDefinitions(),s=G9e({systemPrompt:i.systemPrompt,toolDefinitions:o,messages:[],identityLayers:i.identity?.layers});if(e.json){process.stdout.write(JSON.stringify(s,null,2)+`
17383
+ `),process.exitCode=1}return}let i=await MR({cwd:n,model:e.model||Gt.model||Gr,date:e.date,role:e.role,executionMode:r,identity:e.identity===!1?!1:void 0,memory:e.memory===!1?!1:void 0}),o=Ym(nl({cwd:n}),n).getDefinitions(),s=G9e({systemPrompt:i.systemPrompt,toolDefinitions:o,messages:[],identityLayers:i.identity?.layers});if(e.json){process.stdout.write(JSON.stringify(s,null,2)+`
17384
17384
  `);return}process.stdout.write(V9e(s)+`
17385
- `)});Oe.command("system-prompt").description("Print the fully resolved system prompt for the current workspace").option("--cwd <path>","Workspace path to inspect").option("--date <yyyy-mm-dd>","Override the prompt date").option("--model <model>","Override the inspected model name").option("--mode <mode>","Execution mode: agent or chat").option("--role <name>","Resolve role-specific identity").option("--json","Emit machine-readable JSON output").option("--no-memory","Exclude persisted memory from the inspected prompt").option("--no-identity","Exclude identity layers from the inspected prompt").action(async e=>{let t=String(e.mode||zt.executionMode||"agent").toLowerCase(),r=t==="chat"||t==="chatonly"?"chatOnly":t==="agent"?"agent":void 0;if(!r){process.stderr.write(`Invalid execution mode: ${e.mode}. Expected agent or chat.
17386
- `),process.exitCode=1;return}let n=await MR({cwd:Tg(e.cwd||process.cwd()),model:e.model||zt.model||Gr,date:e.date,role:e.role,executionMode:r,identity:e.identity===!1?!1:void 0,memory:e.memory===!1?!1:void 0});if(e.json){process.stdout.write(JSON.stringify(n,null,2)+`
17385
+ `)});Oe.command("system-prompt").description("Print the fully resolved system prompt for the current workspace").option("--cwd <path>","Workspace path to inspect").option("--date <yyyy-mm-dd>","Override the prompt date").option("--model <model>","Override the inspected model name").option("--mode <mode>","Execution mode: agent or chat").option("--role <name>","Resolve role-specific identity").option("--json","Emit machine-readable JSON output").option("--no-memory","Exclude persisted memory from the inspected prompt").option("--no-identity","Exclude identity layers from the inspected prompt").action(async e=>{let t=String(e.mode||Gt.executionMode||"agent").toLowerCase(),r=t==="chat"||t==="chatonly"?"chatOnly":t==="agent"?"agent":void 0;if(!r){process.stderr.write(`Invalid execution mode: ${e.mode}. Expected agent or chat.
17386
+ `),process.exitCode=1;return}let n=await MR({cwd:Tg(e.cwd||process.cwd()),model:e.model||Gt.model||Gr,date:e.date,role:e.role,executionMode:r,identity:e.identity===!1?!1:void 0,memory:e.memory===!1?!1:void 0});if(e.json){process.stdout.write(JSON.stringify(n,null,2)+`
17387
17387
  `);return}process.stdout.write(n.systemPrompt+`
17388
17388
  `)});Oe.command("bootstrap-plan").description("Show what `xeno init` would scaffold in the current workspace").option("--cwd <path>","Workspace path to inspect").option("--json","Emit machine-readable JSON output").action(e=>{let t=Nye(Tg(e.cwd||process.cwd()));if(e.json){process.stdout.write(JSON.stringify(t,null,2)+`
17389
17389
  `);return}process.stdout.write(Kan(t)+`
@@ -17394,7 +17394,7 @@ ${d===0?"No reachability findings.":`${d} finding(s).`}
17394
17394
  `)});Oe.command("cost").description("Show the last persisted session token, duration, and cost summary for this workspace").option("--json","Emit machine-readable JSON output").action(e=>{let t=process.cwd(),r=uae(t);if(e.json){process.stdout.write(JSON.stringify({cwd:t,summary:r??null},null,2)+`
17395
17395
  `);return}if(!r){process.stdout.write(`No persisted session summary for this workspace.
17396
17396
  `);return}process.stdout.write(Jdr(r)+`
17397
- `)});Oe.command("ws [args...]").description("Use your XENO workspace from the terminal: list, describe and call any capability your credential may use (XENO_WORKSPACE_KEY)").allowExcessArguments(!0).action(async(e=[])=>{process.exitCode=await Idt(e)});Oe.command("agent",{isDefault:!0}).alias("chat").description("Open the XENO Agent or Chat terminal cockpit").option("-m, --model <model>","AI model to use").option("--fallback-models <models>","Comma-separated fallback models for retryable provider failures").option("--effort <level>","Reasoning effort: low, medium, high, xhigh, max, or ultracode").option("-k, --api-key <key>","API key (optional for Xeno API)").option("--base-url <url>","API base URL").option("--max-tokens <n>","Max response tokens").option("--max-iterations <n>","Max agentic loop iterations").option("--max-web-searches <n>","Web searches allowed per turn, 1-200 (default 5 for research, 3 otherwise; env XENO_MAX_WEB_SEARCHES)").option("--max-web-fetches <n>","Page fetches allowed per turn, 1-500 (default 12 for research, 4 otherwise; env XENO_MAX_WEB_FETCHES)").option("--max-web-calls <n>","Searches plus fetches allowed per turn (default: the sum of the two; env XENO_MAX_WEB_CALLS)").option("--memory-context-sessions <n>","Prior-session context entries for prompt memory (1-10)").option("--memory-context-tokens <n>","Token budget for prior-session prompt memory context").option("--memory-context-chars <n>","Per-session char budget for prior-session prompt memory context").option("--mode <mode>","Execution mode: agent, chat").option("--agent <name>","Use a built-in specialist profile or custom .xeno/agents definition").option("--image <path...>","Attach image file paths by asking the agent to inspect them with ReadImage").option("--delegate","Enable planner/explorer/executor/reviewer delegation mode").option("--delegate-max-total-tokens <n>","Total token budget for delegated branches").option("--delegate-timeout-ms <n>","Wall-clock budget for delegated run (ms)").option("--delegate-mode <mode>","Delegation workflow mode: staged or parallel").option("--delegate-team <team>","Delegation team preset: balanced, explore, build, or review").option("--delegate-roles <csv>","Delegated branch roles (comma-separated)").option("--delegate-concurrency <n|auto>","Max concurrent delegated branches").option("--delegate-role-precedence <csv>","Reducer precedence list (comma-separated roles)").option("--delegate-remote <policy>","Delegated branch remote MCP policy: none, prompts, resources, context, all, or role=policy,...").option("--color <color>","UI color/theme name").option("--permission-mode <mode>","Permission mode: default, plan, auto, acceptEdits, bypassPermissions").option("--security-level <level>","Execution security: policy-only, process-hardened, or contained","policy-only").option("--untrusted","Require certified contained execution; never downgrades").option("--allow-network","Acknowledge network access for trusted process-hardened execution").option("--allow-directory <path...>","Additional policy directory allowlist for secured execution").option("--resume [id]","Resume a previous session (latest if no ID)").option("--claim-handoff <id>","Claim a prepared execution handoff while resuming").option("--execution-owner <id>","Stable owner ID required by a reserved handoff").option("--execution-authority <url>","Take this session's execution ownership from an execution authority (also XENO_EXECUTION_AUTHORITY; token in XENO_EXECUTION_TOKEN)").option("--interface","Open the XENO Agent Interface and resume this workspace's session there").option("--bg [prompt]","Start an interactive background agent session and print its session ID").option("--exec <command>","With --bg, start a background shell session for this command").option("--role <name>","Use specific role identity").option("--checkpoint <id>","Resume from a specific checkpoint").option("--mcp","Enable MCP server loading from config").option("--line-input","Use Windows-safe line input instead of the fullscreen raw TUI").option("--tui","Force the fullscreen raw TUI on Windows").option("--accessibility <mode>","Accessibility mode: standard, high-contrast, or plain").option("--safe-mode","Disable user/project customizations for troubleshooting").action(async(e,t)=>{let r=kte(e),n=e.model||zt.model||Gr,i=Fln(e.fallbackModels,Kq.fallbackModels),o=Uln(e.effort,Kq.effort),s=jln(e.effort,Kq.effort);e.effort!==void 0&&!Ovt(e.effort)&&(console.error(`Invalid effort: ${e.effort}. Expected: ${[...Bvt,Su].join(", ")}.`),process.exit(1));let a=yS(e.apiKey,process.env.XENO_API_KEY,zt.apiKey,ld),l=typeof e.apiKey=="string"&&e.apiKey.trim().length>0,c=typeof process.env.XENO_API_KEY=="string"&&process.env.XENO_API_KEY.trim().length>0,d=typeof zt.apiKey=="string"&&zt.apiKey.trim().length>0,u=l?"explicit-api-key":c?"env-api-key":d?"config-api-key":"none",p=bw({explicitBaseURL:e.baseUrl,configuredBaseURL:zt.baseURL}),f=e.maxTokens?parseInt(e.maxTokens,10):zt.maxTokens??Ite,h=e.maxIterations?parseInt(e.maxIterations,10):zt.maxIterations??s_e,m=e.memoryContextSessions?parseInt(e.memoryContextSessions,10):zt.memoryContextSessions,g=e.memoryContextTokens?parseInt(e.memoryContextTokens,10):zt.memoryContextTokens,w=e.memoryContextChars?parseInt(e.memoryContextChars,10):zt.memoryContextChars;if(e.claimHandoff&&!(typeof e.resume=="string"&&e.resume.trim())&&(console.error("--claim-handoff requires --resume <session-id> so the target continues the same durable session."),process.exit(1)),e.claimHandoff)try{let ie=await QX(typeof e.executionAuthority=="string"?e.executionAuthority:void 0,e.resume.trim(),e.claimHandoff,process.cwd());ie&&console.error(ie)}catch(ie){console.error(`Handoff ${e.claimHandoff} could not be claimed: ${ie instanceof Error?ie.message:String(ie)}`),process.exit(1)}let y=t.invokedName()==="chat"||t.invokedName()===void 0&&e.mode!==void 0&&S8e({explicitMode:e.mode})==="chatOnly";if(e.resume===!0&&!y){let ie=i_e(r?void 0:e.agent,process.cwd()),he=await Ndt({resume:!0,cwd:process.cwd(),role:e.role??ie.profile.memory.role,explicitModel:e.model});he&&(e.resume=he.sessionId)}let A=S8e({explicitMode:e.mode,configuredMode:zt.executionMode,resumedMode:await ojr(e.resume),invokedName:t.invokedName()});if(A==="chatOnly"){let ie=i_e(r?void 0:e.agent,process.cwd());process.chdir(await njr({resume:e.resume,role:e.role??ie.profile.memory.role??"default",onResumeSelected:he=>{e.resume=he}}))}else typeof e.resume=="string"&&e.resume.trim()&&process.chdir(await sjr(e.resume));let b=!!e.delegate,I=e.delegateMaxTotalTokens?parseInt(e.delegateMaxTotalTokens,10):void 0,v=e.delegateTimeoutMs?parseInt(e.delegateTimeoutMs,10):void 0,k=qln(e.delegateMode),S=Gln(e.delegateTeam),x=Qln(e.delegateRoles),E=Hln(e.delegateConcurrency),C=Wln(e.delegateRemote),_=typeof e.delegateRolePrecedence=="string"?e.delegateRolePrecedence.split(",").map(ie=>ie.trim()).filter(ie=>ie.length>0):void 0,P=r?!1:!!(e.mcp||zt.mcpEnabled),R=A==="chatOnly"?"default":e.permissionMode||zt.permissionMode||"default",$=(()=>{try{return J_({cwd:process.cwd(),requestedLevel:e.securityLevel,untrusted:!!e.untrusted,allowNetwork:!!e.allowNetwork,allowedDirectories:Array.isArray(e.allowDirectory)?e.allowDirectory:void 0})}catch(ie){console.error(ie instanceof Error?ie.message:String(ie)),process.exit(1)}})(),O=String(e.color||zt.uiColor||"blue").toLowerCase(),N=i_e(r?void 0:e.agent,process.cwd()),j=FUr(Pdt(e.image,process.cwd())),D=await Ndt({resume:e.resume,cwd:process.cwd(),role:e.role??N.profile.memory.role,explicitModel:e.model});D&&(e.resume=D.sessionId,n=D.model);let B=!!(N.name&&!e.model);N.definition?.model&&B&&(n=n_e(N.definition,n)),yG(process.cwd()),Bm(O)||(console.error(`Invalid UI color: ${O}. Expected one of: ${QR().join(", ")}`),process.exit(1)),HR(O);let q=_rr;(ie=>q.includes(ie))(R)||(console.error(`Invalid permission mode: ${R}`),process.exit(1));let U=["agent","chatOnly"];(ie=>U.includes(ie))(A)||(console.error(`Invalid execution mode: ${A}. Expected: agent or chat`),process.exit(1)),m!==void 0&&(!Number.isInteger(m)||m<1||m>10)&&(console.error(`Invalid memory context session count: ${m}. Expected 1-10.`),process.exit(1)),g!==void 0&&(!Number.isInteger(g)||g<120)&&(console.error(`Invalid memory context token budget: ${g}. Expected integer >= 120.`),process.exit(1)),w!==void 0&&(!Number.isInteger(w)||w<200)&&(console.error(`Invalid memory context char budget: ${w}. Expected integer >= 200.`),process.exit(1)),I!==void 0&&(!Number.isInteger(I)||I<300)&&(console.error(`Invalid delegation token budget: ${I}. Expected integer >= 300.`),process.exit(1)),v!==void 0&&(!Number.isInteger(v)||v<1e3)&&(console.error(`Invalid delegation timeout: ${v}. Expected integer >= 1000 ms.`),process.exit(1)),e.delegateMode!==void 0&&k===void 0&&(console.error(`Invalid delegation mode: ${e.delegateMode}. Expected staged or parallel.`),process.exit(1)),e.delegateTeam!==void 0&&S===void 0&&(console.error(`Invalid delegation team: ${e.delegateTeam}. Expected balanced, explore, build, or review.`),process.exit(1)),e.delegateRoles!==void 0&&x===void 0&&(console.error(`Invalid delegation roles: ${e.delegateRoles}. Expected comma-separated planner,explorer,executor,reviewer or aliases like worker,researcher.`),process.exit(1)),e.delegateConcurrency!==void 0&&E===void 0&&String(e.delegateConcurrency).trim().toLowerCase()!=="auto"&&String(e.delegateConcurrency).trim().toLowerCase()!=="default"&&(console.error(`Invalid delegation concurrency: ${e.delegateConcurrency}. Expected integer >= 1 or auto.`),process.exit(1)),E!==void 0&&E<1&&(console.error(`Invalid delegation concurrency: ${E}. Expected integer >= 1 or auto.`),process.exit(1)),e.delegateRemote!==void 0&&C===void 0&&(console.error(`Invalid delegation remote policy: ${e.delegateRemote}. Expected none, prompts, resources, context, all, or role=policy,...`),process.exit(1));let ce=typeof e.bg=="string"?e.bg.trim():"",ne=typeof e.exec=="string"?e.exec.trim():"";if(ne&&e.bg===void 0&&(console.error('Use --exec with --bg, for example: xeno --bg --exec "npm test"'),process.exit(1)),e.bg!==void 0||ne){let ie=ne||ce;ie||(console.error("Usage: xeno --bg <task> or xeno --bg --exec <command>"),process.exit(1));let he=ne?null:ud(ie,{surface:"background"});he&&(console.error(he.message),process.exit(2));let we=new tt().create({kind:ne?"shell":"chat",name:ne?"Shell":N.runRef?.name??"Background",title:ie.replace(/\s+/g," ").slice(0,80),prompt:ie,cwd:process.cwd(),...ne?{}:{model:n},...o?{effort:o}:{},...!ne&&N.runRef?{agent:N.runRef}:{},permissionMode:R,executionSecurity:$.selection,...ne?{}:{authority:bF(N.profile,{safeMode:r})},worktree:{enabled:!0}}),Te=bd(we.sessionId,{cliVersion:Pe});process.stdout.write(`Background ${ne?"shell":"agent"} session queued: ${Te.record.sessionId}
17397
+ `)});Oe.command("ws [args...]").description("Use your XENO workspace from the terminal: list, describe and call any capability your credential may use (XENO_WORKSPACE_KEY)").allowExcessArguments(!0).action(async(e=[])=>{process.exitCode=await Idt(e)});Oe.command("agent",{isDefault:!0}).alias("chat").description("Open the XENO Agent or Chat terminal cockpit").option("-m, --model <model>","AI model to use").option("--fallback-models <models>","Comma-separated fallback models for retryable provider failures").option("--effort <level>","Reasoning effort: low, medium, high, xhigh, max, or ultracode").option("-k, --api-key <key>","API key (optional for Xeno API)").option("--base-url <url>","API base URL").option("--max-tokens <n>","Max response tokens").option("--max-iterations <n>","Max agentic loop iterations").option("--max-web-searches <n>","Web searches allowed per turn, 1-200 (default 5 for research, 3 otherwise; env XENO_MAX_WEB_SEARCHES)").option("--max-web-fetches <n>","Page fetches allowed per turn, 1-500 (default 12 for research, 4 otherwise; env XENO_MAX_WEB_FETCHES)").option("--max-web-calls <n>","Searches plus fetches allowed per turn (default: the sum of the two; env XENO_MAX_WEB_CALLS)").option("--memory-context-sessions <n>","Prior-session context entries for prompt memory (1-10)").option("--memory-context-tokens <n>","Token budget for prior-session prompt memory context").option("--memory-context-chars <n>","Per-session char budget for prior-session prompt memory context").option("--mode <mode>","Execution mode: agent, chat").option("--agent <name>","Use a built-in specialist profile or custom .xeno/agents definition").option("--image <path...>","Attach image file paths by asking the agent to inspect them with ReadImage").option("--delegate","Enable planner/explorer/executor/reviewer delegation mode").option("--delegate-max-total-tokens <n>","Total token budget for delegated branches").option("--delegate-timeout-ms <n>","Wall-clock budget for delegated run (ms)").option("--delegate-mode <mode>","Delegation workflow mode: staged or parallel").option("--delegate-team <team>","Delegation team preset: balanced, explore, build, or review").option("--delegate-roles <csv>","Delegated branch roles (comma-separated)").option("--delegate-concurrency <n|auto>","Max concurrent delegated branches").option("--delegate-role-precedence <csv>","Reducer precedence list (comma-separated roles)").option("--delegate-remote <policy>","Delegated branch remote MCP policy: none, prompts, resources, context, all, or role=policy,...").option("--color <color>","UI color/theme name").option("--permission-mode <mode>","Permission mode: default, plan, auto, acceptEdits, bypassPermissions").option("--security-level <level>","Execution security: policy-only, process-hardened, or contained","policy-only").option("--untrusted","Require certified contained execution; never downgrades").option("--allow-network","Acknowledge network access for trusted process-hardened execution").option("--allow-directory <path...>","Additional policy directory allowlist for secured execution").option("--resume [id]","Resume a previous session (latest if no ID)").option("--claim-handoff <id>","Claim a prepared execution handoff while resuming").option("--execution-owner <id>","Stable owner ID required by a reserved handoff").option("--execution-authority <url>","Take this session's execution ownership from an execution authority (also XENO_EXECUTION_AUTHORITY; token in XENO_EXECUTION_TOKEN)").option("--interface","Open the XENO Agent Interface and resume this workspace's session there").option("--bg [prompt]","Start an interactive background agent session and print its session ID").option("--exec <command>","With --bg, start a background shell session for this command").option("--role <name>","Use specific role identity").option("--checkpoint <id>","Resume from a specific checkpoint").option("--mcp","Enable MCP server loading from config").option("--line-input","Use Windows-safe line input instead of the fullscreen raw TUI").option("--tui","Force the fullscreen raw TUI on Windows").option("--accessibility <mode>","Accessibility mode: standard, high-contrast, or plain").option("--safe-mode","Disable user/project customizations for troubleshooting").action(async(e,t)=>{let r=kte(e),n=e.model||Gt.model||Gr,i=Fln(e.fallbackModels,Kq.fallbackModels),o=Uln(e.effort,Kq.effort),s=jln(e.effort,Kq.effort);e.effort!==void 0&&!Ovt(e.effort)&&(console.error(`Invalid effort: ${e.effort}. Expected: ${[...Bvt,Su].join(", ")}.`),process.exit(1));let a=yS(e.apiKey,process.env.XENO_API_KEY,Gt.apiKey,ld),l=typeof e.apiKey=="string"&&e.apiKey.trim().length>0,c=typeof process.env.XENO_API_KEY=="string"&&process.env.XENO_API_KEY.trim().length>0,d=typeof Gt.apiKey=="string"&&Gt.apiKey.trim().length>0,u=l?"explicit-api-key":c?"env-api-key":d?"config-api-key":"none",p=bw({explicitBaseURL:e.baseUrl,configuredBaseURL:Gt.baseURL}),f=e.maxTokens?parseInt(e.maxTokens,10):Gt.maxTokens??Ite,h=e.maxIterations?parseInt(e.maxIterations,10):Gt.maxIterations??s_e,m=e.memoryContextSessions?parseInt(e.memoryContextSessions,10):Gt.memoryContextSessions,g=e.memoryContextTokens?parseInt(e.memoryContextTokens,10):Gt.memoryContextTokens,w=e.memoryContextChars?parseInt(e.memoryContextChars,10):Gt.memoryContextChars;if(e.claimHandoff&&!(typeof e.resume=="string"&&e.resume.trim())&&(console.error("--claim-handoff requires --resume <session-id> so the target continues the same durable session."),process.exit(1)),e.claimHandoff)try{let ie=await QX(typeof e.executionAuthority=="string"?e.executionAuthority:void 0,e.resume.trim(),e.claimHandoff,process.cwd());ie&&console.error(ie)}catch(ie){console.error(`Handoff ${e.claimHandoff} could not be claimed: ${ie instanceof Error?ie.message:String(ie)}`),process.exit(1)}let y=t.invokedName()==="chat"||t.invokedName()===void 0&&e.mode!==void 0&&S8e({explicitMode:e.mode})==="chatOnly";if(e.resume===!0&&!y){let ie=i_e(r?void 0:e.agent,process.cwd()),he=await Ndt({resume:!0,cwd:process.cwd(),role:e.role??ie.profile.memory.role,explicitModel:e.model});he&&(e.resume=he.sessionId)}let A=S8e({explicitMode:e.mode,configuredMode:Gt.executionMode,resumedMode:await ojr(e.resume),invokedName:t.invokedName()});if(A==="chatOnly"){let ie=i_e(r?void 0:e.agent,process.cwd());process.chdir(await njr({resume:e.resume,role:e.role??ie.profile.memory.role??"default",onResumeSelected:he=>{e.resume=he}}))}else typeof e.resume=="string"&&e.resume.trim()&&process.chdir(await sjr(e.resume));let b=!!e.delegate,I=e.delegateMaxTotalTokens?parseInt(e.delegateMaxTotalTokens,10):void 0,v=e.delegateTimeoutMs?parseInt(e.delegateTimeoutMs,10):void 0,k=qln(e.delegateMode),S=Gln(e.delegateTeam),x=Qln(e.delegateRoles),E=Hln(e.delegateConcurrency),C=Wln(e.delegateRemote),_=typeof e.delegateRolePrecedence=="string"?e.delegateRolePrecedence.split(",").map(ie=>ie.trim()).filter(ie=>ie.length>0):void 0,P=r?!1:!!(e.mcp||Gt.mcpEnabled),R=A==="chatOnly"?"default":e.permissionMode||Gt.permissionMode||"default",$=(()=>{try{return J_({cwd:process.cwd(),requestedLevel:e.securityLevel,untrusted:!!e.untrusted,allowNetwork:!!e.allowNetwork,allowedDirectories:Array.isArray(e.allowDirectory)?e.allowDirectory:void 0})}catch(ie){console.error(ie instanceof Error?ie.message:String(ie)),process.exit(1)}})(),O=String(e.color||Gt.uiColor||"blue").toLowerCase(),N=i_e(r?void 0:e.agent,process.cwd()),j=FUr(Pdt(e.image,process.cwd())),D=await Ndt({resume:e.resume,cwd:process.cwd(),role:e.role??N.profile.memory.role,explicitModel:e.model});D&&(e.resume=D.sessionId,n=D.model);let B=!!(N.name&&!e.model);N.definition?.model&&B&&(n=n_e(N.definition,n)),yG(process.cwd()),Bm(O)||(console.error(`Invalid UI color: ${O}. Expected one of: ${QR().join(", ")}`),process.exit(1)),HR(O);let q=_rr;(ie=>q.includes(ie))(R)||(console.error(`Invalid permission mode: ${R}`),process.exit(1));let U=["agent","chatOnly"];(ie=>U.includes(ie))(A)||(console.error(`Invalid execution mode: ${A}. Expected: agent or chat`),process.exit(1)),m!==void 0&&(!Number.isInteger(m)||m<1||m>10)&&(console.error(`Invalid memory context session count: ${m}. Expected 1-10.`),process.exit(1)),g!==void 0&&(!Number.isInteger(g)||g<120)&&(console.error(`Invalid memory context token budget: ${g}. Expected integer >= 120.`),process.exit(1)),w!==void 0&&(!Number.isInteger(w)||w<200)&&(console.error(`Invalid memory context char budget: ${w}. Expected integer >= 200.`),process.exit(1)),I!==void 0&&(!Number.isInteger(I)||I<300)&&(console.error(`Invalid delegation token budget: ${I}. Expected integer >= 300.`),process.exit(1)),v!==void 0&&(!Number.isInteger(v)||v<1e3)&&(console.error(`Invalid delegation timeout: ${v}. Expected integer >= 1000 ms.`),process.exit(1)),e.delegateMode!==void 0&&k===void 0&&(console.error(`Invalid delegation mode: ${e.delegateMode}. Expected staged or parallel.`),process.exit(1)),e.delegateTeam!==void 0&&S===void 0&&(console.error(`Invalid delegation team: ${e.delegateTeam}. Expected balanced, explore, build, or review.`),process.exit(1)),e.delegateRoles!==void 0&&x===void 0&&(console.error(`Invalid delegation roles: ${e.delegateRoles}. Expected comma-separated planner,explorer,executor,reviewer or aliases like worker,researcher.`),process.exit(1)),e.delegateConcurrency!==void 0&&E===void 0&&String(e.delegateConcurrency).trim().toLowerCase()!=="auto"&&String(e.delegateConcurrency).trim().toLowerCase()!=="default"&&(console.error(`Invalid delegation concurrency: ${e.delegateConcurrency}. Expected integer >= 1 or auto.`),process.exit(1)),E!==void 0&&E<1&&(console.error(`Invalid delegation concurrency: ${E}. Expected integer >= 1 or auto.`),process.exit(1)),e.delegateRemote!==void 0&&C===void 0&&(console.error(`Invalid delegation remote policy: ${e.delegateRemote}. Expected none, prompts, resources, context, all, or role=policy,...`),process.exit(1));let ce=typeof e.bg=="string"?e.bg.trim():"",ne=typeof e.exec=="string"?e.exec.trim():"";if(ne&&e.bg===void 0&&(console.error('Use --exec with --bg, for example: xeno --bg --exec "npm test"'),process.exit(1)),e.bg!==void 0||ne){let ie=ne||ce;ie||(console.error("Usage: xeno --bg <task> or xeno --bg --exec <command>"),process.exit(1));let he=ne?null:ud(ie,{surface:"background"});he&&(console.error(he.message),process.exit(2));let we=new tt().create({kind:ne?"shell":"chat",name:ne?"Shell":N.runRef?.name??"Background",title:ie.replace(/\s+/g," ").slice(0,80),prompt:ie,cwd:process.cwd(),...ne?{}:{model:n},...o?{effort:o}:{},...!ne&&N.runRef?{agent:N.runRef}:{},permissionMode:R,executionSecurity:$.selection,...ne?{}:{authority:bF(N.profile,{safeMode:r})},worktree:{enabled:!0}}),Te=bd(we.sessionId,{cliVersion:Pe});process.stdout.write(`Background ${ne?"shell":"agent"} session queued: ${Te.record.sessionId}
17398
17398
  `),process.stdout.write(`Open: xeno attach ${Te.record.sessionId} --no-follow
17399
17399
  `);return}if(e.interface){try{let ie=await ejr({cwd:process.cwd(),mode:A==="chatOnly"?"chat":"agent",resume:e.resume??!0});process.stdout.write(ie.sessionId?`Opened XENO Agent Interface; the desktop accepted the resume request for session ${ie.sessionId}.
17400
17400
  `:`Opened XENO Agent Interface. No resumable session exists in this workspace yet.
@@ -17403,9 +17403,9 @@ ${d===0?"No reachability findings.":`${d} finding(s).`}
17403
17403
  ${U$(Ge.matches)}`);if(Ge.kind==="unknown")throw new Error(c?`This session acted as ${l}, which is no longer one of your agents. Pass --as me to continue it as yourself, or --as <agent>. Your agents:
17404
17404
  ${U$(Ge.agents)}`:`No agent of yours matches "${Ge.ref}". Your agents:
17405
17405
  ${U$(Ge.agents)}`);Ge.kind==="agent"&&(s=await o.useAgent(Ge.agent.id))}let d=[],u=s?`cli:${vte()}`:void 0,p=null;if(o&&s)try{d=await BIe(o,{runId:u})}catch(se){process.stderr.write(`[xeno] XENO platform services are unavailable for this run (${se.message}); its XENO Tasks tools still work.
17406
- `)}let f=s?UCr(s.runtime,{model:t.model,effort:t.effort}):null,h=t.model||f?.model||zt.model||Gr,m=Fln(t.fallbackModels,Kq.fallbackModels),g=f?.effort!==void 0&&Ovt(f.effort)?f.effort:void 0,w=Uln(t.effort??g,Kq.effort),y=jln(t.effort,Kq.effort);t.effort!==void 0&&!Ovt(t.effort)&&(console.error(`Invalid effort: ${t.effort}. Expected: ${[...Bvt,Su].join(", ")}.`),process.exit(1));let A=yS(t.apiKey,process.env.XENO_API_KEY,zt.apiKey,ld),b=typeof t.apiKey=="string"&&t.apiKey.trim().length>0,I=typeof process.env.XENO_API_KEY=="string"&&process.env.XENO_API_KEY.trim().length>0,v=typeof zt.apiKey=="string"&&zt.apiKey.trim().length>0,k=b?"explicit-api-key":I?"env-api-key":v?"config-api-key":"none",S=bw({explicitBaseURL:t.baseUrl,configuredBaseURL:zt.baseURL}),x=t.maxTokens?parseInt(t.maxTokens,10):zt.maxTokens??Ite,E=t.maxIterations?parseInt(t.maxIterations,10):zt.maxIterations??s_e,C=t.memoryContextSessions?parseInt(t.memoryContextSessions,10):zt.memoryContextSessions,_=t.memoryContextTokens?parseInt(t.memoryContextTokens,10):zt.memoryContextTokens,P=t.memoryContextChars?parseInt(t.memoryContextChars,10):zt.memoryContextChars,R=t.mode||zt.executionMode||"agent",$=String(R).toLowerCase()==="chat"?"chatOnly":R,O=String(t.color||zt.uiColor||"blue").toLowerCase(),N=!!t.json,j=!!t.ndjson,D=N||j;N&&j&&(console.error("Choose either --json or --ndjson, not both."),process.exit(1)),r=LUr(r,Pdt(t.image,process.cwd()));let B=JIe(r),q=B.requested;B.requested&&(r=B.input,w="max",y="ultracode");let L=!q&&YIe(r),U=i_e(i?void 0:t.agent,process.cwd());U.definition?.model&&!t.model&&(h=n_e(U.definition,h));let re=U.runRef,ce=U.promptSections,ne=U.profile?.capabilities.tools,ie=unr(t.allowedTools,t.disallowedTools),he;try{he=pnr(ie)}catch(se){console.error(se instanceof Error?se.message:String(se)),process.exit(2)}for(let se of U.definition?.notices??[])process.stderr.write(`[agent ${U.name}] ${se}
17407
- `);let Se=U.profile?Ka(U.profile.capabilities.permissionProfile)??void 0:void 0,we=U.profile?.memory.role,Te=U.profile?.memory.scope==="none"?!1:{...U.profile?{scope:U.profile.memory.scope}:{},projectSessionContext:{limit:C,maxTokens:_,maxCharsPerSession:P}},Ee=!!t.delegate,Ke=i?!1:!!(t.mcp||zt.mcpEnabled),De=t.delegateMaxTotalTokens?parseInt(t.delegateMaxTotalTokens,10):Math.max(x*3,1200),yt=t.delegateTimeoutMs?parseInt(t.delegateTimeoutMs,10):12e4,Ve=qln(t.delegateMode),nt=Gln(t.delegateTeam),ze=Qln(t.delegateRoles),Qr=Hln(t.delegateConcurrency),Ms=Wln(t.delegateRemote),ua=typeof t.delegateRolePrecedence=="string"?t.delegateRolePrecedence.split(",").map(se=>se.trim()).filter(se=>se.length>0):void 0,ti=typeof t.goal=="string"?t.goal.trim():"",vc=t.goalMaxTurns?parseInt(t.goalMaxTurns,10):void 0,bl=t.goalMaxTokens===void 0?void 0:Number(t.goalMaxTokens),Jf="deterministic";try{Jf=s3o(t.goalVerifier)}catch(se){let Ge=se instanceof Error?se.message:String(se);console.error(Ge),process.exit(1)}yG(process.cwd()),Bm(O)||(console.error(`Invalid UI color: ${O}. Expected one of: ${QR().join(", ")}`),process.exit(1)),HR(O),$!=="agent"&&$!=="chatOnly"&&(console.error(`Invalid execution mode: ${$}. Expected: agent or chat`),process.exit(1)),C!==void 0&&(!Number.isInteger(C)||C<1||C>10)&&(console.error(`Invalid memory context session count: ${C}. Expected 1-10.`),process.exit(1)),_!==void 0&&(!Number.isInteger(_)||_<120)&&(console.error(`Invalid memory context token budget: ${_}. Expected integer >= 120.`),process.exit(1)),P!==void 0&&(!Number.isInteger(P)||P<200)&&(console.error(`Invalid memory context char budget: ${P}. Expected integer >= 200.`),process.exit(1)),Ee&&(!Number.isInteger(De)||De<300)&&(console.error(`Invalid delegation token budget: ${De}. Expected integer >= 300.`),process.exit(1)),Ee&&(!Number.isInteger(yt)||yt<1e3)&&(console.error(`Invalid delegation timeout: ${yt}. Expected integer >= 1000 ms.`),process.exit(1)),t.delegateMode!==void 0&&Ve===void 0&&(console.error(`Invalid delegation mode: ${t.delegateMode}. Expected staged or parallel.`),process.exit(1)),t.delegateTeam!==void 0&&nt===void 0&&(console.error(`Invalid delegation team: ${t.delegateTeam}. Expected balanced, explore, build, or review.`),process.exit(1)),t.delegateRoles!==void 0&&ze===void 0&&(console.error(`Invalid delegation roles: ${t.delegateRoles}. Expected comma-separated planner,explorer,executor,reviewer or aliases like worker,researcher.`),process.exit(1)),t.delegateConcurrency!==void 0&&Qr===void 0&&String(t.delegateConcurrency).trim().toLowerCase()!=="auto"&&String(t.delegateConcurrency).trim().toLowerCase()!=="default"&&(console.error(`Invalid delegation concurrency: ${t.delegateConcurrency}. Expected integer >= 1 or auto.`),process.exit(1)),Qr!==void 0&&Qr<1&&(console.error(`Invalid delegation concurrency: ${Qr}. Expected integer >= 1 or auto.`),process.exit(1)),t.delegateRemote!==void 0&&Ms===void 0&&(console.error(`Invalid delegation remote policy: ${t.delegateRemote}. Expected none, prompts, resources, context, all, or role=policy,...`),process.exit(1)),t.goal!==void 0&&ti.length===0&&(console.error("Invalid goal: condition cannot be empty."),process.exit(1)),vc!==void 0&&(!Number.isInteger(vc)||vc<1)&&(console.error(`Invalid goal max turns: ${t.goalMaxTurns}. Expected integer >= 1.`),process.exit(1)),bl!==void 0&&(!ti||!Number.isSafeInteger(bl)||bl<1)&&(console.error("Invalid goal max tokens: supply --goal and a positive safe integer token limit."),process.exit(1)),bl!==void 0&&(Ee||Qw(process.env[pf])!=="off"||t.remote)&&(console.error("A bounded goal cannot run with host attach, remote execution, or delegated branches; those lanes do not share the goal token budget yet."),process.exit(1)),bl!==void 0&&!D&&process.stderr.write(`Goal budget: ${G0e(bl,J1r(h))}.
17408
- `),bl!==void 0&&Jf!=="deterministic"&&(console.error("A bounded goal currently requires the deterministic verifier; model-based verification has no shared token quota binding."),process.exit(1));let Ut=["default","plan","auto","acceptEdits","bypassPermissions"],Wa=String(t.permissionMode||zt.permissionMode||"default");Ut.includes(Wa)||(console.error(`Invalid permission mode: ${Wa}. Expected: ${Ut.join(", ")}.`),process.exit(1)),Wa==="plan"&&(t.bypassPermissions||t.yes)&&(console.error(`Plan mode is read-only and cannot be combined with ${t.bypassPermissions?"--bypass-permissions":"--yes"}. Remove the flag to plan, or drop --permission-mode plan to let the run make changes.`),process.exit(1)),Wa==="plan"&&ti&&(console.error($rr),process.exit(1));let ki=Wa;t.bypassPermissions?(await Gan("xeno run --bypass-permissions"),ki="bypassPermissions",D||(console.warn(`
17406
+ `)}let f=s?UCr(s.runtime,{model:t.model,effort:t.effort}):null,h=t.model||f?.model||Gt.model||Gr,m=Fln(t.fallbackModels,Kq.fallbackModels),g=f?.effort!==void 0&&Ovt(f.effort)?f.effort:void 0,w=Uln(t.effort??g,Kq.effort),y=jln(t.effort,Kq.effort);t.effort!==void 0&&!Ovt(t.effort)&&(console.error(`Invalid effort: ${t.effort}. Expected: ${[...Bvt,Su].join(", ")}.`),process.exit(1));let A=yS(t.apiKey,process.env.XENO_API_KEY,Gt.apiKey,ld),b=typeof t.apiKey=="string"&&t.apiKey.trim().length>0,I=typeof process.env.XENO_API_KEY=="string"&&process.env.XENO_API_KEY.trim().length>0,v=typeof Gt.apiKey=="string"&&Gt.apiKey.trim().length>0,k=b?"explicit-api-key":I?"env-api-key":v?"config-api-key":"none",S=bw({explicitBaseURL:t.baseUrl,configuredBaseURL:Gt.baseURL}),x=t.maxTokens?parseInt(t.maxTokens,10):Gt.maxTokens??Ite,E=t.maxIterations?parseInt(t.maxIterations,10):Gt.maxIterations??s_e,C=t.memoryContextSessions?parseInt(t.memoryContextSessions,10):Gt.memoryContextSessions,_=t.memoryContextTokens?parseInt(t.memoryContextTokens,10):Gt.memoryContextTokens,P=t.memoryContextChars?parseInt(t.memoryContextChars,10):Gt.memoryContextChars,R=t.mode||Gt.executionMode||"agent",$=String(R).toLowerCase()==="chat"?"chatOnly":R,O=String(t.color||Gt.uiColor||"blue").toLowerCase(),N=!!t.json,j=!!t.ndjson,D=N||j;N&&j&&(console.error("Choose either --json or --ndjson, not both."),process.exit(1)),r=LUr(r,Pdt(t.image,process.cwd()));let B=JIe(r),q=B.requested;B.requested&&(r=B.input,w="max",y="ultracode");let L=!q&&YIe(r),U=i_e(i?void 0:t.agent,process.cwd());U.definition?.model&&!t.model&&(h=n_e(U.definition,h));let re=U.runRef,ce=U.promptSections,ne=U.profile?.capabilities.tools,ie=unr(t.allowedTools,t.disallowedTools),he;try{he=pnr(ie)}catch(se){console.error(se instanceof Error?se.message:String(se)),process.exit(2)}for(let se of U.definition?.notices??[])process.stderr.write(`[agent ${U.name}] ${se}
17407
+ `);let Se=U.profile?Ka(U.profile.capabilities.permissionProfile)??void 0:void 0,we=U.profile?.memory.role,Te=U.profile?.memory.scope==="none"?!1:{...U.profile?{scope:U.profile.memory.scope}:{},projectSessionContext:{limit:C,maxTokens:_,maxCharsPerSession:P}},Ee=!!t.delegate,Ke=i?!1:!!(t.mcp||Gt.mcpEnabled),De=t.delegateMaxTotalTokens?parseInt(t.delegateMaxTotalTokens,10):Math.max(x*3,1200),yt=t.delegateTimeoutMs?parseInt(t.delegateTimeoutMs,10):12e4,Ve=qln(t.delegateMode),nt=Gln(t.delegateTeam),ze=Qln(t.delegateRoles),Qr=Hln(t.delegateConcurrency),Ms=Wln(t.delegateRemote),ua=typeof t.delegateRolePrecedence=="string"?t.delegateRolePrecedence.split(",").map(se=>se.trim()).filter(se=>se.length>0):void 0,ti=typeof t.goal=="string"?t.goal.trim():"",vc=t.goalMaxTurns?parseInt(t.goalMaxTurns,10):void 0,bl=t.goalMaxTokens===void 0?void 0:Number(t.goalMaxTokens),Jf="deterministic";try{Jf=s3o(t.goalVerifier)}catch(se){let Ge=se instanceof Error?se.message:String(se);console.error(Ge),process.exit(1)}yG(process.cwd()),Bm(O)||(console.error(`Invalid UI color: ${O}. Expected one of: ${QR().join(", ")}`),process.exit(1)),HR(O),$!=="agent"&&$!=="chatOnly"&&(console.error(`Invalid execution mode: ${$}. Expected: agent or chat`),process.exit(1)),C!==void 0&&(!Number.isInteger(C)||C<1||C>10)&&(console.error(`Invalid memory context session count: ${C}. Expected 1-10.`),process.exit(1)),_!==void 0&&(!Number.isInteger(_)||_<120)&&(console.error(`Invalid memory context token budget: ${_}. Expected integer >= 120.`),process.exit(1)),P!==void 0&&(!Number.isInteger(P)||P<200)&&(console.error(`Invalid memory context char budget: ${P}. Expected integer >= 200.`),process.exit(1)),Ee&&(!Number.isInteger(De)||De<300)&&(console.error(`Invalid delegation token budget: ${De}. Expected integer >= 300.`),process.exit(1)),Ee&&(!Number.isInteger(yt)||yt<1e3)&&(console.error(`Invalid delegation timeout: ${yt}. Expected integer >= 1000 ms.`),process.exit(1)),t.delegateMode!==void 0&&Ve===void 0&&(console.error(`Invalid delegation mode: ${t.delegateMode}. Expected staged or parallel.`),process.exit(1)),t.delegateTeam!==void 0&&nt===void 0&&(console.error(`Invalid delegation team: ${t.delegateTeam}. Expected balanced, explore, build, or review.`),process.exit(1)),t.delegateRoles!==void 0&&ze===void 0&&(console.error(`Invalid delegation roles: ${t.delegateRoles}. Expected comma-separated planner,explorer,executor,reviewer or aliases like worker,researcher.`),process.exit(1)),t.delegateConcurrency!==void 0&&Qr===void 0&&String(t.delegateConcurrency).trim().toLowerCase()!=="auto"&&String(t.delegateConcurrency).trim().toLowerCase()!=="default"&&(console.error(`Invalid delegation concurrency: ${t.delegateConcurrency}. Expected integer >= 1 or auto.`),process.exit(1)),Qr!==void 0&&Qr<1&&(console.error(`Invalid delegation concurrency: ${Qr}. Expected integer >= 1 or auto.`),process.exit(1)),t.delegateRemote!==void 0&&Ms===void 0&&(console.error(`Invalid delegation remote policy: ${t.delegateRemote}. Expected none, prompts, resources, context, all, or role=policy,...`),process.exit(1)),t.goal!==void 0&&ti.length===0&&(console.error("Invalid goal: condition cannot be empty."),process.exit(1)),vc!==void 0&&(!Number.isInteger(vc)||vc<1)&&(console.error(`Invalid goal max turns: ${t.goalMaxTurns}. Expected integer >= 1.`),process.exit(1)),bl!==void 0&&(!ti||!Number.isSafeInteger(bl)||bl<1)&&(console.error("Invalid goal max tokens: supply --goal and a positive safe integer token limit."),process.exit(1)),bl!==void 0&&(Ee||Qw(process.env[pf])!=="off"||t.remote)&&(console.error("A bounded goal cannot run with host attach, remote execution, or delegated branches; those lanes do not share the goal token budget yet."),process.exit(1)),bl!==void 0&&!D&&process.stderr.write(`Goal budget: ${G0e(bl,J1r(h))}.
17408
+ `),bl!==void 0&&Jf!=="deterministic"&&(console.error("A bounded goal currently requires the deterministic verifier; model-based verification has no shared token quota binding."),process.exit(1));let Ut=["default","plan","auto","acceptEdits","bypassPermissions"],Wa=String(t.permissionMode||Gt.permissionMode||"default");Ut.includes(Wa)||(console.error(`Invalid permission mode: ${Wa}. Expected: ${Ut.join(", ")}.`),process.exit(1)),Wa==="plan"&&(t.bypassPermissions||t.yes)&&(console.error(`Plan mode is read-only and cannot be combined with ${t.bypassPermissions?"--bypass-permissions":"--yes"}. Remove the flag to plan, or drop --permission-mode plan to let the run make changes.`),process.exit(1)),Wa==="plan"&&ti&&(console.error($rr),process.exit(1));let ki=Wa;t.bypassPermissions?(await Gan("xeno run --bypass-permissions"),ki="bypassPermissions",D||(console.warn(`
17409
17409
  \u26A0\uFE0F WARNING: Running with --bypass-permissions (UNSAFE)`),console.warn(` All security checks are disabled. Use with caution.
17410
17410
  `))):t.yes&&(ki=u0t(ki),!D&&ki==="acceptEdits"&&console.warn(`
17411
17411
  \u26A0\uFE0F Auto-accepting file edits (--yes). Terminal commands still need --permission-mode auto or bypassPermissions.
@@ -17418,12 +17418,12 @@ ${U$(Ge.agents)}`);Ge.kind==="agent"&&(s=await o.useAgent(Ge.agent.id))}let d=[]
17418
17418
  Pass --yes (acceptEdits) to let it edit inside the run's workspace.
17419
17419
  `);let Ue=await mIe({cwd:process.cwd(),command:"xeno run --remote",prompt:r,model:h,effort:w,...typeof t.environment=="string"&&t.environment.trim()?{environmentId:t.environment.trim()}:{},...se&&se>1?{attempts:se}:{},...Ge?{hostedReferences:Ge}:{},permissionMode:ki,...typeof t.title=="string"&&t.title.trim().length>0?{title:t.title.trim()}:{},...re?{agent:re}:{}});j?process.stdout.write(JSON.stringify({type:Ue.code,...Ue})+`
17420
17420
  `):N?process.stdout.write(JSON.stringify(Ue,null,2)+`
17421
- `):Ue.ok?process.stdout.write(Sj(Ue)):process.stderr.write(Sj(Ue)),Ue.ok||(process.exitCode=1);return}let Hr;try{Hr=G1e(t,zt,process.env.XENO_BACKGROUND_RUN_ID);let se=U.profile?.execution.isolation;if(se==="container"&&Rr.selection.level!=="contained")throw new Error(`Agent profile ${U.profile?.profile.id} requires certified container isolation.`);if(se==="worktree"&&!YS(process.cwd()))if(t.bg===!0||process.env.XENO_BACKGROUND_RUN_ID)Hr=Hr??{enabled:!0};else throw new Error(`Agent profile ${U.profile?.profile.id} requires worktree isolation. Run it from a linked worktree or use \`xeno run --bg --worktree ...\`.`)}catch(se){console.error(se instanceof Error?se.message:String(se)),process.exit(1)}let qe={schemaVersion:1,capturedAt:new Date().toISOString(),source:"xeno run --bg",cliVersion:Pe,model:h,...w?{effort:w}:{},...m?{fallbackModels:m}:{},permissionMode:ki,executionMode:$,maxTokens:x,maxIterations:E,...C!==void 0?{memoryContextSessions:C}:{},..._!==void 0?{memoryContextTokens:_}:{},...P!==void 0?{memoryContextChars:P}:{},mcpEnabled:Ke,safeMode:i,apiKeySource:k,...S?{baseURL:S}:{},uiColor:O,...re?{agent:re}:{},delegation:{enabled:Ee,...Ve?{mode:Ve}:{},...nt?{team:nt}:{},...ze?{roles:ze}:{},...Qr!==void 0?{concurrency:Qr}:{},...De!==void 0?{maxTotalTokens:De}:{},...yt!==void 0?{timeoutMs:yt}:{},...typeof t.delegateRemote=="string"?{remote:t.delegateRemote}:{}},goal:{enabled:ti.length>0,verifier:Jf,...vc!==void 0?{maxTurns:vc}:{},...bl!==void 0?{maxTokens:bl}:{}}};if(t.bg&&!process.env.XENO_BACKGROUND_RUN_ID){let se=await J0e({prompt:r,cwd:process.cwd(),model:h,effort:w,...re?{agent:re}:{},permissionMode:ki,executionSecurity:Rr.selection,cliVersion:Pe,resourceSurface:"background-run",resourcePriority:"background",...typeof t.title=="string"&&t.title.trim().length>0?{title:t.title.trim()}:{},pinned:!!t.pin,...Hr?{worktree:Hr}:{},configSnapshot:qe,rawArgv:process.argv.slice(2)});process.stdout.write(rke(se.record,D));return}let{AgentInterruptedError:jt,AuditLogger:_p,calculateReportedModelCost:Pp,createDefaultToolRegistry:Nv,createAuditBackedPermissionEngine:Ie,createDelegatedXenoAgent:gu,delegatedBranchOutputTokens:hr,createXenoAgent:pm,matchesMcpRegistryEntryPolicy:XE,normalizeSubagentBranchPolicy:JE,resolveSubagentRemoteMcpAccess:wu,resetAllPersistentShellSessions:yu,registerPlanModeTools:Rg,runDelegatedXenoTurn:$p,syncMcpToolsToRegistry:Kf}=await Promise.resolve().then(()=>(Er(),xrr)),Xe=process.cwd(),Di=process.env.XENO_BACKGROUND_RUN_ID?.trim()||void 0,uo=Di?new vt:void 0,Yf=null;try{Yf=Di?_z():null}catch(se){throw process.stderr.write(`WORKER_PERMIT_CLAIM_REFUSED ${JSON.stringify(Rz(se))}
17421
+ `):Ue.ok?process.stdout.write(Sj(Ue)):process.stderr.write(Sj(Ue)),Ue.ok||(process.exitCode=1);return}let Hr;try{Hr=G1e(t,Gt,process.env.XENO_BACKGROUND_RUN_ID);let se=U.profile?.execution.isolation;if(se==="container"&&Rr.selection.level!=="contained")throw new Error(`Agent profile ${U.profile?.profile.id} requires certified container isolation.`);if(se==="worktree"&&!YS(process.cwd()))if(t.bg===!0||process.env.XENO_BACKGROUND_RUN_ID)Hr=Hr??{enabled:!0};else throw new Error(`Agent profile ${U.profile?.profile.id} requires worktree isolation. Run it from a linked worktree or use \`xeno run --bg --worktree ...\`.`)}catch(se){console.error(se instanceof Error?se.message:String(se)),process.exit(1)}let qe={schemaVersion:1,capturedAt:new Date().toISOString(),source:"xeno run --bg",cliVersion:Pe,model:h,...w?{effort:w}:{},...m?{fallbackModels:m}:{},permissionMode:ki,executionMode:$,maxTokens:x,maxIterations:E,...C!==void 0?{memoryContextSessions:C}:{},..._!==void 0?{memoryContextTokens:_}:{},...P!==void 0?{memoryContextChars:P}:{},mcpEnabled:Ke,safeMode:i,apiKeySource:k,...S?{baseURL:S}:{},uiColor:O,...re?{agent:re}:{},delegation:{enabled:Ee,...Ve?{mode:Ve}:{},...nt?{team:nt}:{},...ze?{roles:ze}:{},...Qr!==void 0?{concurrency:Qr}:{},...De!==void 0?{maxTotalTokens:De}:{},...yt!==void 0?{timeoutMs:yt}:{},...typeof t.delegateRemote=="string"?{remote:t.delegateRemote}:{}},goal:{enabled:ti.length>0,verifier:Jf,...vc!==void 0?{maxTurns:vc}:{},...bl!==void 0?{maxTokens:bl}:{}}};if(t.bg&&!process.env.XENO_BACKGROUND_RUN_ID){let se=await J0e({prompt:r,cwd:process.cwd(),model:h,effort:w,...re?{agent:re}:{},permissionMode:ki,executionSecurity:Rr.selection,cliVersion:Pe,resourceSurface:"background-run",resourcePriority:"background",...typeof t.title=="string"&&t.title.trim().length>0?{title:t.title.trim()}:{},pinned:!!t.pin,...Hr?{worktree:Hr}:{},configSnapshot:qe,rawArgv:process.argv.slice(2)});process.stdout.write(rke(se.record,D));return}let{AgentInterruptedError:jt,AuditLogger:_p,calculateReportedModelCost:Pp,createDefaultToolRegistry:Nv,createAuditBackedPermissionEngine:Ie,createDelegatedXenoAgent:gu,delegatedBranchOutputTokens:hr,createXenoAgent:pm,matchesMcpRegistryEntryPolicy:XE,normalizeSubagentBranchPolicy:JE,resolveSubagentRemoteMcpAccess:wu,resetAllPersistentShellSessions:yu,registerPlanModeTools:Rg,runDelegatedXenoTurn:$p,syncMcpToolsToRegistry:Kf}=await Promise.resolve().then(()=>(Er(),xrr)),Xe=process.cwd(),Di=process.env.XENO_BACKGROUND_RUN_ID?.trim()||void 0,uo=Di?new vt:void 0,Yf=null;try{Yf=Di?_z():null}catch(se){throw process.stderr.write(`WORKER_PERMIT_CLAIM_REFUSED ${JSON.stringify(Rz(se))}
17422
17422
  `),se}if(Di&&uo){let se=Yf?.permit;uo.markStarted(Di,{pid:process.pid,cliVersion:Pe,model:h,effort:w,...se?{workerIdentity:se.owner,workerLease:{permitId:se.permitId,fencingToken:se.fencingToken,attemptId:se.attemptId,idempotencyKey:se.idempotencyKey,expiresAt:se.expiresAt}}:{}});let Ge=uo.get(Di);if(Ge&&iz(Ge)){uo.markCancelled(Di,"Workflow cancellation was requested before worker execution."),uo.appendEvent(Di,"run_worker_cancelled_before_execution",{pid:process.pid,workflow_run_id:Ge.rootRunId}),Yf?.settle("workflow_cancellation_requested");return}uo.appendEvent(Di,"run_worker_started",{pid:process.pid,cwd:Xe,model:h,effort:w})}let Bv=new Date,_g=Bv.toISOString().replace(/[^0-9]/g,"").slice(0,14),Rd=vte(),Zf=o_e(Ix(Xe),`run-${_g}-${process.pid}-${Rd}.jsonl`),rr=Di??`run-${Rd}`,zn=Vw({cwd:Xe,sessionId:rr,runId:rr,rootRunId:rr,permissionMode:ki,model:h,effort:w,...re?.name?{agentName:re.name}:{},...re?.color?{agentColor:re.color}:{},...U.profile?.capabilities.hooks.length?{requiredHookNames:U.profile.capabilities.hooks}:{},disabled:i}),Rt,Jt,Au,Op;try{if(await Gw(zn),r=await lF(zn,r,{command:"run",background:!!Di,structured:D}),ti){Rt=await new Yn().set(ti,{runId:rr,...vc!==void 0?{maxTurns:vc}:{},...bl!==void 0?{maxTokens:bl}:{},verifierModel:h});let se=Zi();Jt=await se.startLoop({sessionId:rr,goalId:Rt.goalId,kind:"goal-continuation",activity:"Starting verified goal execution"}),Au=new n_({store:se,sessionId:rr,ownerId:`run:${process.pid}`}),await Au.start(),Di&&uo&&uo.appendEvent(Di,"goal_set",{goal_id:Rt.goalId,condition:Rt.condition}),r=[r,"","Goal mode is active for this run.",`Goal id: ${Rt.goalId}`,`Goal condition: ${Rt.condition}`,"Work toward this condition and report evidence. Do not claim the goal is complete unless the condition is satisfied."].join(`
17423
17423
  `)}}catch(se){Op=se instanceof Error?se:new Error(String(se))}let Pg=zan(process.env.XENO_REQUIRED_OUTPUT_PATHS_JSON,Xe),$g=Dln(r,Xe),Gy=Bv,Ga=S,po=new _p({filePath:Zf,sessionId:rr,runId:rr,agentId:"agent-main",workspace:Xe,model:h,provider:Ga});await po.append({trace_id:`agent-profile-${U.profile.fingerprint.slice(0,16)}`,event_type:"agent_profile_activated",actor:"system",risk_level:"none",status:"ok",metadata:{surface:"run",profile_id:U.profile.profile.id,profile_version:U.profile.profile.version,profile_fingerprint:U.profile.fingerprint,boundary_sources:U.profile.boundarySources,permission_profile:U.profile.capabilities.permissionProfile,memory_scope:U.profile.memory.scope,soul_mode:U.profile.memory.soul,isolation:U.profile.execution.isolation,default_mode:U.profile.execution.defaultMode}});let eh=async(se,Ge)=>{await po.append({trace_id:`skill-${se.skillHash.slice(0,16)}-${se.argumentsHash?.slice(0,8)??"noargs"}`,event_type:se.type.replace(/-/g,"_"),actor:se.invocation==="model"?"assistant":"user",risk_level:"low",decision:se.type==="skill-denied"?"deny":"allow",status:se.type==="skill-invoked"?"ok":"error",...se.reason?{reason:se.reason}:{},metadata:{surface:Ge,skill_key:se.skillKey,skill_hash:se.skillHash,invocation:se.invocation,arguments_hash:se.argumentsHash,recorded_at:se.recordedAt}})},fm=RCr({taskPrompt:r,requiredOutputPaths:Pg,cwd:Xe,interactiveTurnGovernance:gvt(t)}),_d,Kc=null;try{Kc=await ab.create({profile:U.profile??null,cwd:Xe}),await Kc?.prepare(r)}catch(se){Kc?.clear(),Kc=null,D||process.stderr.write(`[agent-soul] Recall skipped: ${se instanceof Error?se.message:String(se)}
17424
17424
  `)}let bu=(se="agent-main",Ge,Ue,lt)=>se==="agent-main"&&!Ge?zn:Vw({cwd:Xe,sessionId:rr,runId:rr,rootRunId:rr,agentId:se,...Ue?.name?{agentName:Ue.name}:{},...Ue?.color?{agentColor:Ue.color}:{},...lt!==void 0?{requiredHookNames:lt}:Ue?.name&&Wi(Ue.name,Xe).compiled.capabilities.hooks.length?{requiredHookNames:Wi(Ue.name,Xe).compiled.capabilities.hooks}:{},...Ge?{parentAgentId:Ge}:{},permissionMode:ki,model:h,effort:w,disabled:i}),Gl=(se="agent-main",Ge,Ue,lt)=>WI(bu(se,Ge,Ue,lt)),Dv=Gl(),Vl=oc(ne),Xr=Kd({profile:()=>U.profile??null,currentUserPrompt:()=>r}),Og=i?null:Xu({cwd:Xe,policy:U.profile.capabilities.skills,outerExternalActions:U.profile.capabilities.externalActions.default,classifyExternalActions:gd,isExternalActionApproved:se=>wd(se,r),onAudit:se=>eh(se,"run")}),Vy=kJ(rr),qT=wUr(),_e=t.continue===!0?!0:t.resume===void 0?void 0:t.resume===!0?!0:String(t.resume);if(_e!==void 0&&(Ee||t.remote||t.bg))throw new Error("--resume and --continue continue a local run; they cannot be combined with --delegate, --remote or --bg.");let Mp=_e!==void 0?await Z0({cwd:Xe,model:h,resume:_e}):await BR(await Z0({cwd:Xe,model:h}),{cwd:Xe,model:h,executionMode:$}),pa=Mp.sessionManager;if(pa&&_e!==void 0&&$vt(pa.meta.workingDirectory)!==$vt(Xe))throw new Error(`Session ${pa.meta.id} belongs to ${pa.meta.workingDirectory}; run --resume from that folder.`);pa&&(t.as!==void 0||s)&&await pa.updateMeta({platformAgent:s?{issuer:QK(),agentId:s.id}:void 0});let zy=_e!==void 0?(await t_(Mp.restoredMessages??[],pa??void 0)).messages:[],Ei=t.outputSchema?Jue({schema:Xan(String(t.outputSchema),Xe)}):null,th={toolMiddleware:[...fm.toolMiddleware,...Og?[Og.middleware]:[],Dv,Xr,...Vl?[Vl]:[]],promptSections:[...s?[{name:"xeno-agent-identity",order:-50,provide:()=>NIe(s)}]:[],...Ei?[Ei.promptSection]:[],...ce,...Kc?[Kc.promptSection]:[],...fm.promptSections,eke(()=>y),z_(()=>ki==="plan"),pJ(),hC(),...qT?[qT]:[],...Vy?[Vy]:[]],completionGuards:[...Ei?[Ei.completionGuard]:[],...fm.completionGuards]},Lv=(se,Ge)=>{let Ue=fm.getExecutionGovernanceSummary()?.completionDecision??null;return Ge?.reason==="completion_guard_stalled"||Ge?.reason==="completion_guard_stop"?{status:"incomplete",reason:Ge.reason,finalStateVerified:!1,message:Ge.message??"A completion check refused the finish."}:/\[Max iterations reached\]/.test(se)?{status:"incomplete",reason:"max_iterations",finalStateVerified:Ue?.finalStateVerified??!1,message:Ue&&Ue.action!=="complete"?`Agent stopped after reaching the max iterations limit. ${Ue.message}`:"Agent stopped after reaching the max iterations limit without an explicit completion signal."}:Ue?{status:Ue.action==="complete"?"completed":"incomplete",reason:Ue.reason,finalStateVerified:Ue.finalStateVerified,message:Ue.message}:{status:"completed",finalStateVerified:!1}},Fv=n3o(),Si=(se,Ge={})=>{Di&&uo&&uo.appendEvent(Di,se,Ge),j&&process.stdout.write(JSON.stringify({type:se,...Ge})+`
17425
17425
  `)},XM=!process.stdin.isTTY||process.env.XENO_FORCE_AUTO_DENY_PROMPTS==="1",KE=XM?async()=>"deny":void 0;XM&&ki!=="bypassPermissions"&&!D&&process.stderr.write(`[permissions] Non-interactive mode: prompt-required actions are auto-denied.
17426
- `);let Yc=Ie({mode:ki,cwd:Xe,...he.length>0?{rules:he}:{},...Se?{permissionProfile:Se}:{},promptFn:KE,auditLogger:po,fallbackTraceId:`run-${_g}`,decisionHook:async se=>{await aF(zn,se)}});X_(Yc);let Pd=Ige(Yc),QT=EJ({cwd:()=>Xe,profile:()=>U.profile,runId:rr,agentId:"agent-main",sessionId:rr,surface:"cli",securityPolicy:()=>Rr.policy,securityStatus:Rr.status,safeMode:i,onAudit:dS(po)}),zl="",hm=new Db,Mg=async(se,Ge)=>{if(Rt?.maxTokens===void 0)return;let Ue=await hm.prepare(Rt,{cwd:Xe,model:Ge,maxOutputTokens:Math.max(512,Math.min(x,4096)),agent:se});se.configureModelExecution({provider:Ue.provider})},xi=V0();xi.onSettled(se=>{Si("child_agent_settled",{child_id:se.id,kind:se.kind,...se.label?{label:se.label}:{},outcome:se.outcome,duration_ms:se.durationMs,...se.tokenUsage?{token_usage:se.tokenUsage}:{},...se.reason?{reason:se.reason}:{}})});let Ic=r,Uv=(se=0,Ge="agent-main",Ue=()=>sb(U.profile,Xe),lt=()=>Og?.active()??[])=>async({agent:Kt,prompt:it,signal:qt})=>{let At=Ue();if(se>=2)throw new Error("Nested dispatch_agent depth limit reached.");if(Kt?.trim()){if(i)throw new Error("Custom agents are disabled in safe mode.");let fo=Z_(Kt,Xe,At),Br=fo.definition,qv=xf(rr,"dispatch",Br.name),vu=ax(fo.compiled,qv),Bp=await ab.create({profile:fo.compiled,cwd:Xe,...vu?{sessionDir:vu.sessionDir}:{}}).catch(()=>null);if(Bp)try{await Bp.prepare(it)}catch{Bp.clear()}let Qv=Nv({cwd:Xe,sandbox:Rr.policy,ownerSessionId:qv,dispatchAgent:Uv(se+1,Br.name,()=>sb(fo.compiled,Xe,Ue()),()=>Jy.active()),childController:xi}),Jy=Xu({cwd:Xe,policy:fo.compiled.capabilities.skills,outerExternalActions:fo.compiled.capabilities.externalActions.default,classifyExternalActions:gd,isExternalActionApproved:Fg=>wd(Fg,Ic),onAudit:Fg=>eh(Fg,"branch"),inheritedActivations:lt()});Qv.register(Jy.tool),Ym(Qv,Xe,{runId:rr,agentId:Br.name}),ro(Qv,fo.compiled.capabilities.tools),ro(Qv,ie);let Yq=oc(fo.compiled.capabilities.tools),GT=Kd({profile:()=>fo.compiled,currentUserPrompt:()=>Ic}),a_e=Gl(Br.name,Ge,Mvt(Br),fo.compiled.capabilities.hooks),KM=zw({cwd:Xe,registry:Qv,mcpManager:lr,profile:fo.compiled,beforeStep:()=>mm(),getParentProfile:Ue,hooks:bu(Br.name,Ge,Mvt(Br),fo.compiled.capabilities.hooks)}),Zq=Dln(it,Xe),{agent:YE}=await pm({cwd:Xe,sandbox:Rr.policy,apiKey:A,baseURL:Ga,model:n_e(Br,h),...Zq.length?{identity:{targetPaths:Zq}}:{},...m?{fallbackModels:m}:{},effort:w,maxTokens:Math.max(512,Math.min(x,4096)),maxIterations:Math.max(10,Math.min(E,100)),...Br.budget?.maxTokens!==void 0?{turnTokenBudget:Br.budget.maxTokens}:{},requesterLabel:`Agent:${Br.name}`,role:fo.compiled.memory.role,executionMode:$,permissionEngine:Yc,memory:vu,session:{auditLogger:po},promptSections:[fo.compiled.promptSection,...Bp?[Bp.promptSection]:[],...Mc(Xe,fo.compiled.capabilities.skills).promptSections,...fm.promptSections,hC(),...Vy?[Vy]:[]],toolMiddleware:[Jy.middleware,KM.middleware,...fm.toolMiddleware,a_e,GT,...Yq?[Yq]:[]],toolRegistry:Qv,runAuthority:KM.runAuthority,continuationCheckpoints:!1});if(qt?.aborted)throw Bp?.clear(),new jt;let e8="",YM="success";try{await Mg(YE,n_e(Br,h));let Fg=await jA({agent:YE,prompt:it,signal:qt,ownerSessionId:qv,lifecycle:KM,run:()=>ZS(YE,Br.budget?.deadlineMs,()=>YE.run(it))});return e8=Fg.output,fI(Fg.termination)||(YM="partial"),Fg}catch(Fg){throw YM=qt?.aborted?"partial":"failure",Fg}finally{if(Bp)try{await Bp.complete({task:it,transcript:e8||(YM==="partial"?"The delegated run was interrupted before a final answer.":"The delegated run failed before a final answer."),outcome:YM})}catch{}finally{Bp.clear()}}}zl||(zl=(await pm({cwd:Xe,sandbox:Rr.policy,apiKey:A,baseURL:Ga,model:h,...$g.length?{identity:{targetPaths:$g}}:{},...m?{fallbackModels:m}:{},effort:w,maxTokens:x,maxIterations:E,requesterLabel:"Agent",...we?{role:we}:{},executionMode:$,permissionEngine:Yc,memory:Te,session:{auditLogger:po},...th})).systemPrompt);let cr=xf(rr,"dispatch"),Ns=i?null:Xu({cwd:Xe,policy:At.capabilities.skills,outerExternalActions:At.capabilities.externalActions.default,classifyExternalActions:gd,isExternalActionApproved:fo=>wd(fo,Ic),onAudit:fo=>eh(fo,"branch"),inheritedActivations:lt()}),Qt=Nv({cwd:Xe,sandbox:Rr.policy,ownerSessionId:cr});Ns&&Qt.register(Ns.tool),ro(Qt,At.capabilities.tools),ro(Qt,ie);let Ur=oc(At.capabilities.tools),xn=Kd({profile:()=>At,currentUserPrompt:()=>Ic}),Ti=zw({cwd:Xe,registry:Qt,mcpManager:lr,profile:At,beforeStep:()=>mm(),getParentProfile:Ue,hooks:bu("explorer",Ge,void 0,At.capabilities.hooks)}),ga=(await gu({cwd:Xe,sandbox:Rr.policy,apiKey:A,baseURL:Ga,model:h,...m?{fallbackModels:m}:{},effort:w,maxTokens:Math.max(512,Math.min(x,4096)),maxIterations:Math.max(10,Math.min(E,100)),parentSystemPrompt:await Xw({cwd:Xe,model:h,executionMode:$,profile:At,ownerSessionId:cr}),parentExecutionMode:$,subagentRole:"explorer",permissionEngine:Yc,ownerSessionId:cr,childController:xi,toolRegistry:Qt,runAuthority:Ti.runAuthority,toolMiddleware:[Ti.middleware,...Ns?[Ns.middleware]:[],Gl("explorer",Ge,void 0,At.capabilities.hooks),xn,...Ur?[Ur]:[]]})).agent;return await Mg(ga,h),jA({agent:ga,prompt:it,signal:qt,ownerSessionId:cr,lifecycle:Ti})},HT=Uv(),lr,mm=async()=>{lr&&(await oX(lr,{cwd:Xe,allowedServers:U.profile.capabilities.mcpServers}),await aP(lr,{cwd:Xe,filter:se=>U.profile.capabilities.mcpServers===void 0||U.profile.capabilities.mcpServers.includes(se.name)}))},WT=!1,Xy,JM=await eK(QT,new yw),rh=()=>{let se=Nv({cwd:Xe,dispatchAgent:HT,childController:xi,sandbox:Rr.policy,ownerSessionId:rr,...Se?{permissionProfile:Se}:{}});if(JM>0&&QT.register(se),Og&&se.register(Og.tool),yUr(se),Ym(se,Xe,{runId:rr,agentId:"agent-main"}),fJ(se,{cwd:Xe,model:h,getOrchestrationMode:()=>y??"workflow",cliVersion:Pe,getParentOrigin:()=>Xy}),D$(se,{cwd:Xe,model:h,...w?{effort:w}:{},permissionMode:ki,cliVersion:Pe,parentSessionId:rr,getParentOrigin:()=>Xy,getParentProfile:()=>U.profile,getExecutionSecurity:()=>Rr.selection,getParentSkills:()=>Og?.active()??[],safeMode:i,onSessionStarted:()=>{WT=!0}}),lr&&Kf(lr,se),Rg(se,Pd.options),ro(se,ne),o&&s){for(let Ge of MIe(o,{runId:u}))se.register(Ge);for(let Ge of d)se.has(Ge.definition.name)||se.register(Ge);ro(se,f?.agentTools)}if(ro(se,ie),s){for(let Ge of DCr)se.has(Ge)&&se.activateMatchingDefinitions(Ge,1);for(let Ge of d)se.has(Ge.definition.name)&&se.activateMatchingDefinitions(Ge.definition.name,1)}return se},jv=(se,Ge)=>{let Ue=xf(rr,"delegate",se),lt=Nv({cwd:Xe,sandbox:Rr.policy,ownerSessionId:Ue});if(Ym(lt,Xe,{runId:rr,agentId:se}),lr){let Kt=wu(Ge,se);Kf(lr,lt,[],it=>XE(it,Kt)&&(U.profile.capabilities.mcpServers===void 0||U.profile.capabilities.mcpServers.includes(it.server)))}return{...sP({registry:lt,cwd:Xe,safeMode:i,profile:U.profile,currentUserPrompt:()=>Ic,hookMiddleware:Gl(`branch-${se}`,"agent-main",void 0,U.profile.capabilities.hooks),onSkillAudit:Kt=>eh(Kt,"branch"),inheritedActivations:Og?.active()}),ownerSessionId:Ue}},Ng=rh(),Bg=i?void 0:await nF({toolRegistry:Ng}),Qe=i?void 0:Mc(Xe,U.profile?.capabilities.skills),nr=LP(zt.outputStyle,Bg?.outputStyles??[]);if(th.promptSections.push(...nr?[nr]:[],...Bg?.promptSections??[],...Qe?.promptSections??[]),Si("run_start",{cwd:Xe,model:h,fallback_models:m??[],effort:w,prompt:r,safe_mode:i,...re?{agent:re}:{},execution_mode:$,delegation_enabled:Ee,mcp_enabled:Ke,plugin_count:Bg?.activePlugins.length??0,plugin_tool_count:Bg?.registeredTools.length??0,skill_count:Qe?.skills.length??0,enabled_skill_count:Qe?.enabledSkills.length??0}),Ke){lr=sk({permissionProfile:Se??void 0});let se=await oX(lr,{cwd:Xe,allowedServers:U.profile.capabilities.mcpServers}),Ge=await aP(lr,{cwd:Xe,filter:lt=>U.profile.capabilities.mcpServers===void 0||U.profile.capabilities.mcpServers.includes(lt.name)}),Ue=dF(se,Ge);if(Kf(lr,Ng),ro(Ng,ne),s&&ro(Ng,f?.agentTools),ro(Ng,ie),Si("mcp_connect",{connected:Ue.connected.length,skipped:Ue.skipped.length,denied:Ue.denied.length,errors:Ue.errors.length}),!D){let lt=[];Ue.connected.length>0&&lt.push(`connected ${Ue.connected.length}`),Ue.skipped.length>0&&lt.push(`skipped ${Ue.skipped.length}`),Ue.denied.length>0&&lt.push(`denied ${Ue.denied.length}`),Ue.errors.length>0&&lt.push(`errors ${Ue.errors.length}`),lt.length>0&&process.stderr.write(`[mcp] ${lt.join(", ")}
17426
+ `);let Yc=Ie({mode:ki,cwd:Xe,...he.length>0?{rules:he}:{},...Se?{permissionProfile:Se}:{},promptFn:KE,auditLogger:po,fallbackTraceId:`run-${_g}`,decisionHook:async se=>{await aF(zn,se)}});X_(Yc);let Pd=Ige(Yc),QT=EJ({cwd:()=>Xe,profile:()=>U.profile,runId:rr,agentId:"agent-main",sessionId:rr,surface:"cli",securityPolicy:()=>Rr.policy,securityStatus:Rr.status,safeMode:i,onAudit:dS(po)}),zl="",hm=new Db,Mg=async(se,Ge)=>{if(Rt?.maxTokens===void 0)return;let Ue=await hm.prepare(Rt,{cwd:Xe,model:Ge,maxOutputTokens:Math.max(512,Math.min(x,4096)),agent:se});se.configureModelExecution({provider:Ue.provider})},xi=V0();xi.onSettled(se=>{Si("child_agent_settled",{child_id:se.id,kind:se.kind,...se.label?{label:se.label}:{},outcome:se.outcome,duration_ms:se.durationMs,...se.tokenUsage?{token_usage:se.tokenUsage}:{},...se.reason?{reason:se.reason}:{}})});let Ic=r,Uv=(se=0,Ge="agent-main",Ue=()=>sb(U.profile,Xe),lt=()=>Og?.active()??[])=>async({agent:Kt,prompt:it,signal:qt})=>{let At=Ue();if(se>=2)throw new Error("Nested dispatch_agent depth limit reached.");if(Kt?.trim()){if(i)throw new Error("Custom agents are disabled in safe mode.");let fo=Z_(Kt,Xe,At),Br=fo.definition,qv=xf(rr,"dispatch",Br.name),vu=ax(fo.compiled,qv),Bp=await ab.create({profile:fo.compiled,cwd:Xe,...vu?{sessionDir:vu.sessionDir}:{}}).catch(()=>null);if(Bp)try{await Bp.prepare(it)}catch{Bp.clear()}let Qv=Nv({cwd:Xe,sandbox:Rr.policy,ownerSessionId:qv,dispatchAgent:Uv(se+1,Br.name,()=>sb(fo.compiled,Xe,Ue()),()=>Jy.active()),childController:xi}),Jy=Xu({cwd:Xe,policy:fo.compiled.capabilities.skills,outerExternalActions:fo.compiled.capabilities.externalActions.default,classifyExternalActions:gd,isExternalActionApproved:Fg=>wd(Fg,Ic),onAudit:Fg=>eh(Fg,"branch"),inheritedActivations:lt()});Qv.register(Jy.tool),Ym(Qv,Xe,{runId:rr,agentId:Br.name}),ro(Qv,fo.compiled.capabilities.tools),ro(Qv,ie);let Yq=oc(fo.compiled.capabilities.tools),GT=Kd({profile:()=>fo.compiled,currentUserPrompt:()=>Ic}),a_e=Gl(Br.name,Ge,Mvt(Br),fo.compiled.capabilities.hooks),KM=zw({cwd:Xe,registry:Qv,mcpManager:lr,profile:fo.compiled,beforeStep:()=>mm(),getParentProfile:Ue,hooks:bu(Br.name,Ge,Mvt(Br),fo.compiled.capabilities.hooks)}),Zq=Dln(it,Xe),{agent:YE}=await pm({cwd:Xe,sandbox:Rr.policy,apiKey:A,baseURL:Ga,model:n_e(Br,h),...Zq.length?{identity:{targetPaths:Zq}}:{},...m?{fallbackModels:m}:{},effort:w,maxTokens:Math.max(512,Math.min(x,4096)),maxIterations:Math.max(10,Math.min(E,100)),...Br.budget?.maxTokens!==void 0?{turnTokenBudget:Br.budget.maxTokens}:{},requesterLabel:`Agent:${Br.name}`,role:fo.compiled.memory.role,executionMode:$,permissionEngine:Yc,memory:vu,session:{auditLogger:po},promptSections:[fo.compiled.promptSection,...Bp?[Bp.promptSection]:[],...Mc(Xe,fo.compiled.capabilities.skills).promptSections,...fm.promptSections,hC(),...Vy?[Vy]:[]],toolMiddleware:[Jy.middleware,KM.middleware,...fm.toolMiddleware,a_e,GT,...Yq?[Yq]:[]],toolRegistry:Qv,runAuthority:KM.runAuthority,continuationCheckpoints:!1});if(qt?.aborted)throw Bp?.clear(),new jt;let e8="",YM="success";try{await Mg(YE,n_e(Br,h));let Fg=await jA({agent:YE,prompt:it,signal:qt,ownerSessionId:qv,lifecycle:KM,run:()=>ZS(YE,Br.budget?.deadlineMs,()=>YE.run(it))});return e8=Fg.output,fI(Fg.termination)||(YM="partial"),Fg}catch(Fg){throw YM=qt?.aborted?"partial":"failure",Fg}finally{if(Bp)try{await Bp.complete({task:it,transcript:e8||(YM==="partial"?"The delegated run was interrupted before a final answer.":"The delegated run failed before a final answer."),outcome:YM})}catch{}finally{Bp.clear()}}}zl||(zl=(await pm({cwd:Xe,sandbox:Rr.policy,apiKey:A,baseURL:Ga,model:h,...$g.length?{identity:{targetPaths:$g}}:{},...m?{fallbackModels:m}:{},effort:w,maxTokens:x,maxIterations:E,requesterLabel:"Agent",...we?{role:we}:{},executionMode:$,permissionEngine:Yc,memory:Te,session:{auditLogger:po},...th})).systemPrompt);let cr=xf(rr,"dispatch"),Ns=i?null:Xu({cwd:Xe,policy:At.capabilities.skills,outerExternalActions:At.capabilities.externalActions.default,classifyExternalActions:gd,isExternalActionApproved:fo=>wd(fo,Ic),onAudit:fo=>eh(fo,"branch"),inheritedActivations:lt()}),Qt=Nv({cwd:Xe,sandbox:Rr.policy,ownerSessionId:cr});Ns&&Qt.register(Ns.tool),ro(Qt,At.capabilities.tools),ro(Qt,ie);let Ur=oc(At.capabilities.tools),xn=Kd({profile:()=>At,currentUserPrompt:()=>Ic}),Ti=zw({cwd:Xe,registry:Qt,mcpManager:lr,profile:At,beforeStep:()=>mm(),getParentProfile:Ue,hooks:bu("explorer",Ge,void 0,At.capabilities.hooks)}),ga=(await gu({cwd:Xe,sandbox:Rr.policy,apiKey:A,baseURL:Ga,model:h,...m?{fallbackModels:m}:{},effort:w,maxTokens:Math.max(512,Math.min(x,4096)),maxIterations:Math.max(10,Math.min(E,100)),parentSystemPrompt:await Xw({cwd:Xe,model:h,executionMode:$,profile:At,ownerSessionId:cr}),parentExecutionMode:$,subagentRole:"explorer",permissionEngine:Yc,ownerSessionId:cr,childController:xi,toolRegistry:Qt,runAuthority:Ti.runAuthority,toolMiddleware:[Ti.middleware,...Ns?[Ns.middleware]:[],Gl("explorer",Ge,void 0,At.capabilities.hooks),xn,...Ur?[Ur]:[]]})).agent;return await Mg(ga,h),jA({agent:ga,prompt:it,signal:qt,ownerSessionId:cr,lifecycle:Ti})},HT=Uv(),lr,mm=async()=>{lr&&(await oX(lr,{cwd:Xe,allowedServers:U.profile.capabilities.mcpServers}),await aP(lr,{cwd:Xe,filter:se=>U.profile.capabilities.mcpServers===void 0||U.profile.capabilities.mcpServers.includes(se.name)}))},WT=!1,Xy,JM=await eK(QT,new yw),rh=()=>{let se=Nv({cwd:Xe,dispatchAgent:HT,childController:xi,sandbox:Rr.policy,ownerSessionId:rr,...Se?{permissionProfile:Se}:{}});if(JM>0&&QT.register(se),Og&&se.register(Og.tool),yUr(se),Ym(se,Xe,{runId:rr,agentId:"agent-main"}),fJ(se,{cwd:Xe,model:h,getOrchestrationMode:()=>y??"workflow",cliVersion:Pe,getParentOrigin:()=>Xy}),D$(se,{cwd:Xe,model:h,...w?{effort:w}:{},permissionMode:ki,cliVersion:Pe,parentSessionId:rr,getParentOrigin:()=>Xy,getParentProfile:()=>U.profile,getExecutionSecurity:()=>Rr.selection,getParentSkills:()=>Og?.active()??[],safeMode:i,onSessionStarted:()=>{WT=!0}}),lr&&Kf(lr,se),Rg(se,Pd.options),ro(se,ne),o&&s){for(let Ge of MIe(o,{runId:u}))se.register(Ge);for(let Ge of d)se.has(Ge.definition.name)||se.register(Ge);ro(se,f?.agentTools)}if(ro(se,ie),s){for(let Ge of DCr)se.has(Ge)&&se.activateMatchingDefinitions(Ge,1);for(let Ge of d)se.has(Ge.definition.name)&&se.activateMatchingDefinitions(Ge.definition.name,1)}return se},jv=(se,Ge)=>{let Ue=xf(rr,"delegate",se),lt=Nv({cwd:Xe,sandbox:Rr.policy,ownerSessionId:Ue});if(Ym(lt,Xe,{runId:rr,agentId:se}),lr){let Kt=wu(Ge,se);Kf(lr,lt,[],it=>XE(it,Kt)&&(U.profile.capabilities.mcpServers===void 0||U.profile.capabilities.mcpServers.includes(it.server)))}return{...sP({registry:lt,cwd:Xe,safeMode:i,profile:U.profile,currentUserPrompt:()=>Ic,hookMiddleware:Gl(`branch-${se}`,"agent-main",void 0,U.profile.capabilities.hooks),onSkillAudit:Kt=>eh(Kt,"branch"),inheritedActivations:Og?.active()}),ownerSessionId:Ue}},Ng=rh(),Bg=i?void 0:await nF({toolRegistry:Ng}),Qe=i?void 0:Mc(Xe,U.profile?.capabilities.skills),nr=LP(Gt.outputStyle,Bg?.outputStyles??[]);if(th.promptSections.push(...nr?[nr]:[],...Bg?.promptSections??[],...Qe?.promptSections??[]),Si("run_start",{cwd:Xe,model:h,fallback_models:m??[],effort:w,prompt:r,safe_mode:i,...re?{agent:re}:{},execution_mode:$,delegation_enabled:Ee,mcp_enabled:Ke,plugin_count:Bg?.activePlugins.length??0,plugin_tool_count:Bg?.registeredTools.length??0,skill_count:Qe?.skills.length??0,enabled_skill_count:Qe?.enabledSkills.length??0}),Ke){lr=sk({permissionProfile:Se??void 0});let se=await oX(lr,{cwd:Xe,allowedServers:U.profile.capabilities.mcpServers}),Ge=await aP(lr,{cwd:Xe,filter:lt=>U.profile.capabilities.mcpServers===void 0||U.profile.capabilities.mcpServers.includes(lt.name)}),Ue=dF(se,Ge);if(Kf(lr,Ng),ro(Ng,ne),s&&ro(Ng,f?.agentTools),ro(Ng,ie),Si("mcp_connect",{connected:Ue.connected.length,skipped:Ue.skipped.length,denied:Ue.denied.length,errors:Ue.errors.length}),!D){let lt=[];Ue.connected.length>0&&lt.push(`connected ${Ue.connected.length}`),Ue.skipped.length>0&&lt.push(`skipped ${Ue.skipped.length}`),Ue.denied.length>0&&lt.push(`denied ${Ue.denied.length}`),Ue.errors.length>0&&lt.push(`errors ${Ue.errors.length}`),lt.length>0&&process.stderr.write(`[mcp] ${lt.join(", ")}
17427
17427
  `)}}let fa="",Fr,Q=!1,le=!1,pe=!1,me,He=null,It=null,ut={input:0,output:0,total:0},Jr,ri,Li,jn,un=`run-${_g}-${vte().slice(0,8)}`,Ci=new ms,Fi=new tt,ni=t_e("XENO_BACKGROUND_AGENT_NOTIFICATION_WAIT_MS",3e5,0),yn=Math.max(1,Math.min(16,E)),ha=async se=>{if(!WT||!yF())return{timedOut:!1,turnLimitReached:!1,activeChildren:0};let Ge=Date.now(),Ue=0;for(;;){let lt=Ci.listPending(rr);if(lt.length>0){if(Ue>=yn)return{timedOut:!1,turnLimitReached:!0,activeChildren:Fi.list({all:!0}).filter(At=>At.parentSessionId===rr).filter(At=>!["completed","failed","stopped"].includes(At.status)).length};let it=lt.slice(0,Y4o);for(let qt of it){Ci.markDeliveryAttempt(qt.notificationId);let At=AX(qt);Si("agent_notification",{notification_id:qt.notificationId,parent_session_id:qt.parentSessionId,child_session_id:qt.childSessionId,status:qt.status,name:qt.name,summary:qt.summary,remaining_queued:Math.max(0,lt.length-it.length)}),D||process.stderr.write(`${At}
17428
17428
  `)}fa=await se.run(bX(it),{messageId:Iwe(it)}),It=se.lastTraceId,ut=se.tokenUsage,Li=se.messages.length,ri=fm.getExecutionGovernanceSummary()??void 0;for(let qt of it)Ci.markDelivered(qt.notificationId);Ue+=1;continue}let Kt=Fi.list({all:!0}).filter(it=>it.parentSessionId===rr).filter(it=>!["completed","failed","stopped"].includes(it.status));if(Kt.length===0)return{timedOut:!1,turnLimitReached:!1,activeChildren:0};if(Date.now()-Ge>=ni)return{timedOut:!0,turnLimitReached:!1,activeChildren:Kt.length};await Pvt(200)}},es=JE({mode:Ve,teamPreset:nt,roles:ze,rolePrecedence:ua,remoteMcpByRole:Ms,...Qr!==void 0?{maxConcurrentBranches:Qr}:{}}),de=Rt?new Yn:void 0,ge=Rt?Zi():void 0,Ne=Rt?.maxTokens!==void 0?new Db:void 0,at=new Oz,vr=null,Kr=async(se,Ge,Ue)=>{if(!(!Jt||!ge)){for(;;){let lt=await ge.getLoop(rr,Jt.id);if(!lt)throw new Error(`Goal continuation loop ${Jt.id} disappeared`);if(Jt=lt,lt.status==="running")break;if(lt.status==="paused"||lt.status==="waiting"){await Pvt(250);continue}throw new Error(`Goal continuation loop ${lt.id} is ${lt.status}`)}if(await Au?.assertOwned(),Rt?.maxTokens!==void 0){if(!de||!Ne)throw new Error("Bounded goal quota runtime is unavailable.");if(!Ue)throw new Error("A bounded goal turn requires the agent that will run it.");let lt=await Ne.prepare(Rt,{cwd:Xe,model:h,maxOutputTokens:x,agent:Ue}),Kt=await de.admitTurn(rr,Ge,`goal-turn-${vte()}`,Rt,"local-sdk",await Au?.assertOwned(),lt);if(!Kt?.admitted)throw new Error("Bounded goal turn was already admitted; replay is not authorized.");return vr=Kt,Rt=Kt.goal,Jt=await ge.getLoop(rr,Jt.id)??Jt,lt}Jt=await ge.beginLoopIteration(rr,Jt.id,Jt.version,`Goal turn ${se}: ${Ge.replace(/\s+/g," ").trim().slice(0,512)}`)}},kc=async(se,Ge="ok")=>{if(!Rt||!de)return{shouldContinue:!1};await po.flush();let Ue=await xSr({goal:Rt,answer:fa,auditEvents:await po.read(),runStatus:Ge,...Fr?{error:Fr}:{}},{mode:Jf,model:h,...m?{fallbackModels:m}:{},effort:w,apiKey:A,baseURL:Ga}),lt=Rt.maxTurns!==void 0&&se>=Rt.maxTurns;if(Rt=await de.updateVerifierResult(Rt,Ue,{maxTurnsReached:lt,accountedTurns:Math.max(Rt.accountedTurns??0,se)})??Rt,Jt&&ge){let Kt=await ge.getLoop(rr,Jt.id);if(!Kt)throw new Error(`Goal continuation loop ${Jt.id} disappeared`);Jt=Kt,vr&&de?(await de.finishTurn(vr,"completed"),vr=null,Jt=await ge.getLoop(rr,Jt.id)??Jt):Jt=await ge.finishLoopIteration(rr,Jt.id,Jt.version,{status:"completed"}),Rt.status==="complete"&&Jt.status!=="completed"?Jt=await ge.setLoopStatus(rr,Jt.id,Jt.version,"completed","Goal verification passed"):(Rt.status==="blocked"||Rt.status==="failed")&&Jt.status!=="failed"&&(Jt=await ge.setLoopStatus(rr,Jt.id,Jt.version,"failed",`Goal became ${Rt.status}`))}return Si("goal_verifier",{goal_id:Rt.goalId,goal_status:Rt.status,turn:se,max_turns:Rt.maxTurns??null,result:Ue}),Rt.status==="complete"?{shouldContinue:!1}:Rt.status==="blocked"||Rt.status==="failed"?(pe=!0,Fr=`Goal ${Rt.status}: ${Ue.reason}`,{shouldContinue:!1}):{shouldContinue:!0,nextPrompt:vj(Rt,Ue,se+1)}};try{if(Op)throw Op;let se=!1,Ge=Qw(process.env[pf]),Ue=Ge==="off"||Ee?void 0:$Ie({cwd:Xe,allowedDirectories:Rr.selection.allowedDirectories,executionMode:String($),permissionMode:ki,securityLevel:Rr.selection.level,effectiveSecurityLevel:Rr.selection.effectiveLevel,trustMode:Rr.selection.trustMode,allowNetwork:Rr.selection.allowNetwork});if(Ue&&!Ue.carried){if(Ge==="required")throw new Error(`${pf}=require, but this run's authority cannot be carried to the Agent host. ${Ue.reason}`);D||process.stderr.write(`[attach] ${Ue.reason} Running the embedded loop instead.
17429
17429
  `)}if(Ge!=="off"&&!Ee&&Ue?.carried){let{attachAsHeadlessClient:lt,describeAttachRefusal:Kt}=await Promise.resolve().then(()=>(rx(),Zge)),{runTurnThroughHost:it}=await Promise.resolve().then(()=>(pKe(),Iur)),{cliSurfaceAccount:qt}=await Promise.resolve().then(()=>(Eit(),MCr)),At=await lt({clientVersion:Pe,account:qt(),startIfAbsent:!0,...process.env.XENO_AGENT_HOST_ROOT?{hostRootDirectory:process.env.XENO_AGENT_HOST_ROOT}:{}});if(At.attached){let cr=At.host,Ns=vte();try{if(await cr.client.connect(),Ue.authority.mode==="development"){let{grantTerminalFolders:xn}=await Promise.resolve().then(()=>(YL(),Wze)),Ti=await xn(cr.client,[Ue.authority.workspace.primaryDirectory,...Ue.authority.workspace.additionalDirectories??[]]);Ti.failed.length>0&&!D&&process.stderr.write(`[attach] The Agent host did not record access to ${Ti.failed.map(ga=>ga.path).join(", ")}: ${Ti.failed[0].error}
@@ -17453,7 +17453,7 @@ ${U$(Ge.agents)}`);Ge.kind==="agent"&&(s=await o.useAgent(Ge.agent.id))}let d=[]
17453
17453
  `),zi&&process.stderr.write(`[plan] ${zi.message}
17454
17454
  `),process.stderr.write(`[audit] ${Zf}
17455
17455
  `)),rs!==0&&(process.exitCode=rs),process.env.XENO_FORCE_EXIT_AFTER_RUN==="1"){let se=Cln(bt);!D&&(se.stopped.length>0||se.failed.length>0)&&process.stderr.write(`[run] background shutdown: stopped ${se.stopped.length}, preserved ${se.preserved.length}, failed ${se.failed.length}
17456
- `),await Promise.allSettled([Bln(process.stdout),Bln(process.stderr)]),process.exit(rs)}});Oe.addCommand(XFr());Oe.addCommand(GFr(Pe));Oe.addCommand(YFr(Pe));Oe.addCommand(OFr());Oe.addCommand(NFr());Oe.addCommand(BFr());Oe.addCommand(UFr());Oe.addCommand(jFr());Oe.addCommand(LFr());Oe.addCommand(DFr());Oe.addCommand(FFr());Oe.addCommand(oE);Oe.addCommand(iUr());Oe.command("init").description("Initialize project for AI-assisted development").option("-y, --yes","Use detected defaults without prompting").action(async e=>{await Bye({yes:!!e.yes,cwd:process.cwd()})});Oe.command("review").description("AI code review of recent changes").option("--staged","Review only staged changes").option("--range <range>","Review specific commit range (e.g. HEAD~5..HEAD)").option("--files <pattern>","Review specific files").option("--focus <area>","Focus on: security, performance").option("-m, --model <model>","AI model to use").option("-k, --api-key <key>","API key").option("--base-url <url>","API base URL").option("--max-tokens <n>","Max response tokens").option("--production","Run independent specialist reviewers plus verifier agents and persist a typed review artifact").option("--max-findings <n>","Maximum production findings before verification").option("--json","Emit production review as machine-readable JSON").action(async e=>{let t=e.model||zt.model||Gr,r=yS(e.apiKey,process.env.XENO_API_KEY,zt.apiKey,ld),n=bw({explicitBaseURL:e.baseUrl,configuredBaseURL:zt.baseURL}),i=e.maxTokens?parseInt(e.maxTokens,10):zt.maxTokens??Ite;await Ecr({staged:!!e.staged,range:e.range,files:e.files,focus:e.focus,model:t,apiKey:r,baseURL:n,maxTokens:i,production:!!e.production,json:!!e.json,maxFindings:e.maxFindings?parseInt(e.maxFindings,10):void 0,cwd:process.cwd()})});Oe.command("completions <shell>").description("Generate shell completion scripts (bash, zsh, fish)").action(e=>{switch(e.toLowerCase()){case"bash":process.stdout.write(_ln(Oe));break;case"zsh":process.stdout.write(Pln(Oe));break;case"fish":process.stdout.write($ln(Oe));break;default:console.error(`Unknown shell: ${e}. Supported: bash, zsh, fish`),process.exit(1)}});function c3o(){try{let e=v8t();e.importedKey&&process.stderr.write(`Your saved XENO API key was moved to the protected key store. Your old credential file no longer holds it.
17456
+ `),await Promise.allSettled([Bln(process.stdout),Bln(process.stderr)]),process.exit(rs)}});Oe.addCommand(XFr());Oe.addCommand(GFr(Pe));Oe.addCommand(YFr(Pe));Oe.addCommand(OFr());Oe.addCommand(NFr());Oe.addCommand(BFr());Oe.addCommand(UFr());Oe.addCommand(jFr());Oe.addCommand(LFr());Oe.addCommand(DFr());Oe.addCommand(FFr());Oe.addCommand(oE);Oe.addCommand(iUr());Oe.command("init").description("Initialize project for AI-assisted development").option("-y, --yes","Use detected defaults without prompting").action(async e=>{await Bye({yes:!!e.yes,cwd:process.cwd()})});Oe.command("review").description("AI code review of recent changes").option("--staged","Review only staged changes").option("--range <range>","Review specific commit range (e.g. HEAD~5..HEAD)").option("--files <pattern>","Review specific files").option("--focus <area>","Focus on: security, performance").option("-m, --model <model>","AI model to use").option("-k, --api-key <key>","API key").option("--base-url <url>","API base URL").option("--max-tokens <n>","Max response tokens").option("--production","Run independent specialist reviewers plus verifier agents and persist a typed review artifact").option("--max-findings <n>","Maximum production findings before verification").option("--json","Emit production review as machine-readable JSON").action(async e=>{let t=e.model||Gt.model||Gr,r=yS(e.apiKey,process.env.XENO_API_KEY,Gt.apiKey,ld),n=bw({explicitBaseURL:e.baseUrl,configuredBaseURL:Gt.baseURL}),i=e.maxTokens?parseInt(e.maxTokens,10):Gt.maxTokens??Ite;await Ecr({staged:!!e.staged,range:e.range,files:e.files,focus:e.focus,model:t,apiKey:r,baseURL:n,maxTokens:i,production:!!e.production,json:!!e.json,maxFindings:e.maxFindings?parseInt(e.maxFindings,10):void 0,cwd:process.cwd()})});Oe.command("completions <shell>").description("Generate shell completion scripts (bash, zsh, fish)").action(e=>{switch(e.toLowerCase()){case"bash":process.stdout.write(_ln(Oe));break;case"zsh":process.stdout.write(Pln(Oe));break;case"fish":process.stdout.write($ln(Oe));break;default:console.error(`Unknown shell: ${e}. Supported: bash, zsh, fish`),process.exit(1)}});function c3o(){try{let e=v8t();e.importedKey&&process.stderr.write(`Your saved XENO API key was moved to the protected key store. Your old credential file no longer holds it.
17457
17457
  `),e.noticeDue&&process.stderr.write(`${I8t}
17458
17458
  `)}catch{process.stderr.write(`The previous CLI credential file could not be migrated and was left unchanged.
17459
17459
  `)}}var Nvt=process.argv;async function d3o(e=process.argv){if(Nvt=[...e],e[2]==="spawn"){process.exitCode=await ydt(e.slice(3));return}if(e[2]==="ws"){process.exitCode=await Idt(e.slice(3));return}if(ya("modules-loaded"),p0t()&&process.once("exit",()=>{let n=f0t();n&&process.stderr.write(`startup trace: ${n}