@xenosystem/agent-cli 0.5.76 → 0.5.77

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
@@ -2898,7 +2898,7 @@ ${Ce}${K.compose(iU(),K.bold)("\u2717")} ${WT(e)}
2898
2898
  `)}function wk(){return`
2899
2899
  ${Ce}${Ie("Goodbye.")}
2900
2900
  `}var CMt,bNe,iU,Kt,Ie,JT,WT,xMt,XT,RMt,PMt,_Mt,V,Ce,CNe,pte,C,gte,ENe,GT,Yo=we(()=>{"use strict";Ns();Aa();fNe();nU();ute();CMt=new Mu(process.stdout),bNe=new Mu(process.stderr),iU=()=>cr(),Kt=e=>iU()(e),Ie=K.dim,JT=K.bold,WT=e=>iU()(e),xMt="\u25A0",XT="\u2514",RMt={open:"\x1B[4m",close:"\x1B[24m"};PMt={Read:e=>_l()(e),ReadImage:e=>_l()(e),Glob:e=>_l()(e),Grep:e=>_l()(e),ElfAnalyze:e=>_l()(e),MemoryRead:e=>_l()(e),Write:e=>jT()(e),Edit:e=>jT()(e),MemoryWrite:e=>jT()(e),Bash:e=>ste()(e),GitStatus:e=>_l()(e),GitDiff:e=>_l()(e),GitLog:e=>_l()(e),GitBranch:e=>_l()(e),GitCommit:e=>ste()(e),WebSearch:e=>K.cyan(e),WebFetch:e=>K.cyan(e),TaskOutput:e=>_l()(e),TaskInput:e=>K.cyan(e),TaskStop:e=>Kw()(e)};_Mt={Edit:"Update",Glob:"Search",Grep:"Search",WebSearch:"Web Search",WebFetch:"Web Fetch"};V={accent:Kt,purple:WT,cyan:WT,dim:Ie,bold:JT,red:WT,green:WT},Ce=" ",CNe=1e3,pte=3;C={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"};gte=class{atLineStart=!0;writeFn;constructor(t){this.writeFn=t??(n=>{CMt.writeOrdered(n,"stream")})}write(t){let n="";for(let r of t)this.atLineStart&&(n+=Ce,this.atLineStart=!1),n+=r,r===`
2901
- `&&(this.atLineStart=!0);this.writeFn(n)}reset(){this.atLineStart=!0}markLineStarted(){this.atLineStart=!1}},ENe=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],GT=class{interval=null;frameIndex=0;lastLength=0;writeFn;clearFn;constructor(t,n){this.writeFn=t??(r=>{bNe.writeFrame(r,"spinner")}),this.clearFn=n??(()=>{bNe.writeFrame(`\r${" ".repeat(this.lastLength)}\r`,"spinner")})}start(t){this.stop(),this.frameIndex=0,this.interval=setInterval(()=>{let n=ENe[this.frameIndex%ENe.length],r=`${Kt(n)} ${Ie(t)}`;this.writeFn(`\r${" ".repeat(this.lastLength)}\r${r}`),this.lastLength=t.length+4,this.frameIndex++},80)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null,this.clearFn(),this.lastLength=0)}}});var be,Ei=we(()=>{"use strict";be="0.5.76"});var Mte,uOe=we(()=>{"use strict";Mte="1.0.0"});var wOe={};gc(wOe,{TERMINAL_WEB_JOB_STATES:()=>IU,WEB_JOB_PROGRESS_OPERATIONS:()=>Ote,WEB_JOB_PROGRESS_SCHEMA:()=>ry,WEB_JOB_PROGRESS_SCHEMA_VERSION:()=>lP,WEB_JOB_PROGRESS_STATES:()=>Dte,deriveWebJobProgress:()=>kU,isTerminalWebJobState:()=>_f,isWebJobProgress:()=>Qte,parseWebJobProgress:()=>dP,webJobProgressSignature:()=>Fte});function _f(e){return IU.includes(e)}function fOe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function mOe(e,t){return Object.keys(e).every(n=>t.has(n))}function Lte(e,t){return typeof e=="string"&&e.trim().length>0&&e.length<=t&&!/[\u0000-\u001f\u007f]/u.test(e)}function Nte(e){return Lte(e,64)&&Number.isFinite(Date.parse(e))}function AOe(e){return Lte(e,120)&&/^[A-Za-z0-9._:-]+$/u.test(e)}function hOe(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function dP(e){if(!fOe(e)||!mOe(e,rOt))throw new TypeError("invalid Web Context progress object");if(e.schema!==ry||e.schemaVersion!==lP||e.contractVersion!==Mte)throw new TypeError("unsupported Web Context progress schema");if(!Lte(e.jobId,256))throw new TypeError("invalid Web Context progress jobId");if(!Ote.includes(e.operation))throw new TypeError("invalid Web Context progress operation");if(!Dte.includes(e.state))throw new TypeError("invalid Web Context progress state");let t=_f(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||!AOe(e.terminalReason)))throw new TypeError("invalid Web Context terminalReason");if(!fOe(e.counters)||!mOe(e.counters,pOe))throw new TypeError("invalid Web Context progress counters");for(let r of pOe)if(!hOe(e.counters[r]))throw new TypeError(`invalid Web Context counter ${r}`);let n=Number(e.counters.queuedPages)+Number(e.counters.activePages)+Number(e.counters.completedPages)+Number(e.counters.failedPages)+Number(e.counters.excludedPages);if(e.counters.knownPages!==n)throw new TypeError("inconsistent Web Context knownPages counter");if(!hOe(e.sequence))throw new TypeError("invalid Web Context progress sequence");if(!Nte(e.observedAt))throw new TypeError("invalid Web Context observedAt");if("createdAt"in e&&!Nte(e.createdAt))throw new TypeError("invalid Web Context createdAt");if("updatedAt"in e&&!Nte(e.updatedAt))throw new TypeError("invalid Web Context updatedAt");return structuredClone(e)}function Qte(e){try{return dP(e),!0}catch{return!1}}function cP(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):0}function gOe(e){return typeof e=="string"&&e.length>0?e:void 0}function kU(e,t,n=new Date().toISOString()){let r=cP(e.queuedPages),i=cP(e.activePages),o=cP(e.completedPages),s=cP(e.failedPages),a=cP(e.excludedPages),c={queuedPages:r,activePages:i,completedPages:o,failedPages:s,excludedPages:a,knownPages:r+i+o+s+a},l=_f(e.state),d=AOe(e.terminalReason)?e.terminalReason:void 0,u=gOe(e.createdAt),p=gOe(e.updatedAt);return{schema:ry,schemaVersion:lP,contractVersion:Mte,jobId:e.jobId,operation:e.operation,state:e.state,terminal:l,...l?{terminalState:e.state}:{},...d?{terminalReason:d}:{},counters:c,sequence:t,observedAt:n,...u?{createdAt:u}:{},...p?{updatedAt:p}:{}}}function Fte(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 ry,lP,IU,Ote,Dte,rOt,pOe,Ck=we(()=>{"use strict";uOe();ry="xeno.web-context.job-progress",lP="1.0.0",IU=["completed","partial","failed","cancelled"],Ote=["scrape","batch-scrape","map","crawl","render","extract"],Dte=["queued","running",...IU];rOt=new Set(["schema","schemaVersion","contractVersion","jobId","operation","state","terminal","terminalState","terminalReason","counters","sequence","observedAt","createdAt","updatedAt"]),pOe=new Set(["queuedPages","activePages","completedPages","failedPages","excludedPages","knownPages"])});function uP(e){return e.signal?{signal:e.signal}:{}}function yOe(e,t){let n=e;return{message:t,...typeof n?.code=="string"?{code:n.code}:{},...typeof n?.status=="number"?{status:n.status}:{}}}function iOt(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 oOt(e,t){let n=0,r,i=!1;return async o=>{if(!e)return;let s=_f(o.state);if(s&&i)return;let a=kU(o,n),c=Fte(a);if(!(r===c&&!s)){r=c,n+=1,s&&(i=!0);try{await e(a)}catch(l){throw Object.assign(new Error("job progress listener failed"),{code:"PROGRESS_LISTENER_FAILED",jobId:t,state:a.state,cause:l})}}}}var EU,bOe=we(()=>{"use strict";Ck();Ck();EU=class{#e;#t;#r;constructor(t){if(this.#e=new URL(t.baseUrl),this.#t=t.token,!this.#t.trim())throw new TypeError("token is required");this.#r=t.fetchImpl??fetch}async#n(t,n={}){let r=await this.#r(new URL(t,this.#e),{...n,redirect:"error",headers:{authorization:`Bearer ${this.#t}`,...n.body?{"content-type":"application/json"}:{},...n.headers}});if(!r.ok){let i=`HTTP ${r.status}`,o;try{let s=await r.json();i=s.error?.message??i,o=s.error?.code}catch{}throw Object.assign(new Error(i),{status:r.status,...o?{code:o}:{}})}return r.status===204?void 0:await r.json()}async#o(t,n={}){let r=await this.#r(new URL(t,this.#e),{...n,redirect:"error",headers:{authorization:`Bearer ${this.#t}`,...n.headers}});if(!r.ok){let i=`HTTP ${r.status}`,o;try{let s=await r.json();i=s.error?.message??i,o=s.error?.code}catch{}throw Object.assign(new Error(i),{status:r.status,...o?{code:o}:{}})}return r}capabilities(){return this.#n("/v1/capabilities")}account(t={}){return this.#n("/v1/account",uP(t))}usage(){return this.#n("/v1/usage")}search(t,n={}){return this.#n("/v1/search",{method:"POST",body:JSON.stringify(t),...uP(n)})}searchAndScrape(t,n={}){return this.#n("/v1/search-and-scrape",{method:"POST",body:JSON.stringify(t),...uP(n)})}scrape(t){return this.#n("/v1/scrape",{method:"POST",body:JSON.stringify(t)})}render(t){return this.#n("/v1/render",{method:"POST",body:JSON.stringify(t)})}map(t){return this.#n("/v1/map",{method:"POST",body:JSON.stringify(t)})}crawl(t){return this.#n("/v1/crawl",{method:"POST",body:JSON.stringify(t)})}batchScrape(t){return this.#n("/v1/batch-scrape",{method:"POST",body:JSON.stringify(t)})}activity(t={}){let n=new URLSearchParams;return t.limit&&n.set("limit",String(t.limit)),t.cursor&&n.set("cursor",t.cursor),this.#n(`/v1/activity?${n}`)}job(t){return this.#n(`/v1/jobs/${encodeURIComponent(t)}`)}frontier(t,n={}){let r=new URLSearchParams;return n.limit&&r.set("limit",String(n.limit)),n.cursor&&r.set("cursor",n.cursor),this.#n(`/v1/jobs/${encodeURIComponent(t)}/frontier?${r}`)}results(t,n={}){let r=new URLSearchParams;return n.limit&&r.set("limit",String(n.limit)),n.cursor&&r.set("cursor",n.cursor),this.#n(`/v1/jobs/${encodeURIComponent(t)}/results?${r}`,uP(n))}async artifact(t,n,r={}){if(!/^artifact:[a-f0-9]{64}$/i.test(n))throw new TypeError("artifactId is invalid");let i=await this.#o(`/v1/jobs/${encodeURIComponent(t)}/artifacts/${n}`,uP(r)),o=i.headers.get("etag")??void 0;return{jobId:t,artifactId:n,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.#n(`/v1/jobs/${encodeURIComponent(t)}/cancel`,{method:"POST"})}resume(t){return this.#n(`/v1/jobs/${encodeURIComponent(t)}/resume`,{method:"POST"})}webhookDeliveries(t){return this.#n(`/v1/jobs/${encodeURIComponent(t)}/webhooks`)}upload(t){return this.#n("/v1/artifacts",{method:"POST",body:JSON.stringify(t)})}parse(t){return this.#n("/v1/parse",{method:"POST",body:JSON.stringify(t)})}extract(t){return this.#n("/v1/extract",{method:"POST",body:JSON.stringify(t)})}monitors(){return this.#n("/v1/monitors")}createMonitor(t){return this.#n("/v1/monitors",{method:"POST",body:JSON.stringify(t)})}monitorChecks(t,n=100){return this.#n(`/v1/monitors/${encodeURIComponent(t)}/checks?limit=${n}`)}setMonitorState(t,n){return this.#n(`/v1/monitors/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify({state:n})})}removeMonitor(t){return this.#n(`/v1/monitors/${encodeURIComponent(t)}`,{method:"DELETE"})}async#i(t,n,r,i){let o;try{({job:o}=await this.cancel(t))}catch(p){return{attempted:!0,trigger:n,jobId:t,outcome:"failed",error:yOe(p,"Web Context cancellation failed")}}let s=i.cancelConfirmationMs??2e3,a=Date.now()+(Number.isFinite(s)&&s>0?s:0),c=i.pollMs??500,l,d=async p=>{try{await r(p)}catch(f){l??=yOe(f,"Web Context progress listener failed during cancellation confirmation")}};for(await d(o);!_f(o.state)&&Date.now()<a;){await new Promise(f=>{setTimeout(f,Math.min(c,Math.max(0,a-Date.now())))});let p;try{({job:p}=await this.job(t))}catch{break}o=p,await d(o)}let u=_f(o.state)?kU(o,0):void 0;return{attempted:!0,trigger:n,jobId:t,outcome:o.state==="cancelled"?"cancelled":"requested",...u?{terminalProgress:u}:{},...l?{listenerError:l}:{}}}async waitForJob(t,n={}){let r=Date.now()+(n.timeoutMs??12e4),i=oOt(n.onProgress,t),o;try{for(;Date.now()<r;){if(n.signal?.aborted)throw o="abort",n.signal.reason;let{job:s}=await this.job(t);if(await i(s),_f(s.state))return s;await new Promise((a,c)=>{let l=setTimeout(a,n.pollMs??500);n.signal?.addEventListener("abort",()=>{clearTimeout(l),o="abort",c(n.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"?n.cancelOnAbort===!0:o==="timeout"?n.cancelOnTimeout===!0:!1;throw!o||!a?s:iOt(s,await this.#i(t,o,i,n))}}async scrapeAndWait(t,n={}){let r=await this.scrape(t),i=await this.waitForJob(r.job.jobId,n);if(i.state!=="completed"&&i.state!=="partial")throw Object.assign(new Error(`scrape job ended in ${i.state}`),{code:"JOB_NOT_COMPLETED",jobId:i.jobId,state:i.state});let o=await this.results(i.jobId,{limit:1}),s=o.items.find(c=>c.state==="completed"&&typeof c.artifactId=="string")??o.items.find(c=>typeof c.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 sOt}from"node:fs";function cOt(e=process.env){let t=e.XENO_WEB_CONTEXT_TOKEN?.trim();if(t)return t;let n=e.XENO_WEB_CONTEXT_TOKEN_FILE?.trim();if(n){let r=sOt(n,"utf8").trim();if(r)return r}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 qte(e=process.env){return new EU({baseUrl:e.XENO_WEB_CONTEXT_URL?.trim()||aOt,token:cOt(e)})}function vOe(e=process.env){return{client:new Ute(e),createRequest:e2({actor:{id:"xeno-agent-cli",kind:"agent"},scope:{kind:"local-profile",profileId:"pending-token-scope"},classification:"public",purposePrefix:"xeno-agent-cli:chat",budget:{durationMs:12e4,maxAttempts:3,maxConcurrency:4,maxBytes:1e7,maxPages:100,maxRedirects:8,maxProviderCostUsd:0}})}}var aOt,Ute,jte=we(()=>{"use strict";bOe();at();aOt="http://127.0.0.1:8080";Ute=class{constructor(t){this.env=t}env;client;tenantId;async search(t){return this.getClient().search(await this.bindTenant(t))}async scrapeAndWait(t,n){return this.getClient().scrapeAndWait(await this.bindTenant(t),n)}getClient(){return this.client??=qte(this.env),this.client}async bindTenant(t){this.tenantId??=this.getClient().account().then(r=>r.tenantId);let n=await this.tenantId;return{...t,scope:{kind:"tenant",tenantId:n}}}}});var IOe=we(()=>{"use strict"});function kOe(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 n=t.snapshot,r=o=>typeof o=="number"&&Number.isSafeInteger(o)&&o>=0,i=(o,s,a,c=!1)=>Array.isArray(o)&&o.every(l=>l&&typeof l=="object"&&!Array.isArray(l)&&typeof l[s]=="string"&&r(l[a])&&(!c||l.cost===null));return n.source==="local-runtime-journal"&&n.billingStatus==="unavailable"&&n.totalCost===null&&typeof n.observedAt=="string"&&Number.isFinite(Date.parse(n.observedAt))&&r(n.totalTokens)&&r(n.totalRequests)&&r(n.unmeasuredRequests)&&n.unmeasuredRequests<=n.totalRequests&&i(n.dailyUsage,"label","value")&&i(n.weeklyUsage,"label","value")&&i(n.monthlyUsage,"label","value")&&i(n.costByModel,"model","tokens",!0)&&i(n.topAgents,"name","tokens",!0)}var EOe=we(()=>{"use strict"});var SOe=we(()=>{"use strict"});function COe(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(n=>n&&typeof n=="object"&&["id","timestamp","action","actor","target","details"].every(r=>typeof n[r]=="string")&&Number.isFinite(Date.parse(n.timestamp)))}var xOe=we(()=>{"use strict"});function TOe(e){return!Vte(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&&!ROe(e.loadedModel)||e.models!==void 0&&(!Array.isArray(e.models)||e.models.length>1e3||!e.models.every(t=>Vte(t)&&ROe(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&&(!Vte(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 Vte,ROe,POe=we(()=>{"use strict";Vte=e=>!!e&&typeof e=="object"&&!Array.isArray(e),ROe=e=>typeof e=="string"&&e.length>0&&e.length<=512&&!/[\x00-\x1f\x7f]/.test(e)});var mUn,_Oe=we(()=>{"use strict";mUn=new TextEncoder});var $Oe=we(()=>{"use strict"});var BOe=we(()=>{"use strict"});var MOe=we(()=>{"use strict"});var NOe=we(()=>{"use strict"});var OOe=we(()=>{"use strict"});var DOe=we(()=>{"use strict";OOe()});var LOe=we(()=>{"use strict"});var QOe=we(()=>{"use strict"});var FOe=we(()=>{"use strict"});var lOt,UOe=we(()=>{"use strict";Wh();lOt=1024*1024});function mOt(e){return typeof e=="string"&&dOt.includes(e)}function qOe(e){return vo(e)?jn(e.clientId)&&jn(e.clientVersion)&&jn(e.instanceId)&&mOt(e.surface):!1}function VOe(e){return!vo(e)||!vo(e.protocol)||!vo(e.host)||!vo(e.storage)?!1:Number.isInteger(e.protocol.current)&&bOt(e.protocol.supported)&&jn(e.host.instanceId)&&jn(e.host.version)&&(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)&&qOe(e.surface)}function Hte(e){return!vo(e)||!jn(e.revision)||!Array.isArray(e.providers)?!1:e.providers.every(wOt)}function hOt(e){return!vo(e)||!vo(e.event)?!1:jn(e.id)&&Number.isInteger(e.sequence)&&typeof e.sequence=="number"&&e.sequence>=0&&jn(e.timestamp)&&jn(e.conversationId)&&jn(e.requestId)&&jn(e.type)&&jn(e.source)}function HOe(e){return!vo(e)||!Array.isArray(e.events)?!1:(e.nextSequence===null||typeof e.nextSequence=="number"&&Number.isInteger(e.nextSequence)&&e.nextSequence>=0)&&e.events.every(hOt)}function WOe(e){return!vo(e)||typeof e.success!="boolean"?!1:e.success?(e.status==="accepted"||e.status==="replayed")&&jn(e.conversationId)&&jn(e.requestId)&&jn(e.adapterId)&&vo(e.selection)&&jn(e.selection.providerId)&&jn(e.selection.catalogRevision):jn(e.code)&&jn(e.safeError)}function GOe(e){return!vo(e)||typeof e.success!="boolean"?!1:e.success?(e.status==="cancel_requested"||e.status==="replayed")&&jn(e.conversationId)&&jn(e.requestId):jn(e.code)&&jn(e.safeError)}function JOe(e){return vo(e)&&jn(e.id)&&typeof e.sequence=="number"&&Number.isInteger(e.sequence)&&e.sequence>0&&typeof e.timestamp=="number"&&Number.isFinite(e.timestamp)&&gOt(e.type)&&e.source==="host"&&e.schemaVersion===1&&e.redactionState==="safe"&&"payload"in e}function gOt(e){return typeof e=="string"&&fOt.includes(e)}function XOe(e,t,n){if(e.surface.surface!==t.surface||e.surface.instanceId!==t.instanceId)throw new eo("surface_mismatch",`Agent host acknowledged ${e.surface.surface}/${e.surface.instanceId} instead of ${t.surface}/${t.instanceId}.`);if(e.protocol.current<n.min||e.protocol.current>n.max||n.max<e.protocol.supported.min||n.min>e.protocol.supported.max)throw new eo("protocol_mismatch",`Agent host protocol ${e.protocol.current} is incompatible with client range ${n.min}-${n.max}.`)}function AOt(e){return!(!vo(e)||e.chatExecution!==void 0&&!pP(e.chatExecution)||e.durableResume!==void 0&&!pP(e.durableResume)||e.nativeTuiAttach!==void 0&&!pP(e.nativeTuiAttach)||e.reconciliation!==void 0&&!pP(e.reconciliation)||e.modelSwitchInPlace!==void 0&&!pP(e.modelSwitchInPlace)||e.resumeCompatibilityKey!==void 0&&typeof e.resumeCompatibilityKey!="string")}function pP(e){return vo(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 wOt(e){return vo(e)?jn(e.id)&&typeof e.kind=="string"&&uOt.includes(e.kind)&&jn(e.displayName)&&zOe(e.availability)&&vo(e.capabilities)&&(e.providerSession===void 0||AOt(e.providerSession))&&Array.isArray(e.models)&&e.models.every(yOt)&&jn(e.catalogRevision):!1}function yOt(e){return vo(e)&&jn(e.id)&&jn(e.displayName)&&zOe(e.availability)&&(e.reasoningOptions===void 0||Array.isArray(e.reasoningOptions)&&e.reasoningOptions.every(t=>vo(t)&&jn(t.id)&&jn(t.label)&&(t.runtimeModelId===void 0||jn(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 zOe(e){return e==="available"||e==="degraded"||e==="blocked"||e==="unavailable"}function bOt(e){return vo(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 jn(e){return typeof e=="string"&&e.trim().length>0}function vo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function SU(e){for(let t of IOt)for(let n of vOt)if(e===`${t}tool.${n}`)return n;return null}function iy(e,t){let n=e?.[t];return typeof n=="string"&&n.trim()?n:void 0}function CU(e){let t=e.event;return iy(t,"toolName")||iy(t,"tool")||iy(t,"name")||iy(t,"title")||iy(t,"kind")}function Rk(e){let t=e.event;return iy(t,"toolCallId")||iy(t,"tool_call_id")}function KOe(e){let t=e.event;for(let n of["rawInput","input","arguments","parameters","args"]){let r=t?.[n];if(r&&typeof r=="object"&&!Array.isArray(r))return r}}function YOe(e){let t=e.event;for(let n of["rawOutput","output","result","content"]){let r=t?.[n];if(typeof r=="string")return r.length>0?r:void 0;if(r!=null)try{let i=JSON.stringify(r);if(i&&i!=="{}"&&i!=="[]")return i}catch{}}}function xU(e){return e==="completed"?!0:e==="failed"||e==="cancelled"?!1:null}var xk,jOe,dOt,uOt,pOt,kUn,fOt,eo,vOt,IOt,Wh=we(()=>{"use strict";IOe();EOe();SOe();xOe();POe();_Oe();$Oe();Ck();BOe();MOe();NOe();DOe();LOe();QOe();FOe();UOe();xk=1,jOe=1,dOt=["standalone-desktop","hub-embed","shell-embed","embed-preview","panel-embed","headless-client"],uOt=["sdk-native","xeno-cloud","cli-app-server","cli-remote","acp"],pOt=["workspace.usage","workspace.audit","inference.request","workspace.schedule","workspace.backup","workspace.environment","account.request","workforce.request","workspace.notifications","workspace.rules","workspace.browser","workspace.browser.session","host.handshake","providers.list","providers.refresh","runtime.events.list","workspace.lifecycle.apply","state.workspaces.load","state.workspaces.save","state.conversations.load","state.conversations.save","state.conversations.delete","workspace.access.grant","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.resume","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"],kUn=new Set(pOt),fOt=["host.ready","provider.catalog.changed","state.workspaces.changed","runtime.event.appended","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"],eo=class extends Error{code;constructor(t,n){super(n),this.name="AgentHostProtocolError",this.code=t}};vOt=["started","updated","completed","failed","cancelled"],IOt=["","acp."]});function RU(e){let t=e.type.toLowerCase();if(!(t.includes("tool")||Rk(e))&&!(!t.includes("text")&&!t.includes("message")&&!t.includes("delta"))&&!(t.includes("complete")||t.includes("final")||t.includes("end")))for(let n of["delta","text","content","chunk"]){let r=e.event[n];if(typeof r=="string"&&r.length>0)return r}}var Wte=we(()=>{"use strict";Wh()});import{createHash as kOt}from"node:crypto";import{setTimeout as EOt}from"node:timers/promises";function xOt(e,t){return`subrun-${kOt("sha256").update(`${e}\0${t}`).digest("hex").slice(0,32)}`}async function ROt(e,t,n){return((await e.listRuntimeEvents({conversationId:t,subagentRunId:n,limit:500}))?.events??[]).map(i=>RU(i)??"").join("")}function TOt(e,t,n,r){let i=new Set,o=typeof r.onToolStart=="function"||typeof r.onToolEnd=="function",s=a=>{try{a()}catch{}};return async function(){if(!o)return;let c=await e.listRuntimeEvents({conversationId:t,subagentRunId:n,limit:500}).catch(()=>null);for(let l of c?.events??[]){let d=SU(String(l.type??""));if(!d)continue;let u=`${Rk(l)??l.id}:${d}`;if(i.has(u))continue;i.add(u);let p=CU(l)??"unknown";if(d==="started"&&r.onToolStart){let m=r.onToolStart;s(()=>m(p,KOe(l)??{}))}let f=xU(d);if(f!==null&&r.onToolEnd){let m=r.onToolEnd;s(()=>m(p,{success:f,output:YOe(l)??""}))}}}}function ZOe(e){let t=e.pollIntervalMs??250;return async n=>{let r=n.task,i=xOt(e.rootTraceId,r.id),o={lastTraceId:null,tokenUsage:{input:0,output:0,total:0},async run(s){let a=Math.max(1e3,e.deadline-Date.now()),c={parentConversationId:e.parentConversationId,...e.parentRequestId===void 0?{}:{parentRequestId:e.parentRequestId},parentAgentId:e.parentAgentId,childConversationId:i,childAgentId:r.role?`delegated-${r.role}`:"delegated-branch",workspaceId:e.workspaceId,teamId:e.teamId,objective:s,...r.role===void 0?{}:{role:r.role},policy:{maxRuntimeMs:a}},l=await e.client.createSubagentRun(c);if(!l?.success||!l.run)throw new Error(l?.safeError??"The Agent host refused to create a subagent run for this delegated branch.");let d=l.run.id;o.lastTraceId=d;let u=TOt(e.client,i,d,{onToolStart:n.onToolStart,onToolEnd:n.onToolEnd});for(;;){if(e.signal?.aborted){await e.client.cancelSubagentRun({runId:d}).catch(()=>{});let h=new Error("Delegated branch was cancelled.");throw h.name="AgentInterruptedError",h}let f=((await e.client.listSubagentRuns({parentConversationId:e.parentConversationId}))?.runs??[]).find(h=>h.id===d),m=String(f?.status??"");if(SOt.has(m)){if(COt.has(m))throw new Error(f?.error??`The delegated branch ended as '${m}' without reporting a reason.`);await u();let h=await ROt(e.client,i,d);if(h.length===0)throw new Error(`The delegated branch reported '${m}' but produced no readable output. Its runtime events carry no text for this run id.`);return h}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 EOt(t,void 0,{signal:e.signal})}}};return o}}var SOt,COt,eDe=we(()=>{"use strict";Wh();Wte();SOt=new Set(["completed","succeeded","failed","cancelled","error"]),COt=new Set(["failed","cancelled","error"])});import{execFile as tDe,execFileSync as Gte}from"node:child_process";import{promisify as nDe}from"node:util";import{createHash as POt}from"node:crypto";import{existsSync as _Ot,readFileSync as Jte,readlinkSync as $Ot}from"node:fs";import{hostname as oy}from"node:os";function PU(e){return Number.isInteger(e)&&e>0}function MOt(e){return POt("sha256").update(e).digest("hex")}function mP(e){let t=e?.trim().replaceAll("\\","/").toLowerCase();return t?`sha256:${MOt(t)}`:void 0}function TU(){if(process.platform==="linux")try{return Jte("/proc/sys/kernel/random/boot_id","utf8").trim()||void 0}catch{return}}function $f(e){if(typeof e!="number"||!PU(e))return"dead";try{return process.kill(e,0),"live"}catch(t){return t.code==="ESRCH"?"dead":"unknown"}}function Xte(e){let t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():null}function rDe(e){return["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",["$ErrorActionPreference = 'Stop'",`$items = @(Get-Process -Id @(${e.join(", ")}) -ErrorAction SilentlyContinue)`,"$out = @($items | ForEach-Object { $path = try { [string]$_.Path } catch { '' }; [pscustomobject]@{ pid = [int]$_.Id; startedAt = $_.StartTime.ToUniversalTime().ToString('o'); executable = $path } })","$out | ConvertTo-Json -Compress"].join("; ")]}function iDe(e){let t=new Map;try{if(!e)return t;let n=JSON.parse(e);for(let r of Array.isArray(n)?n:[n]){let i=Number(r.pid),o=Xte(String(r.startedAt??""));!PU(i)||!o||t.set(i,{pid:i,processStartedAt:o,hostname:oy(),...mP(r.executable)?{executableFingerprint:mP(r.executable)}:{},confidence:"observed"})}}catch{return t}return t}function NOt(e){if(!e.length)return new Map;try{return iDe(Gte("powershell.exe",rDe(e),{encoding:"utf8",windowsHide:!0,timeout:1e4,stdio:["ignore","pipe","ignore"]}).trim())}catch{return new Map}}function OOt(){if(fP)return fP;try{let e=Number.parseInt(Gte("getconf",["CLK_TCK"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim(),10);fP=Number.isFinite(e)&&e>0?e:100}catch{fP=100}return fP}function DOt(){try{let e=/^btime\s+(\d+)$/m.exec(Jte("/proc/stat","utf8"));return e?Number.parseInt(e[1]??"",10):null}catch{return null}}function LOt(e){try{let t=Jte(`/proc/${e}/stat`,"utf8"),n=t.lastIndexOf(")");if(n<0)return null;let r=t.slice(n+2).trim().split(/\s+/),i=Number(r[19]),o=DOt();if(!Number.isFinite(i)||o===null)return null;let s=new Date((o+i/OOt())*1e3).toISOString(),a;try{a=$Ot(`/proc/${e}/exe`)}catch{a=void 0}return{pid:e,processStartedAt:s,hostname:oy(),...TU()?{bootId:TU()}:{},...mP(a)?{executableFingerprint:mP(a)}:{},confidence:"observed"}}catch{return null}}function oDe(e){let t=new Map;if(process.platform==="linux"){for(let n of e){let r=LOt(n);r&&t.set(n,r)}return t}for(let n of e)try{let r=Gte("ps",["-p",String(n),"-o","lstart="],{encoding:"utf8",timeout:2e3,env:{...process.env,LC_ALL:"C"},stdio:["ignore","pipe","ignore"]}).trim(),i=Xte(r);if(!i)continue;t.set(n,{pid:n,processStartedAt:i,hostname:oy(),confidence:"observed"})}catch{continue}return t}function hP(e){let t=[...new Set(e.filter(PU))],n=t.includes(process.pid),r=n?t.filter(o=>o!==process.pid):t,i=process.platform==="win32"?NOt(r):oDe(r);return n&&i.set(process.pid,Gh()),i}function sDe(e){return hP([e]).get(e)??null}async function aDe(e,t){t?.throwIfAborted();let n=[...new Set(e.filter(PU))],r=n.filter(o=>o!==process.pid),i=new Map;if(process.platform==="win32"&&r.length)try{let o=await nDe(tDe)("powershell.exe",rDe(r),{encoding:"utf8",windowsHide:!0,timeout:1e4,maxBuffer:1048576,signal:t});i=iDe(o.stdout.trim())}catch{t?.throwIfAborted()}else if(process.platform==="linux")i=oDe(r);else if(process.platform!=="win32")for(let o of r){t?.throwIfAborted();try{let{stdout:s}=await nDe(tDe)("ps",["-p",String(o),"-o","lstart="],{encoding:"utf8",timeout:2e3,signal:t,env:{...process.env,LC_ALL:"C"},maxBuffer:4096}),a=Xte(s.trim());a&&i.set(o,{pid:o,processStartedAt:a,hostname:oy(),confidence:"observed"})}catch{t?.throwIfAborted()}}return t?.throwIfAborted(),n.includes(process.pid)&&i.set(process.pid,Gh()),i}function _U(e,t=new Date,n=!1){return(n?sDe(e):null)??{pid:e,processStartedAt:t.toISOString(),hostname:oy(),confidence:"degraded"}}function Gh(){let e=new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString();return{pid:process.pid,processStartedAt:e,hostname:oy(),...TU()?{bootId:TU()}:{},..._Ot(process.execPath)?{executableFingerprint:mP(process.execPath)}:{},confidence:"self"}}function Zo(e,t=sDe){if(e.hostname!==oy())return{status:"remote",expected:e,reason:"Process belongs to another host."};if($f(e.pid)==="dead")return{status:"dead",expected:e,reason:"Process ID is not live."};let n=t(e.pid);if(!n)return{status:"degraded",expected:e,reason:"Creation time could not be observed."};let r=Date.parse(e.processStartedAt),i=Date.parse(n.processStartedAt);return!Number.isFinite(r)||!Number.isFinite(i)||Math.abs(r-i)>BOt?{status:"mismatch",expected:e,observed:n,reason:"Process creation time does not match."}:e.bootId&&n.bootId&&e.bootId!==n.bootId?{status:"mismatch",expected:e,observed:n,reason:"Host boot identity does not match."}:e.executableFingerprint&&n.executableFingerprint&&e.executableFingerprint!==n.executableFingerprint?{status:"mismatch",expected:e,observed:n,reason:"Executable identity does not match."}:{status:"live",expected:e,observed:n}}var BOt,fP,Du=we(()=>{"use strict";BOt=3e3});import{createHash as QOt,randomBytes as FOt}from"node:crypto";import{chmodSync as UOt,existsSync as qOt,mkdirSync as lDe,readFileSync as jOt,renameSync as VOt,unlinkSync as dDe,writeFileSync as HOt}from"node:fs";import{dirname as WOt,join as gP}from"node:path";function uDe(){return pl()}function GOt(e){return QOt("sha256").update(e).digest("hex").slice(0,16)}function xn(){return gP(uDe(),"daemon")}function zte(){return gP(xn(),"daemon.json")}function pDe(){return gP(xn(),"daemon.lock")}function Tk(){return gP(xn(),"daemon.log")}function Kte(){let e=GOt(uDe());return process.platform==="win32"?{transport:"named-pipe",endpoint:`\\\\.\\pipe\\xeno-agent-daemon-${e}`}:{transport:"unix-socket",endpoint:gP(xn(),"daemon.sock")}}function $U(){lDe(xn(),{recursive:!0})}function fDe(){return FOt(32).toString("base64url")}function cDe(e){if(process.platform!=="win32")try{UOt(e,384)}catch{}}function Yte(){try{let e=zte(),t=jOt(e,"utf8"),n=JSON.parse(t);if(!n||n.schemaVersion!==1||n.protocolVersion!==1||n.transport!=="named-pipe"&&n.transport!=="unix-socket"||typeof n.endpoint!="string"||typeof n.authToken!="string"||!Number.isSafeInteger(n.pid)||typeof n.startedAt!="string"||typeof n.cliVersion!="string"||typeof n.logPath!="string")throw new Error("daemon state schema is invalid");return n}catch(e){if(e.code==="ENOENT")return null;throw new Error(`Daemon state is corrupt or unreadable: ${e instanceof Error?e.message:String(e)}`)}}function mDe(e){let t=zte();lDe(WOt(t),{recursive:!0});let n=`${t}.${process.pid}.${Date.now()}.tmp`;HOt(n,JSON.stringify(e,null,2)+`
2901
+ `&&(this.atLineStart=!0);this.writeFn(n)}reset(){this.atLineStart=!0}markLineStarted(){this.atLineStart=!1}},ENe=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],GT=class{interval=null;frameIndex=0;lastLength=0;writeFn;clearFn;constructor(t,n){this.writeFn=t??(r=>{bNe.writeFrame(r,"spinner")}),this.clearFn=n??(()=>{bNe.writeFrame(`\r${" ".repeat(this.lastLength)}\r`,"spinner")})}start(t){this.stop(),this.frameIndex=0,this.interval=setInterval(()=>{let n=ENe[this.frameIndex%ENe.length],r=`${Kt(n)} ${Ie(t)}`;this.writeFn(`\r${" ".repeat(this.lastLength)}\r${r}`),this.lastLength=t.length+4,this.frameIndex++},80)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null,this.clearFn(),this.lastLength=0)}}});var be,Ei=we(()=>{"use strict";be="0.5.77"});var Mte,uOe=we(()=>{"use strict";Mte="1.0.0"});var wOe={};gc(wOe,{TERMINAL_WEB_JOB_STATES:()=>IU,WEB_JOB_PROGRESS_OPERATIONS:()=>Ote,WEB_JOB_PROGRESS_SCHEMA:()=>ry,WEB_JOB_PROGRESS_SCHEMA_VERSION:()=>lP,WEB_JOB_PROGRESS_STATES:()=>Dte,deriveWebJobProgress:()=>kU,isTerminalWebJobState:()=>_f,isWebJobProgress:()=>Qte,parseWebJobProgress:()=>dP,webJobProgressSignature:()=>Fte});function _f(e){return IU.includes(e)}function fOe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function mOe(e,t){return Object.keys(e).every(n=>t.has(n))}function Lte(e,t){return typeof e=="string"&&e.trim().length>0&&e.length<=t&&!/[\u0000-\u001f\u007f]/u.test(e)}function Nte(e){return Lte(e,64)&&Number.isFinite(Date.parse(e))}function AOe(e){return Lte(e,120)&&/^[A-Za-z0-9._:-]+$/u.test(e)}function hOe(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function dP(e){if(!fOe(e)||!mOe(e,rOt))throw new TypeError("invalid Web Context progress object");if(e.schema!==ry||e.schemaVersion!==lP||e.contractVersion!==Mte)throw new TypeError("unsupported Web Context progress schema");if(!Lte(e.jobId,256))throw new TypeError("invalid Web Context progress jobId");if(!Ote.includes(e.operation))throw new TypeError("invalid Web Context progress operation");if(!Dte.includes(e.state))throw new TypeError("invalid Web Context progress state");let t=_f(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||!AOe(e.terminalReason)))throw new TypeError("invalid Web Context terminalReason");if(!fOe(e.counters)||!mOe(e.counters,pOe))throw new TypeError("invalid Web Context progress counters");for(let r of pOe)if(!hOe(e.counters[r]))throw new TypeError(`invalid Web Context counter ${r}`);let n=Number(e.counters.queuedPages)+Number(e.counters.activePages)+Number(e.counters.completedPages)+Number(e.counters.failedPages)+Number(e.counters.excludedPages);if(e.counters.knownPages!==n)throw new TypeError("inconsistent Web Context knownPages counter");if(!hOe(e.sequence))throw new TypeError("invalid Web Context progress sequence");if(!Nte(e.observedAt))throw new TypeError("invalid Web Context observedAt");if("createdAt"in e&&!Nte(e.createdAt))throw new TypeError("invalid Web Context createdAt");if("updatedAt"in e&&!Nte(e.updatedAt))throw new TypeError("invalid Web Context updatedAt");return structuredClone(e)}function Qte(e){try{return dP(e),!0}catch{return!1}}function cP(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):0}function gOe(e){return typeof e=="string"&&e.length>0?e:void 0}function kU(e,t,n=new Date().toISOString()){let r=cP(e.queuedPages),i=cP(e.activePages),o=cP(e.completedPages),s=cP(e.failedPages),a=cP(e.excludedPages),c={queuedPages:r,activePages:i,completedPages:o,failedPages:s,excludedPages:a,knownPages:r+i+o+s+a},l=_f(e.state),d=AOe(e.terminalReason)?e.terminalReason:void 0,u=gOe(e.createdAt),p=gOe(e.updatedAt);return{schema:ry,schemaVersion:lP,contractVersion:Mte,jobId:e.jobId,operation:e.operation,state:e.state,terminal:l,...l?{terminalState:e.state}:{},...d?{terminalReason:d}:{},counters:c,sequence:t,observedAt:n,...u?{createdAt:u}:{},...p?{updatedAt:p}:{}}}function Fte(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 ry,lP,IU,Ote,Dte,rOt,pOe,Ck=we(()=>{"use strict";uOe();ry="xeno.web-context.job-progress",lP="1.0.0",IU=["completed","partial","failed","cancelled"],Ote=["scrape","batch-scrape","map","crawl","render","extract"],Dte=["queued","running",...IU];rOt=new Set(["schema","schemaVersion","contractVersion","jobId","operation","state","terminal","terminalState","terminalReason","counters","sequence","observedAt","createdAt","updatedAt"]),pOe=new Set(["queuedPages","activePages","completedPages","failedPages","excludedPages","knownPages"])});function uP(e){return e.signal?{signal:e.signal}:{}}function yOe(e,t){let n=e;return{message:t,...typeof n?.code=="string"?{code:n.code}:{},...typeof n?.status=="number"?{status:n.status}:{}}}function iOt(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 oOt(e,t){let n=0,r,i=!1;return async o=>{if(!e)return;let s=_f(o.state);if(s&&i)return;let a=kU(o,n),c=Fte(a);if(!(r===c&&!s)){r=c,n+=1,s&&(i=!0);try{await e(a)}catch(l){throw Object.assign(new Error("job progress listener failed"),{code:"PROGRESS_LISTENER_FAILED",jobId:t,state:a.state,cause:l})}}}}var EU,bOe=we(()=>{"use strict";Ck();Ck();EU=class{#e;#t;#r;constructor(t){if(this.#e=new URL(t.baseUrl),this.#t=t.token,!this.#t.trim())throw new TypeError("token is required");this.#r=t.fetchImpl??fetch}async#n(t,n={}){let r=await this.#r(new URL(t,this.#e),{...n,redirect:"error",headers:{authorization:`Bearer ${this.#t}`,...n.body?{"content-type":"application/json"}:{},...n.headers}});if(!r.ok){let i=`HTTP ${r.status}`,o;try{let s=await r.json();i=s.error?.message??i,o=s.error?.code}catch{}throw Object.assign(new Error(i),{status:r.status,...o?{code:o}:{}})}return r.status===204?void 0:await r.json()}async#o(t,n={}){let r=await this.#r(new URL(t,this.#e),{...n,redirect:"error",headers:{authorization:`Bearer ${this.#t}`,...n.headers}});if(!r.ok){let i=`HTTP ${r.status}`,o;try{let s=await r.json();i=s.error?.message??i,o=s.error?.code}catch{}throw Object.assign(new Error(i),{status:r.status,...o?{code:o}:{}})}return r}capabilities(){return this.#n("/v1/capabilities")}account(t={}){return this.#n("/v1/account",uP(t))}usage(){return this.#n("/v1/usage")}search(t,n={}){return this.#n("/v1/search",{method:"POST",body:JSON.stringify(t),...uP(n)})}searchAndScrape(t,n={}){return this.#n("/v1/search-and-scrape",{method:"POST",body:JSON.stringify(t),...uP(n)})}scrape(t){return this.#n("/v1/scrape",{method:"POST",body:JSON.stringify(t)})}render(t){return this.#n("/v1/render",{method:"POST",body:JSON.stringify(t)})}map(t){return this.#n("/v1/map",{method:"POST",body:JSON.stringify(t)})}crawl(t){return this.#n("/v1/crawl",{method:"POST",body:JSON.stringify(t)})}batchScrape(t){return this.#n("/v1/batch-scrape",{method:"POST",body:JSON.stringify(t)})}activity(t={}){let n=new URLSearchParams;return t.limit&&n.set("limit",String(t.limit)),t.cursor&&n.set("cursor",t.cursor),this.#n(`/v1/activity?${n}`)}job(t){return this.#n(`/v1/jobs/${encodeURIComponent(t)}`)}frontier(t,n={}){let r=new URLSearchParams;return n.limit&&r.set("limit",String(n.limit)),n.cursor&&r.set("cursor",n.cursor),this.#n(`/v1/jobs/${encodeURIComponent(t)}/frontier?${r}`)}results(t,n={}){let r=new URLSearchParams;return n.limit&&r.set("limit",String(n.limit)),n.cursor&&r.set("cursor",n.cursor),this.#n(`/v1/jobs/${encodeURIComponent(t)}/results?${r}`,uP(n))}async artifact(t,n,r={}){if(!/^artifact:[a-f0-9]{64}$/i.test(n))throw new TypeError("artifactId is invalid");let i=await this.#o(`/v1/jobs/${encodeURIComponent(t)}/artifacts/${n}`,uP(r)),o=i.headers.get("etag")??void 0;return{jobId:t,artifactId:n,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.#n(`/v1/jobs/${encodeURIComponent(t)}/cancel`,{method:"POST"})}resume(t){return this.#n(`/v1/jobs/${encodeURIComponent(t)}/resume`,{method:"POST"})}webhookDeliveries(t){return this.#n(`/v1/jobs/${encodeURIComponent(t)}/webhooks`)}upload(t){return this.#n("/v1/artifacts",{method:"POST",body:JSON.stringify(t)})}parse(t){return this.#n("/v1/parse",{method:"POST",body:JSON.stringify(t)})}extract(t){return this.#n("/v1/extract",{method:"POST",body:JSON.stringify(t)})}monitors(){return this.#n("/v1/monitors")}createMonitor(t){return this.#n("/v1/monitors",{method:"POST",body:JSON.stringify(t)})}monitorChecks(t,n=100){return this.#n(`/v1/monitors/${encodeURIComponent(t)}/checks?limit=${n}`)}setMonitorState(t,n){return this.#n(`/v1/monitors/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify({state:n})})}removeMonitor(t){return this.#n(`/v1/monitors/${encodeURIComponent(t)}`,{method:"DELETE"})}async#i(t,n,r,i){let o;try{({job:o}=await this.cancel(t))}catch(p){return{attempted:!0,trigger:n,jobId:t,outcome:"failed",error:yOe(p,"Web Context cancellation failed")}}let s=i.cancelConfirmationMs??2e3,a=Date.now()+(Number.isFinite(s)&&s>0?s:0),c=i.pollMs??500,l,d=async p=>{try{await r(p)}catch(f){l??=yOe(f,"Web Context progress listener failed during cancellation confirmation")}};for(await d(o);!_f(o.state)&&Date.now()<a;){await new Promise(f=>{setTimeout(f,Math.min(c,Math.max(0,a-Date.now())))});let p;try{({job:p}=await this.job(t))}catch{break}o=p,await d(o)}let u=_f(o.state)?kU(o,0):void 0;return{attempted:!0,trigger:n,jobId:t,outcome:o.state==="cancelled"?"cancelled":"requested",...u?{terminalProgress:u}:{},...l?{listenerError:l}:{}}}async waitForJob(t,n={}){let r=Date.now()+(n.timeoutMs??12e4),i=oOt(n.onProgress,t),o;try{for(;Date.now()<r;){if(n.signal?.aborted)throw o="abort",n.signal.reason;let{job:s}=await this.job(t);if(await i(s),_f(s.state))return s;await new Promise((a,c)=>{let l=setTimeout(a,n.pollMs??500);n.signal?.addEventListener("abort",()=>{clearTimeout(l),o="abort",c(n.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"?n.cancelOnAbort===!0:o==="timeout"?n.cancelOnTimeout===!0:!1;throw!o||!a?s:iOt(s,await this.#i(t,o,i,n))}}async scrapeAndWait(t,n={}){let r=await this.scrape(t),i=await this.waitForJob(r.job.jobId,n);if(i.state!=="completed"&&i.state!=="partial")throw Object.assign(new Error(`scrape job ended in ${i.state}`),{code:"JOB_NOT_COMPLETED",jobId:i.jobId,state:i.state});let o=await this.results(i.jobId,{limit:1}),s=o.items.find(c=>c.state==="completed"&&typeof c.artifactId=="string")??o.items.find(c=>typeof c.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 sOt}from"node:fs";function cOt(e=process.env){let t=e.XENO_WEB_CONTEXT_TOKEN?.trim();if(t)return t;let n=e.XENO_WEB_CONTEXT_TOKEN_FILE?.trim();if(n){let r=sOt(n,"utf8").trim();if(r)return r}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 qte(e=process.env){return new EU({baseUrl:e.XENO_WEB_CONTEXT_URL?.trim()||aOt,token:cOt(e)})}function vOe(e=process.env){return{client:new Ute(e),createRequest:e2({actor:{id:"xeno-agent-cli",kind:"agent"},scope:{kind:"local-profile",profileId:"pending-token-scope"},classification:"public",purposePrefix:"xeno-agent-cli:chat",budget:{durationMs:12e4,maxAttempts:3,maxConcurrency:4,maxBytes:1e7,maxPages:100,maxRedirects:8,maxProviderCostUsd:0}})}}var aOt,Ute,jte=we(()=>{"use strict";bOe();at();aOt="http://127.0.0.1:8080";Ute=class{constructor(t){this.env=t}env;client;tenantId;async search(t){return this.getClient().search(await this.bindTenant(t))}async scrapeAndWait(t,n){return this.getClient().scrapeAndWait(await this.bindTenant(t),n)}getClient(){return this.client??=qte(this.env),this.client}async bindTenant(t){this.tenantId??=this.getClient().account().then(r=>r.tenantId);let n=await this.tenantId;return{...t,scope:{kind:"tenant",tenantId:n}}}}});var IOe=we(()=>{"use strict"});function kOe(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 n=t.snapshot,r=o=>typeof o=="number"&&Number.isSafeInteger(o)&&o>=0,i=(o,s,a,c=!1)=>Array.isArray(o)&&o.every(l=>l&&typeof l=="object"&&!Array.isArray(l)&&typeof l[s]=="string"&&r(l[a])&&(!c||l.cost===null));return n.source==="local-runtime-journal"&&n.billingStatus==="unavailable"&&n.totalCost===null&&typeof n.observedAt=="string"&&Number.isFinite(Date.parse(n.observedAt))&&r(n.totalTokens)&&r(n.totalRequests)&&r(n.unmeasuredRequests)&&n.unmeasuredRequests<=n.totalRequests&&i(n.dailyUsage,"label","value")&&i(n.weeklyUsage,"label","value")&&i(n.monthlyUsage,"label","value")&&i(n.costByModel,"model","tokens",!0)&&i(n.topAgents,"name","tokens",!0)}var EOe=we(()=>{"use strict"});var SOe=we(()=>{"use strict"});function COe(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(n=>n&&typeof n=="object"&&["id","timestamp","action","actor","target","details"].every(r=>typeof n[r]=="string")&&Number.isFinite(Date.parse(n.timestamp)))}var xOe=we(()=>{"use strict"});function TOe(e){return!Vte(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&&!ROe(e.loadedModel)||e.models!==void 0&&(!Array.isArray(e.models)||e.models.length>1e3||!e.models.every(t=>Vte(t)&&ROe(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&&(!Vte(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 Vte,ROe,POe=we(()=>{"use strict";Vte=e=>!!e&&typeof e=="object"&&!Array.isArray(e),ROe=e=>typeof e=="string"&&e.length>0&&e.length<=512&&!/[\x00-\x1f\x7f]/.test(e)});var mUn,_Oe=we(()=>{"use strict";mUn=new TextEncoder});var $Oe=we(()=>{"use strict"});var BOe=we(()=>{"use strict"});var MOe=we(()=>{"use strict"});var NOe=we(()=>{"use strict"});var OOe=we(()=>{"use strict"});var DOe=we(()=>{"use strict";OOe()});var LOe=we(()=>{"use strict"});var QOe=we(()=>{"use strict"});var FOe=we(()=>{"use strict"});var lOt,UOe=we(()=>{"use strict";Wh();lOt=1024*1024});function mOt(e){return typeof e=="string"&&dOt.includes(e)}function qOe(e){return vo(e)?jn(e.clientId)&&jn(e.clientVersion)&&jn(e.instanceId)&&mOt(e.surface):!1}function VOe(e){return!vo(e)||!vo(e.protocol)||!vo(e.host)||!vo(e.storage)?!1:Number.isInteger(e.protocol.current)&&bOt(e.protocol.supported)&&jn(e.host.instanceId)&&jn(e.host.version)&&(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)&&qOe(e.surface)}function Hte(e){return!vo(e)||!jn(e.revision)||!Array.isArray(e.providers)?!1:e.providers.every(wOt)}function hOt(e){return!vo(e)||!vo(e.event)?!1:jn(e.id)&&Number.isInteger(e.sequence)&&typeof e.sequence=="number"&&e.sequence>=0&&jn(e.timestamp)&&jn(e.conversationId)&&jn(e.requestId)&&jn(e.type)&&jn(e.source)}function HOe(e){return!vo(e)||!Array.isArray(e.events)?!1:(e.nextSequence===null||typeof e.nextSequence=="number"&&Number.isInteger(e.nextSequence)&&e.nextSequence>=0)&&e.events.every(hOt)}function WOe(e){return!vo(e)||typeof e.success!="boolean"?!1:e.success?(e.status==="accepted"||e.status==="replayed")&&jn(e.conversationId)&&jn(e.requestId)&&jn(e.adapterId)&&vo(e.selection)&&jn(e.selection.providerId)&&jn(e.selection.catalogRevision):jn(e.code)&&jn(e.safeError)}function GOe(e){return!vo(e)||typeof e.success!="boolean"?!1:e.success?(e.status==="cancel_requested"||e.status==="replayed")&&jn(e.conversationId)&&jn(e.requestId):jn(e.code)&&jn(e.safeError)}function JOe(e){return vo(e)&&jn(e.id)&&typeof e.sequence=="number"&&Number.isInteger(e.sequence)&&e.sequence>0&&typeof e.timestamp=="number"&&Number.isFinite(e.timestamp)&&gOt(e.type)&&e.source==="host"&&e.schemaVersion===1&&e.redactionState==="safe"&&"payload"in e}function gOt(e){return typeof e=="string"&&fOt.includes(e)}function XOe(e,t,n){if(e.surface.surface!==t.surface||e.surface.instanceId!==t.instanceId)throw new eo("surface_mismatch",`Agent host acknowledged ${e.surface.surface}/${e.surface.instanceId} instead of ${t.surface}/${t.instanceId}.`);if(e.protocol.current<n.min||e.protocol.current>n.max||n.max<e.protocol.supported.min||n.min>e.protocol.supported.max)throw new eo("protocol_mismatch",`Agent host protocol ${e.protocol.current} is incompatible with client range ${n.min}-${n.max}.`)}function AOt(e){return!(!vo(e)||e.chatExecution!==void 0&&!pP(e.chatExecution)||e.durableResume!==void 0&&!pP(e.durableResume)||e.nativeTuiAttach!==void 0&&!pP(e.nativeTuiAttach)||e.reconciliation!==void 0&&!pP(e.reconciliation)||e.modelSwitchInPlace!==void 0&&!pP(e.modelSwitchInPlace)||e.resumeCompatibilityKey!==void 0&&typeof e.resumeCompatibilityKey!="string")}function pP(e){return vo(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 wOt(e){return vo(e)?jn(e.id)&&typeof e.kind=="string"&&uOt.includes(e.kind)&&jn(e.displayName)&&zOe(e.availability)&&vo(e.capabilities)&&(e.providerSession===void 0||AOt(e.providerSession))&&Array.isArray(e.models)&&e.models.every(yOt)&&jn(e.catalogRevision):!1}function yOt(e){return vo(e)&&jn(e.id)&&jn(e.displayName)&&zOe(e.availability)&&(e.reasoningOptions===void 0||Array.isArray(e.reasoningOptions)&&e.reasoningOptions.every(t=>vo(t)&&jn(t.id)&&jn(t.label)&&(t.runtimeModelId===void 0||jn(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 zOe(e){return e==="available"||e==="degraded"||e==="blocked"||e==="unavailable"}function bOt(e){return vo(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 jn(e){return typeof e=="string"&&e.trim().length>0}function vo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function SU(e){for(let t of IOt)for(let n of vOt)if(e===`${t}tool.${n}`)return n;return null}function iy(e,t){let n=e?.[t];return typeof n=="string"&&n.trim()?n:void 0}function CU(e){let t=e.event;return iy(t,"toolName")||iy(t,"tool")||iy(t,"name")||iy(t,"title")||iy(t,"kind")}function Rk(e){let t=e.event;return iy(t,"toolCallId")||iy(t,"tool_call_id")}function KOe(e){let t=e.event;for(let n of["rawInput","input","arguments","parameters","args"]){let r=t?.[n];if(r&&typeof r=="object"&&!Array.isArray(r))return r}}function YOe(e){let t=e.event;for(let n of["rawOutput","output","result","content"]){let r=t?.[n];if(typeof r=="string")return r.length>0?r:void 0;if(r!=null)try{let i=JSON.stringify(r);if(i&&i!=="{}"&&i!=="[]")return i}catch{}}}function xU(e){return e==="completed"?!0:e==="failed"||e==="cancelled"?!1:null}var xk,jOe,dOt,uOt,pOt,kUn,fOt,eo,vOt,IOt,Wh=we(()=>{"use strict";IOe();EOe();SOe();xOe();POe();_Oe();$Oe();Ck();BOe();MOe();NOe();DOe();LOe();QOe();FOe();UOe();xk=1,jOe=1,dOt=["standalone-desktop","hub-embed","shell-embed","embed-preview","panel-embed","headless-client"],uOt=["sdk-native","xeno-cloud","cli-app-server","cli-remote","acp"],pOt=["workspace.usage","workspace.audit","inference.request","workspace.schedule","workspace.backup","workspace.environment","account.request","workforce.request","workspace.notifications","workspace.rules","workspace.browser","workspace.browser.session","host.handshake","providers.list","providers.refresh","runtime.events.list","workspace.lifecycle.apply","state.workspaces.load","state.workspaces.save","state.conversations.load","state.conversations.save","state.conversations.delete","workspace.access.grant","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.resume","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"],kUn=new Set(pOt),fOt=["host.ready","provider.catalog.changed","state.workspaces.changed","runtime.event.appended","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"],eo=class extends Error{code;constructor(t,n){super(n),this.name="AgentHostProtocolError",this.code=t}};vOt=["started","updated","completed","failed","cancelled"],IOt=["","acp."]});function RU(e){let t=e.type.toLowerCase();if(!(t.includes("tool")||Rk(e))&&!(!t.includes("text")&&!t.includes("message")&&!t.includes("delta"))&&!(t.includes("complete")||t.includes("final")||t.includes("end")))for(let n of["delta","text","content","chunk"]){let r=e.event[n];if(typeof r=="string"&&r.length>0)return r}}var Wte=we(()=>{"use strict";Wh()});import{createHash as kOt}from"node:crypto";import{setTimeout as EOt}from"node:timers/promises";function xOt(e,t){return`subrun-${kOt("sha256").update(`${e}\0${t}`).digest("hex").slice(0,32)}`}async function ROt(e,t,n){return((await e.listRuntimeEvents({conversationId:t,subagentRunId:n,limit:500}))?.events??[]).map(i=>RU(i)??"").join("")}function TOt(e,t,n,r){let i=new Set,o=typeof r.onToolStart=="function"||typeof r.onToolEnd=="function",s=a=>{try{a()}catch{}};return async function(){if(!o)return;let c=await e.listRuntimeEvents({conversationId:t,subagentRunId:n,limit:500}).catch(()=>null);for(let l of c?.events??[]){let d=SU(String(l.type??""));if(!d)continue;let u=`${Rk(l)??l.id}:${d}`;if(i.has(u))continue;i.add(u);let p=CU(l)??"unknown";if(d==="started"&&r.onToolStart){let m=r.onToolStart;s(()=>m(p,KOe(l)??{}))}let f=xU(d);if(f!==null&&r.onToolEnd){let m=r.onToolEnd;s(()=>m(p,{success:f,output:YOe(l)??""}))}}}}function ZOe(e){let t=e.pollIntervalMs??250;return async n=>{let r=n.task,i=xOt(e.rootTraceId,r.id),o={lastTraceId:null,tokenUsage:{input:0,output:0,total:0},async run(s){let a=Math.max(1e3,e.deadline-Date.now()),c={parentConversationId:e.parentConversationId,...e.parentRequestId===void 0?{}:{parentRequestId:e.parentRequestId},parentAgentId:e.parentAgentId,childConversationId:i,childAgentId:r.role?`delegated-${r.role}`:"delegated-branch",workspaceId:e.workspaceId,teamId:e.teamId,objective:s,...r.role===void 0?{}:{role:r.role},policy:{maxRuntimeMs:a}},l=await e.client.createSubagentRun(c);if(!l?.success||!l.run)throw new Error(l?.safeError??"The Agent host refused to create a subagent run for this delegated branch.");let d=l.run.id;o.lastTraceId=d;let u=TOt(e.client,i,d,{onToolStart:n.onToolStart,onToolEnd:n.onToolEnd});for(;;){if(e.signal?.aborted){await e.client.cancelSubagentRun({runId:d}).catch(()=>{});let h=new Error("Delegated branch was cancelled.");throw h.name="AgentInterruptedError",h}let f=((await e.client.listSubagentRuns({parentConversationId:e.parentConversationId}))?.runs??[]).find(h=>h.id===d),m=String(f?.status??"");if(SOt.has(m)){if(COt.has(m))throw new Error(f?.error??`The delegated branch ended as '${m}' without reporting a reason.`);await u();let h=await ROt(e.client,i,d);if(h.length===0)throw new Error(`The delegated branch reported '${m}' but produced no readable output. Its runtime events carry no text for this run id.`);return h}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 EOt(t,void 0,{signal:e.signal})}}};return o}}var SOt,COt,eDe=we(()=>{"use strict";Wh();Wte();SOt=new Set(["completed","succeeded","failed","cancelled","error"]),COt=new Set(["failed","cancelled","error"])});import{execFile as tDe,execFileSync as Gte}from"node:child_process";import{promisify as nDe}from"node:util";import{createHash as POt}from"node:crypto";import{existsSync as _Ot,readFileSync as Jte,readlinkSync as $Ot}from"node:fs";import{hostname as oy}from"node:os";function PU(e){return Number.isInteger(e)&&e>0}function MOt(e){return POt("sha256").update(e).digest("hex")}function mP(e){let t=e?.trim().replaceAll("\\","/").toLowerCase();return t?`sha256:${MOt(t)}`:void 0}function TU(){if(process.platform==="linux")try{return Jte("/proc/sys/kernel/random/boot_id","utf8").trim()||void 0}catch{return}}function $f(e){if(typeof e!="number"||!PU(e))return"dead";try{return process.kill(e,0),"live"}catch(t){return t.code==="ESRCH"?"dead":"unknown"}}function Xte(e){let t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():null}function rDe(e){return["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",["$ErrorActionPreference = 'Stop'",`$items = @(Get-Process -Id @(${e.join(", ")}) -ErrorAction SilentlyContinue)`,"$out = @($items | ForEach-Object { $path = try { [string]$_.Path } catch { '' }; [pscustomobject]@{ pid = [int]$_.Id; startedAt = $_.StartTime.ToUniversalTime().ToString('o'); executable = $path } })","$out | ConvertTo-Json -Compress"].join("; ")]}function iDe(e){let t=new Map;try{if(!e)return t;let n=JSON.parse(e);for(let r of Array.isArray(n)?n:[n]){let i=Number(r.pid),o=Xte(String(r.startedAt??""));!PU(i)||!o||t.set(i,{pid:i,processStartedAt:o,hostname:oy(),...mP(r.executable)?{executableFingerprint:mP(r.executable)}:{},confidence:"observed"})}}catch{return t}return t}function NOt(e){if(!e.length)return new Map;try{return iDe(Gte("powershell.exe",rDe(e),{encoding:"utf8",windowsHide:!0,timeout:1e4,stdio:["ignore","pipe","ignore"]}).trim())}catch{return new Map}}function OOt(){if(fP)return fP;try{let e=Number.parseInt(Gte("getconf",["CLK_TCK"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim(),10);fP=Number.isFinite(e)&&e>0?e:100}catch{fP=100}return fP}function DOt(){try{let e=/^btime\s+(\d+)$/m.exec(Jte("/proc/stat","utf8"));return e?Number.parseInt(e[1]??"",10):null}catch{return null}}function LOt(e){try{let t=Jte(`/proc/${e}/stat`,"utf8"),n=t.lastIndexOf(")");if(n<0)return null;let r=t.slice(n+2).trim().split(/\s+/),i=Number(r[19]),o=DOt();if(!Number.isFinite(i)||o===null)return null;let s=new Date((o+i/OOt())*1e3).toISOString(),a;try{a=$Ot(`/proc/${e}/exe`)}catch{a=void 0}return{pid:e,processStartedAt:s,hostname:oy(),...TU()?{bootId:TU()}:{},...mP(a)?{executableFingerprint:mP(a)}:{},confidence:"observed"}}catch{return null}}function oDe(e){let t=new Map;if(process.platform==="linux"){for(let n of e){let r=LOt(n);r&&t.set(n,r)}return t}for(let n of e)try{let r=Gte("ps",["-p",String(n),"-o","lstart="],{encoding:"utf8",timeout:2e3,env:{...process.env,LC_ALL:"C"},stdio:["ignore","pipe","ignore"]}).trim(),i=Xte(r);if(!i)continue;t.set(n,{pid:n,processStartedAt:i,hostname:oy(),confidence:"observed"})}catch{continue}return t}function hP(e){let t=[...new Set(e.filter(PU))],n=t.includes(process.pid),r=n?t.filter(o=>o!==process.pid):t,i=process.platform==="win32"?NOt(r):oDe(r);return n&&i.set(process.pid,Gh()),i}function sDe(e){return hP([e]).get(e)??null}async function aDe(e,t){t?.throwIfAborted();let n=[...new Set(e.filter(PU))],r=n.filter(o=>o!==process.pid),i=new Map;if(process.platform==="win32"&&r.length)try{let o=await nDe(tDe)("powershell.exe",rDe(r),{encoding:"utf8",windowsHide:!0,timeout:1e4,maxBuffer:1048576,signal:t});i=iDe(o.stdout.trim())}catch{t?.throwIfAborted()}else if(process.platform==="linux")i=oDe(r);else if(process.platform!=="win32")for(let o of r){t?.throwIfAborted();try{let{stdout:s}=await nDe(tDe)("ps",["-p",String(o),"-o","lstart="],{encoding:"utf8",timeout:2e3,signal:t,env:{...process.env,LC_ALL:"C"},maxBuffer:4096}),a=Xte(s.trim());a&&i.set(o,{pid:o,processStartedAt:a,hostname:oy(),confidence:"observed"})}catch{t?.throwIfAborted()}}return t?.throwIfAborted(),n.includes(process.pid)&&i.set(process.pid,Gh()),i}function _U(e,t=new Date,n=!1){return(n?sDe(e):null)??{pid:e,processStartedAt:t.toISOString(),hostname:oy(),confidence:"degraded"}}function Gh(){let e=new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString();return{pid:process.pid,processStartedAt:e,hostname:oy(),...TU()?{bootId:TU()}:{},..._Ot(process.execPath)?{executableFingerprint:mP(process.execPath)}:{},confidence:"self"}}function Zo(e,t=sDe){if(e.hostname!==oy())return{status:"remote",expected:e,reason:"Process belongs to another host."};if($f(e.pid)==="dead")return{status:"dead",expected:e,reason:"Process ID is not live."};let n=t(e.pid);if(!n)return{status:"degraded",expected:e,reason:"Creation time could not be observed."};let r=Date.parse(e.processStartedAt),i=Date.parse(n.processStartedAt);return!Number.isFinite(r)||!Number.isFinite(i)||Math.abs(r-i)>BOt?{status:"mismatch",expected:e,observed:n,reason:"Process creation time does not match."}:e.bootId&&n.bootId&&e.bootId!==n.bootId?{status:"mismatch",expected:e,observed:n,reason:"Host boot identity does not match."}:e.executableFingerprint&&n.executableFingerprint&&e.executableFingerprint!==n.executableFingerprint?{status:"mismatch",expected:e,observed:n,reason:"Executable identity does not match."}:{status:"live",expected:e,observed:n}}var BOt,fP,Du=we(()=>{"use strict";BOt=3e3});import{createHash as QOt,randomBytes as FOt}from"node:crypto";import{chmodSync as UOt,existsSync as qOt,mkdirSync as lDe,readFileSync as jOt,renameSync as VOt,unlinkSync as dDe,writeFileSync as HOt}from"node:fs";import{dirname as WOt,join as gP}from"node:path";function uDe(){return pl()}function GOt(e){return QOt("sha256").update(e).digest("hex").slice(0,16)}function xn(){return gP(uDe(),"daemon")}function zte(){return gP(xn(),"daemon.json")}function pDe(){return gP(xn(),"daemon.lock")}function Tk(){return gP(xn(),"daemon.log")}function Kte(){let e=GOt(uDe());return process.platform==="win32"?{transport:"named-pipe",endpoint:`\\\\.\\pipe\\xeno-agent-daemon-${e}`}:{transport:"unix-socket",endpoint:gP(xn(),"daemon.sock")}}function $U(){lDe(xn(),{recursive:!0})}function fDe(){return FOt(32).toString("base64url")}function cDe(e){if(process.platform!=="win32")try{UOt(e,384)}catch{}}function Yte(){try{let e=zte(),t=jOt(e,"utf8"),n=JSON.parse(t);if(!n||n.schemaVersion!==1||n.protocolVersion!==1||n.transport!=="named-pipe"&&n.transport!=="unix-socket"||typeof n.endpoint!="string"||typeof n.authToken!="string"||!Number.isSafeInteger(n.pid)||typeof n.startedAt!="string"||typeof n.cliVersion!="string"||typeof n.logPath!="string")throw new Error("daemon state schema is invalid");return n}catch(e){if(e.code==="ENOENT")return null;throw new Error(`Daemon state is corrupt or unreadable: ${e instanceof Error?e.message:String(e)}`)}}function mDe(e){let t=zte();lDe(WOt(t),{recursive:!0});let n=`${t}.${process.pid}.${Date.now()}.tmp`;HOt(n,JSON.stringify(e,null,2)+`
2902
2902
  `,{encoding:"utf8",mode:384}),cDe(n),VOt(n,t),cDe(t)}function BU(){try{dDe(zte())}catch{}}function hDe(){if(process.platform==="win32")return;let{endpoint:e}=Kte();if(qOt(e))try{dDe(e)}catch{}}function wa(e){return $f(e)!=="dead"}var Io=we(()=>{"use strict";$A();Du()});import{existsSync as JOt,linkSync as XOt,mkdirSync as zOt,readFileSync as KOt,rmSync as ene,statSync as YOt,writeFileSync as ZOt}from"node:fs";import{hostname as gDe}from"node:os";import{dirname as eDt}from"node:path";import{randomUUID as tDt}from"node:crypto";function nDt(){return new Date().toISOString()}function Zte(e){try{return JSON.parse(KOt(e,"utf8"))}catch{return null}}function rDt(e){if(e.hostname!==gDe())return!0;let t=Date.parse(e.acquiredAt);if(Number.isFinite(t)&&Date.now()-t<3e4)return!0;if(!wa(e.pid))return!1;if(e.processIdentity){let n=Zo(e.processIdentity);return n.status==="live"||n.status==="degraded"||n.status==="remote"}return!0}function ADe(e,t){zOt(eDt(e),{recursive:!0});let n=`${e}.${process.pid}.${tDt()}.tmp`;ZOt(n,JSON.stringify(t,null,2)+`
2903
2903
  `,{encoding:"utf8",flag:"wx"});try{XOt(n,e)}finally{ene(n,{force:!0})}}function iDt(e){try{return Date.now()-YOt(e).mtimeMs<3e4}catch{return!1}}function oDt(e,t){return e?.pid===t.pid&&e.hostname===t.hostname&&e.processStartedAt===t.processStartedAt&&e.acquiredAt===t.acquiredAt}function AP(e,t){return Object.assign(new Error(`${e} is already locked ${t}.`),{code:"CONTROL_PLANE_LOCK_BUSY"})}function Tc(e){return e instanceof Error&&"code"in e&&e.code==="CONTROL_PLANE_LOCK_BUSY"}function sDt(e,t,n){try{ADe(e,t)}catch(r){throw r.code==="EEXIST"?AP(n,"by another contender"):r}}function aDt(e,t){let n=Zte(e);n?.pid!==t.pid||n.hostname!==t.hostname||n.processStartedAt!==t.processStartedAt||ene(e,{force:!0})}function Lo(e,t,n){let r=nDt(),i=Gh(),o={schemaVersion:1,name:t,pid:process.pid,hostname:gDe(),processStartedAt:i.processStartedAt,processIdentity:i,version:n,acquiredAt:r,updatedAt:r};try{ADe(e,o)}catch(s){if(s.code!=="EEXIST")throw s;let c=Zte(e);if(c&&rDt(c))throw AP(t,`by PID ${c.pid} on ${c.hostname}`);if(c){if(!oDt(Zte(e),c))throw AP(t,"while ownership was changing")}else{if(!JOt(e))throw AP(t,"while ownership was changing");if(iDt(e))throw AP(t,"by an owner whose record is still being published")}ene(e,{force:!0}),sDt(e,o,t)}return{record:o,release:()=>{aDt(e,o)}}}var Lu=we(()=>{"use strict";Io();Du()});import{createHash as EDe,randomBytes as cDt,randomUUID as SDe}from"node:crypto";import{closeSync as CDe,existsSync as rne,fstatSync as lDt,fsyncSync as dDt,mkdirSync as ine,openSync as xDe,readFileSync as nne,readSync as uDt,renameSync as pDt,writeFileSync as RDe}from"node:fs";import{cpus as fDt}from"node:os";import{dirname as TDe,isAbsolute as mDt,join as $k,resolve as hDt}from"node:path";function yP(e,t,n=1,r=Number.MAX_SAFE_INTEGER){let i=typeof e=="number"?e:Number.parseInt(String(e??""),10);return Number.isFinite(i)?Math.min(r,Math.max(n,Math.trunc(i))):t}function wDt(e,t,n=0,r=Number.MAX_SAFE_INTEGER){let i=typeof e=="number"?e:Number(e);return Number.isFinite(i)?Math.min(r,Math.max(n,i)):t}function Pk(e,t){return t===void 0?e:Math.min(e,t)}function wP(e,t){return{maxConcurrency:Pk(e.maxConcurrency,t?.maxConcurrency),maxCredentialConcurrency:Pk(e.maxCredentialConcurrency,t?.maxCredentialConcurrency),maxRequestsPerWindow:Pk(e.maxRequestsPerWindow,t?.maxRequestsPerWindow),maxTokensPerWindow:Pk(e.maxTokensPerWindow,t?.maxTokensPerWindow),windowMs:t?.windowMs===void 0?e.windowMs:Math.max(1e3,t.windowMs)}}function yDt(e={}){let t=e.env??process.env,n=Math.max(1,e.cpuCount??fDt().length),r=Math.min(Math.max(1,n-2),gDt),i=yP(t.XENO_WORKFLOW_GLOBAL_CONCURRENCY,r,1,tne),s=t.XENO_WORKFLOW_TRUSTED_CONCURRENCY_OVERRIDE==="1"?i:Math.min(r,i);s=Pk(s,e.user?.globalConcurrency),s=Pk(s,e.managed?.globalConcurrency),s=yP(s,r,1,tne);let a={maxConcurrency:Math.min(s,8),maxCredentialConcurrency:Math.min(s,4),maxRequestsPerWindow:120,maxTokensPerWindow:2e6,windowMs:6e4},c=wP(a,e.user?.providerDefault),l=wP(c,e.managed?.providerDefault),d=new Set([...Object.keys(e.user?.providers??{}),...Object.keys(e.managed?.providers??{})]),u=Object.fromEntries([...d].map(f=>[f,wP(wP(l,e.user?.providers?.[f]),e.managed?.providers?.[f])])),p=(f,m,h=1,g=Number.MAX_SAFE_INTEGER)=>{let A=m,w=e.user?.[f],y=e.managed?.[f];return typeof w=="number"&&(A=Math.min(A,w)),typeof y=="number"&&(A=Math.min(A,y)),yP(A,m,h,g)};return{schemaVersion:1,productHardConcurrency:tne,globalConcurrency:s,perRunConcurrency:p("perRunConcurrency",s,1,s),perParentConcurrency:p("perParentConcurrency",s,1,s),reservedPrioritySlots:Math.min(2,Math.max(0,s-1)),maxQueueLength:p("maxQueueLength",4096,1,65536),maxQueueWaitMs:p("maxQueueWaitMs",5*6e4,1e3,1440*6e4),maxAttemptsPerLogicalChild:p("maxAttemptsPerLogicalChild",3,1,100),maxAttemptsPerRun:p("maxAttemptsPerRun",1e3,1,1e4),maxReservedTokens:p("maxReservedTokens",4e6,1,Number.MAX_SAFE_INTEGER),maxReservedCostUsd:wDt(Math.min(e.user?.maxReservedCostUsd??500,e.managed?.maxReservedCostUsd??500),500,.01,1e6),leaseTtlMs:p("leaseTtlMs",4e3,2e3,5*6e4),handoffTtlMs:Math.max(p("leaseTtlMs",4e3,2e3,5*6e4),p("handoffTtlMs",6e4,2e3,10*6e4)),heartbeatIntervalMs:p("heartbeatIntervalMs",1e3,250,6e4),maxStarvationMs:p("maxStarvationMs",3e4,1e3,60*6e4),providerDefault:l,providers:u}}function bDe(e,t){if(!rne(e)){if(t)throw new si("WORKFLOW_GOVERNOR_UNAVAILABLE",`Resource policy file not found: ${e}`);return}try{let n=JSON.parse(nne(e,"utf8"));if(!n||typeof n!="object"||Array.isArray(n))throw new Error("policy root must be an object");return n}catch(n){throw new si("WORKFLOW_GOVERNOR_UNAVAILABLE",`Resource policy is invalid: ${e}: ${n instanceof Error?n.message:String(n)}`)}}function bDt(e=process.env){let t=TDe(xn()),n=e.XENO_WORKFLOW_RESOURCE_POLICY?.trim(),r=e.XENO_MANAGED_WORKFLOW_RESOURCE_POLICY?.trim(),i=a=>mDt(a)?a:hDt(a),o=bDe(n?i(n):$k(t,"resource-policy.json"),!!n),s=r?bDe(i(r),!0):void 0;return yDt({env:e,user:o,managed:s})}function oi(e){return new Date(e).toISOString()}function vDt(e){return{schemaVersion:1,revision:0,nextFencingToken:1,updatedAt:oi(e),permits:[],queue:[],attempts:[],usage:[],providerRates:[],effects:[]}}function IDt(e){let t=e,n=p=>!!(p&&typeof p=="object"&&!Array.isArray(p)),r=p=>typeof p=="string"&&p.length>0&&p.length<=512,i=p=>typeof p=="string"&&Number.isFinite(Date.parse(p)),o=p=>n(p)&&Number.isInteger(p.pid)&&Number(p.pid)>0&&r(p.hostname)&&i(p.processStartedAt),s=p=>n(p)&&r(p.permitId)&&r(p.requestId)&&r(p.operationId)&&r(p.runId)&&r(p.providerId)&&r(p.logicalChildId)&&r(p.attemptId)&&r(p.idempotencyKey)&&Number.isInteger(p.fencingToken)&&Number(p.fencingToken)>0&&o(p.owner)&&i(p.acquiredAt)&&i(p.heartbeatAt)&&i(p.expiresAt)&&Number.isFinite(p.reservedTokens)&&Number(p.reservedTokens)>=0&&Number.isFinite(p.reservedCostUsd)&&Number(p.reservedCostUsd)>=0&&(p.handoff===void 0||n(p.handoff)&&o(p.handoff.target)&&i(p.handoff.startedAt)&&i(p.handoff.deadlineAt))&&(p.claimedAt===void 0||i(p.claimedAt)),a=p=>n(p)&&r(p.requestId)&&r(p.operationId)&&r(p.runId)&&r(p.providerId)&&r(p.logicalChildId)&&r(p.attemptId)&&r(p.idempotencyKey)&&o(p.owner)&&i(p.enqueuedAt)&&i(p.updatedAt),c=p=>n(p)&&r(p.runId)&&r(p.logicalChildId)&&r(p.attemptId)&&r(p.idempotencyKey)&&r(p.state)&&i(p.startedAt),l=p=>n(p)&&r(p.runId)&&Number.isFinite(p.tokens)&&Number(p.tokens)>=0&&Number.isFinite(p.costUsd)&&Number(p.costUsd)>=0&&Number.isInteger(p.attempts)&&Number(p.attempts)>=0&&i(p.updatedAt),d=p=>n(p)&&r(p.providerId)&&i(p.timestamp)&&Number.isFinite(p.tokens)&&Number(p.tokens)>=0,u=p=>n(p)&&r(p.effectKey)&&r(p.idempotencyKey)&&r(p.permitId)&&Number.isInteger(p.fencingToken)&&Number(p.fencingToken)>0&&r(p.state)&&i(p.claimedAt);return!!(t&&t.schemaVersion===1&&Number.isInteger(t.revision)&&Number(t.revision)>=0&&Number.isInteger(t.nextFencingToken)&&Number(t.nextFencingToken)>0&&i(t.updatedAt)&&Array.isArray(t.permits)&&t.permits.every(s)&&Array.isArray(t.queue)&&t.queue.every(a)&&Array.isArray(t.attempts)&&t.attempts.every(c)&&Array.isArray(t.usage)&&t.usage.every(l)&&Array.isArray(t.providerRates)&&t.providerRates.every(d)&&Array.isArray(t.effects)&&t.effects.every(u))}function kDt(e,t){ine(TDe(e),{recursive:!0});let n=`${e}.${process.pid}.${SDe()}.tmp`,r=xDe(n,"wx",384);try{RDe(r,JSON.stringify(t,null,2)+`
2904
2904
  `,"utf8"),dDt(r)}finally{CDe(r)}pDt(n,e)}function EDt(e,t,n){let r=Date.parse(e.requestedAt??""),i=Number.isFinite(r)?r:t,o=Date.parse(e.queueDeadlineAt??"");return{requestedAt:oi(i),deadlineAt:oi(Number.isFinite(o)?Math.min(o,i+n):i+n)}}function PDe(e,t){return wP(e.providerDefault,e.providers[t])}function vDe(e,t,n){let r=Math.max(0,t-Date.parse(e.enqueuedAt));return ADt[e.priorityClass]+Math.floor(r/n.maxStarvationMs)*1001}function SDt(e,t,n){return[...e].sort((r,i)=>vDe(i,t,n)-vDe(r,t,n)||Date.parse(r.enqueuedAt)-Date.parse(i.enqueuedAt)||r.requestId.localeCompare(i.requestId))}function IDe(e,t){return e.pid===t.pid&&e.hostname===t.hostname&&e.processStartedAt===t.processStartedAt}function _k(e){return Number.isFinite(e)?Math.max(0,Number(e)):0}function kDe(e,t,n,r){let i=e.permits;if(i.length>=n.globalConcurrency)return{code:"WORKFLOW_CONCURRENCY_LIMIT",reason:"global_concurrency"};if(!(t.priorityClass==="control"||t.priorityClass==="foreground"||t.priorityClass==="reconciliation"||t.priorityClass==="terminal")&&i.length>=Math.max(0,n.globalConcurrency-n.reservedPrioritySlots))return{code:"WORKFLOW_CONCURRENCY_LIMIT",reason:"reserved_priority_capacity"};let s=Math.min(n.perRunConcurrency,yP(t.runConcurrencyLimit,n.perRunConcurrency,1,n.globalConcurrency));if(i.filter(b=>b.runId===t.runId).length>=s)return{code:"WORKFLOW_CONCURRENCY_LIMIT",reason:"run_concurrency"};if(t.parentId&&i.filter(b=>b.parentId===t.parentId).length>=n.perParentConcurrency)return{code:"WORKFLOW_CONCURRENCY_LIMIT",reason:"parent_concurrency"};let a=PDe(n,t.providerId);if(i.filter(b=>b.providerId===t.providerId).length>=a.maxConcurrency)return{code:"WORKFLOW_CONCURRENCY_LIMIT",reason:"provider_concurrency"};if(t.credentialFingerprint&&i.filter(b=>b.providerId===t.providerId&&b.credentialFingerprint===t.credentialFingerprint).length>=a.maxCredentialConcurrency)return{code:"WORKFLOW_CONCURRENCY_LIMIT",reason:"credential_concurrency"};if(i.some(b=>b.logicalChildId===t.logicalChildId))return{code:"WORKFLOW_CONCURRENCY_LIMIT",reason:"logical_child_active"};let c=new Set(e.attempts.filter(b=>b.logicalChildId===t.logicalChildId).map(b=>b.attemptId));if(!c.has(t.attemptId)&&c.size>=n.maxAttemptsPerLogicalChild)return{code:"WORKFLOW_ATTEMPT_LIMIT",reason:"logical_child_attempt_limit"};let l=new Set(e.attempts.filter(b=>b.runId===t.runId).map(b=>b.attemptId)),d=Math.min(n.maxAttemptsPerRun,yP(t.runAttemptLimit,n.maxAttemptsPerRun,1,n.maxAttemptsPerRun));if(!l.has(t.attemptId)&&l.size>=d)return{code:"WORKFLOW_ATTEMPT_LIMIT",reason:"run_attempt_limit"};let u=_k(t.reservedTokens);if(i.reduce((b,v)=>b+v.reservedTokens,0)+u>n.maxReservedTokens)return{code:"WORKFLOW_TOKEN_LIMIT",reason:"global_token_reservation"};let f=_k(t.reservedCostUsd);if(i.reduce((b,v)=>b+v.reservedCostUsd,0)+f>n.maxReservedCostUsd)return{code:"WORKFLOW_COST_LIMIT",reason:"global_cost_reservation"};let h=e.usage.find(b=>b.runId===t.runId),g=i.filter(b=>b.runId===t.runId).reduce((b,v)=>b+v.reservedTokens,0);if(t.runTokenLimit!==void 0&&(h?.tokens??0)+g+u>t.runTokenLimit)return{code:"WORKFLOW_TOKEN_LIMIT",reason:"run_token_limit"};let A=i.filter(b=>b.runId===t.runId).reduce((b,v)=>b+v.reservedCostUsd,0);if(t.runCostLimitUsd!==void 0&&(h?.costUsd??0)+A+f>t.runCostLimitUsd)return{code:"WORKFLOW_COST_LIMIT",reason:"run_cost_limit"};let w=r-a.windowMs,y=e.providerRates.filter(b=>b.providerId===t.providerId&&Date.parse(b.timestamp)>=w&&(!t.credentialFingerprint||b.credentialFingerprint===t.credentialFingerprint));return y.length>=a.maxRequestsPerWindow?{reason:"provider_request_rate"}:y.reduce((b,v)=>b+v.tokens,0)+u>a.maxTokensPerWindow?{reason:"provider_token_rate"}:{}}function CDt(e){for(let[t,n]of Object.entries({requestId:e.requestId,operationId:e.operationId,runId:e.runId,providerId:e.providerId,logicalChildId:e.logicalChildId,attemptId:e.attemptId,idempotencyKey:e.idempotencyKey}))if(typeof n!="string"||!n.trim()||n.length>512)throw new si("WORKFLOW_GOVERNOR_UNAVAILABLE",`Invalid resource request field: ${t}.`);if(e.credentialFingerprint&&!/^(?:cred_)?sha256_[a-f0-9]{32,64}$/i.test(e.credentialFingerprint))throw new si("WORKFLOW_GOVERNOR_UNAVAILABLE","credentialFingerprint must be a scoped SHA-256 fingerprint.")}function Jh(e,t){let n=String(e??"default").trim().toLowerCase().split(/[/:]/,1)[0]||"default",r=t?.trim()?EDe("sha256").update(t.trim().toLowerCase()).digest("hex").slice(0,16):"default";return`${n}@${r}`}function one(e){let t=EDe("sha256");return t.update(e.salt),t.update("\0"),t.update(e.providerId),t.update("\0"),t.update(e.endpoint?.trim().toLowerCase()??""),t.update("\0"),t.update(e.credential),`cred_sha256_${t.digest("hex")}`}function sne(e=$k(xn(),"governor")){let t=$k(e,"credential-salt.bin");if(ine(e,{recursive:!0}),rne(t))return nne(t);let n=cDt(32);try{return RDe(t,n,{flag:"wx",mode:384}),n}catch{return nne(t)}}function Bk(e,t=process.env,n){let r=e.split("@",1)[0]?.toLowerCase(),o=(r==="anthropic"||r==="claude"?["ANTHROPIC_API_KEY","XENO_API_KEY"]:r==="openai"||r==="gpt"?["OPENAI_API_KEY","XENO_API_KEY"]:r==="google"||r==="gemini"?["GOOGLE_API_KEY","GEMINI_API_KEY","XENO_API_KEY"]:["XENO_API_KEY","ANTHROPIC_API_KEY","OPENAI_API_KEY","GOOGLE_API_KEY","GEMINI_API_KEY"]).map(s=>t[s]?.trim()).find(Boolean);return o?one({providerId:e,endpoint:n,credential:o,salt:sne()}):void 0}function MU(e){return{XENO_RESOURCE_PERMIT_ID:e.permitId,XENO_RESOURCE_FENCING_TOKEN:String(e.fencingToken),XENO_RESOURCE_OPERATION_ID:e.operationId,XENO_RESOURCE_IDEMPOTENCY_KEY:e.idempotencyKey}}function NU(e=process.env){let t=e.XENO_RESOURCE_PERMIT_ID?.trim(),n=Number.parseInt(e.XENO_RESOURCE_FENCING_TOKEN??"",10);return t&&Number.isInteger(n)&&n>0?{permitId:t,fencingToken:n}:null}function Xh(e,t,n=process.env){if(n.XENO_RESOURCE_OPERATION_ID?.trim()!==e)return;let r=NU(n);if(!t||!r||t.permitId!==r.permitId||t.fencingToken!==r.fencingToken)throw new si("WORKER_LEASE_EXPIRED","Worker state write rejected because its fencing token is stale.");new ai().assertFence(r.permitId,r.fencingToken)}var tne,gDt,wDe,yDe,si,ADt,ai,Bf=we(()=>{"use strict";Ei();hk();Io();Lu();Du();tne=64,gDt=16,wDe=16*1024*1024,yDe=15*6e4,si=class extends Error{constructor(n,r){super(r);this.code=n;this.name="WorkflowResourceError"}code},ADt={control:1e3,foreground:900,reconciliation:850,terminal:800,"app-server":700,workflow:500,background:400,scheduled:300};ai=class{policy;rootDir;ledgerPath;lockPath;now;owner;fault;constructor(t={}){this.rootDir=t.rootDir??$k(xn(),"governor"),this.ledgerPath=$k(this.rootDir,"resource-ledger.json"),this.lockPath=$k(this.rootDir,"resource-ledger.lock"),this.policy=t.policy??bDt(),this.now=t.now??Date.now,this.owner=t.owner??Gh,this.fault=t.fault,ine(this.rootDir,{recursive:!0})}acquire(t){CDt(t);let n=0,r=this.withLedger((a,c)=>{this.cleanupExpired(a,c);let l=a.permits.find(v=>v.requestId===t.requestId||v.attemptId===t.attemptId);if(l)return n=a.permits.length,{value:{status:"active",permit:l,reason:"attempt_already_active"},changed:!0};let d=EDt(t,c,this.policy.maxQueueWaitMs);if(c>Date.parse(d.deadlineAt))return{value:{status:"rejected",code:"WORKFLOW_QUEUE_EXPIRED",reason:"Queued work exceeded its deadline."},changed:!1};let u=a.queue.find(v=>v.requestId===t.requestId);if(u&&c>Date.parse(u.queueDeadlineAt??d.deadlineAt))return a.queue=a.queue.filter(v=>v.requestId!==t.requestId),{value:{status:"rejected",code:"WORKFLOW_QUEUE_EXPIRED",reason:"Queued work exceeded its deadline."},changed:!0};if(!u&&a.queue.length>=this.policy.maxQueueLength)return{value:{status:"rejected",code:"WORKFLOW_QUEUE_FULL",reason:"The host workflow queue is full."},changed:!1};let p=t.owner??this.owner(),f=u?{...u,...t,owner:u.owner,updatedAt:oi(c)}:{...t,owner:p,requestedAt:d.requestedAt,queueDeadlineAt:d.deadlineAt,enqueuedAt:oi(c),updatedAt:oi(c)};u?a.queue=a.queue.map(v=>v.requestId===f.requestId?f:v):a.queue.push(f);let m=SDt(a.queue,c,this.policy),h,g={};for(let v of m){let I=kDe(a,v,this.policy,c);if(v.requestId===f.requestId&&(g=I),!I.reason){h=v;break}}if(g.code==="WORKFLOW_ATTEMPT_LIMIT"||g.code==="WORKFLOW_TOKEN_LIMIT"||g.code==="WORKFLOW_COST_LIMIT")return a.queue=a.queue.filter(v=>v.requestId!==f.requestId),{value:{status:"rejected",code:g.code,reason:g.reason??"resource_limit"},changed:!0};if(!h||h.requestId!==f.requestId){let v=a.permits.map(R=>Date.parse(R.expiresAt)).filter(Number.isFinite).sort((R,k)=>R-k)[0],I=PDe(this.policy,f.providerId),E=a.providerRates.filter(R=>R.providerId===f.providerId&&(!f.credentialFingerprint||R.credentialFingerprint===f.credentialFingerprint)).map(R=>Date.parse(R.timestamp)+I.windowMs).filter(R=>Number.isFinite(R)&&R>c).sort((R,k)=>R-k)[0],x=[v,E].filter(R=>typeof R=="number").sort((R,k)=>R-k)[0];return{value:{status:"queued",request:f,reason:g.reason??"waiting_for_fair_turn",...x?{estimatedEligibleAt:oi(x)}:{}},changed:!0}}let A=kDe(a,f,this.policy,c);if(A.reason)return A.code==="WORKFLOW_ATTEMPT_LIMIT"||A.code==="WORKFLOW_TOKEN_LIMIT"||A.code==="WORKFLOW_COST_LIMIT"?(a.queue=a.queue.filter(v=>v.requestId!==f.requestId),{value:{status:"rejected",code:A.code,reason:A.reason},changed:!0}):{value:{status:"queued",request:f,reason:A.reason},changed:!0};let w=oi(c),y={permitId:`permit_${SDe()}`,requestId:f.requestId,operationId:f.operationId,surface:f.surface,priorityClass:f.priorityClass,runId:f.runId,...f.parentId?{parentId:f.parentId}:{},providerId:f.providerId,...f.credentialFingerprint?{credentialFingerprint:f.credentialFingerprint}:{},logicalChildId:f.logicalChildId,attemptId:f.attemptId,idempotencyKey:f.idempotencyKey,fencingToken:a.nextFencingToken++,owner:f.owner,acquiredAt:w,heartbeatAt:w,expiresAt:oi(c+this.policy.leaseTtlMs),reservedTokens:_k(f.reservedTokens),reservedCostUsd:_k(f.reservedCostUsd),lastDurableSequence:0};a.queue=a.queue.filter(v=>v.requestId!==f.requestId),a.permits.push(y),n=a.permits.length;let b=a.attempts.find(v=>v.attemptId===f.attemptId);return b?Object.assign(b,{state:"active",permitId:y.permitId,operationId:f.operationId,endedAt:void 0,outcome:void 0,refusedClaim:void 0}):a.attempts.push({runId:f.runId,operationId:f.operationId,logicalChildId:f.logicalChildId,attemptId:f.attemptId,idempotencyKey:f.idempotencyKey,state:"active",permitId:y.permitId,startedAt:w}),a.providerRates.push({providerId:f.providerId,...f.credentialFingerprint?{credentialFingerprint:f.credentialFingerprint}:{},timestamp:w,tokens:y.reservedTokens}),this.fault?.("acquire.before_commit"),{value:{status:"acquired",permit:y},changed:!0,afterCommit:()=>this.fault?.("acquire.after_commit")}}),i=r.status==="rejected"?r.code:r.status==="acquired"?"admitted":r.reason;Gr("xeno.workflow.admission_results",1,{component:"resource_governor",provider:t.providerId,state:r.status,reason:i,...r.status==="rejected"?{error_code:r.code}:{}}),(i==="provider_request_rate"||i==="provider_token_rate"||i==="provider_concurrency"||i==="credential_concurrency")&&Gr("xeno.workflow.provider_throttles",1,{component:"resource_governor",provider:t.providerId,reason:i});let o=Date.parse((r.status==="queued"?r.request.requestedAt:t.requestedAt)??""),s=r.status==="acquired"||r.status==="active"?Date.parse(r.permit.acquiredAt):this.now();return Number.isFinite(o)&&Number.isFinite(s)&&Is("xeno.workflow.queue_wait_ms",Math.max(0,s-o),{component:"resource_governor",provider:t.providerId,state:r.status}),n>0&&Is("xeno.workflow.active_concurrency",n,{component:"resource_governor",provider:t.providerId}),r}heartbeat(t){return this.withLedger((n,r)=>{let i=this.currentPermit(n,t.permitId,t.fencingToken,r),o=t.owner??this.owner();if(!IDe(i.owner,o))throw new si("WORKER_IDENTITY_MISMATCH","Permit heartbeat came from a different worker identity.");return i.heartbeatAt=oi(r),i.expiresAt=oi(r+this.policy.leaseTtlMs),i.lastDurableSequence=Math.max(i.lastDurableSequence,Math.max(0,t.lastDurableSequence??0)),{value:{...i},changed:!0}})}assertFence(t,n){return this.withLedger((r,i)=>({value:{...this.currentPermit(r,t,n,i)},changed:!1}))}beginHandoff(t){return this.withLedger((n,r)=>{let i=this.currentPermit(n,t.permitId,t.fencingToken,r);if(i.claimedAt)return{value:{...i},changed:!1};let o=Math.max(Date.parse(i.expiresAt),r+this.policy.handoffTtlMs);return i.handoff={target:{...t.target},startedAt:oi(r),deadlineAt:oi(o)},i.owner={...t.target},i.expiresAt=oi(o),{value:{...i},changed:!0}})}transfer(t,n,r){let i=this.withLedger((o,s)=>{this.cleanupExpired(o,s);let a=l=>{let d=o.attempts.find(u=>u.permitId===t);return d?(d.refusedClaim={pid:r.pid,code:l.code,at:oi(s)},{value:{error:l},changed:!0}):{value:{error:l},changed:!1}},c=o.permits.find(l=>l.permitId===t);if(!c||c.fencingToken!==n){let l=o.attempts.find(d=>d.permitId===t);return a(l?.outcome==="WORKER_HANDOFF_EXPIRED"||l?.outcome==="WORKER_HANDOFF_ABANDONED"?new si("WORKER_HANDOFF_EXPIRED",`The worker hand-off window closed (${l.outcome} at ${l.endedAt??"unknown"}) before this worker claimed its permit.`):new si("WORKER_LEASE_EXPIRED","The worker lease is missing, expired, or fenced out."))}if(c.handoff){let l=c.handoff.target;if(l.pid!==r.pid||l.hostname!==r.hostname)return a(new si("WORKER_IDENTITY_MISMATCH","The permit hand-off is bound to a different worker process."))}else if(c.claimedAt&&!IDe(c.owner,r))return a(new si("WORKER_IDENTITY_MISMATCH","The permit is already claimed by another worker process."));return c.owner=r,delete c.handoff,c.claimedAt??=oi(s),c.heartbeatAt=oi(s),c.expiresAt=oi(s+this.policy.leaseTtlMs),{value:{permit:{...c}},changed:!0}});if("error"in i)throw i.error;return i.permit}settle(t){return this.withLedger((n,r)=>{let i=n.permits.find(c=>c.permitId===t.permitId);if(!i)return{value:!1,changed:!1};if(i.fencingToken!==t.fencingToken||Date.parse(i.expiresAt)<=r)throw new si("WORKER_LEASE_EXPIRED","The worker fencing token is stale.");n.permits=n.permits.filter(c=>c.permitId!==i.permitId);let o=n.attempts.find(c=>c.attemptId===i.attemptId);o&&Object.assign(o,{state:"settled",endedAt:oi(r),outcome:t.outcome});let s=n.usage.find(c=>c.runId===i.runId),a={runId:i.runId,tokens:(s?.tokens??0)+_k(t.actualTokens),costUsd:(s?.costUsd??0)+_k(t.actualCostUsd),attempts:(s?.attempts??0)+1,updatedAt:oi(r)};return n.usage=[...n.usage.filter(c=>c.runId!==i.runId),a],{value:!0,changed:!0}})}settleOperation(t,n,r=0,i=0){let o=this.snapshot().permits.find(s=>s.operationId===t);return o?this.settle({permitId:o.permitId,fencingToken:o.fencingToken,outcome:n,actualTokens:r,actualCostUsd:i}):!1}cancelQueued(t){return this.withLedger(n=>{let r=n.queue.some(i=>i.requestId===t);return n.queue=n.queue.filter(i=>i.requestId!==t),{value:r,changed:r}})}claimEffect(t){return this.withLedger((n,r)=>{let i=this.currentPermit(n,t.permitId,t.fencingToken,r),o=n.effects.find(s=>s.effectKey===t.effectKey||s.idempotencyKey===i.idempotencyKey);return o?{value:o.permitId===i.permitId&&o.fencingToken===i.fencingToken&&o.state==="claimed",changed:!1}:(n.effects.push({effectKey:t.effectKey,idempotencyKey:i.idempotencyKey,permitId:i.permitId,fencingToken:i.fencingToken,state:"claimed",claimedAt:oi(r)}),{value:!0,changed:!0})})}commitEffect(t){return this.withLedger((n,r)=>{this.currentPermit(n,t.permitId,t.fencingToken,r);let i=n.effects.find(o=>o.effectKey===t.effectKey);return!i||i.permitId!==t.permitId||i.fencingToken!==t.fencingToken?{value:!1,changed:!1}:i.state==="committed"?{value:!0,changed:!1}:(i.state="committed",i.committedAt=oi(r),{value:!0,changed:!0})})}reconcile(t){let n=this.withLedger((r,i)=>{let o=[...r.permits],s=[...r.queue],a=t??hP(o.map(w=>w.owner.pid)),c=new Set,l=new Set,d=new Set;for(let w of o){let y=Zo(w.owner,b=>a.get(b)??null);if(w.handoff){let b=y.status==="mismatch"&&y.observed&&Date.parse(y.observed.processStartedAt)>Date.parse(w.owner.processStartedAt);y.status==="dead"||b?d.add(w.permitId):y.status!=="live"&&l.add(w.permitId);continue}y.status==="mismatch"&&c.add(w.permitId),(y.status==="degraded"||y.status==="remote")&&l.add(w.permitId)}this.cleanupExpired(r,i,c,d);let u=new Set(r.permits.map(w=>w.permitId)),p=o.filter(w=>!u.has(w.permitId)&&!c.has(w.permitId)),f=o.filter(w=>c.has(w.permitId)),m=new Set(r.queue.map(w=>w.requestId)),h=s.filter(w=>!m.has(w.requestId)),g=new Map(r.effects.map(w=>[w.permitId,w.fencingToken]));for(let w of o)g.set(w.permitId,w.fencingToken);let A=new Map(r.attempts.filter(w=>w.state==="expired"&&w.permitId&&(w.outcome==="WORKER_HANDOFF_EXPIRED"||w.outcome==="WORKER_HANDOFF_ABANDONED")&&i-Date.parse(w.endedAt??"")<=yDe).map(w=>[w.attemptId,{...w.operationId?{operationId:w.operationId}:{},permitId:w.permitId,fencingToken:g.get(w.permitId)??0,outcome:w.outcome,...w.endedAt?{endedAt:w.endedAt}:{},...w.refusedClaim?{refusedClaim:{...w.refusedClaim}}:{}}]));return{value:{expiredPermits:p,handoffFailures:A,identityMismatches:f,expiredQueue:h,livePermits:r.permits.length,degradedPermits:r.permits.filter(w=>l.has(w.permitId)).length},changed:p.length>0||f.length>0||h.length>0}});return Is("xeno.worker.live_leases",n.livePermits,{component:"resource_governor",operation:"reconcile"}),Is("xeno.worker.degraded_leases",n.degradedPermits,{component:"resource_governor",operation:"reconcile"}),n.expiredPermits.length>0&&Gr("xeno.worker.lease_expirations",n.expiredPermits.length,{component:"resource_governor",operation:"reconcile"}),n.identityMismatches.length>0&&Gr("xeno.worker.identity_mismatches",n.identityMismatches.length,{component:"resource_governor",operation:"reconcile"}),n}snapshot(){return this.withLedger(t=>({value:structuredClone(t),changed:!1}))}recentHandoffFailureOperations(){return this.withLedger((t,n)=>({value:[...new Set(t.attempts.filter(r=>r.operationId&&r.state==="expired"&&(r.outcome==="WORKER_HANDOFF_EXPIRED"||r.outcome==="WORKER_HANDOFF_ABANDONED")&&n-Date.parse(r.endedAt??"")<=yDe).map(r=>r.operationId))],changed:!1}))}cleanupExpired(t,n,r=new Set,i=new Set){let o=new Map(t.permits.filter(a=>Date.parse(a.expiresAt)<=n||r.has(a.permitId)||i.has(a.permitId)).map(a=>[a.permitId,a]));if(o.size>0){t.permits=t.permits.filter(a=>!o.has(a.permitId));for(let a of t.attempts)a.permitId&&o.has(a.permitId)&&a.state==="active"&&(a.state="expired",a.endedAt=oi(n),a.outcome=r.has(a.permitId)?"WORKER_IDENTITY_MISMATCH":i.has(a.permitId)?"WORKER_HANDOFF_ABANDONED":o.get(a.permitId)?.handoff?"WORKER_HANDOFF_EXPIRED":"WORKER_LEASE_EXPIRED")}t.queue=t.queue.filter(a=>Date.parse(a.queueDeadlineAt??a.updatedAt)>n);let s=Math.max(this.policy.providerDefault.windowMs,...Object.values(this.policy.providers).map(a=>a.windowMs??0));if(t.providerRates=t.providerRates.filter(a=>Date.parse(a.timestamp)>n-s),t.attempts.length>2e4){let a=t.attempts.filter(l=>l.state==="active"),c=t.attempts.filter(l=>l.state!=="active").slice(-Math.max(0,2e4-a.length));t.attempts=[...c,...a]}t.effects.length>2e4&&(t.effects=t.effects.slice(-2e4)),t.usage.length>1e4&&(t.usage=t.usage.slice(-1e4))}currentPermit(t,n,r,i){let o=t.permits.find(s=>s.permitId===n);if(!o||Date.parse(o.expiresAt)<=i||o.fencingToken!==r)throw new si("WORKER_LEASE_EXPIRED","The worker lease is missing, expired, or fenced out.");return o}readLedger(t){if(!rne(this.ledgerPath))return vDt(t);let n;try{n=xDe(this.ledgerPath,"r");let r=lDt(n).size;if(!Number.isSafeInteger(r)||r>wDe)throw new Error(`ledger exceeds the ${wDe} byte limit`);let i=Buffer.alloc(r),o=0;for(;o<r;){let c=uDt(n,i,o,r-o,o);if(c===0)throw new Error("Resource ledger changed during read");o+=c}let s=i.toString("utf8"),a=JSON.parse(s);if(!IDt(a))throw new Error("Unsupported resource ledger schema.");return a}catch(r){throw new si("WORKFLOW_GOVERNOR_UNAVAILABLE",`Resource ledger is unreadable and was not overwritten: ${r instanceof Error?r.message:String(r)}`)}finally{n!==void 0&&CDe(n)}}withLedger(t){let n=Date.now()+5e3,r=new Int32Array(new SharedArrayBuffer(4)),i,o;for(;!i&&Date.now()<=n;)try{i=Lo(this.lockPath,"workflow-resource-governor",be)}catch(s){if(o=s,!(s instanceof Error)||!s.message.includes("is already locked"))break;Atomics.wait(r,0,0,10)}if(!i)throw new si("WORKFLOW_GOVERNOR_UNAVAILABLE",o instanceof Error?o.message:String(o??"Resource governor lock unavailable."));try{let s=this.now(),a=this.readLedger(s),c=t(a,s);return c.changed&&(a.revision+=1,a.updatedAt=oi(s),kDt(this.ledgerPath,a)),c.afterCommit?.(),c.value}finally{i.release()}}}});import{createHash as xDt,randomUUID as RDt}from"node:crypto";import{setTimeout as TDt}from"node:timers/promises";function PDt(){return`delegation-${Date.now().toString(36)}-${RDt().slice(0,8)}`}function _Dt(e){return async t=>(await Rd({cwd:e.cwd,apiKey:e.apiKey,baseURL:e.baseURL,model:e.model,...e.fallbackModels?{fallbackModels:e.fallbackModels}:{},...e.effort?{effort:e.effort}:{},maxTokens:t.task.maxTokens,maxIterations:t.task.maxIterations,parentSystemPrompt:e.parentSystemPrompt,parentExecutionMode:e.parentExecutionMode,subagentRole:t.task.role,permissionEngine:e.permissionEngine,toolRegistry:e.createToolRegistry?.(),...e.auditLogger?{session:{auditLogger:e.auditLogger}}:{},onIteration:t.onIteration,onToolStart:t.onToolStart,onToolWillExecute:t.onToolWillExecute,onToolEnd:t.onToolEnd})).agent}async function $Dt(e){for(;;){if(e.signal?.aborted){e.governor.cancelQueued(e.request.requestId);let n=new Error("Delegated branch admission was cancelled.");throw n.name="AgentInterruptedError",n}let t=e.governor.acquire(e.request);if(t.status==="acquired")return t.permit;if(t.status==="active")throw new si("WORKFLOW_CONCURRENCY_LIMIT","Delegated branch attempt is already active.");if(t.status==="rejected")throw new si(t.code,t.reason);if(Date.now()>=e.deadline)throw e.governor.cancelQueued(e.request.requestId),new si("WORKFLOW_QUEUE_EXPIRED","Delegated branch exceeded its admission deadline.");await TDt(50,void 0,{signal:e.signal})}}function BDt(e,t,n){let r=e.run.bind(e),i=!1,o=a=>{i||(i=!0,t.settle({permitId:n.permitId,fencingToken:n.fencingToken,outcome:a,actualTokens:e.tokenUsage.total}))};e.run=async a=>{try{let c=await r(a);return o("completed"),c}catch(c){throw o(c instanceof Error&&c.name==="AgentInterruptedError"?"cancelled":"failed"),c}};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 bP(e){let t=new ai,n=e.rootTraceId??PDt(),r=Jh(e.model,e.baseURL),i=e.apiKey?one({providerId:r,endpoint:e.baseURL,credential:e.apiKey,salt:sne()}):Bk(r,process.env,e.baseURL),o=e.createBranchAgent??_Dt(e),s=Date.now()+e.timeoutMs,a=async c=>{let l=c.task,d=`${n}:${l.id}`,u=`${d}:attempt-1`,p=xDt("sha256").update(`${n}\0${l.id}\0${l.prompt}`).digest("hex"),f=await $Dt({governor:t,request:{requestId:`admit:${d}:attempt-1`,operationId:d,surface:"delegated-branch",priorityClass:"foreground",runId:n,parentId:n,providerId:r,...i?{credentialFingerprint:i}:{},logicalChildId:d,attemptId:u,idempotencyKey:p,reservedTokens:l.maxTokens,runConcurrencyLimit:e.branchPolicy?.maxConcurrentBranches,runAttemptLimit:e.branchPolicy?.roles?.length,runTokenLimit:e.maxTotalTokens,queueDeadlineAt:new Date(s).toISOString()},deadline:s,signal:l.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 si("WORKFLOW_CONCURRENCY_LIMIT","Duplicate delegated branch execution was suppressed.");try{let m=await o(c);return t.commitEffect({permitId:f.permitId,fencingToken:f.fencingToken,effectKey:`delegated:${f.operationId}`}),BDt(m,t,f)}catch(m){throw t.settle({permitId:f.permitId,fencingToken:f.fencingToken,outcome:"branch_creation_failed"}),m}};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 PF({...e,rootTraceId:n,createBranchAgent:ZOe({...e.hostDelegation,rootTraceId:n,deadline:s,...e.signal===void 0?{}:{signal:e.signal}})})}return PF({...e,rootTraceId:n,createBranchAgent:a})}var _De=we(()=>{"use strict";at();eDe();Bf();at()});import{renameSync as MDt}from"node:fs";function sy(e,t){for(let n=0;;n++)try{MDt(e,t);return}catch(r){if(n>=10||!["EPERM","EACCES","EBUSY"].includes(r.code??""))throw r;Atomics.wait(NDt,0,0,Math.min(25,(n+1)*5))}}var NDt,OU=we(()=>{"use strict";NDt=new Int32Array(new SharedArrayBuffer(4))});import{closeSync as ODt,fstatSync as DDt,openSync as LDt,readSync as QDt}from"node:fs";function Mk(e){let t;try{t=LDt(e,"r")}catch(n){if(n.code==="ENOENT")return{text:"",startOffset:0,endOffset:0,totalBytes:0};throw n}try{let n=DDt(t);if(!n.isFile()||!Number.isSafeInteger(n.size))throw new Error("Output preview requires a regular file of supported size.");let r=n.size,i=Math.max(0,r-FDt),o=Buffer.allocUnsafe(r-i),s=0;for(;s<o.length;){let d=QDt(t,o,s,o.length-s,i+s);if(d===0)throw new Error("Output changed during preview; retry.");s+=d}let a=0;if(i>0)for(;a<Math.min(3,o.length)&&(o[a]&192)===128;)a++;let c=i+a,l;try{l=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(o.subarray(a),{stream:!0})}catch{throw new Error("Output preview contains invalid UTF-8; inspect the persisted output as bytes.")}return{text:l,startOffset:c,endOffset:c+Buffer.byteLength(l,"utf8"),totalBytes:r}}finally{ODt(t)}}var FDt,DU=we(()=>{"use strict";FDt=64*1024});import*as Pc from"node:fs/promises";import*as zh from"node:path";import{homedir as JDt,platform as XDt,release as zDt}from"node:os";import{spawnSync as eLt}from"node:child_process";async function UDt(e){await Pc.mkdir(e,{recursive:!0})}async function ci(e,t){let n=zh.dirname(e);await UDt(n);let r=Math.random().toString(36).substring(2,15),i=`${e}.tmp.${process.pid}.${r}`;try{await Pc.writeFile(i,t),await VDt(i,e)}finally{try{await Pc.unlink(i)}catch{}}}async function VDt(e,t){for(let n=0;;n+=1)try{await Pc.rename(e,t);return}catch(r){let i=r.code,o=jDt[n];if(process.platform!=="win32"||!i||!qDt.has(i)||o===void 0)throw r;await new Promise(s=>setTimeout(s,o))}}function BDe(e,t){try{return JSON.parse(e)}catch{return t}}function ane(e){let t=HDt(e);return{frontmatter:t.frontmatter,content:t.content.trim()}}function HDt(e){let t=e.replace(/^\uFEFF/,"");if(!t.startsWith("---"))return{frontmatter:{},content:e};let n=t.search(/\r?\n/);if(n<0||t.slice(0,n).trim()!=="---")return{frontmatter:{},content:e};let r=t.slice(n+(t[n]==="\r"?2:1)),i=r.match(/(?:^|\r?\n)---[ \t]*(?:\r?\n|$)/);if(!i||i.index===void 0)throw new Error("YAML frontmatter is not closed.");let o=r.slice(0,i.index),s=i[0],a=i.index+s.length;return{frontmatter:MDe(o),content:r.slice(a)}}function MDe(e){let t={},n=e.split(/\r?\n/);for(let r=0;r<n.length;r+=1){let i=n[r];if(!i.trim()||i.trimStart().startsWith("#"))continue;if(/^\s/.test(i))throw new Error(`Unexpected indentation at line ${r+1}.`);let o=GDt(i,r+1);if(o.key==="<<")throw new Error("YAML merge keys are not supported.");if(o.value!==""){t[o.key]=NDe(o.value,r+1);continue}let s=WDt(n,r+1);t[o.key]=s.value,r=s.nextIndex-1}return t}function WDt(e,t){let n=[],r=t;for(;r<e.length;r+=1){let o=e[r];if(!o.trim()){n.push(o);continue}if(!/^\s/.test(o))break;n.push(o.replace(/^ {2}/,""))}let i=n.filter(o=>o.trim()&&!o.trimStart().startsWith("#"));return i.length===0?{value:{},nextIndex:r}:i.every(o=>o.trimStart().startsWith("- "))?{value:i.map((o,s)=>NDe(o.trimStart().slice(2),t+s+1)),nextIndex:r}:{value:MDe(n.join(`
@@ -3177,9 +3177,9 @@ ${o}`;break;case"retry":z7e(o)&&(n[i]=o);break;case"id":K7e(o)&&(n[i]=o);break;c
3177
3177
  `,s),c=a===-1?e.length:a,l=NNe(e,s,c,o);if(oNt(i,e,l,s,c,a===-1?"end":"hard",n,r),a===-1)break;o.add(a),o.add(a+1),s=a+1}return{text:e,columns:n,tabSize:r,lines:i,graphemeOffsets:[...o].sort((a,c)=>a-c)}}function Ite(e,t,n){let r=tP(n.maxVisibleRows,1),i=Nu(e.graphemeOffsets,t,"backward"),o=dNt(e.lines,i),s=DNe(o,i),a=Math.max(0,e.lines.length-r),c=yk(n.viewportStartLine??0,0,a);return o.index<c?c=o.index:o.index>=c+r&&(c=o.index-r+1),c=yk(c,0,a),{projection:e,visibleLines:e.lines.slice(c,c+r),viewportStartLine:c,cursor:{offset:i,visualLine:o.index,visibleLine:o.index-c,cellColumn:s}}}function MNe(e,t,n){let r=tP(n.columns,1),i=tP(n.tabSize??4,4),o=new Set([0,e.length]),s=NNe(e,0,e.length,o),a=[...o].sort((y,b)=>y-b),c=Nu(a,t,"backward"),l=vte(0,e,0,e.length,"end",s,Number.MAX_SAFE_INTEGER,i);if(l.spans.length===0)return{renderText:"",cellWidth:0,viewportStartOffset:0,viewportEndOffset:0,cursorOffset:c,cursorCellColumn:0};let d=Nu(a,n.viewportStartOffset??0,"backward"),u=DNe(l,c),p=$Ne(l.spans,d),f=l.spans[p]?.startCell??l.cellWidth;for(c<d&&(p=$Ne(l.spans,c),f=l.spans[p]?.startCell??l.cellWidth);p<l.spans.length&&u-f>=r;)p+=1,f=l.spans[p]?.startCell??l.cellWidth;let m=l.spans[p]?.startOffset??e.length,h=m,g="",A=0,w=0;for(let y=p;y<l.spans.length;y+=1){let b=l.spans[y],v=b.endCell-b.startCell,I=r-A;if(I<=0)break;let E=v<=I?v:1;if(v>I&&A>0)break;let x=v<=I?b.renderText:"?";if(g+=x,A+=E,h=b.endOffset,b.endOffset<=c&&(w=A),v>I)break}return c<=m&&(w=0),w=yk(w,0,Math.max(0,r-1)),{renderText:g,cellWidth:A,viewportStartOffset:m,viewportEndOffset:h,cursorOffset:c,cursorCellColumn:w}}function kte(e,t,n){let r=e.cursor.visualLine+t,i=e.projection.lines[r];if(!i)return null;let o=Math.max(0,Math.floor(n??e.cursor.cellColumn));return{offset:uNt(i,o),preferredCellColumn:o}}function bk(e,t){if(e.length===0)return 0;let n=yk(t,0,e[e.length-1]??0),r=LNe(e,n);return r<e.length&&e[r]===n,e[Math.max(0,r-1)]??0}function Vh(e,t){if(e.length===0)return 0;let n=e[e.length-1]??0,r=yk(t,0,n),i=fNt(e,r);return e[Math.min(e.length-1,i)]??n}function Nu(e,t,n="backward"){if(e.length===0)return 0;let r=e[e.length-1]??0,i=yk(t,0,r),o=LNe(e,i);return e[o]===i?i:n==="forward"?e[Math.min(e.length-1,o)]??r:e[Math.max(0,o-1)]??0}function vk(e,t){let n=Math.max(0,Math.floor(Number.isFinite(t)?t:0));if(e.length<=n)return e;let r=pNt(e);return e.slice(0,Nu(r,n,"backward"))}function oNt(e,t,n,r,i,o,s,a){if(n.length===0){e.push(vte(e.length,t,r,i,o,[],s,a));return}let c=0;for(;c<n.length;){let l=0,d=c,u=-1,p=!1;for(;d<n.length;){let A=n[d],w=ONe(A.text,l,s,a);if(l+w.cellWidth>s&&d>c)break;l+=w.cellWidth,d+=1,lNt(A.text)?p&&(u=d):p=!0}let f=d;d<n.length&&u>c&&(f=u),f<=c&&(f=c+1);let m=n[c]?.startOffset??r,h=n[f-1]?.endOffset??m,g=f<n.length?"soft":o;e.push(vte(e.length,t,m,h,g,n.slice(c,f),s,a)),c=f}}function vte(e,t,n,r,i,o,s,a){let c=0,l=o.map(d=>{let u=ONe(d.text,c,s,a),p={startOffset:d.startOffset,endOffset:d.endOffset,renderText:u.renderText,startCell:c,endCell:c+u.cellWidth};return c=p.endCell,p});return{index:e,startOffset:n,endOffset:r,sourceText:t.slice(n,r),renderText:l.map(d=>d.renderText).join(""),cellWidth:c,breakKind:i,spans:l}}function NNe(e,t,n,r){if(t>=n)return[];let i=[];for(let o of BNe.segment(e.slice(t,n))){let s=t+o.index,a=s+o.segment.length;r.add(s),r.add(a),i.push({text:o.segment,startOffset:s,endOffset:a})}return i}function ONe(e,t,n,r){if(e===" "){let s=r-t%r,a=Math.max(1,Math.min(s,n-Math.min(t,n-1)));return{renderText:" ".repeat(a),cellWidth:a}}let i=cNt(e);if(i)return _Ne(i,Re(i),n,t);let o=sNt(e);return _Ne(e,o,n,t)}function _Ne(e,t,n,r){return t<=n-r?{renderText:e,cellWidth:t}:r>0?{renderText:e,cellWidth:t}:t<=n?{renderText:e,cellWidth:t}:{renderText:"?",cellWidth:1}}function sNt(e){if(aNt(e))return 2;let t=e.replace(rNt,"");return t.length===0?0:Re(t)}function aNt(e){if(nNt.test(e))return!0;let t=[...e].map(n=>n.codePointAt(0)??0);return t.length===2&&t.every(n=>n>=127462&&n<=127487)}function cNt(e){let t=[...e].map(r=>r.codePointAt(0)??0);if(t.length!==1)return null;let n=t[0];return n<=31?`^${String.fromCharCode(n+64)}`:n===127?"^?":n>=128&&n<=159?`<0x${n.toString(16).toUpperCase().padStart(2,"0")}>`:null}function lNt(e){return iNt.test(e)}function dNt(e,t){for(let n=0;n<e.length;n+=1){let r=e[n];if(r.breakKind==="soft"){if(t<r.endOffset)return r;continue}if(t<=r.endOffset)return r}return e[e.length-1]}function DNe(e,t){if(t<=e.startOffset)return 0;for(let n of e.spans){if(t<=n.startOffset||t<n.endOffset)return n.startCell;if(t===n.endOffset)return n.endCell}return e.cellWidth}function $Ne(e,t){for(let n=0;n<e.length;n+=1)if(e[n].endOffset>t)return n;return e.length}function uNt(e,t){if(e.spans.length===0||t<=0)return e.startOffset;for(let n of e.spans){if(t<=n.startCell)return n.startOffset;if(t<n.endCell){let r=t-n.startCell,i=n.endCell-t;return r<=i||n.endOffset===e.endOffset&&e.breakKind==="soft"?n.startOffset:n.endOffset}}return e.breakKind==="soft"?e.spans[e.spans.length-1]?.startOffset??e.startOffset:e.endOffset}function pNt(e){let t=new Set([0,e.length]);for(let n of BNe.segment(e))t.add(n.index),t.add(n.index+n.segment.length);return[...t].sort((n,r)=>n-r)}function tP(e,t){return Number.isFinite(e)?Math.max(1,Math.floor(e)):t}function yk(e,t,n){return Number.isFinite(e)?Math.max(t,Math.min(n,Math.floor(e))):t}function LNe(e,t){let n=0,r=e.length;for(;n<r;){let i=n+Math.floor((r-n)/2);(e[i]??Number.POSITIVE_INFINITY)<t?n=i+1:r=i}return n}function fNt(e,t){let n=0,r=e.length;for(;n<r;){let i=n+Math.floor((r-n)/2);(e[i]??Number.POSITIVE_INFINITY)<=t?n=i+1:r=i}return n}var mNt=new Set(["TaskCreate","TaskGet","TaskList","TaskUpdate"]);function rP(e){return mNt.has(e)}function QNe(e){if(!/^\d+$/u.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null}function UNe(e,t){let n=QNe(e.id),r=QNe(t.id);return n!==null&&r!==null?n-r:e.id.localeCompare(t.id)}function FNe(e){return e.status==="in_progress"?0:e.status==="pending"&&(e.blockedBy?.length??0)===0?1:e.status==="pending"?2:3}function hNt(e,t){let n=FNe(e)-FNe(t);if(n!==0)return n;if(e.status==="completed"&&t.status==="completed"){let r=Date.parse(e.updatedAt??""),i=Date.parse(t.updatedAt??"");if(Number.isFinite(r)&&Number.isFinite(i)&&r!==i)return i-r}return UNe(e,t)}function Ete(e,t){let n=Math.max(0,Math.floor(t)),r=e.map(o=>({...o,blockedBy:o.blockedBy?.slice()??[]}));if(n===0)return{visible:[],hidden:r};if(r.length<=n)return{visible:r.sort(UNe),hidden:[]};let i=r.sort(hNt);return{visible:i.slice(0,n),hidden:i.slice(n)}}function pU(e){let t=e.find(r=>r.status==="in_progress");return t?.activeForm?.trim()||t?.subject?.trim()||null}function qNe(e,t,n){if(e==="TaskGet"||e==="TaskList")return"Checking Todo...";let r=typeof t.activeForm=="string"?t.activeForm.trim():"";return r?`${r}...`:pU(n)?`${pU(n)}...`:"Updating Todo..."}Aa();Ei();Ns();Yo();function fU(e,t){let n=Math.max(0,Math.floor(e)),r=(t??"").replace(/[\p{Cc}\p{Cs}\u202a-\u202e\u2066-\u2069]/gu,"").replace(/\s+/gu," ").trim();if(!r||n<8)return"\u2500".repeat(n);let i=` ${nv(r,n-4)} `;return"\u2500".repeat(Math.max(0,n-Re(i)))+i}var jNe="Usage: /memory context [--full] [--json] [--ndjson] [--raw] [--copy] [--stats] [--no-context] [--quiet] [--sessions 1-10] [--tokens >=120] [--chars >=200]",VNe="/memory context [--full] [--json] [--ndjson] [--raw] [--copy] [--stats] [--no-context] [--quiet] [--sessions N] [--tokens N] [--chars N]",mU=[{id:"session",label:"Session"},{id:"auth-model",label:"Auth & Model"},{id:"context",label:"Context & Files"},{id:"agents",label:"Agents & Background"},{id:"tools",label:"Tools, MCP & Skills"},{id:"governance",label:"Governance"},{id:"customization",label:"Customization"},{id:"diagnostics",label:"Diagnostics"}],Ou=[{name:"/help",description:"Show help and available commands",category:"diagnostics"},{name:"/login",description:"Sign in, inspect auth status, or store an API key",category:"auth-model"},{name:"/logout",description:"Sign out and clear local XENO credentials",category:"auth-model"},{name:"/model",description:"Show or switch the AI model",category:"auth-model"},{name:"/effort",usage:"/effort [low|medium|high|xhigh|max|ultracode]",description:"Set model effort or ultracode workflow orchestration",category:"auth-model"},{name:"/fast",description:"Use the fast model profile",category:"auth-model"},{name:"/provider",usage:"/provider [list|resolve|host|use|sessions|status|native|detach|reattach|stop|reconcile]",description:"Inspect SDK routing or manage shared-host provider sessions",category:"auth-model"},{name:"/profile",usage:"/profile [list|create|switch|delete|show]",description:"Manage config profiles",category:"auth-model"},{name:"/clear",description:"Clear the chat history",category:"session"},{name:"/exit",description:"Exit XENO AGENT",category:"session"},{name:"/quit",description:"Exit XENO AGENT",category:"session"},{name:"/sessions",description:"List saved sessions",category:"session"},{name:"/rename",usage:"/rename [name]",description:"Name this session; shown on the input border and used by peers to reach it",category:"session"},{name:"/resume",description:"Resume a saved session",category:"session"},{name:"/save",description:"Save current session",category:"session"},{name:"/export",description:"Export conversation to file or JSON",category:"session"},{name:"/checkpoint",usage:"/checkpoint | /checkpoint list | /checkpoint restore <id>",description:"Create, list, or restore checkpoints",category:"session"},{name:"/rewind",usage:"/rewind [checkpoint-id]",description:"List checkpoints or restore one while saving the current branch",category:"session"},{name:"/compact",usage:"/compact [status]",description:"Compress conversation context",category:"session"},{name:"/goal",usage:"/goal set <condition> [--max-tokens N]|status|clear|pause|resume",description:"Manage persistent goal mode",category:"session"},{name:"/loop",usage:"/loop [status]|start <kind> [activity]|stop [id]|pause [id]|resume [id]",description:"Manage durable loops",category:"session"},{name:"/copy",usage:"/copy [last|block|diff]",description:"Copy the last answer, fenced block, or diff",category:"session"},{name:"/open",description:"Open the current workspace folder in Explorer/Finder",category:"context"},{name:"/tokens",description:"Show token usage and cost",category:"context"},{name:"/usage",description:"Inspect session and weekly token limits, duration, and costs",category:"context"},{name:"/context",description:"Show context usage and token fuel gauge",category:"context"},{name:"/memory",description:"Show and edit memory levels",category:"context"},{name:"/memory context",usage:VNe,description:"Inspect prompt memory context and diagnostics",category:"context"},{name:"/remember",description:"Add text to project memory",category:"context"},{name:"/import",description:"Import a session from Claude Code, Codex or opencode and continue it here",category:"context"},{name:"/workspace",description:"Inspect workspace info, files, and dependencies",category:"context"},{name:"/ctx-viz",description:"Inspect system prompt, tools, and message context usage; --tools lists the live registry",category:"context"},{name:"/diff",usage:"/diff [working|staged|turn [turn-id]|commit <ref>] [--preview-only]",description:"Capture or reopen a durable Git diff artifact",category:"context"},{name:"/artifacts",usage:"/artifacts [publish <file.html> [--cloud]|open [id]|pages|promote <id> [--share]|share <id> [--off]|cloud|comments <id> [text]|list|show|revisions|comment|approve|changes-requested|reject|apply|restore]",description:"Rendered pages (publish, open, comment) and the durable artifact review queue",category:"context"},{name:"/agents",description:"Inspect running agents, specialist profiles, or custom definitions",category:"agents"},{name:"/handoff",usage:"/handoff [status|acquire|prepare|claim|complete|release|<agent>]",description:"Transfer live session execution custody to another terminal or host (deprecated: /handoff <agent>)",category:"agents"},{name:"/processes",description:"List, inspect, attach, and stop background tasks",category:"agents"},{name:"/tasks",description:"Inspect the current structured task plan",category:"agents"},{name:"/delegate",usage:"/delegate [<target> <task> | on|off|status|team|mode|roles]",description:"Send a task to a sub-agent or toggle persona delegation workflow",category:"agents"},{name:"/peers",usage:"/peers [send|ask|note <to> <text> | inbox | sent | status <id> | accept|refuse|cancel <id> | policy]",description:"Discover detached sub-agents and send work between sessions",category:"agents"},{name:"/message",usage:"/message <to> <text>",description:"Delegate a task to another XENO Agent session by name",category:"agents"},{name:"/inbox",description:"Messages other sessions sent to this one",category:"agents"},{name:"/mcp",description:"Manage MCP servers, prompts, and resources",category:"tools"},{name:"/skills",usage:"/skills [list|inspect|enable|disable]",description:"Manage markdown skills",category:"tools"},{name:"/plugin",usage:"/plugin [list|install|uninstall]",description:"Manage plugins",category:"tools"},{name:"/test",usage:"/test [generate <file>|coverage]",description:"Run, generate, or inspect project tests",category:"tools"},{name:"/deploy",usage:"/deploy [target]",description:"Deploy project targets",category:"tools"},{name:"/babysit",usage:"/babysit <command>",description:"Watch a process and analyze its output",category:"tools"},{name:"/workflow",usage:"/workflow <task>|list|run <name> [input]",description:"Create, list, or run workflow definitions",category:"tools"},{name:"/workflows",usage:"/workflows",description:"Show workflow runs, phases, children, artifacts, and definitions",category:"tools"},{name:"/listen",description:"Start system dictation / voice typing",category:"tools"},{name:"/terminal-setup",description:"Install terminal Shift+Enter integration",category:"tools"},{name:"/approvals",description:"Update XENO approvals for tool actions",category:"governance"},{name:"/approved-tools",usage:"/approved-tools [list|remove|clear]",description:"Inspect or revoke remembered tool approvals",category:"governance"},{name:"/mode",description:"Switch runtime mode",category:"governance"},{name:"/review",description:"AI code review of recent git changes",category:"governance"},{name:"/pr-comments",description:"Fetch and render GitHub PR comments",category:"governance"},{name:"/audit",usage:"/audit [tail N|stats|trace [trace-id] [--replay]|export [path]] [--json]",description:"Tail, inspect, replay, or export audit events",category:"governance"},{name:"/eval",description:"Inspect agent evaluation reports and summaries",category:"governance"},{name:"/color",description:"Show or switch the UI color theme",category:"customization"},{name:"/theme",description:"Alias for /color",category:"customization"},{name:"/vim",description:"Toggle Vim-style prompt input mode",category:"customization"},{name:"/style",description:"Set output style",category:"customization"},{name:"/settings",description:"Interactive settings and configuration toggles",category:"customization"},{name:"/config",usage:"/config [show|paths|set|unset] [--json]",description:"Inspect or edit local user/project config",category:"customization"},{name:"/keybindings",usage:"/keybindings [list|validate|path|<action>] [--json]",description:"Inspect user-owned terminal keybindings and conflicts",category:"customization"},{name:"/environment",usage:"/environment [--json] [--safe-mode]",description:"Inspect effective rules, profiles, skills, hooks, plugins, MCP, policies, tools, and context costs",category:"diagnostics"},{name:"/status",description:"Open interactive status, session, and workspace modal",category:"diagnostics"},{name:"/stats",description:"View coding activity heatmap, streaks, and token stats",category:"diagnostics"},{name:"/onboarding",usage:"/onboarding [done|reset]",description:"Show or update onboarding guidance for this workspace",category:"customization"},{name:"/doctor",usage:"/doctor [--json] [--no-mcp]",description:"Run local runtime, config, and MCP health checks",category:"diagnostics"},{name:"/bug-report",usage:"/bug-report [path] [--json]",description:"Export a redacted diagnostics bundle",category:"diagnostics"},{name:"/release-notes",usage:"/release-notes [version]",description:"Show current or requested release notes",category:"diagnostics"},{name:"/debug",usage:"/debug [status|steps|snapshot|clear]",description:"Inspect agent execution debugger state",category:"diagnostics"},{name:"/init",description:"Initialize project for AI-assisted development",category:"diagnostics"}],Ste=Ou.map(e=>e.name);var iP=[{id:"global.cancel",label:"Cancel / exit",description:"Interrupt an operation, clear a draft, or arm exit",context:"global",defaults:["ctrl+c"],emergencyFallback:"ctrl+c"},{id:"agent-session.detach",label:"Detach agent session",description:"Return from an attached agent-session transcript",context:"agent-session",defaults:["escape","ctrl+z"]},{id:"agent-session.stop",label:"Stop agent session",description:"Stop the focused background agent session",context:"agent-session",defaults:["x"]},{id:"delegation.inspect",label:"Inspect delegation",description:"Open the live agent hierarchy inspector",context:"delegation",defaults:["ctrl+l"]},{id:"delegation.toggle-log",label:"Toggle delegation log",description:"Expand or collapse the delegation event log",context:"delegation",defaults:["ctrl+e"]},{id:"composer.quick-actions",label:"Quick actions",description:"Open prompt fix and rewrite actions",context:"composer",defaults:["ctrl+f"]},{id:"operation.background",label:"Background operation",description:"Promote the active foreground operation",context:"busy",defaults:["ctrl+b"]},{id:"output.toggle-verbose",label:"Toggle tool details",description:"Expand or collapse tool-result groups",context:"conversation",defaults:["ctrl+o"]},{id:"artifact.open",label:"Open artifact",description:"Open the most recent artifact page this session published",context:"conversation",defaults:["ctrl+]"]},{id:"conversation.interrupt",label:"Interrupt turn",description:"Interrupt the active model turn",context:"busy",defaults:["escape"]},{id:"conversation.rewind",label:"Rewind conversation",description:"Open rewind after the guarded second press",context:"conversation",defaults:["escape"]},{id:"approval.cycle",label:"Cycle approval mode",description:"Cycle the current approval mode",context:"composer",defaults:["shift+tab"]},{id:"composer.submit",label:"Submit prompt",description:"Submit the current prompt",context:"composer",defaults:["enter"]},{id:"composer.newline",label:"Insert newline",description:"Insert a soft line break in the prompt",context:"composer",defaults:["shift+enter","ctrl+enter"]},{id:"composer.complete",label:"Complete",description:"Accept autocomplete or prompt suggestions",context:"composer",defaults:["tab"]},{id:"composer.backspace",label:"Backspace",description:"Delete the previous grapheme",context:"composer",defaults:["backspace"]},{id:"composer.delete",label:"Delete",description:"Delete the next grapheme",context:"composer",defaults:["delete"]},{id:"composer.home",label:"Prompt start",description:"Move to the start of the prompt",context:"composer",defaults:["ctrl+a"]},{id:"composer.end",label:"Prompt end",description:"Move to the end of the prompt",context:"composer",defaults:["ctrl+e"]},{id:"composer.clear",label:"Clear prompt",description:"Clear the current prompt",context:"composer",defaults:["ctrl+u"]},{id:"composer.kill-to-end",label:"Delete to end",description:"Delete prompt text from the cursor to the end",context:"composer",defaults:["ctrl+k"]},{id:"composer.external-editor",label:"Open external editor",description:"Edit the current prompt in VISUAL or EDITOR",context:"composer",defaults:["ctrl+g"]},{id:"composer.undo-transform",label:"Undo prompt transform",description:"Restore text from before a quick fix or rewrite",context:"composer",defaults:["ctrl+z"]},{id:"processes.open",label:"Open processes",description:"Open background tasks and processes",context:"composer",defaults:["ctrl+t"]},{id:"composer.history-search",label:"Search history",description:"Reverse-search prompt history",context:"composer",defaults:["ctrl+r"]},{id:"composer.paste-image",label:"Paste clipboard image",description:"Capture a clipboard image into the current session and attach it to the prompt",context:"composer",defaults:["ctrl+v","alt+i"]},{id:"composer.voice-dictation",label:"Voice dictation",description:"Start operating-system voice typing without retaining audio in XENO",context:"composer",defaults:["alt+v"]},{id:"model.open",label:"Switch model",description:"Open the model picker",context:"composer",defaults:["alt+p"]},{id:"thinking.hint",label:"Thinking mode",description:"Show thinking-mode guidance",context:"composer",defaults:["alt+t"]},{id:"navigation.activate",label:"Activate",description:"Activate the focused item",context:"overlay",defaults:["enter"]},{id:"navigation.secondary-activate",label:"Secondary action",description:"Open or confirm the focused secondary action",context:"output",defaults:["ctrl+enter"]},{id:"navigation.up",label:"Move up",description:"Move focus or cursor up",context:"overlay",defaults:["up"]},{id:"navigation.down",label:"Move down",description:"Move focus or cursor down",context:"overlay",defaults:["down"]},{id:"navigation.left",label:"Move left",description:"Move focus or cursor left",context:"overlay",defaults:["left"]},{id:"navigation.right",label:"Move right",description:"Move focus or cursor right",context:"overlay",defaults:["right"]},{id:"navigation.page-up",label:"Page up",description:"Scroll the focused viewport up",context:"overlay",defaults:["pageup"]},{id:"navigation.page-down",label:"Page down",description:"Scroll the focused viewport down",context:"overlay",defaults:["pagedown"]},{id:"navigation.home",label:"Viewport start",description:"Jump to the beginning of the focused viewport",context:"overlay",defaults:["home"]},{id:"navigation.end",label:"Viewport end",description:"Jump to the end of the focused viewport",context:"overlay",defaults:["end"]},{id:"search.focus",label:"Focus search",description:"Focus search in the active picker",context:"overlay",defaults:["ctrl+f"]},{id:"search.clear",label:"Clear search",description:"Clear the active picker search",context:"overlay",defaults:["ctrl+u"]},{id:"selection.toggle",label:"Toggle selection",description:"Toggle the focused multi-select item",context:"overlay",defaults:["space"]},{id:"selection.toggle-all",label:"Toggle all",description:"Select or clear all filtered items",context:"overlay",defaults:["ctrl+a"]},{id:"focus.up",label:"Focus up",description:"Move between major TUI focus regions",context:"conversation",defaults:["ctrl+up"]},{id:"focus.down",label:"Focus down",description:"Move between major TUI focus regions",context:"conversation",defaults:["ctrl+down"]},{id:"focus.left",label:"Focus left",description:"Move between major TUI focus regions",context:"conversation",defaults:["ctrl+left"]},{id:"focus.right",label:"Focus right",description:"Move between major TUI focus regions",context:"conversation",defaults:["ctrl+right"]},{id:"editor.save",label:"Save edit",description:"Save the active structured editor",context:"overlay",defaults:["ctrl+s"]},{id:"editor.revert",label:"Revert edit",description:"Revert the active structured editor or draft",context:"overlay",defaults:["ctrl+r"]},{id:"editor.undo",label:"Undo edit",description:"Undo the last structured editor change",context:"overlay",defaults:["ctrl+z"]},{id:"editor.redo",label:"Redo edit",description:"Redo the last structured editor change",context:"overlay",defaults:["ctrl+y"]},{id:"overlay.close",label:"Close",description:"Close or back out of the active overlay",context:"overlay",defaults:["escape"]},{id:"terminal.detach",label:"Detach terminal",description:"Return from an attached interactive background terminal",context:"terminal-attach",defaults:["ctrl+b"]}],gNt=new Map(iP.map(e=>[e.id,e]));function oP(e){return gNt.has(e)}var WNe=["ctrl","alt","shift"],HNe=new Set(WNe),ANt={esc:"escape",return:"enter",spacebar:"space",pgup:"pageup","page-up":"pageup",pgdn:"pagedown","page-down":"pagedown",del:"delete",bs:"backspace"},GNe=new Set(["escape","enter","tab","backspace","delete","space","home","end","pageup","pagedown","up","down","left","right"]);function Ik(e){if(typeof e!="string"||e.trim().length===0)throw new Error("Key chord must be a non-empty string");let t=e.trim().toLowerCase().split("+").map(u=>u.trim());if(t.some(u=>u.length===0))throw new Error(`Malformed key chord: ${e}`);let n=t.at(-1),r=t.slice(0,-1),i=r.find(u=>!HNe.has(u));if(i)throw new Error(`Unsupported modifier '${i}' in '${e}'`);if(new Set(r).size!==r.length)throw new Error(`Duplicate modifier in '${e}'`);let o=ANt[n]??n;if(!GNe.has(o)&&Array.from(o).length!==1)throw new Error(`Unsupported key '${n}' in '${e}'`);if(HNe.has(o))throw new Error(`Key chord '${e}' is missing a non-modifier key`);let s=r.includes("ctrl"),a=r.includes("alt"),c=r.includes("shift");if(o==="escape"&&(s||a||c))throw new Error(`Modified Escape is not portable across supported terminals: '${e}'`);if(o==="backspace"&&a&&s)throw new Error(`Ctrl+Alt+Backspace is reserved by some operating systems: '${e}'`);return{canonical:[...WNe.filter(u=>({ctrl:s,alt:a,shift:c})[u]),o].join("+"),key:o,ctrl:s,alt:a,shift:c}}function wNt(e){return 1+(e.shift?1:0)+(e.alt?2:0)+(e.ctrl?4:0)}function yNt(e,t){let n=wNt(e),r=e.ctrl||e.alt||e.shift,i={up:"A",down:"B",right:"C",left:"D"},o={up:"H",down:"P",right:"M",left:"K"};if(i[e.key])return r?(e.ctrl&&!e.alt&&!e.shift?[5,6,7,8]:[n]).flatMap(a=>[`\x1B[1;${a}${i[e.key]}`,`\x1B[${a}${i[e.key]}`]):[`\x1B[${i[e.key]}`,`\x1BO${i[e.key]}`,`\0${o[e.key]}`,`\xE0${o[e.key]}`,...[2,3,4,5,6,7,8].flatMap(s=>[`\x1B[1;${s}${i[e.key]}`,`\x1B[${s}${i[e.key]}`])];if(e.key==="enter"){if(e.ctrl||e.shift||e.alt){let a=(e.ctrl&&!e.alt&&!e.shift?[5,6]:[n]).flatMap(c=>[`\x1B[13;${c}u`,`\x1B[27;13;${c}~`]);return(e.shift||e.alt)&&a.push("\x1B\r"),e.ctrl&&t==="win32"&&a.push(`
3178
3178
  `),a}return["\r",`
3179
3179
  `,`\r
3180
- `,"\x1BOM"]}return e.key==="tab"?e.shift?["\x1B[Z"]:e.ctrl||e.alt?[`\x1B[9;${n}u`]:[" "]:e.key==="escape"?["\x1B"]:e.key==="backspace"?e.alt?["\x1B\x7F","\x1B\b"]:["\x7F","\b"]:e.key==="delete"?r?[`\x1B[3;${n}~`]:["\x1B[3~"]:e.key==="home"?r?[`\x1B[1;${n}H`]:["\x1B[H","\x1B[1~","\x1B[7~"]:e.key==="end"?r?[`\x1B[1;${n}F`]:["\x1B[F","\x1B[4~","\x1B[8~"]:e.key==="pageup"?r?[`\x1B[5;${n}~`]:["\x1B[5~"]:e.key==="pagedown"?r?[`\x1B[6;${n}~`]:["\x1B[6~"]:e.key==="space"?e.ctrl?["\0"]:[e.alt?"\x1B ":" "]:[]}function Cte(e,t=process.platform){if(GNe.has(e.key))return yNt(e,t);let n=e.shift?e.key.toUpperCase():e.key;if(e.ctrl){let i=e.key.toUpperCase().codePointAt(0);if(i>=64&&i<=95){let o=String.fromCodePoint(i-64);return[e.alt?`\x1B${o}`:o]}}return[e.alt?`\x1B${n}`:n]}function JNe(e,t,n=process.platform){return Cte(e,n).includes(t)}function XNe(e){let t={ctrl:"Ctrl",alt:"Alt",shift:"Shift",escape:"Esc",enter:"Enter",tab:"Tab",backspace:"Backspace",delete:"Delete",space:"Space",home:"Home",end:"End",pageup:"PgUp",pagedown:"PgDn",up:"Up",down:"Down",left:"Left",right:"Right"};return e.canonical.split("+").map(n=>t[n]??n.toUpperCase()).join("+")}Wr();import{existsSync as bNt,readFileSync as vNt}from"node:fs";import{join as INt,resolve as kNt}from"node:path";function kk(e=Ar()){return INt(e,"keybindings.json")}function xte(){return new Map(iP.map(e=>[e.id,{action:e,chords:e.defaults.map(t=>Ik(t)),customized:!1}]))}function ENt(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Root must be a JSON object");let t=e,n=Object.keys(t).filter(r=>r!=="version"&&r!=="bindings");if(n.length>0)throw new Error(`Unknown root field(s): ${n.join(", ")}`);if(t.version!==1)throw new Error(`version must be ${1}`);if(!t.bindings||typeof t.bindings!="object"||Array.isArray(t.bindings))throw new Error("bindings must be an object");return e}function SNt(e){if(typeof e=="string")return[e];if(Array.isArray(e)&&e.every(t=>typeof t=="string"))return e;throw new Error("Binding must be a string or an array of strings")}function CNt(e,t){return e.context==="global"||t.context==="global"||e.context===t.context}function xNt(e,t){let n=Array.from(e.values());for(let r=0;r<n.length;r+=1){let i=n[r];for(let o=r+1;o<n.length;o+=1){let s=n[o];if(!CNt(i.action,s.action))continue;let a=new Set(s.chords.map(c=>c.canonical));for(let c of i.chords)a.has(c.canonical)&&t.push({severity:"error",code:"CONFLICTING_BINDING",action:`${i.action.id},${s.action.id}`,binding:c.canonical,message:`'${c.canonical}' is assigned to both ${i.action.id} and ${s.action.id} in overlapping contexts`})}}}function RNt(e,t){let n=xte(),r=e.bindings;for(let[i,o]of Object.entries(r)){if(!oP(i)){t.push({severity:"error",code:"UNKNOWN_ACTION",action:i,message:`Unknown keybinding action '${i}'`});continue}let s;try{s=SNt(o)}catch(u){t.push({severity:"error",code:"INVALID_BINDING",action:i,message:`${i}: ${u instanceof Error?u.message:String(u)}`});continue}let a=[],c=new Set;for(let u of s)try{let p=Ik(u);if(c.has(p.canonical)){t.push({severity:"warning",code:"DUPLICATE_BINDING",action:i,binding:p.canonical,message:`${i} repeats '${p.canonical}'`});continue}c.add(p.canonical),a.push(p)}catch(p){t.push({severity:"error",code:"INVALID_BINDING",action:i,binding:u,message:`${i}: ${p instanceof Error?p.message:String(p)}`})}let l=n.get(i),d=l.action.emergencyFallback?Ik(l.action.emergencyFallback):void 0;d&&!a.some(u=>u.canonical===d.canonical)&&a.push(d),n.set(i,{...l,chords:a,customized:!0})}return xNt(n,t),n}function Rte(e,t="<memory>"){let n=xte(),r;try{r=ENt(e)}catch(s){return{path:t,source:"defaults",usingDefaults:!0,bindings:n,diagnostics:[{severity:"error",code:"INVALID_DOCUMENT",message:`Invalid keybindings document: ${s instanceof Error?s.message:String(s)}`}]}}let i=[],o=RNt(r,i);return i.some(s=>s.severity==="error")?{path:t,source:"defaults",usingDefaults:!0,document:r,bindings:n,diagnostics:i}:{path:t,source:"user",usingDefaults:!1,document:r,bindings:o,diagnostics:i}}function Ek(e={}){let t=kNt(e.path??kk(e.configDirectory)),n=xte();if(e.safeMode)return{path:t,source:"safe-mode",usingDefaults:!0,bindings:n,diagnostics:[]};if(!bNt(t))return{path:t,source:"defaults",usingDefaults:!0,bindings:n,diagnostics:[]};let r;try{r=JSON.parse(vNt(t,"utf8"))}catch(i){return{path:t,source:"defaults",usingDefaults:!0,bindings:n,diagnostics:[{severity:"error",code:i instanceof SyntaxError?"INVALID_JSON":"READ_FAILED",message:`Unable to load ${t}: ${i instanceof Error?i.message:String(i)}`}]}}return Rte(r,t)}var Tte=class{constructor(t,n=process.platform){this.result=t;this.platform=n}result;platform;matches(t,n){return!!this.result.bindings.get(t)?.chords.some(i=>JNe(i,n,this.platform))}sequences(t){let n=this.result.bindings.get(t);return n?Array.from(new Set(n.chords.flatMap(r=>Cte(r,this.platform)))).sort((r,i)=>i.length-r.length):[]}display(t){return this.result.bindings.get(t)?.chords.map(r=>XNe(r)).join(" / ")||"unbound"}findInInput(t,n){let r=null;for(let i of this.sequences(t)){let o=n.indexOf(i);o<0||(!r||o<r.index||o===r.index&&i.length>r.length)&&(r={index:o,length:i.length})}return r}longestSuffixPrefix(t,n){let r=0;for(let i of this.sequences(t)){let o=Math.min(i.length-1,n.length);for(let s=o;s>r;s-=1)if(n.endsWith(i.slice(0,s))){r=s;break}}return r}};function ey(e={}){return new Tte(Ek(e))}var Te=e=>cr()(e);function zNe(e){let t=e?.elevation;if(!t)return[];let n=[];t.network&&n.push(["Extra access:","network"]);for(let r of t.directories)n.push(["Extra access:",`directory ${r}`]);return n.push(["Justification:",t.justification.replace(/\s+/g," ").trim()]),n}var L=K.dim,ty=e=>cr()(e),Hs=e=>uNe()(e),LNt=e=>pNe()(e),ny=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Pte=["\u25A0","\u25A3","\u25A1","\u25A3"],QNt=180,KNe=ey({safeMode:!0});function FNt(e,t){return e==="chatOnly"?"\u25A1":t==="bypassPermissions"?"\u25A3":"\u25A0"}function gU(e){return e.replace(/^\u276F[ \t]+/u,"")}function bo(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e4?`${Math.round(e/1e3)}K`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e)}function YNe(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:e>=1024?`${(e/1024).toFixed(1)} KB`:`${Math.max(0,Math.floor(e))} B`}function _te(e,t){let n=t.toLowerCase();return e.filter(r=>!n||r.label.toLowerCase().includes(n)||r.key.toLowerCase().includes(n))}function UNt(e){if(!e||e===" ")return!1;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<32||n>=127&&n<=159)return!1}return!0}var Sk=class{opts;keybindingResolver;NORMAL_FOOTER_OVERHEAD_ROWS=5;SHOW_STATUS_BAR=!0;MAX_INPUT_ROWS=6;COLLAPSE_PASTE_MIN_LINES=4;MAX_VISIBLE_TASK_PROGRESS_ITEMS=6;MIN_OUTPUT_ROWS_WITH_TASK_PROGRESS=3;MODEL_PICKER_VISIBLE_OPTIONS=8;SESSION_PICKER_VISIBLE_ITEMS=5;INFO_PANEL_EDIT_UNDO_LIMIT=100;rows=0;cols=0;outputBottom=0;outputRow=1;outputCol=1;outputHistory="";inputBuffer="";cursorPos=0;inputHistory=[];historyIndex=-1;historyDraft="";pastedTextCounter=0;pastedTextBlocks=new Map;clipboardImageCounter=0;clipboardImageLabels=new Set;clipboardImageCaptureInFlight=!1;voiceDictationInFlight=!1;inputScrollOffset=0;inputLineScrollOffset=0;inputViewportStartLine=0;preferredInputCellColumn=null;inputProjectionCache=null;inputViewCache=null;inputSoftWrapEnabled=process.env.XENO_INPUT_SOFT_WRAP!=="0";lastFooterRows=7;quickActionBarOpen=!1;quickActionSelectedIndex=0;QUICK_ACTIONS=["FIX TYPO","REWRITE AS"];QUICK_REWRITE_OPTIONS=["SWE","RESEARCHER","CUSTOM"];quickActionView="main";quickRewriteSelectedIndex=0;quickRewriteCustomInput="";quickActionInlineHint=null;_promptSuggestion=null;quickActionPending=!1;quickActionUndoStack=[];QUICK_ACTION_UNDO_LIMIT=20;spinnerInterval=null;spinnerFrameIndex=0;spinnerMessage="";activeToolOperation=null;busyActivityTicker=null;toolActivityAnimationTimer=null;toolActivityAnimationFrameIndex=0;toolActivityAnimationPositions=[];busyStartedAt=0;busyTokenCount=null;busyActivityLabel="Processing request...";delegationViewState=null;agentSessionFooterItems=[];taskProgressItems=[];agentSessionFooterFocusIndex=0;agentSessionFooterScrollOffset=0;activeAgentSessionFooterId=null;agentSessionFooterRenderSignature="";agentSessionChatViewState=null;delegationLogDockExpanded=!1;delegationLogDockScrollOffset=0;delegationCompletionState=null;transientActivityNotice=null;delegationFocusIndex=0;promptResolve=null;promptQuestion="";isPrompting=!1;permissionState=null;modelPickerState=null;sessionPickerState=null;sessionMultiPickerState=null;actionPickerState=null;helpPanelState=null;statusPanelState=null;infoPanelState=null;_busy=!1;_queuedMessages=[];pendingAgentSessionNotifications=[];_verboseToolOutput=!1;tokensUsed=0;contextTokens;contextBudgetReported=!1;contextTokensEstimated=!1;costDisplay="";autocompleteVisible=!1;autocompleteMatches=[];autocompleteSelectedIndex=0;autocompleteScrollOffset=0;wasAutocompleteVisible=!1;cleaned=!1;lastCtrlCTimestamp=0;CTRL_C_EXIT_WINDOW_MS=1500;statusRightHint=null;artifactFooterItems=[];statusRightHintTimer=null;statusLineText="";statusLineTimer=null;statusLineInFlight=!1;vimInputMode=!1;vimInsertMode=!0;footerFocus="input";statusFocusIndex=0;STATUS_FOCUSABLE_COUNT=6;resizeDebounceTimer=null;footerFrameScheduler;retainedFooterFrame;retainedUiStateStore;pendingFooterFramePrefix="";serializedTerminalWriter;serializedDiagnosticWriter;inputHealthTimer=null;inputHealthTick=0;terminalAttachSuspended=!1;terminalCapabilities=cU();bracketedPasteModeEnabled=!1;lastInputEventAt=0;inputAttachedAt=0;terminalInputDecoder=new aM({onBracketedPasteRejected:({maxCharacters:t})=>{this.showTransientActivityNotice(`Paste ignored: bracketed input exceeded ${t.toLocaleString()} characters.`,6e3)}});terminalInputFlushTimer=null;windowsUnframedPasteDecoder=new sM;windowsUnframedPasteFlushTimer=null;TERMINAL_INPUT_ESCAPE_TIMEOUT_MS=50;WINDOWS_UNFRAMED_PASTE_GRACE_MS=80;RESIZE_DEBOUNCE_MS=60;resizeInProgress=!1;promptContextBreakdown="";providerSessionStatus;delegationEnabled=!1;turnDurationVisible=!0;outputBlocks=[];outputReflowCache=new Map;outputReflowCacheChars=0;renderedOutputBlockOffsets=[];outputFocusIndex=-1;outputViewportTopLine=0;outputViewportManualScroll=!1;mouseReportingEnabled=!1;outputActionState=null;OUTPUT_ACTIONS=["EDIT","RETRY","RESTORE"];INTERRUPT_REWIND_WINDOW_MS=1500;interruptRewindWindowMs=1500;interruptRewindArmed=!1;interruptRewindLastEscAt=0;escCancelableInputDraft=!1;busyInterruptRequested=!1;openRewindAfterInterrupt=!1;handleStdinData=t=>{let n=typeof t=="string"?t:t.toString("utf8");this.lastInputEventAt=Date.now(),Bi("screen:data",{length:n.length,hex:Buffer.from(n,"utf8").toString("hex"),busy:this._busy,isPrompting:this.isPrompting,footerFocus:this.footerFocus,overlays:this.activeOverlayNames(),platform:process.platform,terminalProfile:this.terminalCapabilities.profile,stdinIsTTY:process.stdin.isTTY,stdoutIsTTY:process.stdout.isTTY,listenerCount:process.stdin.listenerCount("data"),isRaw:process.stdin.isRaw}),this.processTerminalInputText(n)};handleStdoutResize=()=>{this.resizeInProgress=!0,this.resizeDebounceTimer&&clearTimeout(this.resizeDebounceTimer),this.resizeDebounceTimer=setTimeout(()=>{this.resizeDebounceTimer=null,this.handleResizeRedraw()},this.RESIZE_DEBOUNCE_MS)};handleProcessExit=()=>{this.cleanup()};constructor(t){this.opts=t,this.keybindingResolver=t.keybindingResolver??ey({safeMode:t.safeMode}),this.promptContextBreakdown=(t.promptContextBreakdown||"").trim(),this.delegationEnabled=!!t.delegationEnabled,this.calculateLayout(),this.retainedUiStateStore=new eP(uU({viewport:{rows:this.rows,columns:this.cols,outputBottom:this.outputBottom}})),this.setupRawMode(),this.setupResize(),this.setupCleanup(),this.startStatusLineCommand(),this.initScreen()}matchesKeybinding(t,n){return(this.keybindingResolver??KNe).matches(t,n)}keybindingLabel(t){return(this.keybindingResolver??KNe).display(t)}terminalWriter(){return this.serializedTerminalWriter??=new Mu(this.opts?.terminalOutput??process.stdout),this.serializedTerminalWriter}diagnosticWriter(){return this.serializedDiagnosticWriter??=new Mu(this.opts?.diagnosticOutput??process.stderr),this.serializedDiagnosticWriter}writeTerminalFrame(t,n="screen"){this.terminalWriter().writeFrame(t,n)}writeRetainedTerminalFrame(t,n,r){this.terminalWriter().writeFrame(t,n,r)}writeTerminalOrdered(t,n="output"){this.terminalWriter().writeOrdered(t,n)}writeTerminalControl(t,n="control"){this.terminalWriter().writeControl(t,n)}writeTerminalPassthrough(t){this.terminalWriter().writePassthrough(t)}writeTerminalTeardown(t){this.terminalWriter().writeTeardown(t)}bracketedPasteModeControl(t,n=!1){return!this.terminalCapabilities.bracketedPaste||!n&&this.bracketedPasteModeEnabled===t?"":(this.bracketedPasteModeEnabled=t,t?C.enableBracketedPaste():C.disableBracketedPaste())}writeDiagnostic(t){this.diagnosticWriter().writeOrdered(t,"diagnostic")}uiStateStore(){return this.retainedUiStateStore??=new eP(uU()),this.retainedUiStateStore}synchronizeUiState(){let t=this.uiStateStore();return t.dispatch({type:"viewport.changed",viewport:{rows:this.rows,columns:this.cols,outputBottom:this.outputBottom}}),t.dispatch({type:"composer.changed",composer:{text:this.inputBuffer,cursorOffset:this.cursorPos,visibleRows:this.getNormalInputRows(),viewportStartLine:this.inputViewportStartLine,busy:this._busy,queuedPromptCount:this.queuedMessages().length}}),t.dispatch({type:"status.changed",status:{model:this.opts.model,effort:this.opts.effort??"",permissionMode:this.opts.permissionMode,executionMode:this.opts.executionMode??"agent",delegationEnabled:this.delegationEnabled,tokenCount:this.tokensUsed}}),t.dispatch({type:"agents.changed",agents:this.agentSessionFooterItems}),t.dispatch({type:"overlays.changed",names:this.activeOverlayNames()}),t.snapshot()}getUiStateSnapshot(){return this.synchronizeUiState()}get busy(){return this._busy}set busy(t){let n=this._busy;this._busy=t,t&&(this.quickActionBarOpen=!1,this.quickActionView="main",this.quickRewriteSelectedIndex=0,this.quickRewriteCustomInput="",this.quickActionInlineHint=null,this._promptSuggestion=null),t&&!n?(this.busyInterruptRequested=!1,this.openRewindAfterInterrupt=!1,this.busyStartedAt=Date.now(),this.busyTokenCount=null,this.startBusyActivityTicker()):!t&&n&&(this.stopBusyActivityTicker(),this.busyInterruptRequested=!1,this.busyStartedAt=0,this.busyTokenCount=null,this.busyActivityLabel="Processing request..."),this.hasOverlayOpen()||this.drawInputBox(),this.drawStatusBar(),this.refreshFooterFocusCursor(),!t&&n&&this.maybeOpenPendingInterruptRewind()}setActiveToolOperation(t){this.activeToolOperation=t,this._busy&&this.redrawBusyActivityRow()}get activePromotableOperationId(){let t=this.activeToolOperation;return t?.promotable&&t.presentation==="foreground"?t.operationId:null}get activeToolOperationId(){return this.activeToolOperation?.operationId??null}setPromptSuggestion(t){t!==null&&(this._busy||this.inputBuffer.length>0)||(this._promptSuggestion=t,!this._busy&&this.inputBuffer.length===0&&this.drawInputBox())}setBusyTokenCount(t){let n=t===null||!Number.isFinite(t)?null:Math.max(0,Math.floor(t));n!==this.busyTokenCount&&(this.busyTokenCount=n,this._busy&&this.redrawBusyActivityRow())}_backgroundTaskCount=0;setBackgroundTaskCount(t){this._backgroundTaskCount!==t&&(this._backgroundTaskCount=t,this.drawStatusBar())}setContextBudgetTokens(t){if(!Number.isFinite(t)||t<=0)return;let n=!this.contextBudgetReported;if(this.contextBudgetReported=!0,this.opts.maxContextTokens===t){n&&this.drawStatusBar();return}this.opts.maxContextTokens=t,this.drawStatusBar()}suspendForTerminalAttach(){return this.terminalAttachSuspended||!process.stdin.isTTY||!process.stdout.isTTY?!1:(this.terminalAttachSuspended=!0,this.stopSpinner(),this.stopBusyActivityTicker(),this.stopToolActivityAnimation(),this.resizeDebounceTimer&&(clearTimeout(this.resizeDebounceTimer),this.resizeDebounceTimer=null),this.resetTerminalInputDecoder(),this.footerFrameScheduler?.suspend(),this.inputHealthTimer&&(clearInterval(this.inputHealthTimer),this.inputHealthTimer=null),this.statusLineTimer&&(clearInterval(this.statusLineTimer),this.statusLineTimer=null),process.stdin.removeListener("data",this.handleStdinData),process.stdin.listenerCount("data")===0&&process.stdin.pause(),process.stdout.removeListener("resize",this.handleStdoutResize),this.setMouseReportingEnabled(!1),this.terminalWriter().invalidateFrames(),this.writeTerminalControl(this.bracketedPasteModeControl(!1)+C.resetScrollRegion()+C.clearScreen()+C.moveTo(1,1)+C.showCursor(),"pty-attach"),!0)}writeAttachedTerminalOutput(t){!this.terminalAttachSuspended||!t||this.writeTerminalPassthrough(t)}getTerminalSize(){return{cols:Math.max(1,process.stdout.columns||this.cols||80),rows:Math.max(1,process.stdout.rows||this.rows||24)}}getRenderCols(){return this.renderCols()}formatUserPrompt(t){return this.formatUserPromptMessage(t)}resumeFromTerminalAttach(){!this.terminalAttachSuspended||this.cleaned||(this.writeTerminalControl("\x1B[?1049l\x1B[?1047l\x1B[?47l\x1B[0m\x1B[?25h"+this.bracketedPasteModeControl(!0),"pty-detach"),this.terminalAttachSuspended=!1,this.calculateLayout(),this.setupRawMode(),this.setupResize(),this.startStatusLineCommand(),this._busy&&this.startBusyActivityTicker(),this.redrawScreenFromHistory(),this.synchronizeToolActivityAnimation(),this.drawInputBox(),this.footerRenderer().invalidate(),this.footerFrameScheduler?.resume(!1),this.refreshFooterFocusCursor())}setTaskProgressItems(t){let n=t.map(o=>({...o,blockedBy:o.blockedBy?.slice()??[]})),r=this.currentTaskProgressSignature();this.taskProgressItems=n;let i=this.currentTaskProgressSignature();r!==i&&!this.resizeInProgress&&!this.hasOverlayOpen()&&this.scheduleFooterFrame(`tasks:${i}`)}setAgentSessionFooterItems(t){let n=this.agentSessionFooterRenderSignature;this.agentSessionFooterItems=t.slice(),this.uiStateStore().dispatch({type:"agents.changed",agents:this.agentSessionFooterItems});let r=(this.agentSessionFooterItems??[]).length;this.agentSessionFooterFocusIndex=Math.max(0,Math.min(this.agentSessionFooterFocusIndex,r)),this.normalizeAgentSessionFooterWindow(),(this.agentSessionFooterItems??[]).length===0&&this.footerFocus==="agentSession"&&(this.footerFocus="input",this.agentSessionFooterFocusIndex=0,this.agentSessionFooterScrollOffset=0),this.redrawAgentSessionFooterIfChanged(n)}setPendingAgentSessionNotifications(t){let n=t.map(i=>i.trim()).filter(Boolean),r=this.pendingAgentSessionNotificationItems();r.length===n.length&&r.every((i,o)=>i===n[o])||(this.pendingAgentSessionNotifications=n,!this.resizeInProgress&&!this.hasOverlayOpen()&&(this.drawInputBox(),this.refreshFooterFocusCursor()))}setActiveAgentSessionFooterId(t){let n=this.agentSessionFooterRenderSignature;this.activeAgentSessionFooterId=t,this.redrawAgentSessionFooterIfChanged(n)}openAgentSessionChatView(t){this.agentSessionChatViewState?.onClose?.(),this.agentSessionChatViewState={sessionId:t.sessionId,title:t.title,subtitle:t.subtitle,placeholder:t.placeholder??"Message this agent session...",historyText:t.historyText??"",pendingUserInputs:[],activityText:t.activityText,activityStartedAt:t.activityStartedAt,activityActive:t.activityActive,submitting:!1,error:void 0,onSubmit:t.onSubmit,onClose:t.onClose},this.activeAgentSessionFooterId=t.sessionId,this.footerFocus="input",this.inputBuffer="",this.cursorPos=0,this.invalidateInputProjection(),this.resetInputVisualState(),this.closeAutocomplete(),this.setMouseReportingEnabled(!1),this.redrawScreenFromHistory(),this.drawInputBox(),this.refreshFooterFocusCursor()}updateAgentSessionChatView(t,n,r){this.agentSessionChatViewState&&(this.agentSessionChatViewState.historyText=t,this.agentSessionChatViewState.pendingUserInputs=this.agentSessionChatViewState.pendingUserInputs.filter(i=>!t.includes(i)),n!==void 0&&(this.agentSessionChatViewState.subtitle=n),r&&(this.agentSessionChatViewState.activityText=r.activityText,this.agentSessionChatViewState.activityStartedAt=r.activityStartedAt,this.agentSessionChatViewState.activityActive=r.activityActive),this.hasOverlayOpen()||(this.redrawScreenFromHistory(),this.drawInputBox(),this.refreshFooterFocusCursor()))}closeAgentSessionChatView(){let t=this.agentSessionChatViewState;t&&(this.agentSessionChatViewState=null,this.activeAgentSessionFooterId=null,this.footerFocus="input",this.agentSessionFooterFocusIndex=0,this.inputBuffer="",this.cursorPos=0,this.invalidateInputProjection(),this.resetInputVisualState(),this.closeAutocomplete(),t.onClose?.(),this.redrawScreenFromHistory(),this.drawInputBox(),this.refreshFooterFocusCursor())}returnToMainAgentSessionFooter(){if(this.agentSessionChatViewState){this.closeAgentSessionChatView();return}this.footerFocus="input",this.agentSessionFooterFocusIndex=0,this.setMouseReportingEnabled(!1),this.hasOverlayOpen()||(this.drawInputBox(),this.refreshFooterFocusCursor())}getBackgroundTaskCount(){return this._backgroundTaskCount}takeQueuedMessage(){return this.queuedMessages().shift()??null}get awaitingHumanPrompt(){return this.isPrompting}get canAcceptExternalInput(){return!this._busy&&!this.isPrompting&&!this.hasOverlayOpen()&&this.inputBuffer.trim().length===0}enqueueMessage(t){let n=t.trim();return n?this.canAcceptExternalInput?(this.setInputText(n,{cursor:"end",escCancelable:!1}),this.handleEnter(),"submitted"):(this.queuedMessages().push(n),this.drawInputBox(),"queued"):"ignored"}echoUserPrompt(t,n=!1){n&&this.inputHistory.push(t);let r=this.collapseClipboardImagesForDisplay(t);this.writeOutput(`
3180
+ `,"\x1BOM"]}return e.key==="tab"?e.shift?["\x1B[Z"]:e.ctrl||e.alt?[`\x1B[9;${n}u`]:[" "]:e.key==="escape"?["\x1B"]:e.key==="backspace"?e.alt?["\x1B\x7F","\x1B\b"]:["\x7F","\b"]:e.key==="delete"?r?[`\x1B[3;${n}~`]:["\x1B[3~"]:e.key==="home"?r?[`\x1B[1;${n}H`]:["\x1B[H","\x1B[1~","\x1B[7~"]:e.key==="end"?r?[`\x1B[1;${n}F`]:["\x1B[F","\x1B[4~","\x1B[8~"]:e.key==="pageup"?r?[`\x1B[5;${n}~`]:["\x1B[5~"]:e.key==="pagedown"?r?[`\x1B[6;${n}~`]:["\x1B[6~"]:e.key==="space"?e.ctrl?["\0"]:[e.alt?"\x1B ":" "]:[]}function Cte(e,t=process.platform){if(GNe.has(e.key))return yNt(e,t);let n=e.shift?e.key.toUpperCase():e.key;if(e.ctrl){let i=e.key.toUpperCase().codePointAt(0);if(i>=64&&i<=95){let o=String.fromCodePoint(i-64);return[e.alt?`\x1B${o}`:o]}}return[e.alt?`\x1B${n}`:n]}function JNe(e,t,n=process.platform){return Cte(e,n).includes(t)}function XNe(e){let t={ctrl:"Ctrl",alt:"Alt",shift:"Shift",escape:"Esc",enter:"Enter",tab:"Tab",backspace:"Backspace",delete:"Delete",space:"Space",home:"Home",end:"End",pageup:"PgUp",pagedown:"PgDn",up:"Up",down:"Down",left:"Left",right:"Right"};return e.canonical.split("+").map(n=>t[n]??n.toUpperCase()).join("+")}Wr();import{existsSync as bNt,readFileSync as vNt}from"node:fs";import{join as INt,resolve as kNt}from"node:path";function kk(e=Ar()){return INt(e,"keybindings.json")}function xte(){return new Map(iP.map(e=>[e.id,{action:e,chords:e.defaults.map(t=>Ik(t)),customized:!1}]))}function ENt(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Root must be a JSON object");let t=e,n=Object.keys(t).filter(r=>r!=="version"&&r!=="bindings");if(n.length>0)throw new Error(`Unknown root field(s): ${n.join(", ")}`);if(t.version!==1)throw new Error(`version must be ${1}`);if(!t.bindings||typeof t.bindings!="object"||Array.isArray(t.bindings))throw new Error("bindings must be an object");return e}function SNt(e){if(typeof e=="string")return[e];if(Array.isArray(e)&&e.every(t=>typeof t=="string"))return e;throw new Error("Binding must be a string or an array of strings")}function CNt(e,t){return e.context==="global"||t.context==="global"||e.context===t.context}function xNt(e,t){let n=Array.from(e.values());for(let r=0;r<n.length;r+=1){let i=n[r];for(let o=r+1;o<n.length;o+=1){let s=n[o];if(!CNt(i.action,s.action))continue;let a=new Set(s.chords.map(c=>c.canonical));for(let c of i.chords)a.has(c.canonical)&&t.push({severity:"error",code:"CONFLICTING_BINDING",action:`${i.action.id},${s.action.id}`,binding:c.canonical,message:`'${c.canonical}' is assigned to both ${i.action.id} and ${s.action.id} in overlapping contexts`})}}}function RNt(e,t){let n=xte(),r=e.bindings;for(let[i,o]of Object.entries(r)){if(!oP(i)){t.push({severity:"error",code:"UNKNOWN_ACTION",action:i,message:`Unknown keybinding action '${i}'`});continue}let s;try{s=SNt(o)}catch(u){t.push({severity:"error",code:"INVALID_BINDING",action:i,message:`${i}: ${u instanceof Error?u.message:String(u)}`});continue}let a=[],c=new Set;for(let u of s)try{let p=Ik(u);if(c.has(p.canonical)){t.push({severity:"warning",code:"DUPLICATE_BINDING",action:i,binding:p.canonical,message:`${i} repeats '${p.canonical}'`});continue}c.add(p.canonical),a.push(p)}catch(p){t.push({severity:"error",code:"INVALID_BINDING",action:i,binding:u,message:`${i}: ${p instanceof Error?p.message:String(p)}`})}let l=n.get(i),d=l.action.emergencyFallback?Ik(l.action.emergencyFallback):void 0;d&&!a.some(u=>u.canonical===d.canonical)&&a.push(d),n.set(i,{...l,chords:a,customized:!0})}return xNt(n,t),n}function Rte(e,t="<memory>"){let n=xte(),r;try{r=ENt(e)}catch(s){return{path:t,source:"defaults",usingDefaults:!0,bindings:n,diagnostics:[{severity:"error",code:"INVALID_DOCUMENT",message:`Invalid keybindings document: ${s instanceof Error?s.message:String(s)}`}]}}let i=[],o=RNt(r,i);return i.some(s=>s.severity==="error")?{path:t,source:"defaults",usingDefaults:!0,document:r,bindings:n,diagnostics:i}:{path:t,source:"user",usingDefaults:!1,document:r,bindings:o,diagnostics:i}}function Ek(e={}){let t=kNt(e.path??kk(e.configDirectory)),n=xte();if(e.safeMode)return{path:t,source:"safe-mode",usingDefaults:!0,bindings:n,diagnostics:[]};if(!bNt(t))return{path:t,source:"defaults",usingDefaults:!0,bindings:n,diagnostics:[]};let r;try{r=JSON.parse(vNt(t,"utf8"))}catch(i){return{path:t,source:"defaults",usingDefaults:!0,bindings:n,diagnostics:[{severity:"error",code:i instanceof SyntaxError?"INVALID_JSON":"READ_FAILED",message:`Unable to load ${t}: ${i instanceof Error?i.message:String(i)}`}]}}return Rte(r,t)}var Tte=class{constructor(t,n=process.platform){this.result=t;this.platform=n}result;platform;matches(t,n){return!!this.result.bindings.get(t)?.chords.some(i=>JNe(i,n,this.platform))}sequences(t){let n=this.result.bindings.get(t);return n?Array.from(new Set(n.chords.flatMap(r=>Cte(r,this.platform)))).sort((r,i)=>i.length-r.length):[]}display(t){return this.result.bindings.get(t)?.chords.map(r=>XNe(r)).join(" / ")||"unbound"}findInInput(t,n){let r=null;for(let i of this.sequences(t)){let o=n.indexOf(i);o<0||(!r||o<r.index||o===r.index&&i.length>r.length)&&(r={index:o,length:i.length})}return r}longestSuffixPrefix(t,n){let r=0;for(let i of this.sequences(t)){let o=Math.min(i.length-1,n.length);for(let s=o;s>r;s-=1)if(n.endsWith(i.slice(0,s))){r=s;break}}return r}};function ey(e={}){return new Tte(Ek(e))}var Te=e=>cr()(e);function zNe(e){let t=e?.elevation;if(!t)return[];let n=[];t.network&&n.push(["Extra access:","network"]);for(let r of t.directories)n.push(["Extra access:",`directory ${r}`]);return n.push(["Justification:",t.justification.replace(/\s+/g," ").trim()]),n}var L=K.dim,ty=e=>cr()(e),Hs=e=>uNe()(e),LNt=e=>pNe()(e),ny=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Pte=["\u25A0","\u25A3","\u25A1","\u25A3"],QNt=180,KNe=ey({safeMode:!0});function FNt(e,t){return e==="chatOnly"?"\u25A1":t==="bypassPermissions"?"\u25A3":"\u25A0"}function gU(e){return e.replace(/^\u276F[ \t]+/u,"")}function bo(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e4?`${Math.round(e/1e3)}K`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e)}function YNe(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:e>=1024?`${(e/1024).toFixed(1)} KB`:`${Math.max(0,Math.floor(e))} B`}function _te(e,t){let n=t.toLowerCase();return e.filter(r=>!n||r.label.toLowerCase().includes(n)||r.key.toLowerCase().includes(n))}function UNt(e){if(!e||e===" ")return!1;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<32||n>=127&&n<=159)return!1}return!0}var Sk=class{opts;keybindingResolver;NORMAL_FOOTER_OVERHEAD_ROWS=5;SHOW_STATUS_BAR=!0;MAX_INPUT_ROWS=6;COLLAPSE_PASTE_MIN_LINES=4;MAX_VISIBLE_TASK_PROGRESS_ITEMS=6;MIN_OUTPUT_ROWS_WITH_TASK_PROGRESS=3;MODEL_PICKER_VISIBLE_OPTIONS=8;SESSION_PICKER_VISIBLE_ITEMS=5;INFO_PANEL_EDIT_UNDO_LIMIT=100;rows=0;cols=0;outputBottom=0;outputRow=1;outputCol=1;outputHistory="";inputBuffer="";cursorPos=0;inputHistory=[];historyIndex=-1;historyDraft="";pastedTextCounter=0;pastedTextBlocks=new Map;clipboardImageCounter=0;clipboardImageLabels=new Set;clipboardImageCaptureInFlight=!1;voiceDictationInFlight=!1;inputScrollOffset=0;inputLineScrollOffset=0;inputViewportStartLine=0;preferredInputCellColumn=null;inputProjectionCache=null;inputViewCache=null;inputSoftWrapEnabled=process.env.XENO_INPUT_SOFT_WRAP!=="0";lastFooterRows=7;quickActionBarOpen=!1;quickActionSelectedIndex=0;QUICK_ACTIONS=["FIX TYPO","REWRITE AS"];QUICK_REWRITE_OPTIONS=["SWE","RESEARCHER","CUSTOM"];quickActionView="main";quickRewriteSelectedIndex=0;quickRewriteCustomInput="";quickActionInlineHint=null;_promptSuggestion=null;quickActionPending=!1;quickActionUndoStack=[];QUICK_ACTION_UNDO_LIMIT=20;spinnerInterval=null;spinnerFrameIndex=0;spinnerMessage="";activeToolOperation=null;busyActivityTicker=null;toolActivityAnimationTimer=null;toolActivityAnimationFrameIndex=0;toolActivityAnimationPositions=[];busyStartedAt=0;busyTokenCount=null;busyActivityLabel="Processing request...";delegationViewState=null;agentSessionFooterItems=[];taskProgressItems=[];agentSessionFooterFocusIndex=0;agentSessionFooterScrollOffset=0;activeAgentSessionFooterId=null;agentSessionFooterRenderSignature="";agentSessionChatViewState=null;delegationLogDockExpanded=!1;delegationLogDockScrollOffset=0;delegationCompletionState=null;transientActivityNotice=null;delegationFocusIndex=0;promptResolve=null;promptQuestion="";isPrompting=!1;permissionState=null;modelPickerState=null;sessionPickerState=null;sessionMultiPickerState=null;actionPickerState=null;helpPanelState=null;statusPanelState=null;infoPanelState=null;_busy=!1;_queuedMessages=[];pendingAgentSessionNotifications=[];_verboseToolOutput=!1;tokensUsed=0;contextTokens;contextBudgetReported=!1;contextTokensEstimated=!1;costDisplay="";autocompleteVisible=!1;autocompleteMatches=[];autocompleteSelectedIndex=0;autocompleteScrollOffset=0;wasAutocompleteVisible=!1;cleaned=!1;lastCtrlCTimestamp=0;CTRL_C_EXIT_WINDOW_MS=1500;statusRightHint=null;artifactFooterItems=[];statusRightHintTimer=null;statusLineText="";statusLineTimer=null;statusLineInFlight=!1;vimInputMode=!1;vimInsertMode=!0;footerFocus="input";statusFocusIndex=0;STATUS_FOCUSABLE_COUNT=6;resizeDebounceTimer=null;footerFrameScheduler;retainedFooterFrame;retainedUiStateStore;pendingFooterFramePrefix="";serializedTerminalWriter;serializedDiagnosticWriter;inputHealthTimer=null;inputHealthTick=0;terminalAttachSuspended=!1;terminalCapabilities=cU();bracketedPasteModeEnabled=!1;lastInputEventAt=0;inputAttachedAt=0;terminalInputDecoder=new aM({onBracketedPasteRejected:({maxCharacters:t})=>{this.showTransientActivityNotice(`Paste ignored: bracketed input exceeded ${t.toLocaleString()} characters.`,6e3)}});terminalInputFlushTimer=null;windowsUnframedPasteDecoder=new sM;windowsUnframedPasteFlushTimer=null;TERMINAL_INPUT_ESCAPE_TIMEOUT_MS=50;WINDOWS_UNFRAMED_PASTE_GRACE_MS=80;RESIZE_DEBOUNCE_MS=60;resizeInProgress=!1;promptContextBreakdown="";providerSessionStatus;delegationEnabled=!1;turnDurationVisible=!0;outputBlocks=[];outputReflowCache=new Map;outputReflowCacheChars=0;renderedOutputBlockOffsets=[];renderedOutputEndCol=1;renderedOutputBlockStartCol=1;renderedOutputWidth=0;outputFocusIndex=-1;outputViewportTopLine=0;outputViewportManualScroll=!1;mouseReportingEnabled=!1;outputActionState=null;OUTPUT_ACTIONS=["EDIT","RETRY","RESTORE"];INTERRUPT_REWIND_WINDOW_MS=1500;interruptRewindWindowMs=1500;interruptRewindArmed=!1;interruptRewindLastEscAt=0;escCancelableInputDraft=!1;busyInterruptRequested=!1;openRewindAfterInterrupt=!1;handleStdinData=t=>{let n=typeof t=="string"?t:t.toString("utf8");this.lastInputEventAt=Date.now(),Bi("screen:data",{length:n.length,hex:Buffer.from(n,"utf8").toString("hex"),busy:this._busy,isPrompting:this.isPrompting,footerFocus:this.footerFocus,overlays:this.activeOverlayNames(),platform:process.platform,terminalProfile:this.terminalCapabilities.profile,stdinIsTTY:process.stdin.isTTY,stdoutIsTTY:process.stdout.isTTY,listenerCount:process.stdin.listenerCount("data"),isRaw:process.stdin.isRaw}),this.processTerminalInputText(n)};handleStdoutResize=()=>{this.resizeInProgress=!0,this.resizeDebounceTimer&&clearTimeout(this.resizeDebounceTimer),this.resizeDebounceTimer=setTimeout(()=>{this.resizeDebounceTimer=null,this.handleResizeRedraw()},this.RESIZE_DEBOUNCE_MS)};handleProcessExit=()=>{this.cleanup()};constructor(t){this.opts=t,this.keybindingResolver=t.keybindingResolver??ey({safeMode:t.safeMode}),this.promptContextBreakdown=(t.promptContextBreakdown||"").trim(),this.delegationEnabled=!!t.delegationEnabled,this.calculateLayout(),this.retainedUiStateStore=new eP(uU({viewport:{rows:this.rows,columns:this.cols,outputBottom:this.outputBottom}})),this.setupRawMode(),this.setupResize(),this.setupCleanup(),this.startStatusLineCommand(),this.initScreen()}matchesKeybinding(t,n){return(this.keybindingResolver??KNe).matches(t,n)}keybindingLabel(t){return(this.keybindingResolver??KNe).display(t)}terminalWriter(){return this.serializedTerminalWriter??=new Mu(this.opts?.terminalOutput??process.stdout),this.serializedTerminalWriter}diagnosticWriter(){return this.serializedDiagnosticWriter??=new Mu(this.opts?.diagnosticOutput??process.stderr),this.serializedDiagnosticWriter}writeTerminalFrame(t,n="screen"){this.terminalWriter().writeFrame(t,n)}writeRetainedTerminalFrame(t,n,r){this.terminalWriter().writeFrame(t,n,r)}writeTerminalOrdered(t,n="output"){this.terminalWriter().writeOrdered(t,n)}writeTerminalControl(t,n="control"){this.terminalWriter().writeControl(t,n)}writeTerminalPassthrough(t){this.terminalWriter().writePassthrough(t)}writeTerminalTeardown(t){this.terminalWriter().writeTeardown(t)}bracketedPasteModeControl(t,n=!1){return!this.terminalCapabilities.bracketedPaste||!n&&this.bracketedPasteModeEnabled===t?"":(this.bracketedPasteModeEnabled=t,t?C.enableBracketedPaste():C.disableBracketedPaste())}writeDiagnostic(t){this.diagnosticWriter().writeOrdered(t,"diagnostic")}uiStateStore(){return this.retainedUiStateStore??=new eP(uU()),this.retainedUiStateStore}synchronizeUiState(){let t=this.uiStateStore();return t.dispatch({type:"viewport.changed",viewport:{rows:this.rows,columns:this.cols,outputBottom:this.outputBottom}}),t.dispatch({type:"composer.changed",composer:{text:this.inputBuffer,cursorOffset:this.cursorPos,visibleRows:this.getNormalInputRows(),viewportStartLine:this.inputViewportStartLine,busy:this._busy,queuedPromptCount:this.queuedMessages().length}}),t.dispatch({type:"status.changed",status:{model:this.opts.model,effort:this.opts.effort??"",permissionMode:this.opts.permissionMode,executionMode:this.opts.executionMode??"agent",delegationEnabled:this.delegationEnabled,tokenCount:this.tokensUsed}}),t.dispatch({type:"agents.changed",agents:this.agentSessionFooterItems}),t.dispatch({type:"overlays.changed",names:this.activeOverlayNames()}),t.snapshot()}getUiStateSnapshot(){return this.synchronizeUiState()}get busy(){return this._busy}set busy(t){let n=this._busy;this._busy=t,t&&(this.quickActionBarOpen=!1,this.quickActionView="main",this.quickRewriteSelectedIndex=0,this.quickRewriteCustomInput="",this.quickActionInlineHint=null,this._promptSuggestion=null),t&&!n?(this.busyInterruptRequested=!1,this.openRewindAfterInterrupt=!1,this.busyStartedAt=Date.now(),this.busyTokenCount=null,this.startBusyActivityTicker()):!t&&n&&(this.stopBusyActivityTicker(),this.busyInterruptRequested=!1,this.busyStartedAt=0,this.busyTokenCount=null,this.busyActivityLabel="Processing request..."),this.hasOverlayOpen()||this.drawInputBox(),this.drawStatusBar(),this.refreshFooterFocusCursor(),!t&&n&&this.maybeOpenPendingInterruptRewind()}setActiveToolOperation(t){this.activeToolOperation=t,this._busy&&this.redrawBusyActivityRow()}get activePromotableOperationId(){let t=this.activeToolOperation;return t?.promotable&&t.presentation==="foreground"?t.operationId:null}get activeToolOperationId(){return this.activeToolOperation?.operationId??null}setPromptSuggestion(t){t!==null&&(this._busy||this.inputBuffer.length>0)||(this._promptSuggestion=t,!this._busy&&this.inputBuffer.length===0&&this.drawInputBox())}setBusyTokenCount(t){let n=t===null||!Number.isFinite(t)?null:Math.max(0,Math.floor(t));n!==this.busyTokenCount&&(this.busyTokenCount=n,this._busy&&this.redrawBusyActivityRow())}_backgroundTaskCount=0;setBackgroundTaskCount(t){this._backgroundTaskCount!==t&&(this._backgroundTaskCount=t,this.drawStatusBar())}setContextBudgetTokens(t){if(!Number.isFinite(t)||t<=0)return;let n=!this.contextBudgetReported;if(this.contextBudgetReported=!0,this.opts.maxContextTokens===t){n&&this.drawStatusBar();return}this.opts.maxContextTokens=t,this.drawStatusBar()}suspendForTerminalAttach(){return this.terminalAttachSuspended||!process.stdin.isTTY||!process.stdout.isTTY?!1:(this.terminalAttachSuspended=!0,this.stopSpinner(),this.stopBusyActivityTicker(),this.stopToolActivityAnimation(),this.resizeDebounceTimer&&(clearTimeout(this.resizeDebounceTimer),this.resizeDebounceTimer=null),this.resetTerminalInputDecoder(),this.footerFrameScheduler?.suspend(),this.inputHealthTimer&&(clearInterval(this.inputHealthTimer),this.inputHealthTimer=null),this.statusLineTimer&&(clearInterval(this.statusLineTimer),this.statusLineTimer=null),process.stdin.removeListener("data",this.handleStdinData),process.stdin.listenerCount("data")===0&&process.stdin.pause(),process.stdout.removeListener("resize",this.handleStdoutResize),this.setMouseReportingEnabled(!1),this.terminalWriter().invalidateFrames(),this.writeTerminalControl(this.bracketedPasteModeControl(!1)+C.resetScrollRegion()+C.clearScreen()+C.moveTo(1,1)+C.showCursor(),"pty-attach"),!0)}writeAttachedTerminalOutput(t){!this.terminalAttachSuspended||!t||this.writeTerminalPassthrough(t)}getTerminalSize(){return{cols:Math.max(1,process.stdout.columns||this.cols||80),rows:Math.max(1,process.stdout.rows||this.rows||24)}}getRenderCols(){return this.renderCols()}formatUserPrompt(t){return this.formatUserPromptMessage(t)}resumeFromTerminalAttach(){!this.terminalAttachSuspended||this.cleaned||(this.writeTerminalControl("\x1B[?1049l\x1B[?1047l\x1B[?47l\x1B[0m\x1B[?25h"+this.bracketedPasteModeControl(!0),"pty-detach"),this.terminalAttachSuspended=!1,this.calculateLayout(),this.setupRawMode(),this.setupResize(),this.startStatusLineCommand(),this._busy&&this.startBusyActivityTicker(),this.redrawScreenFromHistory(),this.synchronizeToolActivityAnimation(),this.drawInputBox(),this.footerRenderer().invalidate(),this.footerFrameScheduler?.resume(!1),this.refreshFooterFocusCursor())}setTaskProgressItems(t){let n=t.map(o=>({...o,blockedBy:o.blockedBy?.slice()??[]})),r=this.currentTaskProgressSignature();this.taskProgressItems=n;let i=this.currentTaskProgressSignature();r!==i&&!this.resizeInProgress&&!this.hasOverlayOpen()&&this.scheduleFooterFrame(`tasks:${i}`)}setAgentSessionFooterItems(t){let n=this.agentSessionFooterRenderSignature;this.agentSessionFooterItems=t.slice(),this.uiStateStore().dispatch({type:"agents.changed",agents:this.agentSessionFooterItems});let r=(this.agentSessionFooterItems??[]).length;this.agentSessionFooterFocusIndex=Math.max(0,Math.min(this.agentSessionFooterFocusIndex,r)),this.normalizeAgentSessionFooterWindow(),(this.agentSessionFooterItems??[]).length===0&&this.footerFocus==="agentSession"&&(this.footerFocus="input",this.agentSessionFooterFocusIndex=0,this.agentSessionFooterScrollOffset=0),this.redrawAgentSessionFooterIfChanged(n)}setPendingAgentSessionNotifications(t){let n=t.map(i=>i.trim()).filter(Boolean),r=this.pendingAgentSessionNotificationItems();r.length===n.length&&r.every((i,o)=>i===n[o])||(this.pendingAgentSessionNotifications=n,!this.resizeInProgress&&!this.hasOverlayOpen()&&(this.drawInputBox(),this.refreshFooterFocusCursor()))}setActiveAgentSessionFooterId(t){let n=this.agentSessionFooterRenderSignature;this.activeAgentSessionFooterId=t,this.redrawAgentSessionFooterIfChanged(n)}openAgentSessionChatView(t){this.agentSessionChatViewState?.onClose?.(),this.agentSessionChatViewState={sessionId:t.sessionId,title:t.title,subtitle:t.subtitle,placeholder:t.placeholder??"Message this agent session...",historyText:t.historyText??"",pendingUserInputs:[],activityText:t.activityText,activityStartedAt:t.activityStartedAt,activityActive:t.activityActive,submitting:!1,error:void 0,onSubmit:t.onSubmit,onClose:t.onClose},this.activeAgentSessionFooterId=t.sessionId,this.footerFocus="input",this.inputBuffer="",this.cursorPos=0,this.invalidateInputProjection(),this.resetInputVisualState(),this.closeAutocomplete(),this.setMouseReportingEnabled(!1),this.redrawScreenFromHistory(),this.drawInputBox(),this.refreshFooterFocusCursor()}updateAgentSessionChatView(t,n,r){this.agentSessionChatViewState&&(this.agentSessionChatViewState.historyText=t,this.agentSessionChatViewState.pendingUserInputs=this.agentSessionChatViewState.pendingUserInputs.filter(i=>!t.includes(i)),n!==void 0&&(this.agentSessionChatViewState.subtitle=n),r&&(this.agentSessionChatViewState.activityText=r.activityText,this.agentSessionChatViewState.activityStartedAt=r.activityStartedAt,this.agentSessionChatViewState.activityActive=r.activityActive),this.hasOverlayOpen()||(this.redrawScreenFromHistory(),this.drawInputBox(),this.refreshFooterFocusCursor()))}closeAgentSessionChatView(){let t=this.agentSessionChatViewState;t&&(this.agentSessionChatViewState=null,this.activeAgentSessionFooterId=null,this.footerFocus="input",this.agentSessionFooterFocusIndex=0,this.inputBuffer="",this.cursorPos=0,this.invalidateInputProjection(),this.resetInputVisualState(),this.closeAutocomplete(),t.onClose?.(),this.redrawScreenFromHistory(),this.drawInputBox(),this.refreshFooterFocusCursor())}returnToMainAgentSessionFooter(){if(this.agentSessionChatViewState){this.closeAgentSessionChatView();return}this.footerFocus="input",this.agentSessionFooterFocusIndex=0,this.setMouseReportingEnabled(!1),this.hasOverlayOpen()||(this.drawInputBox(),this.refreshFooterFocusCursor())}getBackgroundTaskCount(){return this._backgroundTaskCount}takeQueuedMessage(){return this.queuedMessages().shift()??null}get awaitingHumanPrompt(){return this.isPrompting}get canAcceptExternalInput(){return!this._busy&&!this.isPrompting&&!this.hasOverlayOpen()&&this.inputBuffer.trim().length===0}enqueueMessage(t){let n=t.trim();return n?this.canAcceptExternalInput?(this.setInputText(n,{cursor:"end",escCancelable:!1}),this.handleEnter(),"submitted"):(this.queuedMessages().push(n),this.drawInputBox(),"queued"):"ignored"}echoUserPrompt(t,n=!1){n&&this.inputHistory.push(t);let r=this.collapseClipboardImagesForDisplay(t);this.writeOutput(`
3181
3181
  ${this.formatUserPromptMessage(r)}
3182
- `,{forceNewBlock:!0,selectable:!0,blockKind:"user"})}get hasQueuedMessage(){return this.queuedMessages().length>0}updateTokens(t,n){this.tokensUsed=t,n!==void 0&&(this.costDisplay=n),this.drawStatusBar()}getCostDisplay(){return this.costDisplay}getTurnDurationVisible(){return this.turnDurationVisible}setTurnDurationVisible(t){if(typeof t!="boolean")throw new Error("Turn duration visibility must be boolean.");this.turnDurationVisible=t}setContextTokens(t,n=!1){!Number.isFinite(t)||t<0||this.contextTokens===t&&this.contextTokensEstimated===n||(this.contextTokens=t,this.contextTokensEstimated=n,this.drawStatusBar())}setModel(t){this.opts.model=t,this.drawStatusBar()}setSessionName(t){this.opts.sessionName=t,this.drawInputBox()}setEffort(t){t?this.opts.effort=t:delete this.opts.effort,this.drawStatusBar()}setPermissionMode(t){this.opts.permissionMode=t,this.drawInputBox(),this.drawStatusBar()}setExecutionMode(t){this.opts.executionMode=t,this.drawStatusBar()}setProviderSessionStatus(t){this.providerSessionStatus=t?{...t}:void 0,this.drawStatusBar()}setDelegationEnabled(t){this.delegationEnabled=t,this.drawStatusBar()}setPromptContextBreakdown(t){this.promptContextBreakdown=(t||"").trim(),this.drawStatusBar()}setVimMode(t){this.vimInputMode=t,this.vimInsertMode=!0,this.setStatusRightHint(t?"Vim input enabled":"Vim input disabled",3e3),this.drawInputBox()}refreshTheme(){if(this.permissionState){this.drawPermissionUI();return}if(this.modelPickerState){this.drawModelPickerUI();return}if(this.sessionPickerState){this.drawSessionPickerUI();return}if(this.helpPanelState){this.drawHelpPanelUI();return}if(this.statusPanelState){this.drawStatusPanelUI();return}if(this.infoPanelState){this.drawInfoPanelUI();return}this.drawInputBox(),this.drawStatusBar(),this.refreshFooterFocusCursor()}startDelegationView(t){this.delegationLogDockExpanded=!1,this.delegationLogDockScrollOffset=0,this.delegationFocusIndex=0,this.delegationCompletionState?.timer&&clearTimeout(this.delegationCompletionState.timer),this.delegationCompletionState=null,this.delegationViewState={startedAt:Date.now(),agents:t.map(n=>({role:n,status:"queued",phase:"queued",activity:"Waiting",toolCount:0,tokenCount:0,events:[]})),events:[]},this.redrawDelegationFooter()}updateDelegationAgent(t,n){if(!this.delegationViewState)return;let r=this.delegationViewState.agents.find(i=>i.role===t);r&&(n.status!==void 0&&(r.status=n.status),n.phase!==void 0&&(r.phase=n.phase),n.activity!==void 0&&(r.activity=n.activity),n.toolCount!==void 0&&(r.toolCount=n.toolCount),n.tokenCount!==void 0&&(r.tokenCount=n.tokenCount),n.currentTool!==void 0&&(r.currentTool=n.currentTool),n.outputPreview!==void 0&&(r.outputPreview=n.outputPreview),this.refreshDelegationViews())}appendDelegationEvent(t,n){if(!this.delegationViewState)return;let r=t.trim().length>0?t:"system",i=this.getDelegationLogDockVisibleLines(),o=Math.max(0,this.delegationViewState.events.length-i),s=!this.delegationLogDockExpanded||this.delegationLogDockScrollOffset>=o;this.delegationViewState.events.push({role:r,message:n,timestamp:Date.now()}),this.delegationViewState.events.length>12&&this.delegationViewState.events.shift();let a=this.delegationViewState.agents.find(d=>d.role===r);a&&(a.events.push({role:r,message:n,timestamp:Date.now()}),a.events.length>200&&a.events.shift());let c=this.getDelegationLogDockVisibleLines(),l=Math.max(0,this.delegationViewState.events.length-c);s?this.delegationLogDockScrollOffset=l:this.delegationLogDockScrollOffset=Math.max(0,Math.min(this.delegationLogDockScrollOffset,l)),this.refreshDelegationViews()}clearDelegationView(){if(!this.delegationViewState)return;let t=this.shouldUseDelegationLogDock();this.delegationCompletionState?.timer&&clearTimeout(this.delegationCompletionState.timer),this.delegationCompletionState=null,(this.infoPanelState?.source==="delegation-inspector"||this.infoPanelState?.source==="delegation-agent-detail")&&(this.infoPanelState=null,this.calculateLayout(),this.writeTerminalControl(C.setScrollRegion(1,this.outputBottom),"scroll-region"),this.redrawScreenFromHistory()),this.delegationViewState=null,this.delegationLogDockExpanded=!1,this.delegationLogDockScrollOffset=0,this.footerFocus==="delegation"&&(this.footerFocus="input"),t&&!this.resizeInProgress&&this.redrawScreenFromHistory(),this.redrawDelegationFooter()}showDelegationCompletionSummary(t,n=5e3){this.delegationCompletionState?.timer&&clearTimeout(this.delegationCompletionState.timer);let r=setTimeout(()=>{this.delegationCompletionState=null,!this.resizeInProgress&&!this.hasOverlayOpen()&&(this.drawInputBox(),this.refreshFooterFocusCursor())},n);this.delegationCompletionState={text:t,timer:r},!this.resizeInProgress&&!this.hasOverlayOpen()&&(this.drawInputBox(),this.refreshFooterFocusCursor())}showTransientActivityNotice(t,n=4e3){this.transientActivityNotice?.timer&&clearTimeout(this.transientActivityNotice.timer);let r=setTimeout(()=>{this.transientActivityNotice=null,!this.resizeInProgress&&!this.hasOverlayOpen()&&(this.drawInputBox(),this.refreshFooterFocusCursor())},n);this.transientActivityNotice={text:t,timer:r},!this.resizeInProgress&&!this.hasOverlayOpen()&&(this.drawInputBox(),this.refreshFooterFocusCursor())}appendRawOutputBlock(t,n){let r=!!n?.selectable,i=n?.blockKind,o=!!n?.forceNewBlock,s=this.shouldReflowOutputKind(i),a=s?this.wrapOutputForTerminal(t):t,c=this.outputBlocks[this.outputBlocks.length-1];return!o&&c?.type==="raw"&&!!c.selectable===r&&(c.kind??null)===(i??null)?(c.sourceText=(c.sourceText??c.text)+t,c.text+=a,a):(this.outputBlocks.push({type:"raw",text:a,sourceText:s?t:void 0,selectable:r,kind:i}),a)}syncRenderedOutputHistory(){let t=this.renderOutputBlocksWithOffsets();this.outputHistory=t.text,this.renderedOutputBlockOffsets=t.blockOffsets,this.refreshToolActivityAnimationPositions()}activeOutputHistory(){return this.agentSessionChatViewState?this.renderAgentSessionChatOutput(this.agentSessionChatViewState):this.outputHistory}renderAgentSessionChatOutput(t){let n=this.renderCols(),r=[],i=t.historyText.trimEnd();i.length===0?(r.push(L("No transcript messages yet.")),r.push(L("The agent is still starting or waiting for its first output."))):r.push(i);for(let o of t.pendingUserInputs)r.push(`
3182
+ `,{forceNewBlock:!0,selectable:!0,blockKind:"user"})}get hasQueuedMessage(){return this.queuedMessages().length>0}updateTokens(t,n){this.tokensUsed=t,n!==void 0&&(this.costDisplay=n),this.drawStatusBar()}getCostDisplay(){return this.costDisplay}getTurnDurationVisible(){return this.turnDurationVisible}setTurnDurationVisible(t){if(typeof t!="boolean")throw new Error("Turn duration visibility must be boolean.");this.turnDurationVisible=t}setContextTokens(t,n=!1){!Number.isFinite(t)||t<0||this.contextTokens===t&&this.contextTokensEstimated===n||(this.contextTokens=t,this.contextTokensEstimated=n,this.drawStatusBar())}setModel(t){this.opts.model=t,this.drawStatusBar()}setSessionName(t){this.opts.sessionName=t,this.drawInputBox()}setEffort(t){t?this.opts.effort=t:delete this.opts.effort,this.drawStatusBar()}setPermissionMode(t){this.opts.permissionMode=t,this.drawInputBox(),this.drawStatusBar()}setExecutionMode(t){this.opts.executionMode=t,this.drawStatusBar()}setProviderSessionStatus(t){this.providerSessionStatus=t?{...t}:void 0,this.drawStatusBar()}setDelegationEnabled(t){this.delegationEnabled=t,this.drawStatusBar()}setPromptContextBreakdown(t){this.promptContextBreakdown=(t||"").trim(),this.drawStatusBar()}setVimMode(t){this.vimInputMode=t,this.vimInsertMode=!0,this.setStatusRightHint(t?"Vim input enabled":"Vim input disabled",3e3),this.drawInputBox()}refreshTheme(){if(this.permissionState){this.drawPermissionUI();return}if(this.modelPickerState){this.drawModelPickerUI();return}if(this.sessionPickerState){this.drawSessionPickerUI();return}if(this.helpPanelState){this.drawHelpPanelUI();return}if(this.statusPanelState){this.drawStatusPanelUI();return}if(this.infoPanelState){this.drawInfoPanelUI();return}this.drawInputBox(),this.drawStatusBar(),this.refreshFooterFocusCursor()}startDelegationView(t){this.delegationLogDockExpanded=!1,this.delegationLogDockScrollOffset=0,this.delegationFocusIndex=0,this.delegationCompletionState?.timer&&clearTimeout(this.delegationCompletionState.timer),this.delegationCompletionState=null,this.delegationViewState={startedAt:Date.now(),agents:t.map(n=>({role:n,status:"queued",phase:"queued",activity:"Waiting",toolCount:0,tokenCount:0,events:[]})),events:[]},this.redrawDelegationFooter()}updateDelegationAgent(t,n){if(!this.delegationViewState)return;let r=this.delegationViewState.agents.find(i=>i.role===t);r&&(n.status!==void 0&&(r.status=n.status),n.phase!==void 0&&(r.phase=n.phase),n.activity!==void 0&&(r.activity=n.activity),n.toolCount!==void 0&&(r.toolCount=n.toolCount),n.tokenCount!==void 0&&(r.tokenCount=n.tokenCount),n.currentTool!==void 0&&(r.currentTool=n.currentTool),n.outputPreview!==void 0&&(r.outputPreview=n.outputPreview),this.refreshDelegationViews())}appendDelegationEvent(t,n){if(!this.delegationViewState)return;let r=t.trim().length>0?t:"system",i=this.getDelegationLogDockVisibleLines(),o=Math.max(0,this.delegationViewState.events.length-i),s=!this.delegationLogDockExpanded||this.delegationLogDockScrollOffset>=o;this.delegationViewState.events.push({role:r,message:n,timestamp:Date.now()}),this.delegationViewState.events.length>12&&this.delegationViewState.events.shift();let a=this.delegationViewState.agents.find(d=>d.role===r);a&&(a.events.push({role:r,message:n,timestamp:Date.now()}),a.events.length>200&&a.events.shift());let c=this.getDelegationLogDockVisibleLines(),l=Math.max(0,this.delegationViewState.events.length-c);s?this.delegationLogDockScrollOffset=l:this.delegationLogDockScrollOffset=Math.max(0,Math.min(this.delegationLogDockScrollOffset,l)),this.refreshDelegationViews()}clearDelegationView(){if(!this.delegationViewState)return;let t=this.shouldUseDelegationLogDock();this.delegationCompletionState?.timer&&clearTimeout(this.delegationCompletionState.timer),this.delegationCompletionState=null,(this.infoPanelState?.source==="delegation-inspector"||this.infoPanelState?.source==="delegation-agent-detail")&&(this.infoPanelState=null,this.calculateLayout(),this.writeTerminalControl(C.setScrollRegion(1,this.outputBottom),"scroll-region"),this.redrawScreenFromHistory()),this.delegationViewState=null,this.delegationLogDockExpanded=!1,this.delegationLogDockScrollOffset=0,this.footerFocus==="delegation"&&(this.footerFocus="input"),t&&!this.resizeInProgress&&this.redrawScreenFromHistory(),this.redrawDelegationFooter()}showDelegationCompletionSummary(t,n=5e3){this.delegationCompletionState?.timer&&clearTimeout(this.delegationCompletionState.timer);let r=setTimeout(()=>{this.delegationCompletionState=null,!this.resizeInProgress&&!this.hasOverlayOpen()&&(this.drawInputBox(),this.refreshFooterFocusCursor())},n);this.delegationCompletionState={text:t,timer:r},!this.resizeInProgress&&!this.hasOverlayOpen()&&(this.drawInputBox(),this.refreshFooterFocusCursor())}showTransientActivityNotice(t,n=4e3){this.transientActivityNotice?.timer&&clearTimeout(this.transientActivityNotice.timer);let r=setTimeout(()=>{this.transientActivityNotice=null,!this.resizeInProgress&&!this.hasOverlayOpen()&&(this.drawInputBox(),this.refreshFooterFocusCursor())},n);this.transientActivityNotice={text:t,timer:r},!this.resizeInProgress&&!this.hasOverlayOpen()&&(this.drawInputBox(),this.refreshFooterFocusCursor())}lastAppendExtendedBlock=!1;appendRawOutputBlock(t,n){let r=!!n?.selectable,i=n?.blockKind,o=!!n?.forceNewBlock,s=this.shouldReflowOutputKind(i),a=s?this.wrapOutputForTerminal(t):t,c=this.outputBlocks[this.outputBlocks.length-1];return!o&&c?.type==="raw"&&!!c.selectable===r&&(c.kind??null)===(i??null)?(c.sourceText=(c.sourceText??c.text)+t,c.text+=a,this.lastAppendExtendedBlock=!0,a):(this.lastAppendExtendedBlock=!1,this.outputBlocks.push({type:"raw",text:a,sourceText:s?t:void 0,selectable:r,kind:i}),a)}syncRenderedOutputHistory(){let t=this.renderOutputBlocksWithOffsets();this.outputHistory=t.text,this.renderedOutputBlockOffsets=t.blockOffsets,this.renderedOutputEndCol=t.endCol,this.refreshToolActivityAnimationPositions()}syncRenderedOutputHistoryAfterAppend(t){let n=this.outputBlocks,r=n.length-1,i=n[r],o=this.renderedOutputBlockOffsets??[],s=t?n.length:n.length-1,a=n[r-1];if(!(i?.type==="raw"&&o.length===s&&(this.outputActionState??null)===null&&this.renderedOutputWidth===this.renderCols()&&i.kind!=="tool-activity"&&a?.kind!=="tool-activity")){this.syncRenderedOutputHistory();return}let l=t?o[r]:this.outputHistory.length,d=t?this.renderedOutputBlockStartCol:this.renderedOutputEndCol,u=this.shouldReflowRawOutputBlock(i)?this.getRawOutputBlockRenderableText(i,d):this.getRenderableOutputSegment(i,r);this.outputHistory=t?this.outputHistory.slice(0,l)+u:this.outputHistory+u,t||(this.renderedOutputBlockOffsets=[...o,l]),this.renderedOutputBlockStartCol=d,this.renderedOutputEndCol=this.getOutputEndColumn(u,d),this.toolActivityAnimationTimer&&this.refreshToolActivityAnimationPositions()}activeOutputHistory(){return this.agentSessionChatViewState?this.renderAgentSessionChatOutput(this.agentSessionChatViewState):this.outputHistory}renderAgentSessionChatOutput(t){let n=this.renderCols(),r=[],i=t.historyText.trimEnd();i.length===0?(r.push(L("No transcript messages yet.")),r.push(L("The agent is still starting or waiting for its first output."))):r.push(i);for(let o of t.pendingUserInputs)r.push(`
3183
3183
  ${this.formatUserPromptMessage(o)}
3184
3184
  `);return t.submitting&&r.push(L("Queued message...")),t.error&&r.push(K.red(this.clip(t.error,n))),this.normalizeOutputViewportText(r.join(`
3185
3185
  `))}formatUserPromptMessage(t){let n=gU(t),r=this.renderCols(),i="\x1B[48;2;40;40;42m\x1B[38;2;240;240;240m",o="\x1B[0m",s=Te("\u276F"),a=Math.max(10,r-4),c=n.split(`
@@ -3190,9 +3190,9 @@ ${this.formatUserPromptMessage(o)}
3190
3190
  `)}getOutputViewportVisibleRows(){return Math.max(1,this.outputBottom)}splitOutputTextLines(t){let n=t.replace(/\r\n/g,`
3191
3191
  `);if(n.length===0)return[];let r=n.split(`
3192
3192
  `);return r.length>0&&r[r.length-1]===""&&r.pop(),r}styleFocusedOutputLines(t,n){let r=t.findIndex(c=>Jr(c).trim().length>0);if(r===-1)return t.slice();let i=r;for(let c=t.length-1;c>=r;c--)if(Jr(t[c]).trim().length>0){i=c;break}let o=n?LNt:Hs,s=Math.max(10,this.cols),a=[];for(let c=0;c<t.length;c++){let l=t[c];if(c<r||c>i){a.push(l);continue}let d=Jr(l);if(d.length===0){a.push(l);continue}if(d.length>s)for(let u=0;u<d.length;u+=s)a.push(o(d.slice(u,u+s)));else a.push(o(d))}return a}getFocusedOutputRelatedIndices(){let t=new Set;if(this.outputFocusIndex<0)return t;t.add(this.outputFocusIndex);let n=this.outputBlocks[this.outputFocusIndex],r=this.outputBlocks[this.outputFocusIndex-1];return n?.type==="collapsible"&&this.isToolCallPreviewBlock(r)&&t.add(this.outputFocusIndex-1),t}renderOutputBlockLinesForViewport(t,n){let i=(this.footerFocus==="output"?this.getFocusedOutputRelatedIndices():new Set).has(n),o=t.type==="collapsible"?this.getCollapsibleText(t):this.getRawOutputBlockRenderableText(t,1),s=t.type==="raw"&&this.isOutputActionRowOpenForBlock(n);s&&(o=o.replace(/\n$/,""));let a=this.splitOutputTextLines(o);if(i){let l=this.outputActionState?.blockIndex===n&&this.outputActionState.focus!=="message";a=this.styleFocusedOutputLines(a,l)}if(!s)return a;let c=this.splitOutputTextLines(this.renderOutputActionRow(n));return c[0]===""&&c.shift(),a.concat(c)}buildFocusedOutputViewport(){let t=[],n=new Map;return this.outputBlocks.forEach((r,i)=>{let o=this.renderOutputBlockLinesForViewport(r,i),s=t.length;t.push(...o);let a=Math.max(s,t.length-1);n.set(i,{start:s,end:a})}),{lines:t,blockRanges:n}}keepFocusedOutputBlockInView(t){let n=this.getOutputViewportVisibleRows(),r=Math.max(0,t.lines.length-n),o=[...this.getFocusedOutputRelatedIndices()].map(c=>t.blockRanges.get(c)).filter(c=>!!c),s=o.length===0?null:{start:Math.min(...o.map(c=>c.start)),end:Math.max(...o.map(c=>c.end))};if(!s){this.outputViewportTopLine=r;return}if(this.outputViewportTopLine=Math.max(0,Math.min(this.outputViewportTopLine,r)),s.end-s.start+1>=n){let c=s.start,l=Math.max(s.start,s.end-n+1);this.outputViewportTopLine<c?this.outputViewportTopLine=c:this.outputViewportTopLine>l&&(this.outputViewportTopLine=l)}else s.start<this.outputViewportTopLine?this.outputViewportTopLine=s.start:s.end>=this.outputViewportTopLine+n&&(this.outputViewportTopLine=Math.max(0,s.end-n+1));this.outputViewportTopLine=Math.max(0,Math.min(this.outputViewportTopLine,r))}clampOutputViewportTopLine(t){let n=this.getOutputViewportVisibleRows(),r=Math.max(0,t.lines.length-n);this.outputViewportTopLine=Math.max(0,Math.min(this.outputViewportTopLine,r))}pageScrollOutputViewport(t){let n=this.buildFocusedOutputViewport();if(n.lines.length===0)return;let r=this.getOutputViewportVisibleRows(),i=Math.max(1,r-1)*t;this.outputViewportTopLine+=i,this.outputViewportManualScroll=!0,this.clampOutputViewportTopLine(n),this.redrawScreenFromHistory(),this.drawInputBox()}wheelScrollOutputViewport(t){let n=this.buildFocusedOutputViewport();n.lines.length!==0&&(this.outputViewportTopLine+=t*3,this.outputViewportManualScroll=!0,this.clampOutputViewportTopLine(n),this.redrawScreenFromHistory(),this.drawInputBox())}jumpOutputViewport(t){let n=this.buildFocusedOutputViewport();if(n.lines.length===0)return;let r=this.getOutputViewportVisibleRows();this.outputViewportTopLine=t==="start"?0:Math.max(0,n.lines.length-r),this.outputViewportManualScroll=!0,this.redrawScreenFromHistory(),this.drawInputBox()}isToolCallPreviewBlock(t){if(!t||t.type!=="raw")return!1;let n=Jr(t.text).trimStart();return n.startsWith("\u25A0 ")||n.startsWith("\u25CF ")}isPairedToolCallBlock(t){let n=this.outputBlocks[t],r=this.outputBlocks[t+1];return this.isToolCallPreviewBlock(n)&&!!(r&&r.type==="collapsible"&&(r.kind??"tool-result")==="tool-result")}getRenderableOutputSegment(t,n){if(t.type==="collapsible"){let r=this.getCollapsibleText(t),i=`
3193
- `.repeat(t.trailingNewlines);return r+i}return this.renderOutputBlock(t,n)}renderOutputBlocksWithOffsets(){let t=1,n="",r=[];for(let i=0;i<this.outputBlocks.length;i++){let o=this.outputBlocks[i],s=o.type==="raw"&&this.shouldReflowRawOutputBlock(o)?this.getRawOutputBlockRenderableText(o,t):this.getRenderableOutputSegment(o,i),a=this.outputBlocks[i-1];if(!!(a&&(a.kind==="tool-activity"||o.kind==="tool-activity"))&&n.length>0&&s.length>0){n=n.replace(/\n+$/,""),s=s.replace(/^\n+/,"");let l=this.getOutputEndColumn(n,1),d=`
3193
+ `.repeat(t.trailingNewlines);return r+i}return this.renderOutputBlock(t,n)}renderOutputBlocksWithOffsets(){let t=1,n="",r=[];this.renderedOutputWidth=this.renderCols();for(let i=0;i<this.outputBlocks.length;i++){let o=this.outputBlocks[i];this.renderedOutputBlockStartCol=t;let s=o.type==="raw"&&this.shouldReflowRawOutputBlock(o)?this.getRawOutputBlockRenderableText(o,t):this.getRenderableOutputSegment(o,i),a=this.outputBlocks[i-1];if(!!(a&&(a.kind==="tool-activity"||o.kind==="tool-activity"))&&n.length>0&&s.length>0){n=n.replace(/\n+$/,""),s=s.replace(/^\n+/,"");let l=this.getOutputEndColumn(n,1),d=`
3194
3194
 
3195
- ${s}`;r[i]=n.length+2,n+=d,t=this.getOutputEndColumn(d,l)}else r[i]=n.length,n+=s,t=this.getOutputEndColumn(s,t)}return{text:n,blockOffsets:r}}renderOutputBlocks(){return this.renderOutputBlocksWithOffsets().text}getCollapsibleOutputBlockIndices(){return this.outputBlocks.map((t,n)=>({block:t,index:n})).filter(({block:t})=>t.type==="collapsible").map(({index:t})=>t)}getSelectableOutputBlockIndices(){return this.outputBlocks.map((t,n)=>({block:t,index:n})).filter(({block:t,index:n})=>t.type==="collapsible"?!0:!(!t.selectable||this.isPairedToolCallBlock(n))).map(({index:t})=>t)}hasCollapsibleOutputBlocks(){return this.getCollapsibleOutputBlockIndices().length>0}hasSelectableOutputBlocks(){return this.getSelectableOutputBlockIndices().length>0}getFocusedOutputBlockIndex(){return this.outputFocusIndex}getFocusedOutputBlock(){return this.outputBlocks[this.outputFocusIndex]??null}isUserActionableOutputBlock(t){return!!(t&&t.type==="raw"&&t.kind==="user")}getCollapsibleText(t){let n=t.expanded?t.expandedText:t.summaryText;if(!t.expanded||!t.secondaryAction)return n;let r=`
3195
+ ${s}`;r[i]=n.length+2,n+=d,t=this.getOutputEndColumn(d,l)}else r[i]=n.length,n+=s,t=this.getOutputEndColumn(s,t)}return{text:n,blockOffsets:r,endCol:t}}renderOutputBlocks(){return this.renderOutputBlocksWithOffsets().text}getCollapsibleOutputBlockIndices(){return this.outputBlocks.map((t,n)=>({block:t,index:n})).filter(({block:t})=>t.type==="collapsible").map(({index:t})=>t)}getSelectableOutputBlockIndices(){return this.outputBlocks.map((t,n)=>({block:t,index:n})).filter(({block:t,index:n})=>t.type==="collapsible"?!0:!(!t.selectable||this.isPairedToolCallBlock(n))).map(({index:t})=>t)}hasCollapsibleOutputBlocks(){return this.getCollapsibleOutputBlockIndices().length>0}hasSelectableOutputBlocks(){return this.getSelectableOutputBlockIndices().length>0}getFocusedOutputBlockIndex(){return this.outputFocusIndex}getFocusedOutputBlock(){return this.outputBlocks[this.outputFocusIndex]??null}isUserActionableOutputBlock(t){return!!(t&&t.type==="raw"&&t.kind==="user")}getCollapsibleText(t){let n=t.expanded?t.expandedText:t.summaryText;if(!t.expanded||!t.secondaryAction)return n;let r=`
3196
3196
  ${L("\u2514")} ${L(t.secondaryActionLabel??"Press Enter again to open details")}`;return n.endsWith(`
3197
3197
  `)?`${n}${r.trimStart()}`:`${n}${r}`}isOutputActionRowOpenForBlock(t){return this.outputActionState?.blockIndex===t}openOutputActionRow(t){this.outputActionState={blockIndex:t,focus:"actions",selectedActionIndex:0,pendingAction:null},this.redrawScreenFromHistory(),this.drawInputBox()}closeOutputActionRow(t){this.outputActionState=null,t?.returnToInput!==!1&&(this.footerFocus="input",this.setMouseReportingEnabled(!1)),this.redrawScreenFromHistory(),this.drawInputBox(),this.refreshFooterFocusCursor()}exitOutputFocus(){this.outputActionState=null,this.footerFocus="input",this.outputViewportManualScroll=!1,this.setMouseReportingEnabled(!1),this.redrawScreenFromHistory(),this.drawInputBox(),this.refreshFooterFocusCursor()}renderOutputActionRow(t){if(!this.isOutputActionRowOpenForBlock(t))return"";let n=this.outputActionState;if(n.focus==="message")return"";if(n.pendingAction){let a=n.focus==="confirm"?Hs("[CONFIRM]"):L("[CONFIRM]");return`
3198
3198
  ${L("\u2514")} ${a}`}let r=n.focus==="actions"?n.selectedActionIndex:-1,i=r===0?Hs("[EDIT]"):L("[EDIT]"),o=r===1?Hs("[RETRY]"):L("[RETRY]"),s=r===2?Hs("[RESTORE]"):L("[RESTORE]");return`
@@ -3200,7 +3200,7 @@ ${s}`;r[i]=n.length+2,n+=d,t=this.getOutputEndColumn(d,l)}else r[i]=n.length,n+=
3200
3200
  `).replace(/^\n?❯\s*/,"").trim(),o=this.outputBlocks.map((a,c)=>({candidate:a,index:c})).filter(({candidate:a})=>a.type==="raw"&&a.kind==="user").map(({index:a})=>a),s=Math.max(0,o.indexOf(t.blockIndex));return{action:t.pendingAction,text:i,userMessageOrdinal:s}}renderOutputBlock(t,n){if(t.type==="collapsible")return this.getCollapsibleText(t);let r=this.getRawOutputBlockRenderableText(t,1);return this.isOutputActionRowOpenForBlock(n)&&(r=r.replace(/\n$/,""),r+=this.renderOutputActionRow(n),r.endsWith(`
3201
3201
  `)||(r+=`
3202
3202
  `)),r}focusLatestOutputBlock(){let t=this.getSelectableOutputBlockIndices();if(t.length===0)return;this.footerFocus="output",this.setMouseReportingEnabled(!0),this.outputFocusIndex=t[t.length-1],this.outputViewportManualScroll=!1;let n=this.buildFocusedOutputViewport();this.outputViewportTopLine=Math.max(0,n.lines.length-this.getOutputViewportVisibleRows()),this.keepFocusedOutputBlockInView(n),this.redrawScreenFromHistory(),this.drawInputBox()}moveOutputFocus(t){let n=this.getSelectableOutputBlockIndices();if(n.length===0)return;this.setMouseReportingEnabled(!0);let r=n.indexOf(this.outputFocusIndex),i=r===-1?t>0?0:n.length-1:Math.max(0,Math.min(n.length-1,r+t));this.outputFocusIndex=n[i],this.outputViewportManualScroll=!1,this.keepFocusedOutputBlockInView(this.buildFocusedOutputViewport()),this.redrawScreenFromHistory(),this.drawInputBox()}getFocusedOutputViewportText(){if(this.outputFocusIndex<0)return null;let t=this.buildFocusedOutputViewport();if(t.lines.length===0)return null;this.outputViewportManualScroll?this.clampOutputViewportTopLine(t):this.keepFocusedOutputBlockInView(t);let n=this.getOutputViewportVisibleRows(),r=t.lines.slice(this.outputViewportTopLine,this.outputViewportTopLine+n);return this.normalizeOutputViewportText(r.join(`
3203
- `))}writeCollapsibleInfo(t,n,r){let i=r?.updateKey?this.outputBlocks.find(u=>u.type==="collapsible"&&u.updateKey===r.updateKey):void 0,o=i?this.getCollapsibleText(i):null,s=i?.trailingNewlines,a=i?.kind,c=i?.activeAnimation,l=i??{type:"collapsible",updateKey:r?.updateKey,summaryText:t,expandedText:n,expanded:r?.expanded??r?.initiallyExpanded??!!this._verboseToolOutput,trailingNewlines:r?.trailingNewlines??1,selectable:r?.selectable??!0,kind:r?.blockKind??"tool-result",activeAnimation:r?.activeAnimation??!1,autoCollapseTimer:null,secondaryActionLabel:r?.secondaryActionLabel,secondaryAction:r?.secondaryAction};i?(i.autoCollapseTimer&&clearTimeout(i.autoCollapseTimer),i.autoCollapseTimer=null,i.summaryText=t,i.expandedText=n,r?.expanded!==void 0&&(i.expanded=r.expanded),i.trailingNewlines=r?.trailingNewlines??i.trailingNewlines,i.selectable=r?.selectable??i.selectable,i.kind=r?.blockKind??i.kind,i.activeAnimation=r?.activeAnimation??i.activeAnimation,i.secondaryActionLabel=r?.secondaryActionLabel,i.secondaryAction=r?.secondaryAction):this.outputBlocks.push(l);let d=!i||o!==this.getCollapsibleText(l)||s!==l.trailingNewlines||a!==l.kind||c!==l.activeAnimation;d&&this.syncRenderedOutputHistory(),l.expanded&&r?.autoCollapseMs&&r.autoCollapseMs>0&&(l.autoCollapseTimer=setTimeout(()=>{l.expanded=!1,l.autoCollapseTimer=null,this.syncRenderedOutputHistory(),this.resizeInProgress||this.redrawConversationOutputFromHistory()},r.autoCollapseMs)),d&&this.redrawConversationOutputFromHistory(),this.synchronizeToolActivityAnimation()}writeOutput(t,n){if(!t)return;let r=this.appendRawOutputBlock(t,n);if(this.syncRenderedOutputHistory(),this.terminalAttachSuspended)return;if(this.agentSessionChatViewState){this.redrawScreenFromHistory(),this.drawInputBox(),this.refreshFooterFocusCursor();return}let i="";i+=C.hideCursor(),i+=C.moveTo(this.outputRow,this.outputCol),i+=r.replace(/\r?\n/g,`\r
3203
+ `))}writeCollapsibleInfo(t,n,r){let i=r?.updateKey?this.outputBlocks.find(u=>u.type==="collapsible"&&u.updateKey===r.updateKey):void 0,o=i?this.getCollapsibleText(i):null,s=i?.trailingNewlines,a=i?.kind,c=i?.activeAnimation,l=i??{type:"collapsible",updateKey:r?.updateKey,summaryText:t,expandedText:n,expanded:r?.expanded??r?.initiallyExpanded??!!this._verboseToolOutput,trailingNewlines:r?.trailingNewlines??1,selectable:r?.selectable??!0,kind:r?.blockKind??"tool-result",activeAnimation:r?.activeAnimation??!1,autoCollapseTimer:null,secondaryActionLabel:r?.secondaryActionLabel,secondaryAction:r?.secondaryAction};i?(i.autoCollapseTimer&&clearTimeout(i.autoCollapseTimer),i.autoCollapseTimer=null,i.summaryText=t,i.expandedText=n,r?.expanded!==void 0&&(i.expanded=r.expanded),i.trailingNewlines=r?.trailingNewlines??i.trailingNewlines,i.selectable=r?.selectable??i.selectable,i.kind=r?.blockKind??i.kind,i.activeAnimation=r?.activeAnimation??i.activeAnimation,i.secondaryActionLabel=r?.secondaryActionLabel,i.secondaryAction=r?.secondaryAction):this.outputBlocks.push(l);let d=!i||o!==this.getCollapsibleText(l)||s!==l.trailingNewlines||a!==l.kind||c!==l.activeAnimation;d&&this.syncRenderedOutputHistory(),l.expanded&&r?.autoCollapseMs&&r.autoCollapseMs>0&&(l.autoCollapseTimer=setTimeout(()=>{l.expanded=!1,l.autoCollapseTimer=null,this.syncRenderedOutputHistory(),this.resizeInProgress||this.redrawConversationOutputFromHistory()},r.autoCollapseMs)),d&&this.redrawConversationOutputFromHistory(),this.synchronizeToolActivityAnimation()}writeOutput(t,n){if(!t)return;let r=this.appendRawOutputBlock(t,n);if(this.syncRenderedOutputHistoryAfterAppend(this.lastAppendExtendedBlock),this.terminalAttachSuspended)return;if(this.agentSessionChatViewState){this.redrawScreenFromHistory(),this.drawInputBox(),this.refreshFooterFocusCursor();return}let i="";i+=C.hideCursor(),i+=C.moveTo(this.outputRow,this.outputCol),i+=r.replace(/\r?\n/g,`\r
3204
3204
  `),this.advanceOutputPosition(r),this.shouldShowInputCursor()?(i+=this.inputCursorPosition(),i+=C.showCursor()):i+=C.hideCursor(),this.writeTerminalOrdered(i,"conversation-output"),this.shouldUseDelegationLogDock()&&this.drawDelegationLogDock()}writeInfo(t){this.writeOutput(t+`
3205
3205
  `)}writeError(t){this.writeOutput(K.red("\u2717 ")+K.red(t)+`
3206
3206
  `)}trimTrailingOutputNewlines(t){let n=Math.max(0,t),r=0;for(let o=this.outputHistory.length-1;o>=0&&this.outputHistory[o]===`
@@ -4229,7 +4229,7 @@ ${r}`}}import{execFileSync as Tje}from"node:child_process";function zGt(){let e=
4229
4229
  `),i.model||i.baseURL||i.apiKey||i.maxTokens||i.permissionMode||i.plugins&&i.plugins.length>0||i.mcpServers&&i.mcpServers.length>0||n.onOutput(` (no settings configured)
4230
4230
  `),n.onOutput(`
4231
4231
  `),{handled:!0}}function Cg(e){let t=Math.max(0,Math.floor(e)),n=Math.floor(t/1e3),r=Math.floor(n/3600),i=Math.floor(n%3600/60),o=n%60;return r>0?`${r}h ${i}m ${o}s`:i>0?`${i}m ${o}s`:`${o}s`}function Fje(e){let t=["Last Session Summary",`- model: ${e.model}`,`- mode: ${e.mode??"unknown"}`,`- status: ${e.status??"unknown"}`,`- started: ${e.startedAt}`,`- ended: ${e.endedAt}`,`- duration: ${Cg(e.durationMs)}`,`- tokens: ${e.tokenUsage.input.toLocaleString()} in / ${e.tokenUsage.output.toLocaleString()} out / ${e.tokenUsage.total.toLocaleString()} total`,`- estimated cost: ${cy(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(`
4232
- `)}function x4t(e){let t=e.replace(/\s+/g," ").trim();return t.length>72?`${t.slice(0,69)}...`:t}async function c5(e){if(!e.checkpointManager||e.messages.length===0)return null;let t=`Branch before rewind to "${x4t(e.targetPrompt)}"`,n=await e.checkpointManager.create({trigger:"manual",messages:e.messages,description:t});if(e.sessionManager){let r=[n.id,...e.sessionManager.meta.checkpoints.filter(i=>i!==n.id)];await e.sessionManager.updateMeta({checkpoints:r}),await e.sessionManager.transcript.append({type:"checkpoint",data:{id:n.id,action:"create",name:t,trigger:"manual",messageCount:e.messages.length}})}return n.id}Wr();Ei();var R4t={"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 hoe(e=be){return R4t[e]??[]}function T4t(e=be){let t=Et().lastReleaseNotesSeen;return hoe(e).length>0&&t!==e}function BE(e=be){ki({lastReleaseNotesSeen:e})}function l5(e){let t=e??be,n=hoe(t);return n.length===0?`No release notes available for version ${t}.`:[`Release notes for version ${t}`,"",...n.map(r=>`- ${r}`)].join(`
4232
+ `)}function x4t(e){let t=e.replace(/\s+/g," ").trim();return t.length>72?`${t.slice(0,69)}...`:t}async function c5(e){if(!e.checkpointManager||e.messages.length===0)return null;let t=`Branch before rewind to "${x4t(e.targetPrompt)}"`,n=await e.checkpointManager.create({trigger:"manual",messages:e.messages,description:t});if(e.sessionManager){let r=[n.id,...e.sessionManager.meta.checkpoints.filter(i=>i!==n.id)];await e.sessionManager.updateMeta({checkpoints:r}),await e.sessionManager.transcript.append({type:"checkpoint",data:{id:n.id,action:"create",name:t,trigger:"manual",messageCount:e.messages.length}})}return n.id}Wr();Ei();var R4t={"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 hoe(e=be){return R4t[e]??[]}function T4t(e=be){let t=Et().lastReleaseNotesSeen;return hoe(e).length>0&&t!==e}function BE(e=be){ki({lastReleaseNotesSeen:e})}function l5(e){let t=e??be,n=hoe(t);return n.length===0?`No release notes available for version ${t}.`:[`Release notes for version ${t}`,"",...n.map(r=>`- ${r}`)].join(`
4233
4233
  `)}function Uje(e=be){if(T4t(e))return[`What's new in XENO AGENT v${e}`,...hoe(e).map(t=>`- ${t}`),"Run `xeno release-notes` to view this again."].join(`
4234
4234
  `)}Dt();$c();ko();VP();import{spawn as P4t}from"node:child_process";import{setTimeout as Aoe}from"node:timers/promises";dy();import{resolve as d5}from"node:path";var qje="cancel",Ka={name:"WorkflowCancel",command:`workflows ${qje}`,nativeVerb:qje,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 ME(e,t){let n=e.run?.workflowName??t;return e.accepted?e.cancelled?`Cancelled ${n}`:`Cancellation pending for ${n}; inspect operation ${e.operationId}`:`Workflow run not found: ${t}`}function jje(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 Vje=()=>[Ka.description,`Mode: ${Ka.mode}; requiresDisplay: ${Ka.requiresDisplay}; reversibility: ${Ka.reversibility}. Read back with ${Ka.readingTools.join(" or ")}.`,"Returns JSON: "+Object.entries(Ka.replyFields).map(([e,t])=>`${e}: ${t}`).join(" "),"Cancellation progress: "+Object.entries(Ka.cancellationFields).map(([e,t])=>`${e}: ${t}`).join(" ")].join(" ");function va(e){process.stdout.write(JSON.stringify(e,null,2)+`
4235
4235
  `)}function _4t(e,t){if(t){va(e);return}if(e.ok&&e.definition){process.stdout.write(`Workflow valid: ${e.definition.name}