@xeno-corporation/xeno-agent-cli 0.4.0
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/LICENSE +15 -0
- package/dist/index.js +2653 -0
- package/package.json +56 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,2653 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
var La=Object.defineProperty;var Np=Object.getOwnPropertyDescriptor;var Bp=Object.getOwnPropertyNames;var Dp=Object.prototype.hasOwnProperty;var kt=(t,e)=>()=>(t&&(e=t(t=0)),e);var cr=(t,e)=>{for(var n in e)La(t,n,{get:e[n],enumerable:!0})},$a=(t,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Bp(e))!Dp.call(t,r)&&r!==n&&La(t,r,{get:()=>e[r],enumerable:!(s=Np(e,r))||s.enumerable});return t},Me=(t,e,n)=>($a(t,e,"default"),n&&$a(n,e,"default"));var R={};import*as aP from"@xeno-corporation/xeno-agent-sdk";var Wt=kt(()=>{"use strict";Me(R,aP)});import{appendFileSync as Fp,mkdirSync as Up}from"fs";import{homedir as jp}from"os";import{join as Na}from"path";function Bt(t,e={}){if(process.env.XENO_DEBUG_INPUT==="1")try{let n=Na(jp(),".xeno-agent");Up(n,{recursive:!0}),Fp(Na(n,"input-debug.log"),JSON.stringify({ts:new Date().toISOString(),pid:process.pid,event:t,...e})+`
|
|
4
|
+
`,"utf8")}catch{}}function Ct(t){if(!process.stdin.isTTY||typeof process.stdin.setRawMode!="function")return Bt("terminal-input:skip",{isTTY:process.stdin.isTTY,hasSetRawMode:typeof process.stdin.setRawMode=="function"}),{release:()=>{}};let e=o=>{let i=typeof o=="string"?o:o.toString("utf8");Bt("terminal-input:data",{length:i.length,hex:Buffer.from(i,"utf8").toString("hex")}),t(i)},n=process.stdin.listeners("data"),s=process.stdin.isRaw===!0,r=!1;return Bt("terminal-input:acquire",{listenerCountBefore:process.stdin.listenerCount("data"),isRawBefore:process.stdin.isRaw}),process.stdin.removeAllListeners("data"),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",e),Bt("terminal-input:acquired",{listenerCountAfter:process.stdin.listenerCount("data"),isRawAfter:process.stdin.isRaw}),{release(){if(r)return;r=!0,Bt("terminal-input:release",{listenerCountBefore:process.stdin.listenerCount("data"),isRawBefore:process.stdin.isRaw}),process.stdin.removeListener("data",e);let o=process.stdin.listeners("data");for(let i of n)o.includes(i)||process.stdin.on("data",i);process.stdin.isTTY&&process.stdin.setRawMode(s),Bt("terminal-input:released",{listenerCountAfter:process.stdin.listenerCount("data"),isRawAfter:process.stdin.isRaw,restoredListeners:n.length})}}}var fn=kt(()=>{"use strict"});import xo from"chalk";function Xn(t){return Dt.includes(t)}function Po(){return ks}function En(t){ks=t}function Ke(){return xo.hex(Ba[ks])}function Da(){return xo.bgHex(Ba[ks]).black}function Fa(){return xo.bgHex(Vp[ks]).white}var Dt,Ba,Vp,ks,At=kt(()=>{"use strict";Dt=["blue","green","red","purple"],Ba={blue:"#5C8FFF",green:"#22C55E",red:"#EF4444",purple:"#8B5CF6"},Vp={blue:"#2A4080",green:"#145530",red:"#7A2222",purple:"#4A2E80"},ks="blue"});var qa={};cr(qa,{Spinner:()=>Ps,StreamWriter:()=>To,ansi:()=>d,banner:()=>Cn,brand:()=>_,errorMessage:()=>xt,goodbyeMessage:()=>Gn,helpText:()=>fr,inputPrompt:()=>zp,stringWidth:()=>_o,stripAnsi:()=>se,tokenUsage:()=>mr,toolCallBox:()=>_s,toolResultBox:()=>pr});import Ye from"chalk";import Ua from"path";function Ts(t){return qp[t]??Le}function Cn(t,e){let n=`${dr().bold("XENO AGENT")} ${J(`v${t}`)}`,s=`Model: ${e}`,r=`Working directory: ${process.cwd()}`,i=Math.max(se(n).length,s.length,r.length,36)+4,a=`${ne}\u256D${"\u2500".repeat(i)}\u256E`,l=`${ne}\u2570${"\u2500".repeat(i)}\u256F`,c=` ${n}${"".padEnd(Math.max(0,i-2-se(n).length))}`,u=` ${J(s)}${"".padEnd(Math.max(0,i-2-s.length))}`,p=` ${J(r)}${"".padEnd(Math.max(0,i-2-r.length))}`;return["",J(a),`${ne}${J("\u2502")}${c}${J("\u2502")}`,`${ne}${J("\u2502")}${u}${J("\u2502")}`,`${ne}${J("\u2502")}${p}${J("\u2502")}`,J(l),""].join(`
|
|
5
|
+
`)}function se(t){return t.replace(/\x1b\[[0-9;]*[A-Za-z]/g,"").replace(/\x1b\[\?[0-9;]*[A-Za-z]/g,"")}function _o(t){let e=se(t),n=0;for(let s of e){let r=s.codePointAt(0)??0;Hp(r)?n+=2:r>=32&&(n+=1)}return n}function Hp(t){return t>=19968&&t<=40959||t>=13312&&t<=19903||t>=63744&&t<=64255||t>=44032&&t<=55215||t>=131072&&t<=195103||t>=65281&&t<=65376||t>=65504&&t<=65510||t>=12448&&t<=12543||t>=12352&&t<=12447||t>=12288&&t<=12351||t>=12800&&t<=13055||t>=13056&&t<=13311}function zp(){return`
|
|
6
|
+
${ne}${Le(">")} `}function _s(t,e){let s=e.length>120?e.slice(0,117)+"...":e,r=Ts(t);return t==="WebSearch"?`${r("\u25A0")} ${r("Web Search")} ${J(s)}`:t==="WebFetch"?`${r("\u25A0")} ${r("Web Fetch")} ${J(s)}`:`${r("\u25A0")} ${r(t)}${J("(")}${J(s)}${J(")")}`}function pr(t,e,n,s){let o=Ts(t)("\u23BF"),i=t==="Write"?Xp(n,s):null;if(i)return i;let a=t==="Edit"?Kp(n,s):null;if(a)return a;let l=Zp(t,e,n,s);if(l)return l;if(!n?.trim())return`${ne}${o} ${J(e?"Done":"Error")}`;let c=n.trim().split(`
|
|
7
|
+
`),u=c[0].length>80?c[0].slice(0,77)+"...":c[0];return c.length<=1?`${ne}${o} ${J(u)}`:`${ne}${o} ${J(u)}
|
|
8
|
+
${ne} ${J(`\u2026 +${c.length-1} lines`)}`}function ur(t){let e=Ua.relative(process.cwd(),t);return!e||e.startsWith("..")?Ua.basename(t):e.replace(/\\/g,"/")}function Wp(t,e=8){let n=t.slice(0,e).map((s,r)=>{let o=s.length>100?`${s.slice(0,97)}...`:s,i=o.length===0?"(blank)":o;return`${ne} ${r+1} ${i}`});return t.length>e&&n.push(`${ne} ${J(`\uFFFD +${t.length-e} more lines`)}`),n}function Xp(t,e){let n=typeof e?.file_path=="string"?e.file_path:void 0,s=typeof e?.content=="string"?e.content:void 0;if(!n||s===void 0)return null;let r=ur(n),o=s.replace(/\r\n/g,`
|
|
9
|
+
`).split(`
|
|
10
|
+
`),i=Ts("Write");return[`${ne}${i("\u23BF")} ${J(`Wrote ${o.length} lines to ${r}`)}`,...Wp(o)].join(`
|
|
11
|
+
`)}function Kp(t,e){let n=typeof e?.file_path=="string"?e.file_path:void 0,s=typeof e?.old_string=="string"?e.old_string:void 0,r=typeof e?.new_string=="string"?e.new_string:void 0;if(!n||s===void 0||r===void 0)return null;let o=s.replace(/\r\n/g,`
|
|
12
|
+
`).split(`
|
|
13
|
+
`),i=r.replace(/\r\n/g,`
|
|
14
|
+
`).split(`
|
|
15
|
+
`),a=ur(n),l=Ts("Edit"),c=`${ne}${l("\u23BF")} ${J(`Updated ${a} (-${o.length} / +${i.length} lines)`)}`,u=o.map(g=>`${ne} ${Ye.bgRgb(80,20,20)(` - ${g.length>100?`${g.slice(0,97)}...`:g||"(blank)"} `)}`),p=i.map(g=>`${ne} ${Ye.bgRgb(20,60,20)(` + ${g.length>100?`${g.slice(0,97)}...`:g||"(blank)"} `)}`),f=[...u,...p],m=f.slice(0,8);return f.length>8&&m.push(`${ne} ${J(`\uFFFD ${f.length-8} more lines`)}`),[c,...m].join(`
|
|
16
|
+
`)}function Gp(t){if(!t)return null;let e=t.match(/--- Metadata ---\s*\n([\s\S]*?)\n\s*\n--- Content ---/);if(!e)return null;try{let n=JSON.parse(e[1]);return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}function Yp(t){return typeof t!="number"||!Number.isFinite(t)||t<0?null:`${Math.round(t).toLocaleString()} bytes`}function Kn(t,e=100){let n=t.replace(/\s+/g," ").trim();return n.length<=e?n:`${n.slice(0,Math.max(1,e-3))}...`}function Jp(t){if(!t?.trim())return null;try{let e=JSON.parse(t);if(!e||typeof e!="object"||Array.isArray(e))return null;let n=e,r=(Array.isArray(n.results)?n.results:[]).filter(o=>!!(o&&typeof o=="object"&&!Array.isArray(o))).map(o=>({title:typeof o.title=="string"?o.title:void 0,url:typeof o.url=="string"?o.url:void 0,snippet:typeof o.snippet=="string"?o.snippet:void 0}));return{provider:typeof n.provider=="string"?n.provider:void 0,query:typeof n.query=="string"?n.query:void 0,results:r}}catch{return null}}function Qp(t){if(!t)return[];let e="--- Content ---",n=t.indexOf(e);return(n>=0?t.slice(n+e.length):t).replace(/\r\n/g,`
|
|
17
|
+
`).split(`
|
|
18
|
+
`).map(r=>r.trim()).filter(Boolean).slice(0,4)}function Zp(t,e,n,s){if(!e||!n?.trim())return null;let o=Ts(t)("\u23BF"),i=n.trim().split(`
|
|
19
|
+
`);switch(t){case"Read":{let a=typeof s?.file_path=="string"?s.file_path:"",l=a?ur(a):"",c=i.length;return`${ne}${o} ${J(`Read ${l} (${c} lines)`)}`}case"ReadImage":{let a=typeof s?.file_path=="string"?s.file_path:"";return`${ne}${o} ${J(`Read image ${a?ur(a):""}`)}`}case"Glob":{let a=typeof s?.pattern=="string"?s.pattern:"",l=i.length;return l===0||l===1&&!i[0]?`${ne}${o} ${J(`No files matched ${a}`)}`:`${ne}${o} ${J(`Found ${l} file${l!==1?"s":""} matching ${a}`)}`}case"Grep":{let a=typeof s?.pattern=="string"?s.pattern:"",l=i.filter(c=>c.trim()).length;return l===0?`${ne}${o} ${J(`No matches for /${a}/`)}`:`${ne}${o} ${J(`Searched for /${a}/ (${l} match${l!==1?"es":""})`)}`}case"WebSearch":{let a=typeof s?.query=="string"?s.query:"",l=Jp(n),c=l?.results.length??0,u=l?.provider?` via ${l.provider}`:"",p=c>0?`${ne}${o} ${J(`Found ${c} result${c===1?"":"s"}${u}`)}`:`${ne}${o} ${J(`No web results${a?` for ${Kn(a,56)}`:""}`)}`;if(!l||l.results.length===0)return p;let f=l.results.slice(0,5).flatMap((m,g)=>{let b=m.title?Kn(m.title,96):"(untitled)",v=m.url?Kn(m.url,100):"",w=m.snippet?Kn(m.snippet,110):"";return[`${ne} ${J(`${g+1}.`)} ${b}`,...v?[`${ne} ${J(v)}`]:[],...w?[`${ne} ${J(w)}`]:[]]});return[p,...f].join(`
|
|
20
|
+
`)}case"WebFetch":{let a=typeof s?.url=="string"?s.url:"",l=a.length>60?a.slice(0,57)+"...":a,c=Gp(n),u=Yp(c?.originalLength),p=typeof c?.statusCode=="number"?c.statusCode:void 0,f=p?`${p}${p===200?" OK":""}`:null,m=u&&f?`Received ${u} (${f})`:`Fetched ${l} (${i.length} lines)`,g=`${ne}${o} ${J(m)}`,b=Qp(n);return b.length===0?g:[g,...a?[`${ne} ${J(Kn(a,110))}`]:[],...b.map(v=>`${ne} ${Kn(v,110)}`)].join(`
|
|
21
|
+
`)}default:return null}}function mr(t,e){return`${ne}${J(`tokens: ${t.toLocaleString()} in / ${e.toLocaleString()} out`)}`}function xt(t){return`
|
|
22
|
+
${ne}${dr().bold("\u2717")} ${xs(t)}
|
|
23
|
+
`}function fr(){return["",`${ne}${Va("XENO AGENT Commands:")}`,`${ne} ${Le("/help")} ${J("Show this help")}`,`${ne} ${Le("/clear")} ${J("Clear chat history")}`,`${ne} ${Le("/tokens")} ${J("Show token usage and cost")}`,`${ne} ${Le("/cost")} ${J("Show live cost and elapsed session duration")}`,`${ne} ${Le("/model")} ${J("Show or switch the AI model")}`,`${ne} ${Le("/approvals")} ${J("Update XENO approvals for tool actions")}`,`${ne} ${Le("/approved-tools")} ${J("Inspect or revoke remembered tool approvals")}`,`${ne} ${Le("/color")} ${J("Show or switch the UI color theme")}`,`${ne} ${Le("/mode")} ${J("Switch runtime mode (Chat/Agent/Full Access)")}`,`${ne} ${Le("/delegate")} ${J("Toggle delegated planner/explorer/executor/reviewer turns")}`,`${ne} ${Le("/memory")} ${J("Show and edit memory levels")}`,`${ne} ${Le("/remember")} ${J("Add text to project memory")}`,`${ne} ${Le("/memory context")} ${J("Inspect prompt memory context and diagnostics")}`,`${ne} ${Le("/checkpoint")} ${J("Create a manual checkpoint")}`,`${ne} ${Le("/audit")} ${J("Tail, inspect, or export audit events (--json)")}`,`${ne} ${Le("/mcp")} ${J("Manage MCP servers, prompts, and resources")}`,`${ne} ${Le("/doctor")} ${J("Run local runtime, config, and MCP health checks")}`,`${ne} ${Le("/bug-report")} ${J("Export a redacted diagnostics bundle")}`,`${ne} ${Le("/config")} ${J("Inspect or edit local config state")}`,`${ne} ${Le("/ctx-viz")} ${J("Inspect system prompt, tools, and message context usage")}`,`${ne} ${Le("/onboarding")} ${J("Show or update onboarding guidance for this workspace")}`,`${ne} ${Le("/release-notes")} ${J("Show current or requested release notes")}`,`${ne} ${Le("/terminal-setup")} ${J("Install terminal Shift+Enter integration")}`,`${ne} ${Le("/listen")} ${J("Start system dictation / voice typing")}`,`${ne} ${Le("/pr-comments")} ${J("Fetch and render GitHub PR comments")}`,`${ne} ${Le("/sessions")} ${J("List recent sessions")}`,`${ne} ${Le("/save")} ${J("Save current session")}`,`${ne} ${Le("/resume")} ${J("Resume most recent session")}`,`${ne} ${Le("/resume <id>")} ${J("Resume by session id")}`,`${ne} ${Le("/export")} ${J("Export conversation to file or JSON")}`,`${ne} ${Le("/exit")} ${J("Exit XENO AGENT")}`,"",`${ne}${J("In TTY mode, /help, /model, /approvals, /approved-tools, /color, /delegate, /sessions, /resume, /onboarding, /release-notes, and /ctx-viz open interactive panels.")}`,""].join(`
|
|
24
|
+
`)}function Gn(){return`
|
|
25
|
+
${ne}${J("Goodbye.")}
|
|
26
|
+
`}var dr,Le,J,Va,xs,qp,_,ne,d,To,ja,Ps,It=kt(()=>{"use strict";At();dr=()=>Ke(),Le=t=>dr()(t),J=Ye.dim,Va=Ye.bold,xs=t=>dr()(t),qp={Read:t=>Ye.blue(t),ReadImage:t=>Ye.blue(t),Glob:t=>Ye.blue(t),Grep:t=>Ye.blue(t),ElfAnalyze:t=>Ye.blue(t),MemoryRead:t=>Ye.blue(t),Write:t=>Ye.green(t),Edit:t=>Ye.yellow(t),MemoryWrite:t=>Ye.yellow(t),Bash:t=>Ye.red(t),GitStatus:t=>Ye.blue(t),GitDiff:t=>Ye.blue(t),GitLog:t=>Ye.blue(t),GitBranch:t=>Ye.blue(t),GitCommit:t=>Ye.yellow(t),WebSearch:t=>Ye.cyan(t),WebFetch:t=>Ye.cyan(t),TaskOutput:t=>Ye.blue(t),TaskStop:t=>Ye.red(t)};_={accent:Le,purple:xs,cyan:xs,dim:J,bold:Va,red:xs,green:xs},ne=" ";d={moveTo:(t,e)=>`\x1B[${t};${e}H`,saveCursor:()=>"\x1B[s",restoreCursor:()=>"\x1B[u",setScrollRegion:(t,e)=>`\x1B[${t};${e}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"};To=class{atLineStart=!0;writeFn;constructor(e){this.writeFn=e??(n=>{process.stdout.write(n)})}write(e){let n="";for(let s of e)this.atLineStart&&(n+=ne,this.atLineStart=!1),n+=s,s===`
|
|
27
|
+
`&&(this.atLineStart=!0);this.writeFn(n)}reset(){this.atLineStart=!0}markLineStarted(){this.atLineStart=!1}},ja=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Ps=class{interval=null;frameIndex=0;lastLength=0;writeFn;clearFn;constructor(e,n){this.writeFn=e??(s=>{process.stderr.write(s)}),this.clearFn=n??(()=>{process.stderr.write(`\r${" ".repeat(this.lastLength)}\r`)})}start(e){this.stop(),this.frameIndex=0,this.interval=setInterval(()=>{let n=ja[this.frameIndex%ja.length],s=`${Le(n)} ${J(e)}`;this.writeFn(`\r${" ".repeat(this.lastLength)}\r${s}`),this.lastLength=e.length+4,this.frameIndex++},80)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null,this.clearFn(),this.lastLength=0)}}});import{getModelName as vm}from"@xeno-corporation/xeno-agent-sdk";function br(t){let e=t?.trim();if(e)return e.replace(/\/+$/,"")}function tl(){return process.env.XENO_BENCHMARK_MODE?.trim().toLowerCase()==="terminal-bench"}function rn(t={}){let e=br(t.explicitBaseURL);if(e)return e;let n=br(process.env.XENO_BASE_URL);if(n)return n;let s=br(t.configuredBaseURL);if(s)return s;let r=t.benchmarkMode??tl(),o=process.env.XENO_DISABLE_DIRECT_API?.trim()==="1";return r&&!o?br(process.env.XENO_DIRECT_API_BASE_URL)??yr:el}function Ao(t){return t.startsWith("ollama:")}async function Co(t,e={},n=5e3){let s=new AbortController,r=setTimeout(()=>s.abort(),n);try{return await fetch(t,{...e,signal:s.signal})}finally{clearTimeout(r)}}async function Io(t,e){let n=e?.ollamaUrl||process.env.OLLAMA_BASE_URL||Za,s=e?.timeoutMs??15e3,r=vm(t);try{let o=await Co(`${n}/api/tags`,{},Math.min(s,5e3));if(!o.ok)return{ok:!1,model:r,baseUrl:n,error:`Ollama is not reachable at ${n} (HTTP ${o.status})`};let a=((await o.json()).models??[]).map(c=>c.name??"").filter(c=>c.length>0);if(!new Set(a.map(c=>c.toLowerCase())).has(r.toLowerCase())){let c=a.length>0?` Available: ${a.slice(0,5).join(", ")}${a.length>5?", ...":""}`:"";return{ok:!1,model:r,baseUrl:n,error:`Ollama model not found: ${r}.${c}`}}}catch(o){let i=o instanceof Error?o.message:String(o);return{ok:!1,model:r,baseUrl:n,error:`Failed to reach Ollama at ${n}: ${i}`}}try{let o=await Co(`${n}/v1/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:r,messages:[{role:"user",content:"ping"}],max_tokens:1,stream:!1})},s);if(o.ok)return{ok:!0,model:r,baseUrl:n,endpoint:"openai"};if(o.status!==404){let i=(await o.text().catch(()=>"")).trim();return{ok:!1,model:r,baseUrl:n,error:`Ollama chat check failed (HTTP ${o.status}${i?`: ${i}`:""})`}}}catch(o){let i=o instanceof Error?o.message:String(o);return{ok:!1,model:r,baseUrl:n,error:`Ollama OpenAI chat endpoint check failed: ${i}`}}try{let o=await Co(`${n}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:r,messages:[{role:"user",content:"ping"}],stream:!1,options:{num_predict:1}})},s);if(!o.ok){let i=(await o.text().catch(()=>"")).trim();return{ok:!1,model:r,baseUrl:n,error:`Ollama native chat check failed (HTTP ${o.status}${i?`: ${i}`:""})`}}return{ok:!0,model:r,baseUrl:n,endpoint:"native",warning:"OpenAI-compatible endpoint not found; native Ollama API fallback will be used."}}catch(o){let i=o instanceof Error?o.message:String(o);return{ok:!1,model:r,baseUrl:n,error:`Ollama native chat endpoint check failed: ${i}`}}}var ot,yr,Za,el,nl=kt(()=>{"use strict";ot="https://xenostudio.ai",yr="http://direct-api.xenostudio.ai:8443",Za="http://localhost:11434",el="https://api.xenostudio.ai"});var we={};cr(we,{OLLAMA_DEFAULT_URL:()=>Za,XENO_API_BASE_COMPAT:()=>el,XENO_AUTH_BASE:()=>ot,XENO_DIRECT_API_BASE:()=>yr,isOllamaModel:()=>Ao,isXenoBenchmarkMode:()=>tl,preflightOllamaModel:()=>Io,resolveXenoApiBaseURL:()=>rn});import*as FP from"@xeno-corporation/xeno-agent-sdk";var hn=kt(()=>{"use strict";Me(we,FP);nl()});import{chmodSync as Sm,existsSync as As,mkdirSync as sl,readFileSync as $o,rmSync as rl,statSync as km,writeFileSync as Lo}from"fs";import{homedir as Mt}from"os";import{dirname as ol,join as Cs}from"path";function Jn(t){let e=t?.trim();if(e)return e.replace(/\/+$/,"")}function Rm(t){return Array.from(new Set(t))}function No(t,e){let n=Jn(t)??ot;return Rm(e.map(s=>`${n}${s.startsWith("/")?s:`/${s}`}`))}function il(t){if(!t||typeof t!="object")return;let e=t,n=e.token??e.sessionToken??e.accessToken??e.jwt;if(typeof n=="string"&&n.trim().length>0)return n.trim();let s=e.data;if(s&&typeof s=="object")return il(s)}function Mo(t){if(Array.isArray(t)){for(let s of t){let r=Mo(s);if(r)return r}return}if(!t||typeof t!="object")return;let e=t,n=e.apiKey??e.llmApiKey??e.key??e.token;if(typeof n=="string"&&n.trim().length>0)return n.trim();for(let s of Object.values(e))if(s&&typeof s=="object"||Array.isArray(s)){let r=Mo(s);if(r)return r}}function Oo(t){if(!t||typeof t!="object")return;let e=t,n=e.user??(e.data&&typeof e.data=="object"?e.data.user:void 0);return n&&typeof n=="object"?n:void 0}function Em(t){let e=t?.trim();return e?e.startsWith("xeno-")||e.startsWith("sk-")||wr(e):!1}function wr(t){let e=t?.trim();return e?/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(e):!1}function Cm(t){let e=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(t.length/4)*4,"="),n=Buffer.from(e,"base64").toString("utf-8");return JSON.parse(n)}function Am(t){let e=t?.trim();if(wr(e))try{let n=Cm(e.split(".")[1]??"");return n&&typeof n=="object"?n:void 0}catch{return}}function al(t){let e=Am(t)?.exp;if(!(!Number.isFinite(e)||typeof e!="number"||e<=0))return new Date(e*1e3)}function gn(t,e=Date.now(),n=_m){let s=al(t);return s?s.getTime()<=e+n:!1}function Im(t,e){return wr(t)?"jwt":e}function on(t,e={}){let n=[{value:t?.apiKey,type:"api-key",source:t?.source},{value:t?.llmApiKey,type:"legacy",source:t?.source??"legacy-settings"},{value:t?.webToken,type:"legacy",source:t?.source??"legacy-settings"}];for(let s of n){let r=s.value?.trim();if(!Em(r))continue;let o=al(r),i=o?o.getTime()-Date.now():void 0,a=wr(r)?gn(r):!1;if(!(a&&e.includeExpired!==!0))return{value:r,type:Im(r,s.type),source:s.source,...o?{expiresAt:o.toISOString()}:{},...i!==void 0?{expiresInMs:i}:{},expired:a}}}async function Mm(t){let e=await t.text();if(!e.trim())return{};try{return JSON.parse(e)}catch{return{message:e}}}async function vr(t,e,n){let s=await t(e,n),r=await Mm(s);return{ok:s.ok,status:s.status,data:r,response:s}}function Sr(t,e){if(e&&typeof e=="object"){let n=e,s=n.message??n.error;if(typeof s=="string"&&s.trim().length>0)return`${t}: ${s.trim()}`;if(s&&typeof s=="object"){let r=s.message;if(typeof r=="string"&&r.trim().length>0)return`${t}: ${r.trim()}`}}return String(t)}function Xt(t=Mt()){return Cs(t,".xeno",Pm)}function Bo(t=Mt()){return Cs(t,".xeno",Tm)}function Qn(t=Mt()){let e=Bo(t);sl(ol(e),{recursive:!0}),Lo(e,JSON.stringify({loggedOutAt:new Date().toISOString()},null,2)+`
|
|
28
|
+
`,"utf-8")}function Om(t=Mt()){rl(Bo(t),{force:!0})}function ll(t=Mt()){return As(Bo(t))}function Kt(t=Mt()){let e=Xt(t);try{if(!As(e))return;let n=$o(e,"utf-8"),s=JSON.parse(n);return s&&typeof s=="object"?s:void 0}catch{return}}function bt(t,e=Mt()){let n=Xt(e);sl(ol(n),{recursive:!0});let s=Kt(e)??{},r=new Date().toISOString(),o={...s,...t,version:xm,createdAt:s.createdAt??t.createdAt??r,updatedAt:r};for(let i of Object.keys(o))o[i]===void 0&&delete o[i];if(Lo(n,JSON.stringify(o,null,2)+`
|
|
29
|
+
`,"utf-8"),Om(e),process.platform!=="win32")try{(km(n).mode&511)!==384&&Sm(n,384)}catch{}return o}function Zn(t=Mt()){let e=Xt(t);return As(e)?(rl(e,{force:!0}),!0):!1}function es(t=Mt()){let e=Cs(t,".xeno","settings.json");if(!As(e))return!1;let n;try{n=JSON.parse($o(e,"utf-8"))}catch{return!1}let s=JSON.stringify(n);return delete n.apiKey,delete n.llmApiKey,delete n.webToken,delete n.accountToken,JSON.stringify(n)===s?!1:(Lo(e,JSON.stringify(n,null,2)),!0)}function Do(t=Mt()){let e=Kt(t),n=on(e);if(n)return n.value;let s=[{path:Cs(t,".xeno","credentials.json"),extract:r=>{let o=JSON.parse(r);return on(o)?.value}},{path:Cs(t,".xeno","settings.json"),extract:r=>{let o=JSON.parse(r);return on(o)?.value}}];for(let r of s)try{if(!As(r.path))continue;let o=r.extract($o(r.path,"utf-8"));if(o)return o}catch{}}function ts(...t){let e=t.slice(0,2).map(s=>s?.trim()).find(s=>!!s);if(e&&!gn(e))return e;let n=Do();return n||(t.slice(2).map(s=>s?.trim()).find(s=>!!s&&!gn(s))??"")}async function cl(t){let e=t.fetchImpl??fetch,n=Jn(t.authBaseURL)??ot,s=Jn(t.apiBaseURL),r=No(n,["/api/auth/login","/auth/login"]),o="";for(let i of r)try{let a=await vr(e,i,{method:"POST",headers:{"content-type":"application/json","user-agent":"xeno-agent-cli"},body:JSON.stringify({email:t.email,password:t.password})});if(!a.ok){o=`${i} returned ${Sr(a.status,a.data)}`;continue}let l=il(a.data);if(!l){o=`${i} did not return an account token`;continue}let c=Mo(a.data);return{credentials:{accountToken:l,apiKey:c??l,authBaseURL:n,...s?{apiBaseURL:s}:{},...Oo(a.data)?{user:Oo(a.data)}:{},source:"login"},endpoint:i}}catch(a){o=`${i} failed: ${a instanceof Error?a.message:String(a)}`}throw new Error(o||"Login failed")}async function bn(t){let e=t.apiKey.trim();if(!e)return{valid:!1,error:"No API key configured"};if(gn(e))return{valid:!1,error:"Stored Xeno session token is expired. Run `xeno login` again."};let n=Jn(t.apiBaseURL)??we.XENO_API_BASE,s=t.fetchImpl??fetch;try{let r=await vr(s,`${n}/v1/models`,{method:"GET",headers:{authorization:`Bearer ${e}`,"user-agent":"xeno-agent-cli"}});return r.ok?{valid:!0}:{valid:!1,error:Sr(r.status,r.data)}}catch(r){return{valid:!1,error:r instanceof Error?r.message:String(r)}}}async function Fo(t){let e=t.accountToken.trim();if(!e)return{valid:!1,error:"No account token configured"};if(gn(e))return{valid:!1,error:"Stored Xeno session token is expired. Run `xeno login` again."};let n=Jn(t.authBaseURL)??ot,s=t.fetchImpl??fetch,r=No(n,["/api/auth/validate","/api/auth/me","/auth/validate","/auth/me"]),o="";for(let i of r)try{let a=await vr(s,i,{method:"GET",headers:{authorization:`Bearer ${e}`,"user-agent":"xeno-agent-cli"}});if(a.ok)return{valid:!0,user:Oo(a.data)};if(a.status===404){o=`${i} returned 404`;continue}return{valid:!1,error:Sr(a.status,a.data)}}catch(a){o=`${i} failed: ${a instanceof Error?a.message:String(a)}`}return{valid:!1,error:o||"No account validation endpoint responded"}}async function Uo(t){let e=t.accountToken.trim();return e?{apiKey:e,endpoint:void 0,created:!1}:{error:"No account token configured"}}async function Tt(t={}){let e=t.homePath??Mt(),n=Xt(e),s=Kt(e),r=on(s,{includeExpired:!0}),o=r?.value,i=s?.accountToken?.trim()||s?.webToken?.trim(),a=i?gn(i):!1,l=!!(r&&!r.expired),c=!!(i&&!a),u=!!(r||i),p=!!(r&&r.expired||a),f={credentialsPath:n,signedIn:!!(s&&(l||c)),hasApiKey:l,hasAccountToken:c,...r?.type?{modelCredentialType:r.type}:{},...r?.source?{modelCredentialSource:r.source}:{},...r?.expiresAt?{expiresAt:r.expiresAt}:{},...r?.expiresInMs!==void 0?{expiresInSeconds:Math.max(0,Math.floor(r.expiresInMs/1e3))}:{},...u?{expired:p,needsLogin:p}:{},...s?.user?{user:s.user}:{},...s?.authBaseURL?{authBaseURL:s.authBaseURL}:{},...s?.apiBaseURL?{apiBaseURL:s.apiBaseURL}:{}};if(!t.validate||!s)return f;if(p&&!l&&!c)return{...f,valid:!1,error:"Stored Xeno session token is expired. Run `xeno login` again."};if(o&&!r?.expired){let m=await bn({apiKey:o,apiBaseURL:s.apiBaseURL,fetchImpl:t.fetchImpl});return{...f,valid:m.valid,...m.error?{error:m.error}:{}}}if(i&&!a){let m=await Fo({accountToken:i,authBaseURL:s.authBaseURL,fetchImpl:t.fetchImpl});return{...f,valid:m.valid,...m.user?{user:m.user}:{},...m.error?{error:m.error}:{}}}return f}async function jo(t={}){let e=t.homePath??Mt(),n=Kt(e),s=n?.accountToken?.trim()||n?.webToken?.trim(),r=!1,o,i;if(s){let l=Jn(n?.authBaseURL)??ot,c=t.fetchImpl??fetch;for(let u of No(l,["/api/auth/logout","/auth/logout"])){r=!0;try{let p=await vr(c,u,{method:"POST",headers:{authorization:`Bearer ${s}`,"content-type":"application/json","user-agent":"xeno-agent-cli"}});if(p.ok||p.status===404){o=p.ok;break}i=Sr(p.status,p.data)}catch(p){i=p instanceof Error?p.message:String(p)}}}return{cleared:Zn(e),remoteAttempted:r,...o!==void 0?{remoteOk:o}:{},...i?{error:i}:{}}}function an(t){let e=["Xeno auth status"];return e.push(`Credentials: ${t.credentialsPath}`),e.push(`Signed in: ${t.signedIn?"yes":"no"}`),(t.user?.email||t.user?.name||t.user?.username)&&e.push(`Account: ${t.user.email??t.user.name??t.user.username}`),e.push(`API key: ${t.hasApiKey?"configured":"not configured"}`),t.modelCredentialType&&e.push(`Credential type: ${t.modelCredentialType}`),t.modelCredentialSource&&e.push(`Credential source: ${t.modelCredentialSource}`),e.push(`Account token: ${t.hasAccountToken?"configured":"not configured"}`),t.expiresAt&&e.push(`Expires: ${t.expiresAt}${t.expired?" (expired)":""}`),t.apiBaseURL&&e.push(`API base URL: ${t.apiBaseURL}`),t.authBaseURL&&e.push(`Auth base URL: ${t.authBaseURL}`),t.valid!==void 0&&e.push(`Validation: ${t.valid?"ok":"failed"}`),t.error&&e.push(`Error: ${t.error}`),`${e.join(`
|
|
30
|
+
`)}
|
|
31
|
+
`}var xm,Pm,Tm,_m,On=kt(()=>{"use strict";hn();xm=1,Pm="credentials.json",Tm="logout.json",_m=6e4});import dl from"chalk";function $m(t,e){let n=Math.max(40,e??process.stdout.columns??80),s=d.clearScreen();s+=d.hideCursor();let r=1,o=i=>{s+=d.moveTo(r,1)+d.eraseLine()+i,r++};o(` ${Vo(ul("Welcome to XENO"))}${Vo(", the AI-native command-line agent")}`),o(""),o(` ${ns("Sign in with your XENO Studio account to use XENO with your plan")}`),o(` ${ns("or paste an API token for usage-based billing")}`),o("");for(let i=0;i<yn.length;i++){let a=yn[i];i===t?(o(`${ul("> ")}${Vo(`${a.number}. ${a.title}`)}`),o(` ${ns(a.detail)}`)):(o(` ${ns(`${a.number}. ${a.title}`)}`),o(` ${ns(a.detail)}`)),o("")}return o(` ${ns("Press enter to continue \xB7 Up/Down to choose \xB7 Esc to exit")}`),s}function qo(){return process.stdin.isTTY?new Promise(t=>{let e=0,n=null,s=()=>{n?.release(),n=null,process.stdout.removeListener("resize",o),process.stdout.write(d.showCursor()),process.stdout.write(d.resetScrollRegion()),process.stdout.write(d.clearScreen())},r=()=>{process.stdout.write($m(e))},o=()=>{r()};n=Ct(a=>{let l=typeof a=="string"?a:a.toString("utf8");if(l===""){s(),t({choice:"exit"});return}if(l==="\x1B"){s(),t({choice:"exit"});return}if(l==="\x1B[A"){e=(e-1+yn.length)%yn.length,r();return}if(l==="\x1B[B"){e=(e+1)%yn.length,r();return}if(l==="\r"||l===`
|
|
32
|
+
`){let u=yn[e].value;s(),t({choice:u});return}let c=Number.parseInt(l,10);Number.isFinite(c)&&c>=1&&c<=yn.length&&(s(),t({choice:yn[c-1].value}))}),process.stdout.on("resize",o),r()}):Promise.resolve({choice:"exit"})}var ul,ns,Vo,yn,pl=kt(()=>{"use strict";fn();It();At();ul=t=>Ke()(t),ns=dl.dim,Vo=dl.bold,yn=[{value:"browser",number:1,title:"Sign in with XENO Account",detail:"Browser-based login with your XENO Studio account"},{value:"device-code",number:2,title:"Sign in with Device Code",detail:"Sign in from another device with a one-time code"},{value:"token",number:3,title:"Provide your own API token",detail:"Paste an existing XENO token"}]});import zo from"chalk";function Dm(t,e){let n=Math.max(40,e??process.stdout.columns??80),s=d.clearScreen();s+=d.hideCursor();let r=1,o=a=>{s+=d.moveTo(r,1)+d.eraseLine()+a,r++};o(""),o(""),o(` ${Ho(Lm("Welcome to XENO"))}${Ho(", the AI-native command-line agent")}`),o(""),o("");let i=t.email??t.displayName??"your XENO account";return o(` ${Nm("\u2713")} ${Ho(`Signed in as ${i}`)}`),o(""),o(` ${Is(Bm[t.via])}`),o(""),o(""),o(` ${Is("You're all set. The CLI is now authenticated against your XENO")}`),o(` ${Is("Studio account on this machine.")}`),o(""),o(""),o(` ${Is("Press any key to continue \xB7 Esc to exit")}`),s}function ml(t){return process.stdin.isTTY?new Promise(e=>{let n=null,s=a=>{if(n?.release(),n=null,process.stdout.removeListener("resize",o),process.stdout.write(d.showCursor()),process.stdout.write(d.resetScrollRegion()),process.stdout.write(d.clearScreen()),a.mode==="loading"){let l=process.stdout.columns??80,c=process.stdout.rows??24,u="Starting XENO\u2026",p=Math.max(0,Math.floor((l-u.length)/2)),f=Math.max(1,Math.floor(c/2));process.stdout.write(d.moveTo(f,1)+d.eraseLine()+" ".repeat(p)+Is(u)+`
|
|
33
|
+
`)}},r=()=>{process.stdout.write(Dm(t))},o=()=>{r()};n=Ct(a=>{let l=typeof a=="string"?a:a.toString("utf8");if(l===""){s({mode:"exit"}),e({outcome:"exit"});return}if(l==="\x1B"||l==="\x1B"){s({mode:"exit"}),e({outcome:"exit"});return}s({mode:"loading"}),e({outcome:"continue"})}),process.stdout.on("resize",o),r()}):Promise.resolve({outcome:"continue"})}var Lm,Is,Ho,Nm,Bm,fl=kt(()=>{"use strict";fn();It();At();Lm=t=>Ke()(t),Is=zo.dim,Ho=zo.bold,Nm=zo.green,Bm={browser:"Browser-based login","device-code":"Device-code login",token:"API token"}});var Ze,$n=kt(()=>{"use strict";Ze="0.3.0"});import{spawn as Wo}from"child_process";import{createServer as Fm}from"http";import bl from"chalk";function Hm(t){try{process.platform==="win32"?Wo("cmd",["/c","start","",t],{detached:!0,stdio:"ignore"}).unref():process.platform==="darwin"?Wo("open",[t],{detached:!0,stdio:"ignore"}).unref():Wo("xdg-open",[t],{detached:!0,stdio:"ignore"}).unref()}catch{}}async function zm(t){let e=Fm((r,o)=>{if(!r.url){o.statusCode=404,o.end();return}let i=new URL(r.url,"http://127.0.0.1");if(i.pathname!=="/callback"){o.statusCode=404,o.end();return}let a=i.searchParams.get("session")??void 0;o.statusCode=200,o.setHeader("content-type","text/html; charset=utf-8"),o.setHeader("cache-control","no-store"),o.end(qm),t.onCallback(a)}),n=await new Promise((r,o)=>{let i=a=>{a.code==="EADDRINUSE"?(e.removeListener("error",i),e.once("error",o),e.listen(0,"127.0.0.1",()=>{let l=e.address();l&&typeof l=="object"?r(l.port):o(new Error("Failed to bind localhost callback server"))})):o(a)};e.once("error",i),e.listen(Um,"127.0.0.1",()=>{e.removeListener("error",i);let a=e.address();a&&typeof a=="object"?r(a.port):o(new Error("Failed to bind localhost callback server"))})}),s=r=>new Promise(o=>{r.close(()=>o()),r.closeAllConnections?.()});return{url:`http://127.0.0.1:${n}/callback`,close:()=>s(e)}}function Wm(t){return new Promise(e=>{if(!process.stdin.isTTY){let i=()=>{t.removeEventListener("abort",i),e("complete")};t.addEventListener("abort",i);return}let n=()=>{o(),e("complete")},s=null,r=i=>{(i==="\x1B"||i==="")&&(o(),e("cancel"))},o=()=>{s?.release(),s=null,t.removeEventListener("abort",n)};s=Ct(r),t.addEventListener("abort",n)})}function Xm(t){let e=d.clearScreen();e+=d.hideCursor();let n=1,s=r=>{e+=d.moveTo(n,1)+d.eraseLine()+r,n++};return s(` ${Ko(hl("Welcome to XENO"))}${Ko(", the AI-native command-line agent")}`),s(""),s(` ${Ko("Finish signing in via your browser")}`),s(""),s(` ${Xo("If the link doesn't open automatically, open the following link to authenticate:")}`),s(""),s(` ${hl(t)}`),s(""),s(` ${Xo("On a remote or headless machine? Press esc and choose Sign in with Device Code.")}`),s(""),s(` ${Xo("Press esc to cancel")}`),e}function gl(t){let e=t?.trim();if(e)return e.replace(/\/+$/,"")}async function Go(t={}){let e=t.fetchImpl??fetch,n=gl(t.authBaseURL)??ot,s=gl(t.apiBaseURL)??we.XENO_API_BASE,r=t.cliVersion??Ze,o=t.timeoutMs??Vm,i=t.log??($=>process.stdout.write($)),a=t.openBrowser??Hm,l=t.startCallbackServer??zm,c=t.waitForCancel??Wm,u=t.pollIntervalMs??jm,p={resolved:!1},f=new AbortController,m,g=new Promise($=>{m=E=>{p.resolved||(p.resolved=!0,f.abort(),p.pollTimer&&clearTimeout(p.pollTimer),p.timeoutTimer&&clearTimeout(p.timeoutTimer),$(E))}}),b=async()=>{if(p.pollTimer&&clearTimeout(p.pollTimer),p.timeoutTimer&&clearTimeout(p.timeoutTimer),p.server)try{await p.server.close()}catch{}},v={onCallback:$=>{$&&$!==p.sessionId||p.pollTrigger?.()}};try{p.server=await l(v)}catch($){return{kind:"error",message:`Failed to start localhost callback server: ${$ instanceof Error?$.message:String($)}`}}let w;try{let $=await e(`${n}/api/auth/cli/start`,{method:"POST",headers:{"content-type":"application/json","user-agent":"xeno-agent-cli"},body:JSON.stringify({redirect_uri:p.server.url,cli_version:r})});if(!$.ok){let E=await $.text();return await b(),{kind:"error",message:`Failed to start CLI auth session (${$.status}): ${E.slice(0,200)}`}}w=await $.json()}catch($){return await b(),{kind:"error",message:`Failed to start CLI auth session: ${$ instanceof Error?$.message:String($)}`}}p.sessionId=w.session_id,t.onStarted?.({...w,redirect_uri:p.server.url}),t.silent||i(Xm(w.auth_url)),a(w.auth_url);let P=async()=>{if(!p.resolved){try{let $=await e(`${n}/api/auth/cli/poll?session_id=${encodeURIComponent(p.sessionId)}`,{method:"GET",headers:{"user-agent":"xeno-agent-cli"}});if(!$.ok&&$.status!==200){if($.status===404){m({kind:"error",message:"Sign-in session not found."});return}}else{let E=await $.json();if(E.status==="complete"&&E.token){let T={accountToken:E.token,apiKey:E.token,authBaseURL:n,apiBaseURL:s,...E.user?{user:E.user}:{},source:"browser-oauth"},I=bt(T,t.homePath);m({kind:"success",user:E.user,credentials:I});return}if(E.status==="not_found"){m({kind:"error",message:"Sign-in session not found."});return}}}catch{}p.resolved||(p.pollTimer=setTimeout(()=>{P()},u))}};p.pollTrigger=()=>{p.pollTimer&&clearTimeout(p.pollTimer),P()},p.pollTimer=setTimeout(()=>{P()},u),p.timeoutTimer=setTimeout(()=>{m({kind:"timeout",message:"Sign-in timed out. Please try again."})},o),(async()=>{try{if(await c(f.signal)==="cancel"){try{await e(`${n}/api/auth/cli/cancel`,{method:"POST",headers:{"content-type":"application/json","user-agent":"xeno-agent-cli"},body:JSON.stringify({session_id:p.sessionId})})}catch{}m({kind:"cancelled"})}}catch($){let E=$ instanceof Error?$.message:String($);m({kind:"error",message:`Sign-in cancel watcher failed: ${E}`})}})();let C=await g;return await b(),C}var hl,Xo,Ko,Um,jm,Vm,qm,yl=kt(()=>{"use strict";On();hn();fn();It();At();$n();hl=t=>Ke()(t),Xo=bl.dim,Ko=bl.bold,Um=1455,jm=2e3,Vm=600*1e3,qm=`<!doctype html>
|
|
34
|
+
<html lang="en">
|
|
35
|
+
<head>
|
|
36
|
+
<meta charset="utf-8">
|
|
37
|
+
<title>Signed in to XENO</title>
|
|
38
|
+
<style>
|
|
39
|
+
:root { color-scheme: dark; }
|
|
40
|
+
html, body { margin: 0; padding: 0; height: 100%; }
|
|
41
|
+
body {
|
|
42
|
+
background: #121212;
|
|
43
|
+
color: #e0e0e0;
|
|
44
|
+
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
|
|
45
|
+
display: flex;
|
|
46
|
+
align-items: center;
|
|
47
|
+
justify-content: center;
|
|
48
|
+
}
|
|
49
|
+
.card {
|
|
50
|
+
text-align: center;
|
|
51
|
+
padding: 48px 64px;
|
|
52
|
+
border: 1px solid #2a2a2a;
|
|
53
|
+
border-radius: 12px;
|
|
54
|
+
background: #181818;
|
|
55
|
+
max-width: 420px;
|
|
56
|
+
}
|
|
57
|
+
h1 { font-size: 22px; font-weight: 600; margin: 0 0 12px 0; }
|
|
58
|
+
p { font-size: 14px; line-height: 1.5; margin: 0; color: #a0a0a0; }
|
|
59
|
+
.check { font-size: 36px; color: #6ee7b7; margin-bottom: 8px; }
|
|
60
|
+
</style>
|
|
61
|
+
</head>
|
|
62
|
+
<body>
|
|
63
|
+
<div class="card">
|
|
64
|
+
<div class="check">✓</div>
|
|
65
|
+
<h1>Signed in to XENO</h1>
|
|
66
|
+
<p>You can close this tab and return to your terminal.</p>
|
|
67
|
+
</div>
|
|
68
|
+
</body>
|
|
69
|
+
</html>
|
|
70
|
+
`});import vl from"chalk";function wl(t){let e=t?.trim();if(e)return e.replace(/\/+$/,"")}function Km(t,e){return new Promise(n=>{if(e.aborted){n();return}let s=setTimeout(()=>{e.removeEventListener("abort",r),n()},t),r=()=>{clearTimeout(s),e.removeEventListener("abort",r),n()};e.addEventListener("abort",r)})}function Gm(t){return new Promise(e=>{if(!process.stdin.isTTY){let i=()=>{t.removeEventListener("abort",i),e("complete")};t.addEventListener("abort",i);return}let n=()=>{o(),e("complete")},s=null,r=i=>{(i==="\x1B"||i==="")&&(o(),e("cancel"))},o=()=>{s?.release(),s=null,t.removeEventListener("abort",n)};s=Ct(r),t.addEventListener("abort",n)})}function Ym(t){let e=t.trim();return/^[A-HJ-NP-Z2-9]{8}$/.test(e)?`${e.slice(0,4)}-${e.slice(4)}`:e}function Jm(t,e){let n=d.clearScreen();n+=d.hideCursor();let s=1,r=o=>{n+=d.moveTo(s,1)+d.eraseLine()+o,s++};return r(` ${xr(Yo("Welcome to XENO"))}${xr(", the AI-native command-line agent")}`),r(""),r(` ${xr("Finish signing in via your browser")}`),r(""),r(` ${kr("1. Open this link in your browser and sign in")}`),r(""),r(` ${Yo(t)}`),r(""),r(` ${kr("2. Enter this one-time code after you are signed in (expires in 15 minutes)")}`),r(""),r(` ${xr(Yo(e))}`),r(""),r(` ${kr("Device codes are a common phishing target. Never share this code.")}`),r(""),r(` ${kr("Press esc to cancel")}`),n}async function Jo(t={}){let e=t.fetchImpl??fetch,n=wl(t.authBaseURL)??ot,s=wl(t.apiBaseURL)??we.XENO_API_BASE,r=t.cliVersion??Ze,o=t.log??(b=>process.stdout.write(b)),i=t.sleep??Km,a=t.waitForCancel??Gm,l=t.maxPollAttempts??1e3,c;try{let b=await e(`${n}/api/auth/cli/device-code`,{method:"POST",headers:{"content-type":"application/json","user-agent":"xeno-agent-cli"},body:JSON.stringify({cli_version:r})});if(!b.ok){let v=await b.text();return{kind:"error",message:`Failed to start device-code flow (${b.status}): ${v.slice(0,200)}`}}c=await b.json()}catch(b){return{kind:"error",message:`Failed to start device-code flow: ${b instanceof Error?b.message:String(b)}`}}let u=Ym(c.user_code);t.onStarted?.({...c,formattedUserCode:u}),t.silent||o(Jm(c.verification_url,u));let p=new AbortController,f=!1,m,g=new Promise(b=>{m=v=>{f||(f=!0,p.abort(),b(v))}});return(async()=>{try{await a(p.signal)==="cancel"&&m({kind:"cancelled"})}catch(b){let v=b instanceof Error?b.message:String(b);m({kind:"error",message:`Device-code cancel watcher failed: ${v}`})}})(),(async()=>{try{let b=Math.max(1,c.interval||5),v=Date.now()+Math.max(60,c.expires_in||900)*1e3;for(let w=0;w<l;w++){if(f||(await i(b*1e3,p.signal),f))return;if(Date.now()>v){m({kind:"timeout",message:"Sign-in code expired. Please try again."});return}try{let P=await e(`${n}/api/auth/cli/device-code/poll`,{method:"POST",headers:{"content-type":"application/json","user-agent":"xeno-agent-cli"},body:JSON.stringify({device_code:c.device_code})});if(P.status===410){m({kind:"timeout",message:"Sign-in code expired. Please try again."});return}if(!P.ok)continue;let C=await P.json();if(C.status==="complete"&&C.token){let $={accountToken:C.token,apiKey:C.token,authBaseURL:n,apiBaseURL:s,...C.user?{user:C.user}:{},source:"device-code"},E=bt($,t.homePath);m({kind:"success",user:C.user,credentials:E});return}if(C.status==="expired"){m({kind:"timeout",message:"Sign-in code expired. Please try again."});return}if(C.status==="slow_down"){b=Math.min(b*2,60);continue}}catch{}}f||m({kind:"timeout",message:"Sign-in timed out. Please try again."})}catch(b){let v=b instanceof Error?b.message:String(b);m({kind:"error",message:`Device-code polling failed: ${v}`})}})(),g}var Yo,kr,xr,Sl=kt(()=>{"use strict";On();hn();fn();It();At();$n();Yo=t=>Ke()(t),kr=vl.dim,xr=vl.bold});import Zo from"chalk";function Tr(t){let e=t?.trim();if(e)return e.replace(/\/+$/,"")}async function Qm(t,e){let n=Tr(e.apiBaseURL)??we.XENO_API_BASE,s=Tr(e.authBaseURL)??we.XENO_API_BASE,r=await bn({apiKey:t,apiBaseURL:n,fetchImpl:e.fetchImpl});if(r.valid)return{ok:!0,source:"token"};let o=await Fo({accountToken:t,authBaseURL:s,fetchImpl:e.fetchImpl});return o.valid?{ok:!0,source:"browser-oauth",user:o.user}:{ok:!1,source:"token",error:r.error??o.error??"Invalid token."}}function Pr(t){let e=d.clearScreen();e+=d.hideCursor();let n=1,s=u=>{e+=d.moveTo(n,1)+d.eraseLine()+u,n++};s(` ${Qo(kl("Welcome to XENO"))}${Qo(", the AI-native command-line agent")}`),s(""),s(` ${kl("> ")}${Qo("Use your own XENO API token for usage-based billing")}`),s(""),s(` ${wn("Paste or type your API token below.")}`),s(` ${wn("It will be stored locally in ~/.xeno/credentials.json.")}`),s("");let o=Math.max(60,t.buffer.length+4),i=`\u256D\u2500 API token ${"\u2500".repeat(Math.max(0,o-12))}\u256E`,a=`\u2570${"\u2500".repeat(o)}\u256F`,l=t.buffer.length>o-2?t.buffer.slice(t.buffer.length-(o-2)):t.buffer,c=l+" ".repeat(Math.max(0,o-2-l.length));return s(` ${wn(i)}`),s(` ${wn("\u2502")} ${c}${wn("\u2502")}`),s(` ${wn(a)}`),s(""),t.validating?s(` ${wn("Validating token...")}`):t.errorMessage?s(` ${Zo.red(t.errorMessage)}`):s(""),s(""),s(` ${wn("Press enter to save \xB7 Press esc to go back")}`),e}function Zm(t,e,n){return process.stdin.isTTY?new Promise(s=>{let r=n??"",o=null,i=(c,u)=>{e||t(Pr({buffer:r,errorMessage:c,validating:u}))},a=()=>{o?.release(),o=null,process.stdout.write(d.showCursor())};o=Ct(c=>{if(c===""){a(),s({cancelled:!0});return}if(c==="\x1B"){a(),s({cancelled:!0});return}if(c==="\r"||c===`
|
|
71
|
+
`){a(),s(r.trim());return}if(c==="\x7F"||c==="\b"){r=r.slice(0,-1),i();return}if(c.startsWith("\x1B"))return;let u=Array.from(c).filter(p=>{let f=p.charCodeAt(0);return f>=32&&f!==127}).join("");u.length>0&&(r+=u,i())}),i()}):Promise.resolve({cancelled:!0})}async function ei(t={}){let e=t.log??(r=>process.stdout.write(r)),n,s=t.inputToken?.trim();for(;;){let r;if(s!==void 0)r=s,s=void 0;else{let i=await Zm(e,!!t.silent,void 0);if(typeof i!="string")return{kind:"cancelled"};r=i}if(!r){if(n="Token is empty. Please paste a valid token.",t.inputToken!==void 0)return{kind:"error",message:n};t.silent||e(Pr({buffer:"",errorMessage:n}));continue}t.silent||e(Pr({buffer:r,validating:!0}));let o=await Qm(r,{apiBaseURL:t.apiBaseURL,authBaseURL:t.authBaseURL,fetchImpl:t.fetchImpl});if(o.ok){let i=Tr(t.apiBaseURL)??we.XENO_API_BASE,a=Tr(t.authBaseURL)??we.XENO_API_BASE,l=o.source==="browser-oauth"?{accountToken:r,apiKey:r,authBaseURL:a,apiBaseURL:i,...o.user?{user:o.user}:{},source:"token"}:{apiKey:r,apiBaseURL:i,source:"token"},c=bt(l,t.homePath);return{kind:"success",user:o.user,credentials:c}}if(n=`Invalid token. ${o.error??"Please try again."}`,t.inputToken!==void 0)return{kind:"error",message:n};t.silent||e(Pr({buffer:r,errorMessage:n}))}}var kl,wn,Qo,xl=kt(()=>{"use strict";On();hn();fn();It();At();kl=t=>Ke()(t),wn=Zo.dim,Qo=Zo.bold});var _r={};cr(_r,{runBrowserFlow:()=>Go,runDeviceCodeFlow:()=>Jo,runTokenPasteFlow:()=>ei,runWelcomeAuthFlow:()=>ni,showWelcomeScreen:()=>qo});async function ni(t={}){for(;;){let e=await qo();if(e.choice==="exit")return{kind:"exit"};if(e.choice==="browser"){let n=await Go({authBaseURL:t.authBaseURL,apiBaseURL:t.apiBaseURL,fetchImpl:t.fetchImpl,homePath:t.homePath,log:t.log,cliVersion:t.cliVersion}),s=ef(n);if(s)return t.skipSuccessScreen?s:await ti(s);continue}if(e.choice==="device-code"){let n=await Jo({authBaseURL:t.authBaseURL,apiBaseURL:t.apiBaseURL,fetchImpl:t.fetchImpl,homePath:t.homePath,log:t.log,cliVersion:t.cliVersion}),s=tf(n);if(s)return t.skipSuccessScreen?s:await ti(s);continue}if(e.choice==="token"){let n=await ei({apiBaseURL:t.apiBaseURL,authBaseURL:t.authBaseURL,fetchImpl:t.fetchImpl,homePath:t.homePath,log:t.log}),s=nf(n);if(s)return t.skipSuccessScreen?s:await ti(s);continue}}}async function ti(t){return t.kind!=="success"?t:(await ml({via:t.via,email:t.user?.email,displayName:t.user?.name})).outcome==="exit"?{kind:"exit"}:t}function ef(t){if(t.kind==="success")return{kind:"success",via:"browser",user:t.user,credentials:t.credentials};if(t.kind==="error")return{kind:"error",message:t.message};if(t.kind==="timeout")return{kind:"error",message:t.message}}function tf(t){if(t.kind==="success")return{kind:"success",via:"device-code",user:t.user,credentials:t.credentials};if(t.kind==="error"||t.kind==="timeout")return{kind:"error",message:t.message}}function nf(t){if(t.kind==="success")return{kind:"success",via:"token",user:t.user,credentials:t.credentials};if(t.kind==="error")return{kind:"error",message:t.message}}var Ms=kt(()=>{"use strict";pl();fl();yl();Sl();xl()});import{program as je}from"commander";import{randomUUID as Bx}from"crypto";import{join as hp,resolve as ws}from"path";import{createInterface as Dx}from"readline";import{existsSync as lg,readFileSync as cg,statSync as kc,writeFileSync as ug}from"fs";import{randomUUID as dg}from"crypto";import{spawn as pg}from"child_process";import{basename as qs,dirname as mg,join as Us,relative as xc,resolve as Vn}from"path";import{createInterface as Pc}from"readline";var Rn={};Me(Rn,iP);import*as iP from"@xeno-corporation/xeno-agent-sdk";Wt();fn();It();At();import qe from"chalk";import{spawn as em}from"child_process";import{readdirSync as tm,statSync as nm}from"fs";import{join as Ha}from"path";var be=t=>Ke()(t),x=qe.dim,za=t=>Ke()(t),gt=t=>Da()(t),sm=t=>Fa()(t),hr=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];function rm(t,e){return e==="bypassPermissions"?"\u25A3":t==="chatOnly"?"\u25A1":"\u25A0"}function An(t){return t>=1e4?`${Math.round(t/1e3)}K`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}var Yn=[{name:"/help",description:"Show help and available commands"},{name:"/login",description:"Sign in, inspect auth status, or store an API key"},{name:"/logout",description:"Sign out and clear local XENO credentials"},{name:"/open",description:"Open the current workspace folder in Explorer/Finder"},{name:"/clear",description:"Clear the chat history"},{name:"/exit",description:"Exit XENO AGENT"},{name:"/quit",description:"Exit XENO AGENT"},{name:"/tokens",description:"Show token usage and cost"},{name:"/model",description:"Show or switch the AI model"},{name:"/approvals",description:"Update XENO approvals for tool actions"},{name:"/approved-tools",description:"Inspect or revoke remembered tool approvals"},{name:"/color",description:"Show or switch the UI color theme"},{name:"/mode",description:"Switch runtime mode (Chat/Agent/Full Access)"},{name:"/delegate",description:"Toggle delegated planner/explorer/executor/reviewer turns"},{name:"/memory",description:"Show and edit memory levels"},{name:"/remember",description:"Add text to project memory"},{name:"/memory context",description:"Inspect prompt memory context and diagnostics"},{name:"/checkpoint",description:"Create a manual checkpoint"},{name:"/audit",description:"Tail, inspect, or export audit events (--json)"},{name:"/sessions",description:"List saved sessions"},{name:"/resume",description:"Resume a saved session"},{name:"/save",description:"Save current session"},{name:"/export",description:"Export conversation to file or JSON"},{name:"/init",description:"Initialize project for AI-assisted development"},{name:"/review",description:"AI code review of recent git changes"},{name:"/mcp",description:"Manage MCP servers, prompts, and resources"},{name:"/doctor",description:"Run local runtime, config, and MCP health checks"},{name:"/bug-report",description:"Export a redacted diagnostics bundle"},{name:"/config",description:"Inspect or edit local config state"},{name:"/ctx-viz",description:"Inspect system prompt, tools, and message context usage"},{name:"/onboarding",description:"Show or update onboarding guidance for this workspace"},{name:"/release-notes",description:"Show current or requested release notes"},{name:"/terminal-setup",description:"Install terminal Shift+Enter integration"},{name:"/listen",description:"Start system dictation / voice typing"},{name:"/pr-comments",description:"Fetch and render GitHub PR comments"},{name:"/processes",description:"List and manage background tasks"},{name:"/context",description:"Show context usage and token fuel gauge"}],gr=class{opts;MAX_FOOTER_HEIGHT=9;NORMAL_FOOTER_OVERHEAD_ROWS=5;SHOW_STATUS_BAR=!0;MAX_INPUT_ROWS=6;COLLAPSE_PASTE_MIN_LINES=4;MODEL_PICKER_VISIBLE_OPTIONS=8;SESSION_PICKER_VISIBLE_ITEMS=5;INFO_PANEL_EDIT_UNDO_LIMIT=100;SLASH_COMMANDS=Yn.map(e=>e.name);rows=0;cols=0;outputBottom=0;outputRow=1;outputCol=1;outputHistory="";inputBuffer="";cursorPos=0;inputHistory=[];historyIndex=-1;historyDraft="";pastedTextCounter=0;pastedTextBlocks=new Map;inputScrollOffset=0;inputLineScrollOffset=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="";busyActivityTicker=null;busyStartedAt=0;busyActivityLabel="Processing request...";delegationViewState=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;infoPanelState=null;_busy=!1;_queuedMessage=null;_verboseToolOutput=!1;tokensUsed=0;costDisplay="";autocompleteVisible=!1;autocompleteMatches=[];autocompleteSelectedIndex=0;autocompleteScrollOffset=0;wasAutocompleteVisible=!1;cleaned=!1;lastCtrlCTimestamp=0;CTRL_C_EXIT_WINDOW_MS=1500;statusRightHint=null;statusRightHintTimer=null;footerFocus="input";statusFocusIndex=0;STATUS_FOCUSABLE_COUNT=6;resizeDebounceTimer=null;inputHealthTimer=null;inputHealthTick=0;lastInputEventAt=0;inputAttachedAt=0;RESIZE_DEBOUNCE_MS=60;resizeInProgress=!1;promptContextBreakdown="";delegationEnabled=!1;outputBlocks=[];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=e=>{let n=typeof e=="string"?e:e.toString("utf8");this.lastInputEventAt=Date.now(),Bt("screen:data",{length:n.length,hex:Buffer.from(n,"utf8").toString("hex"),busy:this._busy,isPrompting:this.isPrompting,footerFocus:this.footerFocus,overlays:this.activeOverlayNames(),listenerCount:process.stdin.listenerCount("data"),isRaw:process.stdin.isRaw}),this.handleKeypress(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(e){this.opts=e,this.promptContextBreakdown=(e.promptContextBreakdown||"").trim(),this.delegationEnabled=!!e.delegationEnabled,this.calculateLayout(),this.setupRawMode(),this.setupResize(),this.setupCleanup(),this.initScreen()}get busy(){return this._busy}set busy(e){let n=this._busy;this._busy=e,e&&(this.quickActionBarOpen=!1,this.quickActionView="main",this.quickRewriteSelectedIndex=0,this.quickRewriteCustomInput="",this.quickActionInlineHint=null),e&&!n?(this.busyInterruptRequested=!1,this.openRewindAfterInterrupt=!1,this.busyStartedAt=Date.now(),this.startBusyActivityTicker()):!e&&n&&(this.stopBusyActivityTicker(),this.busyInterruptRequested=!1,this.busyStartedAt=0,this.busyActivityLabel="Processing request..."),this.hasOverlayOpen()||this.drawInputBox(),this.drawStatusBar(),this.refreshFooterFocusCursor(),!e&&n&&this.maybeOpenPendingInterruptRewind()}setPromptSuggestion(e){this._promptSuggestion=e,!this._busy&&this.inputBuffer.length===0&&this.drawInputBox()}_backgroundTaskCount=0;setBackgroundTaskCount(e){this._backgroundTaskCount=e,this.drawStatusBar()}getBackgroundTaskCount(){return this._backgroundTaskCount}takeQueuedMessage(){let e=this._queuedMessage;return this._queuedMessage=null,e}get hasQueuedMessage(){return this._queuedMessage!==null}updateTokens(e,n){this.tokensUsed=e,n!==void 0&&(this.costDisplay=n),this.drawStatusBar()}setModel(e){this.opts.model=e,this.drawStatusBar()}setPermissionMode(e){this.opts.permissionMode=e,this.drawInputBox(),this.drawStatusBar()}setExecutionMode(e){this.opts.executionMode=e,this.drawStatusBar()}setDelegationEnabled(e){this.delegationEnabled=e,this.drawStatusBar()}setPromptContextBreakdown(e){this.promptContextBreakdown=(e||"").trim(),this.drawStatusBar()}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.infoPanelState){this.drawInfoPanelUI();return}this.drawInputBox(),this.drawStatusBar(),this.refreshFooterFocusCursor()}startDelegationView(e){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:e.map(n=>({role:n,status:"queued",phase:"queued",activity:"Waiting",toolCount:0,tokenCount:0,events:[]})),events:[]},this.redrawDelegationFooter()}updateDelegationAgent(e,n){if(!this.delegationViewState)return;let s=this.delegationViewState.agents.find(r=>r.role===e);s&&(n.status!==void 0&&(s.status=n.status),n.phase!==void 0&&(s.phase=n.phase),n.activity!==void 0&&(s.activity=n.activity),n.toolCount!==void 0&&(s.toolCount=n.toolCount),n.tokenCount!==void 0&&(s.tokenCount=n.tokenCount),n.currentTool!==void 0&&(s.currentTool=n.currentTool),n.outputPreview!==void 0&&(s.outputPreview=n.outputPreview),this.refreshDelegationViews())}appendDelegationEvent(e,n){if(!this.delegationViewState)return;let s=e.trim().length>0?e:"system",r=this.getDelegationLogDockVisibleLines(),o=Math.max(0,this.delegationViewState.events.length-r),i=!this.delegationLogDockExpanded||this.delegationLogDockScrollOffset>=o;this.delegationViewState.events.push({role:s,message:n,timestamp:Date.now()}),this.delegationViewState.events.length>12&&this.delegationViewState.events.shift();let a=this.delegationViewState.agents.find(u=>u.role===s);a&&(a.events.push({role:s,message:n,timestamp:Date.now()}),a.events.length>200&&a.events.shift());let l=this.getDelegationLogDockVisibleLines(),c=Math.max(0,this.delegationViewState.events.length-l);i?this.delegationLogDockScrollOffset=c:this.delegationLogDockScrollOffset=Math.max(0,Math.min(this.delegationLogDockScrollOffset,c)),this.refreshDelegationViews()}clearDelegationView(){if(!this.delegationViewState)return;let e=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(),process.stdout.write(d.setScrollRegion(1,this.outputBottom)),this.redrawScreenFromHistory()),this.delegationViewState=null,this.delegationLogDockExpanded=!1,this.delegationLogDockScrollOffset=0,this.footerFocus==="delegation"&&(this.footerFocus="input"),e&&!this.resizeInProgress&&this.redrawScreenFromHistory(),this.redrawDelegationFooter()}showDelegationCompletionSummary(e,n=5e3){this.delegationCompletionState?.timer&&clearTimeout(this.delegationCompletionState.timer);let s=setTimeout(()=>{this.delegationCompletionState=null,!this.resizeInProgress&&!this.hasOverlayOpen()&&(this.drawInputBox(),this.refreshFooterFocusCursor())},n);this.delegationCompletionState={text:e,timer:s},!this.resizeInProgress&&!this.hasOverlayOpen()&&(this.drawInputBox(),this.refreshFooterFocusCursor())}showTransientActivityNotice(e,n=4e3){this.transientActivityNotice?.timer&&clearTimeout(this.transientActivityNotice.timer);let s=setTimeout(()=>{this.transientActivityNotice=null,!this.resizeInProgress&&!this.hasOverlayOpen()&&(this.drawInputBox(),this.refreshFooterFocusCursor())},n);this.transientActivityNotice={text:e,timer:s},!this.resizeInProgress&&!this.hasOverlayOpen()&&(this.drawInputBox(),this.refreshFooterFocusCursor())}appendRawOutputBlock(e,n){let s=!!n?.selectable,r=n?.blockKind,o=!!n?.forceNewBlock,i=this.shouldReflowOutputKind(r),a=i?this.wrapOutputForTerminal(e):e,l=this.outputBlocks[this.outputBlocks.length-1];return!o&&l?.type==="raw"&&!!l.selectable===s&&(l.kind??null)===(r??null)?(l.sourceText=(l.sourceText??l.text)+e,l.text+=a,a):(this.outputBlocks.push({type:"raw",text:a,sourceText:i?e:void 0,selectable:s,kind:r}),a)}syncRenderedOutputHistory(){this.outputHistory=this.renderOutputBlocks()}getRawOutputBlockSource(e){return e.sourceText??e.text}shouldReflowRawOutputBlock(e){return this.shouldReflowOutputKind(e.kind)}shouldReflowOutputKind(e){return e!=="tool-call"&&e!=="tool-result"}getRawOutputBlockRenderableText(e,n){let s=this.getRawOutputBlockSource(e);return this.shouldReflowRawOutputBlock(e)?this.wrapOutputForTerminal(s,n):s}normalizeOutputViewportText(e){let s=e.replace(/\r\n/g,`
|
|
72
|
+
`).split(`
|
|
73
|
+
`),r=[];for(let o of s)o.length===0&&r[r.length-1]===""||r.push(o);return r.join(`
|
|
74
|
+
`)}getOutputViewportVisibleRows(){return Math.max(1,this.outputBottom)}splitOutputTextLines(e){let n=e.replace(/\r\n/g,`
|
|
75
|
+
`);if(n.length===0)return[];let s=n.split(`
|
|
76
|
+
`);return s.length>0&&s[s.length-1]===""&&s.pop(),s}styleFocusedOutputLines(e,n){let s=e.findIndex(l=>se(l).trim().length>0);if(s===-1)return e.slice();let r=s;for(let l=e.length-1;l>=s;l--)if(se(e[l]).trim().length>0){r=l;break}let o=n?sm:gt,i=Math.max(10,this.cols),a=[];for(let l=0;l<e.length;l++){let c=e[l];if(l<s||l>r){a.push(c);continue}let u=se(c);if(u.length===0){a.push(c);continue}if(u.length>i)for(let p=0;p<u.length;p+=i)a.push(o(u.slice(p,p+i)));else a.push(o(u))}return a}getFocusedOutputRelatedIndices(){let e=new Set;if(this.outputFocusIndex<0)return e;e.add(this.outputFocusIndex);let n=this.outputBlocks[this.outputFocusIndex],s=this.outputBlocks[this.outputFocusIndex-1];return n?.type==="collapsible"&&this.isToolCallPreviewBlock(s)&&e.add(this.outputFocusIndex-1),e}renderOutputBlockLinesForViewport(e,n){let r=(this.footerFocus==="output"?this.getFocusedOutputRelatedIndices():new Set).has(n),o=e.type==="collapsible"?this.getCollapsibleText(e):this.getRawOutputBlockRenderableText(e,1),i=e.type==="raw"&&this.isOutputActionRowOpenForBlock(n);i&&(o=o.replace(/\n$/,""));let a=this.splitOutputTextLines(o);if(r){let c=this.outputActionState?.blockIndex===n&&this.outputActionState.focus!=="message";a=this.styleFocusedOutputLines(a,c)}if(!i)return a;let l=this.splitOutputTextLines(this.renderOutputActionRow(n));return l[0]===""&&l.shift(),a.concat(l)}buildFocusedOutputViewport(){let e=[],n=new Map;return this.outputBlocks.forEach((s,r)=>{let o=this.renderOutputBlockLinesForViewport(s,r),i=e.length;e.push(...o);let a=Math.max(i,e.length-1);n.set(r,{start:i,end:a})}),{lines:e,blockRanges:n}}keepFocusedOutputBlockInView(e){let n=this.getOutputViewportVisibleRows(),s=Math.max(0,e.lines.length-n),o=[...this.getFocusedOutputRelatedIndices()].map(l=>e.blockRanges.get(l)).filter(l=>!!l),i=o.length===0?null:{start:Math.min(...o.map(l=>l.start)),end:Math.max(...o.map(l=>l.end))};if(!i){this.outputViewportTopLine=s;return}if(this.outputViewportTopLine=Math.max(0,Math.min(this.outputViewportTopLine,s)),i.end-i.start+1>=n){let l=i.start,c=Math.max(i.start,i.end-n+1);this.outputViewportTopLine<l?this.outputViewportTopLine=l:this.outputViewportTopLine>c&&(this.outputViewportTopLine=c)}else i.start<this.outputViewportTopLine?this.outputViewportTopLine=i.start:i.end>=this.outputViewportTopLine+n&&(this.outputViewportTopLine=Math.max(0,i.end-n+1));this.outputViewportTopLine=Math.max(0,Math.min(this.outputViewportTopLine,s))}clampOutputViewportTopLine(e){let n=this.getOutputViewportVisibleRows(),s=Math.max(0,e.lines.length-n);this.outputViewportTopLine=Math.max(0,Math.min(this.outputViewportTopLine,s))}pageScrollOutputViewport(e){let n=this.buildFocusedOutputViewport();if(n.lines.length===0)return;let s=this.getOutputViewportVisibleRows(),r=Math.max(1,s-1)*e;this.outputViewportTopLine+=r,this.outputViewportManualScroll=!0,this.clampOutputViewportTopLine(n),this.redrawScreenFromHistory(),this.drawInputBox()}wheelScrollOutputViewport(e){let n=this.buildFocusedOutputViewport();n.lines.length!==0&&(this.outputViewportTopLine+=e*3,this.outputViewportManualScroll=!0,this.clampOutputViewportTopLine(n),this.redrawScreenFromHistory(),this.drawInputBox())}jumpOutputViewport(e){let n=this.buildFocusedOutputViewport();if(n.lines.length===0)return;let s=this.getOutputViewportVisibleRows();this.outputViewportTopLine=e==="start"?0:Math.max(0,n.lines.length-s),this.outputViewportManualScroll=!0,this.redrawScreenFromHistory(),this.drawInputBox()}isToolCallPreviewBlock(e){return!e||e.type!=="raw"?!1:se(e.text).trimStart().startsWith("\u25A0 ")}isPairedToolCallBlock(e){let n=this.outputBlocks[e],s=this.outputBlocks[e+1];return this.isToolCallPreviewBlock(n)&&!!(s&&s.type==="collapsible"&&(s.kind??"tool-result")==="tool-result")}getRenderableOutputSegment(e,n){if(e.type==="collapsible"){let s=this.getCollapsibleText(e),r=`
|
|
77
|
+
`.repeat(e.trailingNewlines);return s+r}return this.renderOutputBlock(e,n)}renderOutputBlocks(){let e=1,n="";for(let s=0;s<this.outputBlocks.length;s++){let r=this.outputBlocks[s],o=r.type==="raw"&&this.shouldReflowRawOutputBlock(r)?this.getRawOutputBlockRenderableText(r,e):this.getRenderableOutputSegment(r,s);n+=o,e=this.getOutputEndColumn(o,e)}return n}getCollapsibleOutputBlockIndices(){return this.outputBlocks.map((e,n)=>({block:e,index:n})).filter(({block:e})=>e.type==="collapsible").map(({index:e})=>e)}getSelectableOutputBlockIndices(){return this.outputBlocks.map((e,n)=>({block:e,index:n})).filter(({block:e,index:n})=>e.type==="collapsible"?!0:!(!e.selectable||this.isPairedToolCallBlock(n))).map(({index:e})=>e)}hasCollapsibleOutputBlocks(){return this.getCollapsibleOutputBlockIndices().length>0}hasSelectableOutputBlocks(){return this.getSelectableOutputBlockIndices().length>0}getFocusedOutputBlockIndex(){return this.outputFocusIndex}getFocusedOutputBlock(){return this.outputBlocks[this.outputFocusIndex]??null}isUserActionableOutputBlock(e){return!!(e&&e.type==="raw"&&e.kind==="user")}getCollapsibleText(e){let n=e.expanded?e.expandedText:e.summaryText;if(!e.expanded||!e.secondaryAction)return n;let s=`
|
|
78
|
+
${x("\u23BF")} ${x(e.secondaryActionLabel??"Press Enter again to open details")}`;return n.endsWith(`
|
|
79
|
+
`)?`${n}${s.trimStart()}`:`${n}${s}`}isOutputActionRowOpenForBlock(e){return this.outputActionState?.blockIndex===e}openOutputActionRow(e){this.outputActionState={blockIndex:e,focus:"actions",selectedActionIndex:0,pendingAction:null},this.redrawScreenFromHistory(),this.drawInputBox()}closeOutputActionRow(e){this.outputActionState=null,e?.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(e){if(!this.isOutputActionRowOpenForBlock(e))return"";let n=this.outputActionState;if(n.focus==="message")return"";if(n.pendingAction){let a=n.focus==="confirm"?gt("[CONFIRM]"):x("[CONFIRM]");return`
|
|
80
|
+
${x("\u23BF")} ${a}`}let s=n.focus==="actions"?n.selectedActionIndex:-1,r=s===0?gt("[EDIT]"):x("[EDIT]"),o=s===1?gt("[RETRY]"):x("[RETRY]"),i=s===2?gt("[RESTORE]"):x("[RESTORE]");return`
|
|
81
|
+
${x("\u23BF")} ${r} ${o} ${i}`}getSelectedOutputActionRequest(){let e=this.outputActionState;if(!e?.pendingAction)return null;let n=this.outputBlocks[e.blockIndex];if(!n||n.type!=="raw")return null;let r=se(this.getRawOutputBlockSource(n)).replace(/\r\n/g,`
|
|
82
|
+
`).replace(/^\n?❯\s*/,"").trim(),o=this.outputBlocks.map((a,l)=>({candidate:a,index:l})).filter(({candidate:a})=>a.type==="raw"&&a.kind==="user").map(({index:a})=>a),i=Math.max(0,o.indexOf(e.blockIndex));return{action:e.pendingAction,text:r,userMessageOrdinal:i}}renderOutputBlock(e,n){if(e.type==="collapsible")return this.getCollapsibleText(e);let s=this.getRawOutputBlockRenderableText(e,1);return this.isOutputActionRowOpenForBlock(n)&&(s=s.replace(/\n$/,""),s+=this.renderOutputActionRow(n),s.endsWith(`
|
|
83
|
+
`)||(s+=`
|
|
84
|
+
`)),s}focusLatestOutputBlock(){let e=this.getSelectableOutputBlockIndices();if(e.length===0)return;this.footerFocus="output",this.setMouseReportingEnabled(!0),this.outputFocusIndex=e[e.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(e){let n=this.getSelectableOutputBlockIndices();if(n.length===0)return;this.setMouseReportingEnabled(!0);let s=n.indexOf(this.outputFocusIndex),r=s===-1?e>0?0:n.length-1:Math.max(0,Math.min(n.length-1,s+e));this.outputFocusIndex=n[r],this.outputViewportManualScroll=!1,this.keepFocusedOutputBlockInView(this.buildFocusedOutputViewport()),this.redrawScreenFromHistory(),this.drawInputBox()}getFocusedOutputViewportText(){if(this.outputFocusIndex<0)return null;let e=this.buildFocusedOutputViewport();if(e.lines.length===0)return null;this.outputViewportManualScroll?this.clampOutputViewportTopLine(e):this.keepFocusedOutputBlockInView(e);let n=this.getOutputViewportVisibleRows(),s=e.lines.slice(this.outputViewportTopLine,this.outputViewportTopLine+n);return this.normalizeOutputViewportText(s.join(`
|
|
85
|
+
`))}writeCollapsibleInfo(e,n,s){let r={type:"collapsible",summaryText:e,expandedText:n,expanded:!!s?.initiallyExpanded,trailingNewlines:s?.trailingNewlines??1,selectable:s?.selectable??!0,kind:s?.blockKind??"tool-result",autoCollapseTimer:null,secondaryActionLabel:s?.secondaryActionLabel,secondaryAction:s?.secondaryAction};this.outputBlocks.push(r),this.syncRenderedOutputHistory(),r.expanded&&s?.autoCollapseMs&&s.autoCollapseMs>0&&(r.autoCollapseTimer=setTimeout(()=>{r.expanded=!1,r.autoCollapseTimer=null,this.syncRenderedOutputHistory(),this.resizeInProgress||(this.redrawScreenFromHistory(),this.drawInputBox())},s.autoCollapseMs)),this.redrawScreenFromHistory(),this.drawInputBox()}writeOutput(e,n){if(!e)return;let s=this.appendRawOutputBlock(e,n);this.syncRenderedOutputHistory();let r="";r+=d.hideCursor(),r+=d.moveTo(this.outputRow,this.outputCol),r+=s,this.advanceOutputPosition(s),this.shouldShowInputCursor()?(r+=this.inputCursorPosition(),r+=d.showCursor()):r+=d.hideCursor(),process.stdout.write(r),this.shouldUseDelegationLogDock()&&this.drawDelegationLogDock()}writeInfo(e){this.writeOutput(e+`
|
|
86
|
+
`)}writeError(e){this.writeOutput(qe.red("\u2717 ")+qe.red(e)+`
|
|
87
|
+
`)}trimTrailingOutputNewlines(e){let n=Math.max(0,e),s=0;for(let o=this.outputHistory.length-1;o>=0&&this.outputHistory[o]===`
|
|
88
|
+
`;o--)s++;if(s<=n)return;let r=s-n;if(this.outputHistory=this.outputHistory.slice(0,Math.max(0,this.outputHistory.length-r)),!this.resizeInProgress){if(this.redrawScreenFromHistory(),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.infoPanelState){this.drawInfoPanelUI();return}this.drawInputBox(),this.refreshFooterFocusCursor()}}startSpinner(e){this.stopSpinner(),this.spinnerMessage=e,this.spinnerFrameIndex=0,this.busyActivityLabel=e,this.redrawBusyActivityRow(),this.spinnerInterval=setInterval(()=>{let n=hr[this.spinnerFrameIndex%hr.length];if(this.spinnerFrameIndex++,this._busy){if(this.delegationViewState)return;this.redrawBusyActivityRow();return}let s=`${be(n)} ${x(this.spinnerMessage)}`;process.stdout.write(d.hideCursor()+d.moveTo(this.outputRow,1)+d.eraseLine()+s+(this.shouldShowInputCursor()?this.inputCursorPosition()+d.showCursor():d.hideCursor()))},80)}stopSpinner(){this.spinnerInterval&&(clearInterval(this.spinnerInterval),this.spinnerInterval=null,this._busy||process.stdout.write(d.hideCursor()+d.moveTo(this.outputRow,1)+d.eraseLine()+(this.shouldShowInputCursor()?this.inputCursorPosition()+d.showCursor():d.hideCursor())))}startBusyActivityTicker(){this.busyActivityTicker||(this.busyActivityTicker=setInterval(()=>{this.redrawBusyActivityRow()},250))}stopBusyActivityTicker(){this.busyActivityTicker&&(clearInterval(this.busyActivityTicker),this.busyActivityTicker=null)}redrawDelegationFooter(){this.resizeInProgress||this.hasOverlayOpen()||(this.drawInputBox(),this.refreshFooterFocusCursor())}refreshDelegationViews(){if(this.infoPanelState?.source==="delegation-inspector"){this.updateDelegationInspectorState(),this.drawInfoPanelUI();return}if(this.infoPanelState?.source==="delegation-agent-detail"){this.updateDelegationAgentDetailState(),this.drawInfoPanelUI();return}this.redrawDelegationFooter()}getDelegationLogDockVisibleLines(){let e=this.getDelegationLogDockBounds();return e?Math.max(1,e.height-5):1}formatElapsed(e){let n=Math.max(0,Math.floor(e/1e3)),s=Math.floor(n/60),r=n%60;return`${s}m ${String(r).padStart(2,"0")}s`}busyActivityLine(e){let n=this.renderCols(),s=this.delegationViewState?`Delegation active: ${this.delegationViewState.agents.length} agents (${this.delegationViewState.agents.map(l=>l.role).join(", ")})`:this.busyActivityLabel||"Processing request...",r=this.formatElapsed(Date.now()-this.busyStartedAt),o=`${s} (${r} \u2022 esc to interrupt \u2022 ctrl+b to background)`,i=this.clip(o,Math.max(1,n-4)),a=this._busy?hr[this.spinnerFrameIndex%hr.length]:"\u25E6";return d.moveTo(e,1)+d.eraseLine()+` ${be(a)} ${x(i)}`}buildDelegationFooterLines(e,n){return this.shouldUseDelegationLogDock()?this.buildDelegationFooterBoxLines(e,Math.max(10,n)):this.buildDelegationCompactFooterLines(e,n)}buildDelegationCompactFooterLines(e,n){let s=this.buildDelegationFooterBoxLines(e,Math.max(10,n)),r=e.events[e.events.length-1],o=r?`${r.role}: ${r.message}`:"Waiting for delegated branch activity",i=this.footerFocus==="delegation"?"\u2191 back \xB7 \u2190/\u2192 agent \xB7 Enter logs \xB7 Esc close":"Ctrl+\u2193 select agent",a=x(this.clip(i,Math.max(1,Math.min(38,Math.floor(n*.4))))),l=se(a).length,c=x(this.clip(`Recent: ${o}`,Math.max(1,n-l-2))),u=se(c).length,p=Math.max(1,n-u-l),f=` ${c}${" ".repeat(p)}${a}`;return[...s,f]}buildDelegationLogDockLines(e,n,s){let r=Math.max(1,n-3),o=Math.max(1,s-5),i=`Live Logs - ${e.events.length} recent`,a=this.clip(i,r).padEnd(r," "),l=this.buildDelegationLogBodyLines(e.events,o,this.delegationLogDockExpanded,this.delegationLogDockScrollOffset).slice(0,o).map(u=>this.clip(se(u),r).padEnd(r," ")),c=[];c.push(x(`\u256D${"\u2500".repeat(n-1)}`)),c.push(`${x("\u2502")} ${a} `),c.push(x(`\u251C${"\u2500".repeat(n-1)}`)),c.push(`${x("\u2502")} ${" ".repeat(r)} `);for(let u=0;u<o;u++){let p=l[u]??" ".repeat(r);c.push(`${x("\u2502")} ${p} `)}return c.push(x(`\u2570${"\u2500".repeat(n-1)}`)),c}buildDelegationLogDockHintLine(e){let n=this.delegationLogDockExpanded?"PgUp/PgDn logs \xB7 Home/End jump \xB7 Ctrl+E collapse \xB7 Ctrl+L details":"Ctrl+E expand \xB7 Ctrl+L details",s=this.clip(n,Math.max(1,e));return`${" ".repeat(Math.max(0,e-s.length))}${x(s)}`}getDelegationRoleFromLabel(e){let n=e?.trim().toLowerCase()??"";return n==="planner"||n==="explorer"||n==="executor"||n==="reviewer"?n:null}buildDelegationAgentBodyLines(e){return e.length===0?[x("No delegated agents yet.")]:e.map(n=>{let s=n.status==="running"?be(`${n.role.toUpperCase()}`):qe.bold(n.role.toUpperCase()),r=this.delegationPhaseLabel(n),o=this.styleDelegationSegment(n.status,`${this.delegationStatusLabel(n.status)}${r?` \xB7 ${r}`:""}`,"status"),i=this.styleDelegationSegment(n.status,this.delegationDetailLabel(n),"detail");return`${s} ${x("\xB7")} ${o} ${x("\xB7")} ${i}`})}buildDelegationLogBodyLines(e,n,s,r=0){if(e.length===0)return[x("Waiting for delegated branch activity")];let o=Math.max(0,e.length-n),i=Math.max(0,Math.min(r,o));return e.slice(i,i+n).map(a=>{if(!s)return`${this.styleDelegationLogTag(a.role,this.getDelegationLogTag(a.role))} ${a.message}`;let l=this.formatDelegationEventTime(a.timestamp);return`${x(l)} ${a.role} ${x("\xB7")} ${a.message}`})}getDelegationLogTag(e){let n=e.trim().toLowerCase();return n==="planner"?"PLNR":n==="explorer"?"EXPL":n==="executor"?"EXEC":n==="reviewer"?"REWR":n==="system"?"SYST":this.clip(n.toUpperCase(),4).padEnd(4," ")}styleDelegationLogTag(e,n){let s=e.trim().toLowerCase();return s==="planner"?qe.hex("#7a7a7a")(n):s==="explorer"?qe.hex("#858585")(n):s==="executor"?qe.hex("#969696")(n):s==="reviewer"?qe.hex("#b0b0b0")(n):s==="system"?qe.hex("#666666")(n):x(n)}formatDelegationEventTime(e){let n=new Date(e),s=String(n.getHours()).padStart(2,"0"),r=String(n.getMinutes()).padStart(2,"0"),o=String(n.getSeconds()).padStart(2,"0");return`${s}:${r}:${o}`}buildDelegationFooterBoxLines(e,n){if(n<=2)return[];let s=Math.max(1,n-4),r=this.buildDelegationSegmentLine(e.agents,s,"status"),o=this.buildDelegationSegmentLine(e.agents,s,"detail");return[x(`\u256D${"\u2500".repeat(Math.max(0,n-2))}\u256E`),`${x("\u2502")} ${r.padEnd(s," ")} ${x("\u2502")}`,`${x("\u2502")} ${o.padEnd(s," ")} ${x("\u2502")}`,x(`\u2570${"\u2500".repeat(Math.max(0,n-2))}\u256F`)]}buildDelegationSegmentLine(e,n,s){if(e.length===0||n<=0)return"";let r=` ${x("\u2502")} `,o=se(r).length,i=Math.max(e.length,n-(e.length-1)*o),a=Math.max(12,Math.floor(i/e.length)),l=[];for(let c=0;c<e.length;c++){let u=e[c],p=c===e.length-1?Math.max(12,i-a*(e.length-1)):a,f=s==="status"?`${u.role.toUpperCase()} ${this.delegationStatusLabel(u.status)}`:this.delegationDetailLabel(u),m=this.clip(f,Math.max(1,p)).padEnd(Math.max(1,p)," ");this.footerFocus==="delegation"&&c===this.delegationFocusIndex?l.push(gt(m)):l.push(this.styleDelegationSegment(u.status,m,s))}return l.join(r)}delegationStatusLabel(e){return e==="running"?"Running":e==="done"?"Done":e==="failed"?"Failed":e==="interrupted"?"Interrupted":"Queued"}delegationDetailLabel(e){let s=[e.status==="done"?e.outputPreview||"Completed":e.currentTool?`${e.currentTool} \xB7 ${e.activity||"Running tool"}`:e.activity||"Waiting"];return e.toolCount>0&&s.push(`${e.toolCount} tools`),s.push(`${An(e.tokenCount)} tok`),s.join(" \xB7 ")}delegationPhaseLabel(e){return e.phase==="tool"?"Tool":e.phase==="approval"?"Awaiting approval":e.phase==="thinking"?"Thinking":e.phase==="done"?"Done":e.phase==="failed"?"Failed":e.phase==="interrupted"?"Interrupted":e.status==="queued"?"Waiting":""}styleDelegationSegment(e,n,s){return e==="running"?s==="status"?be(n):n:e==="queued"||e==="interrupted"?x(n):n}quickActionBarLine(e){let n=this.renderCols(),s=x(this.quickActionView==="rewriteCustom"?"Enter confirm \xB7 Esc back":"\u2191/\u2193 navigate \xB7 Enter confirm \xB7 Esc cancel"),r=se(s).length;if(this.quickActionInlineHint){let c=Math.max(1,n-r-2),u=x(this.clip(this.quickActionInlineHint,c)),p=se(u).length,f=Math.max(1,n-p-r);return d.moveTo(e,1)+d.eraseLine()+` ${u}${" ".repeat(f)}${s}`}let o=Math.max(1,n-r-2),i="";if(this.quickActionView==="main"){let c=this.QUICK_ACTIONS.map((u,p)=>{let f=`[${u}]`;return p===this.quickActionSelectedIndex?gt(` ${f} `):x(f)});i=this.clip(c.join(" "),o)}else if(this.quickActionView==="rewrite"){let c=this.QUICK_REWRITE_OPTIONS.map((u,p)=>{let f=`[${u}]`;return p===this.quickRewriteSelectedIndex?gt(` ${f} `):x(f)});i=this.clip(c.join(" "),o)}else{let c=this.quickRewriteCustomInput.length>0?this.quickRewriteCustomInput:"type style...",u=this.clip(`[CUSTOM] write as: ${c}`,o);i=this.quickRewriteCustomInput.length>0?u:x(u)}let a=se(i).length,l=Math.max(1,n-a-r);return d.moveTo(e,1)+d.eraseLine()+` ${i}${" ".repeat(l)}${s}`}applyQuickFixTypo(){let e=this.opts.onFixTypo;if(!e||this.quickActionPending){this.quickActionBarOpen=!1,this.quickActionView="main",this.quickRewriteSelectedIndex=0,this.quickRewriteCustomInput="",this.quickActionInlineHint=null,this.drawInputBox(),this.refreshFooterFocusCursor();return}let n=this.inputBuffer;this.quickActionPending=!0,this.quickActionInlineHint="fixing typo...",this.drawInputBox(),this.refreshFooterFocusCursor(),Promise.resolve().then(()=>e(n)).then(s=>{if(s.trim().length===0)throw new Error("empty response");s!==n&&this.pushQuickActionUndoSnapshot(n),this.inputBuffer=s,this.cursorPos=this.inputBuffer.length,this.inputScrollOffset=0,this.inputLineScrollOffset=0,this.quickActionBarOpen=!1,this.quickActionView="main",this.quickRewriteSelectedIndex=0,this.quickRewriteCustomInput="",this.quickActionInlineHint=null}).catch(()=>{this.quickActionInlineHint="failed to fix typo"}).finally(()=>{this.quickActionPending=!1,this.drawInputBox(),this.refreshFooterFocusCursor()})}applyQuickRewriteAs(e,n){let s=this.opts.onRewriteAs;if(!s||this.quickActionPending){this.quickActionBarOpen=!1,this.quickActionView="main",this.quickRewriteSelectedIndex=0,this.quickRewriteCustomInput="",this.quickActionInlineHint=null,this.drawInputBox(),this.refreshFooterFocusCursor();return}let r=this.inputBuffer;this.quickActionPending=!0;let o=e==="CUSTOM"&&n?`rewriting as ${n.trim()}...`:`rewriting as ${e.toLowerCase()}...`;this.quickActionInlineHint=o,this.drawInputBox(),this.refreshFooterFocusCursor(),Promise.resolve().then(()=>s(r,e,n)).then(i=>{if(i.trim().length===0)throw new Error("empty response");i!==r&&this.pushQuickActionUndoSnapshot(r),this.inputBuffer=i,this.cursorPos=this.inputBuffer.length,this.inputScrollOffset=0,this.inputLineScrollOffset=0,this.quickActionBarOpen=!1,this.quickActionView="main",this.quickRewriteSelectedIndex=0,this.quickRewriteCustomInput="",this.quickActionInlineHint=null}).catch(()=>{this.quickActionInlineHint="failed to rewrite"}).finally(()=>{this.quickActionPending=!1,this.drawInputBox(),this.refreshFooterFocusCursor()})}pushQuickActionUndoSnapshot(e){this.quickActionUndoStack.push(e),this.quickActionUndoStack.length>this.QUICK_ACTION_UNDO_LIMIT&&this.quickActionUndoStack.shift()}restoreQuickActionUndoSnapshot(){if(this.quickActionUndoStack.length===0)return!1;let e=this.quickActionUndoStack.pop();return e===void 0?!1:(this.inputBuffer=e,this.cursorPos=this.inputBuffer.length,this.inputScrollOffset=0,this.inputLineScrollOffset=0,this.quickActionInlineHint=null,this.closeAutocomplete(),this.drawInputBox(),this.refreshFooterFocusCursor(),!0)}redrawBusyActivityRow(){if(this.resizeInProgress||!this._busy||this.hasOverlayOpen())return;if(this.delegationViewState){this.drawInputBox(),this.refreshFooterFocusCursor();return}let e=this.rows-this.getNormalFooterRows()+1,n=d.hideCursor()+d.disableWrap();n+=this.busyActivityLine(e),this.shouldShowInputCursor()&&(n+=this.inputCursorPosition(),n+=d.showCursor()),n+=d.enableWrap(),process.stdout.write(n)}prompt(e){return new Promise(n=>{this.isPrompting=!0,this.promptQuestion=e,this.promptResolve=n,this.inputBuffer="",this.cursorPos=0,this.inputScrollOffset=0,this.inputLineScrollOffset=0,this.drawInputBox(),this.positionInputCursor(),process.stdout.write(d.showCursor())})}permissionPrompt(e){return new Promise(n=>{let s=this.getDelegationRoleFromLabel(e.requesterLabel);if(s&&this.delegationViewState){let i=this.delegationViewState.agents.find(a=>a.role===s);i&&(i.phase="approval",i.status="running",i.activity=`Waiting for ${e.toolName} permission`)}let r;if(e.directory)r=`Yes, always allow in ${qe.bold(e.directory)}`;else{let i=process.cwd(),a=e.commandPrefix||e.toolName;r=`Yes, and don't ask again for ${qe.bold(a)} commands in ${i}`}this.permissionState={info:e,selectedIndex:0,options:[{label:"Yes",value:"allow"},{label:r,value:"always"},{label:"No",value:"deny"}],resolve:n};let o=this.getPermissionRows(e);this.outputBottom=Math.max(this.rows-o,1),process.stdout.write(d.setScrollRegion(1,this.outputBottom)),this.drawPermissionUI()})}modelPicker(e){return new Promise(n=>{let s=e.options.findIndex(i=>i.value===e.currentValue),r=e.options.length===0?-1:Math.max(0,s);this.modelPickerState={title:e.title,searchPlaceholder:e.description||"Search models...",options:e.options,selectedIndex:r,scrollOffset:0,currentValue:e.currentValue||"",query:"",searchFocused:!1,resolve:n};let o=this.getModelPickerRows();this.outputBottom=Math.max(this.rows-o,1),process.stdout.write(d.setScrollRegion(1,this.outputBottom)),this.drawModelPickerUI()})}sessionPicker(e){return new Promise(n=>{let s=e.options.findIndex(i=>i.value===e.currentValue),r=e.options.length===0?-1:Math.max(0,s);this.sessionPickerState={title:e.title,searchPlaceholder:e.description||"Search sessions...",options:e.options,selectedIndex:r,scrollOffset:0,query:"",searchFocused:!1,confirmLabel:e.confirmLabel||"Enter to confirm",resolve:n};let o=this.getSessionPickerRows();this.outputBottom=Math.max(this.rows-o,1),process.stdout.write(d.setScrollRegion(1,this.outputBottom)),this.drawSessionPickerUI()})}sessionMultiPicker(e){return new Promise(n=>{this.sessionMultiPickerState={title:e.title,searchPlaceholder:e.description||"Search sessions...",options:e.options,selectedIndex:e.options.length===0?-1:0,scrollOffset:0,query:"",searchFocused:!1,confirmLabel:e.confirmLabel||"Enter to confirm",selectedValues:new Set(e.selectedValues??[]),resolve:n};let s=this.getSessionMultiPickerRows();this.outputBottom=Math.max(this.rows-s,1),process.stdout.write(d.setScrollRegion(1,this.outputBottom)),this.drawSessionMultiPickerUI()})}actionPicker(e){return new Promise(n=>{this.actionPickerState={title:e.title,description:e.description,options:e.options,selectedIndex:Math.max(0,Math.min(e.selectedIndex??0,Math.max(0,e.options.length-1))),resolve:n};let s=this.getActionPickerRows();this.outputBottom=Math.max(this.rows-s,1),process.stdout.write(d.setScrollRegion(1,this.outputBottom)),this.drawActionPickerUI()})}helpPanel(){return new Promise(e=>{this.helpPanelState={activeTab:"general",commandSelectedIndex:0,commandScrollOffset:0,resolve:e};let n=this.getHelpPanelRows();this.outputBottom=Math.max(this.rows-n,1),process.stdout.write(d.setScrollRegion(1,this.outputBottom)),this.drawHelpPanelUI()})}infoPanel(e){return new Promise(n=>{let s=e.layout??"footer";this.infoPanelState={title:e.title,subtitle:e.subtitle,lines:e.lines,footerHint:e.footerHint||(s==="viewport"?"\u2190/\u2192 focus \xB7 \u2191/\u2193 navigate or scroll \xB7 PgUp/PgDn page \xB7 Enter close \xB7 Esc close":"\u2191/\u2193 navigate \xB7 Enter close \xB7 Esc close"),layout:s,singlePane:!!e.singlePane,cards:e.cards??[],sections:e.sections??[],split:e.split,selectedSectionIndex:0,focusPane:e.focusPane??"sections",scrollOffset:0,secondaryScrollOffset:0,notice:void 0,assistant:e.assistant?{placeholder:e.assistant.placeholder??"Ask XENO to edit this file...",messages:e.assistant.history?.slice()??[],inputBuffer:"",cursorPos:0,submitting:!1,error:void 0,onSubmit:e.assistant.onSubmit}:void 0,draft:null,editing:null,resolve:n};let r=this.getInfoPanelRows();this.outputBottom=Math.max(this.rows-r,1),process.stdout.write(d.setScrollRegion(1,this.outputBottom)),this.drawInfoPanelUI()})}clear(){let e="";for(let n=1;n<=this.outputBottom;n++)e+=d.moveTo(n,1)+d.eraseLine();process.stdout.write(e),this.outputHistory="",this.outputBlocks=[],this.outputFocusIndex=-1,this.outputViewportTopLine=0,this.outputViewportManualScroll=!1,this.setMouseReportingEnabled(!1),this.outputActionState=null,this.outputRow=1,this.outputCol=1}cleanup(){if(this.cleaned)return;this.cleaned=!0,this.stopSpinner(),this.stopBusyActivityTicker(),this.resizeDebounceTimer&&(clearTimeout(this.resizeDebounceTimer),this.resizeDebounceTimer=null),this.inputHealthTimer&&(clearInterval(this.inputHealthTimer),this.inputHealthTimer=null),this.statusRightHintTimer&&(clearTimeout(this.statusRightHintTimer),this.statusRightHintTimer=null),this.delegationCompletionState?.timer&&(clearTimeout(this.delegationCompletionState.timer),this.delegationCompletionState.timer=null),this.transientActivityNotice?.timer&&(clearTimeout(this.transientActivityNotice.timer),this.transientActivityNotice.timer=null);let e=process.stdout;this.setMouseReportingEnabled(!1),e.write(d.resetScrollRegion()),e.write(d.showCursor()),e.write(d.moveTo(this.rows,1)),e.write(`
|
|
89
|
+
`),process.stdin.isTTY&&process.stdin.isRaw&&process.stdin.setRawMode(!1),process.stdin.removeListener("data",this.handleStdinData),process.stdout.removeListener("resize",this.handleStdoutResize),process.removeListener("exit",this.handleProcessExit)}calculateLayout(){this.rows=process.stdout.rows||24,this.cols=process.stdout.columns||80,this.outputBottom=Math.max(this.rows-this.getNormalFooterRows(),1),this.outputRow=Math.max(1,Math.min(this.outputRow,this.outputBottom)),this.outputCol=Math.max(1,Math.min(this.outputCol,this.cols))}getInputLines(){return this.inputBuffer.length===0?[""]:this.inputBuffer.split(`
|
|
90
|
+
`)}armInterruptRewind(e=this.INTERRUPT_REWIND_WINDOW_MS,n){this.interruptRewindArmed=!0,this.interruptRewindLastEscAt=0,this.interruptRewindWindowMs=e,n?.openIfRequested&&this.maybeOpenPendingInterruptRewind()}wrapOutputForTerminal(e,n=this.outputCol){let s=this.renderCols();if(s<=1)return e;let r=Math.max(1,Math.min(n,s)),o="",i=0,a=()=>{if(e[i]!=="\x1B")return null;let p=i;for(i++;i<e.length;){let f=e[i++];if(/[A-Za-z]/.test(f))break}return e.slice(p,i)},l=()=>{let p=i;for(;i<e.length&&/[ \t]/.test(e[i]);)i++;return e.slice(p,i)},c=()=>{let p="",f=0;for(;i<e.length;){let m=a();if(m){p+=m;continue}let g=e[i];if(g===`
|
|
91
|
+
`||g==="\r"||/[ \t]/.test(g))break;p+=g,f++,i++}return{text:p,width:f}},u=p=>{let f="",m=!1;for(let g of p){if(m){f+=g,/[A-Za-z]/.test(g)&&(o+=f,f="",m=!1);continue}if(g==="\x1B"){f=g,m=!0;continue}r>s&&(o+=`
|
|
92
|
+
`,r=1),o+=g,r++}f&&(o+=f)};for(;i<e.length;){let p=a();if(p){o+=p;continue}let f=e[i];if(f===`
|
|
93
|
+
`){o+=f,r=1,i++;continue}if(f==="\r"){o+=f,r=1,i++;continue}if(/[ \t]/.test(f)){let g=l();(r===1||r+g.length-1<=s)&&(o+=g,r+=g.length);continue}let m=c();m.width!==0&&(m.width<=s&&r>1&&r+m.width-1>s&&(o=o.replace(/[ \t]+$/,""),o+=`
|
|
94
|
+
`,r=1),u(m.text))}return o}getOutputEndColumn(e,n){let s=this.renderCols(),r=Math.max(1,Math.min(n,s)),o=se(e);for(let i of o){if(i===`
|
|
95
|
+
`||i==="\r"){r=1;continue}r++,r>s+1&&(r=2)}return Math.max(1,Math.min(r,s))}maybeOpenPendingInterruptRewind(){!this.openRewindAfterInterrupt||!this.interruptRewindArmed||this._busy||(this.openRewindAfterInterrupt=!1,this.interruptRewindLastEscAt=0,setTimeout(()=>{!this.interruptRewindArmed||this._busy||this.invokeSafeAction("rewind request",()=>this.opts.onOpenRewind?.())},0))}setInputText(e,n){this.inputBuffer=e,this.cursorPos=n?.cursor==="start"?0:e.length,this.escCancelableInputDraft=!!n?.escCancelable,this.clearPastedTextBlocks(),this.inputScrollOffset=0,this.inputLineScrollOffset=0,this.drawInputBox(),this.positionInputCursor()}normalizePastedText(e){return e.replace(/\r\n/g,`
|
|
96
|
+
`).replace(/\r/g,`
|
|
97
|
+
`)}countLines(e){return e.length===0?1:e.split(`
|
|
98
|
+
`).length}shouldCollapsePastedText(e){return this.countLines(e)>=this.COLLAPSE_PASTE_MIN_LINES}createPastedTextLabel(e){this.pastedTextCounter+=1;let n=Math.max(0,this.countLines(e)-1),s=`[Pasted text #${this.pastedTextCounter} +${n} lines]`;return this.pastedTextBlocks.set(s,e),s}expandPastedTextLabels(e){let n=e,s=this.pastedTextBlocks??new Map;for(let[r,o]of s.entries())n.includes(r)&&(n=n.split(r).join(o));return n}clearPastedTextBlocks(){this.pastedTextBlocks?.clear()}MAX_INPUT_BUFFER_SIZE=100*1024;insertIntoInputBuffer(e){if(e.length===0)return;if(this.inputBuffer.length+e.length>this.MAX_INPUT_BUFFER_SIZE){let s=Math.max(0,this.MAX_INPUT_BUFFER_SIZE-this.inputBuffer.length);if(s===0)return;e=e.slice(0,s)}this.quickActionInlineHint=null,this.inputBuffer=this.inputBuffer.slice(0,this.cursorPos)+e+this.inputBuffer.slice(this.cursorPos),this.cursorPos+=e.length,this.autocompleteSelectedIndex=0,this.drawInputBox(),this.positionInputCursor()}handlePastedText(e){if(e.length<=1||!e.includes(`
|
|
99
|
+
`)&&!e.includes("\r"))return!1;let n=this.normalizePastedText(e),s=this.shouldCollapsePastedText(n)?this.createPastedTextLabel(n):n;return this.insertIntoInputBuffer(s),!0}getCursorLineAndColumn(){let e=Math.max(0,Math.min(this.cursorPos,this.inputBuffer.length)),s=this.inputBuffer.slice(0,e).split(`
|
|
100
|
+
`);return{line:Math.max(0,s.length-1),column:s[s.length-1]?.length??0}}getInputRowCapacity(){let e=this.isStatusBarVisible()?1:0,n=Math.max(1,this.rows-this.NORMAL_FOOTER_OVERHEAD_ROWS-e-1);return Math.max(1,Math.min(this.MAX_INPUT_ROWS,n))}getNormalInputRows(){if(this.isPrompting)return 1;let e=this.getInputLines().length;return Math.max(1,Math.min(e,this.getInputRowCapacity()))}getDelegationPanelRows(){return this.delegationViewState?this.shouldUseDelegationLogDock()?4:5:0}shouldUseDelegationLogDock(){return!1}getDelegationLogDockBounds(){if(!this.shouldUseDelegationLogDock()||!this.delegationViewState||this.hasOverlayOpen())return null;let e=this.delegationLogDockExpanded?Math.max(32,Math.min(44,Math.floor(this.cols*.34))):Math.max(24,Math.min(30,Math.floor(this.cols*.24))),n=this.delegationLogDockExpanded?Math.max(7,Math.min(12,this.outputBottom-3)):Math.max(6,Math.min(9,this.outputBottom-3)),s=n+1,r=Math.max(1,Math.floor((this.outputBottom-s)/2)+1),o=Math.max(1,this.cols-e+1);return{top:r,left:o,width:e,height:n,hintRow:r+n}}toggleDelegationLogDockExpanded(){!this.shouldUseDelegationLogDock()||!this.delegationViewState||this.hasOverlayOpen()||(this.delegationLogDockExpanded=!this.delegationLogDockExpanded,this.resizeInProgress||this.redrawScreenFromHistory(),this.redrawDelegationFooter())}drawDelegationLogDock(){let e=this.getDelegationLogDockBounds();if(!e||!this.delegationViewState)return;let n=this.buildDelegationLogDockLines(this.delegationViewState,e.width,e.height),s=d.hideCursor()+d.disableWrap();for(let r=0;r<e.height;r++){let o=e.top+r,i=n[r]??" ".repeat(e.width);s+=d.moveTo(o,e.left),s+=i}e.hintRow<=this.outputBottom&&(s+=d.moveTo(e.hintRow,e.left),s+=this.buildDelegationLogDockHintLine(e.width)),this.shouldShowInputCursor()?(s+=this.inputCursorPosition(),s+=d.showCursor()):s+=d.hideCursor(),s+=d.enableWrap(),process.stdout.write(s)}scrollDelegationLogDock(e){if(!this.delegationViewState||!this.delegationLogDockExpanded||this.hasOverlayOpen())return;let n=this.getDelegationLogDockVisibleLines(),s=Math.max(0,this.delegationViewState.events.length-n);this.delegationLogDockScrollOffset=Math.max(0,Math.min(s,this.delegationLogDockScrollOffset+e)),this.redrawDelegationFooter()}jumpDelegationLogDock(e){if(!this.delegationViewState||!this.delegationLogDockExpanded||this.hasOverlayOpen())return;let n=this.getDelegationLogDockVisibleLines(),s=Math.max(0,this.delegationViewState.events.length-n);this.delegationLogDockScrollOffset=e==="start"?0:s,this.redrawDelegationFooter()}buildDelegationInspectorSections(){if(!this.delegationViewState)return[{id:"overview",title:"Overview",summary:"inactive",lines:["Delegation is not active."]}];let e=this.formatElapsed(Date.now()-this.delegationViewState.startedAt),n=[`Started: ${new Date(this.delegationViewState.startedAt).toLocaleTimeString()}`,`Elapsed: ${e}`,`Agents: ${this.delegationViewState.agents.length}`,`Events: ${this.delegationViewState.events.length}`],s=[{id:"overview",title:"Overview",summary:`${this.delegationViewState.agents.length} agents`,lines:n}];for(let r of this.delegationViewState.agents)s.push({id:r.role,title:r.role[0].toUpperCase()+r.role.slice(1),summary:`${this.delegationStatusLabel(r.status)} \xB7 ${An(r.tokenCount)} tok`,lines:[`Status: ${this.delegationStatusLabel(r.status)}`,`Phase: ${this.delegationPhaseLabel(r)||"Waiting"}`,`Activity: ${r.activity||"Waiting"}`,`Current tool: ${r.currentTool??"-"}`,`Tool calls: ${r.toolCount}`,`Tokens: ${An(r.tokenCount)}`,`Output preview: ${r.outputPreview??"-"}`]});return s.push({id:"activity",title:"Activity Log",summary:`${this.delegationViewState.events.length} events`,lines:this.buildDelegationLogBodyLines(this.delegationViewState.events,Math.max(this.delegationViewState.events.length,1),!0,0)}),s}getDelegationAgentByRole(e){return!this.delegationViewState||!e?null:this.delegationViewState.agents.find(n=>n.role===e)??null}buildDelegationAgentDetailContent(e){let n=this.getDelegationAgentByRole(e),s=e?`${e[0].toUpperCase()}${e.slice(1)}`:"Agent",r=this.delegationViewState?this.formatElapsed(Date.now()-this.delegationViewState.startedAt):"0m 00s";return n?{title:`${s} Logs`,subtitle:`${this.delegationStatusLabel(n.status)} \xB7 ${r}`,cards:[{title:"Status",value:this.delegationStatusLabel(n.status)},{title:"Phase",value:this.delegationPhaseLabel(n)||"Waiting"},{title:"Tools",value:String(n.toolCount)},{title:"Tokens",value:An(n.tokenCount)}],split:{left:{title:`${s} summary`,lines:[`Role: ${s}`,`Status: ${this.delegationStatusLabel(n.status)}`,`Phase: ${this.delegationPhaseLabel(n)||"Waiting"}`,`Current activity: ${n.activity||"Waiting"}`,`Current tool: ${n.currentTool??"-"}`,`Tool calls: ${n.toolCount}`,`Tokens: ${An(n.tokenCount)}`,`Output preview: ${n.outputPreview??"-"}`]},right:{title:`${s} live log`,lines:this.buildDelegationLogBodyLines(n.events,Math.max(n.events.length,1),!0,0)}}}:{title:`${s} Logs`,subtitle:"Delegation inactive",cards:[],split:{left:{title:`${s} summary`,lines:["Delegation is not active."]},right:{title:`${s} live log`,lines:["No branch activity available."]}}}}updateDelegationAgentDetailState(){if(this.infoPanelState?.source!=="delegation-agent-detail")return;let e=this.infoPanelState,n=this.buildDelegationAgentDetailContent(e.delegationAgentRole);e.title=n.title,e.subtitle=n.subtitle,e.cards=n.cards,e.split=n.split,e.footerHint="\u2190/\u2192 focus \xB7 \u2191/\u2193 scroll \xB7 PgUp/PgDn page \xB7 Home/End jump \xB7 Esc close"}updateDelegationInspectorState(){if(this.infoPanelState?.source!=="delegation-inspector")return;let e=this.buildDelegationInspectorSections(),n=this.infoPanelState;n.title="Delegation Inspector",n.subtitle=this.delegationViewState?`${this.delegationViewState.agents.length} agents \xB7 ${this.formatElapsed(Date.now()-this.delegationViewState.startedAt)}`:"Delegation inactive",n.cards=this.delegationViewState?[{title:"Agents",value:String(this.delegationViewState.agents.length)},{title:"Events",value:String(this.delegationViewState.events.length)},{title:"Running",value:String(this.delegationViewState.agents.filter(s=>s.status==="running").length)},{title:"Elapsed",value:this.formatElapsed(Date.now()-this.delegationViewState.startedAt)}]:[],n.sections=e,n.selectedSectionIndex=Math.max(0,Math.min(n.selectedSectionIndex,Math.max(0,e.length-1))),n.footerHint="\u2190/\u2192 focus \xB7 \u2191/\u2193 navigate or scroll \xB7 PgUp/PgDn page \xB7 Home/End jump \xB7 Ctrl+L close \xB7 Esc close"}openDelegationInspector(){if(!this.delegationViewState||this.infoPanelState?.source==="delegation-inspector")return;this.infoPanelState={source:"delegation-inspector",title:"Delegation Inspector",subtitle:"",lines:[],footerHint:"",layout:"viewport",singlePane:!1,cards:[],sections:[],selectedSectionIndex:0,focusPane:"sections",scrollOffset:0,secondaryScrollOffset:0,notice:void 0,assistant:void 0,draft:null,editing:null,resolve:()=>{}},this.updateDelegationInspectorState();let e=this.getInfoPanelRows();this.outputBottom=Math.max(this.rows-e,1),process.stdout.write(d.setScrollRegion(1,this.outputBottom)),this.drawInfoPanelUI()}openDelegationAgentDetailPanel(){if(!this.delegationViewState)return;let e=this.delegationViewState.agents[this.delegationFocusIndex];if(!e)return;this.infoPanelState={source:"delegation-agent-detail",delegationAgentRole:e.role,title:"",subtitle:"",lines:[],footerHint:"",layout:"footer",singlePane:!1,cards:[],sections:[],split:void 0,selectedSectionIndex:0,focusPane:"content",scrollOffset:0,secondaryScrollOffset:0,notice:void 0,assistant:void 0,draft:null,editing:null,resolve:()=>{}},this.updateDelegationAgentDetailState();let n=this.getInfoPanelRows();this.outputBottom=Math.max(this.rows-n,1),process.stdout.write(d.setScrollRegion(1,this.outputBottom)),this.drawInfoPanelUI()}getNormalFooterRows(){let e=this.getDelegationPanelRows(),n=e>0?e:0,s=this.isStatusBarVisible()?1:0;return this.NORMAL_FOOTER_OVERHEAD_ROWS+this.getNormalInputRows()+n+s}getNormalInputStartRow(){let e=this.getNormalFooterRows();return this.rows-e+4}getStatusRow(){return this.rows-1}isStatusBarVisible(){return!(!this.SHOW_STATUS_BAR||this.delegationViewState||this.autocompleteVisible&&this.autocompleteMatches.length>0)}initScreen(){let e=process.stdout;e.write(d.clearScreen());let n="";for(let s=1;s<=this.rows;s++)n+=d.moveTo(s,1)+d.eraseLine();e.write(n),e.write(d.setScrollRegion(1,this.outputBottom)),e.write(d.moveTo(1,1)),this.outputRow=1,this.outputCol=1,this.drawInputBox(),this.positionInputCursor(),e.write(d.showCursor())}setupRawMode(){process.stdin.isTTY&&(this.attachChatInput("setupRawMode",{clearExistingListeners:!0}),this.inputHealthTimer=setInterval(()=>{this.ensureChatInputAttached()},1e3),this.inputHealthTimer.unref?.())}attachChatInput(e,n={}){if(process.stdin.isTTY){if(Bt(`screen:attach:${e}`,{listenerCountBefore:process.stdin.listenerCount("data"),hasScreenListenerBefore:process.stdin.listeners("data").includes(this.handleStdinData),isRawBefore:process.stdin.isRaw,readableFlowingBefore:process.stdin.readableFlowing,clearExistingListeners:n.clearExistingListeners===!0}),n.clearExistingListeners)process.stdin.removeAllListeners("data");else for(;process.stdin.listeners("data").includes(this.handleStdinData);)process.stdin.removeListener("data",this.handleStdinData);process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.read(0),process.stdin.setEncoding("utf8"),process.stdin.on("data",this.handleStdinData),this.inputAttachedAt=Date.now(),Bt(`screen:attach:${e}:done`,{listenerCountAfter:process.stdin.listenerCount("data"),hasScreenListenerAfter:process.stdin.listeners("data").includes(this.handleStdinData),isRawAfter:process.stdin.isRaw,readableFlowingAfter:process.stdin.readableFlowing})}}ensureChatInputAttached(){if(this.cleaned||!process.stdin.isTTY)return;let e=process.stdin.listeners("data").includes(this.handleStdinData),n=!e||process.stdin.isRaw!==!0||process.stdin.readableFlowing!==!0;this.inputHealthTick++;let s=this.inputAttachedAt>0?Date.now()-this.inputAttachedAt:0,r=this.lastInputEventAt>=this.inputAttachedAt,o=process.platform==="win32"&&!n&&!r&&s>1500&&s<3e4&&this.inputHealthTick%2===0;if(process.env.XENO_DEBUG_INPUT==="1"&&(n||o||this.inputHealthTick%5===0)&&Bt("screen:health",{tick:this.inputHealthTick,listenerCount:process.stdin.listenerCount("data"),hasScreenListener:e,isRaw:process.stdin.isRaw,readableFlowing:process.stdin.readableFlowing,needsRepair:n,shouldNudgeWindowsStdin:o,msSinceAttach:s,sawInputSinceAttach:r}),n){this.attachChatInput("healthcheck",{clearExistingListeners:!e}),this.hasOverlayOpen()||(this.drawInputBox(),this.positionInputCursor());return}o&&(process.stdin.pause(),process.stdin.resume(),process.stdin.read(0))}setupResize(){process.stdout.on("resize",this.handleStdoutResize)}redrawScreenFromHistory(){this.syncRenderedOutputHistory();let e=d.hideCursor()+d.disableWrap();e+=d.clearScreen();for(let s=1;s<=this.rows;s++)e+=d.moveTo(s,1)+d.eraseLine();if(e+=d.setScrollRegion(1,this.outputBottom),e+=d.moveTo(1,1),this.footerFocus==="output"&&this.outputFocusIndex>=0){let s=this.getFocusedOutputViewportText();s&&(e+=s)}else this.outputHistory.length>0&&(e+=this.outputHistory);e+=d.enableWrap(),process.stdout.write(e),this.outputRow=1,this.outputCol=1;let n=this.footerFocus==="output"&&this.outputFocusIndex>=0?this.getFocusedOutputViewportText()??"":this.outputHistory;n.length>0&&this.advanceOutputPosition(n)}handleResizeRedraw(){try{this.calculateLayout(),this.permissionState?this.outputBottom=Math.max(this.rows-this.getPermissionRows(this.permissionState.info),1):this.modelPickerState?this.outputBottom=Math.max(this.rows-this.getModelPickerRows(),1):this.sessionMultiPickerState?this.outputBottom=Math.max(this.rows-this.getSessionMultiPickerRows(),1):this.sessionPickerState?this.outputBottom=Math.max(this.rows-this.getSessionPickerRows(),1):this.helpPanelState?this.outputBottom=Math.max(this.rows-this.getHelpPanelRows(),1):this.infoPanelState&&(this.outputBottom=Math.max(this.rows-this.getInfoPanelRows(),1)),this.redrawScreenFromHistory(),this.permissionState?this.drawPermissionUI():this.modelPickerState?this.drawModelPickerUI():this.actionPickerState?this.drawActionPickerUI():this.sessionMultiPickerState?this.drawSessionMultiPickerUI():this.sessionPickerState?this.drawSessionPickerUI():this.helpPanelState?this.drawHelpPanelUI():this.infoPanelState?this.drawInfoPanelUI():(this.drawInputBox(),this.refreshFooterFocusCursor())}finally{this.resizeInProgress=!1}}setupCleanup(){process.on("exit",this.handleProcessExit)}advanceOutputPosition(e){let n=se(e);for(let s of n)s===`
|
|
101
|
+
`?(this.outputRow++,this.outputCol=1):s==="\r"?this.outputCol=1:(this.outputCol++,this.outputCol>this.cols&&(this.outputCol=1,this.outputRow++)),this.outputRow>this.outputBottom&&(this.outputRow=this.outputBottom)}clearFooterZone(e){let n="",s=this.rows-e+1;for(let r=s;r<=this.rows;r++)n+=d.moveTo(r,1)+d.eraseLine();return n}renderCols(){return Math.max(1,this.cols-1)}drawInputBox(){!this.isStatusBarVisible()&&this.footerFocus==="status"&&(this.footerFocus="input"),this.updateAutocomplete();let e=this.autocompleteVisible&&this.autocompleteMatches.length>0,n=e?this.MAX_FOOTER_HEIGHT:this.getNormalFooterRows(),s=this.lastFooterRows,r=Math.max(this.rows-n,1);r!==this.outputBottom&&(this.outputBottom=r,this.outputRow=Math.max(1,Math.min(this.outputRow,this.outputBottom)),process.stdout.write(d.setScrollRegion(1,this.outputBottom))),e?this.drawInputBoxWithAutocomplete(Math.max(s,n)):this.drawInputBoxNormal(Math.max(s,n)),!e&&this.shouldUseDelegationLogDock()&&!this.hasOverlayOpen()&&this.drawDelegationLogDock(),e||this.drawStatusBar(),this.wasAutocompleteVisible=e,this.lastFooterRows=n}drawInputBoxNormal(e){let n=this.getNormalInputRows(),s=this.getNormalFooterRows(),r=this.rows-s+1,o=this.hasOverlayOpen()?0:this.getDelegationPanelRows(),i=r+1,a=i+1,l=a+1,c=l+n,u=c+1,p=this.isStatusBarVisible()?this.rows:u+o,f=this.renderCols(),m=d.hideCursor()+d.disableWrap();m+=this.clearFooterZone(e);let g=!0;if(this._busy&&!this.hasOverlayOpen()){if(m+=this.busyActivityLine(r),this._queuedMessage){let P=this._queuedMessage.length>Math.max(1,f-8)?this._queuedMessage.slice(0,Math.max(1,f-11))+"...":this._queuedMessage;m+=d.moveTo(i,1)+d.eraseLine(),m+=` ${x("\u25AA Queued \u21B3")} ${x(P)} ${x("(esc to send now)")}`,g=!1}}else if(this.transientActivityNotice&&!this.hasOverlayOpen()){let P=this.clip(this.transientActivityNotice.text,Math.max(1,f-2));m+=d.moveTo(r,1),m+=d.eraseLine(),m+=d.moveTo(i,1),m+=d.eraseLine(),m+=` ${x(P)}`,g=!1}else if(this.delegationCompletionState&&!this.hasOverlayOpen()){let P=this.clip(this.delegationCompletionState.text,Math.max(1,f-4));m+=d.moveTo(r,1),m+=d.eraseLine(),m+=d.moveTo(i,1),m+=d.eraseLine(),m+=` ${x("\u25E6")} ${x(P)}`,g=!1}else this.quickActionBarOpen&&!this.hasOverlayOpen()&&o===0?(m+=d.moveTo(r,1),m+=d.eraseLine(),m+=this.quickActionBarLine(i)):this.quickActionBarOpen&&!this.hasOverlayOpen()?(m+=d.moveTo(r,1),m+=d.eraseLine()):(m+=d.moveTo(r,1),m+=d.eraseLine());if(o>0&&this.delegationViewState){let P=this.buildDelegationFooterLines(this.delegationViewState,f);for(let C=0;C<o;C++){let $=u+C;m+=d.moveTo($,1)+d.eraseLine();let E=P[C];E&&(m+=E)}}else(!this.quickActionBarOpen||this.hasOverlayOpen())&&g&&(m+=d.moveTo(i,1),m+=d.eraseLine());m+=d.moveTo(a,1),m+=d.eraseLine(),m+=x("\u2500".repeat(f));let b=this.clip(this.opts.permissionMode,Math.max(1,Math.min(20,Math.floor(this.cols*.25)))),v=x(b),w=se(v).length;if(this.isPrompting){m+=d.moveTo(l,1),m+=d.eraseLine();let P=`${qe.yellow("\u26A0")} ${this.promptQuestion} `;m+=this.clip(P+this.inputBuffer,f)}else if(this.inputBuffer.length===0){m+=d.moveTo(l,1),m+=d.eraseLine();let P=Math.max(1,f-w-3),C=this._promptSuggestion?`${be("\u203A")} ${x(this.clip(this._promptSuggestion,P))} ${x("Tab to accept")}`:`${be("\u203A")} ${x(this.clip("Message or /command...",P))}`,$=se(C).length,E=Math.max(1,f-$-w);m+=C+" ".repeat(E)+v,this.inputScrollOffset=0,this.inputLineScrollOffset=0}else{let P=this.getInputLines(),{line:C,column:$}=this.getCursorLineAndColumn();C<this.inputLineScrollOffset?this.inputLineScrollOffset=C:C>=this.inputLineScrollOffset+n&&(this.inputLineScrollOffset=C-n+1);let E=Math.max(0,P.length-n);this.inputLineScrollOffset=Math.max(0,Math.min(this.inputLineScrollOffset,E));for(let T=0;T<n;T++){let I=l+T,re=this.inputLineScrollOffset+T,ae=P[re]??"",N=T===0,y=re===C,oe=N?`${be("\u203A")} `:" ",K=se(oe).length,W=N?v:"",Z=N?w:0,le=Math.max(1,f-K-(Z>0?Z+1:0));y&&($-this.inputScrollOffset>=le?this.inputScrollOffset=$-le+1:$<this.inputScrollOffset&&(this.inputScrollOffset=$));let ce=y?this.inputScrollOffset:0,X=ae.slice(ce,ce+le),q=`${oe}${X}`,Q=se(q).length,ye=Math.max(1,f-Q-Z);m+=d.moveTo(I,1),m+=d.eraseLine(),Z>0?m+=q+" ".repeat(ye)+W:m+=q}}m+=d.moveTo(c,1),m+=d.eraseLine(),m+=x("\u2500".repeat(f)),m+=d.moveTo(p,1),m+=d.eraseLine(),this.shouldShowInputCursor()?(m+=this.inputCursorPosition(),m+=d.showCursor()):m+=d.hideCursor(),m+=d.enableWrap(),process.stdout.write(m)}drawInputBoxWithAutocomplete(e){let r=this.rows-9+1,o=r+1,i=o+1,a=i+1,l=this.renderCols(),c=d.hideCursor()+d.disableWrap();c+=this.clearFooterZone(e),c+=d.moveTo(r,1),c+=d.eraseLine(),c+=x("\u2500".repeat(l)),c+=d.moveTo(o,1),c+=d.eraseLine();let p=Math.max(1,l-2-1);this.cursorPos-this.inputScrollOffset>=p?this.inputScrollOffset=this.cursorPos-p+1:this.cursorPos<this.inputScrollOffset&&(this.inputScrollOffset=this.cursorPos);let f=this.inputBuffer.slice(this.inputScrollOffset,this.inputScrollOffset+p);c+=`${be("\u203A")} ${f}`,c+=d.moveTo(i,1),c+=d.eraseLine(),c+=x("\u2500".repeat(l));let m=3,g=this.autocompleteMatches.length,b=this.autocompleteSelectedIndex-m,v=Math.max(0,g-6);this.autocompleteScrollOffset=Math.max(0,Math.min(b,v));for(let w=0;w<6;w++){let P=a+w;c+=d.moveTo(P,1),c+=d.eraseLine();let C=this.autocompleteScrollOffset+w;if(C<this.autocompleteMatches.length){let $=this.autocompleteMatches[C],E=C===this.autocompleteSelectedIndex,T=$.name.padEnd(30),I=this.clip(`${T}${$.description}`,Math.max(1,l-2));E?c+=` ${be(I)}`:c+=` ${x(I)}`}}this.shouldShowInputCursor()?(c+=this.inputCursorPosition(),c+=d.showCursor()):c+=d.hideCursor(),c+=d.enableWrap(),process.stdout.write(c)}updateAutocomplete(){if(this.inputBuffer.includes(`
|
|
102
|
+
`)||this._busy||this.isPrompting){this.autocompleteVisible=!1,this.autocompleteMatches=[],this.autocompleteSelectedIndex=0,this.autocompleteScrollOffset=0;return}let n=this.inputBuffer.slice(0,this.cursorPos).match(/@([^\s]*)$/);if(n){let o=n[1];this.updateFileAutocomplete(o);return}if(!this.inputBuffer.startsWith("/")){this.autocompleteVisible=!1,this.autocompleteMatches=[],this.autocompleteSelectedIndex=0,this.autocompleteScrollOffset=0;return}let s=this.inputBuffer.toLowerCase(),r=Yn.filter(o=>o.name.toLowerCase().startsWith(s)&&o.name!==this.inputBuffer);r.length===0?(this.autocompleteVisible=!1,this.autocompleteMatches=[],this.autocompleteSelectedIndex=0,this.autocompleteScrollOffset=0):(this.autocompleteVisible=!0,this.autocompleteMatches=r,this.autocompleteSelectedIndex>=r.length&&(this.autocompleteSelectedIndex=r.length-1),this.autocompleteScrollOffset>this.autocompleteSelectedIndex&&(this.autocompleteScrollOffset=this.autocompleteSelectedIndex))}fileAutocompleteAtToken="";updateFileAutocomplete(e){this.fileAutocompleteAtToken=e;try{let n=e.includes("/")||e.includes("\\")?Ha(process.cwd(),e.replace(/[^/\\]*$/,"")):process.cwd(),s=e.includes("/")||e.includes("\\")?e.replace(/[^/\\]*$/,""):"",r=e.includes("/")||e.includes("\\")?e.replace(/.*[/\\]/,""):e,o;try{o=tm(n).filter(a=>a.toLowerCase().startsWith(r.toLowerCase()))}catch{o=[]}let i=o.slice(0,20).map(a=>{let l=Ha(n,a),c=!1;try{c=nm(l).isDirectory()}catch{}return{name:`@${s+a+(c?"/":"")}`,description:c?"directory":"file"}});i.length===0?(this.autocompleteVisible=!1,this.autocompleteMatches=[],this.autocompleteSelectedIndex=0,this.autocompleteScrollOffset=0):(this.autocompleteVisible=!0,this.autocompleteMatches=i,this.autocompleteSelectedIndex>=i.length&&(this.autocompleteSelectedIndex=i.length-1),this.autocompleteScrollOffset>this.autocompleteSelectedIndex&&(this.autocompleteScrollOffset=this.autocompleteSelectedIndex))}catch{this.autocompleteVisible=!1,this.autocompleteMatches=[]}}completeAutocomplete(){if(!this.autocompleteVisible||this.autocompleteMatches.length===0)return;let e=this.autocompleteMatches[this.autocompleteSelectedIndex];if(e.name.startsWith("@")){let n=this.inputBuffer.slice(0,this.cursorPos),s=this.inputBuffer.slice(this.cursorPos),r=n.match(/@([^\s]*)$/);if(r){let o=this.cursorPos-r[0].length,i=e.name.slice(1),a=e.description==="directory",l=i+(a?"":" ");this.inputBuffer=this.inputBuffer.slice(0,o)+l+s,this.cursorPos=o+l.length}}else this.inputBuffer=e.name+" ",this.cursorPos=this.inputBuffer.length;this.inputScrollOffset=0,this.inputLineScrollOffset=0,this.autocompleteVisible=!1,this.autocompleteMatches=[],this.autocompleteSelectedIndex=0,this.autocompleteScrollOffset=0}closeAutocomplete(){this.autocompleteVisible=!1,this.autocompleteMatches=[],this.autocompleteSelectedIndex=0,this.autocompleteScrollOffset=0}drawStatusBar(){if(!this.isStatusBarVisible()||this.resizeInProgress||this.permissionState||this.modelPickerState||this.actionPickerState||this.sessionMultiPickerState||this.sessionPickerState||this.helpPanelState||this.infoPanelState)return;let e=d.hideCursor()+d.disableWrap();e+=this.statusBarContent(this.getStatusRow()),this.shouldShowInputCursor()&&(e+=this.inputCursorPosition(),e+=d.showCursor()),e+=d.enableWrap(),process.stdout.write(e)}formatStatusPath(e){let n=process.cwd().replace(/\//g,"\\");if(n.length<=e)return n;let s=n.split("\\").filter(Boolean);if(s.length<=2||e<12)return this.clip(n,e);let o=n.match(/^[A-Za-z]:/)?.[0]??"",i=s.slice(-2).join("\\"),l=`${o?`${o}\\...\\`:"...\\"}${i}`;return l.length<=e?l:`...\\${i.slice(Math.max(0,i.length-Math.max(1,e-4)))}`}openWorkspaceFolder(){return new Promise((e,n)=>{let s=process.cwd(),r=process.platform==="win32"?[{command:"cmd.exe",args:["/d","/s","/c","start","","%XENO_OPEN_PATH%"],env:{...process.env,XENO_OPEN_PATH:s},label:"Explorer"},{command:"powershell.exe",args:["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command","Invoke-Item -LiteralPath $env:XENO_OPEN_PATH"],env:{...process.env,XENO_OPEN_PATH:s},label:"Explorer"},{command:"explorer.exe",args:[`/n,${s}`],label:"Explorer"},{command:"explorer.exe",args:[s],label:"Explorer"},{command:"rundll32.exe",args:["url.dll,FileProtocolHandler",s],label:"Explorer"}]:process.platform==="darwin"?[{command:"open",args:[s],label:"Finder"}]:[{command:"xdg-open",args:[s],label:"file manager"}];this.showTransientActivityNotice(`Opening ${s} in ${r[0].label}`),this.writeInfo(`Opening ${s} in ${r[0].label}`);let o=(i,a)=>{let l=r[i];if(!l){n(a instanceof Error?a:new Error("No folder opener succeeded"));return}let c;try{c=em(l.command,l.args,{detached:!0,stdio:"ignore",windowsHide:!0,env:l.env})}catch(p){o(i+1,p);return}let u=!1;c.once("error",p=>{u||(u=!0,o(i+1,p))}),c.once("exit",p=>{u||p!==0&&p!==null&&(u=!0,o(i+1,new Error(`${l.command} exited with ${p}`)))}),c.unref(),setTimeout(()=>{u||(u=!0,e())},250).unref?.()};o(0)})}statusBarContent(e){let n=this.renderCols(),s=this.clip(this.opts.model,Math.max(14,Math.floor(this.cols*.38))),r=this.opts.maxContextTokens||2e5,o=this.opts.executionMode??"agent",a=this.opts.permissionMode==="bypassPermissions"?"Full Access":o==="chatOnly"?"Chat":"Agent",l=rm(this.opts.executionMode,this.opts.permissionMode),c=`${l} ${a}`,u=be(l)+" "+be(a),p=this.footerFocus==="status"&&this.statusFocusIndex===0?gt(c):u,f=`DELEGATE ${this.delegationEnabled?"ON":"OFF"}`,m=this.delegationEnabled?be(f):x(f),g=this.footerFocus==="status"&&this.statusFocusIndex===1?gt(f):m,b=`\u273B ${s}`,v=za("\u273B")+" "+za(s),w=this.footerFocus==="status"&&this.statusFocusIndex===2?gt(b):v,P=Math.max(12,Math.floor(n*.22)),C=this.footerFocus==="status"&&this.statusFocusIndex===3,$=n>=72||C?this.formatStatusPath(P):"",E=$?C?gt($):x($):"",T=An(this.tokensUsed),I=An(r),re=this.costDisplay?` \xB7 ${this.costDisplay}`:"",ae=`${T}/${I}${re}`,N=this.promptContextBreakdown?this.clip(this.promptContextBreakdown,Math.max(12,Math.floor(this.cols*.22))):"",y=N?x(`ctx ${N}`):"",oe=this._busy?" "+qe.yellow("\u25CF"):"",K=this.getBackgroundTaskCount(),W=`\u25A0 ${K} bg`,Z=K>0?this.footerFocus==="status"&&this.statusFocusIndex===5?gt(W):be(W):"",le=x(" | "),X=[p+oe,g,w,...Z?[Z]:[],...E?[E]:[],...y?[y]:[],x(ae)].join(le),q=this.statusRightHint??"/help";if(this.footerFocus==="status"&&this.statusFocusIndex===3)q="Enter open folder";else if(this.footerFocus==="output"&&this.outputFocusIndex>=0){let pe=this.getFocusedOutputBlock(),te=pe?.type==="collapsible";this.outputActionState?.blockIndex===this.outputFocusIndex?q=this.outputActionState.focus==="confirm"?"Enter confirm | Esc close":this.outputActionState.focus==="actions"?"Ctrl+Left/Right action | Enter select | Esc close":"Up/Down navigate | Ctrl+Enter actions | Ctrl+Down input":te&&pe?.type==="collapsible"&&pe.secondaryAction&&pe.expanded?q="Enter full file | PgUp/PgDn scroll | Esc back":te&&pe?.type==="collapsible"&&pe.secondaryAction?q="Enter preview | Ctrl+Enter preview | PgUp/PgDn":te?q="Enter/Ctrl+Enter expand | PgUp/PgDn scroll":this.isUserActionableOutputBlock(pe)?q="Ctrl+Enter actions | PgUp/PgDn scroll":q="Up/Down select | PgUp/PgDn scroll | Ctrl+Down input"}let Q=this.clip(q,Math.max(1,Math.min(64,Math.floor(n*.52)))),ye=this.footerFocus==="status"&&this.statusFocusIndex===4?gt(Q):x(Q),ee=X,Se=se(ee).length,me=se(ye).length,de=Math.max(1,n-me-1);Se>de&&(ee=x(this.clip(se(ee),de)),Se=se(ee).length);let Ee=Math.max(1,n-Se-me);return d.moveTo(e,1)+d.eraseLine()+ee+" ".repeat(Ee)+ye}inputCursorPosition(){let e;if(this.autocompleteVisible&&this.autocompleteMatches.length>0)e=this.rows-9+2;else{let r=this.getNormalInputRows(),o=this.getNormalInputStartRow();if(this.isPrompting){let p=se(`\u26A0 ${this.promptQuestion} `).length;return d.moveTo(o,p+this.cursorPos+1)}let{line:i,column:a}=this.getCursorLineAndColumn(),l=Math.max(0,Math.min(r-1,i-this.inputLineScrollOffset)),c=Math.max(0,a-this.inputScrollOffset);return e=o+l,d.moveTo(e,2+c+1)}if(this.isPrompting){let r=se(`\u26A0 ${this.promptQuestion} `).length;return d.moveTo(e,r+this.cursorPos+1)}let n=2,s=this.cursorPos-this.inputScrollOffset;return d.moveTo(e,n+s+1)}positionInputCursor(){process.stdout.write(this.inputCursorPosition())}setMouseReportingEnabled(e){!process.stdout.isTTY||this.mouseReportingEnabled===e||(this.mouseReportingEnabled=e,process.stdout.write(e?d.enableMouseReporting():d.disableMouseReporting()))}hasOverlayOpen(){return!!(this.permissionState||this.modelPickerState||this.actionPickerState||this.sessionMultiPickerState||this.sessionPickerState||this.helpPanelState||this.infoPanelState)}activeOverlayNames(){let e=[];return this.permissionState&&e.push("permission"),this.modelPickerState&&e.push("modelPicker"),this.actionPickerState&&e.push("actionPicker"),this.sessionMultiPickerState&&e.push("sessionMultiPicker"),this.sessionPickerState&&e.push("sessionPicker"),this.helpPanelState&&e.push("helpPanel"),this.infoPanelState&&e.push("infoPanel"),e}shouldShowInputCursor(){return this.footerFocus==="input"&&!this.hasOverlayOpen()}refreshFooterFocusCursor(){if(!this.shouldShowInputCursor()){process.stdout.write(d.hideCursor());return}this.positionInputCursor(),process.stdout.write(d.showCursor())}parseCtrlArrow(e){if(e==="\x1B[1;5A"||e==="\x1B[5A")return"up";if(e==="\x1B[1;5B"||e==="\x1B[5B")return"down";if(e==="\x1B[1;5C"||e==="\x1B[5C")return"right";if(e==="\x1B[1;5D"||e==="\x1B[5D")return"left";if(!e.startsWith("\x1B["))return null;let n=/^(?:1;)?(\d+)([ABCD])$/,s=e.slice(2).match(n);if(!s)return null;let r=Number(s[1]);if(![5,6,7,8].includes(r))return null;switch(s[2]){case"A":return"up";case"B":return"down";case"C":return"right";case"D":return"left";default:return null}}parseMouseWheel(e){let n=new RegExp("^\x1B\\[<(\\d+);\\d+;\\d+[mM]$"),s=e.match(n);if(s){let r=Number(s[1]);return!Number.isFinite(r)||(r&64)!==64?null:(r&1)===0?-1:1}if(e.startsWith("\x1B[M")&&e.length>=6){let r=e.charCodeAt(3)-32;return(r&64)!==64?null:(r&1)===0?-1:1}return null}handleCtrlArrow(e){let n=!!this.delegationViewState&&!this.hasOverlayOpen();if(e==="up"&&this.footerFocus==="input"&&this.hasSelectableOutputBlocks()){this.focusLatestOutputBlock();return}if(this.footerFocus==="output"){if(e==="up"){if(this.outputActionState){this.closeOutputActionRow({returnToInput:!1});return}this.moveOutputFocus(-1);return}if(e==="down"){this.exitOutputFocus();return}if(this.outputActionState?.blockIndex===this.outputFocusIndex&&this.outputActionState.focus==="actions"){let s=this.OUTPUT_ACTIONS.length-1;e==="left"?this.outputActionState={...this.outputActionState,selectedActionIndex:Math.max(0,this.outputActionState.selectedActionIndex-1)}:e==="right"&&(this.outputActionState={...this.outputActionState,selectedActionIndex:Math.min(s,this.outputActionState.selectedActionIndex+1)}),this.redrawScreenFromHistory(),this.drawInputBox();return}}if(!(!this.isStatusBarVisible()&&!n)){if(e==="down"){if(n){this.footerFocus!=="delegation"&&(this.setMouseReportingEnabled(!1),this.footerFocus="delegation",this.delegationFocusIndex=Math.max(0,Math.min(this.delegationFocusIndex,Math.max(0,(this.delegationViewState?.agents.length??1)-1))),this.drawInputBox(),this.refreshFooterFocusCursor());return}this.footerFocus!=="status"&&(this.setMouseReportingEnabled(!1),this.footerFocus="status",this.statusFocusIndex=0,this.drawInputBox(),this.refreshFooterFocusCursor());return}if(e==="up"){(this.footerFocus==="status"||this.footerFocus==="delegation")&&(this.setMouseReportingEnabled(!1),this.footerFocus="input",this.drawInputBox(),this.refreshFooterFocusCursor());return}if(this.footerFocus==="delegation"){if(!this.delegationViewState)return;e==="left"?this.delegationFocusIndex=Math.max(0,this.delegationFocusIndex-1):e==="right"&&(this.delegationFocusIndex=Math.min(this.delegationViewState.agents.length-1,this.delegationFocusIndex+1)),this.drawInputBox(),this.refreshFooterFocusCursor();return}if(this.footerFocus==="status"){if(e==="left"){this.statusFocusIndex=Math.max(0,this.statusFocusIndex-1),this.drawInputBox(),this.refreshFooterFocusCursor();return}e==="right"&&(this.statusFocusIndex=Math.min(this.STATUS_FOCUSABLE_COUNT-1,this.statusFocusIndex+1),this.drawInputBox(),this.refreshFooterFocusCursor())}}}isMultilineInsertKey(e){return!!(e===`
|
|
103
|
+
`&&process.platform==="win32"||e==="\x1B\r"||this.matchesModifiedEnterSequence(e,"\x1B[13;","u")||this.matchesModifiedEnterSequence(e,"\x1B[27;13;","~"))}isEnterKey(e){return e==="\r"||e===`
|
|
104
|
+
`||e===`\r
|
|
105
|
+
`||e==="\x1BOM"}isCtrlEnterKey(e){if(e===`
|
|
106
|
+
`&&process.platform==="win32")return!0;let n=this.getModifiedEnterModifier(e,"\x1B[13;","u"),s=this.getModifiedEnterModifier(e,"\x1B[27;13;","~");return n==="5"||n==="6"||s==="5"||s==="6"}matchesModifiedEnterSequence(e,n,s){let r=this.getModifiedEnterModifier(e,n,s);return r==="2"||r==="5"||r==="6"}getModifiedEnterModifier(e,n,s){return!e.startsWith(n)||!e.endsWith(s)?null:e.slice(n.length,e.length-s.length)}isArrowKey(e,n){let s=n==="up"?"A":n==="down"?"B":n==="right"?"C":"D",r=n==="up"?"H":n==="down"?"P":n==="right"?"M":"K",o=new RegExp(`^\\x1b\\[(?:\\d+(?:;\\d+)*)?${s}$`),i=new RegExp(`^\\x1bO${s}$`);switch(n){case"up":case"down":case"left":case"right":return o.test(e)||i.test(e)||e===`\0${r}`||e===`\xE0${r}`;default:return!1}}insertMultilineBreak(){this._busy||this.isPrompting||(this.inputBuffer=this.inputBuffer.slice(0,this.cursorPos)+`
|
|
107
|
+
`+this.inputBuffer.slice(this.cursorPos),this.cursorPos+=1,this.closeAutocomplete(),this.autocompleteSelectedIndex=0,this.drawInputBox(),this.positionInputCursor())}handleStatusEnter(){if(!this._busy){if(this.statusFocusIndex===0){let e=this.opts.permissionMode==="bypassPermissions",n=this.opts.executionMode??"agent",s=e?"chat":n==="chatOnly"?"agent":"full-access";this.submitInput(`/mode ${s}`);return}if(this.statusFocusIndex===1){let e=!this.delegationEnabled;this.delegationEnabled=e,this.drawStatusBar(),this.invokeSafeAction("delegation toggle",()=>this.opts.onToggleDelegation?.(e));return}if(this.statusFocusIndex===2){this.submitInput("/model");return}if(this.statusFocusIndex===3){this.submitInput("/open");return}if(this.statusFocusIndex===4){this.submitInput("/help");return}this.statusFocusIndex===5&&this.getBackgroundTaskCount()>0&&this.submitInput("/processes")}}handleDelegationEnter(){this.delegationViewState&&this.openDelegationAgentDetailPanel()}handleKeypress(e){if(e===""){this.handleCtrlC();return}if(this.infoPanelState){this.handleInfoPanelKeypress(e);return}if(this.helpPanelState){this.handleHelpPanelKeypress(e);return}if(this.permissionState){this.handlePermissionKeypress(e);return}if(this.modelPickerState){this.handleModelPickerKeypress(e);return}if(this.actionPickerState){this.handleActionPickerKeypress(e);return}if(this.sessionMultiPickerState){this.handleSessionMultiPickerKeypress(e);return}if(this.sessionPickerState){this.handleSessionPickerKeypress(e);return}let n=this.parseCtrlArrow(e);if(n){this.handleCtrlArrow(n);return}let s=this.parseMouseWheel(e);if(s!==null){this.footerFocus==="output"&&!this.hasOverlayOpen()&&this.wheelScrollOutputViewport(s);return}if(e==="\f"&&this.delegationViewState&&!this.hasOverlayOpen()){this.openDelegationInspector();return}if(e===""&&this.delegationViewState&&this.shouldUseDelegationLogDock()){this.toggleDelegationLogDockExpanded();return}if(this.delegationViewState&&this.delegationLogDockExpanded&&!this.hasOverlayOpen()){if(e==="\x1B[5~"){this.scrollDelegationLogDock(-Math.max(1,Math.floor(this.getDelegationLogDockVisibleLines()/2)));return}if(e==="\x1B[6~"){this.scrollDelegationLogDock(Math.max(1,Math.floor(this.getDelegationLogDockVisibleLines()/2)));return}if(e==="\x1B[H"||e==="\x1B[1~"){this.jumpDelegationLogDock("start");return}if(e==="\x1B[F"||e==="\x1B[4~"){this.jumpDelegationLogDock("end");return}}if(!this.quickActionPending){if(e===""){this._busy||(this.quickActionBarOpen=!this.quickActionBarOpen,this.quickActionBarOpen?(this.quickActionSelectedIndex=0,this.quickActionView="main",this.quickRewriteSelectedIndex=0,this.quickRewriteCustomInput="",this.quickActionInlineHint=null):(this.quickActionView="main",this.quickRewriteSelectedIndex=0,this.quickRewriteCustomInput="",this.quickActionInlineHint=null),this.drawInputBox(),this.refreshFooterFocusCursor());return}if(this._busy&&e===""){this.invokeSafeAction("background request",()=>this.opts.onBackgroundRequest?.());return}if(e===""){this._verboseToolOutput=!this._verboseToolOutput;for(let r of this.outputBlocks??[])r.type==="collapsible"&&(r.expanded=this._verboseToolOutput,r.autoCollapseTimer&&(clearTimeout(r.autoCollapseTimer),r.autoCollapseTimer=null));this.syncRenderedOutputHistory(),this.redrawScreenFromHistory(),this.drawInputBox(),this.showTransientActivityNotice(this._verboseToolOutput?"Verbose output: ON":"Verbose output: OFF");return}if(this._busy&&e==="\x1B"&&e.length===1){if(this.interruptRewindLastEscAt=0,this.busyActivityLabel="Interrupting current turn...",this.redrawBusyActivityRow(),this.busyInterruptRequested){this.openRewindAfterInterrupt=!0,this.busyActivityLabel="Interrupting current turn... rewind queued",this.redrawBusyActivityRow(),this.showTransientActivityNotice("Rewind will open when interruption finishes");return}this.busyInterruptRequested=!0,this.invokeSafeAction("interrupt request",()=>this.opts.onInterrupt?.());return}if(e==="\x1B"&&e.length===1&&this.escCancelableInputDraft){this.inputBuffer="",this.cursorPos=0,this.escCancelableInputDraft=!1,this.clearPastedTextBlocks(),this.drawInputBox(),this.positionInputCursor();return}if(e==="\x1B"&&e.length===1&&this.interruptRewindArmed){let r=Date.now();this.interruptRewindLastEscAt>0&&r-this.interruptRewindLastEscAt<=this.interruptRewindWindowMs?(this.interruptRewindLastEscAt=0,this.invokeSafeAction("rewind request",()=>this.opts.onOpenRewind?.())):(this.interruptRewindLastEscAt=r,this.showTransientActivityNotice("Esc again to rewind conversation"));return}if(this.footerFocus==="output"){if(e==="\x1B[5~"){this.pageScrollOutputViewport(-1);return}if(e==="\x1B[6~"){this.pageScrollOutputViewport(1);return}if(e==="\x1B[H"||e==="\x1B[1~"||e==="\x1B[7~"){this.jumpOutputViewport("start");return}if(e==="\x1B[F"||e==="\x1B[4~"||e==="\x1B[8~"){this.jumpOutputViewport("end");return}if(this.isArrowKey(e,"up")){this.outputActionState&&this.closeOutputActionRow({returnToInput:!1}),this.moveOutputFocus(-1);return}if(this.isArrowKey(e,"down")){this.outputActionState&&this.closeOutputActionRow({returnToInput:!1}),this.moveOutputFocus(1);return}if(this.isCtrlEnterKey(e)){let r=this.getFocusedOutputBlock();if(this.outputActionState?.blockIndex===this.outputFocusIndex){if(this.outputActionState.focus==="actions"){let o=this.OUTPUT_ACTIONS[this.outputActionState.selectedActionIndex]?.toLowerCase();this.outputActionState={...this.outputActionState,focus:"confirm",pendingAction:o},this.redrawScreenFromHistory(),this.drawInputBox();return}if(this.outputActionState.focus==="confirm"){let o=this.getSelectedOutputActionRequest();o&&this.invokeSafeAction("output action",()=>this.opts.onOutputAction?.(o)),this.closeOutputActionRow({returnToInput:!0});return}}if(this.isUserActionableOutputBlock(r))this.openOutputActionRow(this.outputFocusIndex);else if(r?.type==="collapsible"){if(r.expanded&&r.secondaryAction){this.invokeSafeAction("tool artifact action",()=>r.secondaryAction?.());return}r.expanded=!r.expanded,this.redrawScreenFromHistory(),this.drawInputBox()}return}if(this.isEnterKey(e)){let r=this.getFocusedOutputBlock();if(this.outputActionState?.blockIndex===this.outputFocusIndex){if(this.outputActionState.focus==="actions"){let o=this.OUTPUT_ACTIONS[this.outputActionState.selectedActionIndex]?.toLowerCase();this.outputActionState={...this.outputActionState,focus:"confirm",pendingAction:o},this.redrawScreenFromHistory(),this.drawInputBox();return}if(this.outputActionState.focus==="confirm"){let o=this.getSelectedOutputActionRequest();o&&this.invokeSafeAction("output action",()=>this.opts.onOutputAction?.(o)),this.closeOutputActionRow({returnToInput:!0});return}}if(r?.type==="collapsible"){if(r.expanded&&r.secondaryAction){this.invokeSafeAction("tool artifact action",()=>r.secondaryAction?.());return}r.expanded=!r.expanded,this.redrawScreenFromHistory(),this.drawInputBox()}return}if(e==="\x1B"&&e.length===1&&this.outputActionState){this.closeOutputActionRow({returnToInput:!1});return}if(e==="\x1B"&&e.length===1){this.footerFocus="input",this.setMouseReportingEnabled(!1),this.redrawScreenFromHistory(),this.drawInputBox(),this.refreshFooterFocusCursor();return}}if(this.footerFocus==="status"){(e==="\r"||e===`
|
|
108
|
+
`)&&this.handleStatusEnter(),e==="\x1B[A"&&this.handleCtrlArrow("up"),e==="\x1B[D"&&this.handleCtrlArrow("left"),e==="\x1B[C"&&this.handleCtrlArrow("right");return}if(this.footerFocus==="delegation"){if(this.isEnterKey(e)){this.handleDelegationEnter();return}if(e==="\x1B"&&e.length===1){this.clearDelegationView();return}if(this.isArrowKey(e,"up")){this.handleCtrlArrow("up");return}if(this.isArrowKey(e,"left")){this.handleCtrlArrow("left");return}if(this.isArrowKey(e,"right")){this.handleCtrlArrow("right");return}}if(this.quickActionBarOpen){if(this.quickActionView==="rewriteCustom"){if(e==="\x1B"&&e.length===1){this.quickActionView="rewrite",this.quickActionInlineHint=null,this.drawInputBox(),this.refreshFooterFocusCursor();return}if(e==="\r"||e===`
|
|
109
|
+
`){if(this.inputBuffer.trim().length===0)this.quickActionInlineHint="write something first";else if(this.quickRewriteCustomInput.trim().length===0)this.quickActionInlineHint="write as what";else{this.applyQuickRewriteAs("CUSTOM",this.quickRewriteCustomInput.trim());return}this.drawInputBox(),this.refreshFooterFocusCursor();return}if(e==="\x7F"||e==="\b"){this.quickActionInlineHint=null,this.quickRewriteCustomInput.length>0&&(this.quickRewriteCustomInput=this.quickRewriteCustomInput.slice(0,-1)),this.drawInputBox(),this.refreshFooterFocusCursor();return}if(e>=" "){this.quickActionInlineHint=null,this.quickRewriteCustomInput+=e,this.drawInputBox(),this.refreshFooterFocusCursor();return}return}if(e==="\x1B[C"||e===" "||e==="\x1B[B"){this.quickActionInlineHint=null,this.quickActionView==="main"?this.quickActionSelectedIndex=Math.min(this.QUICK_ACTIONS.length-1,this.quickActionSelectedIndex+1):this.quickRewriteSelectedIndex=Math.min(this.QUICK_REWRITE_OPTIONS.length-1,this.quickRewriteSelectedIndex+1),this.drawInputBox(),this.refreshFooterFocusCursor();return}if(e==="\x1B[D"||e==="\x1B[Z"||e==="\x1B[A"){this.quickActionInlineHint=null,this.quickActionView==="main"?this.quickActionSelectedIndex=Math.max(0,this.quickActionSelectedIndex-1):this.quickRewriteSelectedIndex=Math.max(0,this.quickRewriteSelectedIndex-1),this.drawInputBox(),this.refreshFooterFocusCursor();return}if(e==="\r"||e===`
|
|
110
|
+
`){if(this.inputBuffer.trim().length===0){this.quickActionInlineHint="write something first",this.drawInputBox(),this.refreshFooterFocusCursor();return}if(this.quickActionView==="main"){if(this.QUICK_ACTIONS[this.quickActionSelectedIndex]==="FIX TYPO"){this.applyQuickFixTypo();return}this.quickActionView="rewrite",this.quickRewriteSelectedIndex=0,this.quickRewriteCustomInput="",this.quickActionInlineHint=null,this.drawInputBox(),this.refreshFooterFocusCursor();return}let r=this.QUICK_REWRITE_OPTIONS[this.quickRewriteSelectedIndex];if(r==="CUSTOM"){this.quickActionView="rewriteCustom",this.quickRewriteCustomInput="",this.quickActionInlineHint=null,this.drawInputBox(),this.refreshFooterFocusCursor();return}this.applyQuickRewriteAs(r);return}if(e==="\x1B"&&e.length===1){if(this.quickActionView==="rewrite"){this.quickActionView="main",this.quickActionInlineHint=null,this.drawInputBox(),this.refreshFooterFocusCursor();return}this.quickActionBarOpen=!1,this.quickActionView="main",this.quickRewriteSelectedIndex=0,this.quickRewriteCustomInput="",this.quickActionInlineHint=null,this.drawInputBox(),this.refreshFooterFocusCursor();return}}if(this.isMultilineInsertKey(e)){this.insertMultilineBreak();return}if(e==="\x1B"&&e.length===1){if(this.autocompleteVisible){this.closeAutocomplete(),this.drawInputBox(),this.positionInputCursor();return}return}if(e==="\x1B[Z"){let r=["default","acceptEdits","bypassPermissions"],o=r.indexOf(this.opts.permissionMode),i=r[(o+1)%r.length]??"default",a={default:"read-only",acceptEdits:"default",bypassPermissions:"full-access"};this.submitInput(`/approvals ${a[i]}`);return}if(e.startsWith("\x1B")){this.handleEscapeSequence(e);return}if(e==="\r"||e===`
|
|
111
|
+
`){if(this.autocompleteVisible&&this.autocompleteMatches.length>0){this.completeAutocomplete(),this.handleEnter();return}this.handleEnter();return}if(e===" "){if(this.autocompleteVisible&&this.autocompleteMatches.length>0){this.completeAutocomplete(),this.drawInputBox(),this.positionInputCursor();return}this.handleTab();return}if(e==="\x7F"||e==="\b"){this.handleBackspace();return}if(e===""){this.cursorPos=0,this.inputScrollOffset=0,this.inputLineScrollOffset=0,this.closeAutocomplete(),this.drawInputBox(),this.positionInputCursor();return}if(e===""){this.cursorPos=this.inputBuffer.length,this.drawInputBox(),this.positionInputCursor();return}if(e===""){this.inputBuffer="",this.cursorPos=0,this.clearPastedTextBlocks(),this.inputScrollOffset=0,this.inputLineScrollOffset=0,this.quickActionInlineHint=null,this.closeAutocomplete(),this.drawInputBox(),this.positionInputCursor();return}if(e==="\v"){this.inputBuffer=this.inputBuffer.slice(0,this.cursorPos),this.drawInputBox(),this.positionInputCursor();return}if(e===""){this.restoreQuickActionUndoSnapshot();return}if(e===""){this.submitInput("/processes");return}if(e==="\x1Bp"||e==="\x1BP"||e==="\xC3\xB0"){this.submitInput("/model");return}if(e==="\x1Bt"||e==="\x1BT"||e==="\xC3\xB4"){this.showTransientActivityNotice("Thinking mode: use a thinking-enabled model");return}if(!this.handlePastedText(e)){if(e==="!"&&this.inputBuffer.length===0&&this.cursorPos===0){this.insertIntoInputBuffer("! ");return}e>=" "&&this.insertIntoInputBuffer(e)}}}handleCtrlC(){if(!this.hasOverlayOpen()&&this.inputBuffer.length>0){this.inputBuffer="",this.cursorPos=0,this.clearPastedTextBlocks(),this.inputScrollOffset=0,this.inputLineScrollOffset=0,this.quickActionInlineHint=null,this.closeAutocomplete(),this.lastCtrlCTimestamp=0,this.statusRightHintTimer&&(clearTimeout(this.statusRightHintTimer),this.statusRightHintTimer=null),this.statusRightHint=null,this.drawInputBox(),this.refreshFooterFocusCursor();return}let e=Date.now();if(e-this.lastCtrlCTimestamp<=this.CTRL_C_EXIT_WINDOW_MS){this.cleanup(),process.stderr.write(x(`
|
|
112
|
+
Goodbye.
|
|
113
|
+
`)),process.exit(130);return}this.lastCtrlCTimestamp=e,this.setStatusRightHint("Ctrl+C again to exit",this.CTRL_C_EXIT_WINDOW_MS)}setStatusRightHint(e,n){this.statusRightHint=e,this.drawStatusBar(),this.statusRightHintTimer&&(clearTimeout(this.statusRightHintTimer),this.statusRightHintTimer=null),n&&n>0&&(this.statusRightHintTimer=setTimeout(()=>{this.statusRightHint=null,this.statusRightHintTimer=null,this.drawStatusBar()},n))}handleEscapeSequence(e){if(e==="\x1B[A"){if(this.autocompleteVisible&&this.autocompleteMatches.length>0){this.autocompleteSelectedIndex=Math.max(0,this.autocompleteSelectedIndex-1),this.drawInputBox(),this.positionInputCursor();return}if(this._queuedMessage&&this.inputBuffer.length===0){this.inputBuffer=this._queuedMessage,this.cursorPos=this.inputBuffer.length,this._queuedMessage=null,this.drawInputBox(),this.positionInputCursor();return}this.navigateHistory(-1);return}if(e==="\x1B[B"){if(this.autocompleteVisible&&this.autocompleteMatches.length>0){let n=this.autocompleteMatches.length-1;this.autocompleteSelectedIndex=Math.min(n,this.autocompleteSelectedIndex+1),this.drawInputBox(),this.positionInputCursor();return}this.navigateHistory(1);return}if(e==="\x1B[C"){this.cursorPos<this.inputBuffer.length&&(this.cursorPos++,this.drawInputBox(),this.positionInputCursor());return}if(e==="\x1B[D"){this.cursorPos>0&&(this.cursorPos--,this.drawInputBox(),this.positionInputCursor());return}if(e==="\x1B[H"||e==="\x1B[1~"){this.cursorPos=0,this.inputScrollOffset=0,this.inputLineScrollOffset=0,this.drawInputBox(),this.positionInputCursor();return}if(e==="\x1B[F"||e==="\x1B[4~"){this.cursorPos=this.inputBuffer.length,this.drawInputBox(),this.positionInputCursor();return}if(e==="\x1B[3~"){this.cursorPos<this.inputBuffer.length&&(this.inputBuffer=this.inputBuffer.slice(0,this.cursorPos)+this.inputBuffer.slice(this.cursorPos+1),this.drawInputBox(),this.positionInputCursor());return}}handleEnter(){if(this.isPrompting){this.isPrompting=!1;let o=this.expandPastedTextLabels(this.inputBuffer);this.inputBuffer="",this.cursorPos=0,this.clearPastedTextBlocks(),this.inputScrollOffset=0,this.inputLineScrollOffset=0,this.drawInputBox(),this._busy?process.stdout.write(d.hideCursor()):(this.positionInputCursor(),process.stdout.write(d.showCursor())),this.promptResolve?.(o),this.promptResolve=null;return}let e=this.expandPastedTextLabels(this.inputBuffer),n=e.trim(),s=e.includes(`
|
|
114
|
+
`)?e:n,r=n.startsWith("/");if(n){if(this._busy){this._queuedMessage=s,this.inputBuffer="",this.cursorPos=0,this.inputScrollOffset=0,this.inputLineScrollOffset=0,this.closeAutocomplete(),this.drawInputBox();return}if(r?(this.historyIndex=-1,this.historyDraft=""):(this.inputHistory.push(s),this.historyIndex=-1,this.historyDraft=""),this.interruptRewindArmed=!1,this.interruptRewindLastEscAt=0,this.inputBuffer="",this.cursorPos=0,this.clearPastedTextBlocks(),this.inputScrollOffset=0,this.inputLineScrollOffset=0,this.closeAutocomplete(),this.drawInputBox(),this.positionInputCursor(),!r){let o=s.replace(/\n/g,`
|
|
115
|
+
`);this.writeOutput(`
|
|
116
|
+
${be("\u276F")} ${o}
|
|
117
|
+
`,{forceNewBlock:!0,selectable:!0,blockKind:"user"})}this.submitInput(s)}}submitInput(e){try{Promise.resolve(this.opts.onSubmit(e)).catch(n=>{this.handleSubmitError(n)})}catch(n){this.handleSubmitError(n)}}handleSubmitError(e){this.handleActionError("Command failed",e)}invokeSafeAction(e,n){try{Promise.resolve(n()).catch(s=>{this.handleActionError(`${e} failed`,s)})}catch(s){this.handleActionError(`${e} failed`,s)}}handleActionError(e,n){let s=n instanceof Error?n.message:String(n),r=s.trim().length>0?s.trim():"Unknown command error";this._busy=!1;try{this.writeError(`${e}: ${r}`)}catch{}this.showTransientActivityNotice(`${e}: ${r}`,8e3)}handleBackspace(){this.cursorPos>0&&(this.quickActionInlineHint=null,this.inputBuffer=this.inputBuffer.slice(0,this.cursorPos-1)+this.inputBuffer.slice(this.cursorPos),this.cursorPos--,this.autocompleteSelectedIndex=0,this.drawInputBox(),this.positionInputCursor())}navigateHistory(e){if(this.inputHistory.length!==0){if(e===-1)if(this.historyIndex===-1)this.historyDraft=this.inputBuffer,this.historyIndex=this.inputHistory.length-1;else if(this.historyIndex>0)this.historyIndex-=1;else return;else if(e===1){if(this.historyIndex===-1)return;if(this.historyIndex<this.inputHistory.length-1)this.historyIndex+=1;else return}else return;this.historyIndex>=0&&this.historyIndex<this.inputHistory.length&&(this.inputBuffer=this.inputHistory[this.historyIndex],this.cursorPos=this.inputBuffer.length,this.clearPastedTextBlocks(),this.inputScrollOffset=0,this.inputLineScrollOffset=0,this.drawInputBox(),this.positionInputCursor())}}handleTab(){if(this.inputBuffer.length===0&&this._promptSuggestion){this.inputBuffer=this._promptSuggestion,this.cursorPos=this.inputBuffer.length,this._promptSuggestion=null,this.drawInputBox(),this.positionInputCursor();return}if(!this.inputBuffer.startsWith("/"))return;let e=this.SLASH_COMMANDS.filter(n=>n.startsWith(this.inputBuffer)&&n!==this.inputBuffer);if(e.length!==0)if(e.length===1)this.inputBuffer=e[0]+" ",this.cursorPos=this.inputBuffer.length,this.inputScrollOffset=0,this.inputLineScrollOffset=0,this.drawInputBox(),this.positionInputCursor();else{let n=this.findCommonPrefix(e);n.length>this.inputBuffer.length&&(this.inputBuffer=n,this.cursorPos=this.inputBuffer.length,this.inputScrollOffset=0,this.inputLineScrollOffset=0),this.drawInputBox(),this.positionInputCursor(),this.writeOutput(`
|
|
118
|
+
`+x(" "+e.join(" "))+`
|
|
119
|
+
`)}}findCommonPrefix(e){if(e.length===0)return"";let n=e[0];for(let s=1;s<e.length;s++)for(;!e[s].startsWith(n);)n=n.slice(0,-1);return n}getModelPickerRows(){return 9+this.MODEL_PICKER_VISIBLE_OPTIONS}getModelPickerFilteredIndices(e){let n=e.query.trim().toLowerCase();return n?e.options.map((s,r)=>({opt:s,idx:r})).filter(({opt:s})=>`${s.label} ${s.value} ${s.detail??""}`.toLowerCase().includes(n)).map(({idx:s})=>s):e.options.map((s,r)=>r)}syncModelPickerSelectionAfterFilter(){if(!this.modelPickerState)return;let e=this.modelPickerState,n=this.getModelPickerFilteredIndices(e);if(n.length===0){e.selectedIndex=-1,e.scrollOffset=0;return}if(!n.includes(e.selectedIndex)){let s=n.find(r=>e.options[r].value===e.currentValue);e.selectedIndex=s??n[0],e.scrollOffset=0}}drawModelPickerUI(){if(!this.modelPickerState)return;let e=this.modelPickerState,n=this.getModelPickerFilteredIndices(e);this.syncModelPickerSelectionAfterFilter();let s=this.getModelPickerRows(),r=this.MODEL_PICKER_VISIBLE_OPTIONS,o=e.selectedIndex>=0?n.indexOf(e.selectedIndex):-1,i=Math.max(0,n.length-r);e.scrollOffset>i&&(e.scrollOffset=i),o!==-1&&(o<e.scrollOffset?e.scrollOffset=o:o>=e.scrollOffset+r&&(e.scrollOffset=o-r+1));let a=e.scrollOffset,l=(T,I)=>I<=0?"":T.length<=I?T:I<=3?".".repeat(I):T.slice(0,I-3)+"...",c=this.rows-s+1,u=d.hideCursor()+d.disableWrap();for(let T=this.outputBottom+1;T<=this.rows;T++)u+=d.moveTo(T,1)+d.eraseLine();u+=d.moveTo(c,1)+d.eraseLine(),u+=be("\u2500".repeat(this.renderCols())),c++,u+=d.moveTo(c,1)+d.eraseLine(),u+=` ${x("\u2500".repeat(Math.max(0,this.cols-1)))}`,c++;let p=o>=0?o+1:0,f=`${e.title} (${p} of ${n.length})`;u+=d.moveTo(c,1)+d.eraseLine(),u+=` ${qe.bold(l(f,Math.max(1,this.cols-1)))}`,c++;let m=Math.max(1,this.cols-4),b=`\u2315 ${e.query.length>0?e.query:e.searchFocused?"":e.searchPlaceholder}`,v=l(b,m).padEnd(m," "),w="\u2500".repeat(Math.max(0,this.cols-2));u+=d.moveTo(c,1)+d.eraseLine(),u+=x(`\u256D${w}\u256E`),c++,u+=d.moveTo(c,1)+d.eraseLine();let P=e.searchFocused||e.query.length>0?be(v):x(v);u+=`${x("\u2502")} ${P} ${x("\u2502")}`,c++,u+=d.moveTo(c,1)+d.eraseLine(),u+=x(`\u2570${w}\u256F`),c++,u+=d.moveTo(c,1)+d.eraseLine(),c++;for(let T=0;T<r;T++){u+=d.moveTo(c,1)+d.eraseLine();let I=a+T,re=n[I];if(re===void 0){n.length===0&&T===0&&(u+=` ${x(`No models match "${e.query}"`)}`),c++;continue}let ae=e.options[re],N=re===e.selectedIndex,y=ae.value===e.currentValue,K=[`${I+1}.`,ae.label];y&&K.push("\u2714"),ae.detail&&K.push(ae.detail);let W=K.join(" "),Z=l(W,Math.max(1,this.cols-4));N?u+=` ${be("\u203A")} ${Z}`:u+=` ${x(Z)}`,c++}u+=d.moveTo(c,1)+d.eraseLine(),c++,u+=d.moveTo(c,1)+d.eraseLine();let E=`Ctrl+F search \xB7 Type search \xB7 ${n.length>r?"\u2191/\u2193 navigate \xB7 ":""}Enter confirm \xB7 Esc cancel`;u+=` ${x(l(E,Math.max(1,this.cols-1)))}`,u+=d.enableWrap(),process.stdout.write(u)}handleModelPickerKeypress(e){if(!this.modelPickerState)return;let n=this.modelPickerState,s=this.getModelPickerFilteredIndices(n);if(e===""){n.searchFocused=!0,this.drawModelPickerUI();return}if(e==="\x1B[A"){if(s.length===0)return;let r=Math.max(0,s.indexOf(n.selectedIndex)),o=Math.max(0,r-1);n.selectedIndex=s[o],this.drawModelPickerUI();return}if(e==="\x1B[B"){if(s.length===0)return;let r=Math.max(0,s.indexOf(n.selectedIndex)),o=Math.min(s.length-1,r+1);n.selectedIndex=s[o],this.drawModelPickerUI();return}if(e==="\r"||e===`
|
|
120
|
+
`){let r=n.selectedIndex>=0?n.options[n.selectedIndex]?.value??null:null;if(!r)return;this.exitModelPickerMode(r);return}if(e==="\x7F"||e==="\b"){n.query.length>0&&(n.query=n.query.slice(0,-1),n.searchFocused=!0,this.syncModelPickerSelectionAfterFilter(),this.drawModelPickerUI());return}if(e==="\x1B"){if(n.query.length>0){n.query="",n.searchFocused=!1,this.syncModelPickerSelectionAfterFilter(),this.drawModelPickerUI();return}if(n.searchFocused){n.searchFocused=!1,this.drawModelPickerUI();return}this.exitModelPickerMode(null);return}if(e===""){this.exitModelPickerMode(null);return}if(e===""||e===""){n.query="",n.searchFocused=!0,this.syncModelPickerSelectionAfterFilter(),this.drawModelPickerUI();return}if(!n.searchFocused&&n.query.length===0){let r=parseInt(e,10);if(r>=1&&r<=n.options.length){let o=n.options[r-1].value;this.exitModelPickerMode(o);return}}e>=" "&&e.length===1&&(n.searchFocused=!0,n.query+=e,this.syncModelPickerSelectionAfterFilter(),this.drawModelPickerUI())}exitModelPickerMode(e){let n=this.getModelPickerRows(),s=Math.max(this.rows-n+1,1),r=this.modelPickerState?.resolve;this.modelPickerState=null,this.calculateLayout(),process.stdout.write(d.setScrollRegion(1,this.outputBottom));for(let o=s;o<=this.rows;o++)process.stdout.write(d.moveTo(o,1)+d.eraseLine());this.drawInputBox(),this.refreshFooterFocusCursor(),r?.(e)}getSessionPickerVisibleItems(){let e=Math.max(2,Math.floor((this.rows-8)/3));return Math.min(this.SESSION_PICKER_VISIBLE_ITEMS,e)}getSessionPickerRows(){return 8+this.getSessionPickerVisibleItems()*3}getSessionPickerFilteredIndices(e){let n=e.query.trim().toLowerCase();return n?e.options.map((s,r)=>({opt:s,idx:r})).filter(({opt:s})=>`${s.title} ${s.value} ${s.meta??""}`.toLowerCase().includes(n)).map(({idx:s})=>s):e.options.map((s,r)=>r)}getSessionMultiPickerVisibleItems(){let e=Math.max(2,Math.floor((this.rows-8)/3));return Math.min(this.SESSION_PICKER_VISIBLE_ITEMS,e)}getSessionMultiPickerRows(){return 8+this.getSessionMultiPickerVisibleItems()*3}getSessionMultiPickerFilteredIndices(e){let n=e.query.trim().toLowerCase();return n?e.options.map((s,r)=>({opt:s,idx:r})).filter(({opt:s})=>`${s.title} ${s.value} ${s.meta??""}`.toLowerCase().includes(n)).map(({idx:s})=>s):e.options.map((s,r)=>r)}syncSessionMultiPickerSelectionAfterFilter(){if(!this.sessionMultiPickerState)return;let e=this.sessionMultiPickerState,n=this.getSessionMultiPickerFilteredIndices(e);if(n.length===0){e.selectedIndex=-1,e.scrollOffset=0;return}n.includes(e.selectedIndex)||(e.selectedIndex=n[0],e.scrollOffset=0)}syncSessionPickerSelectionAfterFilter(){if(!this.sessionPickerState)return;let e=this.sessionPickerState,n=this.getSessionPickerFilteredIndices(e);if(n.length===0){e.selectedIndex=-1,e.scrollOffset=0;return}n.includes(e.selectedIndex)||(e.selectedIndex=n[0],e.scrollOffset=0)}drawSessionPickerUI(){if(!this.sessionPickerState)return;let e=this.sessionPickerState,n=this.getSessionPickerFilteredIndices(e);this.syncSessionPickerSelectionAfterFilter();let s=this.getSessionPickerVisibleItems(),r=this.getSessionPickerRows(),o=e.selectedIndex>=0?n.indexOf(e.selectedIndex):-1,i=Math.max(0,n.length-s);e.scrollOffset>i&&(e.scrollOffset=i),o!==-1&&(o<e.scrollOffset?e.scrollOffset=o:o>=e.scrollOffset+s&&(e.scrollOffset=o-s+1));let a=e.scrollOffset,l=(T,I)=>I<=0?"":T.length<=I?T:I<=3?".".repeat(I):T.slice(0,I-3)+"...",c=this.rows-r+1,u=d.hideCursor()+d.disableWrap();for(let T=this.outputBottom+1;T<=this.rows;T++)u+=d.moveTo(T,1)+d.eraseLine();u+=d.moveTo(c,1)+d.eraseLine(),u+=be("\u2500".repeat(this.renderCols())),c++,u+=d.moveTo(c,1)+d.eraseLine(),u+=` ${x("\u2500".repeat(Math.max(0,this.cols-1)))}`,c++;let p=o>=0?o+1:0,f=`${e.title} (${p} of ${n.length})`;u+=d.moveTo(c,1)+d.eraseLine(),u+=` ${qe.bold(l(f,Math.max(1,this.cols-1)))}`,c++;let m=Math.max(1,this.cols-4),b=`\u2315 ${e.query.length>0?e.query:e.searchFocused?"":e.searchPlaceholder}`,v=l(b,m).padEnd(m," "),w="\u2500".repeat(Math.max(0,this.cols-2));u+=d.moveTo(c,1)+d.eraseLine(),u+=x(`\u256D${w}\u256E`),c++,u+=d.moveTo(c,1)+d.eraseLine();let P=e.searchFocused||e.query.length>0?be(v):x(v);u+=`${x("\u2502")} ${P} ${x("\u2502")}`,c++,u+=d.moveTo(c,1)+d.eraseLine(),u+=x(`\u2570${w}\u256F`),c++,u+=d.moveTo(c,1)+d.eraseLine(),c++;for(let T=0;T<s;T++){let I=a+T,re=n[I];if(u+=d.moveTo(c,1)+d.eraseLine(),re===void 0){if(n.length===0&&T===0){let W=l(`No sessions match "${e.query}"`,Math.max(1,this.cols-2));u+=` ${x(W)}`}c++,u+=d.moveTo(c,1)+d.eraseLine(),c++,u+=d.moveTo(c,1)+d.eraseLine(),c++;continue}let ae=e.options[re],N=re===e.selectedIndex,y=Math.max(1,this.cols-3),oe=l(ae.title||"(session)",y);N?u+=`${be("\u203A")} ${oe}`:u+=` ${oe}`,c++;let K=l(ae.meta??"",Math.max(1,this.cols-2));u+=d.moveTo(c,1)+d.eraseLine(),K&&(u+=` ${x(K)}`),c++,u+=d.moveTo(c,1)+d.eraseLine(),c++}let E=`Ctrl+F search \xB7 Ctrl+U clear search \xB7 Type search \xB7 ${n.length>s?"\u2191/\u2193 navigate \xB7 ":""}Enter confirm \xB7 Esc cancel`;u+=d.moveTo(c,1)+d.eraseLine(),u+=` ${x(l(E,Math.max(1,this.cols-1)))}`,u+=d.enableWrap(),process.stdout.write(u)}handleSessionPickerKeypress(e){if(!this.sessionPickerState)return;let n=this.sessionPickerState,s=this.getSessionPickerFilteredIndices(n);if(e===""){n.searchFocused=!0,this.drawSessionPickerUI();return}if(e==="\x1B[A"){if(s.length===0)return;let r=Math.max(0,s.indexOf(n.selectedIndex)),o=Math.max(0,r-1);n.selectedIndex=s[o],this.drawSessionPickerUI();return}if(e==="\x1B[B"){if(s.length===0)return;let r=Math.max(0,s.indexOf(n.selectedIndex)),o=Math.min(s.length-1,r+1);n.selectedIndex=s[o],this.drawSessionPickerUI();return}if(e==="\r"||e===`
|
|
121
|
+
`){let r=n.selectedIndex>=0?n.options[n.selectedIndex]?.value??null:null;if(!r)return;this.exitSessionPickerMode(r);return}if(e==="\x7F"||e==="\b"){n.query.length>0&&(n.query=n.query.slice(0,-1),n.searchFocused=!0,this.syncSessionPickerSelectionAfterFilter(),this.drawSessionPickerUI());return}if(e==="\x1B"){if(n.query.length>0){n.query="",n.searchFocused=!1,this.syncSessionPickerSelectionAfterFilter(),this.drawSessionPickerUI();return}if(n.searchFocused){n.searchFocused=!1,this.drawSessionPickerUI();return}this.exitSessionPickerMode(null);return}if(e===""){this.exitSessionPickerMode(null);return}if(e===""||e===""){n.query="",n.searchFocused=!0,this.syncSessionPickerSelectionAfterFilter(),this.drawSessionPickerUI();return}e>=" "&&e.length===1&&(n.searchFocused=!0,n.query+=e,this.syncSessionPickerSelectionAfterFilter(),this.drawSessionPickerUI())}handleSessionMultiPickerKeypress(e){if(!this.sessionMultiPickerState)return;let n=this.sessionMultiPickerState,s=this.getSessionMultiPickerFilteredIndices(n);if(e===""){n.searchFocused=!0,this.drawSessionMultiPickerUI();return}if(e==="\x1B[A"){if(s.length===0)return;let r=Math.max(0,s.indexOf(n.selectedIndex)),o=Math.max(0,r-1);n.selectedIndex=s[o],this.drawSessionMultiPickerUI();return}if(e==="\x1B[B"){if(s.length===0)return;let r=Math.max(0,s.indexOf(n.selectedIndex)),o=Math.min(s.length-1,r+1);n.selectedIndex=s[o],this.drawSessionMultiPickerUI();return}if(e===" "){if(n.selectedIndex>=0){let r=n.options[n.selectedIndex]?.value;r&&(n.selectedValues.has(r)?n.selectedValues.delete(r):n.selectedValues.add(r),this.drawSessionMultiPickerUI())}return}if(e==="\r"||e===`
|
|
122
|
+
`){let r=n.selectedValues.size>0?Array.from(n.selectedValues):null;if(!r)return;this.exitSessionMultiPickerMode(r);return}if(e==="\x7F"||e==="\b"){n.query.length>0&&(n.query=n.query.slice(0,-1),n.searchFocused=!0,this.syncSessionMultiPickerSelectionAfterFilter(),this.drawSessionMultiPickerUI());return}if(e==="\x1B"){if(n.query.length>0){n.query="",n.searchFocused=!1,this.syncSessionMultiPickerSelectionAfterFilter(),this.drawSessionMultiPickerUI();return}if(n.searchFocused){n.searchFocused=!1,this.drawSessionMultiPickerUI();return}this.exitSessionMultiPickerMode(null);return}if(e===""){this.exitSessionMultiPickerMode(null);return}if(e===""){let r=s.map(i=>n.options[i]?.value).filter(i=>!!i);if(r.length>0&&r.every(i=>n.selectedValues.has(i)))for(let i of r)n.selectedValues.delete(i);else for(let i of r)n.selectedValues.add(i);n.searchFocused=!0,this.drawSessionMultiPickerUI();return}if(e===""){n.query="",n.searchFocused=!0,this.syncSessionMultiPickerSelectionAfterFilter(),this.drawSessionMultiPickerUI();return}e>=" "&&e.length===1&&(n.searchFocused=!0,n.query+=e,this.syncSessionMultiPickerSelectionAfterFilter(),this.drawSessionMultiPickerUI())}exitSessionPickerMode(e){let n=this.getSessionPickerRows(),s=Math.max(this.rows-n+1,1),r=this.sessionPickerState?.resolve;this.sessionPickerState=null,this.calculateLayout(),process.stdout.write(d.setScrollRegion(1,this.outputBottom));for(let o=s;o<=this.rows;o++)process.stdout.write(d.moveTo(o,1)+d.eraseLine());this.drawInputBox(),this.refreshFooterFocusCursor(),r?.(e)}exitSessionMultiPickerMode(e){let n=this.getSessionMultiPickerRows(),s=Math.max(this.rows-n+1,1),r=this.sessionMultiPickerState?.resolve;this.sessionMultiPickerState=null,this.calculateLayout(),process.stdout.write(d.setScrollRegion(1,this.outputBottom));for(let o=s;o<=this.rows;o++)process.stdout.write(d.moveTo(o,1)+d.eraseLine());this.drawInputBox(),this.refreshFooterFocusCursor(),r?.(e)}getActionPickerRows(){let e=this.actionPickerState?.options.length??0;return 7+Math.max(1,e)}drawActionPickerUI(){if(!this.actionPickerState)return;let e=this.actionPickerState,n=this.getActionPickerRows(),s=(i,a)=>a<=0?"":i.length<=a?i:a<=3?".".repeat(a):i.slice(0,a-3)+"...",r=this.rows-n+1,o=d.hideCursor()+d.disableWrap();for(let i=this.outputBottom+1;i<=this.rows;i++)o+=d.moveTo(i,1)+d.eraseLine();o+=d.moveTo(r,1)+d.eraseLine(),o+=be("\u2500".repeat(this.renderCols())),r++,o+=d.moveTo(r,1)+d.eraseLine(),o+=` ${qe.bold(s(e.title,Math.max(1,this.cols-1)))}`,r++,e.description&&(o+=d.moveTo(r,1)+d.eraseLine(),o+=` ${x(s(e.description,Math.max(1,this.cols-1)))}`,r++),o+=d.moveTo(r,1)+d.eraseLine(),r++;for(let i=0;i<Math.max(1,e.options.length);i++){o+=d.moveTo(r,1)+d.eraseLine();let a=e.options[i];if(a){let l=i===e.selectedIndex,c=l?be("\u276F"):" ",u=`${i+1}. ${a.label}`,p=a.detail?` ${a.detail}`:"",f=s(`${u}${p}`,Math.max(1,this.cols-4));o+=` ${c} ${l?be(f):f}`}r++}o+=d.moveTo(r,1)+d.eraseLine(),r++,o+=d.moveTo(r,1)+d.eraseLine(),o+=` ${x("Esc to cancel")}`,o+=d.enableWrap(),process.stdout.write(o)}drawSessionMultiPickerUI(){if(!this.sessionMultiPickerState)return;let e=this.sessionMultiPickerState,n=this.getSessionMultiPickerFilteredIndices(e);this.syncSessionMultiPickerSelectionAfterFilter();let s=this.getSessionMultiPickerVisibleItems(),r=this.getSessionMultiPickerRows(),o=e.selectedIndex>=0?n.indexOf(e.selectedIndex):-1,i=Math.max(0,n.length-s);e.scrollOffset>i&&(e.scrollOffset=i),o!==-1&&(o<e.scrollOffset?e.scrollOffset=o:o>=e.scrollOffset+s&&(e.scrollOffset=o-s+1));let a=e.scrollOffset,l=(E,T)=>T<=0?"":E.length<=T?E:T<=3?".".repeat(T):E.slice(0,T-3)+"...",c=this.rows-r+1,u=d.hideCursor()+d.disableWrap();for(let E=this.outputBottom+1;E<=this.rows;E++)u+=d.moveTo(E,1)+d.eraseLine();u+=d.moveTo(c,1)+d.eraseLine(),u+=be("\u2500".repeat(this.renderCols())),c++,u+=d.moveTo(c,1)+d.eraseLine(),u+=` ${x("\u2500".repeat(Math.max(0,this.cols-1)))}`,c++;let p=`${e.title} (${e.selectedValues.size} selected)`;u+=d.moveTo(c,1)+d.eraseLine(),u+=` ${qe.bold(l(p,Math.max(1,this.cols-1)))}`,c++;let f=Math.max(1,this.cols-4),g=`\u2315 ${e.query.length>0?e.query:e.searchFocused?"":e.searchPlaceholder}`,b=l(g,f).padEnd(f," "),v="\u2500".repeat(Math.max(0,this.cols-2));u+=d.moveTo(c,1)+d.eraseLine(),u+=x(`\u256D${v}\u256E`),c++,u+=d.moveTo(c,1)+d.eraseLine();let w=e.searchFocused||e.query.length>0?be(b):x(b);u+=`${x("\u2502")} ${w} ${x("\u2502")}`,c++,u+=d.moveTo(c,1)+d.eraseLine(),u+=x(`\u2570${v}\u256F`),c++,u+=d.moveTo(c,1)+d.eraseLine(),c++;for(let E=0;E<s;E++){let T=a+E,I=n[T];if(u+=d.moveTo(c,1)+d.eraseLine(),I===void 0){if(n.length===0&&E===0){let ce=l(`No sessions match "${e.query}"`,Math.max(1,this.cols-2));u+=` ${x(ce)}`}c++,u+=d.moveTo(c,1)+d.eraseLine(),c++,u+=d.moveTo(c,1)+d.eraseLine(),c++;continue}let re=e.options[I],ae=I===e.selectedIndex,y=e.selectedValues.has(re.value)?"[x]":"[ ]",oe=ae?`${be("\u203A")} ${y}`:` ${y}`,K=se(oe).length,W=Math.max(1,this.cols-K-2),Z=l(re.title||"(session)",W);u+=`${oe} ${Z}`,c++;let le=l(re.meta??"",Math.max(1,this.cols-2));u+=d.moveTo(c,1)+d.eraseLine(),le&&(u+=` ${x(le)}`),c++,u+=d.moveTo(c,1)+d.eraseLine(),c++}let $=`Space toggle \xB7 Ctrl+A all \xB7 Ctrl+F search \xB7 Type search \xB7 ${n.length>s?"\u2191/\u2193 navigate \xB7 ":""}${e.confirmLabel} \xB7 Esc cancel`;u+=d.moveTo(c,1)+d.eraseLine(),u+=` ${x(l($,Math.max(1,this.cols-1)))}`,u+=d.enableWrap(),process.stdout.write(u)}handleActionPickerKeypress(e){if(!this.actionPickerState)return;let n=this.actionPickerState;if(e==="\x1B[A"){n.selectedIndex=Math.max(0,n.selectedIndex-1),this.drawActionPickerUI();return}if(e==="\x1B[B"){n.selectedIndex=Math.min(n.options.length-1,n.selectedIndex+1),this.drawActionPickerUI();return}if(e==="\r"||e===`
|
|
123
|
+
`){let r=n.options[n.selectedIndex]?.value??null;this.exitActionPickerMode(r);return}if(e==="\x1B"||e===""){this.exitActionPickerMode(null);return}let s=Number.parseInt(e,10);Number.isFinite(s)&&s>=1&&s<=n.options.length&&this.exitActionPickerMode(n.options[s-1].value)}exitActionPickerMode(e){let n=this.getActionPickerRows(),s=Math.max(this.rows-n+1,1),r=this.actionPickerState?.resolve;this.actionPickerState=null,this.calculateLayout(),process.stdout.write(d.setScrollRegion(1,this.outputBottom));for(let o=s;o<=this.rows;o++)process.stdout.write(d.moveTo(o,1)+d.eraseLine());this.drawInputBox(),this.refreshFooterFocusCursor(),r?.(e)}getHelpPanelRows(){let n=Math.max(6,this.rows-1);return Math.min(15,n)}clip(e,n){return n<=0?"":e.length<=n?e:n<=3?".".repeat(n):e.slice(0,n-3)+"..."}formatHelpColumns(e,n,s){let i=Math.max(12,this.cols-1-6),a=Math.max(4,Math.floor(i*.25)),l=Math.max(4,Math.floor(i*.41)),c=Math.max(4,i-a-l),u=this.clip(e,a).padEnd(a," "),p=this.clip(n,l).padEnd(l," "),f=this.clip(s,c);return`${u}${" ".repeat(3)}${p}${" ".repeat(3)}${f}`}getHelpHeader(e){let n=["general","commands","custom-commands"],s=Ke().bold("XENO AGENT v0.1.0"),r=n.map(l=>l===e?gt(` ${l} `):x(l)).join(" "),o=x("(\u2190/\u2192 or tab to cycle)"),i=`${s} ${r} ${o}`,a=`XENO AGENT v0.1.0 ${n.join(" ")} (\u2190/\u2192 or tab to cycle)`;return{styled:i,plain:a}}fitStyledLine(e,n,s){return se(e).length<=s?e:this.clip(n,s)}getHelpPanelBodyLines(e){return e==="general"?["","XENO AGENT understands your workspace, makes edits with your permission, and executes commands right from your terminal.","","Shortcuts",this.formatHelpColumns("! for bash mode","double tap esc to clear input","ctrl + shift + - to undo"),this.formatHelpColumns("/ for commands","ctrl + o for verbose outputedits","meta + p to switch model"),this.formatHelpColumns("@ for file paths","ctrl + t to toggle tasks","ctrl + s to stash promptmode"),this.formatHelpColumns("& for background","backslash (\\) + return (\u23CE) for","ctrl + g to edit in $EDITOR"),this.formatHelpColumns("","newline","/keybindings to customize"),"","For more help: https://xenostudio.ai"]:e==="commands"?["","Use \u2191/\u2193 to navigate and Enter to run the selected command.","","Commands",...Yn.map(n=>`${n.name.padEnd(14," ")}${n.description}`),"","For more help: https://xenostudio.ai"]:["","Custom Commands","No custom commands defined.","","Create reusable command workflows in your project and they will appear here.","For more help: https://xenostudio.ai"]}getHelpCommandsBodyLines(e){if(!this.helpPanelState)return[];let n=this.helpPanelState,s=Yn,r="For more help: https://xenostudio.ai";if(s.length===0){let b=["Browse default commands:","","No commands available."];for(;b.length<Math.max(1,e-1);)b.push("");return b.push(r),b.slice(0,e)}n.commandSelectedIndex=Math.max(0,Math.min(n.commandSelectedIndex,s.length-1));let a=Math.max(2,e-2-1),l=Math.max(1,Math.floor(a/2)),c=Math.max(0,s.length-l);n.commandScrollOffset=Math.min(n.commandScrollOffset,c),n.commandSelectedIndex<n.commandScrollOffset?n.commandScrollOffset=n.commandSelectedIndex:n.commandSelectedIndex>=n.commandScrollOffset+l&&(n.commandScrollOffset=n.commandSelectedIndex-l+1);let u=n.commandScrollOffset,p=Math.min(s.length-1,u+l-1),f=u>0,m=p<s.length-1,g=["Browse default commands:",""];for(let b=u;b<=p;b++){let v=s[b],w=b===n.commandSelectedIndex,P=" ";w?P=be("\u203A"):b===u&&f?P=x("\u2191"):b===p&&m&&(P=x("\u2193"));let C=w?be(v.name):v.name;g.push(`${P} ${C}`),g.push(` ${x(v.description)}`)}for(;g.length<Math.max(1,e-1);)g.push("");return g.push(r),g.slice(0,e)}drawHelpPanelUI(){if(!this.helpPanelState)return;let e=this.helpPanelState,n=this.getHelpPanelRows(),s=Math.max(this.rows-n+1,1),r=this.getHelpHeader(e.activeTab),o=Math.max(1,n-4),i=e.activeTab==="commands"?this.getHelpCommandsBodyLines(o):this.getHelpPanelBodyLines(e.activeTab).slice(0,o),a=s,l=d.hideCursor()+d.disableWrap();for(let u=this.outputBottom+1;u<=this.rows;u++)l+=d.moveTo(u,1)+d.eraseLine();l+=d.moveTo(a,1)+d.eraseLine(),l+=be("\u2500".repeat(this.renderCols())),a++,l+=d.moveTo(a,1)+d.eraseLine(),l+=` ${x("\u2500".repeat(Math.max(0,this.cols-1)))}`,a++,l+=d.moveTo(a,1)+d.eraseLine(),l+=` ${this.fitStyledLine(r.styled,r.plain,Math.max(1,this.cols-1))}`,a++;for(let u=0;u<o;u++){l+=d.moveTo(a,1)+d.eraseLine();let p=i[u]??"";p&&(l+=` ${this.clip(p,Math.max(1,this.cols-1))}`),a++}let c=e.activeTab==="commands"?"\u2190/\u2192 tabs \xB7 Tab cycle \xB7 \u2191/\u2193 navigate \xB7 Enter confirm \xB7 Esc close":"\u2190/\u2192 tabs \xB7 Tab cycle \xB7 Enter close \xB7 Esc close";l+=d.moveTo(a,1)+d.eraseLine(),l+=` ${x(this.clip(c,Math.max(1,this.cols-1)))}`,l+=d.enableWrap(),process.stdout.write(l)}handleHelpPanelKeypress(e){if(!this.helpPanelState)return;let n=["general","commands","custom-commands"],s=n.indexOf(this.helpPanelState.activeTab);if(this.helpPanelState.activeTab==="commands"&&e==="\x1B[A"){this.helpPanelState.commandSelectedIndex=Math.max(0,this.helpPanelState.commandSelectedIndex-1),this.drawHelpPanelUI();return}if(this.helpPanelState.activeTab==="commands"&&e==="\x1B[B"){let r=Math.max(0,Yn.length-1);this.helpPanelState.commandSelectedIndex=Math.min(r,this.helpPanelState.commandSelectedIndex+1),this.drawHelpPanelUI();return}if(e==="\r"||e===`
|
|
124
|
+
`){if(this.helpPanelState.activeTab==="commands"&&!this._busy){let r=Yn[this.helpPanelState.commandSelectedIndex];this.exitHelpPanelMode(),r&&(this.writeOutput(`
|
|
125
|
+
${be("\u203A")} ${r.name}
|
|
126
|
+
`),this.submitInput(r.name));return}this.exitHelpPanelMode();return}if(e==="\x1B"||e===""){this.exitHelpPanelMode();return}if(e==="\x1B[D"){let r=(s-1+n.length)%n.length;this.helpPanelState.activeTab=n[r],this.drawHelpPanelUI();return}if(e==="\x1B[C"||e===" "){let r=(s+1)%n.length;this.helpPanelState.activeTab=n[r],this.drawHelpPanelUI();return}if(e==="1"||e==="2"||e==="3"){this.helpPanelState.activeTab=n[Number(e)-1],this.drawHelpPanelUI();return}}exitHelpPanelMode(){let e=this.getHelpPanelRows(),n=Math.max(this.rows-e+1,1),s=this.helpPanelState?.resolve;this.helpPanelState=null,this.calculateLayout(),process.stdout.write(d.setScrollRegion(1,this.outputBottom));for(let r=n;r<=this.rows;r++)process.stdout.write(d.moveTo(r,1)+d.eraseLine());this.drawInputBox(),this.refreshFooterFocusCursor(),s?.()}getInfoPanelRows(){if(this.infoPanelState?.layout==="viewport")return Math.max(1,this.rows);let n=!!(this.infoPanelState&&(this.infoPanelState.cards.length>0||this.infoPanelState.sections.length>0))?20:16,s=Math.max(8,this.rows-1);return Math.min(n,s)}getInfoPanelFixedRows(e){return e.layout==="viewport",e.subtitle?5:4}getSelectedInfoPanelSection(e){return e.sections.length===0?null:e.sections[Math.max(0,Math.min(e.selectedSectionIndex,e.sections.length-1))]??null}getEditableSplitPane(e){return e.split?e.focusPane==="sections"&&e.split.left.editable?{pane:"left",editable:e.split.left.editable}:e.focusPane==="content"&&e.split.right.editable?{pane:"right",editable:e.split.right.editable}:null:null}hasStructuredInfoPanel(e){return e.cards.length>0||e.sections.length>0||!!e.split}isInfoPanelEditDirty(e){return e.lines.join(`
|
|
127
|
+
`)!==e.originalValue}getInfoPanelFooterHint(e){return e.editing?e.editing.saving?"Saving changes...":e.editing.confirmDiscard&&this.isInfoPanelEditDirty(e.editing)?"Unsaved changes \xB7 Esc again discard \xB7 Ctrl+S save \xB7 Ctrl+Z undo \xB7 Ctrl+Y redo":e.editing.error?`Edit mode \xB7 Ctrl+S save \xB7 Ctrl+Z undo \xB7 Ctrl+Y redo \xB7 ${e.editing.error}`:this.isInfoPanelEditDirty(e.editing)?"Edit mode \xB7 Unsaved changes \xB7 Ctrl+S save \xB7 Ctrl+Z undo \xB7 Ctrl+Y redo \xB7 Esc cancel \xB7 Enter newline":"Edit mode \xB7 Ctrl+S save \xB7 Ctrl+Z undo \xB7 Ctrl+Y redo \xB7 Esc cancel \xB7 Enter newline":e.assistant?.submitting?"Applying scoped file edit...":e.draft?"Agent draft ready | Ctrl+S accept/save | Ctrl+R revert | Enter edit | Tab chat":e.assistant&&e.focusPane==="assistant"?e.assistant.inputBuffer.length>0?"Enter send | Shift+Enter newline | Tab file | Esc clear":"Type request for this file | Enter send | Tab file | Esc close":e.notice?this.getSelectedInfoPanelSection(e)?.editable?`${e.notice} \xB7 Enter edit \xB7 ${e.footerHint}`:`${e.notice} \xB7 ${e.footerHint}`:this.getSelectedInfoPanelSection(e)?.editable?`Enter edit \xB7 ${e.footerHint}`:this.getEditableSplitPane(e)?`Enter edit \xB7 ${e.footerHint}`:e.footerHint}startInfoPanelEditing(){if(!this.infoPanelState||this.infoPanelState.editing)return;let e=this.getSelectedInfoPanelSection(this.infoPanelState);if(!e?.editable)return;let n=this.getInfoPanelSectionDisplayValue(this.infoPanelState,e)??e.editable.value,s=n.replace(/\r\n/g,`
|
|
128
|
+
`).split(`
|
|
129
|
+
`),r=n.replace(/\r\n/g,`
|
|
130
|
+
`),o=e.editable.initialCursor==="start",i=o?0:Math.max(0,s.length-1),a=o?0:s[i]?.length??0;this.infoPanelState.editing={target:"section",sectionId:e.id,lines:s,originalValue:r,cursorRow:i,cursorCol:a,preferredCol:a,saving:!1,confirmDiscard:!1,undoStack:[],redoStack:[]},this.infoPanelState.notice=void 0,this.infoPanelState.focusPane="content",this.infoPanelState.scrollOffset=0,this.drawInfoPanelUI()}startSplitPaneEditing(){if(!this.infoPanelState||this.infoPanelState.editing)return;let e=this.getEditableSplitPane(this.infoPanelState);if(!e)return;let n=e.editable.value.replace(/\r\n/g,`
|
|
131
|
+
`),s=n.split(`
|
|
132
|
+
`),r=e.editable.initialCursor==="start",o=r?0:Math.max(0,s.length-1),i=r?0:s[o]?.length??0;this.infoPanelState.editing={target:e.pane==="left"?"split-left":"split-right",lines:s,originalValue:n,cursorRow:o,cursorCol:i,preferredCol:i,saving:!1,confirmDiscard:!1,undoStack:[],redoStack:[]},this.infoPanelState.notice=void 0,this.infoPanelState.focusPane=e.pane==="left"?"sections":"content",this.syncInfoPanelEditScroll(this.getInfoPanelEditVisibleRows()),this.drawInfoPanelUI()}cancelInfoPanelEditing(){this.infoPanelState?.editing&&(this.infoPanelState.editing=null,this.drawInfoPanelUI())}async saveInfoPanelEditing(){if(!this.infoPanelState?.editing)return;let e=this.infoPanelState,n=e.editing;if(n){n.saving=!0,n.error=void 0,this.drawInfoPanelUI();try{let s=n.lines.join(`
|
|
133
|
+
`),r;if(n.target==="section"){let o=e.sections.find(i=>i.id===n.sectionId);if(!o?.editable)return;r=await o.editable.onSave(s),o.editable.value=s,o.lines=r?.contentLines??n.lines.slice(),e.draft?.sectionId===o.id&&(e.draft=null)}else{let o=n.target==="split-left"?e.split?.left:e.split?.right;if(!o?.editable)return;r=await o.editable.onSave(s),o.editable.value=s,o.lines=o.editable.previewLines(s)}if(r?.summary!==void 0)if(n.target==="section"){let o=e.sections.find(i=>i.id===n.sectionId);o&&(o.summary=r.summary)}else n.target==="split-left"&&e.split?e.split.left.summary=r.summary:n.target==="split-right"&&e.split&&(e.split.right.summary=r.summary);r?.cards&&(e.cards=r.cards),r?.sections&&(e.sections=r.sections),r?.split&&(e.split=r.split),r?.panelLines&&(e.lines=r.panelLines),e.editing=null,e.notice="Saved changes.",e.focusPane="content",e.scrollOffset=0,this.drawInfoPanelUI()}catch(s){n.saving=!1,n.error=s instanceof Error?s.message:String(s),this.drawInfoPanelUI()}}}syncInfoPanelEditScroll(e){if(!this.infoPanelState?.editing)return;let{cursorRow:n,target:s}=this.infoPanelState.editing,r=s==="split-right"?"secondaryScrollOffset":"scrollOffset",o=this.infoPanelState[r];n<o?this.infoPanelState[r]=n:n>=o+e&&(this.infoPanelState[r]=Math.max(0,n-e+1))}getInfoPanelEditVisibleRows(){let e=this.infoPanelState;if(!e)return 1;if(e.layout==="viewport"&&e.singlePane)return this.getSinglePaneInfoPanelMetrics(e).contentBodyRows;let n=this.hasStructuredInfoPanel(e),s=this.getInfoPanelRows(),r=this.getInfoPanelFixedRows(e),o=this.renderCols(),i=n&&o>=(e.layout==="viewport"?108:92),a=o>=108?4:o>=82?3:o>=56?2:1,l=n&&e.cards.length>0?e.layout==="viewport"?Math.ceil(e.cards.length/a)*4:3:0,c=3,u=e.layout==="viewport"?1:Math.max(this.rows-s+1,1),p=n?u+c+(l>0?l:0):1,f=e.layout==="viewport"?this.rows:u+s-1,m=n?Math.max(1,f-p):Math.max(1,s-r);if(e.split){let g=o>=(e.layout==="viewport"?98:88),b=g?m:Math.max(7,Math.min(10,Math.floor(m*.4))),v=g?m:Math.max(7,m-b-1),w=Math.max(1,b-5),P=Math.max(1,v-5);if(e.editing?.target==="split-left")return w;if(e.editing?.target==="split-right")return P}if(n){let g=i?m:Math.max(5,Math.min(8,Math.floor(m*.28))),b=i?m:Math.max(6,m-g-1);return!i&&g+1+b>m&&(g=Math.max(5,m-b-1)),Math.max(1,b-5)}return Math.max(1,s-r)}createInfoPanelEditSnapshot(e){return{lines:e.lines.slice(),cursorRow:e.cursorRow,cursorCol:e.cursorCol,preferredCol:e.preferredCol}}restoreInfoPanelEditSnapshot(e,n,s){e.lines=n.lines.slice(),e.cursorRow=n.cursorRow,e.cursorCol=n.cursorCol,e.preferredCol=n.preferredCol,e.confirmDiscard=!1,e.error=void 0,this.syncInfoPanelEditScroll(s)}pushInfoPanelEditUndoSnapshot(e){e.undoStack.push(this.createInfoPanelEditSnapshot(e)),e.undoStack.length>this.INFO_PANEL_EDIT_UNDO_LIMIT&&e.undoStack.shift(),e.redoStack=[]}undoInfoPanelEdit(e){let n=this.infoPanelState?.editing;if(!n||n.undoStack.length===0)return!1;let s=n.undoStack.pop();return s?(n.redoStack.push(this.createInfoPanelEditSnapshot(n)),this.restoreInfoPanelEditSnapshot(n,s,e),!0):!1}redoInfoPanelEdit(e){let n=this.infoPanelState?.editing;if(!n||n.redoStack.length===0)return!1;let s=n.redoStack.pop();return s?(n.undoStack.push(this.createInfoPanelEditSnapshot(n)),this.restoreInfoPanelEditSnapshot(n,s,e),!0):!1}moveInfoPanelEditCursor(e,n){let s=this.infoPanelState?.editing;if(!s)return;s.confirmDiscard=!1;let r=s.lines[s.cursorRow]??"";if(e==="left"){s.cursorCol>0?s.cursorCol-=1:s.cursorRow>0&&(s.cursorRow-=1,s.cursorCol=s.lines[s.cursorRow]?.length??0),s.preferredCol=s.cursorCol,this.syncInfoPanelEditScroll(n);return}if(e==="right"){s.cursorCol<r.length?s.cursorCol+=1:s.cursorRow<s.lines.length-1&&(s.cursorRow+=1,s.cursorCol=0),s.preferredCol=s.cursorCol,this.syncInfoPanelEditScroll(n);return}if(e==="up"){if(s.cursorRow>0){s.cursorRow-=1;let o=s.lines[s.cursorRow]??"";s.cursorCol=Math.min(o.length,s.preferredCol)}this.syncInfoPanelEditScroll(n);return}if(s.cursorRow<s.lines.length-1){s.cursorRow+=1;let o=s.lines[s.cursorRow]??"";s.cursorCol=Math.min(o.length,s.preferredCol)}this.syncInfoPanelEditScroll(n)}insertInfoPanelEditText(e,n){let s=this.infoPanelState?.editing;if(!s||s.saving)return;s.confirmDiscard=!1;let r=e.replace(/\r\n/g,`
|
|
134
|
+
`);if(r.replace(/\r/g,"").length!==0){this.pushInfoPanelEditUndoSnapshot(s);for(let o of r){if(o==="\r")continue;if(o===`
|
|
135
|
+
`){let a=s.lines[s.cursorRow]??"",l=a.slice(0,s.cursorCol),c=a.slice(s.cursorCol);s.lines.splice(s.cursorRow,1,l,c),s.cursorRow+=1,s.cursorCol=0,s.preferredCol=0;continue}let i=s.lines[s.cursorRow]??"";s.lines[s.cursorRow]=i.slice(0,s.cursorCol)+o+i.slice(s.cursorCol),s.cursorCol+=1,s.preferredCol=s.cursorCol}this.syncInfoPanelEditScroll(n)}}backspaceInfoPanelEdit(e){let n=this.infoPanelState?.editing;if(!(!n||n.saving)){if(n.confirmDiscard=!1,n.cursorCol>0){this.pushInfoPanelEditUndoSnapshot(n);let s=n.lines[n.cursorRow]??"";n.lines[n.cursorRow]=s.slice(0,n.cursorCol-1)+s.slice(n.cursorCol),n.cursorCol-=1,n.preferredCol=n.cursorCol,this.syncInfoPanelEditScroll(e);return}if(n.cursorRow>0){this.pushInfoPanelEditUndoSnapshot(n);let s=n.lines[n.cursorRow]??"",r=n.cursorRow-1,o=n.lines[r]??"";n.lines.splice(r,2,o+s),n.cursorRow=r,n.cursorCol=o.length,n.preferredCol=n.cursorCol,this.syncInfoPanelEditScroll(e)}}}deleteInfoPanelEdit(e){let n=this.infoPanelState?.editing;if(!n||n.saving)return;n.confirmDiscard=!1;let s=n.lines[n.cursorRow]??"";if(n.cursorCol<s.length){this.pushInfoPanelEditUndoSnapshot(n),n.lines[n.cursorRow]=s.slice(0,n.cursorCol)+s.slice(n.cursorCol+1),this.syncInfoPanelEditScroll(e);return}if(n.cursorRow<n.lines.length-1){this.pushInfoPanelEditUndoSnapshot(n);let r=n.lines[n.cursorRow+1]??"";n.lines.splice(n.cursorRow,2,s+r),this.syncInfoPanelEditScroll(e)}}positionInfoPanelEditCursor(e,n,s,r,o=this.infoPanelState?.scrollOffset??0){let i=this.infoPanelState?.editing;if(!i||i.saving)return;let a=Math.max(1,s-4),l=Math.max(0,Math.min(Math.max(0,r-1),i.cursorRow-o)),c=this.getInfoPanelEditHorizontalOffset(a),u=Math.max(0,Math.min(a-1,i.cursorCol-c));process.stdout.write(d.moveTo(e+4+l,n+2+u)+d.showCursor())}getInfoPanelEditHorizontalOffset(e){let n=this.infoPanelState?.editing;return n?e<=1?Math.max(0,n.cursorCol):Math.max(0,n.cursorCol-e+1):0}getRenderedSplitPaneLines(e,n,s){return n===s&&this.infoPanelState?.editing&&e.editable?e.editable.previewLines(this.infoPanelState.editing.lines.join(`
|
|
136
|
+
`)):e.lines}getSinglePaneInfoPanelMetrics(e){let n=this.renderCols(),s=2,r=1+s,o=this.rows,i=!!(e.assistant&&e.focusPane==="assistant"&&!e.editing),a=i?3:0,l=r+a+1,c=e.assistant?i?Math.max(7,o-l):Math.max(7,Math.min(11,Math.floor(this.rows*.3))):0,u=c>0?i?l:Math.max(r+5,o-c):o,p=i?a:Math.max(5,c>0?u-r-1:o-r),f=i?1:Math.max(1,p-5);return{renderCols:n,headerRows:s,bodyTop:r,contentBoxRows:p,contentBodyRows:f,assistantRows:c,assistantTop:u,footerRow:o}}getSinglePaneContentSection(e){return e.sections[0]??null}getInfoPanelCurrentEditableValue(e){let n=this.getSinglePaneContentSection(e)??this.getSelectedInfoPanelSection(e);return n&&e.draft?.sectionId===n.id?e.draft.proposedValue:n?.editable?n.editable.value:this.getEditableSplitPane(e)?.editable.value}getInfoPanelSectionDisplayValue(e,n){if(n)return e.draft?.sectionId===n.id?e.draft.proposedValue:n.editable?.value??n.lines.join(`
|
|
137
|
+
`)}getInfoPanelSectionDisplayLines(e,n){let s=this.getInfoPanelSectionDisplayValue(e,n);return s!==void 0?s.replace(/\r\n/g,`
|
|
138
|
+
`).split(`
|
|
139
|
+
`):n?.lines??e.lines}buildInfoPanelAssistantBoxLines(e,n,s){let r=e.assistant;if(!r||n<=2||s<=4)return[];let o=e.focusPane==="assistant",i=o?be:x,a=Math.max(1,n),l=Math.max(1,a-2),c=this.getSinglePaneContentSection(e),u=e.title||c?.title||"current file",p=r.submitting?"XENO file agent \xB7 working":"XENO file agent",m=`${e.draft?"[FILE DRAFT]":"[FILE ONLY]"} ${u}`,g=o?be(p):x(p),b=x(this.clip(m,Math.max(1,Math.floor(a*.45)))),v=Math.max(1,a-se(g).length-se(b).length-1),w=[];w.push(` ${g}${" ".repeat(v)}${b}`);let P=Math.max(0,s-4),C=r.messages.slice(-Math.max(1,r.messages.length)),$=C.length===0,E=(W,Z,le)=>{let ce=[],X=Z,q=Q=>{let ye=()=>Math.max(1,a-se(X).length),ee=Q.trim().split(/\s+/).filter(Boolean);if(ee.length===0){ce.push(X.trimEnd()),X=le;return}let Se="";for(let me of ee){let de=ye(),Ee=Se.length>0?`${Se} ${me}`:me;if(se(Ee).length<=de){Se=Ee;continue}if(Se.length>0){ce.push(`${X}${Se}`),X=le,Se=me;continue}ce.push(`${X}${this.clip(me,de)}`),X=le,Se=""}Se.length>0&&(ce.push(`${X}${Se}`),X=le)};for(let Q of W.replace(/\r\n/g,`
|
|
140
|
+
`).split(`
|
|
141
|
+
`))q(Q);return ce.length>0?ce:[Z.trimEnd()]},T=$?[x("Private file chat. Requests here only target this opened file."),x("Edits are staged as drafts until Ctrl+S accepts them.")].slice(0,P):C.flatMap(W=>{let Z=W.role==="user"?be("\u203A"):W.role==="error"?qe.red("!"):W.role==="tool"?x("\u25C6"):be("\u25A0"),le=W.role==="user"?"you":W.role==="error"?"error":W.role==="tool"?"tool":"xeno",ce=` ${Z} ${x(le)} `,X=` ${x("\u2502")} ${" ".repeat(le.length)} `;return E(W.content,ce,X)}).slice(-P);for(let W=0;W<P;W++){let Z=T[W]??"";w.push(this.clip(Z,a).padEnd(a," "))}w.push(i("\u2500".repeat(a)));let I=r.inputBuffer.length>0?r.inputBuffer.split(`
|
|
142
|
+
`).at(-1)??"":x(r.placeholder),re=o?be("\u203A"):x("\u203A"),ae=r.submitting?x("working"):x("private"),N=se(ae).length,y=Math.max(1,l-N-4),oe=`${re} ${this.clip(I,y)}`,K=Math.max(1,l-se(oe).length-N);for(w.push(`${oe}${" ".repeat(K)}${ae}`),w.push(i("\u2500".repeat(a)));w.length<s;)w.splice(Math.max(1,w.length-3),0," ".repeat(a));return w.slice(0,s)}buildCollapsedFileAttachmentLines(e,n,s,r,o){if(s<=2||r<=0)return[];let i=x,a=Math.max(1,s-4),l=e.title||n?.title||"current file",u=`${e.draft?.sectionId===n?.id?"FILE DRAFT":"FILE ATTACHED"} \xB7 ${l} \xB7 ${Math.max(1,o)} lines`,p="Tab expand \xB7 Enter edit after expand",f=Math.max(1,a-se(x(p)).length-3),m=be(this.clip(u,f)),g=x(p),b=Math.max(1,a-se(m).length-se(g).length),v=`${m}${" ".repeat(b)}${g}`;return[i(`\u256D${"\u2500".repeat(Math.max(0,s-2))}\u256E`),`${i("\u2502")} ${v.padEnd(a," ")} ${i("\u2502")}`,i(`\u2570${"\u2500".repeat(Math.max(0,s-2))}\u256F`)].slice(0,r)}drawSinglePaneInfoViewport(){if(!this.infoPanelState)return;let e=this.infoPanelState,n=this.getSinglePaneInfoPanelMetrics(e),s=this.getSinglePaneContentSection(e),r=!!(e.editing&&s?.editable&&e.editing.sectionId===s.id),o=!!(e.assistant&&e.focusPane==="assistant"&&!r),i=r&&e.editing?e.editing.lines:this.getInfoPanelSectionDisplayLines(e,s),a=r?i.slice():this.wrapInfoLines(i,Math.max(8,n.renderCols-4)),l=o?0:Math.max(0,a.length-n.contentBodyRows);r&&this.syncInfoPanelEditScroll(n.contentBodyRows),e.scrollOffset=Math.min(e.scrollOffset,l);let c=o?[]:a.slice(e.scrollOffset,e.scrollOffset+n.contentBodyRows),u=e.scrollOffset>0,p=e.scrollOffset+n.contentBodyRows<a.length,f=1,m=d.hideCursor()+d.disableWrap();for(let E=1;E<=this.rows;E++)m+=d.moveTo(E,1)+d.eraseLine();let g=qe.bold(this.clip(e.title,Math.max(1,Math.floor(n.renderCols*.55)))),b=e.subtitle?x(this.clip(e.subtitle,Math.max(1,Math.floor(n.renderCols*.4)))):"",v=b?` ${x("|")} `:"",w=x(`${Math.min(e.scrollOffset+n.contentBodyRows,Math.max(1,a.length))}/${Math.max(1,a.length)}`),P=` ${g}${v}${b}`,C=Math.max(1,n.renderCols-se(P).length-se(w).length);m+=d.moveTo(f,1)+`${P}${" ".repeat(C)}${w}`,f++,m+=d.moveTo(f,1)+be("\u2500".repeat(n.renderCols)),f++;let $=o?this.buildCollapsedFileAttachmentLines(e,s,Math.max(10,n.renderCols),n.contentBoxRows,a.length):this.buildInfoContentBoxLines(s?.title??"File",r?"editing":e.draft?.sectionId===s?.id?`agent draft - ${a.length} lines`:s?.summary??`${a.length} lines`,Math.max(10,n.renderCols),n.contentBoxRows,c,u,p,e.focusPane!=="assistant",r);for(let E=0;E<n.contentBoxRows;E++)m+=d.moveTo(n.bodyTop+E,1)+($[E]??" ".repeat(n.renderCols));if(e.assistant&&n.assistantRows>0){let E=this.buildInfoPanelAssistantBoxLines(e,n.renderCols,n.assistantRows);for(let T=0;T<n.assistantRows;T++)m+=d.moveTo(n.assistantTop+T,1)+(E[T]??" ".repeat(n.renderCols))}if(m+=d.moveTo(n.footerRow,1)+d.eraseLine(),m+=` ${x(this.clip(this.getInfoPanelFooterHint(e),Math.max(1,n.renderCols-1)))}`,m+=d.enableWrap(),process.stdout.write(m),r){this.positionInfoPanelEditCursor(n.bodyTop,1,n.renderCols,n.contentBodyRows,e.scrollOffset);return}if(e.assistant&&e.focusPane==="assistant"){let E=Math.max(1,n.renderCols-2),T=e.assistant.inputBuffer.split(`
|
|
143
|
+
`).at(-1)??"",I=Math.max(0,Math.min(T.length,e.assistant.cursorPos)),re=Math.max(0,Math.min(E-3,I));process.stdout.write(d.moveTo(n.assistantTop+n.assistantRows-2,3+re)+d.showCursor())}}drawInfoPanelUI(){if(!this.infoPanelState)return;if(this.infoPanelState.layout==="viewport"&&this.infoPanelState.singlePane){this.drawSinglePaneInfoViewport();return}if(this.infoPanelState.layout==="viewport"&&this.hasStructuredInfoPanel(this.infoPanelState)){if(this.infoPanelState.split){this.drawSplitInfoViewport();return}this.drawStructuredInfoViewport();return}if(this.infoPanelState.layout!=="viewport"&&this.hasStructuredInfoPanel(this.infoPanelState)){if(this.infoPanelState.split){this.drawSplitInfoFooter();return}this.drawStructuredInfoFooter();return}let e=this.infoPanelState,n=this.getInfoPanelRows(),s=e.layout==="viewport"?1:Math.max(this.rows-n+1,1),r=!!e.subtitle,o=this.getInfoPanelFixedRows(e),i=Math.max(1,n-o),a=Math.max(0,e.lines.length-i);e.scrollOffset>a&&(e.scrollOffset=a);let l=e.lines.slice(e.scrollOffset,e.scrollOffset+i),c=e.scrollOffset>0,u=e.scrollOffset+i<e.lines.length,p=s,f=d.hideCursor()+d.disableWrap(),m=e.layout==="viewport"?1:this.outputBottom+1;for(let C=m;C<=this.rows;C++)f+=d.moveTo(C,1)+d.eraseLine();f+=d.moveTo(p,1)+d.eraseLine(),f+=be("\u2500".repeat(this.renderCols())),p++,f+=d.moveTo(p,1)+d.eraseLine(),f+=` ${x("\u2500".repeat(Math.max(0,this.cols-1)))}`,p++;let g=qe.bold(e.title),b=x(`${Math.min(e.scrollOffset+i,e.lines.length)}/${e.lines.length}`),v=se(g).length,w=se(b).length,P=Math.max(1,this.cols-v-w-1);f+=d.moveTo(p,1)+d.eraseLine(),f+=` ${g}${" ".repeat(P)}${b}`,p++,r&&(f+=d.moveTo(p,1)+d.eraseLine(),f+=` ${x(this.clip(e.subtitle,Math.max(1,this.cols-1)))}`,p++);for(let C=0;C<i;C++){f+=d.moveTo(p,1)+d.eraseLine();let $=l[C]??"";if($){let E=" ";C===0&&c?E="\u2191":C===i-1&&u&&(E="\u2193");let T=E===" "?" ":`${x(E)} `;f+=` ${T}${this.clip($,Math.max(1,this.cols-3))}`}p++}f+=d.moveTo(p,1)+d.eraseLine(),f+=` ${x(this.clip(this.getInfoPanelFooterHint(e),Math.max(1,this.cols-1)))}`,f+=d.enableWrap(),process.stdout.write(f)}drawStructuredInfoViewport(){if(!this.infoPanelState)return;let e=this.infoPanelState,n=this.renderCols();if(this.rows<18||n<68){this.drawLegacyInfoViewport();return}let s=e.sections.length>0?e.sections[Math.max(0,Math.min(e.selectedSectionIndex,e.sections.length-1))]:null,r=!!(e.editing&&s&&e.editing.sectionId===s.id),o=n>=96?4:n>=74?3:n>=52?2:1,i=2,a=n>=140?28:n>=104?26:24,l=Math.max(18,Math.min(a,Math.floor((n-(o-1)*i)/o))),c=e.cards.length>0?Math.ceil(e.cards.length/o)*4:0,p=1+3+(c>0?c+1:0),f=this.rows,m=Math.max(6,f-p),g=n>=108,b=g?Math.max(24,Math.min(32,Math.floor(n*.27))):n,v=g?2:0,w=g?Math.max(28,n-b-v):n,P=g?m:Math.max(5,Math.min(8,Math.floor(m*.28))),C=g?m:Math.max(6,m-P-1);!g&&P+1+C>m&&(P=Math.max(5,m-C-1));let $=Math.max(1,P-5),E=Math.max(1,C-5),T=r&&e.editing?e.editing.lines:s?s.lines:e.lines,I=r?T.slice():this.wrapInfoLines(T,Math.max(8,w-4)),re=Math.max(0,I.length-E);r&&this.syncInfoPanelEditScroll(E),e.scrollOffset>re&&(e.scrollOffset=re);let ae=I.slice(e.scrollOffset,e.scrollOffset+E),N=e.scrollOffset>0,y=e.scrollOffset+E<I.length,oe=this.buildInfoSectionRailLines(e,$,Math.max(8,b-4)),K=1,W=d.hideCursor()+d.disableWrap();for(let te=1;te<=this.rows;te++)W+=d.moveTo(te,1)+d.eraseLine();let Z=e.sections.length>0?`${Math.min(e.selectedSectionIndex+1,e.sections.length)}/${e.sections.length}`:`${Math.min(e.scrollOffset+E,Math.max(1,I.length))}/${Math.max(1,I.length)}`,le=s?.summary?`${s.title} - ${s.summary}`:"Memory context inspector",ce=[e.title,e.subtitle].filter(te=>!!(te&&te.trim().length>0)),X=x(this.clip(le,Math.max(12,Math.floor((n-1)*.38)))),q=Math.max(1,n-1-se(X).length-1),Q=qe.bold(this.clip(ce.join(" | "),q)),ye=Math.max(1,n-1-se(Q).length-se(X).length);W+=d.moveTo(K,1)+` ${Q}${" ".repeat(ye)}${X}`,K++,W+=d.moveTo(K,1)+be("\u2500".repeat(n)),K++;let ee=x(Z),Se=" ".repeat(Math.max(0,n-1-se(ee).length));if(W+=d.moveTo(K,1)+` ${Se}${ee}`,K++,e.cards.length>0){let te=Math.ceil(e.cards.length/o);for(let Re=0;Re<te;Re++){let Ce=[],Ae=[],xe=[],Te=[];for(let Y=0;Y<o;Y++){let D=Re*o+Y,H=e.cards[D];if(H){let M=this.clip(H.title.toUpperCase(),Math.max(1,l-4)).padEnd(Math.max(1,l-4)," "),U=this.clip(H.value,Math.max(1,l-4)).padEnd(Math.max(1,l-4)," ");Ce.push(x(`\u256D${"\u2500".repeat(Math.max(0,l-2))}\u256E`)),Ae.push(`${x("\u2502")} ${x(M)} ${x("\u2502")}`),xe.push(`${x("\u2502")} ${be(U)} ${x("\u2502")}`),Te.push(x(`\u2570${"\u2500".repeat(Math.max(0,l-2))}\u256F`))}else{let M=" ".repeat(l);Ce.push(M),Ae.push(M),xe.push(M),Te.push(M)}}let Ne=Ce.join(" ".repeat(i)),Xe=Ae.join(" ".repeat(i)),He=xe.join(" ".repeat(i)),rt=Te.join(" ".repeat(i));W+=d.moveTo(K,1)+Ne,K++,W+=d.moveTo(K,1)+Xe,K++,W+=d.moveTo(K,1)+He,K++,W+=d.moveTo(K,1)+rt,K++}W+=d.moveTo(K,1)+d.eraseLine(),K++}let me=s?.title??"Details",de=r?"editing":s?.summary??`${I.length} lines`,Ee=this.buildInfoContentBoxLines(me,de,Math.max(10,w),Math.max(3,C),ae,N,y,e.focusPane==="content",r),pe=this.buildInfoContentBoxLines("Sections",e.sections.length>0?`${e.sections.length} containers`:"No sections",Math.max(10,b),Math.max(3,P),oe,!1,!1,e.focusPane==="sections");if(g)for(let te=0;te<m;te++){let Re=pe[te]??" ".repeat(b),Ce=Ee[te]??" ".repeat(w);W+=d.moveTo(p+te,1)+Re+" ".repeat(v)+Ce}else{for(let Re=0;Re<P;Re++)W+=d.moveTo(p+Re,1)+(pe[Re]??" ".repeat(b));let te=p+P+1;W+=d.moveTo(te-1,1)+d.eraseLine();for(let Re=0;Re<C;Re++)W+=d.moveTo(te+Re,1)+(Ee[Re]??" ".repeat(w))}if(W+=d.moveTo(f,1)+d.eraseLine(),W+=` ${x(this.clip(this.getInfoPanelFooterHint(e),Math.max(1,n-1)))}`,W+=d.enableWrap(),process.stdout.write(W),r){let te=g?p:p+P+1,Re=g?b+v+1:1;this.positionInfoPanelEditCursor(te,Re,w,E,e.scrollOffset)}}drawSplitInfoViewport(){if(!this.infoPanelState?.split)return;let e=this.infoPanelState,n=e.split,s=e.editing?.target==="split-left"||e.editing?.target==="split-right"?e.editing.target:null,r=this.renderCols();if(this.rows<18||r<68){this.drawLegacyInfoViewport();return}let o=r>=96?4:r>=74?3:r>=52?2:1,i=2,a=r>=140?28:r>=104?26:24,l=Math.max(18,Math.min(a,Math.floor((r-(o-1)*i)/o))),c=e.cards.length>0?Math.ceil(e.cards.length/o)*4:0,p=1+3+(c>0?c+1:0),f=this.rows,m=Math.max(6,f-p),g=r>=98,b=g?Math.max(30,Math.min(42,Math.floor(r*.34))):r,v=g?2:0,w=g?Math.max(34,r-b-v):r,P=g?m:Math.max(7,Math.min(10,Math.floor(m*.4))),C=g?m:Math.max(7,m-P-1);!g&&P+1+C>m&&(P=Math.max(6,m-C-1));let $=Math.max(1,P-5),E=Math.max(1,C-5),T=this.getRenderedSplitPaneLines(n.left,s,"split-left"),I=this.getRenderedSplitPaneLines(n.right,s,"split-right"),re=this.wrapInfoLines(T,Math.max(8,b-4)),ae=this.wrapInfoLines(I,Math.max(8,w-4)),N=Math.max(0,re.length-$),y=Math.max(0,ae.length-E);e.scrollOffset=Math.min(e.scrollOffset,N),e.secondaryScrollOffset=Math.min(e.secondaryScrollOffset,y);let oe=re.slice(e.scrollOffset,e.scrollOffset+$),K=ae.slice(e.secondaryScrollOffset,e.secondaryScrollOffset+E),W=e.scrollOffset>0,Z=e.scrollOffset+$<re.length,le=e.secondaryScrollOffset>0,ce=e.secondaryScrollOffset+E<ae.length,X=1,q=d.hideCursor()+d.disableWrap();for(let Ce=1;Ce<=this.rows;Ce++)q+=d.moveTo(Ce,1)+d.eraseLine();let Q=e.focusPane==="sections"?"Details":"Preview",ye=qe.bold(e.title),ee=e.subtitle?x(this.clip(e.subtitle,Math.max(1,Math.floor((r-1)*.55)))):"",Se=e.subtitle?` ${x("\u2502")} `:"",me=ee?`${Se}${ee}`:"",de=Math.max(1,r-1-se(me).length);q+=d.moveTo(X,1)+` ${this.clip(se(ye),de)}${me}`,X++,q+=d.moveTo(X,1)+be("\u2500".repeat(r)),X++;let Ee=x(Q),pe=" ".repeat(Math.max(0,r-1-se(Ee).length));if(q+=d.moveTo(X,1)+` ${pe}${Ee}`,X++,e.cards.length>0){let Ce=Math.ceil(e.cards.length/o);for(let Ae=0;Ae<Ce;Ae++){let xe=[],Te=[],Ne=[],Xe=[];for(let H=0;H<o;H++){let M=Ae*o+H,U=e.cards[M];if(U){let G=this.clip(U.title.toUpperCase(),Math.max(1,l-4)).padEnd(Math.max(1,l-4)," "),fe=this.clip(U.value,Math.max(1,l-4)).padEnd(Math.max(1,l-4)," ");xe.push(x(`\u256D${"\u2500".repeat(Math.max(0,l-2))}\u256E`)),Te.push(`${x("\u2502")} ${x(G)} ${x("\u2502")}`),Ne.push(`${x("\u2502")} ${be(fe)} ${x("\u2502")}`),Xe.push(x(`\u2570${"\u2500".repeat(Math.max(0,l-2))}\u256F`))}else{let G=" ".repeat(l);xe.push(G),Te.push(G),Ne.push(G),Xe.push(G)}}let He=xe.join(" ".repeat(i)),rt=Te.join(" ".repeat(i)),Y=Ne.join(" ".repeat(i)),D=Xe.join(" ".repeat(i));q+=d.moveTo(X,1)+He,X++,q+=d.moveTo(X,1)+rt,X++,q+=d.moveTo(X,1)+Y,X++,q+=d.moveTo(X,1)+D,X++}q+=d.moveTo(X,1)+d.eraseLine(),X++}let te=this.buildInfoContentBoxLines(n.left.title,n.left.summary??"",Math.max(10,b),Math.max(3,P),oe,W,Z,e.focusPane==="sections",s==="split-left"),Re=this.buildInfoContentBoxLines(n.right.title,n.right.summary??"",Math.max(10,w),Math.max(3,C),K,le,ce,e.focusPane==="content",s==="split-right");if(g)for(let Ce=0;Ce<m;Ce++){let Ae=te[Ce]??" ".repeat(b),xe=Re[Ce]??" ".repeat(w);q+=d.moveTo(p+Ce,1)+Ae+" ".repeat(v)+xe}else{for(let Ae=0;Ae<P;Ae++)q+=d.moveTo(p+Ae,1)+(te[Ae]??" ".repeat(b));let Ce=p+P+1;q+=d.moveTo(Ce-1,1)+d.eraseLine();for(let Ae=0;Ae<C;Ae++)q+=d.moveTo(Ce+Ae,1)+(Re[Ae]??" ".repeat(w))}if(q+=d.moveTo(f,1)+d.eraseLine(),q+=` ${x(this.clip(this.getInfoPanelFooterHint(e),Math.max(1,r-1)))}`,q+=d.enableWrap(),process.stdout.write(q),s){let Ce=s==="split-left",Ae=g||Ce?p:p+P+1,xe=g?Ce?1:b+v+1:1,Te=Ce?b:w;this.positionInfoPanelEditCursor(Ae,xe,Te,Ce?$:E,Ce?e.scrollOffset:e.secondaryScrollOffset)}}drawSplitInfoFooter(){if(!this.infoPanelState?.split)return;let e=this.infoPanelState,n=e.split,s=e.editing?.target==="split-left"||e.editing?.target==="split-right"?e.editing.target:null,r=this.getInfoPanelRows(),o=Math.max(this.rows-r+1,1),i=this.renderCols(),a=e.cards.length>0?3:0,c=o+3+(a>0?a:0),u=this.rows,p=Math.max(1,u-c),f=i>=88,m=f?Math.max(28,Math.min(40,Math.floor(i*.34))):i,g=f?2:0,b=f?Math.max(30,i-m-g):i,v=f?p:Math.max(7,Math.min(10,Math.floor(p*.42))),w=f?p:Math.max(7,p-v-1);!f&&v+1+w>p&&(v=Math.max(6,p-w-1));let P=Math.max(1,v-5),C=Math.max(1,w-5),$=this.getRenderedSplitPaneLines(n.left,s,"split-left"),E=this.getRenderedSplitPaneLines(n.right,s,"split-right"),T=this.wrapInfoLines($,Math.max(8,m-4)),I=this.wrapInfoLines(E,Math.max(8,b-4)),re=Math.max(0,T.length-P),ae=Math.max(0,I.length-C);e.scrollOffset=Math.min(e.scrollOffset,re),e.secondaryScrollOffset=Math.min(e.secondaryScrollOffset,ae);let N=T.slice(e.scrollOffset,e.scrollOffset+P),y=I.slice(e.secondaryScrollOffset,e.secondaryScrollOffset+C),oe=e.scrollOffset>0,K=e.scrollOffset+P<T.length,W=e.secondaryScrollOffset>0,Z=e.secondaryScrollOffset+C<I.length,le=o,ce=d.hideCursor()+d.disableWrap();for(let pe=o;pe<=this.rows;pe++)ce+=d.moveTo(pe,1)+d.eraseLine();let X=qe.bold(e.title),q=e.subtitle?x(this.clip(e.subtitle,Math.max(1,Math.floor((i-1)*.6)))):"",Q=e.subtitle?` ${x("\u2502")} `:"",ye=q?`${Q}${q}`:"",ee=Math.max(1,i-1-se(ye).length);ce+=d.moveTo(le,1)+be("\u2500".repeat(i)),le++,ce+=d.moveTo(le,1)+` ${this.clip(se(X),ee)}${ye}`,le++;let Se=x(e.focusPane==="sections"?"Details":"Preview"),me=" ".repeat(Math.max(0,i-1-se(Se).length));if(ce+=d.moveTo(le,1)+` ${me}${Se}`,le++,e.cards.length>0){let pe=this.buildInfoFooterCardStripBoxLines(e.cards,Math.max(3,i));for(let te of pe)ce+=d.moveTo(le,1)+d.eraseLine(),ce+=te,le++}let de=this.buildInfoContentBoxLines(n.left.title,n.left.summary??"",Math.max(10,m),Math.max(3,v),N,oe,K,e.focusPane==="sections",s==="split-left"),Ee=this.buildInfoContentBoxLines(n.right.title,n.right.summary??"",Math.max(10,b),Math.max(3,w),y,W,Z,e.focusPane==="content",s==="split-right");if(f)for(let pe=0;pe<p;pe++){let te=de[pe]??" ".repeat(m),Re=Ee[pe]??" ".repeat(b);ce+=d.moveTo(c+pe,1)+te+" ".repeat(g)+Re}else{for(let te=0;te<v;te++)ce+=d.moveTo(c+te,1)+(de[te]??" ".repeat(m));let pe=c+v+1;ce+=d.moveTo(pe-1,1)+d.eraseLine();for(let te=0;te<w;te++)ce+=d.moveTo(pe+te,1)+(Ee[te]??" ".repeat(b))}if(ce+=d.moveTo(u,1)+d.eraseLine(),ce+=` ${x(this.clip(this.getInfoPanelFooterHint(e),Math.max(1,i-1)))}`,ce+=d.enableWrap(),process.stdout.write(ce),s){let pe=s==="split-left",te=f||pe?c:c+v+1,Re=f?pe?1:m+g+1:1,Ce=pe?m:b;this.positionInfoPanelEditCursor(te,Re,Ce,pe?P:C,pe?e.scrollOffset:e.secondaryScrollOffset)}}drawStructuredInfoFooter(){if(!this.infoPanelState)return;let e=this.infoPanelState,n=this.getInfoPanelRows(),s=Math.max(this.rows-n+1,1),r=this.renderCols(),o=this.getSelectedInfoPanelSection(e),i=e.cards.length>0?3:0,l=s+3+(i>0?i:0),c=this.rows,u=Math.max(1,c-l),p=r>=92,f=p?Math.max(24,Math.min(30,Math.floor(r*.28))):r,m=p?2:0,g=p?Math.max(28,r-f-m):r,b=p?u:Math.max(5,Math.min(8,Math.floor(u*.32))),v=p?u:Math.max(6,u-b-1);!p&&b+1+v>u&&(b=Math.max(5,u-v-1));let w=Math.max(1,b-5),P=Math.max(1,v-5),C=o?.lines??e.lines,$=this.wrapInfoLines(C,Math.max(8,g-4)),E=Math.max(0,$.length-P);e.scrollOffset>E&&(e.scrollOffset=E);let T=$.slice(e.scrollOffset,e.scrollOffset+P),I=e.scrollOffset>0,re=e.scrollOffset+P<$.length,ae=this.buildInfoSectionRailLines(e,w,Math.max(8,f-4)),N=s,y=d.hideCursor()+d.disableWrap();for(let Q=s;Q<=this.rows;Q++)y+=d.moveTo(Q,1)+d.eraseLine();y+=d.moveTo(N,1)+be("\u2500".repeat(r)),N++;let oe=qe.bold(e.title),K=e.sections.length>0?`${Math.min(e.selectedSectionIndex+1,e.sections.length)}/${e.sections.length}`:`${Math.min(e.scrollOffset+P,Math.max(1,$.length))}/${Math.max(1,$.length)}`,W=x(K);if(e.subtitle){let Q=x(this.clip(e.subtitle,Math.max(1,Math.floor((r-1)*.6)))),ye=x("\u2502");y+=d.moveTo(N,1)+` ${oe} ${ye} ${Q}`}else y+=d.moveTo(N,1)+` ${oe}`;N++;let Z=" ".repeat(Math.max(0,r-1-se(W).length));if(y+=d.moveTo(N,1)+` ${Z}${W}`,N++,e.cards.length>0){let Q=this.buildInfoFooterCardStripBoxLines(e.cards,Math.max(3,r));for(let ye of Q)y+=d.moveTo(N,1)+d.eraseLine(),y+=ye,N++}let le=o?.title??"Details",ce=o?.summary??`${$.length} lines`,X=this.buildInfoContentBoxLines(le,ce,Math.max(10,g),Math.max(3,v),T,I,re,e.focusPane==="content"),q=this.buildInfoContentBoxLines("Sections",e.sections.length>0?`${e.sections.length} containers`:"No sections",Math.max(10,f),Math.max(3,b),ae,!1,!1,e.focusPane==="sections");if(p)for(let Q=0;Q<u;Q++){let ye=q[Q]??" ".repeat(f),ee=X[Q]??" ".repeat(g);y+=d.moveTo(l+Q,1)+ye+" ".repeat(m)+ee}else{for(let ye=0;ye<b;ye++)y+=d.moveTo(l+ye,1)+(q[ye]??" ".repeat(f));let Q=l+b+1;y+=d.moveTo(Q-1,1)+d.eraseLine();for(let ye=0;ye<v;ye++)y+=d.moveTo(Q+ye,1)+(X[ye]??" ".repeat(g))}y+=d.moveTo(c,1)+d.eraseLine(),y+=` ${x(this.clip(this.getInfoPanelFooterHint(e),Math.max(1,r-1)))}`,y+=d.enableWrap(),process.stdout.write(y)}buildInfoFooterCardStripLine(e,n){if(e.length===0||n<=0)return"";let s=`${x("\u2502")}`,r=se(s).length+2,o=Math.max(e.length,n-(e.length-1)*r),i=Math.max(8,Math.floor(o/e.length)),a=[];for(let c=0;c<e.length;c++){let u=e[c],p=c===e.length-1?Math.max(8,o-i*(e.length-1)):i,f=be(this.clip(u.value,Math.max(1,Math.min(10,p-2)))),m=se(f).length,g=Math.max(1,p-m-1),b=x(this.clip(u.title.toUpperCase(),g)),v=Math.max(1,p-se(b).length-m);a.push(`${b}${" ".repeat(v)}${f}`)}let l=a.join(` ${s} `);return se(l).length<=n?l:this.clip(se(l),n)}buildInfoFooterCardStripBoxLines(e,n){if(n<=2)return[];let s=Math.max(1,n-4),r=this.buildInfoFooterCardStripLine(e,s).padEnd(s," ");return[x(`\u256D${"\u2500".repeat(Math.max(0,n-2))}\u256E`),`${x("\u2502")} ${r} ${x("\u2502")}`,x(`\u2570${"\u2500".repeat(Math.max(0,n-2))}\u256F`)]}drawLegacyInfoViewport(){if(!this.infoPanelState)return;let n={...this.infoPanelState,layout:"footer",singlePane:!1,cards:[],sections:[],split:void 0,selectedSectionIndex:0,focusPane:"sections",secondaryScrollOffset:0,notice:void 0,assistant:void 0,draft:null,editing:null},s=this.infoPanelState;this.infoPanelState=n,this.drawInfoPanelUI(),this.infoPanelState=s}buildInfoSectionRailLines(e,n,s){if(e.sections.length===0)return["No sections available."];let r=[];for(let o=0;o<e.sections.length;o++){let i=e.sections[o],a=o===e.selectedSectionIndex,l=a?be("\u203A"):x("\u2022"),c=a?be(this.clip(i.title,Math.max(1,s-2))):this.clip(i.title,Math.max(1,s-2));r.push(`${l} ${c}`),i.summary&&r.push(` ${x(this.clip(i.summary,Math.max(1,s-2)))}`),o<e.sections.length-1&&r.push("")}return r.length===0&&r.push("No sections available."),r.slice(0,n)}buildInfoContentBoxLines(e,n,s,r,o,i,a,l,c=!1){if(s<=2||r<=2)return[];let u=[],p=Math.max(1,s-4),f=`${e}${n?` - ${n}`:""}`,m=l?be:x;u.push(m(`\u256D${"\u2500".repeat(Math.max(0,s-2))}\u256E`)),u.push(`${m("\u2502")} ${this.clip(f,p).padEnd(p," ")} ${m("\u2502")}`),u.push(m(`\u251C${"\u2500".repeat(Math.max(0,s-2))}\u2524`)),u.push(`${m("\u2502")} ${" ".repeat(p)} ${m("\u2502")}`);let g=Math.max(0,r-5),b=c?this.getInfoPanelEditHorizontalOffset(p):0;for(let v=0;v<g;v++){let w=o[v]??"";if(c){let re=se(w).slice(b,b+p),ae=Math.max(0,p-re.length);u.push(`${m("\u2502")} ${re}${" ".repeat(ae)} ${m("\u2502")}`);continue}let P=" ";v===0&&i&&(P="\u2191"),v===g-1&&a&&(P="\u2193");let C=se(w),$=C.length>p-2?this.clip(C,Math.max(1,p-2)):C,E=w&&se(w).length<=p-2?w:$,T=Math.max(0,p-2-se(E).length);u.push(`${m("\u2502")} ${P===" "?" ":x(P)} ${E}${" ".repeat(T)} ${m("\u2502")}`)}return u.push(m(`\u2570${"\u2500".repeat(Math.max(0,s-2))}\u256F`)),u.slice(0,r)}insertInfoPanelAssistantText(e){let n=this.infoPanelState?.assistant;if(!n||n.submitting)return;let s=e.replace(/\r\n/g,`
|
|
144
|
+
`).replace(/\r/g,`
|
|
145
|
+
`);n.inputBuffer=n.inputBuffer.slice(0,n.cursorPos)+s+n.inputBuffer.slice(n.cursorPos),n.cursorPos+=s.length,n.error=void 0}backspaceInfoPanelAssistantText(){let e=this.infoPanelState?.assistant;!e||e.submitting||e.cursorPos<=0||(e.inputBuffer=e.inputBuffer.slice(0,e.cursorPos-1)+e.inputBuffer.slice(e.cursorPos),e.cursorPos-=1,e.error=void 0)}deleteInfoPanelAssistantText(){let e=this.infoPanelState?.assistant;!e||e.submitting||e.cursorPos>=e.inputBuffer.length||(e.inputBuffer=e.inputBuffer.slice(0,e.cursorPos)+e.inputBuffer.slice(e.cursorPos+1),e.error=void 0)}async submitInfoPanelAssistantPrompt(){let e=this.infoPanelState,n=e?.assistant;if(!e||!n||n.submitting)return;let s=n.inputBuffer.trim();if(s){n.messages.push({role:"user",content:s}),n.inputBuffer="",n.cursorPos=0,n.submitting=!0,n.error=void 0,e.notice=void 0,this.drawInfoPanelUI();try{let r=await n.onSubmit({prompt:s,currentContent:this.getInfoPanelCurrentEditableValue(e),appendMessage:o=>{n.messages.push(o),this.drawInfoPanelUI()}});r?.replacementContent!==void 0&&this.stageInfoPanelAssistantReplacement(r.replacementContent,r),n.messages.push({role:"assistant",content:r?.message??(r?.replacementContent!==void 0?"Drafted a scoped edit. Review it, then Ctrl+S to accept or Ctrl+R to revert.":"No file changes returned.")}),e.notice=r?.notice??(r?.replacementContent!==void 0?"Agent draft ready.":"File chat response added.")}catch(r){let o=r instanceof Error?r.message:String(r);n.error=o,n.messages.push({role:"error",content:o}),e.notice="File edit failed."}finally{n.submitting=!1,this.drawInfoPanelUI()}}}stageInfoPanelAssistantReplacement(e,n){let s=this.infoPanelState;if(!s)return;let r=this.getSinglePaneContentSection(s)??this.getSelectedInfoPanelSection(s);if(!r?.editable)return;let o=r.editable.value.replace(/\r\n/g,`
|
|
146
|
+
`),i=e.replace(/\r\n/g,`
|
|
147
|
+
`);s.draft={sectionId:r.id,originalValue:o,proposedValue:i,message:n?.message},s.scrollOffset=0}async acceptInfoPanelDraft(){let e=this.infoPanelState,n=e?.draft;if(!e||!n)return;let s=e.sections.find(r=>r.id===n.sectionId);if(s?.editable){e.notice="Saving agent draft...",this.drawInfoPanelUI();try{let r=await s.editable.onSave(n.proposedValue);s.editable.value=n.proposedValue,s.lines=r?.contentLines??n.proposedValue.replace(/\r\n/g,`
|
|
148
|
+
`).split(`
|
|
149
|
+
`),s.summary=r?.summary??`${s.lines.length} lines`,r?.cards&&(e.cards=r.cards),r?.sections&&(e.sections=r.sections),r?.split&&(e.split=r.split),r?.panelLines&&(e.lines=r.panelLines),e.draft=null,e.notice="Agent draft saved.",e.scrollOffset=0}catch(r){let o=r instanceof Error?r.message:String(r);e.notice=`Save failed: ${o}`}this.drawInfoPanelUI()}}revertInfoPanelDraft(){let e=this.infoPanelState;e?.draft&&(e.draft=null,e.notice="Agent draft reverted.",e.scrollOffset=0,this.drawInfoPanelUI())}handleSinglePaneInfoPanelKeypress(e,n,s){let r=this.infoPanelState,o=r?.assistant;return r?r.draft&&e===""?(this.acceptInfoPanelDraft(),!0):r.draft&&e===""?(this.revertInfoPanelDraft(),!0):o&&e===" "?(r.focusPane=r.focusPane==="assistant"?"content":"assistant",this.drawInfoPanelUI(),!0):o&&r.focusPane==="assistant"?o.submitting?!0:this.isEnterKey(e)?(this.submitInfoPanelAssistantPrompt(),!0):this.isMultilineInsertKey(e)?(this.insertInfoPanelAssistantText(`
|
|
150
|
+
`),this.drawInfoPanelUI(),!0):e==="\x1B"?o.inputBuffer.length>0?(o.inputBuffer="",o.cursorPos=0,this.drawInfoPanelUI(),!0):(this.exitInfoPanelMode(),!0):e==="\x7F"||e==="\b"?(this.backspaceInfoPanelAssistantText(),this.drawInfoPanelUI(),!0):e==="\x1B[3~"?(this.deleteInfoPanelAssistantText(),this.drawInfoPanelUI(),!0):this.isArrowKey(e,"left")?(o.cursorPos=Math.max(0,o.cursorPos-1),this.drawInfoPanelUI(),!0):this.isArrowKey(e,"right")?(o.cursorPos=Math.min(o.inputBuffer.length,o.cursorPos+1),this.drawInfoPanelUI(),!0):e===""||e==="\x1B[H"||e==="\x1B[1~"?(o.cursorPos=0,this.drawInfoPanelUI(),!0):e===""||e==="\x1B[F"||e==="\x1B[4~"?(o.cursorPos=o.inputBuffer.length,this.drawInfoPanelUI(),!0):(e>=" "&&!e.startsWith("\x1B")&&(this.insertInfoPanelAssistantText(e),this.drawInfoPanelUI()),!0):o&&e>=" "&&!e.startsWith("\x1B")?(r.focusPane="assistant",this.insertInfoPanelAssistantText(e),this.drawInfoPanelUI(),!0):this.isEnterKey(e)&&this.getSinglePaneContentSection(r)?.editable?(r.focusPane="content",this.startInfoPanelEditing(),!0):this.isArrowKey(e,"up")?(r.scrollOffset=Math.max(0,r.scrollOffset-1),this.drawInfoPanelUI(),!0):this.isArrowKey(e,"down")?(r.scrollOffset=Math.min(s,r.scrollOffset+1),this.drawInfoPanelUI(),!0):e==="\x1B[5~"?(r.scrollOffset=Math.max(0,r.scrollOffset-n),this.drawInfoPanelUI(),!0):e==="\x1B[6~"?(r.scrollOffset=Math.min(s,r.scrollOffset+n),this.drawInfoPanelUI(),!0):e==="\x1B[H"||e==="\x1B[1~"?(r.scrollOffset=0,this.drawInfoPanelUI(),!0):e==="\x1B[F"||e==="\x1B[4~"?(r.scrollOffset=s,this.drawInfoPanelUI(),!0):e==="\x1B"||e===""?(this.exitInfoPanelMode(),!0):!1:!1}wrapInfoLines(e,n){let s=[];for(let r of e){let o=se(r);if(!o){s.push("");continue}let a=o.match(/^\s*/)?.[0]??"",l=o.trim().split(/\s+/);if(l.length===0){s.push("");continue}let c=a;for(let u of l){let p=c.trim().length===0?`${a}${u}`:`${c} ${u}`;if(se(p).length<=n){c=p;continue}if(se(c).length>0){s.push(this.clip(c,n)),c=`${a}${u}`;continue}s.push(this.clip(`${a}${u}`,n)),c=a}se(c).length>0&&s.push(this.clip(c,n))}return s.length>0?s:[""]}handleInfoPanelKeypress(e){if(!this.infoPanelState)return;let n=this.infoPanelState;if(n.source==="delegation-inspector"&&e==="\f"){let Z=n.resolve;this.infoPanelState=null,this.outputBottom=Math.max(this.rows-this.getNormalFooterRows(),1),process.stdout.write(d.setScrollRegion(1,this.outputBottom)),this.redrawScreenFromHistory(),this.drawInputBox(),this.refreshFooterFocusCursor(),Z();return}let s=this.hasStructuredInfoPanel(n),r=s&&!!n.split,o=this.getInfoPanelRows(),i=this.getInfoPanelFixedRows(n),a=this.renderCols(),l=s&&a>=(n.layout==="viewport"?108:92),c=a>=108?4:a>=82?3:a>=56?2:1,u=s&&n.cards.length>0?n.layout==="viewport"?Math.ceil(n.cards.length/c)*4:3:0,p=(s&&n.layout==="viewport",3),f=n.layout==="viewport"?1:Math.max(this.rows-o+1,1),m=s?f+p+(u>0?u:0):1,g=n.layout==="viewport"?this.rows:f+o-1,b=s?Math.max(1,g-m):Math.max(1,o-i),v=l?b:Math.max(5,Math.min(8,Math.floor(b*.28))),w=l?b:Math.max(6,b-v-1);s&&!l&&v+1+w>b&&(v=Math.max(5,b-w-1));let P=s?Math.max(1,w-5):Math.max(1,o-i),C=s&&l?Math.max(28,a-Math.max(24,Math.min(32,Math.floor(a*.27)))-2):a,$=s&&n.sections.length>0?n.sections[Math.max(0,Math.min(n.selectedSectionIndex,n.sections.length-1))]:null,E=r&&a>=(n.layout==="viewport"?98:88),T=E?Math.max(30,Math.min(42,Math.floor(a*.34))):a,I=E?Math.max(34,a-T-2):a,re=n.editing?.target==="split-left"||n.editing?.target==="split-right"?n.editing.target:null,ae=r&&n.split?this.wrapInfoLines(this.getRenderedSplitPaneLines(n.split.left,re,"split-left"),Math.max(8,T-4)):[],N=r&&n.split?this.wrapInfoLines(this.getRenderedSplitPaneLines(n.split.right,re,"split-right"),Math.max(8,I-4)):[],y=s?this.wrapInfoLines($?.lines??n.lines,Math.max(8,C-4)):n.lines,oe=P,K=n.editing?this.getInfoPanelEditVisibleRows():oe,W=Math.max(0,y.length-oe);if(n.editing){if(e===""){this.saveInfoPanelEditing();return}if(e===""){this.undoInfoPanelEdit(K)&&this.drawInfoPanelUI();return}if(e===""){this.redoInfoPanelEdit(K)&&this.drawInfoPanelUI();return}if(e==="\x1B"&&e.length===1){if(this.isInfoPanelEditDirty(n.editing)&&!n.editing.confirmDiscard){n.editing.confirmDiscard=!0,n.editing.error=void 0,this.drawInfoPanelUI();return}this.cancelInfoPanelEditing();return}if(e==="\x7F"||e==="\b"){this.backspaceInfoPanelEdit(K),this.drawInfoPanelUI();return}if(e==="\x1B[3~"){this.deleteInfoPanelEdit(K),this.drawInfoPanelUI();return}if(this.isArrowKey(e,"left")){this.moveInfoPanelEditCursor("left",K),this.drawInfoPanelUI();return}if(this.isArrowKey(e,"right")){this.moveInfoPanelEditCursor("right",K),this.drawInfoPanelUI();return}if(this.isArrowKey(e,"up")){this.moveInfoPanelEditCursor("up",K),this.drawInfoPanelUI();return}if(this.isArrowKey(e,"down")){this.moveInfoPanelEditCursor("down",K),this.drawInfoPanelUI();return}if(e==="\x1B[H"||e==="\x1B[1~"||e===""){n.editing.cursorCol=0,n.editing.preferredCol=0,this.syncInfoPanelEditScroll(K),this.drawInfoPanelUI();return}if(e==="\x1B[F"||e==="\x1B[4~"||e===""){let Z=n.editing.lines[n.editing.cursorRow]??"";n.editing.cursorCol=Z.length,n.editing.preferredCol=Z.length,this.syncInfoPanelEditScroll(K),this.drawInfoPanelUI();return}if(e==="\x1B[5~"){n.editing.cursorRow=Math.max(0,n.editing.cursorRow-K),n.editing.cursorCol=Math.min((n.editing.lines[n.editing.cursorRow]??"").length,n.editing.preferredCol),this.syncInfoPanelEditScroll(K),this.drawInfoPanelUI();return}if(e==="\x1B[6~"){n.editing.cursorRow=Math.min(n.editing.lines.length-1,n.editing.cursorRow+K),n.editing.cursorCol=Math.min((n.editing.lines[n.editing.cursorRow]??"").length,n.editing.preferredCol),this.syncInfoPanelEditScroll(K),this.drawInfoPanelUI();return}if(this.isEnterKey(e)||this.isMultilineInsertKey(e)){this.insertInfoPanelEditText(`
|
|
151
|
+
`,K),this.drawInfoPanelUI();return}if(e===" "){this.insertInfoPanelEditText(" ",K),this.drawInfoPanelUI();return}if(e>=" "&&!e.startsWith("\x1B")){this.insertInfoPanelEditText(e,oe),this.drawInfoPanelUI();return}return}if(n.singlePane){let Z=this.getSinglePaneInfoPanelMetrics(n),ce=this.getSinglePaneContentSection(n)?.lines??n.lines,X=this.wrapInfoLines(ce,Math.max(8,Z.renderCols-4)),q=Math.max(0,X.length-Z.contentBodyRows);if(this.handleSinglePaneInfoPanelKeypress(e,Z.contentBodyRows,q))return}if(r&&n.split){let Z=b,le=E?Z:Math.max(7,Math.min(10,Math.floor(Z*.4))),ce=E?Z:Math.max(7,Z-le-1),X=Math.max(1,le-5),q=Math.max(1,ce-5),Q=Math.max(0,ae.length-X),ye=Math.max(0,N.length-q);if(this.isArrowKey(e,"left")){n.focusPane!=="sections"&&(n.focusPane="sections",this.drawInfoPanelUI());return}if(this.isArrowKey(e,"right")||e===" "){n.focusPane!=="content"&&(n.focusPane="content",this.drawInfoPanelUI());return}if(this.isArrowKey(e,"up")){n.focusPane==="sections"?n.scrollOffset=Math.max(0,n.scrollOffset-1):n.secondaryScrollOffset=Math.max(0,n.secondaryScrollOffset-1),this.drawInfoPanelUI();return}if(this.isArrowKey(e,"down")){n.focusPane==="sections"?n.scrollOffset=Math.min(Q,n.scrollOffset+1):n.secondaryScrollOffset=Math.min(ye,n.secondaryScrollOffset+1),this.drawInfoPanelUI();return}if(e==="\x1B[5~"){n.focusPane==="sections"?n.scrollOffset=Math.max(0,n.scrollOffset-X):n.secondaryScrollOffset=Math.max(0,n.secondaryScrollOffset-q),this.drawInfoPanelUI();return}if(e==="\x1B[6~"){n.focusPane==="sections"?n.scrollOffset=Math.min(Q,n.scrollOffset+X):n.secondaryScrollOffset=Math.min(ye,n.secondaryScrollOffset+q),this.drawInfoPanelUI();return}if(e==="\x1B[H"||e==="\x1B[1~"){n.focusPane==="sections"?n.scrollOffset=0:n.secondaryScrollOffset=0,this.drawInfoPanelUI();return}if(e==="\x1B[F"||e==="\x1B[4~"){n.focusPane==="sections"?n.scrollOffset=Q:n.secondaryScrollOffset=ye,this.drawInfoPanelUI();return}if(this.isEnterKey(e)){this.getEditableSplitPane(n)||(n.split.left.editable?n.focusPane="sections":n.split.right.editable&&(n.focusPane="content")),this.getEditableSplitPane(n)&&this.startSplitPaneEditing();return}(e==="\x1B"||e==="")&&this.exitInfoPanelMode();return}if(n.notice&&(n.notice=void 0),s&&n.sections.length>0){if(this.isArrowKey(e,"left")){n.focusPane!=="sections"&&(n.focusPane="sections",this.drawInfoPanelUI());return}if(this.isArrowKey(e,"right")||e===" "){n.focusPane!=="content"&&(n.focusPane="content",this.drawInfoPanelUI());return}if(n.focusPane==="sections"){if(this.isArrowKey(e,"up")){n.selectedSectionIndex=Math.max(0,n.selectedSectionIndex-1),n.scrollOffset=0,this.drawInfoPanelUI();return}if(this.isArrowKey(e,"down")){n.selectedSectionIndex=Math.min(n.sections.length-1,n.selectedSectionIndex+1),n.scrollOffset=0,this.drawInfoPanelUI();return}}}if(this.isEnterKey(e)&&this.getSelectedInfoPanelSection(n)?.editable){this.startInfoPanelEditing();return}if(this.isArrowKey(e,"up")){n.scrollOffset=Math.max(0,n.scrollOffset-1),this.drawInfoPanelUI();return}if(this.isArrowKey(e,"down")){n.scrollOffset=Math.min(W,n.scrollOffset+1),this.drawInfoPanelUI();return}if(e==="\x1B[5~"){n.scrollOffset=Math.max(0,n.scrollOffset-oe),this.drawInfoPanelUI();return}if(e==="\x1B[6~"){n.scrollOffset=Math.min(W,n.scrollOffset+oe),this.drawInfoPanelUI();return}if(e==="\x1B[H"||e==="\x1B[1~"){n.scrollOffset=0,this.drawInfoPanelUI();return}if(e==="\x1B[F"||e==="\x1B[4~"){n.scrollOffset=W,this.drawInfoPanelUI();return}(!s&&this.isEnterKey(e)||e==="\x1B"||e==="")&&this.exitInfoPanelMode()}exitInfoPanelMode(){let e=this.infoPanelState?.resolve;this.infoPanelState=null,this.calculateLayout(),process.stdout.write(d.setScrollRegion(1,this.outputBottom)),this.redrawScreenFromHistory(),this.drawInputBox(),this.refreshFooterFocusCursor(),e?.()}getPermissionRows(e){let n=!!e?.description,s=!!e?.requesterSummary,r=!!e?.directory,o=!!e?.filePath,i=!!e?.detail&&!o,a=e?.preview?.lines.length??0,l=!!e?.preview?.summary,c=a>0,u=10;return s&&u++,o&&u++,r&&u++,i&&u++,n&&u++,c&&(u+=1+a),l&&u++,e?.preview?.truncated&&u++,u}drawPermissionUI(){if(!this.permissionState)return;let{info:e,selectedIndex:n,options:s}=this.permissionState,r=!!e.description,o=!!e.requesterSummary,i=!!e.filePath,a=!!e.directory,l=e.preview,c=this.outputBottom+1,u=d.hideCursor()+d.disableWrap();for(let g=this.outputBottom+1;g<=this.rows;g++)u+=d.moveTo(g,1)+d.eraseLine();u+=d.moveTo(c,1)+d.eraseLine(),u+=be("\u2500".repeat(this.renderCols())),c++,u+=d.moveTo(c,1)+d.eraseLine(),u+=` ${x("\u2500".repeat(Math.max(0,this.cols-1)))}`,c++;let p=e.requesterLabel?`${e.requesterLabel} ${x("\xB7")} ${e.toolName}`:e.toolName,f=e.operation==="edit"?"Edit file":e.operation==="write"?"Write file":e.operation==="bash"?"Run command":e.operation==="filesystem"?"Filesystem access":"Permission request",m=`${qe.bold(f)} ${x(`(${p})`)}`;if(u+=d.moveTo(c,1)+d.eraseLine(),u+=` ${this.clip(m,Math.max(1,this.cols-1))}`,c++,o&&(u+=d.moveTo(c,1)+d.eraseLine(),u+=` ${x("Requester:")} ${this.clip(e.requesterSummary,Math.max(1,this.cols-12))}`,c++),i&&(u+=d.moveTo(c,1)+d.eraseLine(),u+=` ${x("File:")} ${be(this.clip(e.filePath,Math.max(1,this.cols-8)))}`,c++),a&&(u+=d.moveTo(c,1)+d.eraseLine(),u+=` ${x("Directory:")} ${this.clip(e.directory,Math.max(1,this.cols-13))}`,c++),e.detail&&!i){let g=this.clip(e.detail,Math.max(1,this.cols-4));u+=d.moveTo(c,1)+d.eraseLine(),u+=` ${x("Command:")} ${g}`,c++}if(r&&(u+=d.moveTo(c,1)+d.eraseLine(),u+=` ${x(this.clip(e.description,Math.max(1,this.cols-1)))}`,c++),l&&l.lines.length>0){u+=d.moveTo(c,1)+d.eraseLine(),u+=` ${x(l.title)}`,c++,l.summary&&(u+=d.moveTo(c,1)+d.eraseLine(),u+=` ${x(this.clip(l.summary,Math.max(1,this.cols-1)))}`,c++);for(let g of l.lines){u+=d.moveTo(c,1)+d.eraseLine();let b=g.kind==="add"?qe.green("+ "):g.kind==="remove"?qe.red("- "):" ",v=g.kind==="add"?qe.green:g.kind==="remove"?qe.red:g.kind==="meta"?x:w=>w;u+=` ${b}${v(this.clip(g.text,Math.max(1,this.cols-5)))}`,c++}l.truncated&&(u+=d.moveTo(c,1)+d.eraseLine(),u+=` ${x("Preview truncated to fit the terminal overlay.")}`,c++)}u+=d.moveTo(c,1)+d.eraseLine(),c++,u+=d.moveTo(c,1)+d.eraseLine(),u+=" Allow this action?",c++;for(let g=0;g<s.length;g++){u+=d.moveTo(c,1)+d.eraseLine();let b=g===n,v=`${g+1}.`,w=this.clip(s[g].label,Math.max(1,this.cols-8));b?u+=` ${be("\u203A")} ${v} ${w}`:u+=` ${x(v)} ${x(w)}`,c++}u+=d.moveTo(c,1)+d.eraseLine(),c++,u+=d.moveTo(c,1)+d.eraseLine(),u+=` ${x("\u2191/\u2193 navigate \xB7 Enter confirm \xB7 Esc deny")}`,u+=d.enableWrap(),process.stdout.write(u)}handlePermissionKeypress(e){if(!this.permissionState)return;if(e==="\x1B[A"){this.permissionState.selectedIndex=Math.max(0,this.permissionState.selectedIndex-1),this.drawPermissionUI();return}if(e==="\x1B[B"){this.permissionState.selectedIndex=Math.min(this.permissionState.options.length-1,this.permissionState.selectedIndex+1),this.drawPermissionUI();return}if(e==="\r"||e===`
|
|
152
|
+
`){let s=this.permissionState.options[this.permissionState.selectedIndex].value;this.exitPermissionMode(s);return}if(e==="\x1B"||e===""){this.exitPermissionMode("deny");return}let n=parseInt(e,10);if(n>=1&&n<=this.permissionState.options.length){let s=this.permissionState.options[n-1].value;this.exitPermissionMode(s)}}exitPermissionMode(e){let n=this.permissionState?this.getPermissionRows(this.permissionState.info):0,s=n>0?Math.max(this.rows-n+1,1):this.rows,r=this.permissionState?.resolve;this.permissionState=null,this.calculateLayout(),process.stdout.write(d.setScrollRegion(1,this.outputBottom));for(let o=s;o<=this.rows;o++)process.stdout.write(d.moveTo(o,1)+d.eraseLine());this.drawInputBox(),process.stdout.write(d.hideCursor()),r?.(e)}};fn();It();At();import Wa from"chalk";var Ro=t=>Ke()(t),Rs=Wa.dim,om=Wa.bold;async function Xa(t){return process.stdin.isTTY?new Promise(e=>{let n=process.stdout.rows||24,s=process.stdout.columns||80,r=null,o=0,i=[{label:"Yes, I trust this folder",value:!0},{label:"No, exit",value:!1}],a=(f,m)=>m<=0?"":f.length<=m?f:m<=3?".".repeat(m):f.slice(0,m-3)+"...",l=()=>{r?.release(),r=null,process.stdout.removeListener("resize",u),process.stdout.write(d.showCursor()),process.stdout.write(d.resetScrollRegion()),process.stdout.write(d.clearScreen())},c=()=>{n=process.stdout.rows||n,s=process.stdout.columns||s;let f=d.clearScreen();f+=d.hideCursor();let m=1;f+=d.moveTo(m,1)+d.eraseLine(),f+=Ro("\u2500".repeat(s)),m++,f+=d.moveTo(m,1)+d.eraseLine(),f+=` ${Rs("\u2500".repeat(Math.max(0,s-1)))}`,m++,f+=d.moveTo(m,1)+d.eraseLine(),f+=` ${om("Access workspace")}`,m++,f+=d.moveTo(m,1)+d.eraseLine(),f+=` ${Rs("Path:")} ${Ro(a(t,Math.max(1,s-8)))}`,m++,f+=d.moveTo(m,1)+d.eraseLine(),m++;let g="Quick safety check: only continue if this is your code, your team code, or a trusted project.",b="XENO AGENT can read, edit, and execute files in this folder.";f+=d.moveTo(m,1)+d.eraseLine(),f+=` ${a(g,Math.max(1,s-1))}`,m++,f+=d.moveTo(m,1)+d.eraseLine(),f+=` ${a(b,Math.max(1,s-1))}`,m++,f+=d.moveTo(m,1)+d.eraseLine(),m++;for(let v=0;v<i.length;v++){f+=d.moveTo(m,1)+d.eraseLine();let w=v===o,P=`${v+1}.`,C=a(i[v].label,Math.max(1,s-8));w?f+=` ${Ro("\u203A")} ${P} ${C}`:f+=` ${Rs(P)} ${Rs(C)}`,m++}f+=d.moveTo(m,1)+d.eraseLine(),m++,f+=d.moveTo(m,1)+d.eraseLine(),f+=` ${Rs("\u2191/\u2193 navigate \xB7 Enter confirm \xB7 Esc cancel")}`,process.stdout.write(f)},u=()=>{c()};r=Ct(f=>{if(f===""&&(l(),process.exit(0)),f==="\x1B"&&f.length===1){l(),e({trusted:!1});return}if(f==="\x1B[A"){o=Math.max(0,o-1),c();return}if(f==="\x1B[B"){o=Math.min(i.length-1,o+1),c();return}if(f==="\r"||f===`
|
|
153
|
+
`){l(),e({trusted:i[o].value});return}let m=parseInt(f,10);m>=1&&m<=i.length&&(l(),e({trusted:i[m-1].value}))}),process.stdout.on("resize",u),c()}):{trusted:!0}}It();At();import tt from"chalk";var Ka=t=>Ke()(t),im=t=>tt.dim("\u258E ")+tt.italic(t),am=/^(?:#{1,6}\s*)?(?:urls?\s+used|sources?):?$/i,lm=/^(?:[-*]\s+)?https?:\/\/\S+$/i,cm=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function um(t){return am.test(t.trim())}function dm(t){return lm.test(t.trim())}function pm(t){return t.trim().replace(/^#{1,6}\s*/,"").replace(/:$/,"").toLowerCase()==="sources"?"Sources":"URLs used"}function mm(t){return t.trim().replace(/^[-*]\s+/,"")}function Ja(t){return t.replace(cm,"")}function Es(t){let e=0;for(let n of Ja(t))(n.codePointAt(0)??0)<32||(e+=1);return e}function fm(t,e){return t+" ".repeat(Math.max(0,e-Es(t)))}function Qa(t){let e=t.trim();e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&!e.endsWith("\\|")&&(e=e.slice(0,-1));let n=[],s="";for(let r=0;r<e.length;r+=1){let o=e[r],i=e[r+1];if(o==="\\"&&i==="|"){s+="|",r+=1;continue}if(o==="|"){n.push(s.trim()),s="";continue}s+=o}return n.push(s.trim()),n}function Ga(t){return t.trim().includes("|")&&Qa(t).length>=2}function hm(t){return t.length>=2&&t.every(e=>/^:?-{3,}:?$/.test(e.trim()))}function Ya(t,e){return t.map(n=>{let s=n.slice(0,e);for(;s.length<e;)s.push("");return s})}function gm(t,e){let n=t.length,s=n*3+1,r=Math.max(n*8,e-s),o=t.map(a=>Math.max(1,a)),i=t.map(a=>Math.min(a,12));for(;o.reduce((a,l)=>a+l,0)>r;){let a=-1,l=-1;for(let c=0;c<o.length;c+=1)o[c]>i[c]&&o[c]>l&&(a=c,l=o[c]);if(a===-1)break;o[a]-=1}return o}function bm(t,e){let n=t.trim().split(/\s+/).filter(Boolean);if(n.length===0)return[""];let s=[],r="";for(let i of n){if(!r){r=i;continue}if(Es(`${r} ${i}`)<=e){r+=` ${i}`;continue}s.push(r),r=i}r&&s.push(r);let o=[];for(let i of s){if(Es(i)<=e){o.push(i);continue}let a=i;for(;Es(a)>e;)o.push(a.slice(0,e)),a=a.slice(e);a&&o.push(a)}return o.length>0?o:[""]}function ym(t,e){if(t.length<2)return null;let n=t.map(Qa);if(!hm(n[1])||n[0].length<2)return null;let s=Math.max(n[0].length,n[1].length),r=Ya([n[0]],s)[0],o=Ya(n.slice(2),s),i=[r,...o],a=r.map((l,c)=>Math.max(3,...i.map(u=>Es(Ja(Eo(u[c]??""))))));return{headers:r,rows:o,widths:gm(a,e)}}function wm(t,e){let n=ym(t,e);if(!n)return null;let{headers:s,rows:r,widths:o}=n,i=(l,c,u)=>tt.dim(l+o.map(p=>"\u2500".repeat(p+2)).join(c)+u),a=(l,c)=>{let u=l.map((m,g)=>bm(m,o[g])),p=Math.max(...u.map(m=>m.length)),f=[];for(let m=0;m<p;m+=1){let g=u.map((b,v)=>{let w=b[m]??"",P=c(Eo(w));return` ${fm(P,o[v])} `});f.push(tt.dim("\u2502")+g.join(tt.dim("\u2502"))+tt.dim("\u2502"))}return f};return[i("\u256D","\u252C","\u256E"),...a(s,l=>Ke().bold(l)),i("\u251C","\u253C","\u2524"),...r.flatMap(l=>a(l,c=>c)),i("\u2570","\u2534","\u256F")]}function Eo(t){let e=t;return e=e.replace(/^>\s*(.*)$/gm,(n,s)=>im(s)),e=e.replace(/^(#{1,6})\s+(.+)$/gm,(n,s,r)=>Ke().bold(r)),e=e.replace(/\*\*(.+?)\*\*/g,(n,s)=>tt.bold(s)),e=e.replace(/__(.+?)__/g,(n,s)=>tt.bold(s)),e=e.replace(/(?<![a-zA-Z])\*([^*\n]+?)\*(?![a-zA-Z])/g,(n,s)=>tt.italic(s)),e=e.replace(/(?<![a-zA-Z])_([^_\n]+?)_(?![a-zA-Z])/g,(n,s)=>tt.italic(s)),e=e.replace(/`([^`\n]+?)`/g,(n,s)=>Ka(s)),e=e.replace(/~~(.+?)~~/g,(n,s)=>tt.strikethrough(s)),e=e.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,s,r)=>`${Ka(s)} ${tt.dim(`(${r})`)}`),e=e.replace(/^(\s*)[-*]\s+/gm,(n,s)=>`${s}${tt.dim("\u25AA")} `),e=e.replace(/^(\s*)(\d+)\.\s+/gm,(n,s,r)=>`${s}${tt.dim(`${r}.`)} `),e=e.replace(/^[-*]{3,}$/gm,()=>tt.dim("\u2500".repeat(40))),e}var In=class{buffer="";inCodeBlock=!1;atLineStart=!0;lastOutputWasBlank=!1;blankBeforeNextText=!1;inSourceSection=!1;tableLines=[];terminalWidth;writeFn;pad;constructor(e,n=" ",s=process.stdout.columns||100){this.writeFn=e,this.pad=n,this.terminalWidth=Math.max(40,Math.min(s,140))}markLineStarted(){this.atLineStart=!1}write(e){this.buffer+=e;let n;for(;(n=this.buffer.indexOf(`
|
|
154
|
+
`))!==-1;){let s=this.buffer.slice(0,n);if(this.buffer=this.buffer.slice(n+1),!this.inCodeBlock&&Ga(s)){this.tableLines.push(s);continue}if(this.flushTableLines(),s.length===0&&!this.inCodeBlock){this.inSourceSection||this.writeBlankLine();continue}this.processLine(s)&&(this.writeFn(`
|
|
155
|
+
`),this.atLineStart=!0)}}processLine(e){let n=e.trim(),s=n.startsWith("```"),r=um(e),o=dm(e);if(this.blankBeforeNextText&&!s&&n.length>0&&this.writeBlankLine(),this.blankBeforeNextText=!1,!r&&!o&&n.length>0&&(this.inSourceSection=!1),s){let l=this.inCodeBlock;l||this.writeBlankLine();let c=this.atLineStart?this.pad:"";if(this.atLineStart=!1,this.lastOutputWasBlank=!1,l)return this.inCodeBlock=!1,this.writeFn(c+tt.dim("\u2570\u2500")),this.blankBeforeNextText=!0,!0;this.inCodeBlock=!0;let u=n.replace(/^```/,"").trim();return this.writeFn(c+tt.dim(`\u256D\u2500 ${u||"code"}`)),!0}let i=this.atLineStart?this.pad:"";if(this.atLineStart=!1,r)return this.inSourceSection=!0,this.writeFn(i+tt.dim.bold(pm(e))),this.lastOutputWasBlank=!1,!0;if(this.inSourceSection&&o)return this.writeFn(i+" "+tt.dim(mm(e))),this.lastOutputWasBlank=!1,!0;if(this.inCodeBlock)return this.writeFn(i+tt.dim("\u2502 ")+e),this.lastOutputWasBlank=!1,!0;let a=Eo(e);return this.writeFn(i+a),this.lastOutputWasBlank=!1,!0}flushTableLines(){if(this.tableLines.length===0)return;let e=this.tableLines;this.tableLines=[];let n=wm(e,this.terminalWidth-this.pad.length);if(n){for(let s of n){let r=this.atLineStart?this.pad:"";this.writeFn(r+s+`
|
|
156
|
+
`),this.atLineStart=!0}this.lastOutputWasBlank=!1,this.blankBeforeNextText=!1;return}for(let s of e)this.processLine(s)&&(this.writeFn(`
|
|
157
|
+
`),this.atLineStart=!0)}writeBlankLine(){this.lastOutputWasBlank||(this.writeFn(`
|
|
158
|
+
`),this.atLineStart=!0,this.lastOutputWasBlank=!0)}flush(){if(this.buffer)if(!this.inCodeBlock&&Ga(this.buffer))this.tableLines.push(this.buffer),this.buffer="",this.flushTableLines();else{this.flushTableLines();let e=this.processLine(this.buffer);this.buffer="",e&&(this.writeFn(`
|
|
159
|
+
`),this.atLineStart=!0,this.lastOutputWasBlank=!1)}else this.flushTableLines();this.inCodeBlock=!1,this.inSourceSection=!1}reset(){this.buffer="",this.inCodeBlock=!1,this.atLineStart=!0,this.lastOutputWasBlank=!1,this.blankBeforeNextText=!1,this.inSourceSection=!1,this.tableLines=[]}};var sn={};Me(sn,OP);import*as OP from"@xeno-corporation/xeno-agent-sdk/utils";var pt={};Me(pt,$P);import*as $P from"@xeno-corporation/xeno-agent-sdk/utils";var Mn={};Me(Mn,LP);import*as LP from"@xeno-corporation/xeno-agent-sdk";var B={};Me(B,NP);import*as NP from"@xeno-corporation/xeno-agent-sdk";On();Ms();var Ie={};Me(Ie,OT);import*as OT from"@xeno-corporation/xeno-agent-sdk";var ln={};Me(ln,$T);import*as $T from"@xeno-corporation/xeno-agent-sdk";function Rr(t){let e=Math.max(0,Math.floor(t)),n=Math.floor(e/1e3),s=Math.floor(n/3600),r=Math.floor(n%3600/60),o=n%60;return s>0?`${s}h ${r}m ${o}s`:r>0?`${r}m ${o}s`:`${o}s`}function Pl(t){let e=["Last Session Summary",`- model: ${t.model}`,`- mode: ${t.mode??"unknown"}`,`- status: ${t.status??"unknown"}`,`- started: ${t.startedAt}`,`- ended: ${t.endedAt}`,`- duration: ${Rr(t.durationMs)}`,`- tokens: ${t.tokenUsage.input.toLocaleString()} in / ${t.tokenUsage.output.toLocaleString()} out / ${t.tokenUsage.total.toLocaleString()} total`,`- estimated cost: ${(0,pt.formatCost)(t.estimatedCostUsd)}`];return t.sessionId&&e.splice(1,0,`- session: ${t.sessionId}`),t.role&&e.splice(t.sessionId?2:1,0,`- role: ${t.role}`),t.messageCount!==void 0&&e.push(`- messages: ${t.messageCount}`),e.join(`
|
|
160
|
+
`)}import{readdirSync as wf}from"fs";import{homedir as vf}from"os";import{resolve as Sf}from"path";import*as $e from"fs";import*as De from"path";import*as Rl from"readline";var lt={};Me(lt,BT);import*as BT from"@xeno-corporation/xeno-agent-sdk/utils";var sf=["web app","API","library","CLI","monorepo"],rf=["TypeScript","JavaScript","Python","Rust","Go","Java","C#","Other"];function El(t){let e=De.join(t,"package.json");if($e.existsSync(e))try{let r=JSON.parse($e.readFileSync(e,"utf-8"));if(typeof r.name=="string"&&r.name.length>0)return r.name}catch{}let n=De.join(t,"Cargo.toml");if($e.existsSync(n))try{let o=$e.readFileSync(n,"utf-8").match(/^\s*name\s*=\s*"([^"]+)"/m);if(o?.[1])return o[1]}catch{}let s=De.join(t,"pyproject.toml");if($e.existsSync(s))try{let o=$e.readFileSync(s,"utf-8").match(/^\s*name\s*=\s*"([^"]+)"/m);if(o?.[1])return o[1]}catch{}return De.basename(t)}function Cl(t){if((()=>{let r=De.join(t,"package.json");if($e.existsSync(r))try{let o=JSON.parse($e.readFileSync(r,"utf-8"));return Array.isArray(o.workspaces)}catch{}return!1})())return"monorepo";let n=De.join(t,"package.json");if($e.existsSync(n))try{if(JSON.parse($e.readFileSync(n,"utf-8")).bin)return"CLI"}catch{}let s=["next.config.js","next.config.ts","vite.config.ts","vite.config.js","nuxt.config.ts","angular.json"];for(let r of s)if($e.existsSync(De.join(t,r)))return"web app";return $e.existsSync(De.join(t,"Dockerfile"))||$e.existsSync(De.join(t,"docker-compose.yml"))?"API":"library"}function Al(t){return $e.existsSync(De.join(t,"tsconfig.json"))?"TypeScript":$e.existsSync(De.join(t,"Cargo.toml"))?"Rust":$e.existsSync(De.join(t,"go.mod"))?"Go":$e.existsSync(De.join(t,"pyproject.toml"))||$e.existsSync(De.join(t,"setup.py"))?"Python":$e.existsSync(De.join(t,"pom.xml"))||$e.existsSync(De.join(t,"build.gradle"))?"Java":$e.existsSync(De.join(t,"package.json"))?"JavaScript":"Other"}function Il(t){let e=De.join(t,"package.json");if($e.existsSync(e))try{let n=JSON.parse($e.readFileSync(e,"utf-8"));if(typeof n.description=="string"&&n.description.length>0)return n.description}catch{}return""}function si(t){return $e.existsSync(De.join(t,".git"))}async function Tl(t,e,n){return new Promise(s=>{let r=n?` (${n})`:"";t.question(` ${e}${r}: `,o=>{s(o.trim()||n)})})}async function _l(t,e,n,s){return new Promise(r=>{let o=n.indexOf(s),i=o>=0?` [${o+1}]`:"",a=n.map((l,c)=>` ${c+1}. ${l}`).join(`
|
|
161
|
+
`);t.question(` ${e}${i}:
|
|
162
|
+
${a}
|
|
163
|
+
> `,l=>{let c=l.trim();if(!c){r(s);return}let u=parseInt(c,10);u>=1&&u<=n.length?r(n[u-1]):r(c)})})}function Er(t){return t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}function of(t,e){let n=si(e),s=[];return s.push("---"),s.push(`name: "${Er(t.name)}"`),s.push(`type: "${Er(t.type)}"`),s.push(`language: "${Er(t.language)}"`),t.description&&s.push(`description: "${Er(t.description)}"`),s.push(`created: "${new Date().toISOString().split("T")[0]}"`),n&&s.push("vcs: git"),s.push("---"),s.push(""),s.push(`# ${t.name}`),s.push(""),t.description&&(s.push(t.description),s.push("")),s.push("## Project Context"),s.push(""),s.push(`This is a ${t.type} project written in ${t.language}.`),s.push(""),s.push("## Conventions"),s.push(""),s.push("<!-- Add project-specific coding conventions, patterns, and rules here -->"),s.push(""),s.join(`
|
|
164
|
+
`)}function af(){return["# Project Memory","","<!-- XENO Agent will automatically add learned patterns and corrections here -->",""].join(`
|
|
165
|
+
`)}function lf(){return JSON.stringify({plugins:[]},null,2)+`
|
|
166
|
+
`}function cf(){return JSON.stringify({servers:{}},null,2)+`
|
|
167
|
+
`}function Cr(t=process.cwd()){let e=De.join(t,".xeno"),n=De.join(e,"identity.md"),s=De.join(e,"xeno-main.md"),r=$e.existsSync(n)||$e.existsSync(s),o=[];$e.existsSync(e)&&!$e.statSync(e).isDirectory()&&o.push(".xeno exists as a file, not a directory"),r&&o.push("project already initialized");let i=[n,De.join(e,"memory.md"),De.join(e,"plugins.json"),De.join(e,"mcp.json")];return{cwd:t,xenoDir:e,initialized:r,canInitialize:o.length===0,blockers:o,detected:{name:El(t),type:Cl(t),language:Al(t),description:Il(t),gitRepo:si(t)},steps:i.map(a=>({path:a,exists:$e.existsSync(a),action:$e.existsSync(a)?"keep":"create"}))}}async function Ar(t={}){let e=t.cwd??process.cwd(),n=t.onOutput??(u=>process.stdout.write(u)),s=De.join(e,".xeno");if($e.existsSync(s)&&!$e.statSync(s).isDirectory()){n(`[!] Cannot initialize: .xeno exists as a file, not a directory.
|
|
168
|
+
`),n(` Remove the .xeno file first, then re-run /init.
|
|
169
|
+
`);return}if($e.existsSync(De.join(s,"identity.md"))){n(`[!] Project already initialized (.xeno/identity.md exists).
|
|
170
|
+
`),n(` Delete .xeno/ directory to re-initialize.
|
|
171
|
+
`);return}n(`
|
|
172
|
+
XENO AGENT - Project Initialization
|
|
173
|
+
|
|
174
|
+
`);let r=El(e),o=Cl(e),i=Al(e),a=Il(e);si(e)&&n(` Detected git repository.
|
|
175
|
+
`);let c;if(t.yes)c={name:r,type:o,language:i,description:a||`${r} project`},n(` Using detected defaults (--yes):
|
|
176
|
+
`),n(` Name: ${c.name}
|
|
177
|
+
`),n(` Type: ${c.type}
|
|
178
|
+
`),n(` Language: ${c.language}
|
|
179
|
+
`),n(` Description: ${c.description}
|
|
180
|
+
|
|
181
|
+
`);else{let u=Rl.createInterface({input:process.stdin,output:process.stdout});try{let p=await Tl(u,"Project name",r),f=await _l(u,"Project type",sf,o),m=await _l(u,"Language",rf,i),g=await Tl(u,"Description",a);c={name:p,type:f,language:m,description:g}}finally{u.close()}n(`
|
|
182
|
+
`)}n(` Creating .xeno/ directory structure...
|
|
183
|
+
`),await(0,lt.writeAtomic)(De.join(s,"identity.md"),of(c,e)),await(0,lt.writeAtomic)(De.join(s,"memory.md"),af()),await(0,lt.writeAtomic)(De.join(s,"plugins.json"),lf()),await(0,lt.writeAtomic)(De.join(s,"mcp.json"),cf()),(0,B.setProjectOnboardingCompleted)(e,!0),n(`
|
|
184
|
+
`),n(` Created:
|
|
185
|
+
`),n(` .xeno/identity.md Project identity with YAML frontmatter
|
|
186
|
+
`),n(` .xeno/memory.md Project memory (auto-populated)
|
|
187
|
+
`),n(` .xeno/plugins.json Plugin configuration
|
|
188
|
+
`),n(` .xeno/mcp.json MCP server configuration
|
|
189
|
+
`),n(`
|
|
190
|
+
`),n(" Project initialized. Run `xeno chat` to start.\n\n")}import{execFileSync as uf}from"child_process";import{existsSync as Ml,mkdirSync as df,readFileSync as pf,writeFileSync as mf}from"fs";import{homedir as ff,platform as ri}from"os";import{dirname as hf,join as Ir}from"path";var Ln={key:"shift+enter",command:"workbench.action.terminal.sendSequence",args:{text:`\\\r
|
|
191
|
+
`},when:"terminalFocus"};function ss(t=process.env){if(t.TERM_PROGRAM==="vscode")return"vscode";if(ri()==="darwin"&&t.TERM_PROGRAM==="iTerm.app")return"iterm2"}function oi(){return Ir(ff(),ri()==="win32"?Ir("AppData","Roaming","Code","User"):ri()==="darwin"?Ir("Library","Application Support","Code","User"):Ir(".config","Code","User"),"keybindings.json")}function Ol(){let t=oi();if(!Ml(t))return[];try{let e=JSON.parse(pf(t,"utf-8"));return Array.isArray(e)?e:[]}catch(e){throw new Error(`Invalid JSON in ${t}: ${e instanceof Error?e.message:String(e)}`)}}function ii(t){return t.some(e=>e.key===Ln.key&&e.command===Ln.command&&e.when===Ln.when&&e.args?.text===Ln.args?.text)}function gf(t){return t.some(e=>e.key===Ln.key&&e.when===Ln.when&&!ii([e]))}function bf(){let t=oi(),e=Ol();return ii(e)?{supported:!0,target:"vscode",installed:!0,detail:"VS Code terminal Shift+Enter binding is already installed.",configPath:t}:gf(e)?{supported:!0,target:"vscode",installed:!1,detail:`Found an existing Shift+Enter terminal binding in ${t}. Remove it manually, then rerun xeno terminal-setup.`,configPath:t}:(df(hf(t),{recursive:!0}),mf(t,JSON.stringify([...e,Ln],null,2)+`
|
|
192
|
+
`,"utf-8"),{supported:!0,target:"vscode",installed:!0,detail:"Installed the VS Code terminal Shift+Enter binding.",configPath:t})}function yf(){try{return uf("defaults",["write","com.googlecode.iterm2","GlobalKeyMap","-dict-add","0xd-0x20000-0x24",`<dict>
|
|
193
|
+
<key>Text</key>
|
|
194
|
+
<string>\\n</string>
|
|
195
|
+
<key>Action</key>
|
|
196
|
+
<integer>12</integer>
|
|
197
|
+
<key>Version</key>
|
|
198
|
+
<integer>1</integer>
|
|
199
|
+
<key>Keycode</key>
|
|
200
|
+
<integer>13</integer>
|
|
201
|
+
<key>Modifiers</key>
|
|
202
|
+
<integer>131072</integer>
|
|
203
|
+
</dict>`],{stdio:"pipe",encoding:"utf-8"}),{supported:!0,target:"iterm2",installed:!0,detail:"Installed the iTerm2 Shift+Enter binding."}}catch(t){return{supported:!0,target:"iterm2",installed:!1,detail:`Failed to install the iTerm2 key binding: ${t instanceof Error?t.message:String(t)}`}}}function Mr(t=ss()){let e=(0,B.loadConfig)();if(!t)return{supported:!1,installed:!1,detail:"Terminal integration is currently supported for VS Code terminals and iTerm2."};if(t==="vscode"){let n=oi(),s=Ml(n)?Ol():[],r=ii(s)||e.terminalShiftEnterInstalled===!0;return{supported:!0,target:t,installed:r,detail:r?"VS Code terminal Shift+Enter binding is installed.":"VS Code terminal Shift+Enter binding is not installed.",configPath:n}}return{supported:!0,target:t,installed:e.terminalShiftEnterInstalled===!0,detail:e.terminalShiftEnterInstalled===!0?"iTerm2 Shift+Enter binding is marked as installed.":"iTerm2 Shift+Enter binding is not marked as installed."}}function ai(t={}){let e=t.cwd??process.cwd(),n=t.target??ss(),s=n?n==="vscode"?bf():yf():Mr(void 0);return s.installed&&((0,B.saveConfig)({terminalShiftEnterInstalled:!0}),(0,B.setProjectOnboardingCompleted)(e,!0)),t.onOutput?.(`${s.detail}${s.configPath?` (${s.configPath})`:""}
|
|
204
|
+
`),s}async function $l(t,e){let n=t[0]?.toLowerCase()==="status",s=t.includes("--vscode")?"vscode":t.includes("--iterm")?"iterm2":void 0;if(n){let o=Mr(s);return e.onOutput(`${o.detail}${o.configPath?` (${o.configPath})`:""}
|
|
205
|
+
`),{handled:!0}}let r=ai({cwd:e.cwd,target:s,onOutput:e.onOutput});return!r.installed&&r.supported&&e.onOutput(`No changes were applied.
|
|
206
|
+
`),{handled:!0}}function kf(t){try{return wf(t).filter(n=>n!==".git"&&n!==".DS_Store").length===0}catch{return!1}}function Os(t=process.cwd()){let e=Sf(t),n=Cr(e),s=(0,B.loadConfig)(),r=ss(),o=(0,B.hasProjectOnboardingCompleted)(e),i=[];return kf(e)&&i.push({status:"info",text:"The workspace is empty. Ask XENO to scaffold a new project or clone a repository first."}),i.push(n.initialized?{status:"done",text:"Project initialization is already in place under .xeno/."}:{status:"todo",text:"Run `xeno init` or `/init` to scaffold .xeno identity, memory, plugins, and MCP config."}),r&&i.push(s.terminalShiftEnterInstalled?{status:"done",text:`Terminal Shift+Enter integration is installed for ${r}.`}:{status:"todo",text:`Run \`xeno terminal-setup\` or \`/terminal-setup\` to install Shift+Enter integration for ${r}.`}),i.push({status:"info",text:"Use `xeno chat` to explore the codebase, inspect files, and make changes."},{status:"info",text:"Use `/ctx-viz` inside chat to inspect system prompt, tools, and message context usage."}),{cwd:e,completed:o,items:i,...e===vf()?{warning:"You launched XENO in your home directory. A project directory is a better default workspace."}:{}}}function $s(t){let e=["Onboarding","",`Workspace: ${t.cwd}`,`Status: ${t.completed?"completed":"in progress"}`,"",...t.items.map(n=>`${n.status==="done"?"[x]":n.status==="todo"?"[ ]":"[-]"} ${n.text}`)];return t.warning&&e.push("",`Warning: ${t.warning}`),e.join(`
|
|
207
|
+
`)}async function Ll(t,e){let n=t[0]?.toLowerCase();if(n==="done")return(0,B.setProjectOnboardingCompleted)(e.cwd,!0),e.onOutput(`[ok] Marked onboarding as completed for this workspace.
|
|
208
|
+
`),{handled:!0};if(n==="reset")return(0,B.setProjectOnboardingCompleted)(e.cwd,!1),e.onOutput(`[ok] Reset onboarding status for this workspace.
|
|
209
|
+
`),{handled:!0};let s=Os(e.cwd),r=$s(s).split(`
|
|
210
|
+
`);return e.onPanel?(await e.onPanel({title:"Onboarding",subtitle:s.cwd,lines:r,cards:[{title:"Status",value:s.completed?"Done":"Todo"},{title:"Items",value:String(s.items.length)}]}),{handled:!0}):(e.onOutput(`${r.join(`
|
|
211
|
+
`)}
|
|
212
|
+
`),{handled:!0})}$n();var xf={"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 li(t=Ze){return xf[t]??[]}function Pf(t=Ze){let e=(0,B.loadConfig)().lastReleaseNotesSeen;return li(t).length>0&&e!==t}function rs(t=Ze){(0,B.saveConfig)({lastReleaseNotesSeen:t})}function Or(t){let e=t??Ze,n=li(e);return n.length===0?`No release notes available for version ${e}.`:[`Release notes for version ${e}`,"",...n.map(s=>`- ${s}`)].join(`
|
|
213
|
+
`)}function Nl(t=Ze){if(Pf(t))return[`What's new in XENO AGENT v${t}`,...li(t).map(e=>`- ${e}`),"","Run `xeno release-notes` to view this again."].join(`
|
|
214
|
+
`)}hn();import*as Fn from"path";var Ot={};Me(Ot,s_);import*as s_ from"@xeno-corporation/xeno-agent-sdk/utils";import{execSync as Tf}from"child_process";function ci(t,e){try{return Tf(t,{cwd:e,encoding:"utf-8",maxBuffer:10*1024*1024,timeout:3e4}).trim()}catch{return""}}function Bl(t){return ci("git rev-parse --is-inside-work-tree",t)==="true"}function _f(t){return/^[a-zA-Z0-9._~^/\-]+$/.test(t)}function Dl(t,e){let n=["git","diff"];if(t.staged)n.push("--staged");else if(t.range){if(!_f(t.range))return"";n.push(t.range)}else n.push("HEAD~1");n.push("--stat");let s=ci(n.join(" "),e),r=n.filter(i=>i!=="--stat");if(t.files){if(!/^[a-zA-Z0-9._/*\-\s\\:]+$/.test(t.files)||/[;&|`$(){}<>!]/.test(t.files))return"";r.push("--",t.files)}let o=ci(r.join(" "),e);return o?`## Diff Stats
|
|
215
|
+
${s}
|
|
216
|
+
|
|
217
|
+
## Full Diff
|
|
218
|
+
${o}`:""}function Fl(t,e){return`You are performing a code review. Analyze the following git diff and provide a structured review.
|
|
219
|
+
|
|
220
|
+
${e==="security"?"Focus specifically on SECURITY issues: injection vulnerabilities, authentication/authorization flaws, data exposure, insecure defaults, cryptographic misuse, path traversal, and unsafe deserialization.":e==="performance"?"Focus specifically on PERFORMANCE issues: algorithmic complexity, unnecessary allocations, missing caching, N+1 queries, unbounded growth, blocking I/O, and memory leaks.":"Review all aspects: bugs, security issues, performance problems, code style, error handling, and missing tests."}
|
|
221
|
+
|
|
222
|
+
For each issue found, categorize it:
|
|
223
|
+
- CRITICAL: Bugs, security vulnerabilities, data loss risks
|
|
224
|
+
- WARNING: Performance issues, potential bugs, error handling gaps
|
|
225
|
+
- SUGGESTION: Style improvements, refactoring opportunities, best practices
|
|
226
|
+
|
|
227
|
+
Format your response EXACTLY as follows:
|
|
228
|
+
|
|
229
|
+
## Code Review
|
|
230
|
+
|
|
231
|
+
### Issues Found
|
|
232
|
+
- [CRITICAL] Description of critical issue (file:line if applicable)
|
|
233
|
+
- [WARNING] Description of warning (file:line if applicable)
|
|
234
|
+
- [SUGGESTION] Description of suggestion (file:line if applicable)
|
|
235
|
+
|
|
236
|
+
### Summary
|
|
237
|
+
N issues found, M suggestions. Overall: [needs fixes before merge | approve with suggestions | clean].
|
|
238
|
+
|
|
239
|
+
If no issues are found, say "No issues found. Clean code." in the summary.
|
|
240
|
+
|
|
241
|
+
---
|
|
242
|
+
|
|
243
|
+
${t}`}async function Ul(t,e){let n=e.cwd;if(!Bl(n))return e.onOutput(`[!] Not a git repository. /review requires git.
|
|
244
|
+
`),{handled:!0};let s={cwd:n};for(let i=0;i<t.length;i++){let a=t[i]?.toLowerCase();if(a){if(a==="--staged")s.staged=!0;else if(a==="--range"&&t[i+1])s.range=t[i+1],i++;else if(a==="--files"&&t[i+1])s.files=t[i+1],i++;else if(a==="--focus"&&t[i+1]){let l=t[i+1].toLowerCase();(l==="security"||l==="performance")&&(s.focus=l),i++}}}let r=Dl(s,n);if(!r)return e.onOutput(`[!] No changes found to review.
|
|
245
|
+
`),s.staged&&e.onOutput(" Tip: Stage changes with `git add` first, or use /review without --staged.\n"),{handled:!0};let o=Fl(r,s.focus);return e.onOutput(`[review] Sending diff to AI for review...
|
|
246
|
+
`),{handled:!0,messages:[...e.messages,{role:"user",content:o}]}}async function jl(t){let e=t.cwd??process.cwd(),n=t.onOutput??(c=>process.stdout.write(c));if(!Bl(e)){n("[!] Not a git repository. `xeno review` requires git.\n"),process.exitCode=1;return}let s=Dl(t,e);if(!s){n(`[!] No changes found to review.
|
|
247
|
+
`),t.staged&&n(" Tip: Stage changes with `git add` first.\n");return}let r=Fl(s,t.focus),o=t.apiKey||process.env.XENO_API_KEY||"",i=t.baseURL||process.env.XENO_BASE_URL||"https://api.xenostudio.ai",a=t.model||process.env.XENO_MODEL||"xenon-3",l=t.maxTokens??4096;n(`[review] Reviewing changes with ${a}...
|
|
248
|
+
|
|
249
|
+
`);try{let c=await fetch(`${i}/v1/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",...o?{Authorization:`Bearer ${o}`}:{}},body:JSON.stringify({model:a,max_tokens:l,messages:[{role:"user",content:r}],stream:!1})});if(!c.ok){let f=await c.text();n(`[!] API error ${c.status}: ${f}
|
|
250
|
+
`),process.exitCode=1;return}let p=(await c.json())?.choices?.[0]?.message?.content;p?(n(p),n(`
|
|
251
|
+
`)):n(`[!] No response from model.
|
|
252
|
+
`)}catch(c){let u=c instanceof Error?c.message:String(c);n(`[!] Review failed: ${u}
|
|
253
|
+
`),process.exitCode=1}}import{spawn as Rf}from"child_process";var Ef={interval:5,onErrorOnly:!1,maxIterations:20},Cf=[/\berror\b/i,/\bfail(ed|ure|ing)?\b/i,/\bexception\b/i,/\btraceback\b/i,/\bpanic\b/i,/\bfatal\b/i,/\bsegfault\b/i,/\bsegmentation fault\b/i,/\bdenied\b/i,/\bunhandled\b/i,/\bcannot find\b/i,/\bnot found\b/i,/\bEACCES\b/,/\bENOENT\b/,/\bECONNREFUSED\b/,/exit code [1-9]/i,/exited with (?:code |status )?[1-9]/i];function Af(t){return Cf.some(e=>e.test(t))}function If(t){let e={...Ef},n=[],s=0;for(;s<t.length;){let o=t[s];if(o==="--interval"&&s+1<t.length){let i=parseInt(t[s+1],10);if(isNaN(i)||i<1)return{error:`Invalid interval: ${t[s+1]}. Expected positive integer.`};e.interval=i,s+=2}else if(o==="--on-error-only")e.onErrorOnly=!0,s+=1;else if(o==="--max-iterations"&&s+1<t.length){let i=parseInt(t[s+1],10);if(isNaN(i)||i<1)return{error:`Invalid max-iterations: ${t[s+1]}. Expected positive integer.`};e.maxIterations=i,s+=2}else{n.push(...t.slice(s));break}}let r=n.join(" ").trim();return r?{options:e,command:r}:{error:"No command specified. Usage: /babysit [options] <command>"}}async function Vl(t,e){let n=If(t);if("error"in n)return e.onOutput(`[!] ${n.error}
|
|
254
|
+
`),e.onOutput(`
|
|
255
|
+
Usage: /babysit [--interval <seconds>] [--on-error-only] [--max-iterations <n>] <command>
|
|
256
|
+
`),e.onOutput(`
|
|
257
|
+
Examples:
|
|
258
|
+
`),e.onOutput(` /babysit npm test
|
|
259
|
+
`),e.onOutput(` /babysit --on-error-only npm run build --watch
|
|
260
|
+
`),e.onOutput(` /babysit --interval 10 --max-iterations 5 tail -f /var/log/app.log
|
|
261
|
+
`),{handled:!0};let{options:s,command:r}=n;return e.onOutput(`
|
|
262
|
+
[babysit] Starting: ${r}
|
|
263
|
+
`),e.onOutput(`[babysit] Interval: ${s.interval}s | Error-only: ${s.onErrorOnly} | Max iterations: ${s.maxIterations}
|
|
264
|
+
|
|
265
|
+
`),new Promise(o=>{let i=[],a=0,l=!1,c=null,u=null,p=!1,f=Rf(r,{shell:!0,cwd:e.cwd,stdio:["ignore","pipe","pipe"],env:{...process.env}}),m=(w,P)=>{let C=w.toString("utf-8"),$=C.split(`
|
|
266
|
+
`).filter(E=>E.length>0);for(let E of $)i.push(`[${P}] ${E}`);e.onOutput(C)};f.stdout?.on("data",w=>m(w,"stdout")),f.stderr?.on("data",w=>m(w,"stderr"));let g=async()=>{if(p||i.length===0)return;if(a>=s.maxIterations){e.onOutput(`
|
|
267
|
+
[babysit] Max iterations (${s.maxIterations}) reached. Stopping analysis.
|
|
268
|
+
`),b();return}let w=i.splice(0,i.length).join(`
|
|
269
|
+
`);if(s.onErrorOnly&&!Af(w))return;p=!0,a++;let C={role:"user",content:`[babysit analysis request]
|
|
270
|
+
${l?`The command \`${r}\` has exited with code ${c}. Here is its final output:
|
|
271
|
+
|
|
272
|
+
\`\`\`
|
|
273
|
+
${w}
|
|
274
|
+
\`\`\`
|
|
275
|
+
|
|
276
|
+
Analyze this output. If it exited with an error, diagnose the failure and suggest fixes.`:`The following output was produced by \`${r}\` (iteration ${a}/${s.maxIterations}):
|
|
277
|
+
|
|
278
|
+
\`\`\`
|
|
279
|
+
${w}
|
|
280
|
+
\`\`\`
|
|
281
|
+
|
|
282
|
+
Analyze this output and report if any issues need attention.`}`};e.onOutput(`
|
|
283
|
+
[babysit] Sending output to agent for analysis (iteration ${a})...
|
|
284
|
+
`),e.messages.push(C),p=!1},b=()=>{u&&(clearInterval(u),u=null)};f.on("error",w=>{e.onOutput(`
|
|
285
|
+
[babysit] Failed to start process: ${w.message}
|
|
286
|
+
`),b(),process.removeListener("SIGINT",v),o({handled:!0})}),f.on("close",async w=>{l=!0,c=w,e.onOutput(`
|
|
287
|
+
[babysit] Process exited with code ${w??"unknown"}
|
|
288
|
+
`),await g(),b(),process.removeListener("SIGINT",v),e.onOutput(`
|
|
289
|
+
[babysit] Summary: ${a} analysis iteration(s) performed.
|
|
290
|
+
`),w!==0?e.onOutput(`[babysit] Process failed with exit code ${w}. Check agent analysis above for diagnosis.
|
|
291
|
+
`):e.onOutput(`[babysit] Process completed successfully.
|
|
292
|
+
`),o({handled:!0})}),u=setInterval(()=>{g()},s.interval*1e3);let v=()=>{e.onOutput(`
|
|
293
|
+
[babysit] Interrupted. Stopping process...
|
|
294
|
+
`),f.kill("SIGTERM"),b(),process.removeListener("SIGINT",v)};process.on("SIGINT",v)})}Wt();var ql=2e5;function Mf(t){let e=0,n=0;for(let s of t)s.role==="user"?e++:s.role==="assistant"&&n++;return{user:e,assistant:n}}function Of(t,e,n={}){let s=n.maxContextTokens??ql,r=new R.ContextManager({maxContextTokens:s,keepRecentMessages:n.keepRecentMessages??10}),o=r.estimateTokens(t),i=Math.round(o/s*100),{user:a,assistant:l}=Mf(t),c=r.needsCompression(t),u=["",`Context: ${o.toLocaleString()} / ${s.toLocaleString()} tokens (${i}%)`,`Messages: ${t.length} (${a} user, ${l} assistant)`],p=30,f=Math.round(i/100*p),m="\u2588".repeat(f)+"\u2591".repeat(p-f);return u.push(`Usage: [${m}] ${i}%`),c?u.push("Status: Compression recommended (threshold exceeded)"):i>=60?u.push("Status: Context growing, consider compressing soon"):u.push("Status: Context within budget"),u.push("Recommended: compress when >80%"),u.push(""),e.onOutput(u.join(`
|
|
295
|
+
`)),{handled:!0}}async function Hl(t,e,n={}){if(t[0]?.toLowerCase()==="status")return Of(e.messages,e,n);let s=n.maxContextTokens??ql,r=n.keepRecentMessages??10,o=new R.ContextManager({maxContextTokens:s,keepRecentMessages:r,compressionThreshold:0}),i=o.estimateTokens(e.messages),a=e.messages.length;if(a<=r)return e.onOutput(`
|
|
296
|
+
[compact] Only ${a} messages in context (keeping last ${r}). Nothing to compress.
|
|
297
|
+
`),{handled:!0};e.onOutput(`
|
|
298
|
+
Compressing context... `);try{let l=await o.compress(e.messages,n.llmCompress),c=o.estimateTokens(l),u=Math.max(0,i-c),p=i>0?Math.round(u/i*100):0;return e.messages.length=0,e.messages.push(...l),e.onOutput(`${i.toLocaleString()} \u2192 ${c.toLocaleString()} tokens (${p}% saved)
|
|
299
|
+
`),e.onOutput(`[compact] Compressed ${a} messages to ${l.length} messages.
|
|
300
|
+
`),e.onOutput(`[compact] Kept last ${Math.min(r,a)} messages verbatim.
|
|
301
|
+
`),{handled:!0,messages:l}}catch(l){let c=l instanceof Error?l.message:String(l);return e.onOutput(`failed
|
|
302
|
+
`),e.onOutput(`[compact] Compression error: ${c}
|
|
303
|
+
`),{handled:!0,error:c}}}import{execSync as $f}from"child_process";import{existsSync as Nn,readFileSync as Wl}from"fs";import{join as Sn,basename as zl,dirname as Lf,extname as Nf}from"path";var vn={vitest:{name:"vitest",runCommand:"npx vitest run",coverageCommand:"npx vitest run --coverage",testDir:"tests",testSuffix:".test.ts"},jest:{name:"jest",runCommand:"npx jest",coverageCommand:"npx jest --coverage",testDir:"__tests__",testSuffix:".test.ts"},pytest:{name:"pytest",runCommand:"python -m pytest",coverageCommand:"python -m pytest --cov",testDir:"tests",testSuffix:"_test.py"},cargo:{name:"cargo test",runCommand:"cargo test",coverageCommand:"cargo tarpaulin",testDir:"tests",testSuffix:"_test.rs"},go:{name:"go test",runCommand:"go test ./...",coverageCommand:"go test -cover ./...",testDir:".",testSuffix:"_test.go"}};function Bf(t,e){if(e){let s=e.toLowerCase().replace(/\s+/g,"");return s==="cargotest"?vn.cargo??null:s==="gotest"?vn.go??null:vn[s]??null}let n=Sn(t,"package.json");if(Nn(n))try{let s=JSON.parse(Wl(n,"utf-8")),r={...s.devDependencies,...s.dependencies};if(r.vitest)return vn.vitest;if(r.jest)return vn.jest}catch{}return Nn(Sn(t,"pyproject.toml"))||Nn(Sn(t,"setup.py"))?vn.pytest:Nn(Sn(t,"Cargo.toml"))?vn.cargo:Nn(Sn(t,"go.mod"))?vn.go:null}function Xl(t,e){try{return{stdout:$f(t,{cwd:e,encoding:"utf-8",maxBuffer:10485760,timeout:12e4,stdio:["pipe","pipe","pipe"]}).trim(),success:!0}}catch(n){let s=n;return{stdout:[s.stdout??"",s.stderr??""].filter(Boolean).join(`
|
|
304
|
+
`).trim(),success:!1}}}function Df(t,e,n,s){return`Analyze the following source code and generate comprehensive unit tests.
|
|
305
|
+
${s==="edge-cases"?"Focus heavily on edge cases: empty inputs, null/undefined values, boundary values, overflow, underflow, and unusual but valid inputs.":s==="error-handling"?"Focus heavily on error handling: invalid inputs, thrown exceptions, rejected promises, timeout scenarios, and recovery paths.":s==="integration"?"Focus on integration testing: how this module interacts with its dependencies, mock boundaries, and end-to-end flows through this module.":"Include: happy path, edge cases, error cases, boundary values."}
|
|
306
|
+
Use the project's test framework: ${n.name}
|
|
307
|
+
Follow existing test patterns in the project.
|
|
308
|
+
|
|
309
|
+
The source file is: ${e}
|
|
310
|
+
|
|
311
|
+
Generate ONLY the test file content \u2014 no explanation, no markdown fences.
|
|
312
|
+
Include all necessary imports. Use descriptive test names.
|
|
313
|
+
|
|
314
|
+
---
|
|
315
|
+
|
|
316
|
+
${t}`}async function Kl(t,e){let n=e.cwd,s={cwd:n};for(let o=0;o<t.length;o++){let i=t[o]?.toLowerCase();if(i)if(i==="generate"&&!s.subcommand)s.subcommand="generate",t[o+1]&&!t[o+1].startsWith("--")&&(s.file=t[o+1],o++);else if(i==="coverage"&&!s.subcommand)s.subcommand="coverage";else if(i==="--framework"&&t[o+1])s.framework=t[o+1],o++;else if(i==="--dry-run")s.dryRun=!0;else if(i==="--focus"&&t[o+1]){let a=t[o+1].toLowerCase();(a==="edge-cases"||a==="error-handling"||a==="integration")&&(s.focus=a),o++}else!s.file&&!i.startsWith("--")&&s.subcommand==="generate"&&(s.file=t[o])}let r=Bf(n,s.framework);return r?s.subcommand==="generate"?Uf(s,r,e):s.subcommand==="coverage"?jf(r,e):Ff(r,e):(e.onOutput(`[!] Could not detect test framework. Use --framework <name> to specify.
|
|
317
|
+
`),e.onOutput(` Supported: vitest, jest, pytest, cargo, go
|
|
318
|
+
`),{handled:!0})}async function Ff(t,e){e.onOutput(`[test] Running tests with ${t.name}...
|
|
319
|
+
|
|
320
|
+
`);let n=Xl(t.runCommand,e.cwd);if(n.success)e.onOutput(n.stdout+`
|
|
321
|
+
|
|
322
|
+
`),e.onOutput(`[test] All tests passed.
|
|
323
|
+
`);else{let s=`The following test run failed. Analyze the output and provide a clear summary of:
|
|
324
|
+
1. How many tests passed vs failed
|
|
325
|
+
2. Which specific tests failed and why
|
|
326
|
+
3. Suggested fixes for each failure
|
|
327
|
+
|
|
328
|
+
Test framework: ${t.name}
|
|
329
|
+
Test output:
|
|
330
|
+
\`\`\`
|
|
331
|
+
${n.stdout.slice(0,8e3)}
|
|
332
|
+
\`\`\``;return e.onOutput(`[test] Tests failed. Sending output to AI for analysis...
|
|
333
|
+
`),{handled:!0,messages:[...e.messages,{role:"user",content:s}]}}return{handled:!0}}async function Uf(t,e,n){if(!t.file)return n.onOutput(`[!] Usage: /test generate <file> [--dry-run] [--focus <area>]
|
|
334
|
+
`),{handled:!0};let s=Sn(n.cwd,t.file);if(!Nn(s))return n.onOutput(`[!] File not found: ${t.file}
|
|
335
|
+
`),{handled:!0};let r;try{r=Wl(s,"utf-8")}catch(a){let l=a instanceof Error?a.message:String(a);return n.onOutput(`[!] Failed to read file: ${l}
|
|
336
|
+
`),{handled:!0}}if(!r.trim())return n.onOutput(`[!] Source file is empty.
|
|
337
|
+
`),{handled:!0};let o=Df(r,t.file,e,t.focus),i=t.dryRun?"[test] Dry run \u2014 ":"[test] ";if(n.onOutput(`${i}Generating tests for ${zl(t.file)} using ${e.name}...
|
|
338
|
+
`),t.dryRun)n.onOutput(`[test] Generated tests will be shown but NOT written to disk.
|
|
339
|
+
`);else{let a=Nf(t.file),c=`${zl(t.file,a)}${e.testSuffix}`,u=Sn(Lf(s),"..",e.testDir),p=Sn(u,c);Nn(p)&&(n.onOutput(`[test] WARNING: Test file already exists: ${p}
|
|
340
|
+
`),n.onOutput(`[test] The generated tests may overwrite existing tests.
|
|
341
|
+
`)),n.onOutput(`[test] Tests will be written to: ${p}
|
|
342
|
+
`)}return{handled:!0,messages:[...n.messages,{role:"user",content:o}]}}async function jf(t,e){e.onOutput(`[test] Running tests with coverage using ${t.name}...
|
|
343
|
+
|
|
344
|
+
`);let n=Xl(t.coverageCommand,e.cwd);return e.onOutput(n.stdout+`
|
|
345
|
+
`),n.success||e.onOutput(`
|
|
346
|
+
[test] Coverage run completed with failures. See output above.
|
|
347
|
+
`),{handled:!0}}import{execSync as Yl}from"child_process";import{existsSync as Bn,readFileSync as Vf}from"fs";import{join as Dn,basename as qf}from"path";function Hf(t){let e={type:"unknown",name:qf(t),suggestedTargets:[],hasDockerfile:Bn(Dn(t,"Dockerfile")),hasVercelConfig:Bn(Dn(t,"vercel.json")),hasGhPages:!1,isNpmPackage:!1},n=Dn(t,"package.json");if(Bn(n))try{let s=JSON.parse(Vf(n,"utf-8"));e.name=s.name??e.name;let r={...s.devDependencies,...s.dependencies};r.next?(e.type="nextjs",e.suggestedTargets.push("vercel","docker")):r.react||r.vue||r.svelte?(e.type=r.react?"react":r.vue?"vue":"svelte",e.suggestedTargets.push("vercel","gh-pages")):r.express||r.fastify||r.koa?(e.type="node-server",e.suggestedTargets.push("docker")):e.type="node",!(s.private===!0)&&s.main&&(e.isNpmPackage=!0,e.suggestedTargets.push("npm"))}catch{}return(Bn(Dn(t,"pyproject.toml"))||Bn(Dn(t,"setup.py")))&&(e.type="python",e.suggestedTargets.push("docker")),Bn(Dn(t,"Cargo.toml"))&&(e.type="rust",e.suggestedTargets.push("docker")),Bn(Dn(t,"go.mod"))&&(e.type="go",e.suggestedTargets.push("docker")),!e.suggestedTargets.includes("docker")&&e.hasDockerfile&&e.suggestedTargets.unshift("docker"),e.suggestedTargets.includes("custom")||e.suggestedTargets.push("custom"),e}function zf(t,e){try{return{stdout:Yl(t,{cwd:e,encoding:"utf-8",maxBuffer:10485760,timeout:3e5,stdio:["pipe","pipe","pipe"]}).trim(),success:!0}}catch(n){let s=n;return{stdout:[s.stdout??"",s.stderr??""].filter(Boolean).join(`
|
|
348
|
+
`).trim(),success:!1}}}function Gl(t,e,n){return`You are a deployment assistant. Based on the following project information, generate the deployment configuration and commands needed.
|
|
349
|
+
|
|
350
|
+
Project: ${t.name}
|
|
351
|
+
Type: ${t.type}
|
|
352
|
+
Target: ${e}
|
|
353
|
+
Environment: ${n}
|
|
354
|
+
Has Dockerfile: ${t.hasDockerfile}
|
|
355
|
+
Has vercel.json: ${t.hasVercelConfig}
|
|
356
|
+
|
|
357
|
+
For target "${e}", provide:
|
|
358
|
+
1. Any configuration files that need to be created or updated
|
|
359
|
+
2. Step-by-step deployment commands
|
|
360
|
+
3. Any environment variables or secrets needed
|
|
361
|
+
4. Post-deployment verification steps
|
|
362
|
+
|
|
363
|
+
Be specific and actionable. If configuration files are needed, provide their full contents.`}function Wf(t){return`Analyze the following project and suggest the best deployment strategy.
|
|
364
|
+
|
|
365
|
+
Project: ${t.name}
|
|
366
|
+
Type: ${t.type}
|
|
367
|
+
Has Dockerfile: ${t.hasDockerfile}
|
|
368
|
+
Has vercel.json: ${t.hasVercelConfig}
|
|
369
|
+
Is npm package: ${t.isNpmPackage}
|
|
370
|
+
Suggested targets: ${t.suggestedTargets.join(", ")}
|
|
371
|
+
|
|
372
|
+
Provide:
|
|
373
|
+
1. Recommended deployment target and why
|
|
374
|
+
2. Required setup steps
|
|
375
|
+
3. Estimated deployment time
|
|
376
|
+
4. Any prerequisites or considerations
|
|
377
|
+
|
|
378
|
+
Format the response as a clear, actionable deployment plan.`}function Xf(t,e,n,s){let r=s?"[dry-run] Would execute: ":"";switch(t){case"docker":{let o=`${e.name}:${n}`;return{description:`Docker deployment (${n})`,commands:[`${r}docker build -t ${o} .`,`${r}docker tag ${o} ${o}`]}}case"vercel":return{description:`Vercel deployment (${n})`,commands:[n==="production"?`${r}vercel --prod`:`${r}vercel`]};case"gh-pages":return{description:"GitHub Pages deployment",commands:[`${r}npm run build`,`${r}npx gh-pages -d dist`]};case"npm":return{description:"npm publish",commands:[`${r}npm run prepublishOnly`,`${r}npm publish --access public`]};case"custom":return{description:"Custom deployment",commands:[`${r}npm run deploy`]}}}async function Jl(t,e){let n=e.cwd,s={cwd:n};for(let a=0;a<t.length;a++){let l=t[a]?.toLowerCase();if(l)if(l==="--target"&&t[a+1]){let c=t[a+1].toLowerCase();["docker","vercel","gh-pages","npm","custom"].includes(c)&&(s.target=c),a++}else if(l==="--dry-run")s.dryRun=!0;else if(l==="--env"&&t[a+1]){let c=t[a+1].toLowerCase();(c==="staging"||c==="production")&&(s.env=c),a++}else!l.startsWith("--")&&!s.target&&["docker","vercel","gh-pages","npm","custom"].includes(l)&&(s.target=l)}let r=Hf(n),o=s.env??"staging";if(!s.target){let a=Wf(r);return e.onOutput(`[deploy] Analyzing project "${r.name}" (${r.type})...
|
|
379
|
+
`),e.onOutput(`[deploy] Detected targets: ${r.suggestedTargets.join(", ")}
|
|
380
|
+
`),e.onOutput(`[deploy] Sending to AI for deployment analysis...
|
|
381
|
+
`),{handled:!0,messages:[...e.messages,{role:"user",content:a}]}}if(!s.dryRun)try{let a=Yl("git status --porcelain",{cwd:n,encoding:"utf-8",timeout:1e4}).trim();a.length>0&&(e.onOutput(`[deploy] WARNING: You have uncommitted changes in this repository.
|
|
382
|
+
`),e.onOutput(`[deploy] Consider committing or stashing your changes before deploying.
|
|
383
|
+
`),e.onOutput(`[deploy] Modified files:
|
|
384
|
+
${a.split(`
|
|
385
|
+
`).slice(0,10).map(l=>` ${l}`).join(`
|
|
386
|
+
`)}
|
|
387
|
+
`),a.split(`
|
|
388
|
+
`).length>10&&e.onOutput(` ... and ${a.split(`
|
|
389
|
+
`).length-10} more
|
|
390
|
+
`),e.onOutput(`
|
|
391
|
+
`))}catch{}let i=Xf(s.target,r,o,s.dryRun??!1);if(e.onOutput(`[deploy] ${i.description}
|
|
392
|
+
`),s.dryRun){e.onOutput(`[deploy] Dry run \u2014 no commands will be executed.
|
|
393
|
+
|
|
394
|
+
`);for(let a of i.commands)e.onOutput(` ${a}
|
|
395
|
+
`);return e.onOutput(`
|
|
396
|
+
[deploy] Dry run complete.
|
|
397
|
+
`),{handled:!0}}if(s.target==="docker"&&!r.hasDockerfile){let a=Gl(r,s.target,o);return e.onOutput(`[deploy] No Dockerfile found. Asking AI to generate deployment config...
|
|
398
|
+
`),{handled:!0,messages:[...e.messages,{role:"user",content:a}]}}if(s.target==="vercel"&&!r.hasVercelConfig&&r.type!=="nextjs"){let a=Gl(r,s.target,o);return e.onOutput(`[deploy] No vercel.json found. Asking AI to generate deployment config...
|
|
399
|
+
`),{handled:!0,messages:[...e.messages,{role:"user",content:a}]}}e.onOutput(`
|
|
400
|
+
`);for(let a of i.commands){e.onOutput(`$ ${a}
|
|
401
|
+
`);let l=zf(a,n);if(e.onOutput(l.stdout+`
|
|
402
|
+
`),!l.success){let c=`The following deployment command failed. Analyze the error and suggest a fix.
|
|
403
|
+
|
|
404
|
+
Command: ${a}
|
|
405
|
+
Target: ${s.target}
|
|
406
|
+
Project type: ${r.type}
|
|
407
|
+
|
|
408
|
+
Output:
|
|
409
|
+
\`\`\`
|
|
410
|
+
${l.stdout.slice(0,4e3)}
|
|
411
|
+
\`\`\``;return e.onOutput(`
|
|
412
|
+
[deploy] Command failed. Sending to AI for analysis...
|
|
413
|
+
`),{handled:!0,messages:[...e.messages,{role:"user",content:c}]}}}return e.onOutput(`
|
|
414
|
+
[deploy] Deployment complete.
|
|
415
|
+
`),{handled:!0}}function Kf(t){let e=t.indexOf(":");return{approvalKey:t,toolName:e>=0?t.slice(0,e):t,matcher:e>=0?t.slice(e+1):""}}function $r(t){return(0,B.listProjectAllowedTools)(t).map(Kf)}function Lr(t,e){return(0,B.listProjectAllowedTools)(t).includes(e)?((0,B.removeProjectAllowedTool)(t,e),!0):!1}function Nr(t){let e=(0,B.listProjectAllowedTools)(t);return e.length>0&&(0,B.clearProjectAllowedTools)(t),e.length}import{existsSync as uh}from"fs";import{mkdir as dh}from"fs/promises";import{dirname as ph,join as ui,resolve as di}from"path";import{loadConfiguredMcpServers as mh}from"@xeno-corporation/xeno-agent-sdk";import{existsSync as Ls,mkdirSync as th}from"fs";import{access as nh,readdir as ac,readFile as sh}from"fs/promises";import{constants as rh}from"fs";import{join as Ns,resolve as oh}from"path";Wt();import{loadConfiguredMcpServers as ih}from"@xeno-corporation/xeno-agent-sdk";$n();import{spawn as Gf}from"child_process";import{resolve as Ql}from"path";var ec="@xeno-corporation/xeno-agent-cli";function Zl(t){return t.trim().replace(/^v/i,"").split(".").map(e=>Number.parseInt(e.replace(/[^0-9].*$/,""),10)||0)}function Yf(t,e){let n=Zl(t),s=Zl(e),r=Math.max(n.length,s.length);for(let o=0;o<r;o+=1){let i=n[o]??0,a=s[o]??0;if(i>a)return 1;if(i<a)return-1}return 0}function tc(t){return t?.trim().toLowerCase()==="next"?"next":"latest"}function nc(t=process.env){let e=(t.npm_config_user_agent??"").toLowerCase();return e.startsWith("pnpm/")?"pnpm":e.startsWith("yarn/")?"yarn":"npm"}function Jf(t){let e=t?.argv1?Ql(t.argv1):"",n=Ql(t?.cwd??process.cwd());return e?e.includes("node_modules")&&e.startsWith(n)?"workspace":"global":"unknown"}function sc(t,e){return`${t}@${e}`}function Qf(t,e,n){let s=sc(t,e);return n==="pnpm"?`pnpm add -g ${s}`:n==="yarn"?`yarn global add ${s}`:`npm install -g ${s}`}function Zf(t,e,n){let s=`${t}@${e}`;return n==="pnpm"?`pnpm add -g ${s}`:n==="yarn"?`yarn global add ${s}`:`npm install -g ${s}`}function eh(t,e,n){let s=sc(t,e);return n==="pnpm"?{command:process.platform==="win32"?"pnpm.cmd":"pnpm",args:["add","-g",s]}:n==="yarn"?{command:process.platform==="win32"?"yarn.cmd":"yarn",args:["global","add",s]}:{command:process.platform==="win32"?"npm.cmd":"npm",args:["install","-g",s]}}async function Br(t){let e=t?.packageName??ec,n=t?.currentVersion??Ze,s=tc(t?.channel??t?.env?.XENO_RELEASE_CHANNEL),r=t?.env??process.env,o=nc(r),i=Jf({argv1:t?.argv1??process.argv[1],cwd:t?.cwd}),a=t?.fetchImpl??fetch,l=t?.timeoutMs??2500,c=Qf(e,s,o),u=Zf(e,n,o),p=new Date().toISOString(),f=[],m=new AbortController,g=setTimeout(()=>m.abort(),l);i==="workspace"&&f.push("CLI appears to be running from a workspace checkout; update the dependency or rebuild locally instead of relying on a global install.");try{let b=await a(`https://registry.npmjs.org/${encodeURIComponent(e)}`,{signal:m.signal});if(!b.ok)return{packageName:e,channel:s,currentVersion:n,updateAvailable:!1,packageManager:o,installContext:i,installCommand:c,rollbackCommand:u,checkedAt:p,warnings:f,error:`Registry request failed with ${b.status}`};let w=(await b.json())["dist-tags"]?.[s];return w?{packageName:e,channel:s,currentVersion:n,latestVersion:w,updateAvailable:Yf(w,n)>0,packageManager:o,installContext:i,installCommand:c,rollbackCommand:u,checkedAt:p,warnings:f}:{packageName:e,channel:s,currentVersion:n,updateAvailable:!1,packageManager:o,installContext:i,installCommand:c,rollbackCommand:u,checkedAt:p,warnings:f,error:`Registry response did not include the ${s} dist-tag`}}catch(b){return{packageName:e,channel:s,currentVersion:n,updateAvailable:!1,packageManager:o,installContext:i,installCommand:c,rollbackCommand:u,checkedAt:p,warnings:f,error:b instanceof Error?b.message:String(b)}}finally{clearTimeout(g)}}function rc(t){let e=[];if(t.error?e.push(`Update check failed: ${t.error}`):t.latestVersion?t.updateAvailable?e.push(`Update available (${t.channel}): ${t.currentVersion} -> ${t.latestVersion}`):e.push(`XENO AGENT CLI is up to date (${t.currentVersion}) on channel ${t.channel}.`):e.push(`Unable to determine the latest published ${t.channel} version.`),e.push(`Install: ${t.installCommand}`),e.push(`Rollback: ${t.rollbackCommand}`),t.warnings.length>0)for(let n of t.warnings)e.push(`Warning: ${n}`);return e.join(`
|
|
416
|
+
`)}async function oc(t){let e=t?.packageName??ec,n=tc(t?.channel??t?.env?.XENO_RELEASE_CHANNEL),s=nc(t?.env??process.env),r=t?.spawnImpl??Gf,{command:o,args:i}=eh(e,n,s);await new Promise((a,l)=>{let c=r(o,i,{stdio:"inherit"});c.on("error",l),c.on("exit",u=>{if(u===0){a();return}l(new Error(`Updater exited with code ${u??"unknown"}`))})})}function ah(){return Ns((0,B.getConfigDir)(),"config.json")}function lh(t){return t==="ok"?"[ok]":t==="warn"?"[!]":"[x]"}async function ic(t){try{return th(t,{recursive:!0}),await nh(t,rh.W_OK),!0}catch{return!1}}async function ch(t){let e=Ns(t,".xeno","audit");return Ls(e)?{id:"audit_dir",label:"Audit directory",status:"ok",detail:`${(await ac(e)).filter(s=>s.endsWith(".jsonl")).length} audit file(s) in ${e}`}:{id:"audit_dir",label:"Audit directory",status:"warn",detail:`${e} does not exist yet`}}async function os(t){let e=oh(t?.cwd??process.cwd()),n=ah(),s=(0,B.getProjectStatePath)(e),r=(0,B.loadConfig)(),o=(0,B.loadProjectState)(e),i=ih(e),a=[];a.push({id:"user_config",label:"User config",status:Ls(n)?"ok":"warn",detail:Ls(n)?`Loaded ${n}`:`No user config at ${n}`}),a.push({id:"api_key",label:"API key",status:r.apiKey||process.env.XENO_API_KEY?"ok":"warn",detail:r.apiKey||process.env.XENO_API_KEY?"API key is configured":"No API key configured in env or user config"}),a.push({id:"workspace_trust",label:"Workspace trust",status:(0,B.isWorkspaceTrusted)(e)?"ok":"warn",detail:(0,B.isWorkspaceTrusted)(e)?`Trusted workspace (${s})`:`Workspace is not yet trusted (${s})`});let l=Ls(s);a.push({id:"project_state",label:"Project state",status:l?"ok":"warn",detail:l?`Loaded ${s}`:`Project state file does not exist yet at ${s}`});let c=Ns(e,".xeno");if(a.push({id:"workspace_storage",label:"Workspace storage",status:await ic(c)?"ok":"error",detail:await ic(c)?`Writable: ${c}`:`Cannot write to ${c}`}),a.push({id:"permission_state",label:"Permission state",status:"ok",detail:`${o.allowedTools?.length??0} persistent tool approvals, ${o.allowedDirectories?.length??0} directory approvals`}),a.push({id:"mcp_config",label:"MCP config",status:i.length>0?"ok":"warn",detail:i.length>0?`${i.length} configured server(s)`:"No MCP servers configured"}),t?.connectMcp!==!1&&i.length>0){let p=new R.MCPManager;try{let f=await p.connectConfiguredServers({cwd:e}),m=[];f.connected.length>0&&m.push(`connected ${f.connected.length}`),f.skipped.length>0&&m.push(`skipped ${f.skipped.length}`),f.denied.length>0&&m.push(`denied ${f.denied.length}`),f.errors.length>0&&m.push(`errors ${f.errors.length}`),a.push({id:"mcp_connectivity",label:"MCP connectivity",status:f.errors.length>0?f.connected.length>0?"warn":"error":"ok",detail:m.join(" | ")||"No approved MCP servers were connectable"})}finally{p.dispose()}}a.push(await ch(e));let u=await Br();return a.push({id:"cli_updates",label:"CLI updates",status:u.error||u.updateAvailable?"warn":"ok",detail:u.error?`Update check failed: ${u.error}`:u.updateAvailable?`New version available: ${u.currentVersion} -> ${u.latestVersion}`:`Current version ${u.currentVersion} is up to date`}),{generatedAt:new Date().toISOString(),cwd:e,userConfigPath:n,projectStatePath:s,checks:a,configuredMcpServers:i.map(p=>p.name)}}function Dr(t){let e=[`Doctor report for ${t.cwd}`,`Generated: ${t.generatedAt}`,""];for(let n of t.checks)e.push(`${lh(n.status)} ${n.label}: ${n.detail}`);return e.join(`
|
|
417
|
+
`)}async function lc(t){let e=Ns(t,".xeno","audit");if(!Ls(e))return;let s=(await ac(e)).filter(o=>o.endsWith(".jsonl")).sort().reverse()[0];return s?(await sh(Ns(e,s),"utf-8")).trim().split(/\r?\n/).slice(-20):void 0}function Bs(t){return Array.isArray(t)?t.map(e=>Bs(e)):!t||typeof t!="object"?t:Object.fromEntries(Object.entries(t).map(([e,n])=>{let s=e.toLowerCase();return s.includes("apikey")||s==="authorization"||s.includes("token")||s.includes("secret")?[e,n&&"[redacted]"]:[e,Bs(n)]}))}async function pi(t){let e=di(t?.cwd??process.cwd()),n=await os({cwd:e}),s=ui((0,B.getConfigDir)(),"config.json"),r=(0,B.getProjectStatePath)(e);return{generatedAt:new Date().toISOString(),cwd:e,nodeVersion:process.version,platform:process.platform,arch:process.arch,doctor:n,userConfigPath:s,projectStatePath:r,userConfig:Bs((0,B.loadConfig)()),projectState:Bs((0,B.loadProjectState)(e)),configuredMcpServers:Bs(mh(e)),...uh(ui(e,".xeno","audit"))?{recentAuditPreview:await lc(e)}:{}}}async function Ds(t){let e=di(t?.cwd??process.cwd()),n=await pi({cwd:e}),s=di(t?.outputPath??ui(e,".xeno",`bug-report-${new Date().toISOString().replace(/[:.]/g,"-")}.json`));return await dh(ph(s),{recursive:!0}),await(0,lt.writeAtomic)(s,JSON.stringify(n,null,2)+`
|
|
418
|
+
`),{path:s,bundle:n}}import{join as fh}from"path";var hh="config.json",gh=new Set(["__proto__","prototype","constructor"]);function Fs(t){return Array.isArray(t)?t.map(e=>Fs(e)):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).map(([e,n])=>[e,Fs(n)])):t}function is(t){if(Array.isArray(t))return t.map(n=>is(n));if(!t||typeof t!="object")return t;let e=Object.entries(t).filter(([,n])=>n!==void 0).map(([n,s])=>[n,is(s)]);return Object.fromEntries(e)}function cc(t){let e=t.split(".").map(n=>n.trim()).filter(n=>n.length>0);if(e.length===0)throw new Error("Config key path must not be empty");if(e.some(n=>gh.has(n)))throw new Error("Config key path contains an unsafe segment");return e}function bh(t,e,n){let s=cc(e),r=Fs(t),o=r;for(let i=0;i<s.length-1;i+=1){let a=s[i],l=o[a];(!l||typeof l!="object"||Array.isArray(l))&&(o[a]={}),o=o[a]}return o[s[s.length-1]]=Fs(n),is(r)}function yh(t,e){let n=cc(e),s=Fs(t),r=[],o=s;for(let i=0;i<n.length-1;i+=1){let a=n[i],l=o[a];if(!l||typeof l!="object"||Array.isArray(l))return is(s);r.push({parent:o,key:a}),o=l}delete o[n[n.length-1]];for(let i=r.length-1;i>=0;i-=1){let{parent:a,key:l}=r[i],c=a[l];c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length===0&&delete a[l]}return is(s)}function wh(t,e){let n=t.trim();if(e)return JSON.parse(n);if(n==="true")return!0;if(n==="false")return!1;if(n==="null")return null;if(/^-?\d+$/.test(n))return Number.parseInt(n,10);if(/^-?\d+\.\d+$/.test(n))return Number.parseFloat(n);if(n.startsWith("{")&&n.endsWith("}")||n.startsWith("[")&&n.endsWith("]")||n.startsWith('"')&&n.endsWith('"'))try{return JSON.parse(n)}catch{}return t}function uc(t,e){return t==="user"?fh((0,B.getConfigDir)(),hh):(0,B.getProjectStatePath)(e)}function mi(t,e){return{scope:t,path:uc(t,e),document:t==="user"?{...(0,B.loadConfig)()}:{...(0,B.loadProjectState)(e)}}}async function dc(t,e,n){let s=uc(t,e);return await(0,lt.writeAtomic)(s,`${JSON.stringify(is(n),null,2)}
|
|
419
|
+
`),{scope:t,path:s,document:mi(t,e).document}}async function Fr(t){let e=mi(t.scope,t.cwd),n=wh(t.rawValue,t.parseAsJson===!0),s=bh(e.document,t.keyPath,n);return{...await dc(t.scope,t.cwd,s),keyPath:t.keyPath,value:n}}async function Ur(t){let e=mi(t.scope,t.cwd),n=yh(e.document,t.keyPath);return{...await dc(t.scope,t.cwd,n),keyPath:t.keyPath}}function vh(t){if(typeof t.content=="string")return t.content;try{return JSON.stringify(t.content)}catch{return String(t.content)}}function as(t,e){return{label:t,chars:e.length,tokens:(0,Ot.estimateTokens)(e)}}function Sh(t){let n=[{label:"Identity",marker:`
|
|
420
|
+
|
|
421
|
+
# Identity
|
|
422
|
+
`},{label:"Memory",marker:`
|
|
423
|
+
|
|
424
|
+
# Memory
|
|
425
|
+
`}].map(o=>({...o,index:t.indexOf(o.marker)})).filter(o=>o.index>=0).sort((o,i)=>o.index-i.index),s=[];if(n.length===0)return[as("Core Prompt",t)];let r=n[0];r&&r.index>0&&s.push(as("Core Prompt",t.slice(0,r.index)));for(let o=0;o<n.length;o++){let i=n[o],a=n[o+1],l=i.index+i.marker.length,c=a?a.index:t.length;s.push(as(i.label,t.slice(l,c)))}return s.filter(o=>o.chars>0)}function kh(t){let e=t.map(s=>as(s.name,JSON.stringify({name:s.name,description:s.description,input_schema:s.input_schema}))).sort((s,r)=>r.tokens-s.tokens);return{aggregate:{label:"Tool Definitions",chars:e.reduce((s,r)=>s+r.chars,0),tokens:e.reduce((s,r)=>s+r.tokens,0)},topTools:e.slice(0,8)}}function fi(t){let e=as("System Prompt",t.systemPrompt),n=Sh(t.systemPrompt),s=kh(t.toolDefinitions),r=as(`Messages (${t.messages.length})`,t.messages.map(a=>`${a.role}: ${vh(a)}`).join(`
|
|
426
|
+
|
|
427
|
+
`)),o=e.tokens+s.aggregate.tokens+r.tokens,i=t.maxContextTokens??2e5;return{maxContextTokens:i,systemPrompt:e,sections:n,tools:s.aggregate,topTools:s.topTools,messages:r,totalTokens:o,usagePercent:i>0?Math.min(100,Math.round(o/i*100)):0}}function hi(t){let e=Math.max(t.totalTokens,1),n=["Context Visualization","",`Estimated context usage: ${t.totalTokens.toLocaleString()} / ${t.maxContextTokens.toLocaleString()} tokens (${t.usagePercent}%)`,"",`- ${t.systemPrompt.label}: ${t.systemPrompt.tokens.toLocaleString()} tok, ${t.systemPrompt.chars.toLocaleString()} chars`];for(let s of t.sections)n.push(` - ${s.label}: ${s.tokens.toLocaleString()} tok`);n.push(`- ${t.tools.label}: ${t.tools.tokens.toLocaleString()} tok, ${t.tools.chars.toLocaleString()} chars`);for(let s of t.topTools){let r=Math.round(s.tokens/e*100);n.push(` - ${s.label}: ${s.tokens.toLocaleString()} tok (${r}%)`)}return n.push(`- ${t.messages.label}: ${t.messages.tokens.toLocaleString()} tok, ${t.messages.chars.toLocaleString()} chars`,"",t.usagePercent>=80?"Warning: context is running low. Use /compact to compress conversation history.":"Context headroom is healthy."),n.join(`
|
|
428
|
+
`)}async function pc(t,e){if(!e.buildSystemPrompt||!e.toolDefinitions)return e.onOutput(`[!] Context visualization is not available in this session.
|
|
429
|
+
`),{handled:!0};let n=fi({systemPrompt:await e.buildSystemPrompt(),toolDefinitions:e.toolDefinitions(),messages:e.messages,maxContextTokens:e.maxContextTokens}),s=hi(n);return e.onPanel?(await e.onPanel({title:"Context Visualization",subtitle:`${n.totalTokens.toLocaleString()} tok`,lines:s.split(`
|
|
430
|
+
`),cards:[{title:"Total",value:`${n.totalTokens}`},{title:"Usage",value:`${n.usagePercent}%`},{title:"Tools",value:`${e.toolDefinitions().length}`},{title:"Messages",value:`${e.messages.length}`}]}),{handled:!0}):(e.onOutput(`${s}
|
|
431
|
+
`),{handled:!0})}import{execFileSync as mc}from"child_process";function xh(){let t=`tell application "System Events" to tell \xAC
|
|
432
|
+
(the first process whose frontmost is true) to tell \xAC
|
|
433
|
+
menu bar 1 to tell \xAC
|
|
434
|
+
menu bar item "Edit" to tell \xAC
|
|
435
|
+
menu "Edit" to tell \xAC
|
|
436
|
+
menu item "Start Dictation" to \xAC
|
|
437
|
+
if exists then click it`;try{return mc("osascript",["-e",t],{stdio:"pipe",encoding:"utf-8"}),{supported:!0,message:"System dictation started. Press Esc to stop."}}catch(e){return{supported:!0,message:`Failed to start macOS dictation: ${e instanceof Error?e.message:String(e)}`}}}function Ph(){let t=["Add-Type -Namespace Win32 -Name Native -MemberDefinition @'",'[DllImport("user32.dll")] public static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);',"'@","$VK_LWIN = 0x5B","$VK_H = 0x48","$KEYEVENTF_KEYUP = 0x0002","[Win32.Native]::keybd_event($VK_LWIN, 0, 0, 0)","[Win32.Native]::keybd_event($VK_H, 0, 0, 0)","Start-Sleep -Milliseconds 50","[Win32.Native]::keybd_event($VK_H, 0, $KEYEVENTF_KEYUP, 0)","[Win32.Native]::keybd_event($VK_LWIN, 0, $KEYEVENTF_KEYUP, 0)"].join(";");try{return mc("powershell",["-NoProfile","-NonInteractive","-Command",t],{stdio:"pipe",encoding:"utf-8"}),{supported:!0,message:"Windows voice typing started. Press Esc to stop."}}catch(e){return{supported:!0,message:`Failed to start Windows voice typing: ${e instanceof Error?e.message:String(e)}`}}}function gi(){return process.platform==="darwin"?xh():process.platform==="win32"?Ph():{supported:!1,message:"Voice typing is currently supported on macOS and Windows only."}}async function fc(t,e){let n=gi();return e.onOutput(`${n.message}
|
|
438
|
+
`),{handled:!0}}import{spawnSync as Th}from"child_process";function yi(t,e){let n=Th("gh",e,{cwd:t,encoding:"utf-8",stdio:"pipe",maxBuffer:5242880});if(n.error)throw new Error(`Failed to start gh: ${n.error.message}`);if(n.status!==0)throw new Error(n.stderr.trim()||`gh ${e.join(" ")} exited with status ${n.status}`);try{return JSON.parse(n.stdout)}catch(s){throw new Error(`Failed to parse gh output: ${s instanceof Error?s.message:String(s)}`)}}function _h(t,e){let n=yi(t,["pr","view",...e?[e]:[],"--json","number,baseRepository"]);return{number:n.number,repository:n.baseRepository}}function bi(t,e=""){let n=(t??"").trim().replace(/\r\n/g,`
|
|
439
|
+
`).split(`
|
|
440
|
+
`);return n.length===1&&n[0]===""?[`${e}> (empty)`]:n.map(s=>`${e}> ${s}`)}function Rh(t){return t?.trim()?[" ```diff",...t.replace(/\r\n/g,`
|
|
441
|
+
`).split(`
|
|
442
|
+
`).map(e=>` ${e}`)," ```"]:[]}function Eh(t,e){let n=["## Comments",""];if(t.length===0&&e.length===0)return n.push("No comments found."),n.join(`
|
|
443
|
+
`);if(t.length>0){n.push("### PR Comments","");for(let s of t){let r=s.user?.login??"unknown";n.push(`- @${r}${s.html_url?` (${s.html_url})`:""}`),n.push(...bi(s.body," ")),n.push("")}}if(e.length>0){n.push("### Review Comments","");let s=new Map(e.map(i=>[i.id,i])),r=new Map,o=i=>{let a=i,l=new Set;for(;a?.in_reply_to_id&&s.has(a.in_reply_to_id)&&!l.has(a.in_reply_to_id);)l.add(a.in_reply_to_id),a=s.get(a.in_reply_to_id);return a?.id??i.id};for(let i of[...e].sort((a,l)=>String(a.created_at??"").localeCompare(String(l.created_at??"")))){let a=o(i),l=r.get(a)??[];l.push(i),r.set(a,l)}for(let i of r.values()){let a=i[0];if(!a)continue;let l=a.user?.login??"unknown",c=a.path?`${a.path}${typeof a.line=="number"?`#L${a.line}`:""}`:"general";n.push(`- @${l} ${c}${a.html_url?` (${a.html_url})`:""}`),n.push(...Rh(a.diff_hunk)),n.push(...bi(a.body," "));for(let u of i.slice(1)){let p=u.user?.login??"unknown";n.push(` - reply @${p}`),n.push(...bi(u.body," "))}n.push("")}}return n.join(`
|
|
444
|
+
`).trimEnd()}function wi(t={}){let e=t.cwd??process.cwd(),n=_h(e,t.selector),{login:s}=n.repository.owner,{name:r}=n.repository,o=yi(e,["api",`/repos/${s}/${r}/issues/${n.number}/comments`]),i=yi(e,["api",`/repos/${s}/${r}/pulls/${n.number}/comments`]),a=Eh(o,i);return t.onOutput?.(`${a}
|
|
445
|
+
`),a}async function hc(t,e){try{wi({cwd:e.cwd,selector:t[0],onOutput:e.onOutput})}catch(n){e.onOutput(`[x] ${n instanceof Error?n.message:String(n)}
|
|
446
|
+
`)}return{handled:!0}}import{ProfileManager as Ch}from"@xeno-corporation/xeno-agent-sdk";async function gc(t,e){let n=new Ch,s=t[0]?.toLowerCase();if(!s||s==="list")return Ah(n,e);if(s==="create")return Ih(t.slice(1),n,e);if(s==="switch"){let r=t[1];return r?Mh(r,n,e):(e.onOutput(`[!] Usage: /profile switch <name>
|
|
447
|
+
`),{handled:!0})}if(s==="delete"){let r=t[1];return r?Oh(r,n,e):(e.onOutput(`[!] Usage: /profile delete <name>
|
|
448
|
+
`),{handled:!0})}if(s==="show"){let r=t[1];return $h(r,n,e)}return e.onOutput(`[!] Unknown profile subcommand: ${s}
|
|
449
|
+
`),e.onOutput(` Usage: /profile [list|create|switch|delete|show]
|
|
450
|
+
`),{handled:!0}}function Ah(t,e){let n=t.listProfiles(),s=t.getActiveProfileName();if(n.length===0)return e.onOutput(`[profile] No profiles configured.
|
|
451
|
+
`),e.onOutput(` Create one with: /profile create <name> [--model <m>]
|
|
452
|
+
`),{handled:!0};e.onOutput(`
|
|
453
|
+
**Configuration Profiles**
|
|
454
|
+
|
|
455
|
+
`);for(let r of n){let o=r.name===s,i=o?" (active)":"",a=r.model?` | model: ${r.model}`:"",l=r.baseURL?` | url: ${r.baseURL}`:"",c=r.permissionMode?` | mode: ${r.permissionMode}`:"";e.onOutput(` ${o?">":" "} ${r.name}${i}${a}${l}${c}
|
|
456
|
+
`)}return e.onOutput(`
|
|
457
|
+
`),{handled:!0}}function Ih(t,e,n){if(t.length===0)return n.onOutput(`[!] Usage: /profile create <name> [--model <m>] [--api-key <k>] [--base-url <u>] [--max-tokens <n>] [--permission-mode <mode>]
|
|
458
|
+
`),{handled:!0};let s=t[0],r={name:s};for(let o=1;o<t.length;o++){let i=t[o]?.toLowerCase(),a=t[o+1];if(i==="--model"&&a)r.model=a,o++;else if(i==="--api-key"&&a)r.apiKey=a,o++;else if(i==="--base-url"&&a)r.baseURL=a,o++;else if(i==="--max-tokens"&&a){let l=Number.parseInt(a,10);Number.isFinite(l)&&l>0&&(r.maxTokens=l),o++}else if(i==="--permission-mode"&&a){let l=a.toLowerCase();(l==="default"||l==="acceptedits"||l==="bypasspermissions")&&(r.permissionMode=l),o++}}try{e.createProfile(r),n.onOutput(`[profile] Created profile "${s}".
|
|
459
|
+
`),r.model&&n.onOutput(` Model: ${r.model}
|
|
460
|
+
`),r.baseURL&&n.onOutput(` URL: ${r.baseURL}
|
|
461
|
+
`),r.apiKey&&n.onOutput(` API key: ${r.apiKey.slice(0,8)}...
|
|
462
|
+
`)}catch(o){let i=o instanceof Error?o.message:String(o);n.onOutput(`[!] ${i}
|
|
463
|
+
`)}return{handled:!0}}function Mh(t,e,n){try{e.switchProfile(t);let s=e.getActiveProfile();n.onOutput(`[profile] Switched to "${t}".
|
|
464
|
+
`),s.model&&n.onOutput(` Model: ${s.model}
|
|
465
|
+
`),s.baseURL&&n.onOutput(` URL: ${s.baseURL}
|
|
466
|
+
`)}catch(s){let r=s instanceof Error?s.message:String(s);n.onOutput(`[!] ${r}
|
|
467
|
+
`);let o=e.listProfiles();o.length>0&&n.onOutput(` Available profiles: ${o.map(i=>i.name).join(", ")}
|
|
468
|
+
`)}return{handled:!0}}function Oh(t,e,n){try{e.deleteProfile(t),n.onOutput(`[profile] Deleted profile "${t}".
|
|
469
|
+
`)}catch(s){let r=s instanceof Error?s.message:String(s);n.onOutput(`[!] ${r}
|
|
470
|
+
`)}return{handled:!0}}function $h(t,e,n){let s=t??e.getActiveProfileName(),r=e.getProfile(s);if(!r)return n.onOutput(`[!] Profile "${s}" not found.
|
|
471
|
+
`),{handled:!0};let o=s===e.getActiveProfileName();return n.onOutput(`
|
|
472
|
+
**Profile: ${r.name}**${o?" (active)":""}
|
|
473
|
+
|
|
474
|
+
`),r.model&&n.onOutput(` Model: ${r.model}
|
|
475
|
+
`),r.baseURL&&n.onOutput(` Base URL: ${r.baseURL}
|
|
476
|
+
`),r.apiKey&&n.onOutput(` API Key: ${r.apiKey.slice(0,8)}...
|
|
477
|
+
`),r.maxTokens&&n.onOutput(` Max Tokens: ${r.maxTokens}
|
|
478
|
+
`),r.permissionMode&&n.onOutput(` Permission Mode: ${r.permissionMode}
|
|
479
|
+
`),r.plugins&&r.plugins.length>0&&n.onOutput(` Plugins: ${r.plugins.join(", ")}
|
|
480
|
+
`),r.mcpServers&&r.mcpServers.length>0&&n.onOutput(` MCP Servers: ${r.mcpServers.map(a=>a.name).join(", ")}
|
|
481
|
+
`),r.model||r.baseURL||r.apiKey||r.maxTokens||r.permissionMode||r.plugins&&r.plugins.length>0||r.mcpServers&&r.mcpServers.length>0||n.onOutput(` (no settings configured)
|
|
482
|
+
`),n.onOutput(`
|
|
483
|
+
`),{handled:!0}}Wt();var Lh="Usage: /memory context [--full] [--json] [--ndjson] [--raw] [--copy] [--stats] [--no-context] [--quiet] [--sessions 1-10] [--tokens >=120] [--chars >=200]",Nh="/memory context [--full] [--json] [--ndjson] [--raw] [--copy] [--stats] [--no-context] [--quiet] [--sessions N] [--tokens N] [--chars N]",Bh=["--copy","--stats","--no-context","--ndjson"];function Dh(t){let e=Lh,n={full:!1,json:!1,ndjson:!1,raw:!1,copy:!1,stats:!1,noContext:!1,quiet:!1};for(let s=0;s<t.length;s++){let r=t[s]?.toLowerCase();if(r){if(r==="--full"){n.full=!0;continue}if(r==="--sessions"||r==="-s"){let o=t[s+1],i=Number.parseInt(o??"",10);if(!Number.isFinite(i)||i<1||i>10)return{error:e};n.sessionLimit=i,s+=1;continue}if(r==="--tokens"||r==="-t"){let o=t[s+1],i=Number.parseInt(o??"",10);if(!Number.isFinite(i)||i<120)return{error:e};n.maxTokens=i,s+=1;continue}if(r==="--chars"||r==="-c"){let o=t[s+1],i=Number.parseInt(o??"",10);if(!Number.isFinite(i)||i<200)return{error:e};n.maxCharsPerSession=i,s+=1;continue}if(r==="--json"||r==="-j"){n.json=!0;continue}if(r==="--ndjson"){n.ndjson=!0,n.json=!0;continue}if(r==="--raw"||r==="-r"){n.raw=!0;continue}if(r==="--copy"){n.copy=!0,n.json=!0;continue}if(r==="--stats"){n.stats=!0;continue}if(r==="--no-context"){n.noContext=!0;continue}if(r==="--quiet"){n.quiet=!0;continue}return{error:`Unknown option: ${t[s]}. ${e}`}}}return n.ndjson&&n.copy?{error:`Options --ndjson and --copy cannot be combined. ${e}`}:{options:n}}async function Si(t,e){let n=t.trim();if(!n.startsWith("/"))return{handled:!1};let[s,...r]=n.slice(1).split(/\s+/),o=r.join(" ");switch(s.toLowerCase()){case"memory":return Fh(r,e);case"remember":return Vh(o,e);case"checkpoint":return r[0]==="list"?Hh(e):r[0]==="restore"&&r[1]?zh(r[1],e):qh(e);case"audit":return Kh(r,e);case"mcp":return ki(r,e);case"approved-tools":return Gh(r,e);case"review":return Ul(r,e);case"init":return await Ar({cwd:e.cwd,yes:r.includes("--yes"),onOutput:e.onOutput}),{handled:!0};case"babysit":return Vl(r,e);case"compact":return Hl(r,e);case"test":return Kl(r,e);case"deploy":return Jl(r,e);case"doctor":return Yh(r,e);case"bug-report":return Jh(r,e);case"config":return Qh(r,e);case"ctx-viz":return pc(r,e);case"onboarding":return Ll(r,e);case"release-notes":return ig(r,e);case"terminal-setup":return $l(r,e);case"listen":return fc(r,e);case"pr-comments":return hc(r,e);case"profile":return gc(r,e);case"debug":return Zh(r,e);case"eval":return eg(r,e);case"plugin":return tg(r,e);case"workspace":return ng(r,e);case"provider":return sg(r,e);case"processes":case"tasks":return rg(r,e);case"context":return og(r,e);case"help":return ag(e);default:return{handled:!1}}}async function Fh(t,e){if(!e.memoryManager)return e.onOutput(`[!] Memory system not initialized
|
|
484
|
+
`),{handled:!0};let n=t[0]?.toLowerCase();if(n==="context"||n==="planner")return jh(t.slice(1),e);try{let s=p=>p.replace(/\r\n/g,`
|
|
485
|
+
`).split(`
|
|
486
|
+
`),r=p=>`${(0,Ot.estimateTokens)(p)} tok`,o=async()=>{let p=await e.memoryManager.loadForPrompt(),f=(P,C,$)=>({id:P,title:C,summary:r($),lines:s($),editable:{value:$,onSave:async E=>{await e.memoryManager.set(P,E);let T=await o();return{cards:T.cards,sections:T.sections,panelLines:T.lines}}}}),m=p.byLevel.global??"",g=p.byLevel.project??"",b=[f("global","Global Memory",m),f("project","Project Memory",g),...p.byLevel.role?[f("role","Role Memory",p.byLevel.role)]:[],...p.byLevel.session?[f("session","Session Memory",p.byLevel.session)]:[]],v=[{title:"Total Tokens",value:String(p.totalTokens)},{title:"Loaded Levels",value:String(p.files.length)},{title:"Truncated",value:p.truncated?"yes":"no"}],w=[`Total tokens: ${p.totalTokens}`,""];return p.byLevel.global&&(w.push("Global Memory"),w.push(p.byLevel.global.slice(0,500)+(p.byLevel.global.length>500?"...":"")),w.push("")),p.byLevel.project&&(w.push("Project Memory"),w.push(p.byLevel.project.slice(0,500)+(p.byLevel.project.length>500?"...":"")),w.push("")),p.byLevel.role&&(w.push("Role Memory"),w.push(p.byLevel.role.slice(0,500)),w.push("")),p.byLevel.session&&(w.push("Session Memory"),w.push(p.byLevel.session.slice(0,500))),w.length<=2&&w.push("No memory entries found."),{memory:p,cards:v,sections:b,lines:w}},i=await o(),{memory:a,cards:l,sections:c,lines:u}=i;return e.onPanel?(await e.onPanel({title:"Current memory",subtitle:`Workspace: ${e.cwd}`,lines:u,footerHint:"\u2190/\u2192 focus \xB7 \u2191/\u2193 navigate or scroll \xB7 Enter edit \xB7 Esc close",layout:"viewport",cards:l,sections:c}),{handled:!0}):(e.onOutput(`
|
|
487
|
+
**Current Memory**
|
|
488
|
+
|
|
489
|
+
`),e.onOutput(`Total tokens: ${a.totalTokens}
|
|
490
|
+
|
|
491
|
+
`),a.byLevel.global&&(e.onOutput(`### Global Memory
|
|
492
|
+
`),e.onOutput(a.byLevel.global.slice(0,500)+(a.byLevel.global.length>500?"...":"")+`
|
|
493
|
+
|
|
494
|
+
`)),a.byLevel.project&&(e.onOutput(`### Project Memory
|
|
495
|
+
`),e.onOutput(a.byLevel.project.slice(0,500)+(a.byLevel.project.length>500?"...":"")+`
|
|
496
|
+
|
|
497
|
+
`)),a.byLevel.role&&(e.onOutput(`### Role Memory
|
|
498
|
+
`),e.onOutput(a.byLevel.role.slice(0,500)+`
|
|
499
|
+
|
|
500
|
+
`)),a.byLevel.session&&(e.onOutput(`### Session Memory
|
|
501
|
+
`),e.onOutput(a.byLevel.session.slice(0,500)+`
|
|
502
|
+
|
|
503
|
+
`)),{handled:!0})}catch(s){let r=s instanceof Error?s.message:String(s);return e.onOutput(`[x] Error loading memory: ${r}
|
|
504
|
+
`),{handled:!0,error:r}}}function Uh(t){if(t)return Fn.basename(t)}async function jh(t,e){if(!e.memoryManager)return e.onOutput(`[!] Memory system not initialized
|
|
505
|
+
`),{handled:!0};let n=Dh(t);if(!n.options)return e.onOutput(`[!] ${n.error}
|
|
506
|
+
`),{handled:!0};let{full:s,json:r,ndjson:o,raw:i,copy:a,stats:l,noContext:c,quiet:u,sessionLimit:p,maxTokens:f,maxCharsPerSession:m}=n.options,g=typeof e.memoryManager.getProjectSessionContextDefaults=="function"?e.memoryManager.getProjectSessionContextDefaults():void 0,b=p??g?.limit,v=f??g?.maxTokens,w=m??g?.maxCharsPerSession,P=p!==void 0?String(p):b!==void 0?`default (${b})`:"default",C=f!==void 0?String(f):v!==void 0?`default (${v})`:"default",$=m!==void 0?String(m):w!==void 0?`default (${w})`:"default",E=I=>I.replace(/\r\n/g,`
|
|
507
|
+
`).split(`
|
|
508
|
+
`),T=I=>`${(0,Ot.estimateTokens)(I)} tok`;try{let I=async()=>{let X=(Ne,Xe,He)=>({id:Ne,title:Xe,summary:T(He),lines:E(He),editable:{value:He,onSave:async rt=>{await e.memoryManager.set(Ne,rt);let Y=await I();return{cards:Y.cards,sections:Y.sections,panelLines:Y.panelLines}}}}),q=await e.memoryManager.loadForPrompt(),Q=await e.memoryManager.loadProjectSessionContext({excludeSessionId:Uh(e.sessionDir),limit:b,maxTokens:v,maxCharsPerSession:w}),Se=[e.memoryManager.formatForPrompt(q),Q.content].filter(Ne=>Ne&&Ne.trim().length>0).join(`
|
|
509
|
+
|
|
510
|
+
---
|
|
511
|
+
|
|
512
|
+
`),me=(0,Ot.estimateTokens)(Se),de=s||i,Ee=de?Se:Se.slice(0,1500),pe=Ee+(!de&&Se.length>Ee.length?"...":""),te=l||c,Re=Q.entries.length===0?["No prior session history available for this workspace."]:Q.entries.flatMap((Ne,Xe)=>{let He=[`Session ${Ne.sessionId}`,`Model: ${Ne.model}`,`Last activity: ${Ne.lastActivity}`,`Messages: ${Ne.messageCount}`,"",...E(Ne.excerpt)];return Xe<Q.entries.length-1&&He.push("","----------------------------------------",""),He}),Ce=q.byLevel.global??"",Ae=[{id:"overview",title:"Overview",summary:`${Q.entries.length} history entries`,lines:[`Prompt-context tokens: ${me}`,`Memory tokens: ${q.totalTokens}`,`Session-history tokens: ${Q.totalTokens}`,`Session-history entries: ${Q.entries.length}`,"",`Full view: ${s?"on":"off"}`,`Raw context: ${i?"on":"off"}`,`Stats only: ${l?"on":"off"}`,`No context: ${c?"on":"off"}`,`Quiet: ${u?"on":"off"}`,"",`Session limit: ${P}`,`Session token budget: ${C}`,`Session char budget: ${$}`,"",Q.truncated?"Prior session context was truncated to fit the token budget.":"Prior session context fit within the active token budget."]},X("global","Global Memory",Ce),...q.byLevel.project?[X("project","Project Memory",q.byLevel.project)]:[],...q.byLevel.role?[X("role","Role Memory",q.byLevel.role)]:[],...q.byLevel.session?[X("session","Session Memory",q.byLevel.session)]:[],{id:"history",title:"Prior Sessions",summary:`${Q.entries.length} sessions`,lines:Re},{id:"merged",title:"Merged Prompt",summary:de?"full payload":"preview payload",lines:te?["Context payload hidden by current flags."]:E(pe||"No prompt memory context available.")}],xe=[{title:"Prompt Context",value:String(me)},{title:"Memory Tokens",value:String(q.totalTokens)},{title:"Session Tokens",value:String(Q.totalTokens)},{title:"History Entries",value:String(Q.entries.length)}],Te=[`Total prompt-context tokens: ${me}`,`Memory tokens: ${q.totalTokens}`,`Session-history tokens: ${Q.totalTokens}`,`Session-history entries: ${Q.entries.length}`,`Full view: ${s?"on":"off"}`,`Raw context: ${i?"on":"off"}`,`Stats only: ${l?"on":"off"}`,`No context: ${c?"on":"off"}`,`Quiet: ${u?"on":"off"}`,`Session limit: ${P}`,`Session token budget: ${C}`,`Session char budget: ${$}`,""];return l?Te.push("Stats-only mode: context payload hidden."):c?Te.push("Context payload hidden (--no-context)."):Se?Te.push(...pe.split(`
|
|
513
|
+
`)):Te.push("No prompt memory context available."),{memory:q,projectSessions:Q,mergedContext:Se,mergedTokens:me,previewWithSuffix:pe,hideContext:te,cards:xe,sections:Ae,panelLines:Te}},re=await I(),{memory:ae,projectSessions:N,mergedContext:y,mergedTokens:oe,previewWithSuffix:K,hideContext:W,cards:Z,sections:le,panelLines:ce}=re;if(r){let X={kind:"planner_memory_context",totals:{promptContextTokens:oe,memoryTokens:ae.totalTokens,sessionHistoryTokens:N.totalTokens,sessionHistoryEntries:N.entries.length},options:{full:s,ndjson:o,raw:i,copy:a,stats:l,noContext:c,quiet:u,sessions:p??null,tokens:f??null,chars:m??null,effectiveSessions:b??null,effectiveTokens:v??null,effectiveChars:w??null},hasContext:y.length>0};if(W||(X.context=K),o){let q=[];q.push(JSON.stringify({kind:"planner_memory_context_totals",totals:X.totals,hasContext:X.hasContext})),q.push(JSON.stringify({kind:"planner_memory_context_options",options:X.options})),W||q.push(JSON.stringify({kind:"planner_memory_context_context",context:X.context})),e.onOutput(q.join(`
|
|
514
|
+
`)+`
|
|
515
|
+
`)}else a?e.onOutput(JSON.stringify(X)+`
|
|
516
|
+
`):e.onOutput(JSON.stringify(X,null,2)+`
|
|
517
|
+
`);return{handled:!0}}return e.onPanel?(await e.onPanel({title:"Planner memory context",subtitle:"Injected into system prompt",lines:ce,footerHint:`\u2190/\u2192 focus \xB7 \u2191/\u2193 navigate or scroll \xB7 Enter edit \xB7 PgUp/PgDn page \xB7 Home/End jump \xB7 Esc close \xB7 ${Bh.join(" ")}`,layout:"viewport",cards:Z,sections:le}),{handled:!0}):(u||(e.onOutput(`
|
|
518
|
+
**Planner Memory Context**
|
|
519
|
+
|
|
520
|
+
`),e.onOutput(`Total prompt-context tokens: ${oe}
|
|
521
|
+
`),e.onOutput(`Memory tokens: ${ae.totalTokens}
|
|
522
|
+
`),e.onOutput(`Session-history tokens: ${N.totalTokens}
|
|
523
|
+
`),e.onOutput(`Session-history entries: ${N.entries.length}
|
|
524
|
+
`),e.onOutput(`Full view: ${s?"on":"off"}
|
|
525
|
+
`),e.onOutput(`Raw context: ${i?"on":"off"}
|
|
526
|
+
`),e.onOutput(`Stats only: ${l?"on":"off"}
|
|
527
|
+
`),e.onOutput(`No context: ${c?"on":"off"}
|
|
528
|
+
`),e.onOutput(`Quiet: ${u?"on":"off"}
|
|
529
|
+
|
|
530
|
+
`),e.onOutput(`Session limit: ${P}
|
|
531
|
+
`),e.onOutput(`Session token budget: ${C}
|
|
532
|
+
`),e.onOutput(`Session char budget: ${$}
|
|
533
|
+
|
|
534
|
+
`)),u?(e.onOutput(`prompt_context_tokens=${oe}
|
|
535
|
+
`),e.onOutput(`memory_tokens=${ae.totalTokens}
|
|
536
|
+
`),e.onOutput(`session_history_tokens=${N.totalTokens}
|
|
537
|
+
`),e.onOutput(`session_history_entries=${N.entries.length}
|
|
538
|
+
`),e.onOutput(`full=${s}
|
|
539
|
+
`),e.onOutput(`raw=${i}
|
|
540
|
+
`),e.onOutput(`stats=${l}
|
|
541
|
+
`),e.onOutput(`no_context=${c}
|
|
542
|
+
`),e.onOutput(`sessions=${P}
|
|
543
|
+
`),e.onOutput(`tokens=${C}
|
|
544
|
+
`),e.onOutput(`chars=${$}
|
|
545
|
+
`),l?e.onOutput(`context_hidden=stats
|
|
546
|
+
`):c?e.onOutput(`context_hidden=no-context
|
|
547
|
+
`):y?(e.onOutput(`context<<EOF
|
|
548
|
+
`),e.onOutput(K+`
|
|
549
|
+
`),e.onOutput(`EOF
|
|
550
|
+
`)):e.onOutput(`context=
|
|
551
|
+
`)):l?e.onOutput(`Stats-only mode: context payload hidden.
|
|
552
|
+
`):c?e.onOutput(`Context payload hidden (--no-context).
|
|
553
|
+
`):y?e.onOutput(K+`
|
|
554
|
+
`):e.onOutput(`No prompt memory context available.
|
|
555
|
+
`),{handled:!0})}catch(I){let re=I instanceof Error?I.message:String(I);return e.onOutput(`[x] Error loading planner context: ${re}
|
|
556
|
+
`),{handled:!0,error:re}}}async function Vh(t,e){if(!t)return e.onOutput(`[!] Usage: /remember <text to remember>
|
|
557
|
+
`),{handled:!0};if(!e.memoryManager)return e.onOutput(`[!] Memory system not initialized
|
|
558
|
+
`),{handled:!0};try{return await e.memoryManager.add("project",t,"user"),e.onOutput(`[ok] Added to project memory: "${t}"
|
|
559
|
+
`),{handled:!0}}catch(n){let s=n instanceof Error?n.message:String(n);return e.onOutput(`[x] Error saving memory: ${s}
|
|
560
|
+
`),{handled:!0,error:s}}}async function qh(t){if(!t.checkpointManager)return t.onOutput(`[!] Checkpoint system not initialized (no active session)
|
|
561
|
+
`),{handled:!0};try{let e=await t.checkpointManager.create({trigger:"manual",messages:t.messages,description:"Manual checkpoint"});return t.onPanel?await t.onPanel({title:"Checkpoint created",subtitle:e.id,lines:[`Trigger: ${e.trigger}`,`Messages saved: ${t.messages.length}`,`Created: ${new Date(e.createdAt).toLocaleString()}`]}):(t.onOutput(`[ok] Checkpoint created: ${e.id}
|
|
562
|
+
`),t.onOutput(` Messages saved: ${t.messages.length}
|
|
563
|
+
`)),{handled:!0}}catch(e){let n=e instanceof Error?e.message:String(e);return t.onOutput(`[x] Error creating checkpoint: ${n}
|
|
564
|
+
`),{handled:!0,error:n}}}async function Hh(t){if(!t.checkpointManager)return t.onOutput(`[!] Checkpoint system not initialized
|
|
565
|
+
`),{handled:!0};try{let e=await t.checkpointManager.list();if(e.length===0)return t.onPanel?await t.onPanel({title:"Checkpoints",lines:["No checkpoints found."]}):t.onOutput(`No checkpoints found.
|
|
566
|
+
`),{handled:!0};if(t.onPanel){let n=[];for(let s of e){let r=new Date(s.createdAt).toLocaleString();n.push(`${s.id.slice(0,8)} ${s.trigger} ${s.messageCount} msgs ${r}`),s.name&&n.push(` ${s.name}`)}return await t.onPanel({title:"Checkpoints",subtitle:`${e.length} saved`,lines:n}),{handled:!0}}t.onOutput(`
|
|
567
|
+
**Checkpoints**
|
|
568
|
+
|
|
569
|
+
`);for(let n of e){let s=new Date(n.createdAt).toLocaleString();t.onOutput(` ${n.id.slice(0,8)} | ${n.trigger} | ${n.messageCount} msgs | ${s}
|
|
570
|
+
`),n.name&&t.onOutput(` - ${n.name}
|
|
571
|
+
`)}return{handled:!0}}catch(e){let n=e instanceof Error?e.message:String(e);return t.onOutput(`[x] Error listing checkpoints: ${n}
|
|
572
|
+
`),{handled:!0,error:n}}}async function zh(t,e){if(!e.checkpointManager)return e.onOutput(`[!] Checkpoint system not initialized
|
|
573
|
+
`),{handled:!0};try{let n=await e.checkpointManager.restore(t);return e.onPanel?await e.onPanel({title:"Checkpoint restored",subtitle:t,lines:[`Messages restored: ${n.messages.length}`,`Timestamp: ${new Date().toLocaleString()}`]}):(e.onOutput(`[ok] Restored checkpoint: ${t}
|
|
574
|
+
`),e.onOutput(` Messages restored: ${n.messages.length}
|
|
575
|
+
`)),{handled:!0,messages:n.messages}}catch(n){let s=n instanceof Error?n.message:String(n);return e.onOutput(`[x] Failed to restore: ${s}
|
|
576
|
+
`),{handled:!0,error:s}}}function vi(t){return Object.fromEntries([...t.entries()].sort((e,n)=>e[0].localeCompare(n[0])))}function Wh(t){let e=new Map,n=new Map,s=new Map,r=0;for(let o of t)e.set(o.event_type,(e.get(o.event_type)??0)+1),n.set(o.risk_level,(n.get(o.risk_level)??0)+1),o.event_type.startsWith("delegation_")&&(r+=1,s.set(o.event_type,(s.get(o.event_type)??0)+1));return{total:t.length,byType:vi(e),byRisk:vi(n),delegationEvents:r,byDelegationType:vi(s)}}function Xh(t){let e=[],n=!1,s=!1;for(let o of t){let i=o.toLowerCase();if(i==="--json"||i==="-j"){n=!0;continue}if(i==="--replay"){s=!0;continue}e.push(o)}let r=e[0]?.toLowerCase()??"tail";return r!=="tail"&&r!=="stats"&&r!=="export"&&r!=="trace"?null:{json:n,replay:s,mode:r,modeArgs:e}}async function Kh(t,e){let n="Usage: /audit [tail N|stats|trace [trace-id] [--replay]|export [path]] [--json]",s=Xh(t);if(!s)return e.onOutput(`[!] ${n}
|
|
577
|
+
`),{handled:!0};let{json:r,replay:o,mode:i,modeArgs:a}=s;if(!e.auditLogger){if(r&&i==="tail"){let p=a[1],f=p?Number.parseInt(p,10):20;return e.onOutput(JSON.stringify({kind:"audit_tail",limit:Number.isFinite(f)&&f>0?f:20,count:0,events:[]},null,2)+`
|
|
578
|
+
`),{handled:!0}}return r&&i==="stats"?(e.onOutput(JSON.stringify({kind:"audit_stats",path:null,totalEvents:0,byType:{},byRisk:{},delegationEvents:0,byDelegationType:{}},null,2)+`
|
|
579
|
+
`),{handled:!0}):r&&i==="trace"?(e.onOutput(JSON.stringify({kind:"audit_trace",traceId:a[1]??null,traces:[],report:null,replay:null},null,2)+`
|
|
580
|
+
`),{handled:!0}):(e.onOutput(`[!] Audit logger not initialized
|
|
581
|
+
`),{handled:!0})}if(i==="tail"){let p=a[1],f=p?Number.parseInt(p,10):20;if(!Number.isFinite(f)||f<1||f>500)return e.onOutput(`[!] ${n}
|
|
582
|
+
`),{handled:!0};let m=await e.auditLogger.tail(f);if(r)return e.onOutput(JSON.stringify({kind:"audit_tail",limit:f,count:m.length,events:m},null,2)+`
|
|
583
|
+
`),{handled:!0};if(m.length===0)return e.onOutput(`No audit events recorded yet.
|
|
584
|
+
`),{handled:!0};let g=m.map(b=>{let v=b.trace_id.slice(0,8),w=b.tool_name?` | ${b.tool_name}`:"",P=b.decision?` | ${b.decision}`:"",C=b.status?` | ${b.status}`:"",$=b.event_type==="delegation_completed"?b.metadata?.delegation_summary:void 0,E=$?` | ${$.selectedRole??"none"} \xB7 ${$.okBranches??0}/${$.totalBranches??0} ok \xB7 ${Math.max(0,Math.round(($.elapsedMs??0)/1e3))}s`:"";return`${b.timestamp} | ${b.event_type}${w}${P}${C}${E} | ${b.risk_level} | trace ${v}`});if(e.onPanel){let b=new Set(m.map(w=>w.event_type)).size,v=new Set(m.map(w=>w.risk_level)).size;return await e.onPanel({title:"Audit tail",subtitle:e.auditLogger.path,lines:g,footerHint:"\u2190/\u2192 focus \xB7 \u2191/\u2193 navigate or scroll \xB7 Esc close \xB7 /audit stats \xB7 /audit export [path]",cards:[{title:"Events",value:String(m.length)},{title:"Limit",value:String(f)},{title:"Types",value:String(b)},{title:"Risks",value:String(v)}],sections:[{id:"overview",title:"Overview",summary:`${m.length} returned`,lines:[`Audit file: ${e.auditLogger.path}`,`Requested limit: ${f}`,`Returned events: ${m.length}`,`Distinct event types: ${b}`,`Distinct risk levels: ${v}`]},{id:"events",title:"Recent Events",summary:`${m.length} items`,lines:g}]}),{handled:!0}}e.onOutput(`
|
|
585
|
+
**Audit Tail**
|
|
586
|
+
|
|
587
|
+
`);for(let b of g)e.onOutput(` ${b}
|
|
588
|
+
`);return{handled:!0}}if(i==="stats"){let p=await e.auditLogger.read(),f=Wh(p);if(r)return e.onOutput(JSON.stringify({kind:"audit_stats",path:e.auditLogger.path,totalEvents:f.total,byType:f.byType,byRisk:f.byRisk,delegationEvents:f.delegationEvents,byDelegationType:f.byDelegationType},null,2)+`
|
|
589
|
+
`),{handled:!0};if(p.length===0)return e.onOutput(`No audit events recorded yet.
|
|
590
|
+
`),{handled:!0};let m=[`Total events: ${f.total}`,""];m.push("By type");for(let[g,b]of Object.entries(f.byType))m.push(` ${g}: ${b}`);m.push(""),m.push("By risk");for(let[g,b]of Object.entries(f.byRisk))m.push(` ${g}: ${b}`);if(m.push(""),m.push(`Delegation events: ${f.delegationEvents}`),f.delegationEvents>0)for(let[g,b]of Object.entries(f.byDelegationType))m.push(` ${g}: ${b}`);if(e.onPanel){let g=Object.entries(f.byType).map(([w,P])=>`${w}: ${P}`),b=Object.entries(f.byRisk).map(([w,P])=>`${w}: ${P}`),v=f.delegationEvents>0?Object.entries(f.byDelegationType).map(([w,P])=>`${w}: ${P}`):["No delegation events recorded."];return await e.onPanel({title:"Audit stats",subtitle:e.auditLogger.path,lines:m,footerHint:"\u2190/\u2192 focus \xB7 \u2191/\u2193 navigate or scroll \xB7 Esc close \xB7 /audit tail N",cards:[{title:"Total Events",value:String(f.total)},{title:"Type Kinds",value:String(Object.keys(f.byType).length)},{title:"Risk Levels",value:String(Object.keys(f.byRisk).length)},{title:"Delegation",value:String(f.delegationEvents)}],sections:[{id:"overview",title:"Overview",summary:`${f.total} events`,lines:[`Audit file: ${e.auditLogger.path}`,`Total events: ${f.total}`,`Distinct event types: ${Object.keys(f.byType).length}`,`Distinct risk levels: ${Object.keys(f.byRisk).length}`,`Delegation events: ${f.delegationEvents}`]},{id:"types",title:"By Type",summary:`${Object.keys(f.byType).length} kinds`,lines:g.length>0?g:["No events recorded."]},{id:"risk",title:"By Risk",summary:`${Object.keys(f.byRisk).length} levels`,lines:b.length>0?b:["No events recorded."]},{id:"delegation",title:"Delegation",summary:`${f.delegationEvents} events`,lines:v}]}),{handled:!0}}e.onOutput(`
|
|
591
|
+
**Audit Stats**
|
|
592
|
+
|
|
593
|
+
`);for(let g of m)e.onOutput(`${g}
|
|
594
|
+
`);return{handled:!0}}if(i==="trace"){let p=a[1],f=await e.auditLogger.read(),m=(0,R.summarizeAuditTraces)(f),g=(0,R.buildAuditTraceReport)(f,p),b=o?(0,R.buildAuditReplayReport)(f,p):null;if(r)return e.onOutput(JSON.stringify({kind:"audit_trace",traceId:p??g?.traceId??null,traces:m,report:g,replay:b},null,2)+`
|
|
595
|
+
`),{handled:!0};if(f.length===0)return e.onOutput(`No audit events recorded yet.
|
|
596
|
+
`),{handled:!0};if(!p)return e.onPanel?await e.onPanel({title:"Audit traces",subtitle:e.auditLogger.path,lines:(0,R.renderAuditTraceSummaries)(m).split(`
|
|
597
|
+
`),footerHint:"\u2191/\u2193 navigate or scroll \xB7 Esc close \xB7 /audit trace <trace-id>"}):e.onOutput((0,R.renderAuditTraceSummaries)(m)+`
|
|
598
|
+
`),{handled:!0};if(o&&!b)return e.onOutput(`[!] Trace not found: ${p}
|
|
599
|
+
`),{handled:!0};if(!o&&!g)return e.onOutput(`[!] Trace not found: ${p}
|
|
600
|
+
`),{handled:!0};let v=o&&b?(0,R.renderAuditReplayReport)(b):(0,R.renderAuditTraceReport)(g);return e.onPanel?await e.onPanel({title:o?"Audit replay":"Audit trace",subtitle:o?b.traceId:g.traceId,lines:v.split(`
|
|
601
|
+
`),footerHint:o?"\u2191/\u2193 navigate or scroll \xB7 Esc close \xB7 /audit trace <trace-id>":"\u2191/\u2193 navigate or scroll \xB7 Esc close \xB7 /audit trace"}):e.onOutput(v+`
|
|
602
|
+
`),{handled:!0}}let l=a[1],c=l?Fn.resolve(e.cwd,l):Fn.join(e.cwd,".xeno","audit-export.json"),u=await e.auditLogger.read();if(!r&&!l&&e.onActionPicker){let p=await e.onActionPicker({title:"Export Audit Events",description:"Select export method:",options:[{value:"copy",label:"Copy to clipboard",detail:"Copy the audit events JSON to your system clipboard"},{value:"file",label:"Save to file",detail:"Save the audit export JSON in the current directory"}]});if(!p)return{handled:!0};let f=JSON.stringify(u,null,2);if(p==="copy")return(0,sn.copyTextToClipboard)(f),e.onOutput(`[ok] Copied audit export to clipboard
|
|
603
|
+
`),{handled:!0}}return await(0,lt.writeAtomic)(c,JSON.stringify(u,null,2)),r?e.onOutput(JSON.stringify({kind:"audit_export",path:c,count:u.length},null,2)+`
|
|
604
|
+
`):e.onOutput(`[ok] Exported ${u.length} audit events to ${c}
|
|
605
|
+
`),{handled:!0}}async function ki(t,e){if(!e.mcpManager)return e.onOutput(`[!] MCP is not enabled. Use --mcp flag or set mcpEnabled in config.
|
|
606
|
+
`),{handled:!0};let n=new Set,s=new Map,r=[];for(let m=0;m<t.length;m++){let g=t[m];if(!g)continue;if(!g.startsWith("--")){r.push(g);continue}let b=g.toLowerCase();if(b==="--sse"&&t[m+1]&&!t[m+1].startsWith("--")){n.add("--sse"),s.set("--url",t[m+1]),m+=1;continue}if((b==="--url"||b==="--transport")&&t[m+1]&&!t[m+1].startsWith("--")){s.set(b,t[m+1]),m+=1;continue}n.add(b)}let o=r[0]?.toLowerCase(),i=n.has("--user")?"user":n.has("--mcprc")?"mcprc":"project",a=s.get("--transport")?.toLowerCase(),l=n.has("--sse")||a==="sse"?"sse":"stdio",c=e.onActionPicker?async m=>await e.onActionPicker?.({title:"Approve MCP server",description:`${m.name} (${m.scope}) from ${m.sourcePath}`,options:[{value:"approve",label:"Approve",detail:"Save approval for this workspace"},{value:"deny",label:"Deny",detail:"Do not connect this server now"}],selectedIndex:0})==="approve"?"approved":"denied":void 0,u=m=>{let g=[];m.connected.length>0&&g.push(`[ok] Connected: ${m.connected.join(", ")}`),m.skipped.length>0&&g.push(`[i] Skipped: ${m.skipped.join(", ")}`),m.denied.length>0&&g.push(`[i] Denied: ${m.denied.join(", ")}`);for(let b of m.errors)g.push(`[x] ${b.name}: ${b.error}`);return g.length===0&&g.push("[i] No MCP servers were connected."),g},p=m=>{let g=[];m.description&&(g.push(m.description),g.push(""));for(let b of m.messages){let v=typeof b.content=="string"?b.content:b.content.text??b.content.data??`[${b.content.type}]`;g.push(`${b.role}: ${v}`)}return g.length>0?g:["(empty prompt result)"]},f=m=>{let g=[];for(let b of m.contents)g.push(b.uri),b.mimeType&&g.push(` MIME: ${b.mimeType}`),b.text?g.push(...b.text.replace(/\r\n/g,`
|
|
607
|
+
`).split(`
|
|
608
|
+
`).map(v=>` ${v}`)):b.blob&&g.push(` [binary ${b.blob.length} bytes]`),g.push("");return g.length>0?g:["(empty resource result)"]};if(!o||o==="list"){let m=e.mcpManager.listServers(),g=e.mcpManager.listTools(),b=e.mcpManager.loadConfiguredServers(e.cwd),v=new Map(m.map(w=>[w.config.name,w]));if(m.length===0&&b.length===0)return e.onOutput(`No MCP servers configured or connected.
|
|
609
|
+
`),e.onOutput(`Add servers to .xeno/mcp.json, ./.mcprc, or ~/.xeno-agent/mcp.json
|
|
610
|
+
`),{handled:!0};if(e.onPanel){let w=[];for(let P of b){let C=v.get(P.name);w.push(`${P.name} [${C?.status??"configured"}]`),w.push(` Scope: ${P.scope}`),w.push(` Transport: ${P.transport??"stdio"}`),w.push(` Approval: ${P.approvalRequired===!1?"not required":P.approvalState??"pending"}`),P.transport==="sse"&&P.url?w.push(` URL: ${P.url}`):w.push(` Command: ${P.command} ${(P.args??[]).join(" ")}`.trimEnd()),w.push(` Source: ${P.sourcePath}`),w.push(` Tools: ${C?.tools.length??0}`),w.push(` Prompts: ${C?.prompts?.length??0}`),w.push(` Resources: ${C?.resources?.length??0}`),P.disabled&&w.push(" Disabled: yes"),C?.error&&w.push(` Error: ${C.error}`);for(let $ of C?.tools??[])w.push(` - ${$.name}: ${$.description}`);w.push("")}await e.onPanel({title:"MCP Servers",subtitle:`${m.length} servers, ${g.length} tools`,lines:w,cards:[{title:"Servers",value:String(m.length)},{title:"Configured",value:String(b.length)},{title:"Tools",value:String(g.length)},{title:"Ready",value:String(m.filter(P=>P.status==="ready").length)}]})}else{e.onOutput(`
|
|
611
|
+
**MCP Servers**
|
|
612
|
+
|
|
613
|
+
`);for(let w of b){let P=v.get(w.name);e.onOutput(` ${w.name} [${P?.status??"configured"}]
|
|
614
|
+
`),e.onOutput(` Scope: ${w.scope}
|
|
615
|
+
`),e.onOutput(` Transport: ${w.transport??"stdio"}
|
|
616
|
+
`),e.onOutput(` Approval: ${w.approvalRequired===!1?"not required":w.approvalState??"pending"}
|
|
617
|
+
`),w.transport==="sse"&&w.url?e.onOutput(` URL: ${w.url}
|
|
618
|
+
`):e.onOutput(` Command: ${w.command} ${(w.args??[]).join(" ")}
|
|
619
|
+
`),e.onOutput(` Source: ${w.sourcePath}
|
|
620
|
+
`),e.onOutput(` Prompts: ${P?.prompts?.length??0}
|
|
621
|
+
`),e.onOutput(` Resources: ${P?.resources?.length??0}
|
|
622
|
+
`),w.disabled&&e.onOutput(` Disabled: yes
|
|
623
|
+
`),P?.error&&e.onOutput(` Error: ${P.error}
|
|
624
|
+
`);for(let C of P?.tools??[])e.onOutput(` - ${C.name}: ${C.description}
|
|
625
|
+
`);e.onOutput(`
|
|
626
|
+
`)}e.onOutput(`Total: ${b.length} configured, ${m.length} connected, ${g.length} tools
|
|
627
|
+
`)}return{handled:!0}}if(o==="prompts"){let m=r[1],g=e.mcpManager.listPrompts(m);if(g.length===0)return e.onOutput(m?`[i] No MCP prompts found for "${m}".
|
|
628
|
+
`:`[i] No MCP prompts found.
|
|
629
|
+
`),{handled:!0};for(let b of g){let v=b.arguments?.length?` (${b.arguments.map(w=>w.required?`${w.name}*`:w.name).join(", ")})`:"";e.onOutput(` ${b.server}.${b.name}${v}
|
|
630
|
+
`),b.description&&e.onOutput(` ${b.description}
|
|
631
|
+
`)}return{handled:!0}}if(o==="prompt"){let m=r[1],g=r[2];if(!m||!g)return e.onOutput(`[!] Usage: /mcp prompt <server> <name> [arg=value ...]
|
|
632
|
+
`),{handled:!0};let b=Object.fromEntries(r.slice(3).map(v=>{let w=v.indexOf("=");return w>=0?[v.slice(0,w),v.slice(w+1)]:[v,""]}).filter(([v])=>v.length>0));try{let v=await e.mcpManager.getPrompt(m,g,Object.keys(b).length>0?b:void 0);for(let w of p(v))e.onOutput(`${w}
|
|
633
|
+
`)}catch(v){e.onOutput(`[x] ${v instanceof Error?v.message:String(v)}
|
|
634
|
+
`)}return{handled:!0}}if(o==="resources"){let m=r[1],g=e.mcpManager.listResources(m);if(g.length===0)return e.onOutput(m?`[i] No MCP resources found for "${m}".
|
|
635
|
+
`:`[i] No MCP resources found.
|
|
636
|
+
`),{handled:!0};for(let b of g)e.onOutput(` ${b.server}: ${b.uri}
|
|
637
|
+
`),b.name&&e.onOutput(` Name: ${b.name}
|
|
638
|
+
`),b.mimeType&&e.onOutput(` MIME: ${b.mimeType}
|
|
639
|
+
`),b.description&&e.onOutput(` ${b.description}
|
|
640
|
+
`);return{handled:!0}}if(o==="resource"){let m=r[1],g=r[2];if(!m||!g)return e.onOutput(`[!] Usage: /mcp resource <server> <uri>
|
|
641
|
+
`),{handled:!0};try{let b=await e.mcpManager.readResource(m,g);for(let v of f(b))e.onOutput(`${v}
|
|
642
|
+
`)}catch(b){e.onOutput(`[x] ${b instanceof Error?b.message:String(b)}
|
|
643
|
+
`)}return{handled:!0}}if(o==="reload"){for(let g of e.mcpManager.listServers())e.mcpManager.removeServer(g.config.name);let m=await e.mcpManager.connectConfiguredServers({cwd:e.cwd,...c?{promptForApproval:c}:{}});e.refreshMcpTools?.();for(let g of u(m))e.onOutput(`${g}
|
|
644
|
+
`);return{handled:!0}}if(o==="add"){let m=r[1],g=l==="stdio"?r[2]:void 0,b=l==="stdio"?r.slice(3):r.slice(2),v=!n.has("--no-approval"),w=s.get("--url");if(!m||l==="stdio"&&!g||l==="sse"&&!w)return e.onOutput(`[!] Usage: /mcp add <name> <command> [args...] [--project|--mcprc|--user] [--no-approval]
|
|
645
|
+
`),e.onOutput(` /mcp add <name> --sse <url> [--project|--mcprc|--user] [--no-approval]
|
|
646
|
+
`),{handled:!0};try{let{approveMcpServer:P,upsertMcpServerConfig:C}=await import("@xeno-corporation/xeno-agent-sdk"),$=C(i,e.cwd,{name:m,transport:l,...l==="stdio"?{command:g,args:b.length>0?b:void 0}:{url:w},approvalRequired:v}),E=`${i}:${m}`;v&&P(e.cwd,E),e.mcpManager.removeServer(m),await e.mcpManager.addServer({name:m,transport:l,...l==="stdio"?{command:g,args:b.length>0?b:void 0}:{url:w},approvalRequired:v,scope:i,sourcePath:$,approvalKey:E,...v?{approvalState:"approved"}:{}}),e.refreshMcpTools?.();let T=e.mcpManager.listTools().filter(I=>I.server===m);e.onOutput(`[ok] Connected to MCP server "${m}" \u2014 ${T.length} tools available
|
|
647
|
+
`),e.onOutput(` Saved to: ${$}
|
|
648
|
+
`);for(let I of T)e.onOutput(` - ${I.name}: ${I.description}
|
|
649
|
+
`)}catch(P){let C=P instanceof Error?P.message:String(P);e.onOutput(`[x] Failed to connect: ${C}
|
|
650
|
+
`)}return{handled:!0}}if(o==="remove"){let m=r[1];if(!m)return e.onOutput(`[!] Usage: /mcp remove <name> [--project|--mcprc|--user]
|
|
651
|
+
`),{handled:!0};let{clearMcpServerApproval:g,removeMcpServerConfig:b}=await import("@xeno-corporation/xeno-agent-sdk");e.mcpManager.removeServer(m),e.refreshMcpTools?.();let v=`${i}:${m}`;g(e.cwd,v);let w=b(i,e.cwd,m);return e.onOutput(`[ok] Disconnected MCP server "${m}"
|
|
652
|
+
`),e.onOutput(` Removed from: ${w}
|
|
653
|
+
`),{handled:!0}}if(o==="reset-mcprc-choices"){let{resetMcpServerApprovals:m}=await import("@xeno-corporation/xeno-agent-sdk"),g=m(e.cwd,"mcprc");for(let b of e.mcpManager.listServers())b.config.scope==="mcprc"&&e.mcpManager.removeServer(b.config.name);return e.refreshMcpTools?.(),g>0?e.onOutput(`[ok] Reset ${g} remembered .mcprc approval${g===1?"":"s"} for this workspace
|
|
654
|
+
`):e.onOutput(`[i] No remembered .mcprc approvals found for this workspace
|
|
655
|
+
`),{handled:!0}}if(o==="approve"||o==="deny"){let m=r[1];if(!m)return e.onOutput(`[!] Usage: /mcp ${o} <name>
|
|
656
|
+
`),{handled:!0};let b=e.mcpManager.loadConfiguredServers(e.cwd).find(P=>P.name===m);if(!b)return e.onOutput(`[!] MCP server "${m}" is not configured.
|
|
657
|
+
`),{handled:!0};let{approveMcpServer:v,denyMcpServer:w}=await import("@xeno-corporation/xeno-agent-sdk");if(o==="approve"){v(e.cwd,b.approvalKey);try{e.mcpManager.listServers().some(P=>P.config.name===b.name)||(await e.mcpManager.addServer({...b,approvalState:"approved"}),e.refreshMcpTools?.())}catch(P){let C=P instanceof Error?P.message:String(P);return e.onOutput(`[x] ${m}: ${C}
|
|
658
|
+
`),{handled:!0}}e.onOutput(`[ok] Approved MCP server "${m}" for this workspace
|
|
659
|
+
`)}else w(e.cwd,b.approvalKey),e.mcpManager.removeServer(b.name),e.refreshMcpTools?.(),e.onOutput(`[ok] Denied MCP server "${m}" for this workspace
|
|
660
|
+
`);return{handled:!0}}return e.onOutput(`[!] Usage: /mcp [list|reload|prompts [server]|prompt <server> <name>|resources [server]|resource <server> <uri>|add <name> <command>|remove <name>|approve <name>|deny <name>|reset-mcprc-choices]
|
|
661
|
+
`),{handled:!0}}async function Gh(t,e){let n=(t[0]??"list").toLowerCase();if(n==="list"){let s=$r(e.cwd);if(s.length===0)return e.onOutput(`[i] No remembered tool approvals for this workspace.
|
|
662
|
+
`),{handled:!0};let r=s.flatMap(o=>[`${o.toolName}${o.matcher?` -> ${o.matcher}`:""}`,` Key: ${o.approvalKey}`,""]);if(e.onPanel)return await e.onPanel({title:"Approved Tools",subtitle:e.cwd,lines:r,cards:[{title:"Approvals",value:String(s.length)},{title:"Workspace",value:"project"}]}),{handled:!0};for(let o of s)e.onOutput(`- ${o.toolName}${o.matcher?` -> ${o.matcher}`:""}
|
|
663
|
+
`),e.onOutput(` key: ${o.approvalKey}
|
|
664
|
+
`);return{handled:!0}}if(n==="remove"){let s=t.slice(1).join(" ").trim();return s?Lr(e.cwd,s)?(e.onOutput(`[ok] Removed remembered tool approval "${s}"
|
|
665
|
+
`),{handled:!0}):(e.onOutput(`[!] No remembered approval found for "${s}".
|
|
666
|
+
`),{handled:!0}):(e.onOutput(`[!] Usage: /approved-tools remove <approval-key>
|
|
667
|
+
`),{handled:!0})}if(n==="clear"){let s=Nr(e.cwd);return s>0?e.onOutput(`[ok] Cleared ${s} remembered tool approval${s===1?"":"s"}
|
|
668
|
+
`):e.onOutput(`[i] No remembered tool approvals to clear.
|
|
669
|
+
`),{handled:!0}}return e.onOutput(`[!] Usage: /approved-tools [list|remove <approval-key>|clear]
|
|
670
|
+
`),{handled:!0}}async function Yh(t,e){let n=t.includes("--json"),s=await os({cwd:e.cwd,connectMcp:!t.includes("--no-mcp")});return n?(e.onOutput(JSON.stringify(s,null,2)+`
|
|
671
|
+
`),{handled:!0}):e.onPanel?(await e.onPanel({title:"Doctor",subtitle:e.cwd,lines:s.checks.map(r=>`${r.status.toUpperCase()} ${r.label}: ${r.detail}`),cards:[{title:"Checks",value:String(s.checks.length)},{title:"Errors",value:String(s.checks.filter(r=>r.status==="error").length)},{title:"Warnings",value:String(s.checks.filter(r=>r.status==="warn").length)},{title:"MCP",value:String(s.configuredMcpServers.length)}]}),{handled:!0}):(e.onOutput(Dr(s)+`
|
|
672
|
+
`),{handled:!0})}async function Jh(t,e){let n=t.includes("--json"),s=t.find(o=>o.length>0&&!o.startsWith("--"));if(n){let o=await Ds({cwd:e.cwd,...s?{outputPath:s}:{}});return e.onOutput(JSON.stringify(o.bundle,null,2)+`
|
|
673
|
+
`),{handled:!0}}let r=await Ds({cwd:e.cwd,...s?{outputPath:s}:{}});return e.onOutput(`[ok] Bug report bundle written to ${r.path}
|
|
674
|
+
`),{handled:!0}}async function Qh(t,e){let n=t.includes("--json"),s=t.includes("--json-value"),r=t.filter(a=>a!=="--json"&&a!=="--json-value"),o=r[0]?.toLowerCase()??"show";if(o==="set"){let a=r[1]?.toLowerCase(),l=r[2],c=r.slice(3).join(" ");if(a!=="user"&&a!=="project"||!l||c.length===0)return e.onOutput(`[!] Usage: /config set <user|project> <key.path> <value> [--json-value]
|
|
675
|
+
`),{handled:!0};try{let u=await Fr({cwd:e.cwd,scope:a,keyPath:l,rawValue:c,parseAsJson:s});n?e.onOutput(JSON.stringify(u,null,2)+`
|
|
676
|
+
`):(e.onOutput(`[ok] Updated ${a} config at ${u.path}
|
|
677
|
+
`),e.onOutput(` ${l} = ${JSON.stringify(u.value)}
|
|
678
|
+
`))}catch(u){e.onOutput(`[x] ${u instanceof Error?u.message:String(u)}
|
|
679
|
+
`)}return{handled:!0}}if(o==="unset"){let a=r[1]?.toLowerCase(),l=r[2];if(a!=="user"&&a!=="project"||!l)return e.onOutput(`[!] Usage: /config unset <user|project> <key.path>
|
|
680
|
+
`),{handled:!0};try{let c=await Ur({cwd:e.cwd,scope:a,keyPath:l});n?e.onOutput(JSON.stringify(c,null,2)+`
|
|
681
|
+
`):e.onOutput(`[ok] Removed ${l} from ${a} config at ${c.path}
|
|
682
|
+
`)}catch(c){e.onOutput(`[x] ${c instanceof Error?c.message:String(c)}
|
|
683
|
+
`)}return{handled:!0}}if(o!=="show"&&o!=="paths")return e.onOutput(`[!] Usage: /config [show|paths|set|unset] [--json]
|
|
684
|
+
`),e.onOutput(` /config set <user|project> <key.path> <value> [--json-value]
|
|
685
|
+
`),e.onOutput(` /config unset <user|project> <key.path>
|
|
686
|
+
`),{handled:!0};let i={userConfig:(0,B.loadConfig)(),projectState:(0,B.loadProjectState)(e.cwd),paths:{userConfigPath:Fn.join((0,B.getConfigDir)(),"config.json"),projectStatePath:(0,B.getProjectStatePath)(e.cwd)}};return n?(e.onOutput(JSON.stringify(i,null,2)+`
|
|
687
|
+
`),{handled:!0}):o==="paths"?(e.onOutput(`User config: ${i.paths.userConfigPath}
|
|
688
|
+
`),e.onOutput(`Project state: ${i.paths.projectStatePath}
|
|
689
|
+
`),{handled:!0}):e.onPanel?(await e.onPanel({title:"Config",subtitle:e.cwd,lines:["User config",...JSON.stringify(i.userConfig,null,2).split(`
|
|
690
|
+
`).map(a=>` ${a}`),"","Project state",...JSON.stringify(i.projectState,null,2).split(`
|
|
691
|
+
`).map(a=>` ${a}`)]}),{handled:!0}):(e.onOutput(`User config
|
|
692
|
+
`),e.onOutput(JSON.stringify(i.userConfig,null,2)+`
|
|
693
|
+
`),e.onOutput(`Project state
|
|
694
|
+
`),e.onOutput(JSON.stringify(i.projectState,null,2)+`
|
|
695
|
+
`),{handled:!0})}async function Zh(t,e){let n=t[0]?.toLowerCase();return!n||n==="status"?(e.onOutput(`**Agent Debugger**
|
|
696
|
+
|
|
697
|
+
`),e.onOutput(` /debug status - Show debugger status
|
|
698
|
+
`),e.onOutput(` /debug steps - List recent execution steps
|
|
699
|
+
`),e.onOutput(` /debug snapshot - Take a debug snapshot with summary
|
|
700
|
+
`),e.onOutput(` /debug clear - Clear recorded steps
|
|
701
|
+
`),e.onOutput(`
|
|
702
|
+
Debugger records tool calls, LLM requests, and errors
|
|
703
|
+
`),e.onOutput(` for introspection and replay.
|
|
704
|
+
`),{handled:!0}):n==="steps"?(e.onOutput(`**Recent Steps**
|
|
705
|
+
|
|
706
|
+
`),e.onOutput(` Step recording is available via the AgentDebugger API.
|
|
707
|
+
`),e.onOutput(" Enable in code: `debugger.enable()` before running agent.\n"),{handled:!0}):n==="snapshot"?(e.onOutput(`**Debug Snapshot**
|
|
708
|
+
|
|
709
|
+
`),e.onOutput(" Use `AgentDebugger.takeSnapshot()` in code to capture\n"),e.onOutput(` full execution trace with tool call summary.
|
|
710
|
+
`),{handled:!0}):n==="clear"?(e.onOutput(`Debug steps cleared.
|
|
711
|
+
`),{handled:!0}):(e.onOutput(`Unknown debug subcommand: ${n}
|
|
712
|
+
`),{handled:!0})}async function eg(t,e){let n=t[0]?.toLowerCase();return!n||n==="help"?(e.onOutput(`**Agent Evaluation Framework**
|
|
713
|
+
|
|
714
|
+
`),e.onOutput(` /eval report - Show evaluation report
|
|
715
|
+
`),e.onOutput(` /eval tasks - List evaluation tasks
|
|
716
|
+
`),e.onOutput(` /eval summary - Quick performance summary
|
|
717
|
+
`),e.onOutput(`
|
|
718
|
+
The evaluation framework tracks success rates,
|
|
719
|
+
`),e.onOutput(` costs, and performance across agent tasks.
|
|
720
|
+
`),{handled:!0}):n==="report"?(e.onOutput(`**Evaluation Report**
|
|
721
|
+
|
|
722
|
+
`),e.onOutput(` No evaluation results recorded yet.
|
|
723
|
+
`),e.onOutput(` Use the AgentEvaluator API to define tasks and record results.
|
|
724
|
+
`),{handled:!0}):n==="tasks"?(e.onOutput(`**Evaluation Tasks**
|
|
725
|
+
|
|
726
|
+
`),e.onOutput(` No tasks defined. Add tasks via AgentEvaluator.addTask().
|
|
727
|
+
`),{handled:!0}):n==="summary"?(e.onOutput(`**Quick Summary**
|
|
728
|
+
|
|
729
|
+
`),e.onOutput(` Tasks: 0 | Passed: 0 | Failed: 0
|
|
730
|
+
`),e.onOutput(` Success Rate: N/A
|
|
731
|
+
`),{handled:!0}):(e.onOutput(`Unknown eval subcommand: ${n}
|
|
732
|
+
`),{handled:!0})}async function tg(t,e){let n=t[0]?.toLowerCase();if(!n||n==="help")return e.onOutput(`**Plugin Manager**
|
|
733
|
+
|
|
734
|
+
`),e.onOutput(` /plugin list - List installed plugins
|
|
735
|
+
`),e.onOutput(` /plugin install <name> - Install a plugin from npm
|
|
736
|
+
`),e.onOutput(` /plugin uninstall <name> - Remove a plugin
|
|
737
|
+
`),e.onOutput(` /plugin activate <name> - Activate a plugin
|
|
738
|
+
`),e.onOutput(` /plugin deactivate <name> - Deactivate a plugin
|
|
739
|
+
`),e.onOutput(` /plugin search <query> - Search marketplace for plugins
|
|
740
|
+
`),e.onOutput(` /plugin info <name> - Show plugin details
|
|
741
|
+
`),e.onOutput(` /plugin create <name> - Scaffold a new plugin project
|
|
742
|
+
`),e.onOutput(` /plugin test [dir] - Test a plugin in current/given directory
|
|
743
|
+
`),e.onOutput(`
|
|
744
|
+
Plugins add tools, prompts, and capabilities.
|
|
745
|
+
`),e.onOutput(` Install from npm: /plugin install @xeno/plugin-git
|
|
746
|
+
`),{handled:!0};let s=async()=>{let{PluginHost:r}=await import("@xeno-corporation/xeno-agent-sdk"),o=(await import("os")).homedir(),i=(await import("path")).join(o,".xeno","plugins");return new r({pluginDir:i,host:{appName:"xeno-agent-cli",appVersion:"1.0.0",platform:process.platform}})};if(n==="list"){try{let o=(await s()).listInstalled();if(o.length===0)e.onOutput(`**Installed Plugins**
|
|
747
|
+
|
|
748
|
+
`),e.onOutput(` No plugins installed.
|
|
749
|
+
`),e.onOutput(` Use /plugin install <name> to add plugins.
|
|
750
|
+
`);else{e.onOutput(`**Installed Plugins**
|
|
751
|
+
|
|
752
|
+
`);for(let i of o){let a=i.status==="active"?"[active]":i.status==="error"?"[error]":i.status==="disabled"?"[disabled]":"[installed]";e.onOutput(` ${i.manifest.name}@${i.manifest.version} ${a}
|
|
753
|
+
`),i.manifest.description&&e.onOutput(` ${i.manifest.description}
|
|
754
|
+
`),i.error&&e.onOutput(` Error: ${i.error}
|
|
755
|
+
`),i.registeredTools&&i.registeredTools.length>0&&e.onOutput(` Tools: ${i.registeredTools.map(l=>l.definition.name).join(", ")}
|
|
756
|
+
`)}}}catch(r){e.onOutput(`[!] Failed to list plugins: ${r instanceof Error?r.message:String(r)}
|
|
757
|
+
`)}return{handled:!0}}if(n==="install"){let r=t[1];if(!r)return e.onOutput(`[!] Usage: /plugin install <package-name> [version]
|
|
758
|
+
`),{handled:!0};let o=t[2];try{let i=await s();e.onOutput(`Installing plugin: ${r}${o?`@${o}`:""}...
|
|
759
|
+
`);let a=await i.install(r,o);a.status==="error"?e.onOutput(`[!] Installation failed: ${a.error}
|
|
760
|
+
`):(e.onOutput(`Installed ${a.manifest.name}@${a.manifest.version} [${a.status}]
|
|
761
|
+
`),a.registeredTools&&a.registeredTools.length>0&&e.onOutput(` Tools: ${a.registeredTools.map(l=>l.definition.name).join(", ")}
|
|
762
|
+
`))}catch(i){e.onOutput(`[!] Install error: ${i instanceof Error?i.message:String(i)}
|
|
763
|
+
`)}return{handled:!0}}if(n==="uninstall"){let r=t[1];if(!r)return e.onOutput(`[!] Usage: /plugin uninstall <package-name>
|
|
764
|
+
`),{handled:!0};try{await(await s()).uninstall(r)?e.onOutput(`Plugin "${r}" uninstalled.
|
|
765
|
+
`):e.onOutput(`Plugin "${r}" is not installed.
|
|
766
|
+
`)}catch(o){e.onOutput(`[!] Uninstall error: ${o instanceof Error?o.message:String(o)}
|
|
767
|
+
`)}return{handled:!0}}if(n==="activate"){let r=t[1];if(!r)return e.onOutput(`[!] Usage: /plugin activate <package-name>
|
|
768
|
+
`),{handled:!0};try{let o=await s();await o.activate(r);let i=o.getPlugin(r);e.onOutput(`Plugin "${r}" activated [${i?.status}]
|
|
769
|
+
`),i?.registeredTools&&i.registeredTools.length>0&&e.onOutput(` Tools: ${i.registeredTools.map(a=>a.definition.name).join(", ")}
|
|
770
|
+
`)}catch(o){e.onOutput(`[!] Activate error: ${o instanceof Error?o.message:String(o)}
|
|
771
|
+
`)}return{handled:!0}}if(n==="deactivate"){let r=t[1];if(!r)return e.onOutput(`[!] Usage: /plugin deactivate <package-name>
|
|
772
|
+
`),{handled:!0};try{await(await s()).deactivate(r),e.onOutput(`Plugin "${r}" deactivated.
|
|
773
|
+
`)}catch(o){e.onOutput(`[!] Deactivate error: ${o instanceof Error?o.message:String(o)}
|
|
774
|
+
`)}return{handled:!0}}if(n==="search"){let r=t.slice(1).join(" ");if(!r)return e.onOutput(`[!] Usage: /plugin search <query>
|
|
775
|
+
`),{handled:!0};try{let{PluginMarketplace:o}=await import("@xeno-corporation/xeno-agent-sdk"),i=new o;e.onOutput(`Searching for "${r}"...
|
|
776
|
+
|
|
777
|
+
`);let a=await i.search({query:r,limit:10});if(a.length===0)e.onOutput(` No plugins found.
|
|
778
|
+
`);else for(let l of a){let c=l.verified?" [verified]":"";e.onOutput(` ${l.name}@${l.version}${c}
|
|
779
|
+
`),l.description&&e.onOutput(` ${l.description}
|
|
780
|
+
`),l.downloads!==void 0&&e.onOutput(` Downloads: ${l.downloads}
|
|
781
|
+
`)}}catch(o){e.onOutput(`[!] Search error: ${o instanceof Error?o.message:String(o)}
|
|
782
|
+
`)}return{handled:!0}}if(n==="info"){let r=t[1];if(!r)return e.onOutput(`[!] Usage: /plugin info <package-name>
|
|
783
|
+
`),{handled:!0};try{let i=(await s()).getPlugin(r);if(i){if(e.onOutput(`**Plugin Info (installed)**
|
|
784
|
+
|
|
785
|
+
`),e.onOutput(` Name: ${i.manifest.name}
|
|
786
|
+
`),e.onOutput(` Version: ${i.manifest.version}
|
|
787
|
+
`),e.onOutput(` Status: ${i.status}
|
|
788
|
+
`),e.onOutput(` Description: ${i.manifest.description}
|
|
789
|
+
`),i.manifest.author){let a=typeof i.manifest.author=="string"?i.manifest.author:i.manifest.author.name;e.onOutput(` Author: ${a}
|
|
790
|
+
`)}e.onOutput(` Capabilities: ${i.manifest.capabilities.join(", ")}
|
|
791
|
+
`),i.manifest.permissions&&e.onOutput(` Permissions: ${i.manifest.permissions.join(", ")}
|
|
792
|
+
`),e.onOutput(` Installed: ${i.installedAt}
|
|
793
|
+
`),e.onOutput(` Path: ${i.path}
|
|
794
|
+
`)}else{let{PluginMarketplace:a}=await import("@xeno-corporation/xeno-agent-sdk"),c=await new a().getPackageInfo(r);c?(e.onOutput(`**Plugin Info (npm)**
|
|
795
|
+
|
|
796
|
+
`),e.onOutput(` Name: ${c.name}
|
|
797
|
+
`),e.onOutput(` Latest: ${c.version}
|
|
798
|
+
`),e.onOutput(` Description: ${c.description}
|
|
799
|
+
`),c.license&&e.onOutput(` License: ${c.license}
|
|
800
|
+
`),c.verified&&e.onOutput(` Verified: Yes
|
|
801
|
+
`),c.versions&&e.onOutput(` Versions: ${c.versions.length} (${c.versions.slice(-3).join(", ")})
|
|
802
|
+
`)):e.onOutput(`Plugin "${r}" not found.
|
|
803
|
+
`)}}catch(o){e.onOutput(`[!] Info error: ${o instanceof Error?o.message:String(o)}
|
|
804
|
+
`)}return{handled:!0}}if(n==="create"){let r=t[1];if(!r)return e.onOutput(`[!] Usage: /plugin create <name> [--template tools|ui|prompts|full]
|
|
805
|
+
`),{handled:!0};try{let{scaffoldPlugin:o}=await import("@xeno-corporation/xeno-agent-sdk"),i=t.indexOf("--template"),a=i>=0&&t[i+1]?t[i+1]:"tools";e.onOutput(`Scaffolding plugin "${r}" (template: ${a})...
|
|
806
|
+
`);let l=await o({name:r,template:a,outputDir:e.cwd,installDeps:!1,initGit:!0});e.onOutput(`Plugin created at: ${l}
|
|
807
|
+
`),e.onOutput(`
|
|
808
|
+
Next steps:
|
|
809
|
+
`),e.onOutput(` 1. cd into the plugin directory
|
|
810
|
+
`),e.onOutput(` 2. npm install
|
|
811
|
+
`),e.onOutput(` 3. Edit src/index.ts to add your tools
|
|
812
|
+
`),e.onOutput(` 4. npm run build
|
|
813
|
+
`),e.onOutput(` 5. /plugin test to validate
|
|
814
|
+
`)}catch(o){e.onOutput(`[!] Create error: ${o instanceof Error?o.message:String(o)}
|
|
815
|
+
`)}return{handled:!0}}if(n==="test"){let r=t[1]||e.cwd;try{let{testPlugin:o}=await import("@xeno-corporation/xeno-agent-sdk");e.onOutput(`Testing plugin at: ${r}...
|
|
816
|
+
|
|
817
|
+
`);let i=await o(r);for(let a of i.results){let l=a.passed?"[PASS]":"[FAIL]";e.onOutput(` ${l} ${a.name} (${a.duration}ms)
|
|
818
|
+
`),!a.passed&&a.error&&e.onOutput(` ${a.error}
|
|
819
|
+
`)}e.onOutput(`
|
|
820
|
+
${i.passedTests}/${i.totalTests} passed (${i.duration}ms)
|
|
821
|
+
`)}catch(o){e.onOutput(`[!] Test error: ${o instanceof Error?o.message:String(o)}
|
|
822
|
+
`)}return{handled:!0}}return e.onOutput(`Unknown plugin subcommand: ${n}
|
|
823
|
+
`),e.onOutput(`Use /plugin help to see available commands.
|
|
824
|
+
`),{handled:!0}}async function ng(t,e){let n=t[0]?.toLowerCase();if(!n||n==="info"){let{WorkspaceIndex:s}=await import("@xeno-corporation/xeno-agent-sdk"),r=new s(e.cwd);await r.scan({maxFiles:5e3});let o=r.getProjectInfo();if(o){e.onOutput(`**Workspace Info**
|
|
825
|
+
|
|
826
|
+
`),e.onOutput(` Project: ${o.name}
|
|
827
|
+
`),e.onOutput(` Language: ${o.language}
|
|
828
|
+
`),o.framework&&e.onOutput(` Framework: ${o.framework}
|
|
829
|
+
`),o.packageManager&&e.onOutput(` Package Manager: ${o.packageManager}
|
|
830
|
+
`),o.projectType&&e.onOutput(` Type: ${o.projectType}
|
|
831
|
+
`),e.onOutput(` Files: ${o.fileCount}
|
|
832
|
+
`);let i=r.getLanguageDistribution(),a=Object.entries(i).sort((c,u)=>u[1]-c[1]);if(a.length>0){e.onOutput(`
|
|
833
|
+
**Language Distribution:**
|
|
834
|
+
`);for(let[c,u]of a.slice(0,8))e.onOutput(` ${c}: ${u} files
|
|
835
|
+
`)}let l=Object.keys(o.dependencies).length;l>0&&e.onOutput(`
|
|
836
|
+
Dependencies: ${l}
|
|
837
|
+
`),o.git&&(e.onOutput(`
|
|
838
|
+
Git Branch: ${o.git.branch}
|
|
839
|
+
`),o.git.remoteUrl&&e.onOutput(` Remote: ${o.git.remoteUrl}
|
|
840
|
+
`))}else e.onOutput(`Could not detect workspace info.
|
|
841
|
+
`);return{handled:!0}}if(n==="files"){let{WorkspaceIndex:s}=await import("@xeno-corporation/xeno-agent-sdk"),r=new s(e.cwd);await r.scan({maxFiles:2e3});let o=r.getLanguageDistribution();e.onOutput(`**File Distribution**
|
|
842
|
+
|
|
843
|
+
`);let i=Object.entries(o).sort((a,l)=>l[1]-a[1]);for(let[a,l]of i){let c="#".repeat(Math.min(l,40));e.onOutput(` ${a.padEnd(15)} ${String(l).padStart(5)} ${c}
|
|
844
|
+
`)}return e.onOutput(`
|
|
845
|
+
Total: ${r.getFiles().length} files
|
|
846
|
+
`),{handled:!0}}if(n==="deps"){let{WorkspaceIndex:s}=await import("@xeno-corporation/xeno-agent-sdk"),r=new s(e.cwd);await r.scan({maxFiles:2e3,buildDependencyGraph:!0});let o=r.getDependencies();if(e.onOutput(`**Dependency Graph**
|
|
847
|
+
|
|
848
|
+
`),o.length===0)e.onOutput(` No import dependencies found.
|
|
849
|
+
`);else{e.onOutput(` ${o.length} import edges found.
|
|
850
|
+
|
|
851
|
+
`);let i=new Map;for(let l of o)i.set(l.to,(i.get(l.to)??0)+1);let a=Array.from(i.entries()).sort((l,c)=>c[1]-l[1]);e.onOutput(` Most imported files:
|
|
852
|
+
`);for(let[l,c]of a.slice(0,10))e.onOutput(` ${l} (${c} imports)
|
|
853
|
+
`)}return{handled:!0}}return e.onOutput(`**Workspace Commands**
|
|
854
|
+
|
|
855
|
+
`),e.onOutput(` /workspace info - Project info and language detection
|
|
856
|
+
`),e.onOutput(` /workspace files - File distribution by language
|
|
857
|
+
`),e.onOutput(` /workspace deps - Dependency graph analysis
|
|
858
|
+
`),{handled:!0}}async function sg(t,e){let n=t[0]?.toLowerCase();if(!n||n==="list"){let{ModelProviderRegistry:s}=await import("@xeno-corporation/xeno-agent-sdk"),o=new s().listProviders();e.onOutput(`**Model Providers**
|
|
859
|
+
|
|
860
|
+
`);for(let i of o){let a=process.env[i.apiKeyEnvVar]?"set":i.defaultApiKey?"default":"not set";e.onOutput(` ${i.name.padEnd(20)} ${i.id.padEnd(12)} key: ${a}
|
|
861
|
+
`),i.models.length>0&&e.onOutput(` Models: ${i.models.slice(0,4).join(", ")}${i.models.length>4?"...":""}
|
|
862
|
+
`)}return{handled:!0}}if(n==="resolve"){let s=t[1];if(!s)return e.onOutput(`[!] Usage: /provider resolve <model-id>
|
|
863
|
+
`),{handled:!0};let{ModelProviderRegistry:r}=await import("@xeno-corporation/xeno-agent-sdk"),i=new r().resolveProvider(s);return e.onOutput(`**Provider Resolution**
|
|
864
|
+
|
|
865
|
+
`),e.onOutput(` Model: ${i.model}
|
|
866
|
+
`),e.onOutput(` Provider: ${i.provider.name} (${i.provider.id})
|
|
867
|
+
`),e.onOutput(` Base URL: ${i.baseURL}
|
|
868
|
+
`),e.onOutput(` Streaming: ${i.provider.supportsStreaming?"yes":"no"}
|
|
869
|
+
`),e.onOutput(` Tool Use: ${i.provider.supportsToolUse?"yes":"no"}
|
|
870
|
+
`),{handled:!0}}return e.onOutput(`**Provider Commands**
|
|
871
|
+
|
|
872
|
+
`),e.onOutput(` /provider list - List all providers
|
|
873
|
+
`),e.onOutput(` /provider resolve <model> - Show which provider handles a model
|
|
874
|
+
`),{handled:!0}}async function rg(t,e){let{backgroundProcessManager:n}=await import("@xeno-corporation/xeno-agent-sdk"),s=n.list(),r=t[0]?.toLowerCase();if(r==="stop"&&t[1]){let i=n.stop(t[1]);return e.onOutput(i?`Stopped task ${t[1]}
|
|
875
|
+
`:`Failed to stop ${t[1]} (not found or not running)
|
|
876
|
+
`),{handled:!0}}if(r&&s.some(i=>i.id===r)){let i=n.getOutput(r);if(!i)return e.onOutput(`Task ${r} not found
|
|
877
|
+
`),{handled:!0};let a=n.get(r),l=a.endedAt?n.formatDuration(a.endedAt-a.startedAt):n.formatDuration(Date.now()-a.startedAt);if(e.onPanel){let c=i.output?i.output.split(`
|
|
878
|
+
`):["(no output)"];await e.onPanel({title:"Shell details",subtitle:a.command,lines:[],sections:[{id:"info",title:"Process Info",lines:[`Status: ${a.status}${a.exitCode!==null?` (exit ${a.exitCode})`:""}`,`Runtime: ${l}`,`PID: ${a.pid}`,`CWD: ${a.cwd}`,`Output size: ${(a.outputSize/1024).toFixed(1)}KB`]},{id:"output",title:`Output (${c.length} lines)`,summary:`${(a.outputSize/1024).toFixed(1)}KB`,lines:c}],focusPane:"content"})}else{e.onOutput(`Task: ${a.id} | PID: ${a.pid} | Status: ${a.status} | Runtime: ${l}
|
|
879
|
+
`),e.onOutput(`Command: ${a.command}
|
|
880
|
+
`),e.onOutput(`\u2500\u2500\u2500\u2500\u2500
|
|
881
|
+
`);let c=i.output.split(`
|
|
882
|
+
`).slice(-30).join(`
|
|
883
|
+
`);e.onOutput(c+`
|
|
884
|
+
`)}return{handled:!0}}if(s.length===0)return e.onOutput(`No background tasks.
|
|
885
|
+
`),{handled:!0};let o=[];for(let i of s){let a=i.endedAt?n.formatDuration(i.endedAt-i.startedAt):n.formatDuration(Date.now()-i.startedAt),l=i.status==="running"?"\u25CF running":i.status==="completed"?"\u2713 done":i.status==="failed"?"\u2717 failed":"\u25CB killed",c=i.command.length>50?i.command.slice(0,47)+"...":i.command;o.push(` ${i.id} ${l} ${a.padEnd(8)} ${c}`)}return e.onOutput(o.join(`
|
|
886
|
+
`)+`
|
|
887
|
+
`),{handled:!0}}async function og(t,e){let n=e.messages.length,s=e.messages.reduce((g,b)=>{let v=typeof b.content=="string"?b.content:JSON.stringify(b.content);return g+(0,Ot.estimateTokens)(v)},0),r=2e5,o=Math.min(100,Math.round(s/r*100)),i=40,a=Math.round(o/100*i),l=i-a,c="\u2588".repeat(a),u="\u2591".repeat(l),p=o>80?"red":o>60?"yellow":"green",f=p==="red"?` \x1B[31m${c}\x1B[0m${u}`:p==="yellow"?` \x1B[33m${c}\x1B[0m${u}`:` \x1B[32m${c}\x1B[0m${u}`,m=[`Context usage: ${o}%`,f,"",`Messages: ${n}`,`Estimated tokens: ${s.toLocaleString()} / ${r.toLocaleString()}`,"",o>80?"\x1B[33mWarning: Context is getting full. Auto-compaction will trigger soon.\x1B[0m":"Context is healthy. Use /compact to manually compress."];return e.onPanel?await e.onPanel({title:"Context Usage",lines:m}):e.onOutput(m.join(`
|
|
888
|
+
`)+`
|
|
889
|
+
`),{handled:!0}}async function ig(t,e){let n=t.find(r=>!r.startsWith("--")),s=Or(n);return!n&&!t.includes("--no-mark-seen")&&rs(),e.onPanel?(await e.onPanel({title:"Release Notes",subtitle:n??"current",lines:s.split(`
|
|
890
|
+
`)}),{handled:!0}):(e.onOutput(`${s}
|
|
891
|
+
`),{handled:!0})}async function ag(t){return t.onHelp?(await t.onHelp(),{handled:!0}):(t.onOutput(`
|
|
892
|
+
**Available Commands**
|
|
893
|
+
|
|
894
|
+
`),t.onOutput(` /memory - Show current memories
|
|
895
|
+
`),t.onOutput(` ${Nh} - Show prompt memory context
|
|
896
|
+
`),t.onOutput(` /remember <text> - Add text to project memory
|
|
897
|
+
`),t.onOutput(` /checkpoint - Create manual checkpoint
|
|
898
|
+
`),t.onOutput(` /checkpoint list - List all checkpoints
|
|
899
|
+
`),t.onOutput(` /checkpoint restore <id> - Restore from checkpoint
|
|
900
|
+
`),t.onOutput(` /audit [tail N|stats|trace [trace-id] [--replay]|export [path]] [--json] - View/export audit events
|
|
901
|
+
`),t.onOutput(` /mcp [list|reload|prompts|resources|add|remove|approve|deny|reset-mcprc-choices] - Manage MCP servers, prompts, and resources
|
|
902
|
+
`),t.onOutput(` /approved-tools [list|remove|clear] - Inspect or revoke remembered tool approvals
|
|
903
|
+
`),t.onOutput(` /doctor [--json] [--no-mcp] - Run local health checks
|
|
904
|
+
`),t.onOutput(` /bug-report [path] [--json] - Export a redacted diagnostics bundle
|
|
905
|
+
`),t.onOutput(` /config [show|paths|set|unset] [--json] - Inspect or edit local user/project config
|
|
906
|
+
`),t.onOutput(` /ctx-viz - Inspect prompt, tool, and message context usage
|
|
907
|
+
`),t.onOutput(` /onboarding [done|reset] - Show or update onboarding guidance for this workspace
|
|
908
|
+
`),t.onOutput(` /release-notes [version] - Show current or requested release notes
|
|
909
|
+
`),t.onOutput(` /terminal-setup [status] [--vscode|--iterm] - Install terminal Shift+Enter integration
|
|
910
|
+
`),t.onOutput(` /listen - Start system voice dictation / voice typing
|
|
911
|
+
`),t.onOutput(` /pr-comments [selector] - Fetch and render GitHub PR comments via gh
|
|
912
|
+
`),t.onOutput(` /babysit <command> - Watch a process and analyze its output
|
|
913
|
+
`),t.onOutput(` /compact - Compress conversation context
|
|
914
|
+
`),t.onOutput(` /compact status - Show current context usage
|
|
915
|
+
`),t.onOutput(` /test - Run project tests and analyze output
|
|
916
|
+
`),t.onOutput(` /test generate <file> - Generate tests for a file using AI
|
|
917
|
+
`),t.onOutput(` /test coverage - Run tests with coverage report
|
|
918
|
+
`),t.onOutput(` /deploy [target] - Deploy project (docker, vercel, gh-pages, npm, custom)
|
|
919
|
+
`),t.onOutput(` /profile [list|create|switch|delete|show] - Manage config profiles
|
|
920
|
+
`),t.onOutput(` /debug [status|steps|snapshot|clear] - Agent execution debugger
|
|
921
|
+
`),t.onOutput(` /eval [report|tasks|summary] - Agent evaluation framework
|
|
922
|
+
`),t.onOutput(` /plugin [list|install|uninstall] - Plugin management
|
|
923
|
+
`),t.onOutput(` /workspace [info|files|deps] - Workspace awareness & analysis
|
|
924
|
+
`),t.onOutput(` /provider [list|resolve] - Multi-model provider management
|
|
925
|
+
`),t.onOutput(` /help - Show this help
|
|
926
|
+
|
|
927
|
+
`),t.onOutput(`**Available Tools**
|
|
928
|
+
|
|
929
|
+
`),t.onOutput(` Read, Write, Edit, Glob, Grep, Bash
|
|
930
|
+
`),t.onOutput(` WebSearch, WebFetch, ReadImage
|
|
931
|
+
`),t.onOutput(` + any tools from connected MCP servers
|
|
932
|
+
|
|
933
|
+
`),{handled:!0})}function xi(t){return t.trim().startsWith("/")}At();$n();var Ci=2e5;function Vs(t,e){let n=t;try{n.apiKey=e}catch{}}function Tc(t,e){let n=Nl();n&&(e(`${n}
|
|
934
|
+
|
|
935
|
+
`),rs());let s=Os(t);s.completed||e(`${$s(s)}
|
|
936
|
+
|
|
937
|
+
`)}function ls(t,e){let n=`# XENO AGENT Conversation
|
|
938
|
+
Date: ${new Date().toISOString()}
|
|
939
|
+
Model: ${e}
|
|
940
|
+
|
|
941
|
+
`;for(let s of t){let r=s.role==="user"?"User":"Assistant",o=typeof s.content=="string"?s.content:JSON.stringify(s.content);n+=`## ${r}
|
|
942
|
+
${o}
|
|
943
|
+
|
|
944
|
+
`}return n}function js(t){if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}function _c(t){let e=t.toLowerCase();return e.includes("token_invalidated")||e.includes("invalidated")||e.includes("unauthorized")||e.includes("status=401")||e.includes(" 401")||e.includes("invalid api key")||e.includes("authentication token")?`${t}
|
|
945
|
+
|
|
946
|
+
Auth recovery: run /logout, then use \`xeno login\` in a terminal or \`/login api-key <key>\` in this chat.`:t}function Gt(t){return t.replace(/\r\n/g,`
|
|
947
|
+
`).split(`
|
|
948
|
+
`)}function us(t){return Gt(t).length}function fg(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function hg(t){return Buffer.from(t,"utf16le").toString("base64")}function Rc(t){let e=Vn(t);if(!lg(e))return Promise.reject(new Error(`Path not found: ${e}`));let n=kc(e).isDirectory()?e:mg(e),s=hg(["$ErrorActionPreference = 'Stop';","$ProgressPreference = 'SilentlyContinue';","$p = $env:XENO_OPEN_PATH;",'if (-not (Test-Path -LiteralPath $p)) { throw "Path not found: $p" }',`$signature = '[DllImport("user32.dll")] public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow); [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr hWnd);';`,"Add-Type -MemberDefinition $signature -Name XenoOpenWindow -Namespace Xeno -ErrorAction SilentlyContinue | Out-Null;","$shell = New-Object -ComObject Shell.Application;","$shell.Explore($p);","Start-Sleep -Milliseconds 450;","$targetUri = [System.Uri]::new($p).AbsoluteUri;","$windows = @($shell.Windows() | Where-Object { $_.LocationURL -eq $targetUri });","if ($windows.Count -eq 0) { Start-Process -FilePath explorer.exe -ArgumentList @('/n,', $p); Start-Sleep -Milliseconds 450; $windows = @($shell.Windows() | Where-Object { $_.LocationURL -eq $targetUri }) }","if ($windows.Count -gt 0) { $hwnd = [IntPtr]$windows[-1].HWND; [Xeno.XenoOpenWindow]::ShowWindowAsync($hwnd, 9) | Out-Null; [Xeno.XenoOpenWindow]::SetForegroundWindow($hwnd) | Out-Null }"].join(" ")),r=process.platform==="win32"?[{command:"powershell.exe",args:["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",s],env:{...process.env,XENO_OPEN_PATH:n},label:"Explorer",waitForExit:!0,captureStderr:!0},{command:"cmd.exe",args:["/d","/s","/c","start","","%XENO_OPEN_PATH%"],env:{...process.env,XENO_OPEN_PATH:n},label:"Explorer"},{command:"powershell.exe",args:["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command","Invoke-Item -LiteralPath $env:XENO_OPEN_PATH"],env:{...process.env,XENO_OPEN_PATH:n},label:"Explorer"},{command:"explorer.exe",args:[`/n,"${n}"`],label:"Explorer",windowsVerbatimArguments:!0},{command:"explorer.exe",args:[`/n,${n}`],label:"Explorer"},{command:"explorer.exe",args:[n],label:"Explorer"},{command:"rundll32.exe",args:["url.dll,FileProtocolHandler",n],label:"Explorer"}]:process.platform==="darwin"?[{command:"open",args:[n],label:"Finder"}]:[{command:"xdg-open",args:[n],label:"file manager"}];return new Promise((o,i)=>{let a=(l,c)=>{let u=r[l];if(!u){i(c instanceof Error?c:new Error("No folder opener succeeded"));return}let p;try{p=pg(u.command,u.args,{detached:!u.waitForExit,stdio:u.captureStderr?["ignore","ignore","pipe"]:"ignore",windowsHide:!0,env:u.env,windowsVerbatimArguments:u.windowsVerbatimArguments})}catch(g){a(l+1,g);return}let f=!1,m="";u.captureStderr&&p.stderr&&p.stderr.on("data",g=>{m+=String(g)}),p.once("error",g=>{f||(f=!0,a(l+1,g))}),p.once(u.waitForExit?"close":"exit",g=>{if(!f){if(g!==0&&g!==null){f=!0;let b=m.trim()?`: ${m.trim()}`:"";a(l+1,new Error(`${u.command} exited with ${g}${b}`));return}u.waitForExit&&(f=!0,o(u.label))}}),u.waitForExit||p.unref(),setTimeout(()=>{f||(f=!0,o(u.label))},u.waitForExit?2500:250).unref?.()};a(0)})}function gg(t){let e=t?.file_path??t?.path;return typeof e=="string"&&e.trim().length>0?e:null}function bg(t,e,n,s){if(!["Write","Read","Edit"].includes(e))return;let r=gg(n);if(!r)return;let o=Vn(r),i=typeof n?.content=="string"?n.content:void 0,a=xc(process.cwd(),o)||qs(o),l=`${e} artifact`;return async()=>{let c=i??"";try{c=cg(o,"utf8")}catch(p){if(i===void 0)throw p}let u=p=>{let f=Buffer.byteLength(p,"utf8");return[{title:"File",value:a},{title:"Lines",value:String(us(p))},{title:"Size",value:fg(f)},{title:"Source",value:l}]};await t.infoPanel({title:a,subtitle:o,lines:[],layout:"viewport",singlePane:!0,cards:[],sections:[{id:"file",title:"File Content",summary:`${us(c)} lines`,lines:Gt(c),editable:{value:c,initialCursor:"start",onSave:async p=>(ug(o,p,"utf8"),{cards:u(p),contentLines:Gt(p),summary:`${us(p)} lines`})}}],focusPane:"content",assistant:s?{placeholder:`Ask XENO to edit ${a} only...`,onSubmit:async({prompt:p,currentContent:f,appendMessage:m})=>{let g=await s({prompt:p,filePath:a,absolutePath:o,currentContent:f??c,toolName:e,onProgress:m}),b=g.content!==void 0&&g.content!==(f??c)?g.content:void 0;return{replacementContent:b,message:g.message,notice:b?"Agent draft ready.":"File chat response added."}}}:void 0,footerHint:"PgUp/PgDn scroll | Enter edit | Tab file agent | Esc close"})}}function Ai(t,e=48){let n=t.replace(/\r\n/g,`
|
|
949
|
+
`).split(`
|
|
950
|
+
`).map(s=>s.trim()).find(s=>s.length>0)??"";return n.length<=e?n||"Completed":`${n.slice(0,Math.max(1,e-3))}...`}function yg(t,e){let n=["path","filePath","command","query","pattern","name"];for(let r of n){let o=e[r];if(typeof o=="string"&&o.trim().length>0){let i=o.trim().replace(/\s+/g," "),a=i.length>28?`${i.slice(0,25)}...`:i;return`${t} ${a}`}}let s=Object.keys(e).slice(0,2);return s.length>0?`${t} ${s.join(", ")}`:t}function Ec(t,e,n){let s={},r=0,o=0;for(let i of t.results)i.status==="ok"?r+=1:o+=1,s[i.role]={status:i.status,tokensUsed:i.tokensUsed,outputPreview:i.status==="ok"?Ai(i.output):void 0,error:i.status==="error"?i.error:void 0};return{selectedRole:t.reduced.selectedFrom?.role,selectedTaskId:t.reduced.selectedFrom?.id,elapsedMs:n,totalTokens:e,okBranches:r,errorBranches:o,totalBranches:t.results.length,roleSummaries:s}}function wg(t){return`Delegation complete \uFFFD ${t.selectedRole?`${t.selectedRole} selected`:"No selection"} \uFFFD ${t.okBranches}/${t.totalBranches} ok \uFFFD ${t.totalTokens} tok \uFFFD ${Math.max(0,Math.round(t.elapsedMs/1e3))}s`}function bc(t){if(typeof t.content=="string")return t.content;if(!Array.isArray(t.content))return null;let e=[];for(let n of t.content){if(typeof n=="string"){e.push(n);continue}if("type"in n&&n.type==="text"){e.push(n.text??"");continue}return null}return e.join("")}function vg(t){if(typeof t.content=="string")return Gt(t.content);if(!Array.isArray(t.content)||t.content.length===0)return["(empty)"];let e=[];for(let n=0;n<t.content.length;n++){let s=t.content[n];if(typeof s=="string")e.push(...Gt(s));else if(s&&typeof s=="object"&&"type"in s)if(s.type==="text")e.push(...Gt(s.text??""));else if(s.type==="tool_use")e.push(`[tool_use] ${s.name} (${s.id})`),e.push(`input: ${js(s.input)}`);else if(s.type==="tool_result"){let r=s.is_error?"error":"ok";e.push(`[tool_result:${r}] ${s.tool_use_id}`),e.push(...Gt(js(s.content)))}else e.push(js(s));else e.push(js(s));n<t.content.length-1&&e.push("")}return e.length>0?e:["(empty)"]}function Pi(t){if(t.length===0)return" (no messages)";let e=[];for(let n=0;n<t.length;n++){let s=t[n],r=s.role==="assistant"?"\u25A0":"\u203A",o=s.role==="assistant"?"assistant":"user";e.push(`${r} ${o} #${n+1}`);let i=vg(s);for(let a of i)e.push(` ${a}`);e.push("")}return e.join(`
|
|
951
|
+
`).trimEnd()}function Cc(t,e,n,s,r,o=!1,i){let a=pr(e,n,s,r),[l]=a.split(`
|
|
952
|
+
`),c=n?bg(t,e,r,i):void 0;t.writeCollapsibleInfo(l,a,{initiallyExpanded:o,autoCollapseMs:o?2200:void 0,blockKind:"tool-result",secondaryAction:c,secondaryActionLabel:c?"Press Enter again to open full file":void 0})}function Ti(t,e,n){let s=new Map;for(let r of e){if(typeof r.content=="string"){if(r.role==="user"){let o=r.content.replace(/\n/g,`
|
|
953
|
+
`);t.writeOutput(`
|
|
954
|
+
${_.accent("\u276F")} ${o}
|
|
955
|
+
`,{forceNewBlock:!0,selectable:!0,blockKind:"user"})}else{let o=new In(i=>t.writeOutput(i,{selectable:!0,blockKind:"assistant"})," ");t.writeOutput(`
|
|
956
|
+
${_.accent("\u25A0")} `,{forceNewBlock:!0,selectable:!0,blockKind:"assistant"}),o.markLineStarted(),o.write(r.content),o.flush()}continue}if(r.role==="assistant"){let o=!1,i=new In(a=>t.writeOutput(a,{selectable:!0,blockKind:"assistant"})," ");for(let a of r.content){if(a.type==="text"){o||(t.writeOutput(`
|
|
957
|
+
${_.accent("\u25A0")} `,{forceNewBlock:!0,selectable:!0,blockKind:"assistant"}),i.markLineStarted(),o=!0),i.write(a.text);continue}a.type==="tool_use"&&(s.set(a.id,{name:a.name,input:a.input}),o&&(i.flush(),o=!1),t.writeOutput(`
|
|
958
|
+
${_s(a.name,qr(a.name,a.input))}
|
|
959
|
+
`,{forceNewBlock:!0,selectable:!0,blockKind:"tool-call"}))}o&&i.flush();continue}for(let o of r.content){if(o.type!=="tool_result")continue;let i=typeof o.content=="string"?o.content:js(o.content),a=s.get(o.tool_use_id);Cc(t,a?.name??"Result",!o.is_error,i,a?.input,!1,n)}}}function Ac(t){let e=new Set;for(let n of t)if(Array.isArray(n.content)){if(n.role==="assistant"){for(let s of n.content)s.type==="tool_use"&&s.id&&e.add(s.id);continue}for(let s of n.content)s.type==="tool_result"&&s.tool_use_id&&e.delete(s.tool_use_id)}return e.size>0}async function Un(t,e){let n=Ie.SessionRegistry.getSessionDir(t),s=new Ie.TranscriptWriter(n),r=new Ie.CheckpointManager(n);if(e)return(await r.restore(e)).messages;let o=[];try{o=await s.getMessages()}catch{}if(o.length>0&&!Ac(o))return o;let i=await r.list();if(i.length>0)try{return(await r.restore(i[0].id)).messages}catch{}return o}async function Ii(t){if(!Ao(t))return{ok:!0};let e=await Io(t);return e.ok?{ok:!0,warning:e.warning}:{ok:!1,error:e.error||`Ollama preflight failed for ${t}`}}function Sg(t){let e=t.choices?.[0]?.message?.content;if(typeof e=="string")return e;if(Array.isArray(e)){let n=e.map(s=>typeof s?.text=="string"?s.text:"").join("");if(n.trim().length>0)return n}throw new Error("Model returned empty response")}async function Ic(t,e,n){let s=n||process.env.XENO_API_KEY||we.DEFAULT_API_KEY,r=await fetch(`${we.XENO_API_BASE}/v1/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({model:"gemini-2.5-flash-lite",temperature:0,stream:!1,messages:[{role:"system",content:e},{role:"user",content:t}]})});if(!r.ok){let i=await r.text().catch(()=>""),a=i?`: ${i.slice(0,200)}`:"";throw new Error(`Text transform failed (${r.status})${a}`)}let o=await r.json();return Sg(o)}async function kg(t,e){return Ic(t,"You fix spelling and typo mistakes only. Return only corrected text with no extra words, quotes, or formatting.",e)}async function xg(t,e,n,s){let r="Rewrite the user's text while preserving meaning, language, and intent. Return only rewritten text.";if(e==="SWE")r="Rewrite the user's text in a clear software-engineering style: concrete, precise, implementation-focused, and concise. Preserve intent. Return only rewritten text.";else if(e==="RESEARCHER")r="Rewrite the user's text in a researcher style: structured, analytical, and evidence-oriented while preserving intent. Return only rewritten text.";else{let o=n?.trim();if(!o)throw new Error("Missing custom rewrite style");r=`Rewrite the user's text to match this style instruction: "${o}". Preserve meaning and intent. Return only rewritten text.`}return Ic(t,r,s)}function yc(t){let e=Vn(t).replace(/\\/g,"/");return process.platform==="win32"?e.toLowerCase():e}function Pg(t,e){let n=e.file_path??e.path??e.notebook_path??e.filePath;return typeof n!="string"||n.trim().length===0?null:Vn(t,n)}function _i(t,e,n){let s=Pg(t,n);return s?yc(s)===yc(e):!1}function wc(t){let e=t.file_path??t.path??t.notebook_path??t.filePath;return typeof e=="string"&&e.trim().length>0?e:"(missing path)"}function jr(t,e){let n=t[e];return typeof n=="string"?n:null}function Ft(t){return{success:!1,output:"",error:t}}function Tg(t,e,n){let s=Gt(e),r=typeof n.offset=="number"&&Number.isFinite(n.offset)?n.offset:1,o=typeof n.limit=="number"&&Number.isFinite(n.limit)?n.limit:2e3,i=Math.max(0,Math.floor(r)-1),a=Math.max(1,Math.floor(o)),l=Math.min(s.length,i+a),c=String(Math.max(1,l)).length,u=s.slice(i,l).map((f,m)=>`${String(i+m+1).padStart(c," ")} | ${f}`),p=l<s.length?`
|
|
960
|
+
... ${s.length-l} more line(s). Retry with offset=${l+1}.`:"";return[`File: ${t}`,`Lines: ${s.length}`,"Source: staged in-memory draft (not saved to disk until Ctrl+S)","",...u].join(`
|
|
961
|
+
`)+p}function Ri(t,e,n){return[`${e} in ${t}.`,`Draft now has ${n} line(s).`,"This is staged in the file editor only. Press Ctrl+S to save or Ctrl+R to revert."].join(`
|
|
962
|
+
`)}function _g(t){let e=t.trim();return!e||/[\r\n]/.test(e)||/(^|[^=])>{1,2}|<\(|\|\s*(tee|out-file|set-content|add-content)\b/i.test(e)||/[;&]|&&|\|\|/.test(e)?!1:[/^(get-command|where(?:\.exe)?|where)\b/i,/^(get-childitem|gci|dir|ls)\b/i,/^(get-content|gc|type|cat)\b/i,/^(select-string|findstr|rg|grep)\b/i,/^(pwd|get-location|gl)\b/i,/^git\s+(status|diff|log|show)\b/i,/^(node|npm|pnpm|yarn|python|py|pip|uv|cargo|go|rustc|java)\s+(--version|-v|version)\b/i].some(s=>s.test(e))}function Rg(t,e){let n=(0,R.canonicalizeToolName)(t.definition.name),s=qs(e);return n==="Write"||n==="Edit"?`${t.definition.description} In the file editor, this tool is scoped to ${s}; edits are staged in memory and not saved until the user presses Ctrl+S.`:n==="Bash"?`${t.definition.description} In the file editor, Bash is restricted to simple read-only inspection commands so it cannot mutate files outside ${s}.`:t.definition.description}function Eg(t){let e=(0,R.createDefaultToolRegistry)({cwd:t.cwd,memoryManager:t.memoryManager}),n=new R.ToolRegistry,s=Vn(t.openedFilePath),r=t.initialContent.replace(/\r\n/g,`
|
|
963
|
+
`),o=!1,i=(l,c)=>{if(!_i(t.cwd,s,l))return Ft(`${c} is file-scoped here. It may only edit ${t.openedFileDisplayPath}; requested ${wc(l)}.`);let u=jr(l,"content");return u===null?Ft("Missing required parameter: content"):(r=u.replace(/\r\n/g,`
|
|
964
|
+
`),o=!0,{success:!0,output:Ri(t.openedFileDisplayPath,"Staged full-file replacement",us(r))})},a=(l,c)=>{if(!_i(t.cwd,s,l))return Ft(`${c} is file-scoped here. It may only edit ${t.openedFileDisplayPath}; requested ${wc(l)}.`);let u=jr(l,"old_string"),p=jr(l,"new_string"),f=l.replace_all===!0;if(u===null)return Ft("Missing required parameter: old_string");if(p===null)return Ft("Missing required parameter: new_string");if(u===p)return Ft("old_string and new_string must be different");if(u.length===0)return r=p.replace(/\r\n/g,`
|
|
965
|
+
`),o=!0,{success:!0,output:Ri(t.openedFileDisplayPath,"Staged full-file replacement from empty Edit old_string",us(r))};if(!r.includes(u))return Ft("old_string not found in the current staged draft. Read the opened file first and include exact whitespace.");let m=1;if(f)m=r.split(u).length-1,r=r.replaceAll(u,p);else{let g=r.indexOf(u);if(r.indexOf(u,g+u.length)!==-1)return Ft("old_string is not unique in the current staged draft. Use replace_all or provide more context.");r=r.replace(u,p)}return o=!0,{success:!0,output:Ri(t.openedFileDisplayPath,`Staged ${m} exact replacement(s)`,us(r))}};for(let l of e.listNames()){let c=e.get(l);if(!c)continue;let u=(0,R.canonicalizeToolName)(c.definition.name),p={definition:{...c.definition,description:Rg(c,s)},execute:async f=>{if(u==="Read"&&_i(t.cwd,s,f))return{success:!0,output:Tg(t.openedFileDisplayPath,r,f)};if(u==="Write")return i(f,c.definition.name);if(u==="Edit")return a(f,c.definition.name);if(u==="NotebookEdit")return Ft("NotebookEdit is not available in the file-scoped editor yet. Use the main chat for notebook editing.");if(u==="MemoryWrite"||u==="GitCommit"||u==="GitBranch"||u==="dispatch_agent"||u==="TaskStop")return Ft(`${c.definition.name} is disabled in the file-scoped editor because it can mutate state outside ${t.openedFileDisplayPath}.`);if(u==="Bash"){let m=jr(f,"command")??"";if(!_g(m))return Ft("Bash is read-only in the file-scoped editor. Use Read/Grep/Glob/WebSearch/WebFetch, or ask the main chat for workspace-wide mutations.")}return c.execute(f)}};n.register(p)}return{registry:n,getDraftContent:()=>r,hasDraftChanges:()=>o}}function Cg(t){return["You are XENO's file-scoped coding agent inside an opened file editor.",`Opened file: ${t.filePath}`,`Allowed mutation path: ${t.absolutePath}`,"Use the same engineering standard as the main XENO agent: inspect before editing, use tools when useful, and verify changes.","You may read/search the workspace, use web research, inspect git status/diffs, and run simple read-only shell inspection commands.","You may mutate exactly one target: the opened file. The tool layer will block every other mutation.","When editing, use Write or Edit against the opened file. These calls stage an in-memory draft only; they do not save to disk.","Do not claim the file was saved. Tell the user to press Ctrl+S to save or Ctrl+R to revert if a draft was staged.","If the user asks a question, answer directly. If the user asks for an edit, stage the edit and summarize what changed."].join(`
|
|
966
|
+
`)}function Mc(t){return[`User request: ${t.prompt}`,"",`Opened file: ${t.filePath}`,`Absolute path: ${t.absolutePath}`,"","Current staged file content:","```",t.currentContent,"```"].join(`
|
|
967
|
+
`)}function Oc(t){let e=t.trim().toLowerCase().replace(/[.!?]+$/g,"").replace(/\s+/g," ");return/^(hi|hello|hey|yo|sup|gm|good morning|good afternoon|good evening|howdy)( xeno)?$/.test(e)||/^(thanks|thank you|ty|ok|okay|cool|nice|awesome)$/.test(e)}function Ag(t){let e=t.trim().toLowerCase();return!e||Oc(e)||[/\bwhat\s+is\s+(this|the)\s+file\s+(about|for)\b/,/\bwhat\s+does\s+(this|the)\s+file\s+do\b/,/\bexplain\s+(this|the)\s+file\b/,/\bsummarize\s+(this|the)\s+file\b/,/\btell\s+me\s+(what|about)\b.*\b(this|the)\s+file\b/].some(o=>o.test(e))?!1:[/\b(add|append|insert|remove|delete|change|update|replace|rewrite|reword|refactor|format|fix|improve|implement|create|convert|rename)\b/,/\bmake\s+(it|this|the\s+file)\b/,/\bapply\b.*\b(change|edit|patch|fix|update)\b/,/\bstage\b.*\b(edit|change|patch|update)\b/].some(o=>o.test(e))?!0:[/\b(search|browse|look\s+online|web|internet|fetch|url|website|docs)\b/,/\b(grep|glob|find\s+in\s+(repo|project|workspace)|search\s+(repo|project|workspace))\b/,/\b(read|open|inspect|list|ls|dir)\b.*\b(other|repo|project|workspace|folder|directory|file)s?\b/,/\b(run|execute|test|build|lint|typecheck|verify\s+with\s+(command|shell|bash|terminal))\b/,/\b(git\s+status|git\s+diff|commit|branch)\b/].some(o=>o.test(e))}function Ig(t){return Oc(t.prompt)?{message:`Hey. What would you like to do with ${qs(t.filePath)}?`}:null}function Mg(t){return["You are XENO's file-scoped assistant inside an opened file editor.",`Opened file: ${t.filePath}`,"Answer directly from the provided current file content and the user's request.","Do not use tools in this answer-only mode.","Do not claim you edited or saved the file.","If no edit is needed, keep the answer concise and practical."].join(`
|
|
968
|
+
`)}async function Og(t,e){let n=Ig(t);return n||{message:(await(await(0,R.createXenoAgent)({cwd:e.cwd,apiKey:e.apiKey,baseURL:e.baseURL,model:e.model,maxTokens:Math.max(512,Math.min(e.maxTokens??2048,2048)),maxIterations:1,requesterLabel:"File Agent",executionMode:"chatOnly",systemPrompt:Mg(t),identity:!1,memory:!1})).agent.run(Mc(t))).trim()||`I can help with ${qs(t.filePath)}. What would you like to change or understand?`}}function $g(t,e){let n=qr(t,e);return n?`${t}(${n})`:`${t}()`}function Lg(t,e){if(!e.success)return`${t} failed: ${e.error||"unknown error"}`;let n=e.output.replace(/\r\n/g,`
|
|
969
|
+
`).split(`
|
|
970
|
+
`).map(s=>s.trim()).find(Boolean);return n?`${t}: ${n}`:`${t}: completed`}async function Ng(t,e){if(!Ag(t.prompt))return Og(t,e);let n=Eg({cwd:e.cwd,openedFilePath:t.absolutePath,openedFileDisplayPath:t.filePath,initialContent:t.currentContent,memoryManager:e.memoryManager}),r=(await(await(0,R.createXenoAgent)({cwd:e.cwd,apiKey:e.apiKey,baseURL:e.baseURL,model:e.model,maxTokens:Math.max(1024,Math.min(e.maxTokens??8192,8192)),maxIterations:Math.max(4,Math.min(e.maxIterations??12,16)),requesterLabel:"File Agent",executionMode:"agent",systemPrompt:Cg(t),toolRegistry:n.registry,permissionConfig:{mode:"bypassPermissions"},identity:!1,memory:!1,onToolStart:(i,a)=>{t.onProgress?.({role:"tool",content:$g(i,a)})},onToolEnd:(i,a)=>{t.onProgress?.({role:"tool",content:Lg(i,a)})}})).agent.run(Mc(t))).trim(),o=n.hasDraftChanges()&&n.getDraftContent()!==t.currentContent.replace(/\r\n/g,`
|
|
971
|
+
`);return{...o?{content:n.getDraftContent()}:{},message:r||(o?`Drafted updates for ${t.filePath}. Press Ctrl+S to save or Ctrl+R to revert.`:"No file changes were staged.")}}function $c(t,e){return e==="bypassPermissions"?"fullAccess":t==="chatOnly"?"chat":"agent"}function Lc(t){let e=t.trim().toLowerCase();return e==="chat"||e==="chatonly"||e==="chat-only"?"chat":e==="agent"?"agent":e==="full"||e==="fullaccess"||e==="full-access"?"fullAccess":null}function cs(t){return t==="chat"?"Chat":t==="agent"?"Agent":"Full Access"}function Ei(t){return t==="chat"?"?":t==="agent"?"\uFFFD":"?"}function Nc(t){let e=t.trim().toLowerCase();return Xn(e)?e:null}function Bc(t){let e=t.trim().toLowerCase();return e==="on"||e==="enable"||e==="enabled"?"on":e==="off"||e==="disable"||e==="disabled"?"off":e==="status"||e==="show"?"status":null}function Dc(t){let e=t.trim().toLowerCase();return e==="parallel"?"parallel":e==="staged"||e==="stage"?"staged":null}function Fc(t){return(0,R.parseSubagentRoleList)(t)??null}function Uc(t){return(0,R.coerceSubagentTeamPreset)(t)}function jc(t){let e=t.trim().toLowerCase();if(e==="auto"||e==="default")return;let n=Number.parseInt(e,10);return!Number.isInteger(n)||n<1?null:n}function Vc(t){return(0,R.parseSubagentRemoteMcpPolicy)(t)}function Oi(t){return(0,R.normalizeSubagentBranchPolicy)({teamPreset:t.teamPreset,mode:t.mode,roles:t.roles,rolePrecedence:t.rolePrecedence,remoteMcpByRole:t.remoteMcpByRole,...t.maxConcurrentBranches!==void 0?{maxConcurrentBranches:t.maxConcurrentBranches}:{}})}function qc(t){return{teamPreset:t.teamPreset,mode:t.mode,roles:t.roles,rolePrecedence:t.rolePrecedence,remoteMcpByRole:t.remoteMcpByRole,...t.maxConcurrentBranches!==void 0?{maxConcurrentBranches:t.maxConcurrentBranches}:{}}}function Bg(t){return t.join(", ")}function Je(t){let e=Oi(t),n=e.rolePrecedence.join(", "),s=e.maxConcurrentBranches??e.roles.length,r=e.roles.map(i=>`${i}=${(0,R.resolveSubagentRemoteMcpAccess)(e,i)}`).join(", "),o=e.teamPreset??"custom";return`Delegation: ${t.enabled?"On":"Off"} | team ${o} | mode ${e.mode} | roles ${Bg(e.roles)} | concurrency ${s} | budget ${t.maxTotalTokens} | timeout ${t.timeoutMs}ms | precedence ${n} | remote ${r}`}function Hc(t){return t==="acceptEdits"?"default":t==="bypassPermissions"?"fullAccess":"readOnly"}function Mi(t){return t==="default"?"acceptEdits":t==="fullAccess"?"bypassPermissions":"default"}function jn(t){return t==="readOnly"?"Read Only":t==="default"?"Default":"Full Access"}function Dg(t){return t==="readOnly"||t==="default"||t==="fullAccess"}function zc(t){let e=t.trim().toLowerCase();return e==="read-only"||e==="readonly"||e==="read"||e==="ro"?"readOnly":e==="default"||e==="balanced"||e==="standard"?"default":e==="full"||e==="full-access"||e==="fullaccess"||e==="bypass"?"fullAccess":null}function Vr(t){let e=t.memoryContextSessions,n=t.memoryContextTokens,s=t.memoryContextChars;if(!(e===void 0&&n===void 0&&s===void 0))return{limit:e,maxTokens:n,maxCharsPerSession:s}}function Fg(t){let e=[];return t.connected.length>0&&e.push(`connected ${t.connected.length}`),t.skipped.length>0&&e.push(`skipped ${t.skipped.length}`),t.denied.length>0&&e.push(`denied ${t.denied.length}`),t.errors.length>0&&e.push(`errors ${t.errors.length}`),e.length>0?`MCP: ${e.join(" | ")}`:void 0}async function vc(t){if(!process.stdin.isTTY)throw new Error("AskUser is not available in non-interactive mode");let e=Pc({input:process.stdin,output:process.stderr});return new Promise(n=>{e.question(`${t} `,s=>{e.close(),n(s.trim())})})}function Ug(t){return async e=>{let n=t(),s=e.context?.trim();if(e.options&&e.options.length>0){let o=await n.actionPicker({title:"Ask User",description:s||e.question,options:e.options.map(i=>({value:i,label:i,detail:e.question})),selectedIndex:0});if(!o)throw new Error("AskUser was cancelled");return{answer:o,selectedOption:o}}return{answer:(await n.prompt(s?`${e.question} (${s})`:e.question)).trim()}}}function jg(){return async t=>{let e=t.context?.trim();if(t.options&&t.options.length>0){let s=[t.question,...e?[e]:[],...t.options.map((a,l)=>`${l+1}. ${a}`)],r=await vc(`${s.join(`
|
|
972
|
+
`)}
|
|
973
|
+
Choose an option:`),o=Number.parseInt(r,10);if(Number.isInteger(o)&&o>=1&&o<=t.options.length){let a=t.options[o-1];return{answer:a,selectedOption:a}}let i=t.options.find(a=>a===r.trim());if(i)return{answer:i,selectedOption:i};throw new Error("AskUser expected one of the provided options")}return{answer:await vc(e?`${t.question}
|
|
974
|
+
${e}`:t.question)}}}function Wc(t,e,n,s,r){let o=(0,R.createDefaultToolRegistry)({cwd:t,askUser:s});if(r){let i=(0,R.resolveSubagentRemoteMcpAccess)(n,e);(0,R.syncMcpToolsToRegistry)(r,o,[],a=>(0,R.matchesMcpRegistryEntryPolicy)(a,i))}return o}async function Xc(t){if(!t.enabled)return{refreshMcpTools:()=>{}};let e=new R.MCPManager,n=[],s=()=>{n=(0,R.syncMcpToolsToRegistry)(e,t.toolRegistry,n)};e.onServerStateChanged(o=>{(o.reason==="tools_changed"||o.reason==="prompts_changed"||o.reason==="resources_changed"||o.reason==="connected"||o.reason==="disconnected")&&s(),t.onServerStateChanged&&(o.reason==="connected"?t.onServerStateChanged(`MCP connected: ${o.serverName}`):o.reason==="tools_changed"?t.onServerStateChanged(`MCP tools updated: ${o.serverName}`):o.reason==="prompts_changed"?t.onServerStateChanged(`MCP prompts updated: ${o.serverName}`):o.reason==="resources_changed"?t.onServerStateChanged(`MCP resources updated: ${o.serverName}`):o.reason==="resource_updated"&&o.resourceUri?t.onServerStateChanged(`MCP resource updated: ${o.serverName} ${o.resourceUri}`):o.reason==="error"&&o.state.error&&t.onServerStateChanged(`MCP error: ${o.serverName} ${o.state.error}`))});let r=await e.connectConfiguredServers({cwd:t.cwd,...t.promptForApproval?{promptForApproval:t.promptForApproval}:{}});return s(),{mcpManager:e,refreshMcpTools:s,summary:Fg(r)}}async function Vg(t){if(Kc(t))return;let e=await ni({skipSuccessScreen:!0});e.kind==="exit"&&(process.stderr.write(Gn()),process.exit(0)),e.kind==="error"&&(process.stderr.write(xt(e.message)),process.exit(1));let n=Kt();t.apiKey=n?.apiKey??n?.accountToken??t.apiKey}async function qg(t){Kc(t)||process.stderr.write("Not signed in to XENO. Run `xeno login` from a terminal to sign in.\n")}function Kc(t){if(t.authBypassSource==="explicit-api-key")return typeof t.apiKey=="string"&&t.apiKey.trim().length>0;let e=Kt();return e&&on(e)?!0:ll()?!1:t.authBypassSource!=="config-api-key"&&typeof process.env.XENO_API_KEY=="string"&&process.env.XENO_API_KEY.trim().length>0}async function Gc(t){let e=process.cwd();if(!process.stdin.isTTY){await Sc(t);return}if(await Vg(t),t.lineInput||process.env.XENO_LINE_INPUT==="1"){await Sc(t);return}(0,B.isWorkspaceTrusted)(e)||((await Xa(e)).trusted||(process.stderr.write(Gn()),process.exit(0)),(0,B.setWorkspaceTrusted)(e,!0));let n,s,r,o,i,a,l,c,u,p=()=>{},f=null;try{let h=await(0,R.initializeSessionRuntime)({cwd:e,role:t.role,model:t.model,resume:t.resume,checkpoint:t.checkpoint,projectSessionContext:Vr(t),loadRestorableMessages:Un});n=h.sessionManager,s=h.checkpointManager,r=h.memoryManager,o=h.identityResolver,i=h.auditLogger,a=h.restoredMessages,l=h.sessionDir,c=h.sessionHistoryPath,f=h.turnRestoreManager??null}catch(h){let O=h instanceof Error?h.message:String(h);process.stderr.write(_.red(`\u2717 Error resuming session: ${O}
|
|
975
|
+
`)),process.exit(1)}let m;n&&(s=s??n.checkpoints,m=new ln.AutoCheckpointHandler(s));let g=!1,b=async()=>{if(!g){g=!0;try{u?.dispose(),await(0,R.cleanupSessionRuntime)({sessionManager:n,auditLogger:i})}catch(h){console.error("Warning: Session cleanup error:",h)}}},v=0,w=1500;process.on("beforeExit",b),process.on("SIGINT",async()=>{let h=Date.now();if(h-v>w){v=h,process.stderr.write(_.dim(`
|
|
976
|
+
Press Ctrl+C again to exit.
|
|
977
|
+
`));return}await b(),process.exit(130)}),process.on("SIGTERM",async()=>{await b(),process.exit(143)}),process.platform==="win32"&&process.on("SIGBREAK",async()=>{await b(),process.exit(0)});let P=o?await o.resolve({role:t.role}):void 0,C=await(0,R.buildPromptMemoryContext)(r,n?.meta.id),$=(0,R.formatPromptContextBreakdown)(C),E=t.executionMode??"agent";t.executionMode=E;let T={enabled:!!t.delegationEnabled,maxTotalTokens:t.delegationMaxTotalTokens??Math.max(t.maxTokens*3,1200),timeoutMs:t.delegationTimeoutMs??12e4,teamPreset:t.delegationTeamPreset??R.DEFAULT_SUBAGENT_TEAM_PRESET,mode:t.delegationMode??R.DEFAULT_SUBAGENT_BRANCH_POLICY.mode,roles:t.delegationRoles?.length?[...t.delegationRoles]:void 0,rolePrecedence:t.delegationRolePrecedence?.length?[...t.delegationRolePrecedence]:void 0,maxConcurrentBranches:t.delegationMaxConcurrentBranches,remoteMcpByRole:t.delegationRemoteMcpByRole?{...t.delegationRemoteMcpByRole}:void 0},I=new Date().toISOString().split("T")[0],re=async()=>(0,Rn.buildSystemPrompt)({cwd:e,model:t.model,date:I,identity:P,memory:C.merged,executionMode:E}),ae=await re(),N,y,oe=null,K=null,W={input:0,output:0,total:0},Z=Ug(()=>y),le=(0,R.createAuditBackedPermissionEngine)({mode:t.permissionMode,cwd:e,promptFn:h=>(y.stopSpinner(),y.permissionPrompt(h)),auditLogger:i,fallbackTraceId:`session-${n?.meta.id??"unknown"}`}),X=(0,R.createDefaultToolRegistry)({cwd:e,askUser:Z,dispatchAgent:async({prompt:h})=>({output:await(await(0,R.createDelegatedXenoAgent)({cwd:e,apiKey:t.apiKey,baseURL:t.baseURL,model:t.model,maxTokens:Math.max(512,Math.min(t.maxTokens,4096)),maxIterations:Math.max(3,Math.min(t.maxIterations,12)),parentSystemPrompt:ae,parentExecutionMode:E,subagentRole:"explorer",permissionEngine:le})).agent.run(h)}),memoryManager:r}),q=Date.now(),Q=()=>{let h=N.tokenUsage;return{input:h.input+W.input,output:h.output+W.output,total:h.total+W.total}},ye=()=>{let h=Q(),O=(0,pt.calculateCost)(t.model,h.input,h.output),S=n?Date.parse(n.meta.createdAt):q,k=Math.max(0,Date.now()-(Number.isFinite(S)?S:q));return mr(h.input,h.output)+_.dim(` | cost: ${(0,pt.formatCost)(O)} | duration: ${Rr(k)}`)},ee=()=>{let h=T.rolePrecedence?.join(", ")??R.DEFAULT_SUBAGENT_ROLE_PRECEDENCE.join(" > ");return`Delegation: ${T.enabled?"On":"Off"} \uFFFD budget ${T.maxTotalTokens} \uFFFD timeout ${T.timeoutMs}ms \uFFFD precedence ${h}`},Se=()=>{y.showTransientActivityNotice(Je(T))},me=h=>{y.showTransientActivityNotice(h)},de=(h,O)=>{me(O)},Ee=h=>{T={...T,enabled:h},y.setDelegationEnabled(h)},pe=async h=>{E!==h&&(E=h,t.executionMode=h,N.executionMode=h,N.systemPrompt=await re(),y.setExecutionMode(h))},te=h=>{t.permissionMode!==h&&(t.permissionMode=h,le.setMode(h),y.setPermissionMode(h))},Re=()=>$c(E,t.permissionMode),Ce=async h=>{h==="chat"?(await pe("chatOnly"),te("default")):h==="agent"?(await pe("agent"),te("acceptEdits")):(await pe("agent"),te("bypassPermissions"))},Ae=!1,xe=!1,Te=new In(h=>y.writeOutput(h,{selectable:!0,blockKind:"assistant"})," "),Ne=new Map,Xe=h=>Ng(h,{cwd:e,model:t.model,apiKey:t.apiKey,baseURL:t.baseURL,maxTokens:t.maxTokens,maxIterations:t.maxIterations,memoryManager:r}),He=h=>{let O=new Date(h).getTime(),S=Date.now(),k=Math.max(0,S-O),A=Math.floor(k/(60*1e3)),L=Math.floor(k/(3600*1e3)),V=Math.floor(k/(1440*60*1e3));return A<1?"just now":A<60?`${A}m ago`:L<24?`${L}h ago`:V<30?`${V}d ago`:`${Math.floor(V/30)}mo ago`},rt=h=>h<1024?`${h} B`:h<1024*1024?`${(h/1024).toFixed(1)} KB`:`${(h/(1024*1024)).toFixed(1)} MB`,Y=(h,O)=>h.length<=O?h:O<=1?"\uFFFD":h.slice(0,O-1)+"\uFFFD",D=h=>{let O=h.find(k=>k.role==="user"&&typeof k.content=="string");if(O&&typeof O.content=="string"&&O.content.trim().length>0)return Y(O.content.trim().replace(/\s+/g," "),120);let S=h.find(k=>k.role==="assistant"&&typeof k.content=="string");return S&&typeof S.content=="string"&&S.content.trim().length>0?Y(S.content.trim().replace(/\s+/g," "),120):"(session)"},H=async h=>{let O=new Set(h?.excludeSessionIds??[]),S=await Ie.SessionRegistry.list({role:h?.allRoles?void 0:t.role,workingDirectory:h?.workingDirectory,limit:60});return(await Promise.all(S.map(async A=>{if(O.has(A.id))return null;let L=Ie.SessionRegistry.getSessionDir(A.id),V=new Ie.TranscriptWriter(L),ke=new Ie.CheckpointManager(L),Be=[];try{Be=await V.getMessages()}catch{}let Fe=0;try{Fe=kc(Us(L,"transcript.jsonl")).size}catch{}let Qe=D(Be),z=0;if(Be.length>0&&!Ac(Be))z=Be.length;else try{let Ge=await ke.list();Ge.length>0?z=Ge[0].messageCount:z=Be.length}catch{z=Be.length}let ve=A.status==="active"?"HEAD":A.status.toUpperCase(),dt=`${He(A.lastActivity)} \uFFFD ${ve} \uFFFD ${z} msgs \uFFFD ${rt(Fe)}`;return{meta:A,preview:Qe,metaLine:dt}}))).filter(A=>!!A)},M=h=>{let O=h.replace(/[\\/]+$/,"");return process.platform==="win32"?O.toLowerCase():O},U=()=>{if(n)return M(n.meta.workingDirectory)===M(e)?n.meta.id:void 0},G=async()=>{let h=await Ie.SessionRegistry.list({workingDirectory:e}),O=U(),S=O?h.filter(k=>k.id===O).map(k=>k.id):[];return{matchingCount:h.length,purgeableCount:h.length-S.length,skippedIds:S}},fe=h=>{let O=`Purged ${h.deletedIds.length} session${h.deletedIds.length===1?"":"s"} for ${e}`;if(h.skippedIds.length===0)return O;let S=h.skippedIds.length===1?`Skipped active session: ${h.skippedIds[0]}`:`Skipped ${h.skippedIds.length} active sessions`;return`${O}. ${S}.`},ze=async()=>{let h=U();return Ie.SessionRegistry.purgeWorkingDirectory(e,{excludeSessionIds:h?[h]:void 0})},Vt=async h=>{await Ie.SessionRegistry.delete(h);let O=Us(e,".xeno","sessions",`${h}.md`);try{let S=await import("fs");S.existsSync(O)&&S.rmSync(O,{force:!0})}catch{}},ut=async()=>{let h=await y.actionPicker({title:"Sessions",description:"Choose action:",options:[{value:"list",label:"List",detail:"Browse, resume, export, or inspect saved sessions"},{value:"purge",label:"Purge",detail:"Delete saved sessions linked to this folder"}]});return h==="list"||h==="purge"?h:null},Pt=async()=>{let h=await y.actionPicker({title:"Purge Sessions",description:"Choose purge mode:",options:[{value:"all",label:"Purge all",detail:"Delete all saved sessions linked to this folder"},{value:"selected",label:"Select from list",detail:"Choose specific sessions from this folder to delete"}]});return h==="all"||h==="selected"?h:null},zn=async()=>{let h=await H({workingDirectory:e,allRoles:!0});if(h.length===0){y.writeInfo(`No sessions found for ${e}`);return}let O=h.map(L=>({value:L.meta.id,title:L.preview,meta:L.metaLine})),S=await y.sessionPicker({title:"Sessions",description:"Search sessions in this folder...",options:O,confirmLabel:"Enter to view"});if(!S)return;let k=h.find(L=>L.meta.id===S);if(!k)return;let A=await vs();if(A){if(A==="view"){await ht(k);return}if(A==="resume"){await wt(k.meta.id);return}if(A==="export-md"||A==="export-json"){let L=await zt(k,A==="export-md"?"md":"json");await tn({title:"Export Session",content:L.content,defaultPath:L.defaultPath,subject:L.subject});return}A==="delete"&&await y.modelPicker({title:"Delete session",description:"Type to filter",options:[{value:"cancel",label:"Cancel",detail:"(keep session)"},{value:"delete",label:`Delete ${k.meta.id}`,detail:"(permanent)"}],currentValue:"cancel"})==="delete"&&(await Ie.SessionRegistry.delete(k.meta.id),y.writeInfo(`Deleted session: ${k.meta.id}`))}},pn=async()=>{let h=await Pt();if(!h)return;if(h==="all"){let V=await G();if(V.matchingCount===0){y.writeInfo(`No sessions found for ${e}`);return}if(V.purgeableCount===0){y.writeInfo(`No purgeable sessions found for ${e}. Active session is still open.`);return}if(await y.actionPicker({title:"Purge Workspace Sessions",description:`Delete ${V.purgeableCount} saved session${V.purgeableCount===1?"":"s"} for ${e}?`,options:[{value:"cancel",label:"Cancel",detail:"Keep the saved sessions for this folder"},{value:"purge",label:"Purge sessions",detail:"Delete the saved sessions linked to this folder"}]})!=="purge")return;let Be=await ze();y.writeInfo(fe(Be));return}let O=U(),S=await H({workingDirectory:e,excludeSessionIds:O?[O]:void 0,allRoles:!0});if(S.length===0){y.writeInfo(`No purgeable sessions found for ${e}`);return}let k=await y.sessionMultiPicker({title:"Purge Sessions",description:"Select sessions to delete",options:S.map(V=>({value:V.meta.id,title:V.preview,meta:V.metaLine})),confirmLabel:"Enter confirm"});if(!k||k.length===0)return;let A=S.filter(V=>k.includes(V.meta.id));if(await y.actionPicker({title:"Delete Sessions",description:`Delete ${k.length} selected session${k.length===1?"":"s"}?`,options:[{value:"cancel",label:"Cancel",detail:"Keep the selected saved sessions"},{value:"delete",label:"Delete selected",detail:"Permanently remove the selected saved sessions"}]})==="delete"){for(let V of A)await Vt(V.meta.id);y.writeInfo(`Deleted ${A.length} session${A.length===1?"":"s"} from ${e}`)}},wt=async h=>{let O=await Ie.SessionRegistry.find(h);if(!O){y.writeInfo(_.red(`\u2717 Session not found: ${h}`));return}let S=await Un(h);if(S.length===0){y.writeInfo(_.red(`\u2717 Session has no restorable messages: ${h}`));return}N.messages=S,n&&await n.updateMessageCount(S.length),O.model&&O.model!==t.model&&(t.model=O.model,N.model=O.model,N.systemPrompt=await re(),y.setModel(O.model)),Ti(y,S,Xe)},at=h=>{let O=0;for(let S=0;S<N.messages.length;S++){let k=N.messages[S];if(!(k.role!=="user"||typeof k.content!="string")){if(O===h)return S;O+=1}}return-1},vt=()=>l?(f||(f=new Ie.TurnRestoreManager(l,e)),f):null,qt=async h=>{let O=vt();if(K=null,!O)return;K=(await O.create({id:dg(),restoreMessageCount:N.messages.length,userPrompt:h})).id},$t=async(h,O)=>{let S=vt();!S||!K||await S.recordToolExecution(K,h,O)},ft=()=>{K=null},Lt=async(h,O)=>{let S=at(h);if(S<0)return y.showTransientActivityNotice("Could not find that user turn to restore"),{ok:!1,exactWorkspaceRestore:!1,hadRestorePoint:!1,unsupportedTools:[]};let k=vt(),A=k?await k.inspectAtOrAfter(S):null;if(O?.requireExactWorkspace){if(!A?.hadRestorePoints)return y.showTransientActivityNotice("No safe workspace restore point for that turn"),{ok:!1,exactWorkspaceRestore:!1,hadRestorePoint:!1,unsupportedTools:[]};if(!A.exactWorkspaceRestore){let L=A.unsupportedTools.length>0?` because it used ${A.unsupportedTools.join(", ")}`:"";return y.showTransientActivityNotice(`Exact workspace restore unavailable${L}`),{ok:!1,exactWorkspaceRestore:!1,hadRestorePoint:!0,unsupportedTools:A.unsupportedTools}}}return A?.hadRestorePoints&&await k.restoreAtOrAfter(S),ft(),N.messages=N.messages.slice(0,S),n&&(await n.updateMessageCount(N.messages.length),await n.transcript.truncateAfterMessageCount(S)),await mn(),y.clear(),y.writeOutput(Cn(Ze,t.model)),Ti(y,N.messages,Xe),{ok:!0,exactWorkspaceRestore:A?.exactWorkspaceRestore??!1,hadRestorePoint:A?.hadRestorePoints??!1,unsupportedTools:A?.unsupportedTools??[]}},Rt=async()=>{let h=vt(),O=await Promise.all(N.messages.map((ke,Be)=>({message:ke,index:Be})).filter(({message:ke})=>ke.role==="user"&&typeof ke.content=="string").map(async({message:ke,index:Be},Fe)=>{let Qe=h?await h.inspectAtOrAfter(Be):null,z="Conversation only";if(!Qe?.hadRestorePoints)z="Conversation only \uFFFD no safe workspace restore point";else if(Qe.exactWorkspaceRestore)z="Conversation + workspace restore";else{let ve=Qe.unsupportedTools.join(", ");z=ve.length>0?`Conversation + tracked file restore \uFFFD exact restore blocked by ${ve}`:"Conversation + tracked file restore"}return{userOrdinal:Fe,text:String(ke.content).trim()||"(empty)",meta:z}}));if(O.reverse(),O.length===0){y.showTransientActivityNotice("Nothing to rewind");return}let S=await y.sessionPicker({title:"Rewind",description:"Restore to before a prior user turn",options:[...O.map(ke=>({value:String(ke.userOrdinal),title:ke.text,meta:ke.meta})),{value:"__current__",title:"(current)",meta:"Keep the current interrupted state"}],confirmLabel:"Enter to continue"});if(!S||S==="__current__")return;let k=Number(S),A=O.find(ke=>ke.userOrdinal===k);if(!A)return;let L=await Lt(k);if(!L.ok)return;let V=L.exactWorkspaceRestore||L.hadRestorePoint?`Restored to before: ${A.text}`:`Restored conversation before: ${A.text}`;y.writeInfo(` ${_.dim(`? ${V}`)}`),L.hadRestorePoint&&!L.exactWorkspaceRestore&&L.unsupportedTools.length>0&&y.writeInfo(` ${_.dim(`? Workspace restore stayed safe; exact rollback was blocked by ${L.unsupportedTools.join(", ")}.`)}`)},en=h=>h.every(O=>bc(O)!==null),Ht=h=>{if(!h)return["Delegation summary: none recorded"];let O=[`Selected role: ${h.selectedRole??"-"}`,`Elapsed: ${Math.max(0,Math.round(h.elapsedMs/1e3))}s`,`Branches: ${h.okBranches}/${h.totalBranches} ok`,`Tokens: ${h.totalTokens}`];for(let[S,k]of Object.entries(h.roleSummaries))O.push(`${S}: ${k.status} \uFFFD ${k.tokensUsed} tok${k.outputPreview?` \uFFFD ${k.outputPreview}`:""}`);return O},F=h=>h.length===0?"(no restorable messages)":h.map(O=>{let S=O.role==="assistant"?"assistant":"user",k=bc(O)??"";return[`[${S}]`,k].join(`
|
|
978
|
+
`)}).join(`
|
|
979
|
+
|
|
980
|
+
`),et=h=>{let O=h.replace(/\r\n/g,`
|
|
981
|
+
`).trim();return!O||O==="(no restorable messages)"?[]:O.split(/\n{2,}(?=\[(?:user|assistant)\])/g).map(k=>{let A=k.split(`
|
|
982
|
+
`),L=A.shift()?.trim().toLowerCase();if(L!=="[user]"&&L!=="[assistant]")throw new Error("Invalid session conversation format");let V=A.join(`
|
|
983
|
+
`).trimEnd();return{role:L==="[assistant]"?"assistant":"user",content:V}})},ht=async h=>{let O=await Un(h.meta.id),S=O.slice(-6),A=await new Ie.TranscriptWriter(Ie.SessionRegistry.getSessionDir(h.meta.id)).read({types:["delegation_summary"]}),L=A.length>0?A[A.length-1]?.data:null;await y.infoPanel({title:"Session details",subtitle:h.metaLine,lines:[],layout:"viewport",focusPane:"content",footerHint:"?/? focus \uFFFD ?/? scroll pane \uFFFD Enter edit \uFFFD Esc close",cards:[{title:"Messages",value:String(O.length)},{title:"Status",value:h.meta.status.toUpperCase()},{title:"Role",value:h.meta.role},{title:"Model",value:h.meta.model},{title:"Delegations",value:String(A.length)}],split:{left:{title:"Details",summary:`${O.length} messages`,lines:[`ID: ${h.meta.id}`,`Model: ${h.meta.model}`,`Role: ${h.meta.role}`,`Status: ${h.meta.status}`,`Messages: ${O.length}`,`Last activity: ${new Date(h.meta.lastActivity).toLocaleString()}`,`Working directory: ${h.meta.workingDirectory}`,"",...Ht(L)]},right:{title:"Conversation History",summary:S.length>0?`${S.length} recent messages`:"preview only",lines:Gt(F(O)),editable:en(O)?{label:"Conversation History",value:F(O),initialCursor:"start",previewLines:V=>Gt(V),onSave:async V=>{let ke=et(V);if(ke.length!==O.length)throw new Error("Message count must stay the same");return await new Ie.TranscriptWriter(Ie.SessionRegistry.getSessionDir(h.meta.id)).replaceMessages(ke),{summary:`${ke.length} messages`}}}:void 0}}})},zt=async(h,O)=>{let S=await Un(h.meta.id),k=`session-${h.meta.id}`;return O==="json"?{content:JSON.stringify(S,null,2),defaultPath:Us(process.cwd(),`${k}.json`),subject:"session JSON"}:{content:ls(S,h.meta.model),defaultPath:Us(process.cwd(),`${k}.md`),subject:"session markdown"}},St=()=>new Date().toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"").replace("T","-"),Nt=()=>Us(process.cwd(),`conversation-${n?.meta.id??St()}.md`),Pn=async()=>{await tn({title:"Export Conversation",content:ls(N.messages,t.model),defaultPath:Nt(),subject:"conversation"})},tn=async h=>{let O=await y.actionPicker({title:h.title,description:"Select export method:",options:[{value:"copy",label:"Copy to clipboard",detail:`Copy the ${h.subject} to your system clipboard`},{value:"file",label:"Save to file",detail:"Save the export to a file in the current directory"}]});if(!O)return;if(O==="copy"){(0,sn.copyTextToClipboard)(h.content),y.writeInfo(`Copied ${h.subject} to clipboard`);return}(await import("fs")).writeFileSync(h.defaultPath,h.content,"utf-8"),y.writeInfo(`Saved ${h.subject}: ${h.defaultPath}`)},vs=async()=>{let h=await y.modelPicker({title:"Session action",description:"Choose action",options:[{value:"view",label:"View details",detail:"(preview and metadata)"},{value:"resume",label:"Resume session",detail:"(restore conversation)"},{value:"export-md",label:"Export markdown",detail:"(opens export method picker)"},{value:"export-json",label:"Export JSON",detail:"(opens export method picker)"},{value:"delete",label:"Delete session",detail:"(remove permanently)"}]});return h&&(h==="view"||h==="resume"||h==="export-md"||h==="export-json"||h==="delete")?h:null},Tn=async h=>{let O=`session-${n?.meta.id??"unknown"}-${Date.now().toString(36)}`,S=Oi(T),k=[...S.roles],A=Date.now(),L=new Map;y.startDelegationView(k),y.appendDelegationEvent("system",`Workflow started (${S.mode}, max ${S.maxConcurrentBranches??k.length} concurrent)`);let V;try{V=await(0,R.runDelegatedXenoTurn)({userPrompt:h,cwd:e,apiKey:t.apiKey,baseURL:t.baseURL,model:t.model,maxIterations:t.maxIterations,maxTotalTokens:T.maxTotalTokens,timeoutMs:T.timeoutMs,rolePrecedence:T.rolePrecedence,branchPolicy:qc(T),parentSystemPrompt:N.systemPrompt,parentExecutionMode:E,auditLogger:i,rootTraceId:O,skipAuditCompletion:!0,onBranchStart:async z=>{if(xe)throw new R.AgentInterruptedError;L.set(z.id,0),y.updateDelegationAgent(z.role,{status:"running",phase:"thinking",activity:"Starting delegated branch"}),y.appendDelegationEvent(z.role,"started")},createBranchAgent:async({task:z})=>{let ve=(await(0,R.createDelegatedXenoAgent)({cwd:e,apiKey:t.apiKey,baseURL:t.baseURL,model:t.model,maxTokens:z.maxTokens,maxIterations:z.maxIterations,parentSystemPrompt:N.systemPrompt,parentExecutionMode:E,subagentRole:z.role,permissionEngine:le,toolRegistry:Wc(e,z.role,S,Z,u),...i?{session:{auditLogger:i}}:{},onIteration:(dt,Ge)=>{y.updateDelegationAgent(z.role,{phase:"thinking",activity:`Iteration ${dt}`,tokenCount:Ge})},onToolStart:(dt,Ge)=>{let Et=(L.get(z.id)??0)+1;L.set(z.id,Et);let or=yg(dt,Ge);y.updateDelegationAgent(z.role,{phase:"tool",activity:or,toolCount:Et,tokenCount:ve.tokenUsage.total,currentTool:dt}),y.appendDelegationEvent(z.role,`${or} started`)},onToolWillExecute:async(dt,Ge)=>{await $t(dt,Ge)},onToolEnd:(dt,Ge)=>{let Et=Ge.success?"completed":"failed";y.updateDelegationAgent(z.role,{phase:Ge.success?"thinking":"failed",activity:`${dt} ${Et}`,toolCount:L.get(z.id)??0,tokenCount:ve.tokenUsage.total,currentTool:void 0}),y.appendDelegationEvent(z.role,`${dt} ${Et}`)}})).agent;return oe=ve,ve},onBranchComplete:async(z,ve)=>{y.updateDelegationAgent(z.role,{status:"done",phase:"done",activity:"Completed",toolCount:L.get(z.id)??0,tokenCount:ve.tokenUsage.total,currentTool:void 0,outputPreview:Ai(ve.output)}),y.appendDelegationEvent(z.role,"completed"),oe=null},onBranchError:async(z,ve,dt)=>{let Ge=ve instanceof R.AgentInterruptedError;y.updateDelegationAgent(z.role,{status:Ge?"interrupted":"failed",phase:Ge?"interrupted":"failed",activity:Ge?"Interrupted":ve instanceof Error?ve.message:String(ve),toolCount:L.get(z.id)??0,tokenCount:dt.tokenUsage.total,currentTool:void 0}),y.appendDelegationEvent(z.role,Ge?"interrupted":"failed"),oe=null}})}catch(z){throw y.appendDelegationEvent("system",z instanceof R.AgentInterruptedError?"Workflow interrupted":`Workflow failed: ${z instanceof Error?z.message:String(z)}`),z}let ke=Ec(V.workflow,V.tokenUsage.total,Date.now()-A),Be=V.answer,Fe=V.selectedTraceId;W.input+=V.tokenUsage.input,W.output+=V.tokenUsage.output,W.total+=V.tokenUsage.total;let Qe=[...N.messages,{role:"user",content:h},{role:"assistant",content:Be}];N.messages=Qe,n&&(await n.recordUserMessage(h),await n.recordAssistantMessage(Be),await n.recordTokenUsage(V.tokenUsage.input,V.tokenUsage.output),await n.recordDelegationSummary(ke)),await i?.append({trace_id:Fe??O,event_type:"delegation_completed",actor:"system",risk_level:"none",status:"ok",metadata:{selected_from:V.workflow.reduced.selectedFrom,subagents:V.summary,branch_policy:{mode:S.mode,roles:S.roles,max_concurrent_branches:S.maxConcurrentBranches},delegation_summary:ke,recent_activity:V.workflow.results.map(z=>({role:z.role,status:z.status,preview:z.status==="ok"?Ai(z.output):z.error}))}}),y.appendDelegationEvent("system",wg(ke)),y.trimTrailingOutputNewlines(1),y.writeOutput(`
|
|
984
|
+
${_.accent("\u25A0")} `,{forceNewBlock:!0,selectable:!0,blockKind:"assistant"}),Te.reset(),Te.markLineStarted(),Te.write(Be),Te.flush(),y.writeOutput(`
|
|
985
|
+
`,{selectable:!0,blockKind:"assistant"})},mn=async()=>{C=await(0,R.buildPromptMemoryContext)(r,n?.meta.id),$=(0,R.formatPromptContextBreakdown)(C),y&&y.setPromptContextBreakdown($),N&&(N.systemPrompt=await re())},ie=async()=>{if(n)return!0;try{let h=await(0,R.activateSessionRuntime)({sessionManager:n,checkpointManager:s,memoryManager:r,identityResolver:o,auditLogger:i,restoredMessages:a,sessionDir:l,sessionHistoryPath:c,turnRestoreManager:f},{cwd:e,role:t.role,model:t.model,projectSessionContext:Vr(t)});n=h.sessionManager,s=h.checkpointManager,r=h.memoryManager,o=h.identityResolver,i=h.auditLogger,a=h.restoredMessages,l=h.sessionDir,c=h.sessionHistoryPath,f=h.turnRestoreManager??null,m=s?new ln.AutoCheckpointHandler(s):void 0;let O=h.sessionManager;if(!O)throw new Error("Session activation succeeded without a session manager");return N.attachSessionIntegration({transcript:O.transcript,checkpoints:s,sessionManager:O,historyMarkdownPath:c,auditLogger:i}),await mn(),!0}catch(h){let O=h instanceof Error?h.message:String(h);return y.writeInfo(_.red(`? Error creating session: ${O}`)),!1}};y=new gr({model:t.model,permissionMode:t.permissionMode,executionMode:E,delegationEnabled:T.enabled,maxContextTokens:Ci,promptContextBreakdown:$,onToggleDelegation:h=>{Ee(h),Se()},onOpenRewind:async()=>{await Rt()},onOutputAction:async h=>{if(h.action==="restore"){let k=at(h.userMessageOrdinal);if(k<0){y.showTransientActivityNotice("Could not find that user turn");return}let A=vt(),L=A?await A.inspectAtOrAfter(k):null,V=[],ke=N.messages.length-k;if(V.push(`${_.dim("Messages to remove:")} ${ke}`),V.push(""),!L?.hadRestorePoints)V.push(`${_.dim("Workspace:")} conversation only (no file restore points)`);else{V.push(`${_.dim("Workspace:")} ${L.exactWorkspaceRestore?"exact restore available":"partial restore (some tools untracked)"}`),L.unsupportedTools.length>0&&V.push(`${_.dim("Untracked tools:")} ${L.unsupportedTools.join(", ")}`);let Fe=[],Qe=[];for(let z of L.points)for(let ve of z.mutations)ve.existedBefore?Fe.includes(ve.relativePath)||Fe.push(ve.relativePath):Qe.includes(ve.relativePath)||Qe.push(ve.relativePath);if(Fe.length>0){V.push(""),V.push(_.accent("Files to revert:"));for(let z of Fe)V.push(` ${_.dim("~")} ${z}`)}if(Qe.length>0){V.push(""),V.push(_.accent("Files to remove (created during turn):"));for(let z of Qe)V.push(` ${_.dim("+")} ${z}`)}Fe.length===0&&Qe.length===0&&(V.push(""),V.push(_.dim("No tracked file changes.")))}await y.infoPanel({title:"Restore Details",subtitle:`Rewind to before: ${h.text}`,lines:V,footerHint:"Enter to restore \u2022 Esc to cancel"}),(await Lt(h.userMessageOrdinal)).ok&&me(`Restored to before "${h.text}"`);return}if(!(await Lt(h.userMessageOrdinal)).ok)return;let S=h.action==="edit"?"Edit":"Retry";if(me(`${S}: restored to before "${h.text}"`),h.action==="edit"){y.setInputText(h.text,{cursor:"end",escCancelable:!0});return}y.setInputText(h.text,{cursor:"end",escCancelable:!1}),y.handleEnter()},onFixTypo:h=>kg(h,t.apiKey),onRewriteAs:(h,O,S)=>xg(h,O,S,t.apiKey),onSubmit:async h=>{if(h.startsWith("! ")||h.startsWith("!")){let S=h.startsWith("! ")?h.slice(2):h.slice(1);S.trim()&&(h=`Run this exact command: ${S}`)}if(xi(h)){let S=await Si(h,{cwd:e,sessionDir:n?Ie.SessionRegistry.getSessionDir(n.meta.id):void 0,memoryManager:r,checkpointManager:s,auditLogger:i,mcpManager:u,refreshMcpTools:p,messages:N.messages,onOutput:k=>y.writeOutput(k),onHelp:async()=>{await y.helpPanel()},onPanel:async k=>{await y.infoPanel(k)},onActionPicker:async k=>await y.actionPicker(k),buildSystemPrompt:re,toolDefinitions:()=>X.getDefinitions(),maxContextTokens:Ci});if(S.handled){S.messages&&(N.messages=S.messages);return}}if(h==="/login"||h.startsWith("/login ")){let S=h.slice(6).trim().split(/\s+/).filter(Boolean),k=S[0]?.toLowerCase();if(k==="status"){let A=await Tt({validate:!0});y.writeInfo(an(A).trimEnd());return}if(k==="api-key"){let A=S.slice(1).join(" ").trim();if(!A){y.writeOutput(xt("Usage: /login api-key <key>"));return}let L=await bn({apiKey:A,apiBaseURL:t.baseURL});if(!L.valid){y.writeOutput(xt(`API key validation failed: ${L.error??"unknown error"}`));return}bt({apiKey:A,apiBaseURL:t.baseURL,source:"api-key"}),t.apiKey=A,Vs(N,A),y.writeInfo("Stored API key and switched this chat session to it.");return}if(k==="help"){y.writeInfo("Xeno auth\nUse `/login` to launch the sign-in welcome screen.\nUse `/login status` to inspect local auth.\nUse `/login api-key <key>` to switch this chat to a model API key immediately.");return}if(!k){let A=await y.actionPicker({title:"Xeno Sign In",description:"Choose a sign-in method. The chat UI stays attached while Xeno waits for completion.",options:[{value:"browser",label:"Browser Login",detail:"Open xenostudio.ai and authorize this CLI session"},{value:"device-code",label:"Device Code",detail:"Use a one-time code for remote/headless terminals"},{value:"status",label:"Auth Status",detail:"Inspect the current local auth state"}],selectedIndex:0});if(!A){y.writeInfo("Sign-in cancelled.");return}if(A==="status"){let Fe=await Tt({validate:!0});y.writeInfo(an(Fe).trimEnd());return}let L=Fe=>new Promise(Qe=>{if(Fe.aborted){Qe("complete");return}Fe.addEventListener("abort",()=>Qe("complete"),{once:!0})});y.writeInfo(A==="browser"?"Starting browser sign-in...":"Starting device-code sign-in...");let{runBrowserFlow:V,runDeviceCodeFlow:ke}=await Promise.resolve().then(()=>(Ms(),_r)),Be=A==="browser"?await V({authBaseURL:ot,apiBaseURL:t.baseURL,silent:!0,waitForCancel:L,onStarted:Fe=>{y.writeInfo(["Browser sign-in started.",`Open: ${Fe.auth_url}`,`Local callback: ${Fe.redirect_uri}`].join(`
|
|
986
|
+
`))},log:Fe=>y.writeOutput(Fe)}):await ke({authBaseURL:ot,apiBaseURL:t.baseURL,silent:!0,waitForCancel:L,onStarted:Fe=>{y.writeInfo(["Device-code sign-in started.",`Open: ${Fe.verification_url}`,`Code: ${Fe.formattedUserCode}`,"Do not share this code."].join(`
|
|
987
|
+
`))},log:Fe=>y.writeOutput(Fe)});if(Be.kind==="success"){let Fe=Kt(),Qe=on(Fe)?.value??t.apiKey;t.apiKey=Qe,Vs(N,Qe);let z=Be.user?.email;y.writeInfo(z?`Signed in as ${z}.`:"Signed in to XENO.")}else Be.kind==="error"||Be.kind==="timeout"?y.writeOutput(xt(Be.message)):y.writeInfo("Sign-in cancelled.");return}y.writeOutput(xt("Usage: /login [status|api-key <key>]"));return}if((h==="/logout"||h.startsWith("/logout "))&&(Zn(),es(),Qn(),(0,B.saveConfig)({apiKey:void 0}),t.apiKey=void 0,Vs(N,void 0),await b(),y.cleanup(),process.stdout.write("Signed out. Run `xeno` to sign in again.\n"),process.exit(0)),h==="/open"||h.startsWith("/open ")){let S=h.slice(5).trim(),k=S?Vn(e,S):e,A=process.platform==="win32"?"Explorer":process.platform==="darwin"?"Finder":"file manager";me(`Opening ${k} in ${A}...`);try{let L=await Rc(k);de(h,`Opened ${k} in ${L}`)}catch(L){y.writeOutput(xt(`Failed to open folder: ${L instanceof Error?L.message:String(L)}`))}return}if((h==="/exit"||h==="/quit")&&(await b(),y.cleanup(),process.stderr.write(Gn()),process.exit(0)),h==="/clear"){N.clearHistory(),y.clear(),y.writeOutput(Cn(Ze,t.model)),me("Cleared chat history");return}if(h==="/tokens"||h==="/cost"){y.writeInfo(ye());return}if(h==="/help"){await y.helpPanel();return}if(h==="/export"||h.startsWith("/export ")){let S=h.slice(8).trim(),k=N.messages;if(!S)await Pn();else if(S==="json"){let A=JSON.stringify(k,null,2);y.writeOutput(`
|
|
988
|
+
`+A+`
|
|
989
|
+
`)}else if(S&&S!=="md"){let A=await import("fs"),L=ls(k,t.model);A.writeFileSync(S,L,"utf-8"),y.writeInfo(`Exported to: ${S}`)}else{let A=ls(k,t.model);y.writeOutput(`
|
|
990
|
+
`+A+`
|
|
991
|
+
`)}return}if(h==="/save"){let S=Q(),k=(0,Mn.saveSession)(null,N.messages,t.model,S.total);y.writeInfo(`Session saved: ${k}`);return}if(h.trim()==="/sessions purge"){try{await pn()}catch(S){let k=S instanceof Error?S.message:String(S);y.writeInfo(_.red(`? Failed to purge sessions: ${k}`))}return}if(h==="/sessions"){try{let S=await ut();if(!S)return;S==="list"?await zn():await pn()}catch(S){let k=S instanceof Error?S.message:String(S);y.writeInfo(_.red(`? Failed to load sessions: ${k}`))}return}if(h==="/resume"){try{let S=await H({workingDirectory:e,allRoles:!0});if(S.length===0){y.writeInfo("No sessions found in this workspace");return}let k=S.map(L=>({value:L.meta.id,title:L.preview,meta:L.metaLine})),A=await y.sessionPicker({title:"Resume Session",description:"Search sessions...",options:k,confirmLabel:"Enter to resume"});A&&await wt(A)}catch(S){let k=S instanceof Error?S.message:String(S);y.writeInfo(_.red(`? Failed to resume session: ${k}`))}return}if(h.startsWith("/resume ")){let S=h.slice(8).trim();if(!S){y.writeInfo(_.red("Usage: /resume <session-id>"));return}await wt(S);return}if(h==="/model"){try{let k=(await(0,we.getAvailableModels)({apiKey:t.apiKey})).filter(we.isChatModel),A=Array.from(new Map(k.map(V=>[V.id,V])).values());if(A.length===0){y.writeInfo("No models available");return}A.sort((V,ke)=>V.id===t.model?-1:ke.id===t.model?1:V.id===we.DEFAULT_MODEL?-1:ke.id===we.DEFAULT_MODEL?1:V.source!==ke.source?V.source==="xeno"?-1:1:V.id.localeCompare(ke.id));let L=await y.modelPicker({title:"Select model",description:"Type to filter models",currentValue:t.model,options:A.map(V=>({value:V.id,label:V.id,detail:V.id===we.DEFAULT_MODEL?"(recommended default)":V.source==="local"?"(local model)":"(Xeno API)"}))});if(L&&L!==t.model){y.startSpinner("Checking model...");let V=await Ii(L);if(y.stopSpinner(),!V.ok){y.writeInfo(_.red(`\u2717 ${V.error}`));return}t.model=L,N.model=L,N.systemPrompt=await re(),y.setModel(L),de("/model",`Switched model to ${L}`),V.warning&&y.writeInfo(_.dim(V.warning))}else de("/model",`Kept model as ${t.model}`)}catch(S){y.stopSpinner();let k=S instanceof Error?S.message:String(S);y.writeInfo(_.red(`\u2717 Failed to load models: ${k}`))}return}if(h.startsWith("/model ")){let S=h.slice(7).trim();if(S==="--all"){de("/model --all",`Listed models (current: ${t.model})`);let k=await(0,we.formatModelList)(t.apiKey,!0);y.writeInfo(`Available models:
|
|
992
|
+
${k}`)}else if(S){if(S===t.model){de(h,`Kept model as ${t.model}`);return}y.startSpinner("Checking model...");let k=await Ii(S);if(y.stopSpinner(),!k.ok){y.writeInfo(_.red(`\u2717 ${k.error}`));return}t.model=S,N.model=S,N.systemPrompt=await re(),y.setModel(S),de(h,`Switched model to ${S}`),k.warning&&y.writeInfo(_.dim(k.warning))}return}if(h==="/mode"){let S=Re(),k=await y.modelPicker({title:"Select mode",description:"Switch runtime mode",currentValue:S,options:[{value:"chat",label:`${Ei("chat")} Chat`,detail:"(read-only behavior, ask before edits/commands)"},{value:"agent",label:`${Ei("agent")} Agent`,detail:"(default behavior: edits allowed, ask before commands)"},{value:"fullAccess",label:`${Ei("fullAccess")} Full Access`,detail:"(no per-action prompts; trusted workspaces only)"}]});k==="chat"||k==="agent"||k==="fullAccess"?(await Ce(k),(0,B.saveConfig)({executionMode:E,permissionMode:t.permissionMode}),de("/mode",`Switched mode to ${cs(Re())}`)):de("/mode",`Kept mode as ${cs(S)}`);return}if(h.startsWith("/mode ")){let S=h.slice(6).trim(),k=Lc(S);if(!k){y.writeInfo(_.red("Usage: /mode <chat|agent|full-access>"));return}let A=Re();if(k===A){de(h,`Kept mode as ${cs(A)}`);return}await Ce(k),(0,B.saveConfig)({executionMode:E,permissionMode:t.permissionMode}),de(h,`Switched mode to ${cs(Re())}`);return}if(h==="/delegate"||h.startsWith("/delegate ")){let S=h.slice(9).trim();if(!S){let A=await y.modelPicker({title:"Delegation mode",description:"Planner/explorer/executor/reviewer workflow",currentValue:T.enabled?"on":"off",options:[{value:"off",label:"Off",detail:"(default single-agent turns)"},{value:"on",label:"On",detail:"(delegated multi-agent turns)"}]});A==="on"||A==="off"?(Ee(A==="on"),de("/delegate",`Delegation ${A==="on"?"enabled":"disabled"}`)):de("/delegate",`Kept delegation ${T.enabled?"enabled":"disabled"}`);return}let k=Bc(S);if(k==="status"){de(h,Je(T));return}if(k==="on"||k==="off"){Ee(k==="on"),de(h,`Delegation ${k==="on"?"enabled":"disabled"}`);return}if(S.toLowerCase().startsWith("precedence ")){let A=S.slice(11).trim();if(A.toLowerCase()==="default"){T={...T,rolePrecedence:void 0},de(h,Je(T));return}let L=A.split(",").map(V=>V.trim()).filter(V=>V.length>0);if(L.length===0){y.writeInfo(_.red("Usage: /delegate precedence <role1,role2,role3>"));return}T={...T,rolePrecedence:L},de(h,Je(T));return}if(S.toLowerCase().startsWith("mode ")){let A=S.slice(5).trim(),L=Dc(A);if(!L){y.writeInfo(_.red("Usage: /delegate mode <staged|parallel>"));return}T={...T,mode:L},de(h,Je(T));return}if(S.toLowerCase().startsWith("team ")){let A=S.slice(5).trim();if(A.toLowerCase()==="default"||A.toLowerCase()==="balanced"){T={...T,teamPreset:R.DEFAULT_SUBAGENT_TEAM_PRESET},de(h,Je(T));return}let L=Uc(A);if(!L){y.writeInfo(_.red("Usage: /delegate team <balanced|explore|build|review|default>"));return}T={...T,teamPreset:L},de(h,Je(T));return}if(S.toLowerCase().startsWith("roles ")){let A=S.slice(6).trim();if(A.toLowerCase()==="default"||A.toLowerCase()==="all"){T={...T,roles:void 0},de(h,Je(T));return}let L=Fc(A);if(!L){y.writeInfo(_.red("Usage: /delegate roles <planner,explorer,executor,reviewer|default>"));return}T={...T,teamPreset:void 0,roles:L},de(h,Je(T));return}if(S.toLowerCase().startsWith("concurrency ")){let A=S.slice(12).trim(),L=jc(A);if(L===null){y.writeInfo(_.red("Usage: /delegate concurrency <n|auto>"));return}T={...T,maxConcurrentBranches:L},de(h,Je(T));return}if(S.toLowerCase().startsWith("remote ")){let A=S.slice(7).trim(),L=Vc(A);if(L===null){y.writeInfo(_.red("Usage: /delegate remote <none|prompts|resources|context|all|role=policy,...|default>"));return}T={...T,remoteMcpByRole:L},de(h,Je(T));return}y.writeInfo(_.red("Usage: /delegate [on|off|status|team <balanced|explore|build|review|default>|mode <staged|parallel>|roles <csv|default>|concurrency <n|auto>|precedence <csv|default>|remote <policy|role=policy,...|default>]"));return}if(h==="/approvals"||h.startsWith("/approvals ")){let S=h.slice(10).trim();if(!S){let L=Hc(t.permissionMode),V=await y.modelPicker({title:"Update XENO Approvals",description:"Choose how XENO asks for permission",currentValue:L,options:[{value:"readOnly",label:"Read Only",detail:"XENO can read files in this workspace. XENO asks before edits or commands."},{value:"default",label:"Default",detail:"XENO can read and edit files in this workspace. XENO asks before running commands."},{value:"fullAccess",label:"Full Access",detail:"XENO can read, edit, and run commands with no per-action prompts. Use only in trusted workspaces."}]});if(!V||!Dg(V)||V===L){de("/approvals",`Kept approvals as ${jn(L)}`);return}let ke=Mi(V);t.permissionMode=ke,le.setMode(ke),(0,B.saveConfig)({permissionMode:ke}),y.setPermissionMode(ke),de("/approvals",`Set approvals to ${jn(V)}`);return}let k=zc(S);if(!k){y.writeInfo(_.red("Usage: /approvals <read-only|default|full-access>"));return}let A=Mi(k);if(A===t.permissionMode){de(h,`Kept approvals as ${jn(k)}`);return}t.permissionMode=A,le.setMode(A),(0,B.saveConfig)({permissionMode:A}),y.setPermissionMode(A),de(h,`Set approvals to ${jn(k)}`);return}if(h==="/color"||h.startsWith("/color ")){let S=h.slice(6).trim();if(!S){let A=Po(),L=await y.modelPicker({title:"Select color",description:"Switch UI color",currentValue:A,options:Dt.map(V=>({value:V,label:V,detail:V==="blue"?"(default)":void 0}))});if(!L||!Xn(L)||L===A){de("/color",`Kept UI color as ${A}`);return}En(L),(0,B.saveConfig)({uiColor:L}),y.refreshTheme(),de("/color",`Switched UI color to ${L}`);return}let k=Nc(S);if(!k){y.writeInfo(_.red(`Usage: /color <${Dt.join("|")}>`));return}En(k),(0,B.saveConfig)({uiColor:k}),y.refreshTheme(),de(h,`Switched UI color to ${k}`);return}if(!await ie())return;await qt(h),y.busy=!0;try{xe=!1,Ae=!0,Te.reset();let S=N.tokenUsage;if(T.enabled)y.startSpinner("Delegating..."),await Tn(h);else{if(y.startSpinner("Thinking..."),await N.run(h),n){let L=N.tokenUsage,V=Math.max(0,L.input-S.input),ke=Math.max(0,L.output-S.output);await n.updateMessageCount(N.messages.length),(V>0||ke>0)&&await n.recordTokenUsage(V,ke)}Te.flush()}if(m)try{await m.checkInterval(N.messages)&&y.showTransientActivityNotice("Auto-checkpoint created")}catch(L){console.error("[AutoCheckpoint] Failed to create interval checkpoint:",L)}y.stopSpinner();let k=Q(),A=(0,pt.formatCost)((0,pt.calculateCost)(t.model,k.input,k.output));y.updateTokens(k.total,A)}catch(S){if(y.stopSpinner(),S instanceof R.AgentInterruptedError||xe)Te.flush(),y.hasQueuedMessage||(y.armInterruptRewind(void 0,{openIfRequested:!0}),y.writeOutput(`
|
|
993
|
+
${_.dim("Interrupted \u2014 what should Xeno do instead?")}
|
|
994
|
+
`),y.showTransientActivityNotice("Press Esc twice to rewind conversation"));else{let k=S instanceof Error?S.message:String(S);y.writeOutput(xt(_c(k)))}}finally{ft()}y.busy=!1,Hg(N.messages).then(S=>{y.setPromptSuggestion(S)}).catch(()=>{});let O=y.takeQueuedMessage();O&&setTimeout(()=>{y.setInputText(O,{cursor:"end",escCancelable:!1}),y.handleEnter()},50)},onInterrupt:()=>{!y.busy||xe||(xe=!0,y.stopSpinner(),oe?.cancelCurrentTurn(),N.cancelCurrentTurn())},onBackgroundRequest:async()=>{if(!y.busy)return;let{requestBackground:h}=await import("@xeno-corporation/xeno-agent-sdk");h(),y.showTransientActivityNotice("Moving command to background...")}});let ue=await Xc({cwd:e,enabled:t.mcpEnabled,toolRegistry:X,onServerStateChanged:h=>{y.showTransientActivityNotice(h)},promptForApproval:async h=>(y.stopSpinner(),await y.actionPicker({title:"Approve MCP server",description:`${h.name} (${h.scope}) from ${h.sourcePath}`,options:[{value:"approve",label:"Approve",detail:"(save approval for this workspace)"},{value:"deny",label:"Deny",detail:"(skip this server)"}],selectedIndex:0})==="approve"?"approved":"denied")});u=ue.mcpManager,p=ue.refreshMcpTools;let _e=ue.summary;N=(await(0,R.createXenoAgent)({cwd:e,apiKey:t.apiKey,baseURL:t.baseURL,model:t.model,maxTokens:t.maxTokens,maxIterations:t.maxIterations,systemPrompt:ae,requesterLabel:"Agent",executionMode:E,permissionEngine:le,toolRegistry:X,session:{transcript:n?.transcript,checkpoints:s,sessionManager:n,historyMarkdownPath:c,auditLogger:i},onModeSwitchRequest:async h=>{y.stopSpinner();let O=h.requestedTools.length>0?h.requestedTools.join(", "):"tool access";return await y.modelPicker({title:"Switch to agent mode?",description:`Requested: ${O}`,currentValue:"switch",options:[{value:"switch",label:"Switch to agent",detail:"(allow tools for this and future turns)"},{value:"stay",label:"Stay in Chat",detail:"(continue without running tools)"}]})==="switch"?(await pe("agent"),!0):!1},onExecutionModeChanged:h=>{E=h,t.executionMode=h,y.setExecutionMode(h)},onText:h=>{y.stopSpinner(),Ae&&(Ae=!1,y.trimTrailingOutputNewlines(1),y.writeOutput(`
|
|
995
|
+
${_.accent("\u25A0")} `,{forceNewBlock:!0,selectable:!0,blockKind:"assistant"}),Te.markLineStarted()),Te.write(h)},onToolStart:(h,O)=>{y.stopSpinner(),Te.flush(),y.trimTrailingOutputNewlines(1),m&&m.checkBeforeDangerous(h,O,N.messages).catch(k=>console.error("[AutoCheckpoint] Failed to create pre-dangerous checkpoint:",k));let S=qr(h,O);Ne.set(h,O),y.writeOutput(`
|
|
996
|
+
`+_s(h,S)+`
|
|
997
|
+
`,{forceNewBlock:!0,selectable:!0,blockKind:"tool-call"}),y.startSpinner(`Running ${h}...`)},onToolWillExecute:async(h,O)=>{await $t(h,O)},onToolEnd:(h,O)=>{y.stopSpinner(),y.trimTrailingOutputNewlines(1);let S=Q(),k=(0,pt.formatCost)((0,pt.calculateCost)(t.model,S.input,S.output));y.updateTokens(S.total,k);let A=O.success?O.output:O.error||O.output;Cc(y,h,O.success,A,Ne.get(h),!0,Xe),Ae=!0,h==="Bash"&&import("@xeno-corporation/xeno-agent-sdk").then(({backgroundProcessManager:L})=>{let V=L.list().filter(ke=>ke.status==="running").length;y.setBackgroundTaskCount(V)}).catch(()=>{})},onIteration:h=>{h>1&&(Ae=!0,y.startSpinner(`Thinking (iteration ${h})...`))}})).agent;{let h=N;h.config&&(h.config.onContextCompressed=(O,S)=>{let k=S>=1e3?`${(S/1e3).toFixed(1)}K`:String(S);y.showTransientActivityNotice(`Context compressed: ${O} messages removed, ${k} tokens saved`)})}y.writeOutput(Cn(Ze,t.model)),Tc(e,h=>y.writeOutput(h)),_e&&y.writeInfo(_e);{let{backgroundProcessManager:h}=await import("@xeno-corporation/xeno-agent-sdk");h.onTaskComplete(O=>{let S=O.status==="completed"?"completed":`failed (exit ${O.exitCode})`;y.showTransientActivityNotice(`Background task ${O.id} ${S}`);let k=h.list().filter(A=>A.status==="running").length;y.setBackgroundTaskCount(k)})}a&&a.length>0&&(N.messages=a,n&&await n.updateMessageCount(a.length),Ti(y,a,Xe)),setInterval(()=>{},3600*1e3),await new Promise(()=>{})}async function Sc(t){let e=process.cwd();await qg(t);let n=new Ps,s=new In(D=>process.stdout.write(D)," "),r=jg();process.stderr.write("\x1B[2J\x1B[3J\x1B[H"),process.stderr.write(Cn(Ze,t.model)),Tc(e,D=>process.stderr.write(D));let o,i,a,l,c,u,p,f,m,g=()=>{};try{let D=await(0,R.initializeSessionRuntime)({cwd:e,role:t.role,model:t.model,resume:t.resume,checkpoint:t.checkpoint,projectSessionContext:Vr(t),loadRestorableMessages:Un});o=D.sessionManager,i=D.checkpointManager,a=D.memoryManager,l=D.identityResolver,c=D.auditLogger,u=D.restoredMessages,p=D.sessionDir,f=D.sessionHistoryPath}catch(D){let H=D instanceof Error?D.message:String(D);process.stderr.write(_.red(`\u2717 Error resuming session: ${H}
|
|
998
|
+
`)),process.exit(1)}o&&(i=i??o.checkpoints);let b;i&&(b=new ln.AutoCheckpointHandler(i));let v=!1,w=async()=>{if(!v){v=!0;try{m?.dispose(),await(0,R.cleanupSessionRuntime)({sessionManager:o,auditLogger:c})}catch(D){console.error("Warning: Session cleanup error:",D)}}},P=0,C=1500;process.on("beforeExit",w),process.on("SIGINT",async()=>{let D=Date.now();if(D-P>C){P=D,process.stderr.write(_.dim(`
|
|
999
|
+
Press Ctrl+C again to exit.
|
|
1000
|
+
`));return}await w(),process.exit(130)}),process.on("SIGTERM",async()=>{await w(),process.exit(143)}),process.platform==="win32"&&process.on("SIGBREAK",async()=>{await w(),process.exit(0)});let $=l?await l.resolve({role:t.role}):void 0,E=await(0,R.buildPromptMemoryContext)(a,o?.meta.id),T=t.executionMode??"agent";t.executionMode=T;let I={enabled:!!t.delegationEnabled,maxTotalTokens:t.delegationMaxTotalTokens??Math.max(t.maxTokens*3,1200),timeoutMs:t.delegationTimeoutMs??12e4,teamPreset:t.delegationTeamPreset??R.DEFAULT_SUBAGENT_TEAM_PRESET,mode:t.delegationMode??R.DEFAULT_SUBAGENT_BRANCH_POLICY.mode,roles:t.delegationRoles?.length?[...t.delegationRoles]:void 0,rolePrecedence:t.delegationRolePrecedence?.length?[...t.delegationRolePrecedence]:void 0,maxConcurrentBranches:t.delegationMaxConcurrentBranches,remoteMcpByRole:t.delegationRemoteMcpByRole?{...t.delegationRemoteMcpByRole}:void 0},re=new Date().toISOString().split("T")[0],ae=async()=>(0,Rn.buildSystemPrompt)({cwd:e,model:t.model,date:re,identity:$,memory:E.merged,executionMode:T}),N=await ae(),y=Date.now(),oe=(0,R.createAuditBackedPermissionEngine)({mode:t.permissionMode,cwd:e,auditLogger:c,fallbackTraceId:`session-${o?.meta.id??"unknown"}`}),W=(0,R.createDefaultToolRegistry)({cwd:e,askUser:r,dispatchAgent:async({prompt:D})=>({output:await(await(0,R.createDelegatedXenoAgent)({cwd:e,apiKey:t.apiKey,baseURL:t.baseURL,model:t.model,maxTokens:Math.max(512,Math.min(t.maxTokens,4096)),maxIterations:Math.max(3,Math.min(t.maxIterations,12)),parentSystemPrompt:N,parentExecutionMode:T,subagentRole:"explorer",permissionEngine:oe})).agent.run(D)}),memoryManager:a}),Z=await Xc({cwd:e,enabled:t.mcpEnabled,toolRegistry:W});m=Z.mcpManager,g=Z.refreshMcpTools;let le=Z.summary;le&&process.stderr.write(`${_.dim(le)}
|
|
1001
|
+
`);let ce=!1,X={input:0,output:0,total:0},q=()=>{let D=ee.tokenUsage;return{input:D.input+X.input,output:D.output+X.output,total:D.total+X.total}},Q=()=>{let D=q(),H=(0,pt.calculateCost)(t.model,D.input,D.output),M=o?Date.parse(o.meta.createdAt):y,U=Math.max(0,Date.now()-(Number.isFinite(M)?M:y));return mr(D.input,D.output)+_.dim(` | cost: ${(0,pt.formatCost)(H)} | duration: ${Rr(U)}`)},ye=new Map,ee=(await(0,R.createXenoAgent)({cwd:e,apiKey:t.apiKey,baseURL:t.baseURL,model:t.model,maxTokens:t.maxTokens,maxIterations:t.maxIterations,systemPrompt:N,requesterLabel:"Agent",executionMode:T,permissionEngine:oe,toolRegistry:W,session:{transcript:o?.transcript,checkpoints:i,sessionManager:o,historyMarkdownPath:f,auditLogger:c},onModeSwitchRequest:async D=>{let H=D.requestedTools.length>0?D.requestedTools.join(", "):"tool access";return process.stderr.write(`
|
|
1002
|
+
${_.dim("Tool access requested in Chat mode:")} ${H}
|
|
1003
|
+
${_.dim("Run /mode agent if you want to enable tools, then retry your request.")}
|
|
1004
|
+
`),!1},onExecutionModeChanged:D=>{T=D,t.executionMode=D},onText:D=>{n.stop(),ce&&(ce=!1,process.stderr.write(`
|
|
1005
|
+
${_.accent("\u25A0")} `),s.markLineStarted()),s.write(D)},onToolStart:(D,H)=>{n.stop(),s.flush(),b&&b.checkBeforeDangerous(D,H,ee.messages).catch(U=>console.error("[AutoCheckpoint] Failed to create pre-dangerous checkpoint:",U)),ye.set(D,H);let M=qr(D,H);process.stderr.write(`
|
|
1006
|
+
`+_s(D,M)+`
|
|
1007
|
+
`),n.start(`Running ${D}...`)},onToolEnd:(D,H)=>{n.stop();let M=H.success?H.output:H.error||H.output;process.stderr.write(pr(D,H.success,M,ye.get(D))+`
|
|
1008
|
+
`),ce=!0},onIteration:D=>{D>1&&(ce=!0,n.start(`Thinking (iteration ${D})...`))}})).agent,Se=async D=>{T!==D&&(T=D,t.executionMode=D,ee.executionMode=D,ee.systemPrompt=await ae())},me=D=>{t.permissionMode!==D&&(t.permissionMode=D,oe.setMode(D))},de=()=>$c(T,t.permissionMode),Ee=async D=>{D==="chat"?(await Se("chatOnly"),me("default")):D==="agent"?(await Se("agent"),me("acceptEdits")):(await Se("agent"),me("bypassPermissions"))},pe=()=>{let D=I.rolePrecedence?.join(", ")??R.DEFAULT_SUBAGENT_ROLE_PRECEDENCE.join(" > ");return`Delegation: ${I.enabled?"On":"Off"} \uFFFD budget ${I.maxTotalTokens} \uFFFD timeout ${I.timeoutMs}ms \uFFFD precedence ${D}`},te=async D=>{let H=`session-${o?.meta.id??"unknown"}-${Date.now().toString(36)}`,M=Oi(I),U=Date.now(),G=await(0,R.runDelegatedXenoTurn)({userPrompt:D,cwd:e,apiKey:t.apiKey,baseURL:t.baseURL,model:t.model,maxIterations:t.maxIterations,maxTotalTokens:I.maxTotalTokens,timeoutMs:I.timeoutMs,rolePrecedence:I.rolePrecedence,branchPolicy:qc(I),parentSystemPrompt:ee.systemPrompt,parentExecutionMode:T,auditLogger:c,rootTraceId:H,skipAuditCompletion:!0,onBranchStart:async Pt=>{n.start(`Delegating (${Pt.role})...`)},createBranchAgent:async({task:Pt})=>(await(0,R.createDelegatedXenoAgent)({cwd:e,apiKey:t.apiKey,baseURL:t.baseURL,model:t.model,maxTokens:Pt.maxTokens,maxIterations:Pt.maxIterations,parentSystemPrompt:ee.systemPrompt,parentExecutionMode:T,subagentRole:Pt.role,permissionEngine:oe,toolRegistry:Wc(e,Pt.role,M,r,m),...c?{session:{auditLogger:c}}:{}})).agent}),fe=Ec(G.workflow,G.tokenUsage.total,Date.now()-U),ze=G.answer,Vt=G.selectedTraceId;X.input+=G.tokenUsage.input,X.output+=G.tokenUsage.output,X.total+=G.tokenUsage.total;let ut=[...ee.messages,{role:"user",content:D},{role:"assistant",content:ze}];ee.messages=ut,o&&(await o.recordUserMessage(D),await o.recordAssistantMessage(ze),await o.recordTokenUsage(G.tokenUsage.input,G.tokenUsage.output),await o.recordDelegationSummary(fe)),await c?.append({trace_id:Vt??H,event_type:"delegation_completed",actor:"system",risk_level:"none",status:"ok",metadata:{selected_from:G.workflow.reduced.selectedFrom,subagents:G.summary,branch_policy:{mode:M.mode,roles:M.roles,max_concurrent_branches:M.maxConcurrentBranches},delegation_summary:fe}}),process.stderr.write(`
|
|
1009
|
+
${_.accent("\u25A0")} `),s.reset(),s.markLineStarted(),s.write(ze),s.flush(),process.stderr.write(`
|
|
1010
|
+
`)},Re=async()=>{E=await(0,R.buildPromptMemoryContext)(a,o?.meta.id),ee.systemPrompt=await ae()},Ce=async()=>{if(o)return!0;try{let D=await(0,R.activateSessionRuntime)({sessionManager:o,checkpointManager:i,memoryManager:a,identityResolver:l,auditLogger:c,restoredMessages:u,sessionDir:p,sessionHistoryPath:f},{cwd:e,role:t.role,model:t.model,projectSessionContext:Vr(t)});o=D.sessionManager,i=D.checkpointManager,a=D.memoryManager,l=D.identityResolver,c=D.auditLogger,u=D.restoredMessages,p=D.sessionDir,f=D.sessionHistoryPath,b=i?new ln.AutoCheckpointHandler(i):void 0;let H=D.sessionManager;if(!H)throw new Error("Session activation succeeded without a session manager");return ee.attachSessionIntegration({transcript:H.transcript,checkpoints:i,sessionManager:H,historyMarkdownPath:f,auditLogger:c}),await Re(),!0}catch(D){let H=D instanceof Error?D.message:String(D);return process.stderr.write(`
|
|
1011
|
+
${_.red(`? Error creating session: ${H}`)}
|
|
1012
|
+
`),!1}};u&&u.length>0&&(ee.messages=u,o&&await o.updateMessageCount(u.length),process.stderr.write(`
|
|
1013
|
+
${Pi(u)}
|
|
1014
|
+
`));let Ae=D=>{let H=["/help","/clear","/exit","/quit","/login","/logout","/open","/tokens","/cost","/model","/approvals","/approved-tools","/color","/mode","/delegate","/sessions","/resume","/save","/export","/memory","/remember","/checkpoint","/audit","/mcp","/doctor","/bug-report","/config","/ctx-viz","/onboarding","/release-notes","/terminal-setup","/listen","/pr-comments"];if(D.startsWith("/")){let M=H.filter(U=>U.startsWith(D));return[M.length?M:H,D]}return[[],D]},xe=Pc({input:process.stdin,output:process.stderr,completer:Ae}),Te=!1,Ne=!1,Xe=!1,He=async()=>{Xe||(Xe=!0,n.stop(),await w(),process.stderr.write(Gn()),process.exitCode=0,process.stdin.pause())};xe.on("close",()=>{Te=!0,Ne||He()});let{inputPrompt:rt}=await Promise.resolve().then(()=>(It(),qa)),Y=()=>{if(Te){He();return}xe.question(rt(),async D=>{Ne=!0;try{let H=D.trim();if(!H){Y();return}if(xi(H)){let M=await Si(H,{cwd:e,sessionDir:o?Ie.SessionRegistry.getSessionDir(o.meta.id):void 0,memoryManager:a,checkpointManager:i,auditLogger:c,mcpManager:m,refreshMcpTools:g,messages:ee.messages,onOutput:U=>process.stderr.write(U),onHelp:()=>{process.stderr.write(fr())},onPanel:U=>{process.stderr.write(`
|
|
1015
|
+
${_.bold(U.title)}${U.subtitle?` \uFFFD ${U.subtitle}`:""}
|
|
1016
|
+
`);for(let G of U.lines)process.stderr.write(` ${G}
|
|
1017
|
+
`);U.footerHint&&process.stderr.write(` ${U.footerHint}
|
|
1018
|
+
`)},buildSystemPrompt:ae,toolDefinitions:()=>W.getDefinitions(),maxContextTokens:Ci});if(M.handled){M.messages&&(ee.messages=M.messages),Y();return}}if(H==="/login"||H.startsWith("/login ")){let M=H.slice(6).trim().split(/\s+/).filter(Boolean),U=M[0]?.toLowerCase();if(!U){process.stderr.write("Run `xeno login` to sign in.\n"),Y();return}if(U==="help"){process.stderr.write("\nXeno auth\nRun `xeno login` to launch the sign-in welcome screen.\nUse `/login status` to inspect local auth.\nUse `/login api-key <key>` to switch this chat to a model API key immediately.\n"),Y();return}if(U==="status"){let G=await Tt({validate:!0});process.stderr.write(`
|
|
1019
|
+
${an(G)}
|
|
1020
|
+
`),Y();return}if(U==="api-key"){let G=M.slice(1).join(" ").trim();if(!G){process.stderr.write(xt("Usage: /login api-key <key>")),Y();return}let fe=await bn({apiKey:G,apiBaseURL:t.baseURL});if(!fe.valid){process.stderr.write(xt(`API key validation failed: ${fe.error??"unknown error"}`)),Y();return}bt({apiKey:G,apiBaseURL:t.baseURL,source:"api-key"}),t.apiKey=G,Vs(ee,G),process.stderr.write(`
|
|
1021
|
+
${_.dim("Stored API key and switched this chat session to it.")}
|
|
1022
|
+
`),Y();return}process.stderr.write(xt("Usage: /login [status|api-key <key>]")),Y();return}if(H==="/logout"||H.startsWith("/logout ")){Zn(),es(),Qn(),(0,B.saveConfig)({apiKey:void 0}),t.apiKey=void 0,Vs(ee,void 0),process.stdout.write("Signed out. Run `xeno` to sign in again.\n"),xe.close();return}if(H==="/open"||H.startsWith("/open ")){let M=H.slice(5).trim(),U=M?Vn(e,M):e,G=process.platform==="win32"?"Explorer":process.platform==="darwin"?"Finder":"file manager";process.stderr.write(`
|
|
1023
|
+
Opening ${U} in ${G}...
|
|
1024
|
+
`);try{let fe=await Rc(U);process.stderr.write(`${_.dim(`Opening ${U} in ${fe}`)}
|
|
1025
|
+
`)}catch(fe){process.stderr.write(xt(`Failed to open folder: ${fe instanceof Error?fe.message:String(fe)}`))}Y();return}if(H==="/exit"||H==="/quit"){xe.close();return}if(H==="/clear"){ee.clearHistory(),process.stderr.write("\x1B[2J\x1B[3J\x1B[H"),process.stderr.write(Cn(Ze,t.model)),process.stderr.write(_.dim(` Chat history cleared.
|
|
1026
|
+
`)),Y();return}if(H==="/tokens"||H==="/cost"){process.stderr.write(`
|
|
1027
|
+
`+Q()+`
|
|
1028
|
+
`),Y();return}if(H==="/help"){process.stderr.write(fr()),Y();return}if(H==="/export"||H.startsWith("/export ")){let M=H.slice(8).trim(),U=ee.messages;if(M==="json"){let G=JSON.stringify(U,null,2);process.stderr.write(`
|
|
1029
|
+
`+G+`
|
|
1030
|
+
`)}else if(M&&M!=="md"){let G=await import("fs"),fe=ls(U,t.model);G.writeFileSync(M,fe,"utf-8"),process.stderr.write(`
|
|
1031
|
+
${_.dim("Exported to:")} ${M}
|
|
1032
|
+
`)}else{let G=ls(U,t.model);process.stderr.write(`
|
|
1033
|
+
`+G+`
|
|
1034
|
+
`)}Y();return}if(H==="/save"){let M=q(),U=(0,Mn.saveSession)(null,ee.messages,t.model,M.total);process.stderr.write(`
|
|
1035
|
+
${_.dim("Session saved:")} ${U}
|
|
1036
|
+
`),Y();return}if(H==="/sessions purge"){try{let M=o&&o.meta.workingDirectory===e?o.meta.id:void 0,U=await Ie.SessionRegistry.list({workingDirectory:e}),G=U.filter(ut=>ut.id!==M).length;if(U.length===0){process.stderr.write(`
|
|
1037
|
+
${_.dim(`No sessions found for ${e}`)}
|
|
1038
|
+
`),Y();return}if(G===0){process.stderr.write(`
|
|
1039
|
+
${_.dim(`No purgeable sessions found for ${e}. Active session is still open.`)}
|
|
1040
|
+
`),Y();return}let fe=await Ie.SessionRegistry.purgeWorkingDirectory(e,{excludeSessionIds:M?[M]:void 0}),ze=`Purged ${fe.deletedIds.length} session${fe.deletedIds.length===1?"":"s"} for ${e}`,Vt=fe.skippedIds.length>0?`${ze}. Skipped active session: ${fe.skippedIds[0]}.`:ze;process.stderr.write(`
|
|
1041
|
+
${_.dim(Vt)}
|
|
1042
|
+
`)}catch(M){let U=M instanceof Error?M.message:String(M);process.stderr.write(`
|
|
1043
|
+
${_.red("Failed to purge sessions:")} ${U}
|
|
1044
|
+
`)}Y();return}if(H==="/sessions"){let M=await Ie.SessionRegistry.list({role:t.role,workingDirectory:e,limit:12});if(M.length===0){process.stderr.write(`
|
|
1045
|
+
${_.dim("No sessions found")}
|
|
1046
|
+
`),Y();return}process.stderr.write(`
|
|
1047
|
+
${_.dim("Recent sessions:")}
|
|
1048
|
+
`);for(let U of M){let G=new Date(U.lastActivity).toLocaleString();process.stderr.write(` ${U.id} | ${U.model} | ${U.messageCount} msgs | ${G}
|
|
1049
|
+
`)}process.stderr.write(_.dim(`
|
|
1050
|
+
Use /resume <session-id> to load one.
|
|
1051
|
+
`)),Y();return}if(H==="/resume"){let M=await Ie.SessionRegistry.findMostRecent({role:t.role,workingDirectory:e});if(!M){process.stderr.write(`
|
|
1052
|
+
${_.dim("No sessions found")}
|
|
1053
|
+
`),Y();return}let U=await Un(M.id);if(U.length===0){process.stderr.write(`
|
|
1054
|
+
${_.red("Session has no restorable messages:")} ${M.id}
|
|
1055
|
+
`),Y();return}ee.messages=U,o&&await o.updateMessageCount(U.length),M.model&&M.model!==t.model&&(t.model=M.model,ee.model=M.model,ee.systemPrompt=await ae()),process.stderr.write(`
|
|
1056
|
+
${Pi(U)}
|
|
1057
|
+
`),Y();return}if(H.startsWith("/resume ")){let M=H.slice(8).trim();if(!M){process.stderr.write(`
|
|
1058
|
+
${_.red("Usage: /resume <session-id>")}
|
|
1059
|
+
`),Y();return}let U=await Ie.SessionRegistry.find(M);if(!U){process.stderr.write(`
|
|
1060
|
+
${_.red("Session not found:")} ${M}
|
|
1061
|
+
`),Y();return}let G=await Un(M);if(G.length===0){process.stderr.write(`
|
|
1062
|
+
${_.red("Session has no restorable messages:")} ${M}
|
|
1063
|
+
`),Y();return}ee.messages=G,o&&await o.updateMessageCount(G.length),U.model&&U.model!==t.model&&(t.model=U.model,ee.model=U.model,ee.systemPrompt=await ae()),process.stderr.write(`
|
|
1064
|
+
${Pi(G)}
|
|
1065
|
+
`),Y();return}if(H==="/model"||H.startsWith("/model ")){let M=H.slice(7).trim();if(!M||M==="--all"){process.stderr.write(`
|
|
1066
|
+
${_.dim("Current model:")} ${t.model}
|
|
1067
|
+
`);let U=M==="--all",G=await(0,we.formatModelList)(t.apiKey,U);process.stderr.write(`${_.dim("Available models:")}
|
|
1068
|
+
${G}
|
|
1069
|
+
`)}else{let U=await Ii(M);if(!U.ok){process.stderr.write(`
|
|
1070
|
+
${_.red("\u2717 "+U.error)}
|
|
1071
|
+
`),Y();return}t.model=M,ee.model=M,ee.systemPrompt=await ae(),process.stderr.write(`
|
|
1072
|
+
${_.dim("Switched to model:")} ${M}
|
|
1073
|
+
`),U.warning&&process.stderr.write(`${_.dim(U.warning)}
|
|
1074
|
+
`)}Y();return}if(H==="/mode"||H.startsWith("/mode ")){let M=H.slice(6).trim();if(!M){process.stderr.write(`
|
|
1075
|
+
${_.dim("Current mode:")} ${cs(de())}
|
|
1076
|
+
`),process.stderr.write(`${_.dim("Available:")} chat, agent, full-access
|
|
1077
|
+
`),Y();return}let U=Lc(M);if(!U){process.stderr.write(`
|
|
1078
|
+
${_.red("Usage: /mode <chat|agent|full-access>")}
|
|
1079
|
+
`),Y();return}let G=de();if(U===G){process.stderr.write(`
|
|
1080
|
+
${_.dim("Mode already set:")} ${cs(G)}
|
|
1081
|
+
`),Y();return}await Ee(U),(0,B.saveConfig)({executionMode:T,permissionMode:t.permissionMode}),Y();return}if(H==="/delegate"||H.startsWith("/delegate ")){let M=H.slice(9).trim();if(!M){process.stderr.write(`
|
|
1082
|
+
${_.dim(Je(I))}
|
|
1083
|
+
`),process.stderr.write(`${_.dim("Usage:")} /delegate [on|off|status|team <balanced|explore|build|review|default>|mode <staged|parallel>|roles <csv|default>|concurrency <n|auto>|precedence <csv|default>|remote <policy|role=policy,...|default>]
|
|
1084
|
+
`),Y();return}let U=Bc(M);if(U==="status"){process.stderr.write(`
|
|
1085
|
+
${_.dim(Je(I))}
|
|
1086
|
+
`),Y();return}if(U==="on"||U==="off"){I={...I,enabled:U==="on"},process.stderr.write(`
|
|
1087
|
+
${_.dim(Je(I))}
|
|
1088
|
+
`),Y();return}if(M.toLowerCase().startsWith("precedence ")){let G=M.slice(11).trim();if(G.toLowerCase()==="default"){I={...I,rolePrecedence:void 0},process.stderr.write(`
|
|
1089
|
+
${_.dim(Je(I))}
|
|
1090
|
+
`),Y();return}let fe=G.split(",").map(ze=>ze.trim()).filter(ze=>ze.length>0);if(fe.length===0){process.stderr.write(`
|
|
1091
|
+
${_.red("Usage: /delegate precedence <role1,role2,role3>")}
|
|
1092
|
+
`),Y();return}I={...I,rolePrecedence:fe},process.stderr.write(`
|
|
1093
|
+
${_.dim(Je(I))}
|
|
1094
|
+
`),Y();return}if(M.toLowerCase().startsWith("mode ")){let G=M.slice(5).trim(),fe=Dc(G);if(!fe){process.stderr.write(`
|
|
1095
|
+
${_.red("Usage: /delegate mode <staged|parallel>")}
|
|
1096
|
+
`),Y();return}I={...I,mode:fe},process.stderr.write(`
|
|
1097
|
+
${_.dim(Je(I))}
|
|
1098
|
+
`),Y();return}if(M.toLowerCase().startsWith("team ")){let G=M.slice(5).trim();if(G.toLowerCase()==="default"||G.toLowerCase()==="balanced"){I={...I,teamPreset:R.DEFAULT_SUBAGENT_TEAM_PRESET},process.stderr.write(`
|
|
1099
|
+
${_.dim(Je(I))}
|
|
1100
|
+
`),Y();return}let fe=Uc(G);if(!fe){process.stderr.write(`
|
|
1101
|
+
${_.red("Usage: /delegate team <balanced|explore|build|review|default>")}
|
|
1102
|
+
`),Y();return}I={...I,teamPreset:fe},process.stderr.write(`
|
|
1103
|
+
${_.dim(Je(I))}
|
|
1104
|
+
`),Y();return}if(M.toLowerCase().startsWith("roles ")){let G=M.slice(6).trim();if(G.toLowerCase()==="default"||G.toLowerCase()==="all"){I={...I,roles:void 0},process.stderr.write(`
|
|
1105
|
+
${_.dim(Je(I))}
|
|
1106
|
+
`),Y();return}let fe=Fc(G);if(!fe){process.stderr.write(`
|
|
1107
|
+
${_.red("Usage: /delegate roles <planner,explorer,executor,reviewer|default>")}
|
|
1108
|
+
`),Y();return}I={...I,teamPreset:void 0,roles:fe},process.stderr.write(`
|
|
1109
|
+
${_.dim(Je(I))}
|
|
1110
|
+
`),Y();return}if(M.toLowerCase().startsWith("concurrency ")){let G=M.slice(12).trim(),fe=jc(G);if(fe===null){process.stderr.write(`
|
|
1111
|
+
${_.red("Usage: /delegate concurrency <n|auto>")}
|
|
1112
|
+
`),Y();return}I={...I,maxConcurrentBranches:fe},process.stderr.write(`
|
|
1113
|
+
${_.dim(Je(I))}
|
|
1114
|
+
`),Y();return}if(M.toLowerCase().startsWith("remote ")){let G=M.slice(7).trim(),fe=Vc(G);if(fe===null){process.stderr.write(`
|
|
1115
|
+
${_.red("Usage: /delegate remote <none|prompts|resources|context|all|role=policy,...|default>")}
|
|
1116
|
+
`),Y();return}I={...I,remoteMcpByRole:fe},process.stderr.write(`
|
|
1117
|
+
${_.dim(Je(I))}
|
|
1118
|
+
`),Y();return}process.stderr.write(`
|
|
1119
|
+
${_.red("Usage: /delegate [on|off|status|team <balanced|explore|build|review|default>|mode <staged|parallel>|roles <csv|default>|concurrency <n|auto>|precedence <csv|default>|remote <policy|role=policy,...|default>]")}
|
|
1120
|
+
`),Y();return}if(H==="/approvals"||H.startsWith("/approvals ")){let M=H.slice(10).trim();if(!M){let fe=Hc(t.permissionMode);process.stderr.write(`
|
|
1121
|
+
${_.dim("Current approvals:")} ${jn(fe)}
|
|
1122
|
+
`),process.stderr.write(`${_.dim("Available:")} read-only, default, full-access
|
|
1123
|
+
${_.dim("Use:")} /approvals <read-only|default|full-access>
|
|
1124
|
+
`),Y();return}let U=zc(M);if(!U){process.stderr.write(`
|
|
1125
|
+
${_.red("Usage: /approvals <read-only|default|full-access>")}
|
|
1126
|
+
`),Y();return}let G=Mi(U);if(G===t.permissionMode){process.stderr.write(`
|
|
1127
|
+
${_.dim("Approvals already set:")} ${jn(U)}
|
|
1128
|
+
`),Y();return}t.permissionMode=G,oe.setMode(G),(0,B.saveConfig)({permissionMode:G}),process.stderr.write(`
|
|
1129
|
+
${_.dim("Approvals:")} ${jn(U)}
|
|
1130
|
+
`),Y();return}if(H==="/color"||H.startsWith("/color ")){let M=H.slice(6).trim();if(!M){process.stderr.write(`
|
|
1131
|
+
${_.dim("Current color:")} ${Po()}
|
|
1132
|
+
`),process.stderr.write(`${_.dim("Available:")} ${Dt.join(", ")}
|
|
1133
|
+
`),Y();return}let U=Nc(M);if(!U){process.stderr.write(`
|
|
1134
|
+
${_.red(`Usage: /color <${Dt.join("|")}>`)}
|
|
1135
|
+
`),Y();return}En(U),(0,B.saveConfig)({uiColor:U}),process.stderr.write(`
|
|
1136
|
+
${_.dim("Switched UI color:")} ${U}
|
|
1137
|
+
`),Y();return}try{if(!await Ce()){Y();return}ce=!0,s.reset();let M=ee.tokenUsage;if(I.enabled)n.start("Delegating..."),await te(H);else{if(n.start("Thinking..."),await ee.run(H),o){let U=ee.tokenUsage,G=Math.max(0,U.input-M.input),fe=Math.max(0,U.output-M.output);await o.updateMessageCount(ee.messages.length),(G>0||fe>0)&&await o.recordTokenUsage(G,fe)}s.flush(),process.stderr.write(`
|
|
1138
|
+
`)}if(b)try{await b.checkInterval(ee.messages)&&process.stderr.write(_.dim(` ? Auto-checkpoint created
|
|
1139
|
+
`))}catch(U){console.error("[AutoCheckpoint] Failed to create interval checkpoint:",U)}n.stop()}catch(M){if(n.stop(),M instanceof R.AgentInterruptedError)process.stderr.write(` ${_.dim("? Interrupted \uFFFD What should Xeno do instead?")}
|
|
1140
|
+
`);else{let U=M instanceof Error?M.message:String(M);process.stderr.write(xt(_c(U)))}}Y()}finally{Ne=!1,Te&&He()}})};Y()}function qr(t,e){let n=s=>{let r=typeof s=="string"?s:"";if(!r)return"";let o=xc(process.cwd(),r);return!o||o.startsWith("..")?qs(r):o.replace(/\\/g,"/")};switch(t){case"Read":return n(e.file_path);case"Write":return n(e.file_path);case"Edit":return n(e.file_path);case"Bash":return String(e.command??"").slice(0,60);case"Glob":return String(e.pattern??"").replace(/\\/g,"/");case"Grep":return`/${e.pattern}/`;case"WebSearch":return String(e.query??"").slice(0,80);case"WebFetch":return String(e.url??"").slice(0,100);default:return""}}async function Hg(t){if(t.length<2)return null;let e=[...t].reverse().find(r=>r.role==="assistant");if(!e)return null;let n=typeof e.content=="string"?e.content:Array.isArray(e.content)?e.content.filter(r=>"type"in r&&r.type==="text").map(r=>r.text).join(" "):"";if(!n)return null;let s=n.toLowerCase();return s.includes("error")||s.includes("failed")||s.includes("fix")?"Can you fix that?":s.includes("test")&&(s.includes("pass")||s.includes("success"))?"Run the tests again":s.includes("created")||s.includes("wrote")?"Show me what you created":s.includes("commit")||s.includes("changes")?"Commit these changes":s.includes("installed")||s.includes("dependencies")?"What else needs to be configured?":null}function Yc(t){let e=new Map,n=new Map,s=0,r=0;for(let a of t){if(a.event_type==="permission_decision"&&a.decision==="deny"&&(r+=1),a.event_type==="tool_call"){let l=a.tool_name??"unknown",c=e.get(l)??{calls:0,errors:0};c.calls+=1,s+=1,e.set(l,c)}if(a.event_type==="tool_result"&&a.status==="error"){let l=a.tool_name??"unknown",c=e.get(l)??{calls:0,errors:0};c.errors+=1,e.set(l,c)}if(a.event_type==="tool_result"){let l=a.tool_name??"unknown";n.set(l,(n.get(l)??0)+1)}}let o=0;for(let[a,l]of n.entries()){let c=e.get(a)??{calls:0,errors:0},u=Math.max(0,l-c.calls);u!==0&&(c.calls+=u,s+=u,o+=u,e.set(a,c))}let i=o>0?[`Recovered ${o} tool call(s) from tool_result audit events that had no matching tool_call event.`]:void 0;return{total_calls:s,permission_denied:r,by_tool:Object.fromEntries([...e.entries()].sort((a,l)=>a[0].localeCompare(l[0]))),...i?{observability_warnings:i}:{}}}function Jc(t){return t.interrupted?"interrupted":t.permissionDeniedCount>0?"permission_denied":t.hadError?"error":t.incomplete?"incomplete":"ok"}function Qc(t,e={}){return t==="ok"?0:t==="permission_denied"?2:t==="interrupted"?130:t==="incomplete"&&e.nonFatalIncomplete===!0?0:1}import{Command as zg}from"commander";It();var he={};Me(he,JR);import*as JR from"@xeno-corporation/xeno-agent-sdk/utils";var Hs=new zg("sessions").description("Manage chat sessions");Hs.command("list").description("List sessions for the current working directory (use --all for every workspace)").option("--role <role>","Filter by role").option("--limit <n>","Limit results","20").option("--status <status>","Filter by status (active, paused, completed, abandoned)").option("--all","List sessions across every working directory, not just this one").action(async t=>{try{let e=parseInt(t.limit,10),n=await Ie.SessionRegistry.list({role:t.role,limit:isNaN(e)?20:e,status:t.status?[t.status]:void 0,workingDirectory:t.all?void 0:process.cwd()});if(n.length===0){he.info(t.all?"No sessions found":"No sessions found in this workspace (use --all to list every workspace)");return}he.info(`Found ${n.length} session(s)${t.all?"":" in this workspace"}:
|
|
1141
|
+
`);for(let s of n){let r=Zc(s.status),o=$i(new Date(s.lastActivity));he.info(`${_.accent("\u25CF")} ${_.bold(s.id)}`),he.info(` ${_.dim("Role:")} ${s.role}`),he.info(` ${_.dim("Status:")} ${r(s.status)}`),he.info(` ${_.dim("Messages:")} ${s.messageCount}`),he.info(` ${_.dim("Tokens:")} ${s.tokenUsage.total.toLocaleString()}`),he.info(` ${_.dim("Last activity:")} ${o}`),he.info(` ${_.dim("Working directory:")} ${s.workingDirectory}`),he.info("")}}catch(e){let n=e instanceof Error?e.message:String(e);he.error(`Error listing sessions: ${n}`),process.exit(1)}});Hs.command("show <id>").description("Show detailed information about a session").action(async t=>{try{let e=await Ie.SessionRegistry.find(t);if(e||(he.error(`Session not found: ${t}`),process.exit(1)),he.info(""),he.info(_.bold(`Session: ${e.id}`)),he.info(_.dim("\u2500".repeat(60))),he.info(`${_.dim("Role:")} ${e.role}`),he.info(`${_.dim("Status:")} ${Zc(e.status)(e.status)}`),he.info(`${_.dim("Model:")} ${e.model}`),he.info(`${_.dim("Working directory:")} ${e.workingDirectory}`),he.info(""),he.info(_.dim("Timestamps:")),he.info(` ${_.dim("Created:")} ${new Date(e.createdAt).toLocaleString()}`),he.info(` ${_.dim("Updated:")} ${new Date(e.updatedAt).toLocaleString()}`),he.info(` ${_.dim("Last activity:")} ${new Date(e.lastActivity).toLocaleString()} (${$i(new Date(e.lastActivity))})`),he.info(""),he.info(_.dim("Usage:")),he.info(` ${_.dim("Messages:")} ${e.messageCount}`),he.info(` ${_.dim("Input tokens:")} ${e.tokenUsage.input.toLocaleString()}`),he.info(` ${_.dim("Output tokens:")} ${e.tokenUsage.output.toLocaleString()}`),he.info(` ${_.dim("Total tokens:")} ${e.tokenUsage.total.toLocaleString()}`),e.checkpoints.length>0){he.info(""),he.info(_.dim("Checkpoints:"));for(let n of e.checkpoints)he.info(` ${_.accent("\u25CF")} ${n}`)}e.parentSession&&(he.info(""),he.info(`${_.dim("Parent session:")} ${e.parentSession}`)),he.info("")}catch(e){let n=e instanceof Error?e.message:String(e);he.error(`Error showing session: ${n}`),process.exit(1)}});Hs.command("clean").description("Clean up old or abandoned sessions in this workspace (use --all for every workspace)").option("--older-than <days>","Delete sessions older than N days","30").option("--status <status>","Only delete sessions with this status","abandoned").option("--dry-run","Show what would be deleted without deleting").option("--all","Operate on sessions across every working directory, not just this one").action(async t=>{try{let e=parseInt(t.olderThan,10);(isNaN(e)||e<1)&&(he.error("Invalid --older-than value. Must be a positive number."),process.exit(1));let n=new Date;n.setDate(n.getDate()-e);let r=(await Ie.SessionRegistry.list({status:t.status?[t.status]:void 0,workingDirectory:t.all?void 0:process.cwd()})).filter(c=>new Date(c.lastActivity)<n);if(r.length===0){he.info(`No sessions to clean (older than ${e} days)`);return}he.info(`Found ${r.length} session(s) to clean:
|
|
1142
|
+
`);for(let c of r){let u=$i(new Date(c.lastActivity));he.info(` ${_.accent("\u25CF")} ${c.id} (${u})`)}if(t.dryRun){he.info("[Dry run - no sessions deleted]");return}he.info("");let i=(await import("readline")).createInterface({input:process.stdin,output:process.stdout});if((await new Promise(c=>{i.question(_.cyan(`Delete ${r.length} session(s)? (y/N) `),u=>{i.close(),c(u)})})).toLowerCase()!=="y"){he.info("Cancelled");return}let l=0;for(let c of r)try{await Ie.SessionRegistry.delete(c.id),l++}catch(u){let p=u instanceof Error?u.message:String(u);he.error(`Failed to delete ${c.id}: ${p}`)}he.info(`Deleted ${l} session(s)`)}catch(e){let n=e instanceof Error?e.message:String(e);he.error(`Error cleaning sessions: ${n}`),process.exit(1)}});function Zc(t){switch(t){case"active":return _.green;case"paused":return _.cyan;case"completed":return _.purple;case"abandoned":return _.dim;case"archived":return _.dim;default:return e=>e}}function $i(t){let n=new Date().getTime()-t.getTime();if(n<0)return"just now";let s=Math.floor(n/1e3),r=Math.floor(s/60),o=Math.floor(r/60),i=Math.floor(o/24);if(s<60)return"just now";if(r<60)return`${r} minute${r===1?"":"s"} ago`;if(o<24)return`${o} hour${o===1?"":"s"} ago`;if(i<30)return`${i} day${i===1?"":"s"} ago`;{let a=Math.floor(i/30);return`${a} month${a===1?"":"s"} ago`}}Wt();async function eu(t){return(0,R.benchmarkCodingTools)({cwd:t?.cwd,iterations:t?.iterations,fileCount:t?.fileCount,linesPerFile:t?.linesPerFile})}function tu(t){return(0,R.renderCodingBenchmarkReport)(t)}function nu(t){return(0,R.renderCodingBenchmarkMarkdown)(t)}import{existsSync as cn,readdirSync as Bi,readFileSync as Wg,statSync as zs}from"fs";import{basename as Ni,join as it,resolve as Xg}from"path";function ds(t){try{return cn(t)?Wg(t,"utf-8"):void 0}catch{return}}function Li(t){let e=ds(t);if(e)try{return JSON.parse(e)}catch{return}}function Kg(t){let e=Xg(t);if(cn(it(e,"result.json"))||cn(it(e,"results.json")))return e;let n=Bi(e).map(r=>it(e,r)).filter(r=>zs(r).isDirectory()&&(cn(it(r,"result.json"))||cn(it(r,"results.json"))));if(n.length===1)return n[0];let s=it(e,Ni(e));return cn(it(s,"result.json"))||cn(it(s,"results.json"))?s:e}function su(t){let e=it(t,"artifacts","xeno-audit");return cn(e)?Bi(e).map(s=>it(e,s)).filter(s=>zs(s).isFile()).sort((s,r)=>zs(r).mtimeMs-zs(s).mtimeMs)[0]:void 0}function Gg(t,e){return e&&(typeof t!="number"||t<=0)?"error":typeof t=="number"?t>0?"pass":"fail":e?"error":"fail"}function ru(t){let e=new Set,n=[],s=[t.exceptionType??"",t.exceptionMessage??"",t.taskPrompt??"",t.verifierStdout??"",t.agentLog??"",t.audit??""].join(`
|
|
1143
|
+
`);return/(?:invalid_api_key|401\b|unauthorized|forbidden|403\b|payment required)[\s\S]{0,180}\b(?:api|auth|credential|key|token|bearer|xeno|provider|billing)\b|\b(?:api|auth|credential|key|token|bearer|xeno|provider|billing)\b[\s\S]{0,180}(?:invalid_api_key|401\b|unauthorized|forbidden|403\b|payment required)/i.test(s)&&(e.add("auth_credentials"),n.push("agent log or exception shows API authentication failure")),/API error[\s\S]*(?:timed out|timeout|fetch failed|socket hang up|ECONNRESET|ENOTFOUND|EAI_AGAIN|status=(?:429|502|503|504))|request timed out after|Chat completions API request timed out/i.test(s)&&(e.add("api_transport_resilience"),n.push("agent log shows a retryable provider or network transport failure")),/RangeError:\s*Invalid string length|output truncated; omitted \d+ leading characters/i.test(s)&&(e.add("runtime_output_backpressure"),n.push("shell output volume stressed the CLI runtime capture path")),/agent_timeout|AgentTimeoutError|timed out after/i.test(s)&&(e.add("bounded_experimentation"),n.push("trial ended in agent timeout")),/\b(?:SELF_CHECK|CONTRACT|ROUNDTRIP|MODEL_ARTIFACT|VALIDATION)[A-Z0-9_-]*PASS\b/i.test(s)&&/(?:AssertionError|FAILED|FAILURES?|Wrong output|does not match|mismatch|No such file or directory|FileNotFoundError|expected .* got|below .* threshold)/i.test(s)&&(e.add("self_check_mismatch"),n.push("agent reported a self-check pass but verifier output still failed")),/Solution .* not found|Required task outputs are still missing|\/app\/[A-Za-z0-9_.-]+(?:txt|sql|json|md)/i.test(s)&&/not found|missing/i.test(s)&&(e.add("output_contract"),n.push("required output file was missing or incomplete")),/(?:FileNotFoundError|No such file or directory|Expected \d+ rows|got \d+|original .* directory .* empty|documents directory should be empty|summary_csv|test_output\.csv|reconstructed\.ppm|result\.txt contains unexpected value)/i.test(s)&&(e.add("final_state_contract"),n.push("verifier expected a different final filesystem or artifact state")),/Running iteration \d+ of \d+|median_s|speedup_solution_vs_golden|EXPLAIN QUERY PLAN/i.test(s)&&(e.add("performance_validation"),n.push("task required explicit performance measurement")),/sqlite|sql query|golden|solution.*median_s|Open English Wordnet|oewn\.sqlite/i.test(s)&&(e.add("sql_optimization"),n.push("task behavior or verifier output indicates SQL optimization")),/(?:model|weights?|checkpoint|ckpt|torch|pytorch|caffe|cifar|gpt-?2|tokeni[sz]er|vocab|bpe|logits?|accuracy|loss|forward\(\)|inference|prediction)/i.test(s)&&/(?:accuracy .* below|Wrong output|expected .* output|forward\(\) expected|loss|training output suspiciously short|Too few iteration logs|mutation|state_dict|weights)/i.test(s)&&(e.add("ml_artifact_quality"),n.push("failure concerns model artifact behavior, training quality, or inference contract")),/(?:image|video|frame|opencv|cv2|ffmpeg|ocr|render|pixel|path\s*tracing|ray\s*tracing|ppm|mask|segmentation|document|invoice|pdf|html|BeautifulSoup)/i.test(s)&&/(?:FileNotFoundError|Wrong output|similarity|mask|alignment|CSV|rows|modified .* clean HTML|expected .* got|No alert detected|image|frame|document|invoice)/i.test(s)&&(e.add("visual_document_pipeline"),n.push("failure concerns visual, video, document, OCR, rendering, or media-derived artifacts")),/(?:csv|tsv|parquet|jsonl?|dataframe|columns?|rows?|schema|coords_[xy]|ast\.literal_eval|summary_csv|test_output\.csv)/i.test(s)&&/(?:Expected \d+ rows|got \d+|columns?|shape|FileNotFoundError|list-valued|tuple|schema|row count|Column names\/order differ)/i.test(s)&&(e.add("structured_output_contract"),n.push("failure concerns generated structured artifact schema, rows, or field types")),/(?:dna|primer|protein|gblock|oligotm|Tm|melting|raman|spectrum|peak|gamma|amplitude|mjcf|simulation|molecule|assembly)/i.test(s)&&/(?:Tm|melting|order|Fusion protein|Expected .* Got|threshold|x0|gamma|amplitude|offset|sequence|assembly)/i.test(s)&&(e.add("science_numeric_domain"),n.push("failure concerns domain-specific scientific, biological, or numeric constraints")),/(?:regex|regular expression|legal moves|python-chess|codegolf|search|solver|circuit|fibsqrt|constraint|round[- ]?trip|decompress)/i.test(s)&&/(?:not found in|Wrong output|counterexample|too few|larger than|timeout|AssertionError)/i.test(s)&&(e.add("symbolic_search_generalization"),n.push("failure concerns search, symbolic generalization, regex, solver, or code-size correctness")),/(?:compile|compiler|cross-?compile|gcc|clang|make|cmake|ninja|qemu|emulator|mips|riscv|doom|windows\s+3\.11|kernel|ELF|readelf|objdump|binary)/i.test(s)&&/(?:NonZeroAgentExitCodeError|Compilation failed|process .* exited|No such file|timeout|wrong output|ELF|segment|binary)/i.test(s)&&(e.add("toolchain_emulator_reliability"),n.push("failure concerns compiler, emulator, binary recovery, or cross-toolchain execution")),/golden.*median_s|solution.*median_s|speedup_solution_vs_golden/i.test(s)&&/assert .*solution.*median_s/i.test(s)&&(e.add("solution_quality"),n.push("solution matched output contract but was slower than golden")),/MISSING \/tests|MISSING \/run-tests\.sh|MISSING \/README\.md|MISSING \/instruction\.md/i.test(s)&&(e.add("hidden_verifier_discovery"),n.push("no explicit verifier path was exposed in the task environment")),/CORRELATED SCALAR SUBQUERY|USE TEMP B-TREE FOR ORDER BY|USE TEMP B-TREE FOR GROUP BY/i.test(s)&&(e.add("query_plan_quality"),n.push("query plan suggests expensive correlated subqueries or temp b-tree churn")),/tool_name\":\"Write\".*\/app\/sol\.sql|Created \/app\/sol\.sql/i.test(s)&&(e.add("writes_output_early"),n.push("agent wrote the required output file before final completion")),/SIGINT|SIGTERM|send_signal|KeyboardInterrupt|cancel(?:lation)?|asyncio|Cleaned up/i.test(s)&&/Cleaned up.*0 == 2|assert stdout\.count\(\"Cleaned up\.\"\)|cleanup|cancel(?:lation)?/is.test(s)&&(e.add("async_process_validation"),n.push("failure concerns signal, cancellation, or async cleanup behavior")),e.size===0&&(e.add("uncategorized"),n.push("no known failure heuristic matched")),{categories:Array.from(e),evidence:n}}function Yg(t){return!t||typeof t!="object"?"":Object.entries(t).map(([e,n])=>`${e}: ${String(n)}`).join(`
|
|
1144
|
+
`)}function Jg(t,e){return(e.results??[]).map(n=>{let s=n.trial_name??n.task_id??"unknown-trial",r=n.task_id??s,o=n.failure_mode&&n.failure_mode!=="unset"?n.failure_mode:void 0,i=Yg(n.parser_results),a=ru({exceptionType:o,taskPrompt:n.instruction,verifierStdout:i});return{trialName:s,taskName:r,status:n.is_resolved===!0?"pass":"fail",reward:n.is_resolved===!0?1:0,exceptionType:o,categories:a.categories,evidence:a.evidence}})}function Qg(t){let e=new Map,n=t.filter(r=>r.status!=="pass");for(let r of n)for(let o of r.categories){let i=e.get(o)??[];i.push(r),e.set(o,i)}let s={auth_credentials:{severity:"critical",summary:"Benchmark failures include credential or API authentication problems.",recommendation:"Prefer local signed-in credential fallback and run a preflight auth check before launching long jobs."},api_transport_resilience:{severity:"critical",summary:"Retryable provider or network failures can still turn useful filesystem work into failed trials.",recommendation:"Recover late transport failures only when required outputs are present and the completion guard has no blocking validation left; otherwise retry before work starts."},runtime_output_backpressure:{severity:"critical",summary:"Large command output can stress runtime capture or log handling.",recommendation:"Keep shell stdout/stderr capture bounded and preserve a tail plus truncation notice instead of accumulating unbounded strings."},bounded_experimentation:{severity:"warn",summary:"At least one task spent too much of the budget inside long-running experimentation or benchmarking loops.",recommendation:"Cap verifier-shaped measurement loops, prefer smaller fixed samples, and bias toward earlier convergence once the evidence is clear."},self_check_mismatch:{severity:"critical",summary:"The agent's local success marker did not match the official verifier result.",recommendation:"Strengthen verifier synthesis: require final-artifact readback, adversarial fixtures, and same-entrypoint checks before accepting SELF_CHECK_PASS."},output_contract:{severity:"warn",summary:"The agent risks failing tasks by delaying or missing required output files.",recommendation:"Write the best current candidate to the required output path early, then overwrite it if better evidence emerges."},final_state_contract:{severity:"critical",summary:"The final filesystem or process state did not match what the verifier inspected.",recommendation:"Add a final-state auditor that checks required paths, cleanup side effects, latest write ordering, and post-cleanup positive validation."},performance_validation:{severity:"info",summary:"Performance-sensitive tasks require stronger runtime evidence than ordinary correctness tasks.",recommendation:"Use bounded, verifier-shaped measurement routines and inspect query plans or profiles before finalizing."},sql_optimization:{severity:"warn",summary:"SQL optimization remains a benchmark-critical capability area.",recommendation:"Prefer set-based rewrites, reuse pre-aggregated CTEs, and delay presentation-only joins until after top-k reduction when possible."},solution_quality:{severity:"critical",summary:"The agent produced a valid solution that still lost to the benchmark's golden implementation on runtime.",recommendation:"Improve candidate ranking: compare multiple query shapes, inspect EXPLAIN plans, and reject slower rewrites even when correctness already matches."},ml_artifact_quality:{severity:"critical",summary:"Model artifacts, training loops, or inference wrappers did not satisfy the real behavior contract.",recommendation:"Use the ML project kit: inspect schemas, validate multiple samples or labels, prove dependency on provided artifacts, and reject shallow stubs."},visual_document_pipeline:{severity:"warn",summary:"Visual, video, document, OCR, or rendering-derived artifacts need stronger extraction and verification.",recommendation:"Use independent render/OCR/numeric passes and read generated CSV/media outputs back through the exact verifier-facing path."},structured_output_contract:{severity:"warn",summary:"Generated structured outputs failed schema, row, column, or field-type expectations.",recommendation:"Run submitted scripts end-to-end, then assert row counts, column order, field parseability, list/scalar types, and exact values from the produced artifact."},science_numeric_domain:{severity:"warn",summary:"Scientific, biological, or numeric-domain constraints were not validated with enough precision.",recommendation:"Measure every stated numeric constraint using the required calculator/tool and rerun the complete reconstruction check on the final artifact."},symbolic_search_generalization:{severity:"warn",summary:"Search, regex, code-size, or symbolic solutions failed outside a narrow local sample.",recommendation:"Create a counterexample generator or independent oracle first, checkpoint valid candidates early, and only optimize after correctness is broad."},toolchain_emulator_reliability:{severity:"warn",summary:"Compiler, emulator, binary, or cross-toolchain tasks still need stronger phased execution.",recommendation:"Split setup, build, run, and final client verification into bounded phases with logs and preserve the final runnable state."},hidden_verifier_discovery:{severity:"info",summary:"Some tasks hide the verifier path entirely, so the agent must infer the contract from artifacts and behavior.",recommendation:"When no verifier is exposed, fall back to contract-matched self-checks rather than waiting for explicit test entrypoints."},query_plan_quality:{severity:"warn",summary:"The failed task shows signs of query-plan inefficiency rather than tool-use failure.",recommendation:"Teach the agent to treat correlated subqueries and repeated rescans as red flags and to prefer plan-improving rewrites early."},async_process_validation:{severity:"warn",summary:"Async/process tasks require real signal-path and cleanup validation.",recommendation:"Require post-write validation that sends the actual signal or cancellation path and observes cleanup, termination, and boundary behavior."},writes_output_early:{severity:"info",summary:"The agent now writes required output files earlier in the run.",recommendation:"Keep this behavior; it reduces output-contract failures and preserves partial progress under time pressure."},uncategorized:{severity:"info",summary:"Some failures could not be classified automatically.",recommendation:"Inspect the trial audit log and verifier output directly, then extend the classifier with the new failure pattern."}};return Array.from(e.entries()).map(([r,o])=>{let i=s[r]??s.uncategorized;return{category:r,severity:i.severity,summary:i.summary,recommendation:i.recommendation,tasks:o.map(a=>a.trialName)}}).sort((r,o)=>{let i={critical:0,warn:1,info:2};return i[r.severity]-i[o.severity]})}function ou(t){let e=Kg(t),n=Li(it(e,"result.json")),s=Li(it(e,"results.json")),r=s?.results?[]:Bi(e).map(c=>it(e,c)).filter(c=>cn(it(c,"config.json"))&&zs(c).isDirectory()),o=s?.results?Jg(e,s):r.map(c=>{let u=Li(it(c,"result.json")),p=ds(it(c,"verifier","reward.txt"))?.trim(),f=u?.verifier_result?.rewards?.reward??(p?Number.parseFloat(p):null),m=u?.exception_info?.exception_type,g=u?.exception_info?.exception_message??ds(it(c,"exception.txt"))?.split(/\r?\n/)[0],b=ds(it(c,"verifier","test-stdout.txt")),v=ds(it(c,"agent","xeno.txt")),w=su(c)?ds(su(c)):void 0,P=ru({exceptionType:m,exceptionMessage:g,taskPrompt:u?.instruction??u?.task_name,verifierStdout:b,agentLog:v,audit:w}),C=u?.trial_name??Ni(c);return{trialName:C,taskName:u?.task_name??C,status:Gg(f,m),reward:Number.isFinite(f)?f:null,exceptionType:m,exceptionMessage:g,categories:P.categories,evidence:P.evidence}}),i=o.filter(c=>c.status==="pass").length,a=o.filter(c=>c.status==="fail").length,l=o.filter(c=>c.status==="error").length;return{generatedAt:new Date().toISOString(),jobPath:e,jobName:Ni(e),startedAt:n?.started_at??s?.started_at,finishedAt:n?.finished_at??s?.finished_at,totalTrials:n?.n_total_trials??s?.results?.length??o.length,passed:i,failed:a,errors:l,passRate:o.length>0?i/o.length:0,tasks:o,findings:Qg(o)}}function iu(t){let e=["Harbor benchmark analysis",`Job: ${t.jobName}`,`Path: ${t.jobPath}`,`Trials: ${t.totalTrials} | Passed: ${t.passed} | Failed: ${t.failed} | Errors: ${t.errors}`,`Pass rate: ${(t.passRate*100).toFixed(1)}%`];t.startedAt&&e.push(`Started: ${t.startedAt}`),t.finishedAt&&e.push(`Finished: ${t.finishedAt}`),e.push("","Task summary");for(let n of t.tasks){let s=typeof n.reward=="number"?n.reward.toFixed(1):"n/a",r=n.exceptionType?` | ${n.exceptionType}`:"";e.push(`- ${n.trialName}: ${n.status.toUpperCase()} | reward ${s}${r}`),e.push(` task: ${n.taskName}`),e.push(` categories: ${n.categories.join(", ")}`)}if(t.findings.length>0){e.push("","Findings");for(let n of t.findings)e.push(`- [${n.severity}] ${n.category}: ${n.summary}`),e.push(` recommendation: ${n.recommendation}`),e.push(` tasks: ${n.tasks.join(", ")}`)}return e.join(`
|
|
1145
|
+
`)}function au(t){let e=["## Harbor Benchmark Analysis","",`- Job: \`${t.jobName}\``,`- Trials: \`${t.totalTrials}\``,`- Passed: \`${t.passed}\``,`- Failed: \`${t.failed}\``,`- Errors: \`${t.errors}\``,`- Pass rate: \`${(t.passRate*100).toFixed(1)}%\``];t.startedAt&&e.push(`- Started: \`${t.startedAt}\``),t.finishedAt&&e.push(`- Finished: \`${t.finishedAt}\``),e.push("","### Task Summary","","| Trial | Status | Reward | Categories |","| --- | --- | ---: | --- |");for(let n of t.tasks)e.push(`| ${n.trialName} | ${n.status.toUpperCase()} | ${typeof n.reward=="number"?n.reward.toFixed(1):"n/a"} | ${n.categories.join(", ")} |`);if(t.findings.length>0){e.push("","### Findings","");for(let n of t.findings)e.push(`- **${n.category}** (${n.severity})`),e.push(` ${n.summary}`),e.push(` Recommendation: ${n.recommendation}`),e.push(` Tasks: ${n.tasks.join(", ")}`)}return e.join(`
|
|
1146
|
+
`)}Wt();import{Command as Zg}from"commander";function eb(t){let e=new R.MCPManager;return{cwd:t,mcpManager:e,messages:[],onOutput:n=>{process.stdout.write(n)},refreshMcpTools:()=>{}}}async function Ut(t,e){let n=process.cwd(),s=eb(n);try{e?.connect&&await s.mcpManager?.connectConfiguredServers({cwd:n}),await ki(t,s)}finally{s.mcpManager?.dispose()}}function lu(t){return t==="user"?"--user":t==="mcprc"?"--mcprc":"--project"}function cu(){let t=new Zg("mcp").description("Manage configured MCP servers, prompts, and resources");return t.command("list").option("--no-connect","Skip connecting approved servers before listing").action(async e=>{await Ut(["list"],{connect:e.connect!==!1})}),t.command("prompts [server]").action(async e=>{await Ut(e?["prompts",e]:["prompts"],{connect:!0})}),t.command("prompt <server> <name> [argValues...]").action(async(e,n,s)=>{await Ut(["prompt",e,n,...s??[]],{connect:!0})}),t.command("resources [server]").action(async e=>{await Ut(e?["resources",e]:["resources"],{connect:!0})}),t.command("resource <server> <uri>").action(async(e,n)=>{await Ut(["resource",e,n],{connect:!0})}),t.command("reload").action(async()=>{await Ut(["reload"],{connect:!0})}),t.command("add <name> [command] [serverArgs...]").option("--scope <scope>","Configuration scope: project, mcprc, or user","project").option("--sse <url>","Connect to a remote SSE MCP server").option("--no-approval","Do not require workspace approval before loading").action(async(e,n,s,r)=>{let o=["add",e];typeof r.sse=="string"&&r.sse.length>0?o.push("--sse","--url",r.sse):typeof n=="string"&&n.length>0&&o.push(n,...s??[]),o.push(lu(r.scope)),r.approval===!1&&o.push("--no-approval"),await Ut(o,{connect:!0})}),t.command("remove <name>").option("--scope <scope>","Configuration scope: project, mcprc, or user","project").action(async(e,n)=>{await Ut(["remove",e,lu(n.scope)],{connect:!0})}),t.command("approve <name>").action(async e=>{await Ut(["approve",e],{connect:!0})}),t.command("deny <name>").action(async e=>{await Ut(["deny",e],{connect:!0})}),t.command("reset-mcprc-choices").action(async()=>{await Ut(["reset-mcprc-choices"],{connect:!0})}),t}import{existsSync as tb,readFileSync as nb}from"fs";function sb(t=process.env){return t.XENO_ALLOW_UNSAFE_BYPASS==="1"}function rb(t=process.platform,e=typeof process.getuid=="function"?process.getuid:void 0){if(t==="win32"||!e)return!1;try{return e()===0}catch{return!1}}function ob(t=process.env){if(t.container?.toLowerCase()==="docker"||tb("/.dockerenv"))return!0;try{let e=nb("/proc/1/cgroup","utf-8").toLowerCase();return e.includes("docker")||e.includes("containerd")||e.includes("kubepods")}catch{return!1}}async function ib(t=fetch,e=1500){let n=new AbortController,s=setTimeout(()=>n.abort(),e);try{return(await t("https://registry.npmjs.org/-/ping",{method:"GET",signal:n.signal})).ok}catch{return!1}finally{clearTimeout(s)}}async function ab(t){let e=t?.env??process.env,n=sb(e),s=rb(t?.platform??process.platform,t?.getuid),r=ob(e),o=n?!1:await ib(t?.fetchImpl??fetch);return n?{allowed:!0,reason:"Unsafe bypass override enabled via XENO_ALLOW_UNSAFE_BYPASS=1",checks:{override:n,isRoot:s,isDocker:r,hasInternet:o}}:s?{allowed:!1,reason:"--bypass-permissions cannot be used with root/sudo privileges.",checks:{override:n,isRoot:s,isDocker:r,hasInternet:o}}:!r||o?{allowed:!1,reason:"--bypass-permissions is only allowed in Docker containers without internet access. Set XENO_ALLOW_UNSAFE_BYPASS=1 to override explicitly.",checks:{override:n,isRoot:s,isDocker:r,hasInternet:o}}:{allowed:!0,reason:"Safe bypass environment detected (Docker + no internet).",checks:{override:n,isRoot:s,isDocker:r,hasInternet:o}}}async function uu(t){let e=await ab();if(!e.allowed)throw new Error(`${t}: ${e.reason}`)}import{existsSync as Kr,readFileSync as Hn,statSync as jt}from"fs";import{basename as qn,dirname as Qu,resolve as yt}from"path";import{gzipSync as py}from"zlib";var lb=/(?:[A-Za-z]:\\[^\s"'`<>|]+|\/[^\s"'`<>|]+)/g,cb=[/\bwrite\s+(?:the\s+)?(?:output|result|answer|contents?|solution)\s+to\s+(?:"|'|`)?([^\s"'`]+)(?:"|'|`)?/i,/\bsave\s+(?:it|them|your\s+solution|the\s+(?:output|result|answer|solution|model|file|artifact))?\s+(?:as|to|in)\s+(?:"|'|`)?([^\s"'`]+)(?:"|'|`)?/i,/\b(?:create|place)\s+(?:a\s+file\s+(?:called|named)|the\s+file)\s+(?:"|'|`)?([^\s"'`]+)(?:"|'|`)?/i,/\b(?:must|should|needs?\s+to)\s+be\s+(?:saved|written|placed|stored)\s+(?:as|to|in)\s+(?:"|'|`)?([^\s"'`]+)(?:"|'|`)?/i,/\bfinal\s+(?:model|output|artifact|answer|solution)\s+(?:needs?\s+to|should|must)\s+be\s+saved\s+as\s+(?:"|'|`)?([^\s"'`]+)(?:"|'|`)?/i,/\b(?:at|in)\s+(?:"|'|`)?((?:\/app|\/workspace|\/tmp|\.{1,2}\/)[^\s"'`]+)(?:"|'|`)?\s+(?:containing|with\s+the\s+(?:answer|result|solution))/i],ub=/(?:"([^"\n]{4,240})"|'([^'\n]{4,240})'|`([^`\n]{4,240})`)/g,db=/(?:^|\n)\s*(?:\$?\s*)?(uv run|python3?|pytest|npm|pnpm|yarn|cargo|make|cmake|ninja|gcc|g\+\+|clang|go|rustc|sqlite3|ffmpeg|openssl|qemu-system-[\w-]+|curl|ssh|git|docker|bash|sh)\b[^\n]{0,220}/gi,pb=/\b(?:at\s+least|at\s+most|less\s+than|more\s+than|greater\s+than|under|over|within|max(?:imum)?|min(?:imum)?|accuracy|score|valid\s+for|size|runtime|timeout|precision|recall|f1|rmse|mae)\b[^\n.;:]{0,120}\d+(?:\.\d+)?\s*(?:%|mb|gb|kb|bytes?|s|sec(?:onds?)?|ms|days?|years?|accuracy|score)?/gi,mb=[{name:"ML/model artifact",pattern:/\b(?:model|weights?|checkpoint|ckpt|onnx|torch|pytorch|tensorflow|keras|fasttext|embedding|inference|prediction|logits?|classif(?:y|ication)|train(?:ing)?|accuracy|gpt-?2|tokeni[sz]er)\b/i,checks:["validate on multiple representative samples or a holdout, not one smoke input","reject constant, hard-coded, or one-sample inference stubs unless the task explicitly proves they are valid","verify artifact size, invocation, preprocessing, label order, and output schema together"]},{name:"visual/video/geometry",pattern:/\b(?:image|video|frame|opencv|cv2|ffmpeg|ocr|render|pixel|sprite|gcode|g-code|path\s*tracing|ray\s*tracing|camera|toml|move\s+extraction)\b/i,checks:["derive answers from pixels, frames, geometry, or rendered previews instead of filenames or comments","use at least two independent views when possible, such as numeric analysis plus preview inspection","for exact tokens or flags, verify the final text byte-for-byte before finishing"]},{name:"compiler/emulator/build",pattern:/\b(?:compile|compiler|cross-?compile|gcc|clang|cargo|rustc|make|cmake|ninja|mips|riscv|x86|arm|kernel|qemu|emulator|interpreter|assembly|linker|windows\s+3\.11|doom)\b/i,checks:["split build, run, and verifier phases, each with bounded logs and explicit success criteria","keep the final runnable artifact or service state after the last positive check","if full builds are expensive, run narrow syntax/unit checks before the full verifier-shaped command"]},{name:"symbolic/search/optimization",pattern:/\b(?:regex|regular expression|solver|constraint|backtracking|search|codegolf|shortest|smallest|optimi[sz]e|fibonacci|circuit|sat|smt|brute\s*force)\b/i,checks:["build a small independent verifier or counterexample generator before optimizing","checkpoint the current best valid candidate to the required output path before long searches","treat near-threshold wins as failures unless repeated checks show a clear margin"]},{name:"data integrity/conversion",pattern:/\b(?:csv|tsv|parquet|jsonl?|dataset|dataframe|reshard|compress|decompress|wal|sqlite|database|token(?:s|i[sz]e)?)\b/i,checks:["compare row counts, ordering, schema, nulls, and exact byte or cell values where relevant","validate by reading the produced artifact back, not only by checking that files exist","preserve required final files after temporary validation cleanup"]},{name:"service/VM/network",pattern:/\b(?:server|service|daemon|webserver|http|https|localhost|port\s+\d+|ssh|sshd|qemu|vm|virtual\s+machine|container)\b/i,checks:["poll readiness and verify the exact final client command, including auth and content","leave required long-running services or VMs alive in the final state","an open port alone is not a pass; verify the protocol-level contract"]},{name:"security/sanitization",pattern:/\b(?:xss|sanitize|html|javascript|script|payload|exploit|decrypt|archive|hash|password|secret|certificate|openssl)\b/i,checks:["test both positive and negative/adversarial cases, including idempotence when preserving clean input matters","do not write guesses or placeholders into required answer files","verify final artifacts with format-specific tools where available"]},{name:"science/numeric/bio",pattern:/\b(?:dna|protein|genome|melting|tm\b|raman|spectrum|fit|curve|simulation|molecule|assembly)\b/i,checks:["measure the exact numeric constraints the prompt states and keep safety margin beyond thresholds","run validation on the final submitted artifact, not an intermediate candidate","if stochastic search is used, save the best validated candidate before continuing"]},{name:"binary/ELF/recovery",pattern:/\b(?:elf|binary|disassembl|objdump|readelf|segment|memory|recovery|reverse\s*engineer)\b/i,checks:["parse the file format generically and validate against header/segment metadata","confirm address formats, endian handling, and value types match the required output","test on a second generated or varied sample when possible"]}];function pu(t){return t.trim().replace(/^[`'"]+|[`'"]+$/g,"").replace(/[.,;:)\]]+$/g,"").trim()}function mu(t){return t.length===0||/^[a-z][a-z0-9+.-]*:\/\//i.test(t)||t.startsWith("//")}function Ws(t,e){let n=[],s=new Set;for(let r of t){let o=r.trim();if(!(!o||s.has(o))&&(s.add(o),n.push(o),n.length>=e))break}return n}function fb(t){let e=[];for(let n of cb){let s=new RegExp(n.source,n.flags.includes("g")?n.flags:`${n.flags}g`),r;for(;(r=s.exec(t))!==null;){let o=r[1]?pu(r[1]):"";mu(o)||e.push(o)}}return Ws(e,8)}function hb(t,e){let n=new Set(e),s=t.match(lb)??[];return Ws(s.map(r=>pu(r)).filter(r=>!mu(r)&&!n.has(r)),8)}function gb(t){let e=[],n;for(;(n=ub.exec(t))!==null;){let s=(n[1]??n[2]??n[3]??"").trim();s&&(/^(?:\/|[A-Za-z]:\\|\.\.?\/)/.test(s)||/^(?:python|npm|uv|cargo|make|curl|ssh|git|docker)\b/i.test(s)||e.push(s.length>96?`${s.slice(0,93)}...`:s))}return Ws(e,6)}function bb(t){let e=[],n;for(;(n=db.exec(t))!==null;){let s=n[0].replace(/^\s*\$?\s*/,"").trim();s.length>0&&e.push(s.length>140?`${s.slice(0,137)}...`:s)}return Ws(e,6)}function yb(t){let e=[],n;for(;(n=pb.exec(t))!==null;)e.push(n[0].replace(/\s+/g," ").trim());return Ws(e,6)}function wb(t){return mb.filter(e=>e.pattern.test(t)).slice(0,5)}function du(t){return/\b(?:terminal-bench|benchmark|verifier|hidden tests?|run-tests\.sh|live benchmark task container|\/app)\b/i.test(t)}function Di(t){let e=t?.trim()??"";if(!e)return"";let n=fb(e),s=hb(e,n),r=gb(e),o=bb(e),i=yb(e),a=wb(e);if(n.length===0&&s.length===0&&r.length===0&&o.length===0&&i.length===0&&a.length===0&&!du(e))return"";let l=["","","# Contract Ledger","- Before implementation, maintain a mental or written ledger of the required final artifacts, exact outputs, thresholds, and verifier-shaped commands.","- Update the ledger when new evidence appears. Do not finish until every ledger item has direct evidence from the final submitted state."];n.length>0&&l.push(`- Required output artifacts: ${n.join(", ")}`),s.length>0&&l.push(`- Mentioned input/reference paths: ${s.join(", ")}`),r.length>0&&l.push(`- Exact literal candidates to preserve byte-for-byte: ${r.join(" | ")}`),i.length>0&&l.push(`- Numeric or policy thresholds to measure directly: ${i.join(" | ")}`),o.length>0&&l.push(`- Prompt-provided command shapes to honor or emulate: ${o.join(" | ")}`),a.length>0&&l.push(`- Risk domains detected: ${a.map(c=>c.name).join(", ")}`),l.push("","# Adversarial Verification","- Treat file existence, one happy-path sample, a self-written smoke test, or a plausible-looking artifact as insufficient evidence.","- Build hidden-test-like checks: multiple samples, malformed/adversarial inputs, round trips, byte-level reads, schema checks, process-level invocation, or exact verifier commands as appropriate.","- Run checks against the final submitted artifact or final live service state, not only against an intermediate candidate.","- If validation is ambiguous, below threshold, near threshold, or only passes because of a narrow stub, keep working or explicitly mark the task incomplete instead of claiming success."),du(e)&&l.push("- In benchmark containers, do not declare SELF_CHECK_PASS until the required files or services survive final cleanup and at least one verifier-shaped check passes.");for(let c of a)l.push(`- ${c.name}: ${c.checks.join("; ")}.`);return l.join(`
|
|
1147
|
+
`)}var vb=/(?:[A-Za-z]:\\[^\s"'`<>|]+|\/[^\s"'`<>|]+)/g,Sb=[/\b(?:save|write|place|store)\s+(?:the\s+)?(?:output|result|answer|solution|model|artifact|file|contents?)\s+(?:as|to|in)\s+(?:"|'|`)?([^\s"'`]+)(?:"|'|`)?/gi,/\b(?:save|write|place|store)\s+(?:the\s+)?final\s+(?:output|result|answer|solution|model|artifact|file)\s+(?:as|to|in)\s+(?:"|'|`)?([^\s"'`]+)(?:"|'|`)?/gi,/\b(?:create|place)\s+(?:a\s+file\s+(?:called|named)|the\s+file)\s+(?:"|'|`)?([^\s"'`]+)(?:"|'|`)?/gi,/\b(?:write|create|implement)\s+(?:a\s+)?(?:C|C\+\+|Python|Rust|Go|JavaScript|TypeScript|shell|bash)?\s*(?:source\s+)?(?:program|script|implementation|module|file|code)\s+(?:at|as|in|to)?\s*(?:"|'|`)?((?:\/|\.{1,2}[\\/]|[A-Za-z0-9_.-]+[\\/])[^\s"'`]+|[A-Za-z0-9_.-]+\.(?:c|cc|cpp|h|hpp|py|js|ts|tsx|sh|rs|go|java|rb|pl|php|json|xml|tex|sql|vim))(?:"|'|`)?/gi,/\b(?:must|should|needs?\s+to)\s+be\s+(?:saved|written|placed|stored)\s+(?:as|to|in)\s+(?:"|'|`)?([^\s"'`]+)(?:"|'|`)?/gi,/\bfinal\s+(?:model|output|artifact|answer|solution)\s+(?:needs?\s+to|should|must)\s+be\s+saved\s+as\s+(?:"|'|`)?([^\s"'`]+)(?:"|'|`)?/gi,/\b(?:file|path)\s+(?:"|'|`)?((?:\/app|\/workspace|\/tmp|\.{1,2}\/)[^\s"'`]+)(?:"|'|`)?\s+(?:must|should|needs?\s+to|containing|with)\b/gi],kb=[{key:"ml_artifact",label:"ML/model artifact",trigger:/\b(?:model|weights?|checkpoint|ckpt|onnx|torch|pytorch|tensorflow|keras|fasttext|embedding|inference|prediction|logits?|classif(?:y|ication)|train(?:ing)?|accuracy|loss|gpt-?2|tokeni[sz]er|vocab|bpe)\b/i,verifierRequirements:["inspect model, weight, tokenizer, preprocessing, label-order, and entrypoint schema before wrapping it","validate multiple representative samples or known labels; one smoke input is not enough","when provided artifacts exist, prove dependency by loading/schema-checking or mutation/removal changing outputs","for distributed/tensor-parallel code, run the actual multiprocess/world-size verifier shape instead of only syntax or static checks"],finalAuditItems:["final model or wrapper loads from the submitted path","final invocation uses provided weights/tokenizers instead of constants","metric or known-output evidence is recorded against the final artifact"]},{key:"visual_artifact",label:"visual/video/geometry artifact",trigger:/\b(?:image|video|frame|opencv|cv2|ffmpeg|ocr|render|raster|pixel|sprite|gcode|g-code|path\s*tracing|ray\s*tracing|camera|toml|move\s+extraction|mask|segmentation|pdf|invoice|document)\b/i,verifierRequirements:["derive answers from rendered pixels, frame samples, geometry, OCR, or simulation rather than filenames/comments","use two independent views for exact text, coordinates, masks, or temporal outputs","read generated images, CSVs, PDFs, or media outputs back through the same shape the verifier will inspect"],finalAuditItems:["submitted visual/document/media artifact exists at the required path","second-pass content check agrees with the final output","temporary previews did not replace or remove the final deliverable"]},{key:"structured_data",label:"structured data or script output",trigger:/\b(?:csv|tsv|parquet|arrow|jsonl?|dataframe|table|schema|columns?|rows?|coords_[xy]|metadata|reshard|compress|decompress|output_path)\b/i,verifierRequirements:["run the submitted script or converter end-to-end, then read the generated artifact back","assert row count, column order, scalar/list field types, nulls, dtypes, and exact value preservation","for conversions, compare source and produced artifact with dataframe or byte-level equality where relevant"],finalAuditItems:["final generated artifact has the required schema and parseable fields","clean/reference inputs were not overwritten unless explicitly required","single-file deliverables contain only expected final content"]},{key:"performance",label:"performance or optimization",trigger:/\b(?:optimi[sz]e|faster|speed\s*up|runtime|latency|throughput|benchmark|profile|median|p95|under\s+\d+(?:\.\d+)?\s*(?:ms|s|sec|seconds?|min|minutes?)|accuracy|score)\b/i,verifierRequirements:["measure a baseline before optimizing and compare against the final candidate","use bounded warmed runs with medians or thresholds instead of one noisy timing","inspect relevant plans/profiles and reject changes that only preserve correctness while losing the target metric"],finalAuditItems:["best measured candidate is written to the required path","metric evidence has clear margin beyond the threshold","no long benchmark loop is still running in the final state"]},{key:"compiler_emulator",label:"compiler, emulator, or cross-architecture",trigger:/\b(?:compile|compiler|cross-?compile|gcc|clang|cargo|rustc|make|cmake|ninja|mips|riscv|x86|arm|kernel|qemu|emulator|interpreter|polyglot|doom|windows\s+3\.11|assembly|linker)\b/i,verifierRequirements:["identify the exact target toolchain and verifier command first","run a small compile/run smoke before expensive full builds","leave the final runnable artifact, VM, or emulator state after the last positive check"],finalAuditItems:["final binary/script/service starts with the verifier-shaped command","logs show the latest build/run result, not an old intermediate","background VM/emulator/service remains alive when the task requires post-run access"]},{key:"service_vm",label:"service, VM, network, or SSH",trigger:/\b(?:server|service|daemon|webserver|http|https|localhost|port\s+\d+|ssh|sshd|git\s+(?:server|clone|push)|grpc|protobuf|proto\b|rpc|request|response|client|qemu|vm|virtual\s+machine|container|socket|telnet|serial|monitor\s+socket|qmp|sendkey)\b/i,verifierRequirements:["separate setup, readiness polling, final client command, and cleanup into bounded phases","verify the exact user/verifier client command including auth, content, and protocol behavior","for gRPC/protobuf/RPC work, instantiate generated request messages with required fields and call every required RPC through a real client","for VM/QEMU work, verify monitor/QMP/serial control surfaces and expected framebuffer or service behavior, not screenshots alone","keep only required long-lived processes in the background and preserve logs"],finalAuditItems:["final service or VM is running if the verifier connects after completion","last positive client check happened after cleanup/negative tests","open port is backed by protocol-level success, not only socket readiness","protocol schemas, request fields, response fields, and VM control sockets match the verifier contract when applicable"]},{key:"search_symbolic",label:"search, symbolic, regex, or code-size",trigger:/\b(?:regex|regular expression|solver|constraint|backtracking|search|codegolf|shortest|smallest|fibonacci|circuit|sat|smt|brute\s*force|decompress|codec|round\s*trip)\b/i,verifierRequirements:["build a correctness oracle or counterexample generator before optimizing size or speed","checkpoint the best valid candidate to the required output before long searches","for regex/chess/legal-move tasks, compare against an independent oracle such as python-chess across provided PGN/FEN fixtures","cap search loops and pivot after repeated failures in the same direction"],finalAuditItems:["current best valid candidate is preserved at the submission path","randomized or adversarial fixtures ran against the final candidate","no known counterexample from the latest check remains unresolved"]},{key:"security_sanitization",label:"security, sanitization, archive, or certificate",trigger:/\b(?:xss|sanitize|html|javascript|script|payload|exploit|decrypt|archive|7z|zip|rar|hash|password|secret|credential|token|leak|git\s+repo|repository\s+cleanup|diff\s+scope|certificate|openssl|pem|tls)\b/i,verifierRequirements:["test harmful and clean/idempotent cases through the submitted entrypoint","use format-specific tooling before broad guessing for archives, hashes, and certificates","avoid regex-only sanitizers when parser or allowlist behavior is required","for repository secret cleanup, scan for remaining secrets and audit changed paths against the contaminated/allowed file set"],finalAuditItems:["clean inputs remain semantically unchanged when required","harmful/adversarial inputs are blocked by the final artifact","placeholder outputs such as UNKNOWN or TODO are absent","repository diff scope contains no unrelated clean-file modifications when the task asks for surgical cleanup"]},{key:"science_bio_numeric",label:"science, biosequence, or numeric fitting",trigger:/\b(?:dna|primer|protein|genome|melting|tm\b|oligotm|raman|spectrum|fit|curve|simulation|molecule|assembly|mjcf|robot)\b/i,verifierRequirements:["measure every stated numeric constraint using the specified calculator or an equivalent exact implementation","keep safety margin beyond hard thresholds and rerun validation on the final submitted artifact","for biological assembly, verify orientation, overhangs, circularity, translation, and sequence order end-to-end"],finalAuditItems:["final sequence/numeric file passes exact threshold calculations","no intermediate candidate is mistaken for the final artifact","round-trip or reconstruction checks cover the complete intended product"]},{key:"binary_recovery",label:"binary/ELF/recovery",trigger:/\b(?:elf|binary|disassembl|objdump|readelf|segment|memory|address|endianness|reverse\s*engineer)\b/i,verifierRequirements:["parse file-backed bytes and metadata, not only loader-expanded memory","validate address formats, endian handling, p_filesz/p_memsz boundaries, and exact JSON/value types","test on a second generated or varied sample when possible"],finalAuditItems:["final parser reads the required input file directly","output values match declared numeric/string formats","metadata and data-region boundary cases are covered"]},{key:"async_process",label:"async, signal, or process cleanup",trigger:/\b(?:async|asyncio|signal|sigterm|sigint|interrupt|cancel(?:lation)?|cleanup|terminate|shutdown|background\s+process|worker|taskgroup|semaphore)\b/i,verifierRequirements:["exercise the real interruption, signal, cancellation, or shutdown path through the submitted entrypoint","assert cleanup markers, drained finalizers, process termination, and exit behavior","include boundary cases around queued work or concurrency limits when mentioned"],finalAuditItems:["final entrypoint handles the same signal path the verifier will call","cleanup evidence comes from the submitted artifact, not only the validation harness","no orphaned process remains unless it is the required final service"]}];function fu(t){return t.trim().replace(/^[`'"]+|[`'"]+$/g,"").replace(/[.,;:)\]]+$/g,"").trim()}function hu(t){return!!(!t||/^[a-z][a-z0-9+.-]*:\/\//i.test(t)||t.startsWith("//"))}function Hr(t,e){let n=[],s=new Set;for(let r of t){let o=r.trim();if(!(!o||s.has(o))&&(s.add(o),n.push(o),n.length>=e))break}return n}function xb(t){let e=[];for(let n of Sb){let s;for(;(s=n.exec(t))!==null;){let r=fu(s[1]??"");hu(r)||e.push(r)}}return Hr(e,10)}function Pb(t,e){let n=new Set(e),s=t.match(vb)??[];return Hr(s.map(fu).filter(r=>!hu(r)&&!n.has(r)),10)}function Tb(t){return kb.filter(e=>e.trigger.test(t)).slice(0,6)}function gu(t){return/\b(?:terminal-bench|benchmark|hidden tests?|verifier|\/tests|test\.sh|run-tests\.sh|\/app)\b/i.test(t)}function _b(t,e,n){return e.length>0||n.length>0||gu(t)?!0:/\b(?:implement|fix|build|create|write|debug|optimi[sz]e|train|configure|recover|extract|convert|process|validate)\b/i.test(t)}function Rb(t,e){let n=t.some(r=>r.key==="ml_artifact"||r.key==="compiler_emulator"||r.key==="service_vm"||r.key==="search_symbolic"||r.key==="science_bio_numeric"),s=e||t.some(r=>r.key==="structured_data"||r.key==="visual_artifact"||r.key==="security_sanitization"||r.key==="binary_recovery"||r.key==="async_process");return n?[{name:"inspect",budgetPercent:15,objective:"extract the acceptance contract, toolchain, inputs, and verifier path before touching expensive work"},{name:"baseline",budgetPercent:15,objective:"create the smallest runnable baseline or measurement harness and write a checkpoint if an output path exists"},{name:"implement",budgetPercent:40,objective:"iterate on the candidate while keeping work bounded and evidence-driven"},{name:"validate",budgetPercent:20,objective:"run verifier-shaped checks against the final candidate and fix concrete failures only"},{name:"finalize",budgetPercent:10,objective:"restore final state, remove accidental temp artifacts, and preserve required outputs/services"}]:s?[{name:"inspect",budgetPercent:20,objective:"extract required outputs, fixtures, schema, and hidden-verifier assumptions"},{name:"baseline",budgetPercent:15,objective:"produce a narrow runnable baseline and a failing/passing local oracle"},{name:"implement",budgetPercent:35,objective:"implement the simplest general solution that satisfies the oracle"},{name:"validate",budgetPercent:20,objective:"read back artifacts and run adversarial, round-trip, or protocol checks"},{name:"finalize",budgetPercent:10,objective:"ensure the final filesystem/process state is exactly what the user or verifier will inspect"}]:[{name:"inspect",budgetPercent:20,objective:"understand the requested final state and available tests"},{name:"baseline",budgetPercent:10,objective:"make a small working baseline or reproduce the issue"},{name:"implement",budgetPercent:40,objective:"make the targeted change"},{name:"validate",budgetPercent:20,objective:"run the most relevant tests against the final state"},{name:"finalize",budgetPercent:10,objective:"clean temporary state and report only after validation"}]}function zr(t){let e=t?.trim()??"",n=xb(e),s=Pb(e,n),r=Tb(e),o=gu(e),i=_b(e,n,r),a=Rb(r,o),l=Hr([o?"check /tests, /test.sh, /run-tests.sh, README/instruction files, and prompt-provided commands early; if hidden, synthesize a contract-matched self-check":"look for existing tests or task-provided commands before writing custom checks",n.length>0?"write or preserve the best current candidate at each required output path before long-running work":"if a final artifact emerges, keep it in a stable path and validate that path","after any failed verifier/self-check, fix the first concrete failure and rerun the same check until a later passing signal supersedes it",...r.flatMap(u=>u.verifierRequirements)],12),c=Hr([...n.map(u=>`required output exists, is non-empty when applicable, and was read back: ${u}`),"latest validation ran after the last write to the submitted artifact","no known failed verifier, self-check, diff, build, or runtime signal remains unresolved","final filesystem/process state matches what the user or verifier will inspect after the agent exits",...r.flatMap(u=>u.finalAuditItems)],14);return{projectLike:i,hiddenVerifierLikely:o,requiredOutputs:n,referencedPaths:s,domains:r,phases:a,verifierRequirements:l,finalAuditItems:c}}function Fi(t){let e=zr(t);if(!e.projectLike)return"";let n=["","","# Project Execution Board","- Treat non-trivial coding/terminal work as a project with phases, a live contract, a current best candidate, and explicit final-state proof.","- Do not optimize for appearing done. Optimize for the final filesystem, process, service, or artifact state a verifier/user will inspect.",`- Phase budget: ${e.phases.map(s=>`${s.name} ${s.budgetPercent}%`).join(" -> ")}.`];for(let s of e.phases)n.push(`- ${s.name}: ${s.objective}.`);return e.requiredOutputs.length>0&&n.push(`- Required outputs to preserve early: ${e.requiredOutputs.join(", ")}.`),e.referencedPaths.length>0&&n.push(`- Reference/input paths to avoid overwriting unless required: ${e.referencedPaths.join(", ")}.`),e.domains.length>0&&n.push(`- Domain kits active: ${e.domains.map(s=>s.label).join(", ")}.`),n.push("","# Verifier Synthesis",...e.verifierRequirements.map(s=>`- ${s}.`),"","# Final-State Auditor",...e.finalAuditItems.map(s=>`- ${s}.`)),n.join(`
|
|
1148
|
+
`)}var Wr={official:6,project:5,user:4,self:3,smoke:2,syntax:1},bu=/\b(?:pytest|py\.test|unittest|npm\s+(?:test|run\s+test)|pnpm\s+(?:test|run\s+test)|yarn\s+test|cargo\s+test|go\s+test|make\s+(?:test|check)|ctest|run-tests?\.sh|test\.sh|verifier|verify|check)\b/i,Eb=/(?:^|\s)(?:\/tests\b|\/run-tests\.sh\b|\.\/run-tests?\.sh\b|\.\/test\.sh\b|test_outputs\.py\b|official\s+verifier|hidden\s+tests?|verifier\b)/i,ji=/\b(?:SELF_CHECK|CONTRACT|READBACK|ROUNDTRIP|SCHEMA|VALIDATION|VERIFIER)[_-]?(?:PASS|FAIL|FAILED|ERROR)\b/i,Cb=/(?:^|\s)(?:cat\s+>|tee\b|cp\b|mv\b|rm\b|touch\b|mkdir\b|sed\b.*\s-i\b|patch\b|apply_patch\b|npm\s+install|pip\s+install)\b|[>]{1,2}|\b(?:writeFileSync|open\s*\([^)]*,\s*["']w|Path\([^)]*\)\.write_text)\b/i,yu=[/\bFAILED\b/i,/\bFAILURES?\b/i,/\bAssertionError\b/i,/\bTraceback \(most recent call last\)/i,/\b(?:RuntimeError|ValueError|TypeError|SyntaxError|ModuleNotFoundError|ImportError)\b/i,/\b(?:mismatch|differs?|wrong output|does not match|not equal|not equivalent)\b/i,/\b(?:exit|status|return code|returncode)\s*[:=]?\s*[1-9]\d*\b/i,/\btimed?\s*out\b|\btimeout\b/i],Ab=[/\b(?:all\s+tests?\s+passed|all\s+checks?\s+passed|verifier\s+passed|validation\s+passed)\b/i,/\b(?:SELF_CHECK|CONTRACT|READBACK|ROUNDTRIP|SCHEMA|VALIDATION|VERIFIER)[_-]?PASS\b/i,/\b(?:0\s+failed|no\s+failures?|passed)\b/i,/\b(?:SUCCESS|successful|verified)\b/i];function Ib(t,e=500){return t.replace(/\r\n/g,`
|
|
1149
|
+
`).replace(/[ \t]+$/gm,"").trim().slice(0,e)}function Mb(t){return t.toLowerCase().replace(/\b0x[0-9a-f]+\b/g,"0x").replace(/\b\d+(?:\.\d+)?\b/g,"#").replace(/\s+/g," ").trim().slice(0,160)}function Xs(t){let e=t.command;return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function Ob(t,e,n){let s=Xs(e)??"";return/^Bash$/i.test(t)&&bu.test(s)||/^TaskOutput$/i.test(t)&&(bu.test(n)||ji.test(n))?!0:ji.test(n)}function $b(t,e,n){let s=Xs(e)??"",r=`${s}
|
|
1150
|
+
${n}`;return Eb.test(r)?"official":/\b(?:pytest|npm\s+(?:test|run\s+test)|pnpm\s+(?:test|run\s+test)|yarn\s+test|cargo\s+test|go\s+test|make\s+(?:test|check)|ctest)\b/i.test(s)?"project":ji.test(r)||/\bself[-_ ]?check\b/i.test(r)?"self":/\b(?:syntax|compile|lint|import)\b/i.test(r)?"syntax":/^Bash$/i.test(t)?"user":"smoke"}function Lb(t){let e,n,s=t.match(/(?:^|\s)(\d+)\s+failed\b/i),r=t.match(/(?:^|\s)(\d+)\s+passed\b/i);return s&&(e=Number.parseInt(s[1],10)),r&&(n=Number.parseInt(r[1],10)),{failed:e,passed:n}}function Nb(t,e){let n=t.replace(/\r\n/g,`
|
|
1151
|
+
`).split(`
|
|
1152
|
+
`),s=[];for(let o=0;o<n.length;o+=1){let i=n[o]??"";if(/^(?:FAILED|ERROR)\s+[\w./:-]+/i.test(i.trim())||yu.some(a=>a.test(i))){let a=n.slice(Math.max(0,o-1),Math.min(n.length,o+3)).join(`
|
|
1153
|
+
`);s.push(Ib(a,260))}}let r=new Map;for(let o of s.slice(0,12)){let i=Mb(o);if(!i)continue;let a=r.get(i);if(a){a.count+=1,a.latestExcerpt=o,a.lastIteration=e;continue}r.set(i,{signature:i,title:o.split(`
|
|
1154
|
+
`).find(l=>l.trim().length>0)?.trim().slice(0,140)??"Validation failure",count:1,firstIteration:e,lastIteration:e,latestExcerpt:o})}return[...r.values()]}function Bb(t,e){let n=Lb(e);return n.failed!==void 0&&n.failed>0?{outcome:"fail",failureCount:n.failed,...n.passed!==void 0?{passCount:n.passed}:{},summary:`${n.failed} pytest failure(s)${n.passed!==void 0?`, ${n.passed} passed`:""}`}:t.success===!1||yu.some(s=>s.test(e))?{outcome:"fail",summary:t.error?`Command failed: ${t.error}`:"Validation output contains failure evidence"}:n.passed!==void 0&&n.passed>0?{outcome:"pass",passCount:n.passed,summary:`${n.passed} pytest test(s) passed`}:Ab.some(s=>s.test(e))?{outcome:"pass",summary:"Validation output contains pass evidence"}:{outcome:"unknown",summary:t.success?"Validation-like command produced no clear pass/fail signal":"Command failed without parseable validation signal"}}function Db(t,e,n){if(!n.success)return!1;if(/^(?:Write|Edit|NotebookEdit|MemoryWrite)$/i.test(t))return!0;let s=Xs(e);return/^Bash$/i.test(t)&&!!s&&Cb.test(s)}function Ui(t){return Wr[t.authority]>=Wr.project}function Xr(t){let e=t.taskPrompt??"";return t.benchmarkMode||(t.requiredOutputPaths??[]).length>0?!0:/\b(?:test|tests|pytest|verifier|benchmark|hidden\s+tests?|build|fix|implement|debug|\/app|run-tests?\.sh)\b/i.test(e)}var Ks=class{contract;signals=[];clusters=new Map;toolCalls=0;workspaceRevision=0;lastCompletionDecision=null;lastValidationIteration=null;lastEvaluatedIteration=null;constructor(e={}){let n=e.taskPrompt??"",s=[...e.requiredOutputPaths??[]],r=e.benchmarkMode===!0||s.length>0||/\b(?:test|tests|pytest|verifier|hidden\s+tests?|run-tests?\.sh|official|validate|validation)\b/i.test(n);this.contract={projectLike:Xr(e),benchmarkMode:e.benchmarkMode===!0,requiredOutputPaths:s,requiredValidation:r}}recordToolResult(e){if(this.toolCalls+=1,Db(e.toolName,e.input,e.result)){this.workspaceRevision+=1;for(let i of this.signals)i.stale=!0}let n=`${e.result.output??""}
|
|
1155
|
+
${e.result.error??""}`;if(!Ob(e.toolName,e.input,n))return[];let s=$b(e.toolName,e.input,n),r=Bb(e.result,n),o={id:`validation-${this.signals.length+1}`,iteration:e.iteration,toolName:e.toolName,...Xs(e.input)?{command:Xs(e.input)}:{},authority:s,outcome:r.outcome,stale:!1,workspaceRevision:this.workspaceRevision,summary:r.summary,...r.failureCount!==void 0?{failureCount:r.failureCount}:{},...r.passCount!==void 0?{passCount:r.passCount}:{},clusters:r.outcome==="fail"?Nb(n,e.iteration):[]};this.signals.push(o),this.lastValidationIteration=e.iteration;for(let i of o.clusters){let a=this.clusters.get(i.signature);if(a){a.count+=i.count,a.lastIteration=i.lastIteration,a.latestExcerpt=i.latestExcerpt;continue}this.clusters.set(i.signature,{...i})}return[o]}evaluateCompletion(e){this.lastEvaluatedIteration=e.iteration;let n=this.getLatestUnresolvedFailure(),s=this.getLatestAuthoritativeSignal();if(n){let r=this.getRepeatedFailure(),o=["Do not finish yet. The latest authoritative validation signal is still failing.",`Latest failure: ${n.summary}.`,r?`Repeated failure signature detected (${r.count}x): ${r.title}`:"Use the concrete failure output, make the smallest targeted repair, then rerun the same verifier-shaped check.","A self-check pass or candidate note cannot supersede a later project/official failure."].join(`
|
|
1156
|
+
`);return this.setDecision({action:e.stopReason==="max_iterations"?"incomplete":"continue",finalStateVerified:!1,reason:"authoritative_validation_failed",message:o,blocking:!0,unresolvedFailures:n.clusters,latestAuthoritativeSignal:s})}if(s?.outcome==="pass"&&!s.stale)return this.setDecision({action:"complete",finalStateVerified:!0,reason:"authoritative_validation_passed",message:"Latest authoritative validation passed after the current workspace revision.",blocking:!1,unresolvedFailures:[],latestAuthoritativeSignal:s});if(this.contract.requiredValidation&&e.stopReason!=="progress_checkpoint"){let r=this.getLatestSignal(),o=r?.outcome==="pass"&&!Ui(r),i=["Do not finish yet. This task requires authoritative validation evidence.",o?"The latest pass signal is only a self/smoke check; run the project test, verifier, or strongest exposed validation command.":"Run the project test, verifier, or strongest exposed validation command and fix concrete failures before answering."].join(`
|
|
1157
|
+
`);return this.setDecision({action:e.stopReason==="max_iterations"?"incomplete":"continue",finalStateVerified:!1,reason:o?"weak_validation_only":"missing_authoritative_validation",message:i,blocking:!0,unresolvedFailures:[],latestAuthoritativeSignal:s})}return this.setDecision({action:"complete",finalStateVerified:!1,reason:"no_governance_blocker",message:"No execution-governance blocker found.",blocking:!1,unresolvedFailures:[],latestAuthoritativeSignal:s})}getSummary(){return{contract:{...this.contract,requiredOutputPaths:[...this.contract.requiredOutputPaths]},validation:{latestSignal:this.cloneSignal(this.getLatestSignal()),latestAuthoritativeSignal:this.cloneSignal(this.getLatestAuthoritativeSignal()),latestUnresolvedFailure:this.cloneSignal(this.getLatestUnresolvedFailure()),signals:this.signals.slice(-20).map(e=>this.cloneSignal(e))},progress:{toolCalls:this.toolCalls,validationRuns:this.signals.length,workspaceRevision:this.workspaceRevision,repeatedFailureSignature:this.getRepeatedFailure()?.signature??null,repeatedFailureCount:this.getRepeatedFailure()?.count??0,iterationsSinceLastValidation:this.lastValidationIteration===null?null:Math.max(0,(this.lastEvaluatedIteration??this.lastValidationIteration)-this.lastValidationIteration)},completionDecision:this.lastCompletionDecision?{...this.lastCompletionDecision}:null}}getLatestSignal(){return this.signals.at(-1)??null}getLatestAuthoritativeSignal(){return[...this.signals].reverse().find(e=>Ui(e))??null}getLatestUnresolvedFailure(){let e=[...this.signals].reverse().find(s=>Ui(s)&&s.outcome==="fail"&&!s.stale);return e?this.signals.some(s=>s.iteration>e.iteration&&!s.stale&&s.outcome==="pass"&&Wr[s.authority]>=Wr[e.authority])?null:e:null}getRepeatedFailure(){let e=null;for(let n of this.clusters.values())n.count<2||(!e||n.count>e.count)&&(e=n);return e}setDecision(e){return this.lastCompletionDecision=e,e}cloneSignal(e){return e?{...e,clusters:e.clusters.map(n=>({...n}))}:null}};var Fb=/\b(?:installed|install(?:ed)?|on\s+(?:my|this)\s+(?:machine|pc|computer|system)|cli|command(?:\s+line)?|executable|on\s+(?:the\s+)?path|version|where(?:\.exe)?|which|available)\b/i,Ub=/\b(?:Get-Command|where(?:\.exe)?|command\s+-v|which|type\s+-a?|--version|-v\b|--help|-h\b)\b/i,jb=/\b(?:yes|installed|you\s+(?:have|do\s+have)|found|available|on\s+(?:your|the)\s+path|callable|working|responds?|verified|confirmed)\b/i,Vb=/\b(?:cannot\s+confirm|can't\s+confirm|not\s+confirm(?:ed)?|not\s+proven|not\s+verified|uncertain|failed|fails|could\s+not\s+verify|not\s+installed|does\s+not\s+appear|isn't\s+available|not\s+available)\b/i,qb=/\b(?:exit\s+code|exit\s+status|status|return\s+code|returncode)\s*[:= -]?\s*(?:-[1-9]\d*|[1-9]\d*)\b|\b(?:not\s+recognized|not\s+found|could\s+not\s+find|cannot\s+find|no\s+such\s+file|failed)\b/i,Hb=/\b(?:official|docs?|documentation|source|reference|install(?:ation)?|supported|features?|commands?)\b/i,zb=/\b(?:search\s+online|look\s+online|web\s+search|web\s+fetch|fetch\s+(?:the\s+)?(?:official\s+)?page|official|docs?|documentation|source|reference|summarize|url)\b/i,Wb=/\b(?:HTTP\s+404|404\s+Not\s+Found|not\s+found|does\s+not\s+exist|gone|HTTP\s+410|410\s+Gone)\b/i,Xb=/\b(?:curl|wget|Invoke-WebRequest|Invoke-RestMethod|iwr|irm)\b[\s\S]*https?:\/\/|\bpython(?:3|\.exe)?\b[\s\S]*\b(?:urllib\.request|requests\.get|http\.client)\b[\s\S]*https?:\/\/|\bnode(?:\.exe)?\b[\s\S]*\b(?:fetch|https\.get|axios)\b[\s\S]*https?:\/\//i,Kb=/https?:\/\/[^\s)>\]]+/i;function Vi(t){return t.trim().replace(/\s+/g," ")}function Gb(t){if(typeof t!="string")return null;let e=Vi(t).toLowerCase();return e.length>0?e:null}function wu(t){if(typeof t!="string")return null;try{let e=new URL(t);return e.hash="",e.pathname=e.pathname.replace(/\/+$/,"")||"/",e.toString().toLowerCase()}catch{let e=Vi(t).toLowerCase().replace(/#.*$/,"").replace(/\/+$/,"");return e.length>0?e:null}}function vu(t){let e=t.command;return typeof e=="string"&&e.trim().length>0?e.trim():null}function Su(t){return Vi([t.output,t.error].filter(Boolean).join(" ")).slice(0,240)}function Yb(t){return t.success===!1||qb.test([t.output,t.error].filter(Boolean).join(`
|
|
1158
|
+
`))}function ku(t){return/^Bash$/i.test(t)}function xu(t){return/^WebSearch$/i.test(t)}function Pu(t){return/^WebFetch$/i.test(t)}var Gs=class{taskPrompt;maxWebSearches;maxWebFetches;maxTotalWebResearchCalls;searchQueries=new Map;fetchedUrls=new Map;localEvidence=[];webFetchEvidence=[];webSearches=0;webFetches=0;constructor(e,n={}){this.taskPrompt=e,this.maxWebSearches=Math.max(1,n.maxWebSearches??3),this.maxWebFetches=Math.max(1,n.maxWebFetches??4),this.maxTotalWebResearchCalls=Math.max(1,n.maxTotalWebResearchCalls??6)}maybeBlockToolCall(e){if(ku(e.toolName)&&this.isWebResearchQuestion()){let n=vu(e.input);if(n&&Xb.test(n))return this.blockedResult(["[Xeno interactive research guard]","Do not use Bash, Python, PowerShell, curl, wget, or ad hoc scripts to fetch public web pages during a web-research turn.","Use WebSearch to discover sources and WebFetch to read exact URLs. WebFetch handles timeouts, redirects, readable extraction, source metadata, and discovered documentation links.",this.fetchedSourceSummary()])}if(xu(e.toolName)){let n=Gb(e.input.query),s=n?this.searchQueries.get(n)??0:0;if(this.shouldStopOfficialResearch())return this.blockedResult(["[Xeno interactive research guard]","Official web evidence has already been fetched this turn.",this.fetchedSourceSummary(),"Stop searching. Answer now from the fetched official source(s), naming the URL(s) used and clearly stating any remaining uncertainty."]);if(n&&s>0)return this.blockedResult(["[Xeno interactive research guard]",`The WebSearch query has already been run this turn: ${n}`,"Do not repeat equivalent searches. Use the existing search result, fetch one clearly relevant source, run a local verification command if the question is about this machine, or answer with the uncertainty that remains."]);if(this.webSearches>=this.maxWebSearches||this.totalWebResearchCalls()>=this.maxTotalWebResearchCalls)return this.blockedResult(["[Xeno interactive research guard]",`The per-turn web-search budget is exhausted (${this.webSearches}/${this.maxWebSearches} searches, ${this.totalWebResearchCalls()}/${this.maxTotalWebResearchCalls} total web calls).`,"Stop broad web exploration. Prefer official documentation already found, run a local check if relevant, or give a bounded answer that states what is and is not verified."]);this.webSearches+=1,n&&this.searchQueries.set(n,s+1)}if(Pu(e.toolName)){let n=wu(e.input.url),s=n?this.fetchedUrls.get(n)??0:0;if(this.shouldStopOfficialResearch())return this.blockedResult(["[Xeno interactive research guard]","Enough official web evidence has already been fetched this turn.",this.fetchedSourceSummary(),"Do not guess more nearby documentation URLs. Answer from the fetched source(s), cite the URL(s), and mention if a specific detail was not present."]);if(n&&s>0)return this.blockedResult(["[Xeno interactive research guard]",`This URL has already been fetched this turn: ${n}`,"Do not fetch the same page again. Use the existing content, fetch a more precise official source, run a local verification command if relevant, or answer with the uncertainty that remains."]);if(this.webFetches>=this.maxWebFetches||this.totalWebResearchCalls()>=this.maxTotalWebResearchCalls)return this.blockedResult(["[Xeno interactive research guard]",`The per-turn web-fetch budget is exhausted (${this.webFetches}/${this.maxWebFetches} fetches, ${this.totalWebResearchCalls()}/${this.maxTotalWebResearchCalls} total web calls).`,"Stop broad web exploration. Use the best source already gathered, run a local check if relevant, or answer with a clear limitation."]);this.webFetches+=1,n&&this.fetchedUrls.set(n,s+1)}return null}recordToolResult(e){if(xu(e.toolName))return;if(Pu(e.toolName)){let r=wu(e.input.url);r&&this.webFetchEvidence.push({iteration:e.iteration,url:r,success:e.result.success===!0,summary:Su(e.result)});return}if(!ku(e.toolName)||!this.isLocalSetupQuestion())return;let n=vu(e.input);if(!n||!Ub.test(n))return;let s=Yb(e.result);this.localEvidence.push({iteration:e.iteration,command:n,success:e.result.success===!0&&!s,summary:Su(e.result)})}evaluateCompletion(e){if(this.isWebResearchQuestion()){let o=this.evaluateWebResearchCompletion(e.finalText);if(o)return o}if(!this.isLocalSetupQuestion())return null;let n=[...this.localEvidence].reverse().find(o=>!o.success);if(!n||this.localEvidence.some(o=>o.iteration>=n.iteration&&o.success))return null;let r=e.finalText.trim();return!r||!jb.test(r)||Vb.test(r)?null:{blocking:!0,message:["[Xeno evidence correction]","Do not claim the local tool/app/CLI is installed or working yet.",`The latest local verification command failed: ${n.command}`,n.summary?`Failure evidence: ${n.summary}`:null,"Next step: either run one robust local verification command that directly proves the claim, or answer that the launcher/path may exist but the CLI status is not confirmed.","Do not use web documentation as proof of what is installed on this machine."].filter(Boolean).join(`
|
|
1159
|
+
`)}}evaluateWebResearchCompletion(e){let n=e.trim();if(!n)return null;let s=this.successfulWebFetches(),r=s.map(a=>a.url),o=Kb.test(n),i=r.some(a=>n.toLowerCase().includes(a.toLowerCase()));return s.length>0&&(!o||!i)?{blocking:!0,message:["[Xeno source-citation correction]","The answer uses web/documentation evidence but does not clearly cite the fetched source URL(s).",this.fetchedSourceSummary(),"Rewrite the final answer with a short Sources section listing the exact URLs used, then the requested sections. Do not run more tools unless a required detail is still missing."].join(`
|
|
1160
|
+
`)}:null}isLocalSetupQuestion(){return Fb.test(this.taskPrompt)}totalWebResearchCalls(){return this.webSearches+this.webFetches}isOfficialResearchQuestion(){return Hb.test(this.taskPrompt)}isWebResearchQuestion(){return zb.test(this.taskPrompt)}successfulWebFetches(){return this.webFetchEvidence.filter(e=>e.success)}failedSpeculativeWebFetches(){return this.webFetchEvidence.filter(e=>!e.success&&Wb.test(e.summary))}shouldStopOfficialResearch(){if(!this.isOfficialResearchQuestion())return!1;let e=this.successfulWebFetches();return e.length>=this.minimumOfficialEvidenceFetches()?!0:e.length>=1&&this.failedSpeculativeWebFetches().length>=1}minimumOfficialEvidenceFetches(){let e=this.taskPrompt.toLowerCase(),n=/\binstall(?:ation)?|update|upgrade|version|verify\b/.test(e),s=/\binteractive|usage|using|agent\s+commands?|session|resume|flags?|shortcuts?\b/.test(e),r=/\bslash|reference|commands?\s+list|all\s+commands?\b/.test(e);return n&&s||r?Math.min(4,this.maxWebFetches):2}fetchedSourceSummary(){let e=this.successfulWebFetches().map(n=>n.url);return e.length===0?"No successful web fetch is recorded yet.":`Fetched source(s): ${e.join(", ")}`}blockedResult(e){return{success:!1,output:e.join(`
|
|
1161
|
+
`),error:"Interactive research guard blocked redundant or excessive web research"}}};var Tu=String.raw`(?:^|[\n;&|]\s*|\(\s*)`,Jb=new RegExp(String.raw`${Tu}(?:timeout\s+\S+\s+)?(?:sudo\s+)?eval\s+(?:"|'|)?\$\(\s*(?:curl|wget)\b`,"i"),Qb=new RegExp(`${Tu}(?:timeout\\s+\\S+\\s+)?(?:sudo\\s+)?(?:env\\s+(?:\\S+=\\S+\\s+)*)?(?:make(?:\\s|$)|cmake\\s+--build\\b|ninja\\b|cargo\\s+build\\b|go\\s+build\\b)`,"i"),Zb=/\b(?:make|ninja|cmake\s+--build)\b[\s\S]*?(?:^|\s)-j\s*(?:\$\(?nproc\)?|[5-9]\b|\d{2,}\b)/i,ey=900,ty=/\b(?:cifar(?:-?10)?|mnist|imagenet|yelp|fasttext|wikitext|c4|common\s*crawl|glue|squad|train(?:ing)?[_ -]?data|test[_ -]?data|lmdb)\b/i,ny=/\b(?:synthetic|fake|dummy|placeholder|random(?:\.|_|ness|\b)|randint|randn|np\.random|os\.urandom|bytearray|generate(?:d|s)?\s+(?:data|dataset|samples?|images?|records?)|make_img|SYNTHETIC[_ -]?DATA)\b/i,sy=/\b(?:>\s*|tee\s+|open\s*\(|write(?:_text|_bytes)?\s*\(|to_csv\s*\(|np\.save|torch\.save|pickle\.dump|lmdb|create[_ -]?(?:dataset|data)|mkdir(?:\s+-p)?|rm\s+-rf)\b/i,ry=/\btimeout\s+(\d+)([smhd]?)/i;function oy(t){let e=t.command;return typeof e=="string"&&e.trim().length>0?e.trim():null}function iy(t){return/^Bash$/i.test(t)}function ay(t){let e=t.match(ry);if(!e)return null;let n=Number(e[1]);if(!Number.isFinite(n))return null;let s=e[2]?.toLowerCase();return s==="h"?n*3600:s==="m"?n*60:s==="d"?n*86400:n}function ly(t){if(!Qb.test(t))return null;if(Zb.test(t))return["[xeno guidance]","This finite source build uses an unbounded or oversized parallelism setting such as -j$(nproc).","In benchmark containers this often slows the build down or causes timeout/memory failure instead of making progress.","Rerun the build with conservative parallelism such as -j2 or -j4, keep logs visible, and continue from the existing partial build artifacts."].join(`
|
|
1162
|
+
`);let e=ay(t);return e!==null&&e<ey?["[xeno guidance]",`This required finite build is wrapped in a shell timeout of ${e}s.`,"Do not use a too-short shell timeout around source builds where partial output is not the final artifact.","Use the Bash tool timeout instead, run with conservative parallelism such as -j2 or -j4, and preserve final budget for verifier/training only after the build succeeds."].join(`
|
|
1163
|
+
`):null}function cy(t){return!ty.test(t)||!ny.test(t)||!sy.test(t)?null:["[xeno guidance]","This command appears to synthesize or overwrite a named/provided training dataset.","Do not replace CIFAR, MNIST, Yelp, C4, LMDB, or other task datasets with random, synthetic, dummy, or placeholder data to recover from a crash.","Fix the real data path instead: repair the download/extraction/conversion/dependency issue, remove corrupted partial outputs, and rerun only the failed stage with bounded resources."].join(`
|
|
1164
|
+
`)}function uy(t){return Jb.test(t)}function dy(){return{success:!1,output:["[Xeno benchmark Bash guard]",'Blocked a shell-eval-download command (eval "$(curl \u2026)" / eval "$(wget \u2026)").',"Piping remote content straight into a shell evaluator is unsafe and non-reproducible.","Download the artifact to a file with WebFetch or curl/wget, inspect it, then run the verified script explicitly."].join(`
|
|
1165
|
+
`),error:"Benchmark Bash guard blocked a shell-eval-download command"}}function qi(t={}){let e=t.benchmarkMode===!0;return async(n,s)=>{if(!iy(n.toolName))return s();let r=oy(n.input);if(!r)return s();if(uy(r))return dy();if(e){let o=ly(r);o&&n.addGuidance(o);let i=cy(r);i&&n.addGuidance(i)}return s()}}var _u=`
|
|
1166
|
+
|
|
1167
|
+
`;function Ru(t){let e=t.taskPrompt??"",n=t.benchmarkMode===!0,s=t.requiredOutputPaths??[],r=t.interactiveTurnGovernance===!1?null:new Gs(e,t.interactiveTurnGovernance??{}),i=(t.executionGovernance===!1?!1:t.executionGovernance===!0||Xr({taskPrompt:e,benchmarkMode:n,requiredOutputPaths:s}))?new Ks({taskPrompt:e,benchmarkMode:n,requiredOutputPaths:s}):null,a=i?.getSummary()??null,l=[];(r||i)&&l.push(async(p,f)=>{if(r){let g=r.maybeBlockToolCall({toolName:p.toolName,input:p.input,iteration:p.iteration});if(g)return g}let m=await f();return r&&r.recordToolResult({toolName:p.toolName,input:p.input,result:m,iteration:p.iteration}),i&&(i.recordToolResult({toolName:p.toolName,input:p.input,result:m,iteration:p.iteration}),a=i.getSummary(),t.onExecutionGovernanceUpdate?.(a)),m}),l.push(qi({benchmarkMode:n}));let c=[];r&&c.push({name:"interactive-turn-governance",order:10,evaluate(p){let f=r.evaluateCompletion({finalText:p.finalText,iteration:p.iteration,stopReason:p.stopReason});return f?{allow:!1,guidance:f.message}:{allow:!0}}}),i&&c.push({name:"execution-governance",order:20,evaluate(p){let f=i.evaluateCompletion({finalText:p.finalText,iteration:p.iteration,stopReason:p.stopReason,messages:p.messages,maxIterations:p.maxIterations});if(a=i.getSummary(),t.onExecutionGovernanceUpdate?.(a),f.action==="complete"||!f.blocking)return{allow:!0};let m=f.action==="incomplete";return{allow:!1,guidance:f.message,stop:m}}});let u=[];return t.promptGuidance!==!1&&(u.push({name:"contract-ledger",order:100,provide(p){let f=Di(p.taskPrompt??e);return f?`${_u}${f.replace(/^\n+/,"")}`:null}}),u.push({name:"project-execution",order:110,provide(p){let f=Fi(p.taskPrompt??e);return f?`${_u}${f.replace(/^\n+/,"")}`:null}})),{toolMiddleware:l,promptSections:u,completionGuards:c,getExecutionGovernanceSummary:()=>a}}var my=/\blive benchmark task container\b|\bterminal-bench\b/i,fy=/(?:^|[\s("'`])(?:\/tests\b|\/run-tests\.sh\b|\.\/run-tests\.sh\b|\.\/test\.sh\b|test\.sh\b|run-tests\.sh\b|pytest\b|unittest\b|verifier\b)/i,hy=/(?:^|\n)\s*(?:EXISTS|FOUND|AVAILABLE|PRESENT|PATH|FILE|DIR|DIRECTORY|VERIFIER)\s*:?\s*(?:\/tests\b|\/run-tests\.sh\b|\.\/run-tests\.sh\b|\.\/test\.sh\b|test_outputs\.py\b|run-tests\.sh\b|test\.sh\b)/im,gy=/\b(?:run|execute|use|invoke|call)\b[^\n]{0,120}(?:\/tests\b|\/run-tests\.sh\b|\.\/run-tests\.sh\b|\.\/test\.sh\b|test_outputs\.py\b|run-tests\.sh\b|test\.sh\b|pytest\b|unittest\b|verifier\b)/i,by=/\b(?:optimi[sz]e|speed\s*up|make\s+(?:it|this|that|the\s+[\w.-]+)\s+faster|reduce\s+(?:runtime|latency|execution\s+time|wall\s*time)|lower\s+(?:runtime|latency)|improve\s+(?:query\s+)?(?:runtime|latency|throughput|speed)|minimi[sz]e\s+(?:runtime|latency|time)|must\s+(?:run|complete|finish)\s+(?:within|under|in\s+less\s+than)|(?:runtime|latency|throughput|speed|performance)\s+(?:target|budget|requirement|benchmark|limit)|faster\s+than|under\s+\d+(?:\.\d+)?\s*(?:ms|msec|s|sec|secs|seconds?|minutes?|min)\b)\b/i,yy=/\b(?:sqlite|sql query|query)\b/i,wy=/\b(?:async|signal|sigterm|sigint|interrupt|cancel(?:lation)?|cleanup|terminate|shutdown|background\s+process|worker|daemon)\b/i,vy=/\b(?:server|service|daemon|webserver|http|https|localhost|port\s+\d+|ssh|sshd|git\s+(?:server|clone|push|receive|upload)|nginx|apache|grpc|protobuf|proto\b|rpc|request|response|client|socket|qemu|vm|virtual\s+machine|emulator|vnc|serial|monitor)\b/i,Sy=/\b(?:grpc|protobuf|proto\b|rpc|request\s+message|response\s+message|client\s+stub|schema|endpoint|api\s+contract)\b/i,ky=/\b(?:qemu|vm|virtual\s+machine|windows\s+3\.11|emulator|vnc|serial|monitor\s+socket|qmp|sendkey|framebuffer|screenshot)\b/i,xy=/\b(?:7z|7-zip|zip|rar|archive|encrypted|decrypt|passphrase|password|crack|john|hash|secret_file)\b/i,Py=/\b(?:xss|sanitize|saniti[sz]er|remove\s+javascript|javascript\s+from\s+html|harmful\s+substrings?|dangerous\s+attributes?|html\s+filter|script\s+tags?|on(?:error|load|click|mouseover)\s*=|javascript:|srcdoc)\b/i,Ty=/\b(?:git|repo(?:sitory)?|commit|branch|working\s+tree|diff)\b[\s\S]{0,500}\b(?:secret|credential|token|leak|sanitize|clean|contaminated|remove|redact)\b|\b(?:secret|credential|token|leak|sanitize|clean|contaminated|remove|redact)\b[\s\S]{0,500}\b(?:git|repo(?:sitory)?|commit|branch|working\s+tree|diff)\b|\bno\s+other\s+files\s+changed\b/i,_y=/\b(?:convert|conversion|csv|tsv|parquet|arrow|jsonl?|dataframe|table|tabular)\b/i,Ry=/\b(?:dna|primer|protein|genome|melting|tm\b|oligotm|gblock|donor|acceptor|dhfr|snap|raman|spectrum|lorentzian|curve[_ -]?fit|peak|residual|mjcf|mujoco|simulation|eigen(?:value|val)?|numeric|threshold|parameter\s+fit)\b/i,Ki=/\b(?:csv|tsv|parquet|arrow|jsonl?|dataframe)\b/i,Ey=/\b(?:convert|conversion|export|import|reshard|compress|decompress)\b/i,Cy=/\b(?:parquet|arrow|dataframe)\b/i,Ay=/\b(?:script|program|cli|argparse|command)\b[\s\S]{0,700}\b(?:csv|tsv|jsonl|output[_ -]?path|output\s+file|save|saves|saved|write|writes|wrote|written)\b|\b(?:csv|tsv|jsonl|output[_ -]?path|output\s+file|save|saves|saved|write|writes|wrote|written)\b[\s\S]{0,700}\b(?:script|program|cli|argparse|command)\b/i,Iy=/\b(?:python\s+script|script|program|cli|argparse|command)\b/i,My=/\b(?:output[_ -]?path|output\s+file|output\s+folder|save(?:d|s)?|write(?:s|n|ten)?|csv_path|jsonl_path)\b/i,Eu=/\b(?:coords_[xy]|columns?|rows?|metadata|schema|list(?:s|ed)?|array|polyline|json|csv|tsv|output_path)\b/i,Oy=/\b(?:vim|apply_macros\.vim|setreg|normal!\s*@[a-z]|keystroke-efficient|macro recording|headlessly)\b/i,$y=/\b(?:synonyms\.txt|only\s+(?:modify|change|replace)\s+(?:words?|tokens?)|must\s+only\s+(?:modify|change|replace)|do\s+not\s+(?:add|remove|delete)\s+(?:words?|tokens?)|preserve\s+(?:the\s+)?(?:token|word)\s+count|same\s+(?:token|word)\s+count|modified\s+\w+\.\w+\s+must\s+only\s+modify)\b/i,Ly=/\b(?:model|weights?|checkpoint|ckpt|onnx|torch|pytorch|tensorflow|keras|mnist|cifar|fasttext|embedding|inference|prediction|classif(?:y|ication)|logits?|tokeni[sz]er|gpt-?2|neural|train(?:ing)?)\b/i,Ny=/\b(?:provided|pretrained|existing|saved|loaded|recover(?:y|ed)?|extract(?:ion|ed)?|weights?|checkpoint|ckpt|onnx|\.pt\b|\.pth\b|model\.bin|state[_ -]?dict|logits?|tokeni[sz]er|vocab|bpe)\b/i,By=/\b(?:extract|extraction|recover|recovery|reconstruct|steal|stolen|infer|identify)\b[\s\S]{0,260}\b(?:matrix|matrices|rows?|columns?|weights?|parameters?|logits?|relu|rank|layers?|neurons?)\b|\b(?:matrix|matrices|rows?|columns?|weights?|parameters?|logits?|relu|rank|layers?|neurons?)\b[\s\S]{0,260}\b(?:extract|extraction|recover|recovery|reconstruct|steal|stolen|infer|identify)\b/i,Dy=/\b(?:gpt-?2|language\s+model|continu(?:e|ation|ations)|completion|next\s+\d+\s+tokens?|prompt(?:s)?\b[\s\S]{0,160}\b(?:tokens?|completion|continuation)|tokeni[sz]er|vocab\.bpe|bpe)\b/i,Fy=/\b(?:image|video|frame|opencv|cv2|ffmpeg|ocr|render|raster|pixel|sprite|diagram|gcode|g-code|path\s*tracing|ray\s*tracing|toml|takeoff|landing|move\s+extraction)\b/i,Uy=/\b(?:path\s*tracing|ray\s*tracing|image\s+similarity|reverse\s+(?:render(?:ing)?|engineer(?:ing)?|image)|recreate|match(?:es|ed|ing)?\s+(?:the\s+)?(?:target|reference|image|render)|target\s+image|reference\s+image)\b/i,Zu=/\b(?:decode|decipher|read|recover|extract|identify|show|prints?|printed|printing)\b[\s\S]{0,240}\b(?:flag|text|token|string|message|word|answer)\b|\b(?:flag|text|token|string|message|word|answer)\b[\s\S]{0,240}\b(?:image|video|frame|render|raster|pixel|gcode|g-code|geometry|artifact|prints?|printed|printing|show)\b/i,jy=/\b(?:compile|compiler|cross-?compile|gcc|clang|cargo|rustc|make|cmake|ninja|mips|riscv|x86|arm|kernel|qemu|emulator|interpreter|polyglot|doom|windows\s+3\.11|assembly|linker)\b/i,Vy=/\b(?:compiled\s+(?:program|binary)|decompil(?:e|ed|ing)|reverse[- ]?engineer(?:ing)?|identical\s+operation|same\s+(?:behavior|behaviour|output|operation)|fully\s+independent|complete\s+isolation|reimplementation|reimplement)\b/i,qy=/\b(?:compress|compressor|decompress|codec|encode|decode|codegolf|under\s+\d+\s*(?:bytes?|kb|kilobytes?)|size\s+limit|smallest|search|solver|backtracking|constraint|regex|regular expression|filters?|filtering)\b/i,Hy=/\b(?:regex|regular expression|replacement)\b[\s\S]{0,360}\b(?:chess|legal\s+moves?|FEN|PGN)|\b(?:chess|legal\s+moves?|FEN|PGN)\b[\s\S]{0,360}\b(?:regex|regular expression|replacement)\b/i,zy=/\b(?:python-chess|chess\.Board|legal_moves|legal\s+moves?|FEN|PGN|oracle)\b[\s\S]{0,360}\b(?:all\s+passed|pass(?:ed)?|matches?|0\s+(?:failures|mismatches)|mismatches?\s*[:=]\s*0|positions?\s*[:=]\s*(?:[2-9]|\d{2,}))\b|\b(?:all\s+passed|pass(?:ed)?|matches?|0\s+(?:failures|mismatches)|mismatches?\s*[:=]\s*0|positions?\s*[:=]\s*(?:[2-9]|\d{2,}))\b[\s\S]{0,360}\b(?:python-chess|chess\.Board|legal_moves|legal\s+moves?|FEN|PGN|oracle)\b/i,Wy=/\b(?:elf|compiled\s+c\s+binary|binary)\b[\s\S]{0,600}\b(?:memory\s+(?:values?|addresses?)|addresses?\s+as\s+keys|json\s+object|extract\s+memory)\b/i,Xy=/\binstall(?:ed|ing)?\b[\s\S]{0,240}\b(?:package|dependency|dependencies|library|module|tool|runtime|framework|cran|pip|npm|apt|rstan|cmdstan|caffe|fasttext|mujoco)\b|\b(?:package|dependency|dependencies|library|module|tool|runtime|framework|cran|pip|npm|apt|rstan|cmdstan|caffe|fasttext|mujoco)\b[\s\S]{0,240}\binstall(?:ed|ing)?\b/i,Ky=/\b(?:Rscript|R)\b[\s\S]{0,260}\b(?:library\s*\(|requireNamespace\s*\(|packageVersion\s*\()|\bpython(?:3)?\b[\s\S]{0,220}\b(?:import\s+[A-Za-z_][\w.]*|importlib\.import_module|pkg_resources|get_distribution|metadata\.version)|\bnode\b[\s\S]{0,220}\b(?:require\s*\(|import\s*\(|package\.json)|\b(?:pip|pip3|python(?:3)?\s+-m\s+pip)\s+(?:show|freeze|list)\b|\b(?:npm|pnpm|yarn)\s+(?:ls|list|why)\b|\b(?:dpkg\s+-s|apt-cache\s+policy|command\s+-v|which)\b/i,Gy=/\b(?:PACKAGE_INSTALL|DEPENDENCY|IMPORT|LIBRARY|MODULE|TOOL|VERSION)[_-]?PASS\b|\b(?:loaded|available|installed|found|version|packageVersion)\b|(?:^|\s)(?:true|TRUE)(?:\s|$)|\b\d+\.\d+(?:\.\d+)?\b/i,Yy=/\b(?:there is no package called|package\s+['"][^'"]+['"]\s+is\s+not\s+available|ModuleNotFoundError|ImportError|Cannot find module|not\s+found|not\s+installed|No module named|Error in library|Error:\s+package|returned non[- ]zero|exit(?:ed)?\s+(?:with\s+)?(?:code|status)\s*[1-9]\d*)\b/i,Jy=["rstan","cmdstanr","pystan","stan","caffe","fasttext","mujoco","dm_control","torch","torchvision","tensorflow","keras","numpy","scipy","pandas","sklearn","scikit-learn","opencv","cv2","pillow","PIL","pyarrow","r-base","gcc","g++","make"],Qy=new Set(["package","packages","dependency","dependencies","library","libraries","module","modules","tool","tools","version","runtime","framework","system","python","node","npm","pip","apt","cran","the","a","an","and","or","for","from","with"]),ed=/^(?:unknown|todo|tbd|placeholder|fixme|n\/a|\?)$/i,td=/\bflag\b/i,Ji=/\bflag\{[^}\r\n]{1,200}\}/i,nd=/^(?:embossed\s+text|shape[-\s]*box|text|label|object\s*\d*|model|mesh|thumbnail|preview|image|video|g-?code|unknown)$/i,Zy=4096,ew=720*1e3,tw=90*1e3,_t=[/\bpytest\b/i,/\bpy\.test\b/i,/\bpython(?:3)?\s+-m\s+pytest\b/i,/\buv\s+run\s+pytest\b/i,/\bpython(?:3)?\s+-m\s+unittest\b/i,/\bmake\b[\s\S]{0,160}\b(?:test|testsuite|check|verify)\b/i,/\bctest\b/i,/\bcargo\s+test\b/i,/\bgo\s+test\b/i,/\b(?:npm|pnpm|yarn)\s+(?:test|run\s+test)\b/i,/\brun-tests\.sh\b/i,/\b(?:bash|sh)\s+(?:\.\s+)?(?:\/[\w./-]*tests?\/[\w./-]+|(?:\.\/)?test\.sh)\b/i,/\b(?:bash|sh)\s+(?:\.\s+)?(?:\/[\w./-]*run-tests\.sh|(?:\.\/)?run-tests\.sh)\b/i,/\bpython(?:3)?\s+\/tests\/[\w./-]+\.py\b/i,/\bTEST_DIR\b.*\btest_outputs\.py\b/i],to=[/\bEXPLAIN(?:\s+QUERY\s+PLAN)?\b/i,/\btime\b/i,/\bhyperfine\b/i,/\bbenchmark\b/i,/\bsqlite3\b.*\bEXPLAIN\b/i],Jr=[/\bsqlite3\.connect\b/i,/\btime\.perf_counter\b/i,/\bstats\.median\b/i,/\bPRAGMA\s+temp_store\s*=\s*MEMORY\b/i,/\bPRAGMA\s+optimize\b/i],Qr=[/\bEXPLAIN\s+QUERY\s+PLAN\b/i],nw=/\bsqlite3\b[\s\S]*(?:\/app\/my-sql-query\.sql|\/app\/sol\.sql)[\s\S]*(?:\/app\/my-sql-query\.sql|\/app\/sol\.sql)|(?:\/app\/my-sql-query\.sql|\/app\/sol\.sql)[\s\S]*(?:\/app\/my-sql-query\.sql|\/app\/sol\.sql)[\s\S]*\bsqlite3\b/i,Cu=/\b(?:Command timed out|Exit code 124|ETIMEDOUT|timeout)\b/i,Qi=/\b(?:pytest|py\.test|unittest|run-tests\.sh|test\.sh|node|python3?|uv\s+run|cc|gcc|clang|make|cmp|diff|sha256sum|jq|sqlite3|readelf|objdump|file)\b/i,sw=/\b(?:strings|objdump|readelf|nm|file|ldd|hexdump|xxd|od|gdb|strace|ltrace|ls|find|grep|egrep|fgrep|sed|awk|head|tail|cat|wc|stat)\b/i,sd=/\b(?:self[-_ ]?check|contract|validation|verifier|threshold|similarity|ssim|expected|candidate|reference|baseline|round[-_ ]?trip|compare|comparison|ArtifactCompare|HtmlSanitizerAudit|SqliteAnalyze|GcodeAnalyze)\b/i,rw=/\b(?:python3?|node|deno|bun|ruby|perl|php|java|go|cargo|npm|pnpm|yarn|uv\s+run|make|cmake|ninja|cc|gcc|clang|g\+\+|c\+\+)\b/i,ow=/\b(?:xeno-toolbox-install|apt(?:-get)?\s+(?:update|install|dist-upgrade)|pip(?:3)?\s+install|python(?:3)?\s+-m\s+(?:pip\s+install|venv)|uv\s+(?:sync|pip\s+install)|conda\s+install|mamba\s+install|npm\s+(?:ci|install)|pnpm\s+(?:install|add)|yarn\s+(?:install|add)|bun\s+install|cargo\s+install|Rscript\s+-e\s+[^\n;&|]*(?:install\.packages|remotes::install_version|devtools::install_version|pak::pkg_install|BiocManager::install)|R\s+-e\s+[^\n;&|]*(?:install\.packages|remotes::install_version|devtools::install_version|pak::pkg_install|BiocManager::install))\b/i,iw=/\b(?:python3?|node|ruby|perl|php)\s+(?:-|-[ce]\b)/i,aw=/\b(?:Traceback \(most recent call last\)|ModuleNotFoundError|ImportError|SyntaxError|AttributeError|NameError|FileNotFoundError|IndexError|KeyError|ValueError|TypeError)\b/i,lw=/\b(?:ModuleNotFoundError|ImportError|SyntaxError|AttributeError|NameError)\b/i,xn=/\b(?:(?:CONTRACT|SELF_CHECK|READBACK|SCHEMA|ROUNDTRIP|METRIC|THRESHOLD|VERIFIER|VALIDATION|SECURITY|XSS|SANITI[ZS]ER)[_-]?PASS|(?:MODEL|INFERENCE|PREDICTION|TOKENI[ZS]ER|WEIGHT|CHECKPOINT|CKPT|LOGIT|BEHAVIOU?R)(?:[_-][A-Z]+)?[_-]?PASS)\b/i,cw=xn,uw=/\b(?:CMP(?:_EXIT)?|DIFF(?:_EXIT)?|EXIT|STATUS)\s*:\s*[1-9]\d*\b|\b(?:mis|mismatches?|diffs?|errors?)\s*[:=]?\s*[1-9]\d*\b|\b(?:mae|mse|rmse|pixel[_ -]?(?:error|diff)|mean[_ -]?(?:absolute[_ -]?)?(?:error|diff)|max[_ -]?(?:error|diff)|maxdiff|max_diff)\s*[:=]?\s*(?!0+(?:\.0+)?\b)\d+(?:\.\d+)?\b|AssertionError|FAILED|FAILURES|failed\b|does not match|not match|differs?|mismatch|not identical/i,Zi=/\b(?:cmp|diff)\b/i,dw=/\b(?:sha(?:1|256|512)sum|md5sum|Get-FileHash)\b/i,pw=/\b(?:hash(?:es)?|checksum|sha(?:1|256|512)|md5)\b[\s\S]{0,160}\b(?:match(?:es|ed)?|identical|same|equal|PASS)\b|\b(?:match(?:es|ed)?|identical|same|equal|PASS)\b[\s\S]{0,160}\b(?:hash(?:es)?|checksum|sha(?:1|256|512)|md5)\b/i,mw=/\b(?:baseline|candidate|median|mean|p(?:50|90|95|99)|runtime|latency|throughput|ops\/s|rows\/s|req\/s|speedup|faster|slower|improvement|threshold|target|budget|profile|hotspot|ms|msec|sec|seconds?)\b/i,fw=/\b(?:strong(?:er)?\s+self[- ]?check\s+(?:failed|fails|failing)|self[- ]?check\s+(?:failed|fails|failing)|not\s+(?:fully\s+)?general|not\s+a\s+fully\s+general|fails?\s+on\s+unseen|does\s+not\s+pass|did\s+not\s+pass|cannot\s+pass|can't\s+pass|verifier\s+(?:failed|fails|failing)|tests?\s+(?:failed|fail|failing)|hidden\s+tests?\s+(?:may\s+)?(?:fail|failed|failing)|not\s+solved|unable\s+to\s+complete|could\s+not\s+complete|did\s+not\s+finish|remaining\s+(?:bug|issue|failure)|miss(?:es|ed|ing)?\s+(?:the\s+)?(?:[\w.-]+\s+)?(?:threshold|target|requirement|score|metric)|below\s+(?:the\s+)?(?:required\s+)?(?:threshold|target|requirement|score|metric)|under\s+(?:the\s+)?(?:required\s+)?(?:threshold|target|requirement|score|metric)|short\s+of\s+(?:the\s+)?(?:threshold|target|requirement|score|metric)|insufficient(?:ly)?|not\s+(?:enough|sufficient)|does\s+not\s+meet\s+(?:the\s+)?(?:requirement|threshold|target|score|metric)|best\s+(?:observed|current|available|candidate)[\s\S]{0,180}\b(?:miss(?:es|ed|ing)?|below|under|short\s+of|not\s+enough|insufficient))\b/i,rd=/Traceback \(most recent call last\)|\bAssertionError\b|\bModuleNotFoundError\b|\bSyntaxError\b|\bTypeError\b|\bValueError\b|\bFAILURES?\b|\bFAILED\b|\bOverall:\s*FAIL\b|(?:^|\s)[1-9]\d*\s+failed\b|\b(?:self[- ]?check|validation|verifier|tests?|audit)\s+(?:failed|fails|failing)\b|\b(?:failed|fails|failing)\s+(?:on|for|because|with|hidden|self[- ]?check|validation|verifier|tests?|exit code)\b|\b(?:HtmlSanitizerAudit|SqliteAnalyze|GcodeAnalyze|ArtifactCompare)\s+failed\b|\b(?:attack|clean|browser|policy)_failures\s*=\s*[1-9]\d*\b|\bclean_mismatches\s*=\s*[1-9]\d*\b|\b(?:mis|mismatches?|diffs?|errors?)\s*[:=]?\s*[1-9]\d*\b|\b(?:mae|mse|rmse|pixel[_ -]?(?:error|diff)|mean[_ -]?(?:absolute[_ -]?)?(?:error|diff)|max[_ -]?(?:error|diff)|maxdiff|max_diff)\s*[:=]?\s*(?!0+(?:\.0+)?\b)\d+(?:\.\d+)?\b|(?<!No\s)\bALERT DETECTED\b|\bwrong output\b|\bdoes not match\b|\bnot match\b|\bdiffers?\b|\bmismatch(?:ed|es)?\b|\bnot identical\b|\bnot equivalent\b|\bRow counts differ\b|\bColumn names\/order differ\b|\bFirst differing row\b|\bCommand failed\b|\breturned non[- ]zero\b|\bexit(?:ed)?\s+(?:with\s+)?(?:code|status)\s*[1-9]\d*\b|\b(?:exit|status|returncode|return code)\s*[:=]\s*[1-9]\d*\b|\bNo such file or directory\b|\bdoes not exist\b|\btimed?\s*out\b|\btimeout\b/i,hw=/\b(?:all\s+checks?\s+pass(?:ed)?|all\s+tests?\s+pass(?:ed)?|tests?\s+pass(?:ed)?|verifier\s+pass(?:ed)?|validation\s+pass(?:ed)?|self[- ]?check\s+pass(?:ed)?|PASSED|PASS\b|SUCCESS|successful|verified|valid|no differences|identical|outputs?\s+match(?:es|ed)?(?:\s+exactly)?|No alert detected|Certificate verification successful|CMP(?:_EXIT)?\s*:?0\b|DIFF(?:_EXIT)?\s*:?0\b|EXIT\s*:?0\b|STATUS\s*:?0\b|0\s+failed\b|metric_zero|mismatch_zero)\b|\b(?:CONTRACT|SECURITY|ROUNDTRIP|SELF_CHECK|READBACK|SCHEMA|DIFF_SCOPE|SECRET_SCAN|REPO_SURGERY|PLACEHOLDER|REPLACEMENT|METRIC|THRESHOLD|NUMERIC|SCIENCE|BIO|BIOSEQUENCE|SIMULATION|EIGEN|FIT|RESIDUAL|TM|PRIMER|ASSEMBLY|TRANSLATION|VERIFIER|VALIDATION)[_-]?PASS\b|\b(?:byte_equal|bytes_equal|outputs_equal|files_equal)\s*(?:[:=]|\s)\s*(?:true|yes|1)\b/i,gw=[/\bSIG(?:TERM|INT|KILL)\b/i,/\bkill(?:all)?\b/i,/\bpkill\b/i,/\bCtrl-C\b/i,/\binterrupt\b/i,/\bcancel(?:lation)?\b/i,/\bcleanup\b/i],bw=/\b(?:cleanup|clean\s+up|cleaned\s+up|finally|finalizer|teardown|release\s+(?:resources?|locks?|handles?))\b/i,yw=[/\bCleaned up\./i,/\bcleanup\s+(?:complete|completed|done|ok|successful)\b/i,/\bcleaned\s+up\b/i],ww=[/\bcancelled\b/i,/\bcanceled\b/i,/\bterminated\b/i,/\bshutdown\s+(?:complete|completed|done|ok|successful)\b/i,/\bexit(?:ed)?\s+(?:code\s*)?0\b/i,/\bexit[_ -]?code\s*-?\d+\b/i,/\breturn[_ -]?code\s*-?\d+\b/i,/\bKeyboardInterrupt\b/i],vw=/\bexcept\s+KeyboardInterrupt\b|\bKeyboardInterrupt\s+received\b/i,Sw=/\bfinally\s*:[\s\S]{0,320}\bawait\b[\s\S]{0,320}\b(?:Cleaned up|cleaned\s+up|cleanup)\b/i,ea=[/\b(?:accuracy|classification_report|confusion_matrix|validation|holdout|test\s+set|eval(?:uate)?|metric|top[-_ ]?1|loss)\b/i,/\b(?:for|while)\b[\s\S]{0,240}\b(?:png|jpg|jpeg|image|sample|prediction|label|class|token|prompt)\b/i,/\brange\s*\(\s*(?:[2-9]|\d{2,})\s*\)/i,/\b(?:glob|find)\b[\s\S]{0,160}\b(?:png|jpg|jpeg|wav|json|csv|sample)\b/i,/\b(?:DataLoader|batch|batches|predict_proba|argmax|softmax)\b[\s\S]{0,240}\b(?:labels?|expected|accuracy|samples?|range|for)\b/i,/\b(?:expected|TRUE_PRED|labels?)\b[\s\S]{0,240}\b(?:prediction|output|class|accuracy)\b/i],od=/\b(?:(?:MODEL|INFERENCE|PREDICTION|TOKENI[ZS]ER|WEIGHT|CHECKPOINT|CKPT|LOGIT|BEHAVIOU?R|METRIC|THRESHOLD)[_-]?(?:CONTRACT|CHECK|VALIDATION|BEHAVIOU?R|DEPENDENCY|MUTATION)?[_-]?PASS|(?:MODEL|INFERENCE|PREDICTION|TOKENI[ZS]ER|WEIGHT|CHECKPOINT|CKPT|LOGIT|BEHAVIOU?R)[_-]?PASS)\b/i,kw=/\b(?:[2-9]|\d{2,})\s+(?:samples?|cases?|prompts?|images?|inputs?|predictions?|labels?|tokens?|continuations?)\b|\b(?:samples?|cases?|prompts?|images?|inputs?|predictions?|labels?|tokens?|continuations?)\s*[:=]\s*(?:[2-9]|\d{2,})\b|\brange\s*\(\s*(?:[2-9]|\d{2,})\s*\)|\b(?:for|while)\b[\s\S]{0,240}\b(?:samples?|cases?|prompts?|images?|labels?|tokens?)\b/i,xw=/\b(?:accuracy|classification_report|confusion_matrix|validation|holdout|test\s+set|eval(?:uate)?|metric|top[-_ ]?1|loss|perplexity|f1|precision|recall|auc|bleu|rouge)\b/i,Pw=/\b(?:weights?|checkpoint|ckpt|model|tokeni[sz]er|vocab|bpe|logits?)\b[\s\S]{0,260}\b(?:mutat|perturb|zero|shuffle|dependency|dependence|changes?|changed|different|differs?|non[- ]?constant|not\s+constant|schema|loaded|parsed?|read)\b|\b(?:mutat|perturb|zero|shuffle|dependency|dependence|changes?|changed|different|differs?|non[- ]?constant|not\s+constant|schema|loaded|parsed?|read)\b[\s\S]{0,260}\b(?:weights?|checkpoint|ckpt|model|tokeni[sz]er|vocab|bpe|logits?)\b/i,Tw=/\b(?:expected|gold(?:en)?|known|label|target|truth|reference)\b[\s\S]{0,220}\b(?:prediction|output|class|token|continuation|logit|matches?|equals?|==)\b|\b(?:prediction|output|class|token|continuation|logit)\b[\s\S]{0,220}\b(?:expected|gold(?:en)?|known|label|target|truth|reference)\b/i,_w=/\b(?:official\s+verifier|\/tests|test_outputs\.py|README|instruction|fixture|golden[_ -]?file|expected[_ -]?file|known[_ -]?fixture|reference\s+(?:implementation|model|decoder|runtime|script)|python\s+reference|independent\s+reference)\b/i,id=/\b(?:stub|placeholder|hard[- ]?coded|constant\s+output|ignores?\s+(?:weights?|checkpoint|ckpt|model|tokeni[sz]er|prompt|input)|same\s+output|output\s+unchanged|mutation(?:\s+check)?\s+(?:failed|fails|unchanged)|without\s+(?:loading|reading)\s+(?:weights?|checkpoint|ckpt|model|tokeni[sz]er))\b/i,Rw=/\b(?:all[_ -]?(?:rows?|columns?|weights?|parameters?|neurons?|layers?)\s*(?:matched|recovered|validated|present)|missing[_ -]?(?:rows?|columns?|weights?|parameters?|neurons?|layers?)\s*[:=]\s*(?:0|\[\]|none)|unmatched[_ -]?(?:rows?|columns?|weights?|parameters?|neurons?|layers?)\s*[:=]\s*(?:0|\[\]|none)|failures?\s*[:=]\s*(?:0|\[\]|none)|complete[_ -]?(?:rank|matrix|weight|parameter|recovery)|full[_ -]?(?:rank|matrix|row|column|weight|parameter|recovery)|shape\s*[:=]\s*\(?\s*(?:[2-9]\d|\d{3,})\s*[,x]\s*(?:[2-9]|\d{2,})|rows?\s*[:=]\s*(?:[2-9]\d|\d{3,})\b[\s\S]{0,160}\b(?:cols?|columns?|shape|matched|recovered|validated))\b/i,Au=/\b(?:[A-Za-z]:[\\/]|\/|\.{1,2}[\\/])?[A-Za-z0-9_./\\-]+\.(?:caffemodel|pt|pth|onnx|ckpt|bin|pkl|pickle|joblib|h5|keras|safetensors|npy|npz)\b/gi,Zr=1e5,Ew=/\b(?:train(?:ing|ed)?|solver|epoch|iteration|iter(?:ation)?\s*[#: ]?\s*(?:[1-9]\d{2,}|\d+)|max_iter|snapshot(?:ting|ted)?|checkpoint|caffemodel|training_output|fit\s*\(|fit_generator|trainer\.fit|model\.fit)\b/i,Iu=/\b(?:accuracy|test\s+net\s+output|train(?:ing)?[_ -]?accuracy|test[_ -]?accuracy|validation[_ -]?accuracy|val[_ -]?accuracy|holdout|top[-_ ]?1|loss|auc|f1|precision|recall|metric|threshold)\b/i,Cw=[/\bcaffe(?:\.bin)?\s+test\b[\s\S]*-model\b[\s\S]*-weights\b/i,/(?:^|[\s;&|])(?:\.{0,2}\/)?(?:\.build_release|build)\/tools\/caffe(?:\.bin)?\s+test\b[\s\S]*-model\b[\s\S]*-weights\b/i,/\b(?:python3?|uv\s+run\s+python)\b[\s\S]{0,1600}\b(?:caffe\.Net|torch\.load|onnxruntime|InferenceSession|keras\.models\.load_model|tf\.keras\.models\.load_model|joblib\.load|pickle\.load|fasttext\.load_model)\b[\s\S]{0,1600}\b(?:predict|forward|eval|accuracy|test|validation|holdout|DataLoader|batch|samples?)\b/i],Aw=/\b(?:tensor\s*parallel(?:ism)?|ColumnParallelLinear|RowParallelLinear|world[_ -]?sizes?|torch\.distributed|distributed\s+(?:linear|tensor|torch)|all[_ -]?reduce|all[_ -]?gather|reduce[_ -]?scatter)\b/i,Iw=/\b(?:RowParallelLinear|row[-_ ]?parallel)\b/i,Mw=/\b(?:ColumnParallelLinear|column[-_ ]?parallel)\b/i,Ow=/\b(?:column\s*=\s*row|row\s*=\s*column|column[_ -]?(?:and|plus|with)[_ -]?row|row[_ -]?(?:and|plus|with)[_ -]?column|column\s*[+,&/]\s*row|row\s*[+,&/]\s*column)\b/i,$w=/\b(?:scattered[_ -]?input|pre[-_ ]?scattered|rank[-_ ]?local[_ -]?input|row[_ -]?local[_ -]?input|local[_ -]?row[_ -]?input|local\s+input\s+(?:contract|shape|mode)|input\s+is\s+already\s+(?:split|scattered|sharded)|already[-_ ]?(?:split|scattered|sharded)\s+input|torch\.(?:chunk|tensor_split)\b[\s\S]{0,180}\binput|input\b[\s\S]{0,180}\b(?:chunk|tensor_split|split)\b)\b/i,Lw=/\b(?:TENSOR[_-]?PARALLEL[_-]?PASS|DISTRIBUTED[_-]?PASS|CONTRACT[_-]?PASS|SELF[_-]?CHECK[_-]?PASS|all\s+(?:tests\s+)?passed|\d+\s+passed)\b/i,Nw=/\b(?:pytest|python3?|uv\s+run\s+python)\b[\s\S]{0,320}\b(?:\/tests\b|\/tests\/test_outputs\.py|test_outputs\.py)\b/i,Bw=/\b(?:failed|failure|error|RuntimeError|AssertionError|shape\s+mismatch|mismatches?\s*[:=]\s*(?:[1-9]\d*)|incorrect|wrong|nan|inf)\b/i,ad=/\bcaffe(?:\.bin)?\s+test\b[\s\S]*-model\b[\s\S]*-weights\b|(?:^|[\s;&|])(?:\.{0,2}\/)?(?:\.build_release|build)\/tools\/caffe(?:\.bin)?\s+test\b[\s\S]*-model\b[\s\S]*-weights\b/i,Dw=/\b(?:caffe|bvlc|cifar-?10|caffemodel)\b/i,Fw=/\b(?:FIRST|FIRST_BATCH|FIRST_REGEX|VERIFIER_REGEX|MIN(?:IMUM)?)[_-]?ACCURACY[_-]?(?:CHECK[_-]?)?PASS\b/i,no=[/\b(?:ffmpeg|ffprobe|cv2|opencv|PIL|ImageMagick|convert|magick|tesseract|ocr)\b/i,/\b(?:render|rasteri[sz]e|simulate|sample\s+frames?|frame\s+diff|threshold|contour|optical\s+flow)\b/i,/\b(?:second|independent|cross[- ]?check|compare)\b[\s\S]{0,240}\b(?:preview|render|frame|image|candidate|decode)\b/i],Mu=[...no,/\b(?:gcode|g-code|M486|G0|G1|projection|PCA|toolpath|extrusion)\b/i,/\b(?:png|jpg|jpeg|webp|svg)\b[\s\S]{0,240}\b(?:inspect|preview|render|threshold|ocr|decode|candidate|flag|text)\b/i],Uw=/\b(?:ssim|mse|rmse|psnr|pixel\s*(?:diff|error|distance)|image\s*(?:similarity|diff|compare)|similarity|compare(?:d)?\s+(?:against|to)\s+(?:target|reference|expected)|target|reference)\b[\s\S]{0,320}\b(?:pass(?:ed)?|score|threshold|within|below|above|match(?:es|ed)?|<=|>=)\b|\b(?:pass(?:ed)?|score|threshold|within|below|above|match(?:es|ed)?|<=|>=)\b[\s\S]{0,320}\b(?:ssim|mse|rmse|psnr|pixel\s*(?:diff|error|distance)|image\s*(?:similarity|diff|compare)|target|reference)\b/i,Ou=/\b(?:read_bytes|readFileSync|open\s*\([^)]*['"]rb['"]|cmp|diff|sha(?:1|256|512)sum|md5sum|Get-FileHash|wc\s+-c|stat\s+-c|cat|type|Get-Content)\b/i,jw=/\b(?:cat|type|Get-Content|head|tail|sed\s+-n|awk|wc\s+-c|stat|sha(?:1|256|512)sum|md5sum|cmp|diff|read_bytes|read_text|readFileSync|fs\.readFileSync|open\s*\(|Path\s*\(|pd\.read_|pandas\.read_|np\.load|numpy\.load|json\.load|json\.loads|csv\.reader|csv\.DictReader|torch\.load|load_state_dict|pickle\.load|joblib\.load)\b/i,$u=/\b(?:python3?|node|deno|bun|ruby|perl|php|bash|sh|zsh|fish|java\s+-jar|go\s+run|cargo\s+run|uv\s+run|sqlite3|qemu|cc|gcc|clang|g\+\+|c\+\+|make|cmake|ninja|chmod\s+\+x)\b/i,Vw=/\b(?:READBACK|SELF_CHECK|CONTRACT|ROUNDTRIP|SCHEMA|METRIC|THRESHOLD|MODEL|INFERENCE|PREDICTION|TOKENI[ZS]ER|WEIGHT|CHECKPOINT|CKPT|LOGIT|BEHAVIOU?R)(?:[_-][A-Z]+)?[_-]?PASS\b|PASS\b|SUCCESS|verified|valid|exists|loaded|shape|rows?|columns?|bytes?|sha(?:1|256|512)|identical|matches?|outputs?\s+match|\bmatch\s+(?:True|true|yes|1)\b|\ball_int\s+(?:True|true|yes|1)\b/i,qw=/\b(?:curl|wget|httpie|httpx|requests\.(?:get|post|put|delete)|fetch\s*\(|grpcurl|grpc\.\w+|[A-Za-z_]\w*_pb2(?:_grpc)?|protoc\b|sshpass|ssh\b|scp\b|sftp\b|git\s+(?:clone|push|ls-remote|fetch)|nc\b|ncat\b|netcat\b|telnet\b|socat\b|qemu(?:-system-[\w-]+)?\b|qmp|sendkey|human-monitor-command)\b|\b(?:stub|client)\.[A-Za-z_]\w*\s*\(/i,Hw=/\b(?:ss\s+-|netstat\b|lsof\b|pgrep\b|ps\b|nc\s+-z|ncat\s+-z|test\s+-S|stat\s+.+sock|port\s+(?:open|listening)|listening\s+on)\b/i,zw=/\b(?:SERVICE|CLIENT|PROTOCOL|RPC|GRPC|HTTP|SSH|GIT|VM|QEMU|MONITOR|CONTROL|READY|CONTRACT|SELF_CHECK)[_-]?(?:PASS|OK|READY|SUCCESS)\b|\bTEST PASSED\b|\bHTTP\/\d(?:\.\d)?\s+2\d\d\b|\bstatus(?:_code)?\s*[:=]\s*2\d\d\b|\b(?:clone|push|curl|ssh|grpc|rpc|request|response|sendkey|monitor|qmp)\b[\s\S]{0,180}\b(?:passed|ok|success|succeeded|worked|verified|matches?|received|returned)\b/i,Ww=/\b(?:new\s+)?[A-Z]\w*(?:Request|Response)\s*\([^)]*(?:=|:)[^)]*\)|\b(?:request|message|payload)\s*=\s*[A-Z]\w*(?:Request|Response)\b|\bgrpcurl\b[\s\S]{0,220}\b-d\s+['"]?\{|\bprotoc\b[\s\S]{0,160}\b(?:--python_out|--go_out|--js_out|--grpc)\b/i,Xw=/\b(?:stub|client)\.[A-Za-z_]\w*\s*\(|\bgrpcurl\b[\s\S]{0,240}\b[A-Za-z_]\w*\/[A-Za-z_]\w+|\b(?:requests|httpx)\.(?:get|post|put|delete)\s*\(|\bcurl\b[\s\S]{0,240}\b(?:GET|POST|PUT|DELETE|http)|\bresponse\s*=\s*(?:stub|client)\./i,Kw=/\b(?:qemu-monitor\.sock|monitor\.sock|QMP|human-monitor-command|sendkey|info\s+status|qemu\s+monitor|serial\s+console|telnet\b[\s\S]{0,120}\b(?:login|shell|prompt|connected)|VNC|screenshot|framebuffer|frame\.bmp)\b/i,Gw=.72,Lu=8*6e4,Yw=4*6e4,eo=[/\b(?:make|cmake|ninja|cargo|rustc|gcc|clang|qemu|spim|mips|pytest|ctest|run-tests?\.sh)\b/i,/\b(?:smoke|unit|integration|verifier|cross[- ]?compile|target)\b/i],Jw=/\b(?:original|mystery|reference|baseline|source\s+binary)\b[\s\S]{0,300}\b(?:candidate|reverse[dr]?|reimplementation|generated|rebuilt)\b[\s\S]{0,300}\b(?:match(?:es|ed)?|identical|equivalent|cmp|diff|similarity|cosine|mae|mse|rmse|byte_equal|files_equal|zero\s+(?:diffs?|mismatches?|errors?))\b|\b(?:candidate|reverse[dr]?|reimplementation|generated|rebuilt)\b[\s\S]{0,300}\b(?:original|mystery|reference|baseline|source\s+binary)\b[\s\S]{0,300}\b(?:match(?:es|ed)?|identical|equivalent|cmp|diff|similarity|cosine|mae|mse|rmse|byte_equal|files_equal|zero\s+(?:diffs?|mismatches?|errors?))\b/i,Qw=/\b(?:BEHAVIOU?R|EQUIVALENCE|CONTRACT|METRIC|SELF_CHECK)[_-]?PASS\b|\b(?:outputs?|stdout|stderr|files?|images?|pixels?|hash(?:es)?|checksums?)\s+(?:match(?:es|ed)?|identical|equivalent|same)\b|\b(?:match(?:es|ed)?|identical|equivalent|same)\s+(?:outputs?|stdout|stderr|files?|images?|pixels?|hash(?:es)?|checksums?)\b|\b(?:cosine|similarity|ssim)\s*[:=]\s*(?:0\.99[5-9]\d*|1(?:\.0+)?)\b|\b(?:cmp|diff|mismatches?|diffs?|errors?|mis)(?:_exit)?\s*[:=]\s*0\b|\b(?:metric_zero|mismatch_zero)\b|\b(?:byte_equal|bytes_equal|outputs_equal|files_equal)\s*(?:[:=]|\s)\s*(?:true|yes|1)\b/i,Zw=/(?:\.\/mystery|\/app\/mystery|\bmystery\.(?:orig|bak)\b|\b(?:source\s+binary|original\s+binary|preserved\s+original|provided\s+binary|a\.out)\b)/i,ev=/\b(?:system|popen|execlp?|execv(?:p|pe)?|posix_spawnp?|fork|vfork)\s*\(/i,tv=/\.(?:incbin)\b|\\x7fELF|0x7f\s*,\s*0x45\s*,\s*0x4c\s*,\s*0x46|\b(?:790376|789K|bytes\s+embedded|embed(?:ded)?\s+(?:the\s+)?(?:original|source|provided)\s+binary)\b/i,ta=[/\b(?:round[- ]?trip|decompress|decode|verify|diff|cmp|sha256|checksum|randomized|fuzz)\b/i,/\b(?:best|candidate|checkpoint)\b[\s\S]{0,160}\b(?:score|size|bytes|ratio|valid)\b/i,/\b(?:oracle|python-chess|chess\.Board|legal_moves|legal\s+moves?|FEN|PGN)\b/i],Nu=[{key:"script-tag",pattern:/<\s*script\b|script\s+tag/i},{key:"event-handler",pattern:/\bon(?:error|load|click|mouseover|focus|submit|input)\b|event\s+handler/i},{key:"javascript-url",pattern:/javascript\s*:|href\s*=|src\s*=/i},{key:"embedded-html",pattern:/srcdoc|data\s*:\s*text\/html|iframe|object|embed/i},{key:"svg-mathml",pattern:/\b(?:svg|mathml|foreignObject|animate|set)\b/i},{key:"encoded-obfuscated",pattern:/&#x?|:|entity|encoded|mixed\s*case|case[- ]?insensitive|null\s*byte|comment\s+breakout/i},{key:"style-css",pattern:/\b(?:style|expression\s*\(|url\s*\(|-moz-binding|css)\b/i},{key:"clean-roundtrip",pattern:/\b(?:clean|benign|safe|round[- ]?trip|idempoten|preserve|formatting|checksum|byte[- ]?preserv)\b/i}],nv=/\b(?:timeout|time[-_ ]?limit|bounded|deadline|subprocess\.run|signal\.alarm|perf_counter|monotonic|large|pathological|fuzz|randomi[sz]ed?|repeat(?:ed)?|1000|10000|50k|kb|mb|catastrophic|backtracking|linear[- ]?time|no\s+(?:network|fetch|remote)|network[- ]?free)\b/i,sv=/\b(?:selenium|webdriver|chrom(?:e|ium)|playwright|puppeteer|jsdom|DOMParser|headless|browser|alert[_ -]?(?:detected|present)|EC\.alert_is_present|switch_to\.alert|no\s+alert\s+detected)\b/i,rv=/\b(?:BeautifulSoup|bs4|html\.parser|html5lib|lxml|parse5|parser[-_ ]?normal(?:i[sz]ed|ization)|DOM[-_ ]?normal(?:i[sz]ed|ization)|clean[_-]?html[_-]?unchanged|normalized[_-]?original|normalized\s+(?:clean|benign|round[- ]?trip))\b/i,ov=/\b(?:html[-_ ]?sanitizer[-_ ]?testbed|davidwagner|OWASP|xss[-_ ]?filter[-_ ]?evasion|public\s+(?:xss|html)\s+(?:corpus|payloads?|testcases?)|established\s+(?:xss|html|sanitizer)\s+(?:corpus|payloads?|testcases?)|download(?:ed)?\s+(?:xss|attack|sanitizer)\s+(?:vectors?|payloads?|testcases?))\b/i,iv=/\b(?:(?:[5-9]\d|[1-9]\d{2,})\s+(?:xss\s+)?(?:vectors?|test(?:case)?s|cases?|payloads?|attack(?:\s+vectors?)?)|(?:vectors?|test(?:case)?s|cases?|payloads?|attack(?:\s+vectors?)?)\s*[:=]\s*(?:[5-9]\d|[1-9]\d{2,})|(?:batch(?:es|ed)?|groups?)\s*[:=]\s*(?:[2-9]|\d{2,})|(?:[2-9]|\d{2,})\s+(?:browser\s+)?batch(?:es|ed)?|hundreds[- ]?(?:of[- ])?(?:vector|case|payload))\b/i,av=/\b(?:(?:[3-9]\d{2}|[1-9]\d{3,})\s+(?:xss\s+)?(?:vectors?|test(?:case)?s|cases?|payloads?|attack(?:\s+vectors?)?)|(?:vectors?|test(?:case)?s|cases?|payloads?|attack(?:\s+vectors?)?)\s*[:=]\s*(?:[3-9]\d{2}|[1-9]\d{3,})|(?:3[0-9]|[4-9]\d|\d{3,})\s+(?:browser\s+)?batch(?:es|ed)?)\b/i,lv=/\b(?:network|internet|github|download|curl|wget|urllib|requests)\b[\s\S]{0,120}\b(?:unavailable|blocked|failed|timeout|timed\s+out|not\s+available|connection\s+refused|dns|could\s+not|unable)\b|\b(?:unavailable|blocked|failed|timeout|timed\s+out|not\s+available|connection\s+refused|dns|could\s+not|unable)\b[\s\S]{0,120}\b(?:network|internet|github|download|curl|wget|urllib|requests)\b/i,cv=/\b(?:malformed|legacy|comment\s+breakout|split\s+script|nested\s+script|scriptlet|xhtml|namespace|xml|CDATA|UTF-7|meta\s+refresh|base\s+tag|link\s+rel|isindex|layer|bgsound|protocol\s+alias|mocha\s*:|livescript\s*:|css\s+import|escaped\s+css|attribute\s+breakout|unquoted\s+attribute)\b|<<\s*SCRIPT|<\s*P\s*<\s*SCRIPT|<\s*img\s*\/\s*onerror/i,uv=/\b(?:BeautifulSoup\s*\([^)]*html\.parser|str\s*\(\s*BeautifulSoup|clean[_ -]?html[_ -]?unchanged|parser[-_ ]?normalized\s+(?:equality|equivalence|matches?|comparison)|normalized[_ -]?original\s*==\s*filtered|filtered\s*==\s*normalized[_ -]?original|clean\s+(?:samples?|fixtures?)\s*(?:matched|unchanged|equal|equivalent)|zero\s+clean\s+(?:diffs?|mismatches?))\b/i,dv=/\b(?:(?:clean|benign)[-_ ]?(?:samples?|fixtures?|cases?)\s*[:=]\s*(?:1[0-9]|[2-9]\d|\d{3,})|(?:1[0-9]|[2-9]\d|\d{3,})\s+(?:clean|benign)\s+(?:samples?|fixtures?|cases?)|clean[_ -]?mismatches?\s*[:=]\s*0|zero\s+clean\s+(?:diffs?|mismatches?))\b/i,pv=[{key:"void-tags",pattern:/\b(?:void\s+tags?|self[- ]?closing|<br\s*\/?>|<hr\s*\/?>|<img\b)\b/i},{key:"entities",pattern:/\b(?:entities?|entity\s+decod(?:e|ed|ing)|&| |copyright|quote\s+entities?)\b|[©]/i},{key:"forms",pattern:/\b(?:forms?|<form\b|<input\b|<label\b|<textarea\b|<select\b)\b/i},{key:"media",pattern:/\b(?:media|<img\b|<video\b|<audio\b|<picture\b|srcset)\b/i},{key:"semantic",pattern:/\b(?:semantic|<article\b|<section\b|<nav\b|<header\b|<footer\b|<main\b)\b/i}],Bu=/\bgit\s+(?:diff|status|show|ls-files)\b|\bgit\s+diff-tree\b/i,ld=/\b(?:DIFF_SCOPE|SCOPE|REPO_SURGERY|SANITIZE|SECRET_SCAN)[_-]?PASS\b|\bno\s+other\s+files\s+changed\b|\bonly\s+(?:contaminated|expected|allowed|secret-bearing|targeted)\s+files?\b|\bunexpected(?:_|\s+)files?\s*[:=]\s*(?:0|\[\]|none)\b|\bsecret(?:_|\s+)matches?\s*[:=]\s*0\b/i,mv=/\b(?:DIFF_SCOPE|SCOPE|REPO_SURGERY|SANITIZE|SECRET_SCAN)[_-]?FAIL\b|\bunexpected(?:_|\s+)files?\s*[:=]\s*(?!0\b|\[\]|none)\S+|\bextra(?:_|\s+)files?\s*[:=]\s*(?!0\b|\[\]|none)\S+|\bmodified\s+clean\s+files?\b|\bnon[- ]?contaminated\s+files?\s+(?:changed|modified)\b/i,fv=/<your-[a-z0-9-]+>|placeholder\s+values?|replace\s+(?:it|them|actual\s+values?)\s+with/i,cd=/\b(?:PLACEHOLDER|REPLACEMENT|TOKEN_PLACEHOLDER|SECRET_PLACEHOLDER)[_-]?PASS\b|\bplaceholder(?:s)?\s+(?:consistent|exact|match(?:ed|es)?|ok|pass(?:ed)?)\b|\bplaceholder(?:_|\s+)mismatches?\s*[:=]\s*(?:0|\[\]|none)\b|\bexact\s+replacement(?:s)?\s+(?:verified|pass(?:ed)?|ok)\b/i,hv=/\b(?:tm\b|melting|oligotm|primer|translate|translation|codon|amino\s+acid|gblock|donor|acceptor|dhfr|snap|assembly|lorentzian|curve_fit|least_squares|residual|rmse|mse|chi[- ]?square|peak|x0|gamma|amplitude|offset|simulation|mjcf|mujoco|eigen(?:value|val)?|threshold|bounds?|margin|reconstruction|speedup|time\s+pctg|final\s+state\s+difference|max[_ -]?(?:abs|norm)|atol)\b/i,ud=/\b(?:SCIENCE|BIO|BIOSEQUENCE|NUMERIC|THRESHOLD|TM|PRIMER|ASSEMBLY|TRANSLATION|FIT|RESIDUAL|SIMULATION|EIGEN|METRIC)[_-]?PASS\b|\b(?:all\s+)?(?:tm|primer|translation|order|residual|fit|threshold|bounds?|margin|simulation|eigen(?:value|val)?)\s+(?:checks?\s+)?(?:pass(?:ed)?|ok|within|satisfied)\b/i,gv=/\b(?:exists|non[- ]?empty|wrote|created|json\s+valid|fasta\s+valid|shape\s+ok|file\s+ok|smoke\s+pass)\b/i;function un(t,e){let n=t.filter(r=>typeof r=="string"&&r.trim().length>0).map(r=>so(r)).filter(r=>!dd(r)).filter(r=>!yv(r)).map(r=>yt(e,r));return Array.from(new Set(n)).filter(r=>!wv(r))}function so(t){let e=t.trim();for(let n=0;n<4;n+=1){let s=e;if(e=e.replace(/^[`'"]+|[`'"]+$/g,""),e=Ys(e,"**"),e=Ys(e,"__"),e=Ys(e,"`"),e=Ys(e,"*"),e=Ys(e,"_"),e=e.replace(/^[*_`]+(?=(?:[A-Za-z]:\\|\/|\.{1,2}[\\/]|[A-Za-z0-9_.-]+[\\/]))/g,""),e=e.replace(/(?:\*\*|__|`)+$/g,""),e=e.replace(/[.,;:)\]]+$/g,""),e=e.trim(),e===s)break}return e}function Ys(t,e){if(t.length<=e.length*2||!t.startsWith(e)||!t.endsWith(e))return t;let n=t.slice(e.length,-e.length).trim();return bv(n)?n:t}function bv(t){return/^(?:[A-Za-z]:\\|\/|\.{1,2}[\\/]|[A-Za-z0-9_.-]+[\\/])/.test(t)}function dd(t){return!!(!t||/^[a-z][a-z0-9+.-]*:\/\//i.test(t)||t.startsWith("//")||/^\/[a-z][a-z0-9+.-]*:\/\//i.test(t))}function yv(t){let e=so(t);return e?/[\\/]$/.test(e):!0}function wv(t){try{return Kr(t)&&jt(t).isDirectory()}catch{return!1}}function pd(t,e){if(!t||t.trim().length===0)return[];try{let n=JSON.parse(t);return Array.isArray(n)?un(n.filter(s=>typeof s=="string"),e):[]}catch{return[]}}function md(t,e){if(!t||t.trim().length===0)return[];let n=[],s=fd(t),r=t.match(/Required output paths:\s*\n((?:-\s+[^\n]+\n?)+)/i);if(r?.[1])for(let a of r[1].split(/\r?\n/)){let l=a.match(/^\s*-\s+(.+?)\s*$/);l?.[1]&&n.push(l[1])}let o=[/\bwrite\s+(?:the\s+)?(?:output|result|answer|contents?)\s+to\s+(?:"|'|`)?([^\s"'`]+)(?:"|'|`)?/gi,/\bsave\s+(?:it|them|the\s+(?:output|result|answer|model|file))?\s+as\s+(?:"|'|`)?([^\s"'`]+)(?:"|'|`)?/gi,/\bsave\s+(?:your\s+)?(?:solution|answer|output|result|artifact)\s+(?:in|to)\s+(?:the\s+file\s+)?(?:"|'|`)?([^\s"'`]+)(?:"|'|`)?/gi,/\b(?:create|place)\s+(?:a\s+file\s+(?:called|named)|the\s+file)\s+(?:"|'|`)?([^\s"'`]+)(?:"|'|`)?/gi,/\b(?:write|create|implement)\s+(?:a\s+)?(?:C|C\+\+|Python|Rust|Go|JavaScript|TypeScript|shell|bash)?\s*(?:source\s+)?(?:program|script|implementation|module|file|code)\s+(?:at|as|in|to)?\s*(?:"|'|`)?((?:\/|\.{1,2}[\\/]|[A-Za-z0-9_.-]+[\\/])[^\s"'`]+|[A-Za-z0-9_.-]+\.(?:c|cc|cpp|h|hpp|py|js|ts|tsx|sh|rs|go|java|rb|pl|php|json|xml|tex|sql|vim))(?:"|'|`)?/gi,/\bconvert\s+(?:the\s+)?(?:file\s+)?[^\n]*?\s+(?:into|to)\s+(?:a\s+)?(?:[\w-]+\s+)*file\s+named\s+(?:"|'|`)?([^\s"'`]+)(?:"|'|`)?/gi,/\b(?:must|should)\s+be\s+(?:saved|written|placed)\s+(?:as|to|in)\s+(?:"|'|`)?([^\s"'`]+)(?:"|'|`)?/gi,/\bfinal\s+(?:model|output)\s+should\s+be\s+saved\s+as\s+(?:"|'|`)?([^\s"'`]+)(?:"|'|`)?/gi];for(let a of o){let l;for(;(l=a.exec(s))!==null;)l[1]&&n.push(l[1])}let i=Array.from(s.matchAll(/(?:[A-Za-z]:\\[^\s"'`]+|\/[^\s"'`]+)/g));for(let a of i){let l=so(a[0]??"");if(l.length===0||dd(l))continue;let c=a.index??-1;if(c<0)continue;let u=vv(s,c,l.length).toLowerCase(),p=0,f=0;/\b(save|write|create|place|put|store|submit|final)\b/.test(u)&&(p+=1),/\b(solution|answer|output|result|artifact|submission)\b/.test(u)&&(p+=2),/\b(?:source\s+)?(?:program|script|implementation|module|code)\b/.test(u)&&/\b(?:write|create|implement)\b/.test(u)&&(p+=2),/\bin the file\b|\bto the file\b|\brequired output\b/.test(u)&&(p+=2),/\bmust contain\b|\bshould contain\b|\bterminated by\b/.test(u)&&(p+=1),/\blocated at\b|\bdatabase\b|\bbaseline\b|\breference\b|\bgolden\b|\binput\b/.test(u)&&(f+=2),/\bcompiled\b|\b(?:program|binary|executable)\s+at\b|\bprovided\s+(?:program|binary|executable)\b|\boriginal\s+(?:program|binary|executable)\b/.test(u)&&(f+=3),/\bsaved in\b|\bimplemented in\b|\bprovided in\b|\bstored in\b/.test(u)&&(f+=2),/\bquery\b/.test(u)&&/\bimplemented\b/.test(u)&&(f+=1),/\bi implemented\b|\bimplemented\s+(?:a\s+)?sql query\b/.test(u)&&(f+=2),p>0&&p>f&&n.push(l)}return un(n,e)}function fd(t){let n=Array.from(t.matchAll(/(?:^|\n)Task:\s*\n?/gi)).at(-1);if(!n||typeof n.index!="number")return t;let s=n.index+n[0].length;return t.slice(s)}function vv(t,e,n){let s=t.lastIndexOf(`
|
|
1168
|
+
`,e-1)+1,r=t.indexOf(`
|
|
1169
|
+
`,e+n),o=r===-1?t.length:r,i=t.slice(s,o),a=Math.max(0,e-s),l=Math.min(i.length,a+n),c=i.slice(0,a),p=Array.from(c.matchAll(/[.!?]\s+/g)).at(-1),f=p?.index===void 0?0:p.index+p[0].length,g=i.slice(l).match(/[.!?](?:\s+|$)/),b=g?.index===void 0?i.length:l+g.index+1;return i.slice(f,b)}function ro(t,e){let n=[];for(let s of t)if(!(s.role!=="assistant"||!Array.isArray(s.content)))for(let r of s.content)r.type==="tool_use"&&(e&&r.name!==e||n.push({name:r.name,input:r.input??{}}));return n}function hd(t){return!!t&&typeof t=="object"}function er(t){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(e=>er(e)).filter(e=>e.trim().length>0).join(`
|
|
1170
|
+
|
|
1171
|
+
`);if(!hd(t))return"";if(t.type==="text"&&typeof t.text=="string"||typeof t.text=="string")return t.text;if("content"in t){let e=er(t.content);if(e.trim().length>0)return e}return typeof t.output=="string"?t.output:typeof t.data=="string"?t.data:t.type==="image_url"?"[image]":t.type==="resource"?`[resource ${typeof t.uri=="string"?t.uri:typeof t.mimeType=="string"?t.mimeType:"resource"}]`:""}function Sv(t){return[er(t.content),er(t.assistant_content),er(t.assistant_only_content)].filter(e=>e.trim().length>0).join(`
|
|
1172
|
+
|
|
1173
|
+
`)}function Ue(t,e){let n=[],s=0;for(let r of t)if(!(r.role!=="assistant"||!Array.isArray(r.content)))for(let o of r.content)o.type==="tool_use"&&((!e||o.name===e)&&n.push({index:s,name:o.name,input:o.input??{}}),s+=1);return n}function Oe(t,e){let n=new Map,s=0;for(let o of t)if(!(o.role!=="assistant"||!Array.isArray(o.content)))for(let i of o.content)i.type==="tool_use"&&(n.set(i.id,{index:s,name:i.name,input:i.input??{}}),s+=1);let r=[];for(let o of t)if(!(o.role!=="user"||!Array.isArray(o.content)))for(let i of o.content){if(!hd(i)||i.type!=="tool_result")continue;let a=typeof i.tool_use_id=="string"?i.tool_use_id:"",l=n.get(a);l&&(e&&l.name!==e||r.push({index:l.index,name:l.name,input:l.input,content:Sv(i),isError:i.is_error===!0}))}return r}function kv(t,e){let n=new Set;for(let{name:s,input:r}of ro(t)){if(s!=="Write"&&s!=="Edit")continue;let o=typeof r.file_path=="string"?r.file_path:typeof r.notebook_path=="string"?r.notebook_path:null;!o||o.trim().length===0||n.add(yt(e,o))}return Array.from(n)}function xv(t,e){let n=t.match(/(?:[A-Za-z]:\\[^\s"'`]+|\/[^\s"'`]+)/g)??[];return un(n,e)}function ge(t,e=!1,n){return{message:t,blocking:e,...n?{toolPolicy:n}:{}}}function ps(t){return{message:t,stop:!0}}function Du(t,e){return ro(t,e).length}function Pv(t){return ro(t).length}function na(t){return ro(t,"Bash").map(e=>e.input.command).filter(e=>typeof e=="string"&&e.trim().length>0)}function Fu(t){try{let e=jt(t);return e.isFile()?e.size>0:!0}catch{return!1}}function Tv(t){try{let e=jt(t);return!e.isFile()||e.size>1024?!1:ed.test(Hn(t,"utf-8").trim())}catch{return!1}}function Gi(t,e=4096){try{let n=jt(t);return!n.isFile()||n.size>e?null:Hn(t,"utf-8").trim()}catch{return null}}function _v(t,e){let n=Number.parseFloat(t);if(!Number.isFinite(n)||n<=0)return 0;let s=(e??"bytes").toLowerCase();return Math.floor(s==="k"||s==="kb"||s==="kib"||s==="kilobytes"?n*1024:n)}function Rv(t){let e=[/(?:<|under|less\s+than|below)\s*(\d+(?:\.\d+)?)\s*(kib|kb|k|kilobytes|bytes?|b)\b[\s\S]{0,100}\b(?:compressed|gzip|gzipped)\b/i,/\b(?:compressed|gzip|gzipped)\b[\s\S]{0,100}(?:<|under|less\s+than|below)\s*(\d+(?:\.\d+)?)\s*(kib|kb|k|kilobytes|bytes?|b)\b/i];for(let n of e){let s=n.exec(t);if(!s)continue;let r=_v(s[1]??"",s[2]);if(r>0)return r}return null}function Ev(t){try{return jt(t).isFile()?py(Hn(t)).length:null}catch{return null}}function Cv(t){return/\.(?:c|cc|cpp|cxx|h|hpp|rs|go|py|js|ts|mjs|cjs|java|cs|rb|pl|sh|lua)$/i.test(t)}function Av(t,e=512*1024){try{let n=jt(t);return!n.isFile()||n.size>e?null:Hn(t,"utf-8")}catch{return null}}function Iv(t){let e=Zw.test(t),n=ev.test(t),s=tv.test(t);return e&&n||s}function Mv(t,e){let n=[],s=Rv(e),r=/\b(?:fully\s+independent|complete\s+isolation|must\s+not\s+invoke|do\s+not\s+invoke|without\s+(?:using|calling|invoking)\s+(?:the\s+)?(?:original|source|provided|compiled)?\s*(?:binary|program|executable|\.\/mystery))\b/i.test(e);for(let o of t){if(!Cv(o))continue;let i=s!==null?Ev(o):null;if(s!==null&&i!==null&&i>=s&&n.push(`${o} gzips to ${i} bytes, which violates the compressed-source limit of < ${s} bytes.`),!r)continue;let a=Av(o);if(a===null){try{let l=jt(o);l.isFile()&&l.size>512*1024&&n.push(`${o} is too large for an independence audit (${l.size} bytes); reverse-engineering submissions should be source, not embedded binary cargo.`)}catch{}continue}Iv(a)&&n.push(`${o} appears to preserve, embed, or invoke the original binary instead of reimplementing its behavior independently.`)}return n}function Ov(t){return t.replace(/\\r/g,"\r").replace(/\\n/g,`
|
|
1174
|
+
`).replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\'/g,"'").replace(/\\\\/g,"\\")}function Hi(t,e,n,s){if(!n||s===void 0||s.length>Zy||/^(?:it|them|this|that)$/i.test(so(n)))return;let o=un([n],e)[0];o&&t.set(o,{path:o,text:Ov(s)})}function $v(t,e){let n=new Map,s=/\b(?:create|place)\s+a\s+file\s+(?:called|named)\s+(?:"|')?([^\s"'`]+)(?:"|')?[.,;:]?\s*(?:write|put)\s+(?:"([^"]{0,4096})"|'([^']{0,4096})')\s+to\s+it\b/gis,r;for(;(r=s.exec(t))!==null;)Hi(n,e,r[1],r[2]??r[3]);let o=/\b(?:write|put)\s+(?:"([^"]{0,4096})"|'([^']{0,4096})')\s+(?:to|into|in)\s+(?:the\s+file\s+)?(?:"|')?([^\s"'`]+)(?:"|')?/gis,i;for(;(i=o.exec(t))!==null;)Hi(n,e,i[3],i[1]??i[2]);let a=/\b(?:file|path)\s+(?:"|')?([^\s"'`]+)(?:"|')?\s+(?:must\s+|should\s+)?(?:contain|contains|equal|equals)\s+(?:exactly\s+)?(?:"([^"]{0,4096})"|'([^']{0,4096})')/gis,l;for(;(l=a.exec(t))!==null;)Hi(n,e,l[1],l[2]??l[3]);return Array.from(n.values())}function Lv(t){try{let e=Hn(t.path,"utf-8");return e===t.text?null:e}catch{return""}}function Js(t){let e=t.replace(/\r/g,"\\r").replace(/\n/g,"\\n");return e.length>160?`${e.slice(0,157)}...`:e}function kn(t,e){return na(t).some(s=>e.some(r=>r.test(s)))}var Uu={official:6,runtime:5,self_check:5,specialized:4,comparison:4,build:2,generic:1};function tr(t){let e=t.replace(/\b[A-Z0-9_-]*(?:NO|WITHOUT|FIXED|RESOLVED|SUPERSEDED)[A-Z0-9_-]*(?:TRACEBACK|FAILURE|FAILED|ERROR|EXCEPTION)[A-Z0-9_-]*PASS\b/gi,"PASS").replace(/\b[A-Z0-9_-]*(?:TRACEBACK|FAILURE|FAILED|ERROR|EXCEPTION)[A-Z0-9_-]*(?:FIXED|RESOLVED|SUPERSEDED)[A-Z0-9_-]*PASS\b/gi,"PASS").replace(/\b0\s+failed\b/gi,"zero_failed").replace(/\bfailures?\s*[:=]\s*(?:0|\[\]|none)(?=\s|$|[;,])/gi,"failures_zero").replace(/\b(?:mis|mismatches?|diffs?|errors?)\s*[:=]?\s*0\b/gi,"mismatch_zero").replace(/\b(?:mae|mse|rmse|pixel[_ -]?(?:error|diff)|mean[_ -]?(?:absolute[_ -]?)?(?:error|diff)|max[_ -]?(?:error|diff)|maxdiff|max_diff)\s*[:=]?\s*0+(?:\.0+)?\b/gi,"metric_zero").replace(/\bno\s+failures?\b/gi,"no_failures").replace(/\bnot\s+failed\b/gi,"not_failed").replace(/\bwithout\s+failure\b/gi,"without_failure").replace(/\bexpected\s+failures?\b/gi,"expected_failures").replace(/\btimeout\s*[:=]\s*\d+(?:\.\d+)?\s*(?:ms|s|sec|seconds)?\b/gi,"timeout_limit").replace(/\b(?:deadline|time[-_ ]?limit)\s*[:=]\s*\d+(?:\.\d+)?\s*(?:ms|s|sec|seconds)?\b/gi,"time_limit").replace(/\bxfail(?:ed)?\b/gi,"xfail");return(/\b(?:NO|WITHOUT|FIXED|RESOLVED|SUPERSEDED)[A-Z0-9_-]*WARNING[A-Z0-9_-]*PASS\b/i.test(e)||/\bwarnings?[_ -]?as[_ -]?errors?\b/i.test(e))&&(e=e.replace(/^.*\bUserWarning:\s*Failed to initialize NumPy\b.*$/gmi,"numpy_warning_cleared").replace(/\bFailed to initialize NumPy\b/gi,"numpy_warning_cleared")),e}function gd(t){return uw.test(tr(t))}function nt(t){return rd.test(tr(t))}function mt(t){let e=tr(t);return hw.test(e)&&!rd.test(e)}function Nv(t,e){return t.name==="SqliteAnalyze"||t.name==="GcodeAnalyze"||t.name==="HtmlSanitizerAudit"||t.name==="ArtifactCompare"||t.name==="dispatch_agent"?!0:t.name!=="Bash"?nt(t.content)||mt(t.content):Qi.test(e)||_t.some(n=>n.test(e))||to.some(n=>n.test(e))||Jr.some(n=>n.test(e))||Qr.some(n=>n.test(e))||ea.some(n=>n.test(e))||no.some(n=>n.test(e))||eo.some(n=>n.test(e))||ta.some(n=>n.test(e))||nt(t.content)||mt(t.content)}function Bv(t){let e=t.trim().replace(/\\/g,"/").replace(/\/+$/g,"");return/^(?:\/app)?\/(?:tests?|test\.sh|run-tests\.sh|README\.md|instruction\.md)$/i.test(e)||/(?:^|[\/\\])(?:tests?|test\.sh|run-tests\.sh|README\.md|instruction\.md)$/i.test(e)}function Dv(t){if(t.name!=="LS"&&t.name!=="Read"&&t.name!=="Glob"||!/\b(?:File not found|ENOENT|No such file or directory|does not exist)\b/i.test(t.content))return!1;let e=typeof t.input.path=="string"?t.input.path:null,n=typeof t.input.file_path=="string"?t.input.file_path:null,s=typeof t.input.pattern=="string"?t.input.pattern:null;return[e,n,s].some(r=>typeof r=="string"&&Bv(r))}function Fv(t){return t.isError&&/\b(?:Completion guard policy blocked non-checkpoint tool call|Tool blocked by active completion-guard policy|Benchmark finite build should use conservative parallelism|Benchmark compute\/search command needs an explicit budget and checkpoint|Benchmark named dataset synthesis blocked)\b/i.test(t.content)}function Uv(t){return t.isError||t.name!=="Read"&&t.name!=="Grep"&&t.name!=="Glob"&&t.name!=="LS"&&t.name!=="Edit"&&t.name!=="Write"?!1:!/\b(?:SELF_CHECK|CONTRACT|VERIFIER|VALIDATION|THRESHOLD|METRIC|ARTIFACT|MODEL_LOAD|MODEL|INFERENCE|PREDICTION)[_-]?(?:PASS|FAIL|FAILED|ERROR)\b/i.test(t.content)}function ju(t){if(!t.isError)return!1;let e=tr(t.content);return/\b(?:AssertionError|FAILED|FAILURES?|Traceback|mismatch(?:ed|es)?|not identical|not equivalent|does not match|not match|differs?|wrong output)\b/i.test(e)||/\b(?:mae|mse|rmse|pixel[_ -]?(?:error|diff)|mean[_ -]?(?:absolute[_ -]?)?(?:error|diff)|max[_ -]?(?:error|diff)|maxdiff|max_diff)\s*[:=]?\s*(?!0+(?:\.0+)?\b)\d+(?:\.\d+)?\b/i.test(e)?!1:/\b(?:command not found|not found|No such file or directory|does not exist|ENOENT)\b/i.test(e)}function bd(t){return _t.some(e=>e.test(t))}function jv(t){return!sw.test(t)||bd(t)||Zi.test(t)||rw.test(t)?!1:!sd.test(t)}function Vv(t,e,n,s){return t.name!=="Bash"||!t.isError||n||s||!iw.test(e)?!1:lw.test(t.content)?!0:sd.test(e)?!1:aw.test(t.content)}function qv(t,e){return e.some(n=>Jt(t,n))}function Hv(t){return t==="SqliteAnalyze"||t==="GcodeAnalyze"||t==="HtmlSanitizerAudit"||t==="ArtifactCompare"||t==="dispatch_agent"}function zv(t,e,n,s,r){if(!s||!t.isError&&!r||ju(t)&&!Hv(t.name)&&t.name!=="Bash")return!1;if(t.name!=="Bash")return t.isError||r;let o=bd(e),i=qv(e,n);return Vv(t,e,o,i)||t.name==="Bash"&&ow.test(e)&&!o&&!i||!t.isError&&r&&jv(e)&&!i||ju(t)&&!o&&!i?!1:t.isError||r}function Wv(t){let e=t.split(/\r?\n/).map(i=>i.trim()).filter(i=>i.length>0),o=[/^next_repair_target:/i,/^-\s*(?:attack|browser|clean):/i,/\b(?:attack|browser|policy)_failures\s*=\s*[1-9]\d*\b/i,/\bclean_failures\s*=\s*[1-9]\d*\b/i,/\bclean_mismatches\s*=\s*[1-9]\d*\b/i,/\bTraceback\b|\bAssertionError\b|\bmismatch(?:ed|es)?\b/i].map(i=>e.find(a=>i.test(a))).find(i=>typeof i=="string")??e.find(i=>nt(i))??t.trim().replace(/\s+/g," ");return o.length>240?`${o.slice(0,237)}...`:o}function Xv(t,e){let n=`${e}
|
|
1175
|
+
${t.content}`;if(t.name==="SqliteAnalyze"||t.name==="GcodeAnalyze"||t.name==="HtmlSanitizerAudit"||t.name==="ArtifactCompare"||t.name==="dispatch_agent")return"specialized";if(t.name==="Bash"){if(_t.some(s=>s.test(e)))return"official";if(/\b(?:py_compile|tsc\s+(?:--noEmit\b|-p\b)|mypy\b|ruff\b|eslint\b|cargo\s+check\b|go\s+vet\b|shellcheck\b)\b/i.test(e))return"build";if(xn.test(n)||ud.test(n)||/\bSELF_CHECK_PASS\b/i.test(n)||ld.test(n)||cd.test(n)||/\b(?:self[- ]?check|contract|round[- ]?trip|read\s+back|readback|assert(?:ed)?|invariant)\b/i.test(n))return"self_check";if(/\b(?:python3?|node|ruby|perl|php|java|go|cargo|npm|pnpm|yarn|bun)\b/i.test(e)&&/(?:^|\s)(?:\.\/|\/app\/|src\/|app\/|bin\/|scripts\/)[^\s;&|]+/i.test(e))return"runtime";if(/\b(?:cmp|diff|sha(?:1|256|512)sum|md5sum|jq|sqlite3|readelf|objdump|file)\b/i.test(e))return"comparison";if(to.some(s=>s.test(e))||Jr.some(s=>s.test(e))||Qr.some(s=>s.test(e))||ea.some(s=>s.test(e))||no.some(s=>s.test(e))||eo.some(s=>s.test(e))||ta.some(s=>s.test(e)))return"specialized"}return/\b(?:Traceback|AssertionError|ModuleNotFoundError|SyntaxError|TypeError|ValueError|FAILED|FAILURES?)\b/i.test(t.content)?"runtime":"generic"}function Kv(t,e){return t.index>e.index&&Uu[t.kind]>=Uu[e.kind]}function Vu(t,e=[]){let n=new Map;for(let i of Ue(t,"Bash")){let a=typeof i.input.command=="string"?i.input.command:"";n.set(i.index,a)}let s=[],r=[];for(let i of Oe(t)){let a=i.name==="Bash"?n.get(i.index)??"":"";if(Dv(i)||Fv(i)||Uv(i))continue;let l=Nv(i,a),c=nt(i.content),u=mt(i.content),p=Xv(i,a);zv(i,a,e,l,c)&&s.push({index:i.index,kind:p,toolName:i.name,summary:Wv(i.content||a||`${i.name} failed`)}),!i.isError&&l&&u&&r.push({index:i.index,kind:p})}return s.filter(i=>!r.some(a=>Kv(a,i))).sort((i,a)=>a.index-i.index)[0]??null}function Gv(t){let e=Ue(t,"Bash"),n=new Map(Oe(t,"Bash").map(r=>[r.index,r])),s=0;for(let r of e){let o=typeof r.input.command=="string"?r.input.command:"";if(!nw.test(o))continue;let i=n.get(r.index);i&&(i.isError||Cu.test(i.content))&&Cu.test(i.content)&&(s+=1)}return s}function Yv(t){let e=t.trim().toLowerCase();if(!e)return null;let n=0,s=!1;for(let r of e.matchAll(/(\d+)\s*(h|m|s)\b/g)){let o=Number.parseInt(r[1]??"",10);if(!Number.isFinite(o))continue;s=!0;let i=r[2];i==="h"&&(n+=o*60*60*1e3),i==="m"&&(n+=o*60*1e3),i==="s"&&(n+=o*1e3)}return s?n:null}function Jv(t){let e=new Map;for(let r of Oe(t,"Bash")){if(r.isError||r.input.run_in_background!==!0)continue;let o=r.content.match(/\bBackground task started:\s*([A-Za-z0-9_.-]+)/i)?.[1],i=typeof r.input.command=="string"?r.input.command:"";o&&i.trim().length>0&&e.set(o,i)}let n=new Map,s=null;for(let r of Oe(t,"TaskOutput")){if(r.isError)continue;let o=r.content;if(!/\bStatus:\s*running\b/i.test(o))continue;let i=(typeof r.input.task_id=="string"?r.input.task_id:null)??o.match(/\bTask:\s*([A-Za-z0-9_.-]+)/i)?.[1]??"unknown",a=o.match(/\bCommand:\s*(.+)/i)?.[1]?.trim()??"",l=e.get(i)??"",c=[a,l].filter(C=>C.trim().length>0).join(`
|
|
1176
|
+
`),u=o.match(/\bProgress:\s*([A-Za-z_-]+)/i)?.[1]?.toLowerCase()??"",p=o.match(/\bIdle:\s*([^\r\n]+)/i)?.[1]?.trim()??"",f=Yv(p),m=Number.parseInt(o.match(/\bOutput delta bytes:\s*(\d+)/i)?.[1]??"0",10),g=Number.parseInt(o.match(/\bPolls without output:\s*(\d+)/i)?.[1]??"0",10),b=/\b(?:Iteration\s+\d+|iter(?:ation)?\s*[#: ]?\s*\d+|epoch\s+\d+|loss\s*[=:]|accuracy\s*[=:]|Snapshotting|checkpoint|caffemodel)\b/i.test(o),v=/\b(?:caffe\s+train|fasttext\b|fit\s*\(|model\.fit|trainer\.fit|solver=|max_iter|epochs?)\b/i.test(c)||b;if(v&&b){n.set(i,0);continue}if(v&&Number.isFinite(m)&&m===0&&g<6&&(f===null||f<10*6e4))continue;if(!(u==="stalled"&&(!v||g>=6)||Number.isFinite(m)&&m===0&&g>=(v?6:2)||Number.isFinite(m)&&m===0&&f!==null&&f>=(v?10*6e4:5*6e4))){n.set(i,0);continue}let P=(n.get(i)??0)+1;n.set(i,P),(u==="stalled"||P>=2)&&(s={index:r.index,taskId:i,command:c,idleText:p,pollsWithoutOutput:g,repeatedNoProgressPolls:P,progressState:u||"idle"})}return s}function Yt(t,e){return e.length===0||e.some(n=>Jt(t,n))}function Qv(t){return Aw.test(t)}function Zv(t){let e=new Set;for(let n of t.matchAll(/\bworld[_ -]?sizes?\b(?:\s*(?:of|=|:|are|is|including|for)?\s*)?([^\r\n.;]{0,100})/gi)){let s=n[1]??"";for(let r of s.matchAll(/\b([1-9]\d*)\b/g)){let o=Number.parseInt(r[1]??"",10);Number.isInteger(o)&&o>0&&o<=16&&e.add(o)}}return Array.from(e).sort((n,s)=>n-s)}function eS(t,e){let n=String(e).replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`\\bworld[_ -]?sizes?\\b[\\s\\S]{0,100}\\b${n}\\b`,"i").test(t)||new RegExp(`\\b(?:ws|world)\\s*=?\\s*${n}\\b`,"i").test(t)||new RegExp(`\\bworld_size\\s*=?\\s*${n}\\b`,"i").test(t)}function tS(t,e){let n=String(e).replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`\\brank\\s*=?\\s*${n}\\b`,"i").test(t)||new RegExp(`\\branks?\\s*[:=]\\s*\\[[^\\]]*\\b${n}\\b[^\\]]*\\]`,"i").test(t)}function nS(t){return/\branks?[_ -]?covered\s*[:=]?\s*all\b/i.test(t)||/\ball\s+ranks?\b/i.test(t)}function sS(t,e){return e.filter(n=>!eS(t,n))}function rS(t,e,n){return Yt(t,n)?!0:n.some(s=>{let r=s.replace(/\\/g,"/");return e.includes(r)||e.includes(qn(s))})}function oS(t,e,n,s,r){let o=new Map;for(let i of Ue(t,"Bash")){let a=typeof i.input.command=="string"?i.input.command:"";o.set(i.index,a)}for(let i of Oe(t,"Bash")){if(i.index<=e||i.isError)continue;let a=o.get(i.index)??"",l=`${a}
|
|
1177
|
+
${i.content}`;if(nt(l)||Bw.test(l))continue;if((Nw.test(a)||_t.some(b=>b.test(a)))&&mt(i.content))return!0;if(!rS(a,l,n))continue;let u=i.content,p=Ow.test(u),f=Iw.test(u)||p,m=Mw.test(u)||p;if(!f||!m||!$w.test(u)||sS(u,s).length>0||r&&!/\b(?:grad|gradient|backward|autograd)\b/i.test(u))continue;let g=s.at(-1)??0;if(!(g>=4&&!nS(u)&&Array.from({length:g},(v,w)=>w).filter(v=>!tS(u,v)).length>0)&&Lw.test(i.content))return!0}return!1}function iS(t,e,n){if(e<0)return[];let s=new Map;for(let o of Ue(t,"Bash")){let i=typeof o.input.command=="string"?o.input.command:"";s.set(o.index,i)}let r=[];for(let o of Oe(t,"Bash")){if(o.index<=e)continue;let i=s.get(o.index)??"",a=_t.some(u=>u.test(i)),l=Yt(i,n),c=Qi.test(i);!a&&!c||!a&&!l||r.push({event:o,toolName:o.name,command:i,isOfficialVerifier:a,mentionsRequiredOutput:l})}for(let o of Oe(t,"HtmlSanitizerAudit")){if(o.index<=e)continue;let i=JSON.stringify(o.input),a=Yt(i,n);a&&r.push({event:o,toolName:o.name,command:i,isOfficialVerifier:!1,mentionsRequiredOutput:a})}for(let o of Oe(t,"ArtifactCompare")){if(o.index<=e)continue;let i=JSON.stringify(o.input),a=Yt(i,n);a&&r.push({event:o,toolName:o.name,command:i,isOfficialVerifier:!1,mentionsRequiredOutput:a})}return r.sort((o,i)=>o.event.index-i.event.index)}function yd(t){let e=`${t.command}
|
|
1178
|
+
${t.event.content}`;return t.event.isError||gd(t.event.content)||nt(e)}function aS(t){return yd(t)?!1:t.isOfficialVerifier?!0:t.mentionsRequiredOutput?t.toolName==="HtmlSanitizerAudit"?mt(t.event.content):t.toolName==="ArtifactCompare"?nr(t.event):Zi.test(t.command)?!0:dw.test(t.command)?pw.test(t.event.content):cw.test(t.event.content):!1}function lS(t,e,n){return[t.file_path,t.path,t.notebook_path,t.image_path,t.target_file].filter(r=>typeof r=="string"&&r.trim().length>0).some(r=>yt(n,r)===e||Jt(r,e))}function cS(t,e){if(!Jt(t,e))return!1;if(jw.test(t))return!0;let n=qn(e).toLowerCase().match(/\.[a-z0-9]+$/)?.[0]??"";return([".py",".js",".mjs",".cjs",".sh",".bash",".rb",".pl",".php",".jar",".go",".rs",".sql",".c",".cc",".cpp",".h",".hpp",".java",".ts",".tsx"].includes(n)||/\b(?:script|extract|filter|convert|solve|main|run|server|client|app)\b/i.test(qn(e)))&&$u.test(t)?!0:/\b(?:validate|verify|check|eval|test|inspect|analy[sz]e)[\w.-]*\.(?:py|js|mjs|cjs|sh|bash|rb|pl|php)\b/i.test(t)&&$u.test(t)}function uS(t,e,n,s){if(n.length===0)return{latestIndex:-1,missingPaths:[]};let r=new Set,o=-1,i=new Map(Oe(t).map(a=>[a.index,a]));for(let a of Ue(t)){if(a.index<=e)continue;let l=i.get(a.index);if(!l||l.isError)continue;if(a.name==="Read"||a.name==="ReadImage"||a.name==="NotebookRead"){for(let p of n)lS(a.input,p,s)&&(r.add(p),o=Math.max(o,a.index));continue}if(a.name!=="Bash")continue;let c=typeof a.input.command=="string"?a.input.command:"";if(!(gd(l.content)||!(Vw.test(l.content)||mt(l.content))))for(let p of n)cS(c,p)&&(r.add(p),o=Math.max(o,a.index))}return{latestIndex:o,missingPaths:n.filter(a=>!r.has(a))}}function dS(t,e,n){let s=iS(t,e,n),r=-1;for(let o of s)aS(o)&&(r=Math.max(r,o.event.index));return r<0?!1:!s.some(o=>o.event.index>r&&yd(o))}function qu(t,e){if(e<0)return!1;let n=new Map;for(let s of Ue(t,"Bash")){let r=typeof s.input.command=="string"?s.input.command:"";n.set(s.index,r)}return Oe(t).some(s=>{if(s.index<=e||s.isError)return!1;if(s.name==="ArtifactCompare")return!0;if(s.name!=="Bash")return!1;let r=n.get(s.index)??"";return Qi.test(r)||_t.some(o=>o.test(r))})}function pS(t,e,n){let s=new Map;for(let r of Ue(t,"Bash")){let o=typeof r.input.command=="string"?r.input.command:"";s.set(r.index,o)}return Oe(t,"Bash").some(r=>{if(r.index<=e||r.isError)return!1;let o=s.get(r.index)??"",i=`${o}
|
|
1179
|
+
${r.content}`;return!to.some(a=>a.test(o))||nt(i)||!Yt(o,n)?!1:xn.test(r.content)||mw.test(r.content)})}function Hu(t,e,n,s=""){let r=rk(s),o=new Map;for(let i of Ue(t,"Bash")){let a=typeof i.input.command=="string"?i.input.command:"";o.set(i.index,a)}return Oe(t,"Bash").some(i=>{if(i.index<=e||i.isError)return!1;let a=o.get(i.index)??"",l=`${a}
|
|
1180
|
+
${i.content}`;return!ta.some(c=>c.test(l))||nt(l)||!Yt(a,n)||r&&!zy.test(l)?!1:xn.test(i.content)||mt(i.content)||Zi.test(a)})}function mS(t,e,n){let s=new Map;for(let i of Ue(t,"Bash")){let a=typeof i.input.command=="string"?i.input.command:"";s.set(i.index,a)}if(Oe(t,"Bash").some(i=>{if(i.index<=e||i.isError)return!1;let a=s.get(i.index)??"";if(!Yt(a,n))return!1;let l=`${a}
|
|
1181
|
+
${i.content}`;return nt(l)?!1:zu(l,i.content)}))return!0;let o=new Map;for(let i of Ue(t,"HtmlSanitizerAudit"))o.set(i.index,JSON.stringify(i.input));return Oe(t,"HtmlSanitizerAudit").some(i=>{if(i.index<=e||i.isError)return!1;let a=o.get(i.index)??"";if(!Yt(a,n))return!1;let l=`${a}
|
|
1182
|
+
${i.content}`;return nt(l)?!1:zu(l,i.content)})}function zu(t,e){if(!/\b(?:CONTRACT|SELF_CHECK|ROUNDTRIP|SECURITY|XSS|SANITI[ZS]ER)[_-]?PASS\b/i.test(e))return!1;let n=Nu.filter(w=>w.pattern.test(t)),s=n.some(w=>w.key==="clean-roundtrip"),r=n.length===Nu.length,o=nv.test(t),i=sv.test(t),a=rv.test(t),l=ov.test(t),c=iv.test(t),u=av.test(t),p=lv.test(t),f=cv.test(t),m=l&&c||p&&u&&f,g=uv.test(t),b=dv.test(t),v=pv.every(w=>w.pattern.test(t));return r&&s&&o&&i&&a&&m&&g&&b&&v}function fS(t,e,n=""){let s=new Map;for(let o of Ue(t,"Bash")){let i=typeof o.input.command=="string"?o.input.command:"";s.set(o.index,i)}let r=fv.test(n);return Oe(t,"Bash").some(o=>{if(o.index<=e||o.isError)return!1;let i=s.get(o.index)??"",a=`${i}
|
|
1183
|
+
${o.content}`;if(!Bu.test(i)&&!/\b(?:secret|credential|token|leak|contaminated)\b/i.test(a)||nt(a)||mv.test(a))return!1;let l=!r||cd.test(a)||/<your-[a-z0-9-]+>/i.test(a)&&/\b(?:placeholder(?:s)?|replacement(?:s)?|exact)\b/i.test(a);if(/\b(?:DIFF_SCOPE|SCOPE|REPO_SURGERY)[_-]?PASS\b/i.test(o.content)&&(/\bSECRET_SCAN[_-]?PASS\b/i.test(o.content)||/\bsecret(?:_|\s+)matches?\s*[:=]\s*0\b/i.test(o.content))&&(/\bunexpected(?:_|\s+)files?\s*[:=]\s*(?:0|\[\]|none)\b/i.test(o.content)||/\bno\s+other\s+files\s+changed\b/i.test(o.content)))return l;let u=Bu.test(i)&&/\b(?:git\s+(?:diff|status)|diff[_ -]?files?|changed[_ -]?files?|modified[_ -]?files?|name-only|unexpected)\b/i.test(a),p=/\b(?:secret|credential|token|leak|contaminated)\b[\s\S]{0,120}\b(?:matches?|count|remaining|scan)\b/i.test(a);return u&&p&&l&&ld.test(a)})}function hS(t,e,n){let s=new Map;for(let r of Ue(t,"Bash")){let o=typeof r.input.command=="string"?r.input.command:"";s.set(r.index,o)}return Oe(t,"Bash").some(r=>{if(r.index<=e||r.isError)return!1;let o=s.get(r.index)??"",i=`${o}
|
|
1184
|
+
${r.content}`;if(nt(r.content))return!1;if(_t.some(f=>f.test(o)))return mt(r.content);let l=Yt(o,n)||n.some(f=>i.includes(qn(f))),c=hv.test(i),u=ud.test(r.content),p=gv.test(r.content)&&!/\b(?:assert|<=|>=|within|bounds?|threshold|residual|rmse|tm\b|translation|order|margin|all\s+primers?|all\s+components?)\b/i.test(i);return l&&c&&u&&!p})}function gS(t,e,n){let s=new Map;for(let o of Ue(t,"Bash")){let i=typeof o.input.command=="string"?o.input.command:"";s.set(o.index,i)}let r=bw.test(n);return Oe(t,"Bash").some(o=>{if(o.index<=e||o.isError)return!1;let a=`${s.get(o.index)??""}
|
|
1185
|
+
${o.content}`;if(!(gw.some(p=>p.test(a))||/\bsend_signal\s*\(/i.test(a)||/\bKeyboardInterrupt\b/i.test(a)||/\bproc\.(?:terminate|kill)\s*\(/i.test(a))||r&&vw.test(a)||r&&/\basyncio\b/i.test(a)&&!Sw.test(a))return!1;let c=!r||yw.some(p=>p.test(o.content)),u=ww.some(p=>p.test(o.content));return c&&u})}function bS(t,e,n){let s=kd(n),r=xd(n),o=new Map;for(let i of Ue(t,"Bash")){let a=typeof i.input.command=="string"?i.input.command:"";o.set(i.index,a)}return Oe(t,"Bash").some(i=>{if(i.index<=e||i.isError)return!1;let a=o.get(i.index)??"",l=`${a}
|
|
1186
|
+
${i.content}`;if(nt(l))return!1;if(_t.some(g=>g.test(a)))return mt(i.content);if(!qw.test(l)||Hw.test(a)&&!/\b(?:curl|requests\.(?:get|post|put|delete)|httpx|grpcurl|grpc\.|ssh\b|sshpass|git\s+(?:clone|push|ls-remote|fetch)|sendkey|qmp|human-monitor-command|telnet\b[\s\S]{0,120}\b(?:login|shell|prompt))\b/i.test(l))return!1;if(s){let g=Ww.test(l),b=Xw.test(l);if(!g||!b)return!1}if(r&&!Kw.test(l))return!1;let p=zw.test(l),f=mt(i.content),m=i.content.trim().length>0&&/\b(?:curl|requests\.(?:get|post|put|delete)|httpx|grpcurl|grpc\.|ssh\b|sshpass|git\s+(?:clone|push|ls-remote|fetch)|sendkey|qmp|human-monitor-command|telnet)\b/i.test(a);return p||f||m})}function Qs(t,e){let n=t.match(e);if(!n?.[1])return null;let s=Number.parseInt(n[1],10);return Number.isFinite(s)?s:null}function yS(t){let e=Qs(t,/\bfilesz\s+(\d+)\b/i),n=Qs(t,/\bmemsz\s+(\d+)\b/i),s=Qs(t,/\bnode\s+entries\s+(\d+)\b/i)??Qs(t,/\bout_count\s+(\d+)\b/i)??Qs(t,/\bcount\s+(\d+)\b/i);return e===null||n===null||s===null?!1:n>e&&s>=n}function wS(t,e){if(e<0)return!1;let n=new Map;for(let s of Ue(t,"Bash")){let r=typeof s.input.command=="string"?s.input.command:"";n.set(s.index,r)}return Oe(t,"Bash").some(s=>{if(s.index<=e||s.isError)return!1;let r=n.get(s.index)??"",o=`${r}
|
|
1187
|
+
${s.content}`,i=/\bnode\b[\s\S]{0,240}\bextract\.js\b/i.test(r),a=/\bpython3?\b/i.test(r)&&/\b(?:ELF|PT_LOAD|readelf|struct|p_filesz|filesz|file-backed|file backed)\b/i.test(o),l=/\b(?:match|matches|matched|equal|equals|identical)\s+(?:True|true|yes|1)\b/i.test(s.content)||/\ball_int\s+(?:True|true|yes|1)\b/i.test(s.content),c=/\b(?:p_filesz|filesz|file-backed|file backed)\b/i.test(o);return!(!i||!a||!l||!c||yS(s.content))})}function vS(t){let e=na(t).join(`
|
|
1188
|
+
`);return e?!!(/\bpd\.read_csv\s*\(/i.test(e)&&/\bpd\.read_parquet\s*\(/i.test(e)&&/\bassert_frame_equal\s*\(/i.test(e)||/\bpyarrow\b/i.test(e)&&/\bread_csv\s*\(/i.test(e)&&/\bread_table\s*\(/i.test(e)&&/\bto_pandas\s*\(/i.test(e)&&/\bassert_frame_equal\s*\(/i.test(e)):!1}function SS(t,e){let n=new Map;for(let s of Ue(t,"Bash")){let r=typeof s.input.command=="string"?s.input.command:"";n.set(s.index,r)}return Oe(t,"Bash").some(s=>{if(s.index<=e||s.isError)return!1;let o=`${n.get(s.index)??""}
|
|
1189
|
+
${s.content}`;if(nt(o))return!1;let i=/\bsynonyms\.txt\b/i.test(o)||/\b(?:allowed|allowlist|whitelist)\s+(?:substitutions?|words?|tokens?)\b/i.test(o),a=/\b(?:token|word)s?\b[\s\S]{0,180}\b(?:match(?:es|ed)?|same|unchanged|preserv(?:ed|ation)|equal|==|0\s+(?:added|removed|deleted))\b/i.test(o)||/\b(?:original|before|expected)[_-]?(?:token|word)s?\s*[:=]\s*(\d+)\b[\s\S]{0,180}\b(?:modified|after|actual)[_-]?(?:token|word)s?\s*[:=]\s*\1\b/i.test(o)||/\b(?:token|word)[_-]?count[_-]?pass\b/i.test(o),l=/\b(?:allowed|synonym|substitution|replacement)[_-]?(?:only|check|validation)?[_-]?pass\b/i.test(o)||/\b(?:illegal|disallowed|unexpected|outside[_ -]?synonyms?)[_-]?(?:changes?|tokens?|words?)?\s*[:=]\s*(?:0|\[\]|none)\b/i.test(o)||/\b(?:only|all)\s+(?:allowed|synonym)\s+(?:substitutions?|replacements?|changes?)\b/i.test(o),c=/\b(?:CONSTRAINED_EDIT|SYNONYM_SUBSTITUTION|TOKEN_COUNT|WORD_COUNT|ALLOWED_SUBSTITUTION|TEXT_CONTRACT)[_-]?PASS\b/i.test(s.content)||xn.test(s.content);return i&&a&&l&&c})}function kS(t){return/\b(?:coords_[xy]|list(?:s|ed)?|array|polyline)\b/i.test(t)}function xS(t){let e=/\b(?:ast\.literal_eval|json\.loads)\s*\(/i.test(t),n=/\bisinstance\s*\([^,\r\n]+,\s*list\s*\)/i.test(t)||/\btype\s*\([^)]*\)\s+is\s+list\b/i.test(t),s=/\bisinstance\s*\([^)]*,\s*\(\s*list\s*,\s*(?:tuple|np\.ndarray|numpy\.ndarray)/i.test(t)||/\bisinstance\s*\([^)]*,\s*\(\s*(?:tuple|np\.ndarray|numpy\.ndarray)\s*,\s*list/i.test(t);return e&&n&&!s}function PS(t,e){let n=kS(e),s=new Map;for(let r of Ue(t,"Bash")){let o=typeof r.input.command=="string"?r.input.command:"";s.set(r.index,o)}return Oe(t,"Bash").some(r=>{if(r.isError)return!1;let o=s.get(r.index)??"",i=`${o}
|
|
1190
|
+
${r.content}`,a=/\b(?:pd\.read_csv|pandas\.read_csv|csv\.DictReader|csv\.reader|json\.loads|json\.load|ast\.literal_eval)\b/i.test(i),l=/\bassert\b/i.test(i)&&/\b(?:columns?|rows?|len\s*\(|shape|dtype|isinstance|list|dict|coords_[xy]|schema|no overlap|contiguous)\b/i.test(i),c=/\b(?:CONTRACT|SELF_CHECK|READBACK|SCHEMA)[_-]?PASS\b/i.test(r.content),u=/\bpy_compile\b/i.test(o)||!/\b(?:ast\.literal_eval|json\.loads|json\.load|isinstance|columns?|shape|dtype|coords_[xy]|schema)\b/i.test(i)&&/\b(?:exists|row count|rows?\s+\d+)\b/i.test(i);return a&&l&&c&&!u&&(!n||xS(i))})}function wd(t){return t.trim().match(/^:?\s*call\s+setreg\(\s*['"]([a-z])['"]\s*,\s*(['"])(.*)\2\s*\)$/i)}function TS(t){return t.trim().match(/^:%normal!\s+@([a-z])$/i)}function _S(t,e){let n=t.trim();if(n===":wq"||n===":x")return!0;let s=TS(n);if(s?.[1])return e.size===0||e.has(s[1].toLowerCase());let r=wd(n);return r?.[1]?e.size===0||e.has(r[1].toLowerCase()):!1}function RS(t){let e=new Set;for(let n of t.matchAll(/\bsetreg\(\s*['"]([a-z])['"]/gi))n[1]&&e.add(n[1].toLowerCase());for(let n of t.matchAll(/%normal!\s*@([a-z])/gi))n[1]&&e.add(n[1].toLowerCase());for(let n of t.matchAll(/\bregisters?\s+([a-z](?:\s*,\s*[a-z])*(?:\s*,?\s*and\s+[a-z])?)(?=\s*(?:[.,;:]|\bwith\b|\busing\b|\bfor\b|\(|$))/gi))for(let s of(n[1]??"").match(/[a-z]/gi)??[])e.add(s.toLowerCase());return e.size===0&&/\bthree\s+distinct\b[\s\S]{0,120}\bmacros?\b/i.test(t)&&(e.add("a"),e.add("b"),e.add("c")),Array.from(e).sort()}function ES(t){let e=t.match(/<\s*(\d+)\s+total\s+keystrokes/i);if(!e?.[1])return null;let n=Number.parseInt(e[1],10);return Number.isFinite(n)&&n>0?n:null}function CS(t,e){return t.find(n=>/\.vim$/i.test(n))??e.find(n=>/\.vim$/i.test(n))??null}function AS(t,e){let n=t.match(/\btransform\s+([^\s"'`]+)\s+(?:[\s\S]{0,300}?)\bmatch\s+([^\s"'`]+)\s+exactly/i),s=un([n?.[1]??""].filter(Boolean),e)[0]??null,r=un([n?.[2]??""].filter(Boolean),e)[0]??null;return{inputPath:s,expectedPath:r}}function IS(t,e){let n;try{n=Hn(t,"utf-8")}catch{return[`${t} could not be read.`]}let s=n.split(/\r?\n/).map(u=>u.trim()).filter(u=>u.length>0&&!u.startsWith('"')),r=[],o=RS(e),i=new Set(o),a=s.filter(u=>!_S(u,i));a.length>0&&r.push(`contains command lines outside the allowed Vim macro contract: ${a.slice(0,3).join(" | ")}`),s.some(u=>u===":wq"||u===":x")||r.push("is missing an exact final :wq or :x line");for(let u of o){let p=new RegExp(`^:?\\s*call\\s+setreg\\(\\s*['"]${u}['"]\\s*,`,"i"),f=new RegExp(`^:%normal!\\s+@${u}$`,"i");s.some(m=>p.test(m))||r.push(`is missing call setreg('${u}', ...)`),s.some(m=>f.test(m))||r.push(`is missing :%normal! @${u}`)}let l=new Map;for(let u of s){let p=wd(u);p?.[1]&&p[3]!==void 0&&l.set(p[1].toLowerCase(),p[3])}for(let[u,p]of l)/\\?<CR>/i.test(p)&&r.push(`macro register ${u} uses <CR> key notation; use an explicit \\r command terminator inside the setreg string for headless Vim validation`),/:\s*%[a-z]*/i.test(p)&&r.push(`macro register ${u} contains a whole-file Ex range such as :%s; macros executed by :%normal! run once per line, so use line-local commands such as 0:s/.../.../\\r instead`);if(/\bnon-empty\s+macros?\b/i.test(e))for(let u of o)(l.get(u)??"").length===0&&r.push(`macro register ${u} is empty`);if(/\bdistinct\b[\s\S]{0,80}\bmacros?\b/i.test(e)){let u=o.map(p=>l.get(p)??"");u.length>1&&new Set(u).size!==u.length&&r.push("required macro registers are not distinct")}let c=ES(e);if(c!==null){let u=o.reduce((p,f)=>p+(l.get(f)??"").length,0);u>=c&&r.push(`required macro registers use ${u} keystrokes, which is not below ${c}`)}return r}function oo(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Wu(t){let e=Array.from(new Set([t,t.replace(/\\/g,"/"),qn(t)].filter(Boolean)));return String.raw`(?:"|')?(?:${e.map(oo).join("|")})(?:"|')?`}function Jt(t,e){let n=t.replace(/\\/g,"/"),s=e.replace(/\\/g,"/");return n.includes(s)?!0:new RegExp(String.raw`(^|[^A-Za-z0-9_.-])${oo(qn(e))}($|[^A-Za-z0-9_.-])`).test(n)}function MS(t,e,n){let s=Wu(e),r=Wu(n);return[new RegExp(String.raw`(?:^|[;&|]\s*)cp(?:\s+-[^\s]+)*\s+${s}\s+${r}(?:\s|$|[;&|])`,"i"),new RegExp(String.raw`(?:^|[;&|]\s*)cat\s+${s}\s*>\s*${r}(?:\s|$|[;&|])`,"i"),new RegExp(String.raw`(?:^|[;&|]\s*)rsync(?:\s+-[^\s]+)*\s+${s}\s+${r}(?:\s|$|[;&|])`,"i"),new RegExp(String.raw`(?:^|[;&|]\s*)install(?:\s+-[^\s]+|\s+\d+)*\s+${s}\s+${r}(?:\s|$|[;&|])`,"i")].some(a=>a.test(t))?!0:[new RegExp(String.raw`shutil\.copy(?:file)?\s*\(\s*${s}\s*,\s*${r}`,"i"),new RegExp(String.raw`copyfile\s*\(\s*${s}\s*,\s*${r}`,"i"),new RegExp(String.raw`${r}[\s\S]{0,200}\.write_bytes\s*\([\s\S]{0,200}${s}[\s\S]{0,120}\.read_bytes\s*\(`,"i")].some(a=>a.test(t))}function OS(t,e,n){if(!e||!n)return null;let s=null;for(let r of Ue(t,"Bash")){let o=typeof r.input.command=="string"?r.input.command:"";!Jt(o,n)||!Jt(o,e)||MS(o,n,e)&&(s={index:r.index,command:o,sourcePath:n,destinationPath:e})}return s}function vd(t,e){return/\bgen_large_csv\.py\b[\s\S]{0,120}\binput\b/i.test(t)||/\brun-tests\.sh\b/i.test(t)||/\bpytest\b[\s\S]{0,160}\btest_outputs\.py\b/i.test(t)?!0:!e||!Jt(t,e)?!1:/\brestore(?:d)?\b[\s\S]{0,120}\b(?:original|source|fresh)\b/i.test(t)}function $S(t,e){let n=-1;for(let s of Ue(t,"Bash")){let r=typeof s.input.command=="string"?s.input.command:"";vd(r,e)&&(n=Math.max(n,s.index))}return n}function LS(t,e){return!e||!Jt(t,e)?!1:t.split(/(?:&&|\|\||;|\r?\n)+/g).map(s=>s.trim()).filter(s=>s.length>0).some(s=>Jt(s,e)?/^(?:(?:env|command|timeout|stdbuf|xargs)\s+(?:\S+\s+){0,8})?vim(?:\s|$)/i.test(s)&&(/(?:^|\s)-(?:Nu|n|E|s|S|c)\b/i.test(s)||/\s-S(?:\s|$)/i.test(s)):!1)}function NS(t,e,n=Number.POSITIVE_INFINITY){let s=-1;for(let r of Ue(t,"Bash")){if(r.index>=n)continue;let o=typeof r.input.command=="string"?r.input.command:"";LS(o,e)&&(s=Math.max(s,r.index))}return s}function BS(t,e,n,s,r){return n<0||r<=n||s>n&&r>s||vd(t,e)?!0:!(e&&Jt(t,e))}function Xu(t,e,n,s=null,r=-1,o=-1){if(e<0)return!1;let i=new Map;for(let l of Ue(t,"Bash")){let c=typeof l.input.command=="string"?l.input.command:"";i.set(l.index,c)}let a=n.split(/[\\/]/).pop()??n;return Oe(t,"Bash").some(l=>{if(l.index<=e||l.isError)return!1;let c=i.get(l.index)??"",u=`${c}
|
|
1191
|
+
${l.content}`,p=/\bvim\b[\s\S]*(?:^|\s)-Nu\s+NONE\b[\s\S]*(?:^|\s)-S(?:\s|$)/i.test(c),f=/\bPASS\s+script(?:[_ -]?contract|\s+contract)?\b/i.test(u);if(!p&&!f||!c.includes(n)&&!c.includes(a)&&!f||!BS(c,s,r,o,l.index))return!1;let m=/\b(?:VIM_EXIT|EXIT):?0\b/i.test(u)||/\bexit\s+0\b/i.test(u),g=/\b(?:BYTE_MATCH|MATCH)\s+(?:True|true|yes|1)\b/i.test(u)||/\bBYTES_EQUAL\s+(?:True|true|yes|1)\b/i.test(u)||/\bCMP(?:_EXIT)?:0\b/i.test(u)||/\bSELF_CHECK_PASS\b/i.test(u)||/\b(?:byte[-_ ]?for[-_ ]?byte|identical|no differences)\b/i.test(u)||/\bcmp\b[\s\S]*\b(?:&&\s*echo|no differences|identical|MATCH)\b/i.test(u);return m&&g})}function Gr(t,e,n){let s=-1;for(let r of t){if(r.name!=="Write"&&r.name!=="Edit")continue;let o=typeof r.input.file_path=="string"?r.input.file_path:typeof r.input.notebook_path=="string"?r.input.notebook_path:null;o&&e.includes(yt(n,o))&&(s=Math.max(s,r.index))}return s}function zi(t,e){let n=t.match(e);if(!n?.[1])return null;let s=Number.parseFloat(n[1]);return Number.isFinite(s)?s:null}function DS(t,e,n){if(e.length===0)return null;let s=Ue(t),r=Ue(t,"SqliteAnalyze"),o=new Map(Oe(t,"SqliteAnalyze").map(i=>[i.index,i]));for(let i of[...r].reverse()){let a=o.get(i.index);if(!a||a.isError)continue;let l=typeof i.input.candidate_sql_path=="string"?i.input.candidate_sql_path:null;if(!l)continue;let c=yt(n,l);if(!e.includes(c)||!(typeof i.input.compare_outputs=="boolean"?i.input.compare_outputs:!0))continue;let p=Gr(s,[c],n);if(p<0||i.index<=p||!/Outputs match exactly:\s*yes\b/i.test(a.content))continue;let f=zi(a.content,/Candidate runtime median:\s*([0-9]*\.?[0-9]+)s\b/i),m=zi(a.content,/Baseline runtime median:\s*([0-9]*\.?[0-9]+)s\b/i);if(f===null||m===null)continue;let g=zi(a.content,/Candidate vs baseline speedup:\s*([0-9]*\.?[0-9]+)x\b/i);if(!(!/(?:^|\r?\n)Candidate plan:\s*(?:\r?\n-\s+.+)+/i.test(a.content)||!(g!==null?g>1:f<m)))return{index:i.index,candidatePath:c,candidateRuntimeMedianSeconds:f,baselineRuntimeMedianSeconds:m,speedup:g}}return null}function FS(t,e){return typeof e=="boolean"?e:process.env.XENO_BENCHMARK_MODE?.trim().toLowerCase()==="terminal-bench"?!0:my.test(t)}function Sd(t){return by.test(t)}function US(t){return Sd(t)&&yy.test(t)}function jS(t){return wy.test(t)}function VS(t){return vy.test(t)}function kd(t){return Sy.test(t)}function xd(t){return ky.test(t)}function qS(t){return xy.test(t)}function HS(t){return Py.test(t)}function zS(t){return Ty.test(t)}function WS(t){return Ey.test(t)&&_y.test(t)&&Ki.test(t)&&Cy.test(t)}function XS(t){return Ry.test(t)}function KS(t){return Ki.test(t)&&Ay.test(t)&&Eu.test(t)?!0:Iy.test(t)&&Ki.test(t)&&My.test(t)&&Eu.test(t)}function GS(t){return Oy.test(t)&&/\b(?:allowed commands|call\s+setreg|%normal!|:wq|:x|headlessly|script must contain)\b/i.test(t)}function YS(t){return $y.test(t)}function Pd(t){return Ly.test(t)}function JS(t){return By.test(t)}function QS(t){return Dy.test(t)}function ZS(t){return Fy.test(t)&&!Pd(t)}function ek(t){return Uy.test(t)}function tk(t){return jy.test(t)}function nk(t){return Vy.test(t)}function sk(t){return qy.test(t)}function rk(t){return Hy.test(t)}function ok(t){return Wy.test(t)}function ik(t){return Xy.test(t)}function Yi(t){return t.trim().replace(/^['"`]+|['"`:;,.]+$/g,"")}function ak(t){let e=Yi(t),n=e.toLowerCase(),s=new Set([e,n]);return n==="rstan"&&s.add("RStan"),n==="opencv"&&s.add("cv2"),n==="cv2"&&s.add("opencv"),n==="pillow"&&s.add("PIL"),n==="pil"&&s.add("Pillow"),n==="scikit-learn"&&s.add("sklearn"),n==="sklearn"&&s.add("scikit-learn"),Array.from(s).filter(r=>r.length>0)}function Td(t){let e=new Set,n=t.toLowerCase();for(let r of Jy)new RegExp(String.raw`(^|[^A-Za-z0-9_.-])${oo(r)}($|[^A-Za-z0-9_.-])`,"i").test(t)&&e.add(Yi(r));let s=[/\binstall(?:ed|ing)?\s+(?:the\s+)?(?:R\s+|Python\s+|Node(?:\.js)?\s+|npm\s+|CRAN\s+|system\s+)?(?:package|library|module|dependency|tool)?\s*['"`]?(@?[A-Za-z][A-Za-z0-9_.-]{1,63}(?:\/[A-Za-z0-9_.-]+)?)['"`]?/gi,/\b(?:package|library|module|dependency|tool)\s+(?:called|named)?\s*['"`]?(@?[A-Za-z][A-Za-z0-9_.-]{1,63}(?:\/[A-Za-z0-9_.-]+)?)['"`]?/gi,/\b([A-Za-z][A-Za-z0-9_.-]{1,63})\s+(?:package|library|module|dependency|tool)\b/gi];for(let r of s){let o;for(;(o=r.exec(t))!==null;){let i=Yi(o[1]??""),a=i.toLowerCase();i.length<2||Qy.has(a)||/^\d/.test(i)||e.add(i)}}return(/\brstan\b/i.test(t)||/\bRStan\b/.test(t))&&e.add("rstan"),/\bR\s+package\b/i.test(t)&&n.includes("stan")&&e.add("rstan"),Array.from(e).slice(0,8)}function lk(t,e){return ak(e).some(n=>{let s=oo(n);return new RegExp(String.raw`(^|[^A-Za-z0-9_.-])${s}($|[^A-Za-z0-9_.-])`,"i").test(t)})}function ck(t,e){let n=Td(e),s=new Map;for(let r of Ue(t,"Bash")){let o=typeof r.input.command=="string"?r.input.command:"";s.set(r.index,o)}return Oe(t,"Bash").some(r=>{if(r.isError)return!1;let o=s.get(r.index)??"",i=`${o}
|
|
1192
|
+
${r.content}`;return!Ky.test(o)||Yy.test(i)||nt(i)||n.length>0&&!n.some(a=>lk(i,a))?!1:Gy.test(i)})}function uk(t){return Oe(t).some(e=>!e.isError&&/(?:^|\s)(?:\/tests\b|\/tests\/[\w./-]+|\.\/test\.sh\b|\.\/run-tests\.sh\b|test_outputs\.py\b|run-tests\.sh\b|test\.sh\b)/i.test(e.content))}function Ku(t,e=-1,n=[],s=!1,r=!1,o=!1){let i=new Map;for(let a of Ue(t,"Bash")){let l=typeof a.input.command=="string"?a.input.command:"";i.set(a.index,l)}return Oe(t).some(a=>{if(a.index<=e||a.isError)return!1;if(a.name==="ArtifactCompare")return nr(a);if(a.name!=="Bash")return!1;let l=i.get(a.index)??"",c=`${l}
|
|
1193
|
+
${a.content}`;if(nt(c)||id.test(c))return!1;if(_t.some($=>$.test(l)))return mt(a.content);if(!ea.some($=>$.test(c)))return!1;let f=Yt(l,n),m=kw.test(c),g=xw.test(c),b=Pw.test(c),v=Tw.test(c),w=Rw.test(c),P=od.test(a.content),C=xn.test(a.content);return s&&!b&&!v||r&&!w||o&&!v||o&&!_w.test(c)||!f&&!b&&!v?!1:g&&(m||v)||P&&(m||b||v||g)?!0:C&&m&&(g||v||b)})}function dk(t,e){let n=Number.parseFloat(t);if(!Number.isFinite(n)||n<=0)return 0;let s=(e??"").toLowerCase();return Math.floor(s==="g"||s==="gb"||s==="gib"||s==="gigabyte"||s==="gigabytes"?n*1024*1024*1024:s==="m"||s==="mb"||s==="mib"||s==="megabyte"||s==="megabytes"?n*1024*1024:s==="k"||s==="kb"||s==="kib"||s==="kilobyte"||s==="kilobytes"?n*1024:n)}function sa(t){return Au.lastIndex=0,Array.from(t.matchAll(Au)).map(e=>e[0]).filter(e=>e.trim().length>0)}function _d(t){if(sa(t).length===0)return null;let e=0;for(let n of t.matchAll(/\b(\d+(?:\.\d+)?)\s*(gigabytes?|gib|gb|g|megabytes?|mib|mb|m|kilobytes?|kib|kb|k|bytes?|b)?\b/gi)){let s=dk(n[1]??"",n[2]);e=Math.max(e,s)}return e>0?e:null}function Rd(t,e,n){let s=t.replace(/\\/g,"/"),r=new Set;r.add(yt(n,t)),/^(?:[A-Za-z]:[\\/]|\/)/.test(t)&&r.add(yt(t));for(let o of e){let i=Qu(o);r.add(yt(i,s))}return Array.from(r)}function Ed(t){try{let e=jt(t);return e.isFile()?e.size:null}catch{return null}}function pk(t,e,n){let s=0;for(let r of t.split(/\r?\n/))s=Math.max(s,_d(r)??0);for(let r of sa(t))for(let o of Rd(r,e,n))s=Math.max(s,Ed(o)??0);return s>0?s:null}function mk(t,e,n,s){let r=!1,o=!1;for(let i of Oe(t))if(!(i.index<=e||i.isError)&&!(i.name!=="Bash"&&i.name!=="Read")){for(let a of i.content.split(/\r?\n/)){let l=_d(a);l!==null&&(l>=Zr?o=!0:r=!0)}for(let a of sa(i.content))for(let l of Rd(a,n,s)){let c=Ed(l);c!==null&&(c>=Zr?o=!0:c>0&&(r=!0))}}return r&&!o}function fk(t,e,n,s,r){let o=new Map;for(let f of Ue(t,"Bash")){let m=typeof f.input.command=="string"?f.input.command:"";o.set(f.index,m)}let i=!1,a=!1,l=!1,c=!1,u=!1;for(let f of Oe(t,"Bash")){if(f.index<=e||f.isError)continue;let m=o.get(f.index)??"",g=`${m}
|
|
1194
|
+
${f.content}`;if(id.test(g)||nt(f.content)&&!mt(f.content))continue;let b=pk(g,n,s);b!==null&&b>=Zr&&(i=!0),Ew.test(g)&&(a=!0),Iu.test(g)&&(l=!0),(od.test(f.content)||xn.test(f.content)||mt(f.content))&&(c=!0),(Cw.some(v=>v.test(m))||_t.some(v=>v.test(m)))&&(Iu.test(g)||xn.test(f.content)||mt(f.content))&&(u=!0)}let p=r===null||Cd(t,e,r);return i&&a&&(l||c)&&u&&p}function hk(t){return kn(t,no)}function Yr(t,e){let n=e.map(i=>i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),s=new RegExp(`\\b(?:${n})\\s*[:=]\\s*([0-9]+(?:\\.[0-9]+)?)\\b`,"i"),r=t.match(s);if(!r)return null;let o=Number.parseFloat(r[1]);return Number.isFinite(o)?o:null}function gk(t){let n=Array.from(t.matchAll(/\b(?:greater\s+than|above|over|at\s+least|>=|>)\s*(\d+(?:\.\d+)?)\s*%/gi)).at(-1);if(n?.[1]){let o=Number.parseFloat(n[1]);if(Number.isFinite(o)&&o>0)return o/100}let r=Array.from(t.matchAll(/\b(?:accuracy|metric|score)\b[\s\S]{0,80}\b(?:greater\s+than|above|over|at\s+least|>=|>)\s*(0?\.\d+|1(?:\.0+)?)\b/gi)).at(-1);if(r?.[1]){let o=Number.parseFloat(r[1]);if(Number.isFinite(o)&&o>0&&o<=1)return o}return null}function bk(t){return!Dw.test(t)||!/\baccuracy\b/i.test(t)?null:gk(t)}function Gu(t,e){let n=new Map;for(let s of Ue(t,"Bash")){let r=typeof s.input.command=="string"?s.input.command:"";n.set(s.index,r)}return Oe(t,"Bash").some(s=>{if(s.index<=e||s.isError)return!1;let r=n.get(s.index)??"";return ad.test(r)})}function Cd(t,e,n){let s=new Map;for(let r of Ue(t,"Bash")){let o=typeof r.input.command=="string"?r.input.command:"";s.set(r.index,o)}return Oe(t,"Bash").some(r=>{if(r.index<=e||r.isError)return!1;let o=s.get(r.index)??"",i=`${o}
|
|
1195
|
+
${r.content}`;if(!ad.test(o)&&!/\bcaffe\b/i.test(i)||nt(r.content)&&!mt(r.content))return!1;let a=Yr(i,["first_accuracy","first_batch_accuracy","first_regex_accuracy","verifier_regex_accuracy"]),l=Yr(i,["min_accuracy","minimum_accuracy","min_batch_accuracy"]),c=a??Yr(i,["verifier_accuracy"]),u=c!==null&&c>n,p=l===null||l>n;return u&&p&&(Fw.test(i)||/\b(?:first|first_batch|first_regex|verifier_regex|min(?:imum)?)_?accuracy\b[\s\S]{0,160}\b(?:threshold|pass|>)\b/i.test(i))})}function yk(t){return t.find(e=>qn(e).toLowerCase()==="training_output.txt")??null}function Wi(t,e=1024*1024){try{let n=jt(t);return!n.isFile()||n.size<=0||n.size>e?null:Hn(t,"utf-8")}catch{return null}}function Xi(t,e=1){try{let n=jt(t);return n.isFile()&&n.size>=e}catch{return!1}}function Yu(t){try{return jt(t).isDirectory()}catch{return!1}}function wk(t){let e=[],n=yk(t);if(!n)return e;let s=Wi(n);s!==null&&(/\bIteration\s+500\b/i.test(s)||e.push("submitted training_output.txt does not contain the real `Iteration 500` training marker"),/\bTest net output #0:\s*accuracy\s*=/i.test(s)||e.push("submitted training_output.txt does not contain Caffe `Test net output #0: accuracy = ...` training evidence"),/\b(?:Optimization Done|Snapshotting to binary proto file|cifar10_quick_iter_500\.caffemodel)\b/i.test(s)||e.push("submitted training_output.txt does not show the final 500-iteration snapshot or optimization completion"));let r=Qu(n),o=yt(r,"examples/cifar10/cifar10_quick_solver.prototxt"),i=Wi(o);if(i===null)e.push("canonical examples/cifar10/cifar10_quick_solver.prototxt is missing or empty");else{let c=i.replace(/\s+/g,"");/solver_mode:CPU/i.test(c)||e.push("canonical examples/cifar10/cifar10_quick_solver.prototxt is not configured with `solver_mode: CPU`"),/max_iter:500(?!\d)/i.test(c)||e.push("canonical examples/cifar10/cifar10_quick_solver.prototxt is not configured with `max_iter: 500`")}let a=yt(r,"Makefile.config"),l=Wi(a);return l===null?e.push("canonical BVLC Caffe Makefile.config is missing or empty"):/^[ \t]*CPU_ONLY[ \t]*:?=[ \t]*1\b/im.test(l)||e.push("canonical BVLC Caffe Makefile.config is not configured with `CPU_ONLY := 1`"),Xi(yt(r,".build_release/tools/caffe.bin"),1e5)||e.push("canonical BVLC Caffe binary `.build_release/tools/caffe.bin` is missing or too small"),Xi(yt(r,"examples/cifar10/cifar10_quick_iter_500.caffemodel"),1e5)||e.push("canonical CIFAR-10 snapshot `examples/cifar10/cifar10_quick_iter_500.caffemodel` is missing or too small"),Yu(yt(r,"examples/cifar10/cifar10_train_lmdb"))||e.push("canonical CIFAR-10 training LMDB directory `examples/cifar10/cifar10_train_lmdb` is missing"),Yu(yt(r,"examples/cifar10/cifar10_test_lmdb"))||e.push("canonical CIFAR-10 test LMDB directory `examples/cifar10/cifar10_test_lmdb` is missing"),Xi(yt(r,"examples/cifar10/mean.binaryproto"),1)||e.push("canonical CIFAR-10 mean file `examples/cifar10/mean.binaryproto` is missing or empty"),e}function nr(t){if(t.name!=="ArtifactCompare"||t.isError)return!1;let e=tr(t.content);if(!/\bOverall:\s*PASS\b/i.test(e)||/\bOverall:\s*FAIL\b/i.test(e))return!1;if(/\bbyte_equal:\s*true\b/i.test(e))return!0;let n=Yr(e,["cosine_similarity","cosine"]);return n!==null&&n>=.995?!0:!/\bArtifact:\s+\S+/i.test(e)&&/\bStdout equal:\s*yes\b/i.test(e)}function vk(t,e=-1){let n=new Map;for(let s of Ue(t,"Bash")){let r=typeof s.input.command=="string"?s.input.command:"";n.set(s.index,r)}return Oe(t).some(s=>{if(s.index<=e||s.isError)return!1;if(s.name==="ArtifactCompare")return nr(s);if(s.name!=="Bash")return!1;let r=n.get(s.index)??"",o=`${r}
|
|
1196
|
+
${s.content}`;return nt(o)?!1:_t.some(a=>a.test(r))?mt(s.content):Uw.test(o)})}function Sk(t){return Zu.test(t)||td.test(t)}function ra(t){return t.map(e=>Gi(e,1024)).filter(e=>e!==null&&e.trim().length>0).map(e=>e.trim()).filter(e=>e.length>=2)}function Zs(t,e){if(e.length===0)return!1;let n=t.replace(/\r/g,"");return e.some(s=>n.includes(s.replace(/\r/g,"")))}function kk(t){return ra(t).some(e=>Ji.test(e)?!0:ed.test(e)||nd.test(e)?!1:e.length>=8&&/[A-Za-z0-9]/.test(e))}function xk(t,e,n){if(e<=0||!kk(n))return!1;let s=ra(n);return Oe(t,"GcodeAnalyze").some(r=>r.index>=e||r.isError?!1:/\b(?:XY_DESKEW|text-focused PCA contact sheet|PCA projection)\b/i.test(r.content)&&Zs(r.content,s))}function Pk(t,e,n){let s=new Set,r=new Map(Oe(t).map(i=>[i.index,i])),o=ra(n);for(let i of Ue(t)){if(i.index<=e)continue;let a=r.get(i.index);if(!a||a.isError)continue;if(i.name==="GcodeAnalyze"){Zs(a.content,o)&&s.add("gcode-geometry");continue}if(i.name==="ReadImage"){Zs(a.content,o)&&s.add("image-read");continue}if(i.name==="dispatch_agent"){let f=[typeof i.input.prompt=="string"?i.input.prompt:"",typeof i.input.task=="string"?i.input.task:"",typeof i.input.description=="string"?i.input.description:"",a?.content??""].join(`
|
|
1197
|
+
`);(Zu.test(f)||Ji.test(f))&&Zs(a.content,o)&&s.add("delegated-review");continue}if(i.name!=="Bash")continue;let l=typeof i.input.command=="string"?i.input.command:"",c=`${l}
|
|
1198
|
+
${a?.content??""}`;!Mu.some(f=>f.test(c))||!Zs(c,o)||Ou.test(l)&&!Mu.some(f=>f.test(l.replace(Ou,"")))||s.add("visual-bash")}return s}function Tk(t,e,n){return Pk(t,e,n).size>0}function Ju(t){return kn(t,eo)||Oe(t,"ArtifactCompare").some(e=>{if(!nr(e))return!1;let n=`${JSON.stringify(e.input)}
|
|
1199
|
+
${e.content}`;return eo.some(s=>s.test(n))})}function _k(t,e=-1){let n=new Map;for(let s of Ue(t,"Bash")){let r=typeof s.input.command=="string"?s.input.command:"";n.set(s.index,r)}return Oe(t).some(s=>{if(s.index<=e||s.isError)return!1;if(s.name==="ArtifactCompare")return nr(s);if(s.name!=="Bash")return!1;let r=n.get(s.index)??"",o=`${r}
|
|
1200
|
+
${s.content}`;return nt(o)?!1:_t.some(a=>a.test(r))?mt(s.content):Jw.test(o)?Qw.test(o):!1})}function Rk(t){return fy.test(t)}function Ek(t,e){return hy.test(t)||gy.test(e)}function Ad(t){let e=fd(t.prompt),n=zr(e),s=n.domains.map(F=>F.label),r=n.verifierRequirements.slice(0,5),o=n.finalAuditItems.slice(0,6),i=un(t.requiredOutputPaths,t.cwd),a=$v(e,t.cwd),l=xv(e,t.cwd),c=l.filter(F=>!i.includes(F)),u=FS(t.prompt,t.benchmarkMode),p=Ek(t.prompt,e),f=p||Rk(e),m=u||f,g=Sd(e),b=US(e),v=jS(e),w=VS(e),P=kd(e),C=xd(e),$=qS(e),E=HS(e),T=zS(e),I=WS(e),re=XS(e),ae=KS(e),N=GS(e),y=YS(e),oe=N?CS(i,l):null,K=N?AS(e,t.cwd):{inputPath:null,expectedPath:null},W=Pd(e),Z=bk(e),le=W&&Ny.test(e),ce=W&&JS(e),X=W&&QS(e),q=Qv(e),Q=Zv(e),ye=/\b(?:grad|gradient|backward|autograd)\b/i.test(e),ee=ZS(e),Se=ee&&Sk(e),me=ee&&ek(e),de=tk(e),Ee=!ee&&nk(e),pe=ok(e),te=sk(e)&&!ee&&!pe&&!I&&!E,Re=ik(e),Ce=Number.isFinite(t.startedAtMs)?t.startedAtMs:Date.now(),Ae=Number.isFinite(t.externalTimeoutMs)&&t.externalTimeoutMs>0?t.externalTimeoutMs:void 0;if(i.length===0&&!m&&!g&&!b&&!v&&!w&&!$&&!E&&!T&&!I&&!re&&!N&&!y&&!W&&!q&&!ee&&!de&&!Ee&&!pe&&!te&&!Re&&!n.projectLike)return;let xe=!1,Te=!1,Ne=!1,Xe=!1,He=!1,rt=!1,Y=!1,D=!1,H=!1,M=!1,U=!1,G=!1,fe=!1,ze=!1,Vt=!1,ut=!1,Pt=!1,zn=!1,pn=!1,wt=!1,at=!1,vt=!1,qt=!1,$t=!1,ft=!1,Lt=!1,Rt=!1,en=!1,Ht=0;return async F=>{let et=Pv(F.messages),ht=Number.isFinite(F.elapsedMs)&&F.elapsedMs>=0?F.elapsedMs:Math.max(0,Date.now()-Ce),zt=Number.isFinite(F.externalTimeoutMs)&&F.externalTimeoutMs>0?F.externalTimeoutMs:Ae,St=zt?Math.max(3e4,zt-tw):ew,Nt=Math.max(Lu,Math.min(Math.floor(St*Gw),Math.max(Lu,St-Yw))),Pn=i.filter(j=>!Kr(j)||!Fu(j));if(Pn.length>0){Ht+=1;let j=Se&&Oe(F.messages,"GcodeAnalyze").some(ko=>!ko.isError),Ve=me||de||Ee||pe,So=Ve?4:2,Ap=Ve?28:12,Ip=Ve?.75:.6,Mp=Ve?7:4,Op=Ve?45:18,$p=Ve?.85:.45,lr=u&&et>0&&(j||Ht>=So||(F.iteration??0)>=Ap||ht>=Math.floor(St*Ip)),Oa=lr&&(j||Ht>=Mp||(F.iteration??0)>=Op||ht>=Math.floor(St*$p)),Lp=Oa?{mode:"require_output_checkpoint",requiredOutputPaths:Pn,message:"Repeated progress checkpoints found required outputs still missing; Xeno is enforcing candidate checkpoint mode."}:void 0;return ge(["Required task outputs are still missing.",...Pn.map(ko=>`- ${ko}`),...Oa?["Xeno has entered candidate checkpoint mode: more broad exploration is blocked until one missing output path is created or updated."]:[],lr?"Do not run more open-ended inspection, rendering, search, training, or benchmarking before checkpointing a candidate.":"Do not finish yet. Use tools to create or update the missing file(s), verify they exist, and only then answer.",lr?j?"A visual/G-code decoding preview already exists. Your next action should create or update the missing output path with the best current decoded string, then refine or overwrite it if stronger evidence changes any character.":"Your next action should create or update the missing output path with the best current candidate, even if imperfect; refine or overwrite it afterward if stronger evidence appears.":"If you already have a strong candidate result, write your best current answer to the missing output file now and refine it afterward if needed.",...lr?["A wrong but concrete candidate is recoverable; no candidate at all usually becomes an unrecoverable timeout or output-contract failure."]:[]].join(`
|
|
1201
|
+
`),!0,Lp)}if($){let j=i.filter(Ve=>Tv(Ve));if(j.length>0)return ge(["Required extraction/decryption outputs still contain placeholder content.",...j.map(Ve=>`- ${Ve}`),"Do not finish with UNKNOWN, TODO, or guessed placeholder values.","Use archive/decryption tooling to recover the real content, overwrite the output file, and verify it against the source artifact before answering."].join(`
|
|
1202
|
+
`),!0)}let tn=a.map(j=>({expectation:j,actual:Lv(j)})).filter(j=>j.actual!==null);if(tn.length>0)return ge(["Required exact literal output does not match the task contract.",...tn.flatMap(({expectation:j,actual:Ve})=>[`- ${j.path}`,` expected: ${Js(j.text)}`,` actual: ${Js(Ve)}`]),"Do not finish yet. Overwrite the file with the exact quoted literal from the task and verify it byte-for-byte before answering."].join(`
|
|
1203
|
+
`),!0);let Tn=td.test(e)&&!(re&&/\bFLAG\s+(?:fragment|gene|sequence|protein|tag|component|peptide)\b/i.test(e))?i.map(j=>({path:j,content:Gi(j)})).filter(j=>j.content!==null&&j.content.length>0&&!Ji.test(j.content)):[];if(Tn.length>0)return ge(["The task appears to require a flag, but a required output file does not contain a flag-like token.",...Tn.map(({path:j,content:Ve})=>`- ${j}: ${Js(Ve)}`),"Do not finish with a description, object label, filename, or metadata string.","Continue decoding from the artifact behavior and overwrite the output with the recovered flag token, typically in a flag{...} format, then verify the file bytes before answering."].join(`
|
|
1204
|
+
`),!0);let mn=ee?i.map(j=>({path:j,content:Gi(j)})).filter(j=>j.content!==null&&j.content.length>0&&nd.test(j.content)):[];if(mn.length>0)return ge(["A required output file contains only a generic visual/artifact label.",...mn.map(({path:j,content:Ve})=>`- ${j}: ${Js(Ve)}`),"Do not finish based on comments, object names, or metadata labels when the task asks what the artifact actually shows or encodes.","Render, simulate, sample, or otherwise inspect the artifact behavior and overwrite the output with the decoded answer before finishing."].join(`
|
|
1205
|
+
`),!0);if(N&&oe){let j=IS(oe,e);if(j.length>0)return ge(["The generated Vim macro script does not satisfy the task's explicit file-format contract.",`- ${oe}`,...j.map(Ve=>`- ${Ve}`),"Do not finish yet. Fix the script file itself, then rerun the exact headless Vim command and a byte-level comparison against the expected output before answering."].join(`
|
|
1206
|
+
`),!0)}let ie=new Set(a.map(j=>j.path)),ue=i.length>0&&i.every(j=>ie.has(j));if(u&&F.stopReason==="progress_checkpoint"&&et>0&&a.length>0&&ue)return ps("Exact required output file(s) match the task contract; stopping now to preserve the verified final state.");let _e=kv(F.messages,t.cwd),h=Ue(F.messages),O=i.filter(j=>_e.includes(j)),S=c.filter(j=>_e.includes(j));if(i.length>0&&O.length===0&&S.length>0)return ge(["The task has a required submission path, but this run only wrote to reference or baseline files.","Do not finish yet.","Write the final artifact to the required output path before answering.","Reference files written in this run:",...S.map(j=>`- ${j}`),"Required output paths:",...i.map(j=>`- ${j}`)].join(`
|
|
1207
|
+
`),!0);let k=Gr(h,i,t.cwd),A=Gr(h,c,t.cwd),L=N?OS(F.messages,K.inputPath,K.expectedPath):null,V=N?$S(F.messages,K.inputPath):-1,ke=oe!==null?Gr(h,[oe],t.cwd):-1,Be=Math.max(k,ke),Fe=N?NS(F.messages,K.inputPath,Be>=0?Be:Number.POSITIVE_INFINITY):-1,Qe=oe!==null&&Be>=0&&Xu(F.messages,Be,oe,K.inputPath,L?.index??-1,V);if(i.length>0&&c.length>0&&k>=0&&A>k)return ge(["The run continued editing a reference or baseline artifact after the required submission file was written.","Do not finish yet.","Promote the best validated candidate into the required submission path, then validate that submission file before answering.","Required output paths:",...i.map(j=>`- ${j}`),"Reference paths modified later in the run:",...c.map(j=>`- ${j}`)].join(`
|
|
1208
|
+
`),!0);if(N&&L&&L.index>V&&!(oe!==null&&Xu(F.messages,Math.max(Be,L.index),oe,K.inputPath,L.index,V)))return ge(["The run copied the expected/reference file over the source input before validating the Vim macro script.",`- copied ${L.sourcePath} -> ${L.destinationPath}`,"That makes a later byte comparison on the official input path non-credible.","Do not finish yet. Validate the macro script on a fresh original/source-like input, or restore/regenerate the source input first, then rerun the headless Vim command and byte comparison."].join(`
|
|
1209
|
+
`),!0);if(N&&K.inputPath&&Fe>V&&Be>Fe&&!Qe)return ge(["The Vim macro script was changed after a previous Vim run already mutated the official source input.",`- source input: ${K.inputPath}`,"A later validation against that same input path is stale because it is no longer the original task input.","Do not finish yet. Restore or regenerate the source input, or run the updated script against a saved pristine copy, then perform the headless Vim command and byte comparison again."].join(`
|
|
1210
|
+
`),!0);let z=F.stopReason==="end_turn"||F.stopReason==="empty_response"||F.stopReason==="max_tokens"||F.stopReason==="transport_error";if(z&&et===0&&u&&!Y)return Y=!0,ge(["No tool work has happened yet, so this task is not ready to finish.","This is a real task container, not a chat-only question.","Start by inspecting the filesystem and verifier paths with tools, then create or update the required artifacts before answering.","Do not stop until you have actually interacted with the environment and validated the result."].join(`
|
|
1211
|
+
`),!0);let ve=i.length>0&&i.every(j=>Kr(j)&&Fu(j));if(u&&W&&ve&&F.stopReason==="progress_checkpoint"&&!$t&&mk(F.messages,k,i,t.cwd))return $t=!0,ge(["A model/checkpoint artifact exists, but its recorded size is too small to be credible.",`Model artifacts under ${Zr} bytes are treated as placeholders, not trained or recovered models.`,"Do not validate, preserve, or summarize the tiny placeholder as the final model.","Overwrite it by running the real build/training/recovery path, then verify the resulting artifact size, schema/loadability, and multi-sample or metric evidence before stopping."].join(`
|
|
1212
|
+
`),!0);if(u&&F.stopReason==="progress_checkpoint"&&(F.iteration??0)>0&&(F.iteration??0)<=10&&n.projectLike&&et>=6&&!en)return en=!0,ge(["Project execution checkpoint: switch from exploration to artifact-driven progress.",s.length>0?`Active project risk kits: ${s.join(", ")}.`:"Use the general project final-state audit.","Current phase objective: preserve the best candidate, run one verifier-shaped check, then fix only concrete failures from that check.","Verifier requirements to satisfy before final answer:",...r.map(j=>`- ${j}`),"Final-state audit items:",...o.map(j=>`- ${j}`)].join(`
|
|
1213
|
+
`));if(u&&z){let j=F.finalText?.trim()??"";if(j.length>0&&fw.test(j))return ge(["The final answer says the current solution is incomplete or failed a self-check.",`Evidence: ${Js(j)}`,"Do not finish with a known-bad candidate.","Repair the concrete failure, overwrite the required final artifact if needed, and rerun a verifier-shaped check before answering."].join(`
|
|
1214
|
+
`),!0)}let dt=Oe(F.messages,"SqliteAnalyze").filter(j=>j.isError),Ge=dt.at(-1)??null,Et=DS(F.messages,i,t.cwd),or=kn(F.messages,Jr)||kn(F.messages,Qr)||na(F.messages).some(j=>/\bsqlite3\b/i.test(j)),va=Gv(F.messages),kp=Ge?/Row counts differ|Column names\/order differ|First differing row/i.test(Ge.content):!1,Wn=u?Vu(F.messages,i):null,xp=Z===null||Cd(F.messages,k,Z),Sa=u&&W&&ve&&Z!==null?wk(i):[];if(Sa.length>0&&(z||F.stopReason==="progress_checkpoint"&&Gu(F.messages,k)))return ge(["This Caffe/model-training final state does not satisfy the canonical submitted-file contract yet.",...Sa.map(j=>`- ${j}`),"Do not validate only an alternate solver file or overwrite training_output.txt with a fresh test-only log.","Repair the canonical source-build and training contract: Makefile.config CPU_ONLY, .build_release/tools/caffe.bin, CIFAR-10 LMDBs/mean, the 500-iteration snapshot, and the real training log. Then rerun the final .build_release/tools/caffe.bin test command and parser-shaped metric check."].join(`
|
|
1215
|
+
`),!0);if(u&&W&&ve&&Z!==null&&!xp&&Gu(F.messages,k)&&(z||F.stopReason==="progress_checkpoint"))return ge(["This Caffe/model-training metric check is not verifier-shaped enough yet.","Caffe test output can contain per-batch `accuracy = ...` lines before the final average; hidden verifiers may parse the first regex match.",`Run the final weights with the exact Caffe test command, parse the first and minimum accuracy values, and require them to be greater than ${Z}.`,"Print explicit evidence such as FIRST_ACCURACY_PASS first_accuracy=... min_accuracy=... final_accuracy=... only after the parser-shaped threshold check passes.","If the first/min accuracy is too close to the threshold, improve the model or retrain with a safer margin instead of finalizing on the final average alone."].join(`
|
|
1216
|
+
`),!0);let Pp=zt?Math.min(St,Math.max(Nt,zt-4*6e4)):St,Tp=W&&ve&&fk(F.messages,k,i,t.cwd,Z);if(u&&W&&F.stopReason==="progress_checkpoint"&&ht>=Pp&&Tp&&!Wn)return ps(["Model-training finalization evidence is sufficient and the benchmark budget is in the final window.","A non-trivial model/checkpoint artifact exists and training or evaluation metrics have been observed after the submitted output was created.","Do not start another long build, full retrain, or broad hyperparameter pass.","Preserve the current model artifacts, training output, and final filesystem state now."].join(`
|
|
1217
|
+
`));let ka=Ee&&ve?Mv(i,e):[];if(ka.length>0)return ge(["The binary/reverse-engineering submission violates the source-independence contract.",...ka.map(j=>`- ${j}`),"Do not preserve, embed, execute, or depend on the original compiled artifact.","Replace the required source file with a compact independent reimplementation, then rerun the same original-vs-candidate behavioral comparison and any compressed-size check from the prompt."].join(`
|
|
1218
|
+
`),!0);let _p=N&&K.inputPath!==null&&Kr(K.inputPath),xa=N&&oe!==null&&Be>=0&&(ve||i.length===0&&_p)&&Qe;if(xa&&F.stopReason==="progress_checkpoint")return ps(["Vim macro script contract and final byte-level output validation passed.","Stop now and preserve the generated script plus edited file instead of continuing broad verifier or performance exploration."].join(`
|
|
1219
|
+
`));if(xa&&z)return null;if(u&&b&&Ge&&!kp&&Et===null&&va>=1&&ve&&!p)return ps(["SQL validation has reached diminishing returns.","The required output file exists, SqliteAnalyze could not complete in this environment, and a baseline/candidate SQLite comparison already timed out.","Do not start another full-query comparison, timing loop, or verifier-shaped SQL harness.","Preserve the current required output file and finish with the best available bounded evidence."].join(`
|
|
1220
|
+
`));if(b&&Ge&&Et===null&&F.stopReason==="progress_checkpoint"&&(dt.length>=2||va>=1))return ps(["SQL validation is now consuming the benchmark budget without producing stronger evidence.",dt.length>=2?"SqliteAnalyze has failed more than once on the current task.":"A baseline/candidate SQLite comparison already timed out.","Do not start another full-query comparison, timing loop, or SqliteAnalyze rerun.","Preserve the strongest current candidate in the required output path, run only a sub-30-second sanity check if one is still necessary, then finish with the current filesystem state."].join(`
|
|
1221
|
+
`));if(b&&Ge&&or&&!Xe){Xe=!0;let j=Ge.content,Ve=/Row counts differ|Column names\/order differ|First differing row/i.test(j),So=/requires node:sqlite|Python sqlite3|sqlite3 failed|spawnSync|ENOENT|ETIMEDOUT|timeout/i.test(j);return ge([Ve?"SqliteAnalyze already proved the current candidate is not output-equivalent.":"SqliteAnalyze failed earlier in this run, and the fallback path is starting to sprawl.","Do not keep expanding an ad hoc Bash benchmark harness for many more turns.",Ve?"Fix correctness first, then rerun a bounded validation before spending more time on timing.":So?"If the preferred analysis backend is unavailable, do at most one minimal read-only sqlite self-check, then move to the official verifier or a verifier-shaped check.":"Use one bounded validator-shaped check, keep the strongest candidate in the submission file, and stop once the evidence is clear.","Keep the winning candidate synchronized into the required output path before you continue.","After that, run the official verifier when it is exposed, or one strong verifier-shaped self-check, and answer."].join(`
|
|
1222
|
+
`))}if(u&&z){let j=Vu(F.messages,i);if(j)return ge(["The latest validation signal is still failing.",`Tool: ${j.toolName}`,`Evidence: ${j.summary}`,"Do not finish after a failed verifier, self-check, build, diff, or runtime check.",...j.toolName==="HtmlSanitizerAudit"?["Use the concrete HtmlSanitizerAudit failure lines; do not spend turns reading generated /tmp/xeno-html-sanitizer-audit-* harness files or /app/.xeno/audit traces."]:[],"Fix the concrete failure and rerun the same verifier-shaped check until a later passing signal supersedes it."].join(`
|
|
1223
|
+
`),!0)}if(u&&F.stopReason==="progress_checkpoint"&&et>0&&ht>=St&&!Rt){Rt=!0;let j=Math.max(1,Math.round(ht/6e4)),Ve=zt?Math.max(1,Math.round(zt/6e4)):null;return ge([Ve?`External benchmark timeout is approaching: ${j} of about ${Ve} minutes have elapsed.`:`Wall-clock budget checkpoint: this run has already used about ${j} minutes.`,"Do not start another long foreground build, training run, exhaustive search, or broad exploration pass.","Preserve the strongest current candidate in the required output path now.","Run only one bounded verifier-shaped check, inspect concrete failures, and make the smallest targeted fix.","If no better validated candidate is available, finish with the best current filesystem state instead of being killed by the outer timeout."].join(`
|
|
1224
|
+
`))}if(u&&F.stopReason==="progress_checkpoint"&&et>0&&ht>=Nt&&ht<St&&!Lt){Lt=!0;let j=Math.max(1,Math.round(ht/6e4)),Ve=Math.max(1,Math.round(St/6e4));return ge([`Benchmark budget checkpoint: about ${j} minutes have elapsed; the finalization window starts around ${Ve} minutes.`,"Switch from broad exploration to candidate preservation and targeted repair.","Write or preserve the strongest current candidate in the required output path before any more expensive search.","Run one bounded verifier-shaped check that exercises the real final artifact, then fix only the first concrete failing requirement.","Do not start a new long search, full retraining pass, exhaustive solver, or broad benchmark loop unless it directly addresses a verifier failure."].join(`
|
|
1225
|
+
`))}let We=kn(F.messages,_t),Pa=uS(F.messages,k,i,t.cwd),Ta=i.length===0||We||Pa.missingPaths.length===0,_a=!Se||We||Tk(F.messages,k,i)||xk(F.messages,k,i),nn=u&&ve&&!p&&dS(F.messages,k,i),uo=I&&vS(F.messages),po=ae&&PS(F.messages,e),mo=!y||We||SS(F.messages,Math.max(k,A)),fo=pe&&wS(F.messages,k),ho=!v||gS(F.messages,Math.max(k,A),e),go=!w||We||bS(F.messages,Math.max(k,A),e),Ra=!g||N||Et!==null||pS(F.messages,k,i),Ss=!q||We||oS(F.messages,k,i,Q,ye),Ea=!W||We||(q?Ss:Ku(F.messages,k,i,le,ce,X)),ir=!me||We||vk(F.messages,k),Ca=!de||We||Ju(F.messages),bo=!Ee||We||_k(F.messages,k),yo=!te||We||Hu(F.messages,k,i,e),Aa=!E||We||mS(F.messages,k,i),wo=!T||We||fS(F.messages,Math.max(k,A),e),vo=!re||We||hS(F.messages,k,i),Ia=!Re||ck(F.messages,e),ar=(pe?fo:nn)&&Ta&&(Ra&&Ea&&Ss&&Ca&&bo&&yo&&Aa&&wo&&vo&&Ia&&go&&mo)&&(!pe||fo)&&_a&&ir,Rp=k>=0?h.filter(j=>j.index>k).length:0,_n=Jv(F.messages);if(u&&F.stopReason==="progress_checkpoint"&&_n&&!ar&&!qt)return qt=!0,ge(["A background task appears stalled or no longer produces useful progress.",`Task: ${_n.taskId}`,_n.command?`Command: ${_n.command}`:"",_n.idleText?`Idle time: ${_n.idleText}`:"",`Polls without output: ${_n.pollsWithoutOutput}`,"Do not keep polling the same background task without new evidence.",ve?"Preserve the current required output candidate, run one bounded verifier-shaped check against it, then stop or make a targeted repair from concrete failures.":i.length>0?"Checkpoint the best current candidate to the required output path before spending more time waiting.":"Switch to a bounded liveness/artifact/readiness check, or stop the task and pivot to the simplest verifiable route.","For services or VMs, verify the exact final client/protocol command instead of treating quiet background output as progress."].filter(Boolean).join(`
|
|
1226
|
+
`),!0);if(w&&!We&&!go&&(!rt||z)&&(z||u&&F.stopReason==="progress_checkpoint"&&et>=8))return rt=!0,ge(["This service, VM, or protocol task is not validated strongly enough yet.","Do not finish from a running process, generated schema, listening port, screenshot, or socket existence alone.",P?"For protocol/RPC work, instantiate the generated request messages with the task-required fields, call each required RPC through a real client or grpcurl, and assert response fields before stopping.":"",C?"For VM/QEMU work, verify the control surface the verifier will use: monitor/QMP/socket/sendkey or serial access, plus the expected visible/framebuffer/service state.":"","Run the exact final client command shape the user/verifier will run, including authentication and content checks, after the last setup/write.","Print SERVICE_PASS, PROTOCOL_PASS, CLIENT_PASS, VM_CONTROL_PASS, or CONTRACT_PASS only after that end-to-end check succeeds.","If only a port probe has passed, continue: open port is readiness evidence, not final contract evidence."].filter(Boolean).join(`
|
|
1227
|
+
`),!0);if(Re&&!Ia&&(!zn||z)&&(z||u&&F.stopReason==="progress_checkpoint"&&(ve||et>=8))){zn=!0;let j=Td(e);return ge(["This task explicitly requires an installed package, dependency, library, or tool, but the live environment has not been verified yet.","Do not rely on a submitted script to lazily install dependencies during verifier execution.","Install the required dependency in the task environment during this run, then verify it with a direct import/library/version command before finishing.",j.length>0?`Detected package/tool names: ${j.join(", ")}.`:"",`Examples of acceptable checks: R --slave -e "library(pkg); packageVersion('pkg')", python -c "import pkg; print(pkg.__version__)", node -e "require('pkg')", pip show pkg, dpkg -s tool, or command -v tool && tool --version.`,"Only print PACKAGE_INSTALL_PASS, DEPENDENCY_PASS, IMPORT_PASS, or VERSION_PASS after that direct environment check succeeds."].filter(Boolean).join(`
|
|
1228
|
+
`),!0)}if(y&&!We&&!mo&&(!pn||z)&&(z||u&&F.stopReason==="progress_checkpoint"&&et>=8))return pn=!0,ge(["This constrained text-edit task is not validated strongly enough yet.","Do not finish after only compiling or rendering the edited document.","Prove the mutation contract directly: token/word count is preserved and every changed token is an allowed substitution from the prompt's allowlist or synonyms file.","Run a post-edit audit against the final edited file and the original/allowed substitution source.","Print CONSTRAINED_EDIT_PASS, SYNONYM_SUBSTITUTION_PASS, or TOKEN_COUNT_PASS only after illegal changes are zero and token counts match."].join(`
|
|
1229
|
+
`),!0);if(T&&!We&&!wo&&(!ut||z)&&(z||u&&F.stopReason==="progress_checkpoint"&&et>=8))return ut=!0,ge(["This repository sanitization or surgical mutation task is not validated strongly enough yet.","Do not finish after only proving the secret/token is gone; also prove clean files were not changed.","Run a path-scoped diff audit such as git diff --name-only or git status --short, compare changed files against the contaminated/allowed set, and scan for remaining secrets.","If the task specifies placeholder values, also prove exact placeholder replacement consistency across every contaminated file and embedded serialized/diff text.","If any clean or unrelated file changed, restore it before answering.","Print DIFF_SCOPE_PASS, SECRET_SCAN_PASS, REPO_SURGERY_PASS, and when applicable PLACEHOLDER_PASS only after unexpected files are zero, remaining secret matches are zero, and exact placeholders match."].join(`
|
|
1230
|
+
`),!0);if(re&&!We&&!vo&&(!Pt||z)&&(z||u&&F.stopReason==="progress_checkpoint"&&et>=8))return Pt=!0,ge(["This science, biosequence, or numeric-fitting task is not validated strongly enough yet.","Do not finish after only proving the file exists, JSON/FASTA parses, or one smoke sample looks plausible.","Run verifier-equivalent numeric checks against the final artifact: thresholds, bounds, residuals, reconstruction/order, translation, Tm, or repeated timing/metric margin as applicable.","For near-threshold results, require margin or repeated measurements; equal or barely passing evidence is not robust.","Print SCIENCE_PASS, BIO_PASS, NUMERIC_PASS, THRESHOLD_PASS, TM_PASS, ASSEMBLY_PASS, FIT_PASS, or METRIC_PASS only after those assertions pass."].join(`
|
|
1231
|
+
`),!0);if(u&&F.stopReason==="progress_checkpoint"&&Wn){let j=ve&&k>=0&&Rp>=10&&!ar,Ve=j?{mode:"require_output_checkpoint",requiredOutputPaths:i,message:"A submitted candidate exists, but repeated verifier-shaped checks are still failing; Xeno is enforcing targeted repair mode."}:void 0;return ge(["The most recent verifier-shaped validation is still failing.",`Tool: ${Wn.toolName}`,`Evidence: ${Wn.summary}`,j?"Xeno has entered targeted repair mode: more broad exploration is blocked until the submitted artifact is patched.":"Do not keep broad-reading or finish around this failure.",...Wn.toolName==="HtmlSanitizerAudit"?["Use the concrete HtmlSanitizerAudit failure lines; do not spend turns reading generated /tmp/xeno-html-sanitizer-audit-* harness files or /app/.xeno/audit traces."]:[],"Patch the concrete artifact defect shown by that validation, then rerun the same verifier-shaped check until a later passing signal supersedes it."].join(`
|
|
1232
|
+
`),j,Ve)}if(u&&Se&&ve&&!p&&!_a&&(!M||z))return M=!0,ge(["A file-presence or byte-level check only proves the required output file was written; it does not validate the decoded visual/G-code content.","Before finishing, do one independent second-pass content validation after the current output write.","Use a different visual method from the primary guess, such as GcodeAnalyze with auto/PCA projection, ReadImage on an alternate render, OCR/image processing, or a read-only delegated reviewer.","Compare that second-pass reading to the exact required output content and overwrite the file if any character changes."].join(`
|
|
1233
|
+
`),!0);if(u&&pe&&ve&&!p&&qu(F.messages,k)&&!fo&&(!at||z))return at=!0,ge(["This binary memory-extraction self-check is not strong enough yet.","For ELF/binary-file extraction, validate the final script against file-backed bytes, not p_memsz-only zero-filled loader memory.","Use ElfAnalyze or an independent Python/readelf parser to check PT_LOAD p_filesz, exact integer JSON values, and decimal address keys.","Run the exact required node command on the provided binary and, if a C source/compiler is available, on one freshly built second binary before finishing."].join(`
|
|
1234
|
+
`));if(u&&ve&&!p&&nn&&!Ta&&(!wt||z))return wt=!0,ge(["Final-state audit is incomplete: the required output was validated indirectly, but the final artifact itself was not read back or exercised after the latest write.","Before finishing, read or execute each required output path after the last write and print an explicit READBACK_PASS, CONTRACT_PASS, or SELF_CHECK_PASS marker only after the submitted artifact behaves correctly.","Missing final artifact evidence:",...Pa.missingPaths.map(j=>`- ${j}`)].join(`
|
|
1235
|
+
`),!0);if(u&&ve&&!p&&nn&&!Ra&&(!Te||z))return Te=!0,ge(["The current self-check proves the required output exists, but this performance-sensitive task still needs real metric evidence.","Before stopping, run a bounded baseline-vs-candidate or threshold check against the final artifact and print an explicit METRIC_PASS or THRESHOLD_PASS only after the assertions pass.","Use labeled measurements such as median runtime, latency, throughput, speedup, or target budget so the next step can distinguish a real improvement from a smoke test."].join(`
|
|
1236
|
+
`));if(u&&ve&&!p&&nn&&!Aa&&(!Vt||z))return Vt=!0,ge(["The current self-check is too shallow for this HTML/JavaScript sanitization task.","Do not finish after only one script-removal sample or a generic parser/filter smoke test.","Prefer the HtmlSanitizerAudit tool against the final submitted filter command, then fix concrete failures and rerun it until it prints SECURITY_PASS, ROUNDTRIP_PASS, and CONTRACT_PASS.","Run an adversarial sanitizer matrix against the submitted final artifact and keep benign HTML round-tripping intact.","Cover at least script tags, event-handler attributes, javascript: URLs, embedded/srcdoc/data HTML, SVG/MathML vectors, encoded or mixed-case variants, CSS/style vectors, and a clean round-trip fixture.","Attempt an established public XSS/sanitizer corpus such as html-sanitizer-testbed/OWASP payloads first and print the corpus/vector count; only use a hand-built substitute when the download/network attempt clearly failed, and then make it 300+ vectors including malformed tags, comment breakouts, legacy protocol aliases, XML/XHTML namespace vectors, CSS import/escape cases, and attribute breakouts.","For browser-executed HTML/XSS behavior, validate with a real browser/DOM path such as Selenium, Chromium, Playwright, Puppeteer, jsdom, or DOMParser-style execution evidence instead of only scanning strings.",'For clean HTML, compare every benign sample against an exact parser-normalized representation such as str(BeautifulSoup(original, "html.parser")), html5lib, lxml, or parse5 output so formatting/entity/void-tag behavior is explicitly covered.',"Clean fixtures must include at least 10 benign samples, zero clean mismatches, and coverage for void tags, entities, forms, media, and semantic elements; a single clean paragraph or string scan is not enough.","Also prove bounded runtime on a large/pathological or fuzzed HTML input, preferably with an explicit timeout/deadline, so verifier cases cannot hang on catastrophic parsing or regex behavior.","Print CONTRACT_PASS, SECURITY_PASS, or ROUNDTRIP_PASS only after those assertions pass."].join(`
|
|
1237
|
+
`),!0);if(u&&ve&&!p&&nn&&q&&!Ss&&(!D||z))return D=!0,ge(["The current self-check is too shallow for this tensor-parallel/distributed implementation task.","Do not finish after validating only importability, one rank, one world size, or a custom smoke test.","Validate the final submitted artifact with both RowParallelLinear and ColumnParallelLinear, all prompt-required world sizes, every rank in the largest world size, and forward plus gradient behavior when gradients are part of the contract.","For RowParallelLinear, prove the verifier-style contract where forward receives an already-scattered/rank-local input shard; do not only test a full input that the layer slices internally.",...Q.length>0?[`Required world sizes to prove explicitly: ${Q.map(j=>`world_size=${j}`).join(", ")}.`]:[],"Prefer running the exposed verifier under /tests, for example pytest /tests or python /tests/test_outputs.py, when it exists.","Print SELF_CHECK_PASS only after those assertions pass against the final submitted file."].join(`
|
|
1238
|
+
`),!0);if(u&&ve&&!p&&nn&&!Ea&&(!D||z))return D=!0,ge(["The current self-check is too shallow for this ML/model artifact task.","Do not finish after only a one-sample smoke test or a structurally valid wrapper.","Validate the final model, wrapper, or generated artifact with a multi-sample check across representative samples or known labels before stopping.",...le?["Because this task references provided/recovered weights, checkpoints, logits, or tokenizer artifacts, prove the submitted entrypoint actually depends on those artifacts, for example by loading/schema-checking them or by a mutation/removal check that changes outputs."]:[],...ce?["For extraction/recovery tasks, prove complete matrix/weight recovery: expected shape or row/parameter count plus all rows/weights matched with zero missing or unmatched entries. Partial multi-sample probes are not enough."]:[],...X?["For language-model/tokenizer inference, dependency and multi-prompt smoke checks are not enough; compare the final entrypoint against a known/golden/reference continuation from an official fixture, task-provided verifier, or independent reference implementation using the real checkpoint and tokenizer."]:[],"Print SELF_CHECK_PASS only after the submitted entrypoint and final artifact pass those assertions."].join(`
|
|
1239
|
+
`),!0);if(u&&ve&&!p&&nn&&!ir&&(!U||z))return U=!0,ge(["The current self-check is too shallow for this visual reverse-rendering task.","A compile, render, file-existence check, or generic SELF_CHECK_PASS only proves the program runs.","Compare the final rendered candidate to the target/reference image with SSIM, cosine similarity, MSE/RMSE, PSNR, pixel diff, or the task-provided image-similarity verifier before stopping.","If you use ArtifactCompare for visual identity/equivalence, use its strict image metric profile or min_cosine_similarity >= 0.995; loose approximate thresholds are not passing evidence for an identical-output task.","Print VISUAL_SIMILARITY_PASS, METRIC_PASS, or SELF_CHECK_PASS only after that target/reference comparison passes."].join(`
|
|
1240
|
+
`),!0);if(u&&ve&&!p&&nn&&!Ca&&(!G||z))return G=!0,ge(["The current self-check is too shallow for this compiler, emulator, cross-architecture, or polyglot task.","Run a verifier-shaped build/run check against the final artifact or service state before stopping.","Preserve the final runnable state after the last positive check."].join(`
|
|
1241
|
+
`));if(u&&Ee&&ve&&!p&&qu(F.messages,k)&&!bo&&(!fe||z))return fe=!0,ge(["The current self-check is too shallow for this binary/reverse-engineering equivalence task.","A compile, run, file-existence check, or standalone hash only proves the candidate executes; it does not prove it behaves like the original binary.","Before stopping, run the original and the reimplementation in the same final-state shape and compare the real observable contract: stdout, stderr, generated files, image pixels/similarity, protocol behavior, or task-specific outputs.","Prefer ArtifactCompare for generated-file equivalence checks so the reference and candidate run in isolated workdirs with structured byte/image metrics and source-size/independence auditing.","For visual identity/equivalence, ArtifactCompare must pass with byte equality or strict cosine_similarity >= 0.995; do not lower thresholds to make an approximate rendering pass.","Only print SELF_CHECK_PASS, CONTRACT_PASS, BEHAVIOR_PASS, or METRIC_PASS after the comparison proves zero mismatches or meets the explicit similarity/metric threshold against the final submitted artifact."].join(`
|
|
1242
|
+
`),!0);if(u&&ve&&!p&&nn&&!yo&&(!ze||z))return ze=!0,ge(["The current self-check is too shallow for this parser/filter, compression, regex, solver, code-size, or search-heavy task.","Prove correctness with round-trip, diff/checksum, randomized samples, or verifier-shaped fixtures against the final output before stopping.","Print ROUNDTRIP_PASS, CONTRACT_PASS, or SELF_CHECK_PASS only after those assertions pass."].join(`
|
|
1243
|
+
`));if(!I&&!ae&&ar&&ho&&!Wn&&F.stopReason==="progress_checkpoint"&&et>=12)return ps(["Required output exists and a post-write verifier-shaped self-check passed.","No explicit verifier path is exposed in the task container.","Stop now and preserve the validated final filesystem state instead of continuing broad verifier searches."].join(`
|
|
1244
|
+
`));if(u&&F.stopReason==="progress_checkpoint"&&(F.iteration??0)>=18&&et>=18&&!vt)return vt=!0,ge(["Budget checkpoint: this benchmark task has already used many turns.","Do not continue open-ended exploration in the same direction.","Write or preserve the strongest current candidate, run the official verifier if exposed, or run one verifier-shaped self-check that covers the real acceptance contract.","Then fix only concrete failures from that check. If the current approach has failed twice, pivot to the simplest verifiable implementation."].join(`
|
|
1245
|
+
`));if(u&&F.stopReason==="progress_checkpoint"&&ve&&(me&&!ir||Ee&&!bo)&&((F.iteration??0)>=40||et>=40)&&(!ft||(F.iteration??0)>=80))return ft=!0,ge(["Target-metric checkpoint: stop broad reverse-engineering or rendering exploration until the current submitted candidate is measured.","The final source/artifact exists, but there is no passing target/reference comparison yet.","Run a bounded verifier-shaped comparison now: compile/run the submitted source in the final workdir shape, compare produced artifacts to the target/reference with SSIM, cosine similarity, MSE/RMSE, PSNR, pixel diff, ArtifactCompare, or the task verifier, then patch only the first concrete metric failure.","Do not keep disassembling, sampling, or rewriting without preserving and measuring the current best candidate."].join(`
|
|
1246
|
+
`),!0);if(!z||u&&b&&!p&&Et!==null||u&&w&&!p&&go||u&&T&&!p&&wo||u&&re&&!p&&vo||u&&y&&!p&&mo||u&&te&&!p&&yo||u&&q&&!p&&Ss||ar&&ho&&(!I||uo)&&(!ae||po)||I&&uo&&(!m||xe||We)||ae&&po)return null;if(I&&!We&&!uo)return ge(["This structured data conversion is not validated strongly enough yet.","Do not finish based only on row counts, printed rows, or hand-written parser output.","Run a dataframe-level equality check against the source and generated artifact, preferably with pandas:","pd.testing.assert_frame_equal(pd.read_csv(source).reset_index(drop=True), pd.read_parquet(output).reset_index(drop=True))","This catches significant whitespace, null, dtype, and column-order differences before the hidden verifier does."].join(`
|
|
1247
|
+
`),!0);if(ae&&!We&&!po)return ge(["This structured-output script is not validated strongly enough yet.","Do not finish based only on py_compile, --help, file existence, or row counts.","Run the submitted script or a verifier-shaped stub if heavy runtime dependencies are unavailable, then read the generated CSV/JSON artifact back.","Assert the actual acceptance contract: required columns, row count, column order, scalar/list field types, parseability with ast.literal_eval/json.loads where relevant, and any prompt-specific invariants such as non-overlap or contiguous masks.","Print a clear CONTRACT_PASS or SELF_CHECK_PASS marker only after those assertions pass."].join(`
|
|
1248
|
+
`),!0);if(q&&!We&&!Ss&&(!D||z))return D=!0,ge(["This tensor-parallel/distributed task is not validated strongly enough yet.","Do not finish after a static review, one-rank smoke test, or partial world-size check.","Run the submitted file through both RowParallelLinear and ColumnParallelLinear with the prompt-required world sizes and all ranks in the largest world size.","For RowParallelLinear, include a verifier-shaped case where the input passed to forward is already scattered/rank-local for each rank.",...Q.length>0?[`Required world sizes to prove explicitly: ${Q.map(j=>`world_size=${j}`).join(", ")}.`]:[],"Include forward-output agreement and gradient/backward evidence when the task touches PyTorch autograd behavior.","Use the real /tests verifier when exposed; otherwise run a verifier-shaped distributed/multiprocess check against the final artifact.","Print SELF_CHECK_PASS only after the command output reports the world sizes, ranks, row-local/scattered-input case, forward checks, and gradient checks that actually ran."].join(`
|
|
1249
|
+
`),!0);let Ma=p||uk(F.messages);if(m&&!We&&(Ma||!xe))return xe=!0,ge(["This benchmark task is not ready to finish yet.","If the task exposes an official verifier path, run it before you answer.","Use the real task checks such as pytest, test.sh, or the files under /tests when they exist, then inspect failures and iterate until they pass.","If no explicit verifier is exposed, perform a strong self-check that matches the acceptance contract instead of relying on manual reasoning alone."].join(`
|
|
1250
|
+
`),Ma);if(g&&!N&&!kn(F.messages,to)&&Et===null&&(!Te||z))return Te=!0,ge([u?"This is a performance-sensitive benchmark task.":"This is a performance-sensitive task.","Before you finish, gather explicit performance evidence for your solution.","Measure baseline vs. candidate runtime, inspect query plans or profiles, and confirm the optimized path improves the actual bottleneck instead of only preserving correctness.","Keep the measurement bounded: use a small fixed number of warmed runs and stop once the result is clear instead of leaving one ad hoc timing script running for minutes.",...m?["After optimizing, rerun the task's verifier path before you answer."]:["After optimizing, run a strong self-check that matches the task's acceptance contract before you answer."]].join(`
|
|
1251
|
+
`));let Ep=kn(F.messages,Jr),Cp=kn(F.messages,Qr);if(b&&(!Ep||!Cp)&&Et===null&&!Ne)return Ne=!0,ge(["This looks like a SQL performance benchmark task, and your current evidence is not verifier-shaped yet.","Do not rely on shell redirection timing alone.","Benchmark both baseline and candidate through a read-only Python sqlite3 connection, fetch all rows, warm both queries first, alternate order across multiple iterations, compare medians, and inspect EXPLAIN QUERY PLAN before you finish.","Prefer a set-based rewrite that removes correlated subqueries, reuses pre-aggregated CTEs instead of rescanning the same base table, and delays presentation-only joins until after top-k reduction when possible.","Write your best current candidate SQL to the required output file before any long benchmark loop, then overwrite it if stronger evidence changes the answer.","Keep the timing harness bounded to a small fixed sample so you do not spend minutes in one script before producing the required output.","After that, keep the faster SQL in the required output file and answer."].join(`
|
|
1252
|
+
`));if(v&&!ho)return ge(["This task appears to depend on async, signal, process, or cleanup behavior.","Before you finish, exercise the real interruption or shutdown path instead of relying only on static reasoning or one ordinary success run.","Send the actual signal or cancellation path, then confirm termination and cleanup behavior, cleanup output, and the final exit state match the task contract.","For subprocess or CLI-style tasks, validate the submitted artifact through the same import/entrypoint shape a verifier or user will call, and assert observable stdout/stderr cleanup markers such as `Cleaned up.` instead of surrogate START/CLEAN labels or private log counters.","Do not wrap the validation entrypoint in a custom top-level KeyboardInterrupt handler unless the final submitted interface includes that handler; it can mask whether the real caller gets cleanup.",'For async cleanup, make the validation task\'s `finally` block await before printing the cleanup marker, for example `finally: await asyncio.sleep(...); print("Cleaned up.")`, so the check proves awaited finalizers are drained.',"Include at least one boundary case around configured concurrency, queued work, or pending tasks when the prompt mentions max concurrency or cancellation."].join(`
|
|
1253
|
+
`),!0);if(W&&!We&&!Ku(F.messages,k,i,le,ce,X)&&(!D||z))return D=!0,ge(["This ML/model artifact task is not validated strongly enough yet.","Do not finish after only a one-sample smoke test or a structurally valid wrapper.","Inspect the weight/model schema, preprocessing, label order, and exact invocation contract, then run a multi-sample or known-label verifier-shaped check.",...le?["Also prove the final code uses the provided/recovered artifact instead of a constant or narrow stub: load/check the artifact schema and run a dependency or mutation check where removing/changing the artifact changes outputs."]:[],...ce?["For extraction/recovery tasks, prove complete matrix/weight recovery: expected shape or row/parameter count plus all rows/weights matched with zero missing or unmatched entries. Partial multi-sample probes are not enough."]:[],...X?["For language-model/tokenizer inference, dependency and multi-prompt smoke checks are not enough; compare the final entrypoint against a known/golden/reference continuation from an official fixture, task-provided verifier, or independent reference implementation using the real checkpoint and tokenizer."]:[],"For inference CLIs, test several inputs and compare predictions to labels or expected outputs when available. For model generation, check the exact expected continuation or multiple prompts.","Keep the best validated model, weights, CLI, or output artifact at the required final path before answering."].join(`
|
|
1254
|
+
`),!0);if(me&&!ir&&(!U||z))return U=!0,ge(["This visual reverse-rendering task is not validated against the target/reference image yet.","A compile, render, file-existence check, or generic SELF_CHECK_PASS only proves the program runs.","Before finishing, compare the rendered candidate to the target/reference image with a concrete metric such as SSIM, cosine similarity, MSE/RMSE, PSNR, pixel diff, or the task-provided image-similarity verifier.","If you use ArtifactCompare for visual identity/equivalence, use its strict image metric profile or min_cosine_similarity >= 0.995; loose approximate thresholds are not passing evidence for an identical-output task.","Only print VISUAL_SIMILARITY_PASS, METRIC_PASS, or SELF_CHECK_PASS after the comparison passes the chosen threshold against the final submitted artifact."].join(`
|
|
1255
|
+
`),!0);if(ee&&!We&&!hk(F.messages)&&(!H||z))return H=!0,ge(["This visual/video/geometry artifact task is not validated strongly enough yet.","Do not finish from filenames, comments, or one visual guess.","Derive the answer from artifact behavior with parsing, rendering, frame sampling, OCR, or simulation, then do an independent second pass such as a different threshold, preview, or numeric check.","If the task needs frame numbers, coordinates, decoded text, or generated media, validate the final output against multiple representative frames or samples before answering."].join(`
|
|
1256
|
+
`));if(de&&!We&&!Ju(F.messages)&&(!G||z))return G=!0,ge(["This compiler, emulator, cross-architecture, or polyglot task needs a verifier-shaped build/run check before finishing.","Identify the target toolchain and exact command contract, run the smallest focused compile or smoke test first, then run the full verifier when exposed.","Preserve the final runnable artifact or required service state after the last positive check."].join(`
|
|
1257
|
+
`));if(te&&!We&&!Hu(F.messages,k,i,e)&&(!ze||z))return ze=!0,ge(["This compression, regex, solver, code-size, or search-heavy task needs more than a single example before finishing.","First prove correctness with round-trip, diff/checksum, randomized samples, or verifier-shaped fixtures, then continue size/speed/search optimization.","Checkpoint the best valid candidate to the required output path before any long search loop."].join(`
|
|
1258
|
+
`));if(!He&&i.length>0){let j=Du(F.messages,"ReadImage"),Ve=Du(F.messages,"dispatch_agent");if(j>=3&&Ve===0)return He=!0,ge(["A required output file exists, but this looks like an ambiguous visual decoding task.","Before you finish, perform one independent second-pass validation of the decoded string.","Use a different method from your primary approach, such as a read-only helper or a distinct alternate rendering, and overwrite the output file if the candidate changes."].join(`
|
|
1259
|
+
`))}return null}}import{existsSync as Ck,statSync as Ak}from"fs";function oa(t){let e=t.toLowerCase();return e.includes("model_cooldown")||e.includes("status=400")||e.includes("status=401")||e.includes("status=402")||e.includes("status=403")?!1:e.includes("network error")||e.includes("api error:")||e.includes("fetch failed")||e.includes("timeout")||e.includes("econnreset")||e.includes("econnrefused")||e.includes("enotfound")||e.includes("eai_again")||e.includes("socket hang up")||e.includes("temporarily unavailable")||e.includes("cloudflare tunnel error")||e.includes("rate limit")||e.includes("429")||e.includes("530")||e.includes("502")||e.includes("503")||e.includes("504")}function Ik(t){return t.length===0?!1:t.every(e=>{try{let n=Ak(e);return n.isDirectory()||Ck(e)&&n.size>0}catch{return!1}})}function Mk(t){return t?typeof t=="string"?!1:t.stop===!0?!0:t.blocking!==!0&&t.message.trim().length===0:!0}function Id(t){return t.benchmarkMode&&oa(t.errorMessage)&&Ik(t.requiredOutputPaths)&&Mk(t.completionGuardDecision)}import{basename as Ok}from"path";function Md(t){return t.map(e=>({name:e.name(),description:e.description(),aliases:e.aliases()})).sort((e,n)=>e.name.localeCompare(n.name))}function Od(t){let e=["Bootstrap Plan","",`Workspace: ${t.cwd}`,`XENO dir: ${t.xenoDir}`,`Ready to initialize: ${t.canInitialize?"yes":"no"}`,"","Detected project",`- Name: ${t.detected.name}`,`- Type: ${t.detected.type}`,`- Language: ${t.detected.language}`,`- Git repo: ${t.detected.gitRepo?"yes":"no"}`];t.detected.description&&e.push(`- Description: ${t.detected.description}`),e.push("","Planned files");for(let n of t.steps)e.push(`- ${n.action==="create"?"create":"keep"} ${n.path}`);if(t.blockers.length>0){e.push("","Blockers");for(let n of t.blockers)e.push(`- ${n}`)}return e.join(`
|
|
1260
|
+
`)}function $d(t){let e=["Runtime Manifests","",`Workspace: ${t.cwd}`,"",`Commands (${t.commands.length})`];for(let n of t.commands){let s=n.aliases.length>0?` [aliases: ${n.aliases.join(", ")}]`:"";e.push(`- ${n.name}${s}`),n.description&&e.push(` ${n.description}`)}e.push("",`Tools (${t.toolCount})`);for(let n of t.tools){let s=n.inputFields.length>0?` (${n.inputFields.join(", ")})`:"";e.push(`- ${n.name}${s}`)}if(e.push("",`Plugins (${t.pluginCount})`,`Plugin dir: ${t.pluginDir}`),t.plugins.length===0)e.push("- none");else for(let n of t.plugins)e.push(`- ${n.name}@${n.version} [${n.status}]`),n.entryPoint&&e.push(` entry: ${n.entryPoint}`),n.capabilities.length>0&&e.push(` capabilities: ${n.capabilities.join(", ")}`),n.permissions.length>0&&e.push(` permissions: ${n.permissions.join(", ")}`),n.error&&e.push(` error: ${n.error}`);e.push("","Project files");for(let n of t.projectFiles)e.push(`- ${n.exists?"present":"missing"} ${Ok(n.path)}`);return e.join(`
|
|
1261
|
+
`)}import{existsSync as $k}from"fs";import{readdir as Lk,readFile as VE}from"fs/promises";import{join as ia,resolve as Ld}from"path";var ms={};Me(ms,FE);import*as FE from"@xeno-corporation/xeno-agent-sdk";Wt();async function Nk(t){let e=ia(t,".xeno","audit");if(!$k(e))return null;let s=(await Lk(e)).filter(r=>r.endsWith(".jsonl")).sort().reverse()[0];return s?ia(e,s):null}async function Bk(t){return new ms.AuditLogger({filePath:t}).read()}async function Nd(t){let e=Ld(t?.cwd??process.cwd()),n=t?.auditFilePath?Ld(e,t.auditFilePath):await Nk(e);if(!n)throw new Error(`No audit files found under ${ia(e,".xeno","audit")}`);let s=await Bk(n),r=(0,R.summarizeAuditTraces)(s),o=(0,R.buildAuditTraceReport)(s,t?.traceId),i=t?.replay?(0,R.buildAuditReplayReport)(s,t?.traceId):null;return{auditFilePath:n,traceSummaries:r,report:o,replay:i}}function Bd(t,e){let n=[`Audit file: ${t.auditFilePath}`,""];return e?.listOnly?(n.push((0,R.renderAuditTraceSummaries)(t.traceSummaries)),n.join(`
|
|
1262
|
+
`)):e?.replay?t.replay?(n.push(e?.markdown?(0,R.renderAuditReplayMarkdown)(t.replay):(0,R.renderAuditReplayReport)(t.replay)),n.join(`
|
|
1263
|
+
`)):(n.push("No audit replay found."),n.join(`
|
|
1264
|
+
`)):t.report?(n.push(e?.markdown?(0,R.renderAuditTraceMarkdown)(t.report):(0,R.renderAuditTraceReport)(t.report)),n.join(`
|
|
1265
|
+
`)):(n.push("No audit trace found."),n.join(`
|
|
1266
|
+
`))}On();hn();import{createHash as Dk}from"crypto";import{copyFileSync as Fk,existsSync as Qt,mkdirSync as Uk,readdirSync as jk,readFileSync as da,statSync as Vk,writeFileSync as sr}from"fs";import{spawnSync as la}from"child_process";import{basename as pa,delimiter as qk,dirname as ma,join as ct,resolve as st}from"path";var Hk="<redacted>",zk=new Set(["PYTHONIOENCODING","PYTHONUTF8","FORCE_COLOR","NO_COLOR","UV_LINK_MODE","PYTHONPATH"]),Hd="xeno_terminal_bench_agent",Wk="XenoTerminalBenchAgent",ca="xeno_harbor_agent",Xk="XenoHarborAgent",Kk="24",Gk=1200,Yk=1200,zd=2,Wd=900,Xd=1e4,Kd=250,Gd=3e5,Dd=yr,Jk="gpt-5.5",Yd=2,Jd=1500,Qd=12e4,Zd="terminal-bench@2.0",Qk=0,Zk=4,ex=60,tx=24,Fd=6e4,nx=12e4,Ud=new Set([408,409,425,429,500,502,503,504]),sx=`import base64
|
|
1267
|
+
import io
|
|
1268
|
+
import os
|
|
1269
|
+
import re
|
|
1270
|
+
import json
|
|
1271
|
+
import shlex
|
|
1272
|
+
import tarfile
|
|
1273
|
+
import tempfile
|
|
1274
|
+
import time
|
|
1275
|
+
from pathlib import Path
|
|
1276
|
+
|
|
1277
|
+
from terminal_bench.agents.base_agent import AgentResult
|
|
1278
|
+
from terminal_bench.agents.installed_agents.abstract_installed_agent import AbstractInstalledAgent
|
|
1279
|
+
from terminal_bench.agents.failure_mode import FailureMode
|
|
1280
|
+
from terminal_bench.terminal.models import TerminalCommand
|
|
1281
|
+
|
|
1282
|
+
def _xeno_patch_terminal_bench_container_paths() -> None:
|
|
1283
|
+
"""Keep container paths POSIX when Terminal-Bench is launched from Windows."""
|
|
1284
|
+
try:
|
|
1285
|
+
from pathlib import PurePosixPath
|
|
1286
|
+
|
|
1287
|
+
from terminal_bench.terminal.docker_compose_manager import DockerComposeManager
|
|
1288
|
+
from terminal_bench.terminal.tmux_session import TmuxSession
|
|
1289
|
+
|
|
1290
|
+
DockerComposeManager.CONTAINER_TEST_DIR = PurePosixPath("/tests")
|
|
1291
|
+
DockerComposeManager.CONTAINER_SESSION_LOGS_PATH = "/logs"
|
|
1292
|
+
DockerComposeManager.CONTAINER_AGENT_LOGS_PATH = "/agent-logs"
|
|
1293
|
+
|
|
1294
|
+
TmuxSession._GET_ASCIINEMA_TIMESTAMP_SCRIPT_CONTAINER_PATH = PurePosixPath(
|
|
1295
|
+
"/tmp/get-asciinema-timestamp.sh"
|
|
1296
|
+
)
|
|
1297
|
+
|
|
1298
|
+
def logging_path(self):
|
|
1299
|
+
return PurePosixPath(DockerComposeManager.CONTAINER_SESSION_LOGS_PATH) / f"{self._session_name}.log"
|
|
1300
|
+
|
|
1301
|
+
def recording_path(self):
|
|
1302
|
+
if self._disable_recording:
|
|
1303
|
+
return None
|
|
1304
|
+
return PurePosixPath(DockerComposeManager.CONTAINER_SESSION_LOGS_PATH) / f"{self._session_name}.cast"
|
|
1305
|
+
|
|
1306
|
+
TmuxSession.logging_path = property(logging_path)
|
|
1307
|
+
TmuxSession._recording_path = property(recording_path)
|
|
1308
|
+
|
|
1309
|
+
original_create_tar_archive = DockerComposeManager._create_tar_archive
|
|
1310
|
+
if not getattr(original_create_tar_archive, "_xeno_lf_normalization_patch", False):
|
|
1311
|
+
def should_normalize_lf(path, data):
|
|
1312
|
+
name = path.name.lower()
|
|
1313
|
+
if name.endswith((".sh", ".bash", ".zsh", ".ksh")):
|
|
1314
|
+
return True
|
|
1315
|
+
return data.startswith(b"#!") and b"\\r\\n" in data[:4096]
|
|
1316
|
+
|
|
1317
|
+
def add_path(tar, source, arcname):
|
|
1318
|
+
arcname = str(arcname).replace("\\\\", "/")
|
|
1319
|
+
if source.is_symlink():
|
|
1320
|
+
tar.add(source, arcname=arcname, recursive=False)
|
|
1321
|
+
return
|
|
1322
|
+
info = tar.gettarinfo(str(source), arcname=arcname)
|
|
1323
|
+
if source.is_file():
|
|
1324
|
+
data = source.read_bytes()
|
|
1325
|
+
if b"\\r\\n" in data and should_normalize_lf(source, data):
|
|
1326
|
+
data = data.replace(b"\\r\\n", b"\\n")
|
|
1327
|
+
info.size = len(data)
|
|
1328
|
+
tar.addfile(info, io.BytesIO(data))
|
|
1329
|
+
return
|
|
1330
|
+
tar.addfile(info)
|
|
1331
|
+
|
|
1332
|
+
def create_tar_archive(paths, container_filename=None):
|
|
1333
|
+
tar_stream = io.BytesIO()
|
|
1334
|
+
with tarfile.open(fileobj=tar_stream, mode="w") as tar:
|
|
1335
|
+
for path in paths:
|
|
1336
|
+
path = Path(path)
|
|
1337
|
+
if path.is_file() or path.is_symlink():
|
|
1338
|
+
arcname = container_filename if container_filename else path.name
|
|
1339
|
+
add_path(tar, path, arcname)
|
|
1340
|
+
elif path.is_dir():
|
|
1341
|
+
for item in path.rglob("*"):
|
|
1342
|
+
add_path(tar, item, item.relative_to(path))
|
|
1343
|
+
else:
|
|
1344
|
+
raise ValueError(f"Path {path} is neither a file nor directory")
|
|
1345
|
+
tar_stream.seek(0)
|
|
1346
|
+
return tar_stream
|
|
1347
|
+
|
|
1348
|
+
create_tar_archive._xeno_lf_normalization_patch = True
|
|
1349
|
+
DockerComposeManager._create_tar_archive = staticmethod(create_tar_archive)
|
|
1350
|
+
|
|
1351
|
+
original_copy_to_container = DockerComposeManager.copy_to_container
|
|
1352
|
+
if getattr(original_copy_to_container, "_xeno_posix_path_patch", False):
|
|
1353
|
+
return
|
|
1354
|
+
|
|
1355
|
+
def copy_to_container(container, paths, container_dir=None, container_filename=None):
|
|
1356
|
+
if container_dir is not None:
|
|
1357
|
+
container_dir = str(container_dir).replace("\\\\", "/")
|
|
1358
|
+
return original_copy_to_container(
|
|
1359
|
+
container=container,
|
|
1360
|
+
paths=paths,
|
|
1361
|
+
container_dir=container_dir,
|
|
1362
|
+
container_filename=container_filename,
|
|
1363
|
+
)
|
|
1364
|
+
|
|
1365
|
+
copy_to_container._xeno_posix_path_patch = True
|
|
1366
|
+
DockerComposeManager.copy_to_container = staticmethod(copy_to_container)
|
|
1367
|
+
except Exception:
|
|
1368
|
+
return
|
|
1369
|
+
|
|
1370
|
+
|
|
1371
|
+
_xeno_patch_terminal_bench_container_paths()
|
|
1372
|
+
|
|
1373
|
+
TERMINAL_BENCH_PREAMBLE = """You are running inside a live benchmark task container.
|
|
1374
|
+
|
|
1375
|
+
You must perform the task directly in the environment by using tools and making the required changes yourself.
|
|
1376
|
+
Do not reply with instructions for a human to follow unless the task explicitly asks for documentation.
|
|
1377
|
+
Assume the verifier will inspect the filesystem, processes, and command behavior after you finish.
|
|
1378
|
+
|
|
1379
|
+
Critical first step:
|
|
1380
|
+
- inspect the filesystem root and the common verifier locations with absolute paths before exploring domain artifacts
|
|
1381
|
+
- check these absolute paths early: /tests, /test.sh, /run-tests.sh, /README.md, /instruction.md, /app, and the current working directory
|
|
1382
|
+
- do not assume the verifier or README lives under /app; benchmark tasks often place them at /tests or the filesystem root
|
|
1383
|
+
- before opening any large primary input files, inspect task files and verification guidance first
|
|
1384
|
+
- if the task names a required output path such as /app/out.txt, you must actually create or update that file; returning the answer only in your final message is insufficient
|
|
1385
|
+
- if the task gives an exact quoted literal to write, copy that literal byte-for-byte including punctuation and casing; do not add extra punctuation or words
|
|
1386
|
+
- if the task asks for exact short strings from a rendered artifact, write your best candidate to the required output path early and verify that path before finalizing
|
|
1387
|
+
|
|
1388
|
+
Approach requirements:
|
|
1389
|
+
- identify the official verification path early by checking /tests, test.sh, run-tests.sh, pytest targets, unittest entrypoints, and task-provided verifier scripts
|
|
1390
|
+
- some harnesses do not expose verifier files during the agent phase; if /tests and root-level verifier files are absent after a quick check, do not spend the budget searching for hidden tests, satisfy the prompt contract and self-verify the required final behavior
|
|
1391
|
+
- if tests, verifier scripts, or task-provided checks are available, run them before you finish and iterate until they pass
|
|
1392
|
+
- do not rely only on ad hoc spot checks when task-provided tests or verifier scripts exist
|
|
1393
|
+
- if a standard helper command is missing, run \`xeno-toolbox-install <tool-or-package>\` once instead of abandoning the direct approach; it maps common terminal tools such as 7z, bsdtar, nc, sshpass, expect, telnet, socat, lsof, fuser, modprobe, pip, and pexpect to their Debian packages with bounded apt timeouts
|
|
1394
|
+
- if the task explicitly requires installing a package, dependency, library, module, or tool, install it in the live environment during the agent phase; do not rely on the submitted script to lazily install dependencies during verifier execution
|
|
1395
|
+
- after installing a required dependency, verify it with a direct import/library/version command before finishing, for example R --slave -e "library(pkg); packageVersion('pkg')", python -c "import pkg; print(pkg.__version__)", node -e "require('pkg')", pip show pkg, dpkg -s tool, or command -v tool && tool --version
|
|
1396
|
+
- when no official verifier is exposed, write a self-check with real assertions against the final artifact and print an explicit SELF_CHECK_PASS, CONTRACT_PASS, ROUNDTRIP_PASS, or METRIC_PASS marker only after those assertions pass
|
|
1397
|
+
- for exact literal file tasks, verify the final file with a byte-level check such as Python read_bytes() or an equivalent tool before you stop
|
|
1398
|
+
- do not validate by undoing the required final state; if a negative test or cleanup removes required files, services, repository contents, or deployed output, restore the required final state and rerun the positive check before finishing
|
|
1399
|
+
- when the task says a user or verifier will perform an action after you finish, leave the environment ready for that exact action instead of only proving it worked earlier
|
|
1400
|
+
- if the task is performance-sensitive, measure baseline versus candidate and inspect the relevant profiling or explain tooling before you finish
|
|
1401
|
+
- use a four-phase budget loop: inspect the task contract and verifier path, create the smallest viable candidate, run verifier-shaped validation early, then spend remaining time only on concrete failures
|
|
1402
|
+
- reserve final budget for verifier reruns, cleanup, and preserving the final state; after two failed attempts in one direction, pivot to the simplest verifiable route instead of expanding the same path
|
|
1403
|
+
- for service, VM, emulator, SSH, or network tasks, start long-running processes in the background, keep logs, poll readiness, and verify the exact final client command including authentication; an open port alone is not enough
|
|
1404
|
+
- keep only the long-lived service, VM, or emulator in the background; run finite setup/configuration scripts in the foreground with bounded timeouts so you can see completion, errors, and success markers before verifying
|
|
1405
|
+
- for VM or emulator tasks, separate the work into phases: boot the VM in the background, establish a reliable serial/control channel, run finite guest setup commands, then verify from outside the VM with the exact required client command
|
|
1406
|
+
- for QEMU tasks, prefer a daemonized/headless VM plus an explicit serial/control channel such as telnet, TCP, or a Unix socket; if a port opens but SSH/authentication is not ready, stop probing the port and configure the guest through serial/control
|
|
1407
|
+
- for Linux live-ISO SSH tasks, a reliable setup is: boot with user-mode networking and host forwarding, log in on serial, bring up the guest NIC, install or enable OpenSSH, generate host keys, allow root/password login if requested, set the requested password, start sshd, verify externally with ssh or sshpass, and leave the VM running
|
|
1408
|
+
- if a VM serial console shows a login prompt, do not restart the VM; send the login in that same serial session and continue configuration because restarting throws away boot progress
|
|
1409
|
+
- for expect/telnet serial automation, match both login prompts and shell prompts, keep only one serial client active during configuration, and print explicit success markers before final SSH verification
|
|
1410
|
+
- if a verifier or user will connect after you finish, leave the actual service, VM, or emulator running in that final state and rerun the positive client check after any cleanup or negative test
|
|
1411
|
+
- once the exact final positive check passes against the required final state, stop and provide the completion summary; do not keep running exploratory diagnostics, alternate implementations, cleanup, or negative probes that can break the final state
|
|
1412
|
+
- if the task expects a concrete output file, write your best current candidate to that path before any long benchmark loop and overwrite it later if stronger evidence changes the answer
|
|
1413
|
+
- keep ad hoc benchmark harnesses bounded: warm both paths, alternate a small fixed number of runs, and stop once the evidence is clear instead of spending many minutes in one timing script
|
|
1414
|
+
- treat tiny performance wins as noise; repeat measurements and aim for a clear margin before trusting an optimization
|
|
1415
|
+
- for ML/model artifact tasks, inspect weight formats, tensor shapes, preprocessing, label order, and exact CLI/interface contracts before writing wrappers or replacement models
|
|
1416
|
+
- for inference CLIs, validate across multiple representative samples or known labels; a one-image or one-prompt smoke test is not enough evidence
|
|
1417
|
+
- for model-training tasks, build a fast holdout/evaluation loop early and optimize metric, runtime, and artifact-size constraints together
|
|
1418
|
+
- for model-training or source-build tasks with canonical config files, patch and validate the exact config path named by the task or used by the standard training script; do not finish with only an alternate copied config unless the prompt explicitly asks for that alternate path
|
|
1419
|
+
- preserve the real long-running build/training log in the required output file; do not overwrite it with a short validation-only log after training because verifiers often inspect both the training markers and the final metric
|
|
1420
|
+
- when an alternate build system succeeds, preserve upstream-compatible executable and config paths too; validate the exact binary path a user or verifier will execute, not only the alternate build output path
|
|
1421
|
+
- for BVLC Caffe specifically, prefer the upstream Makefile layout when possible: create/verify Makefile.config with CPU_ONLY := 1, leave a real executable at .build_release/tools/caffe.bin, keep examples/cifar10/cifar10_quick_solver.prototxt at solver_mode: CPU and max_iter: 500, and run the final .build_release/tools/caffe.bin test ... command before finishing
|
|
1422
|
+
- if a standard named dataset is required, verify the real dataset directory or database exists before training/testing; locate and run the project-provided download/conversion scripts instead of creating synthetic or surrogate data with the same filenames
|
|
1423
|
+
- for compact model implementations, first match expected outputs and runtime, then reduce size while rerunning the same verifier-shaped examples
|
|
1424
|
+
- for PyTorch/distributed/tensor-parallel implementations, run the actual parametrized world-size or multiprocess verifier shape after edits; py_compile, static grep, or a single-process smoke test is not enough
|
|
1425
|
+
- for language-model/tokenizer inference, only trust known-output checks that come from an official fixture, task-provided verifier, or independent reference implementation using the same checkpoint and tokenizer
|
|
1426
|
+
- for visual/video/G-code/rendering/geometry tasks, derive answers from artifact behavior by parsing, rendering, sampling frames, or simulating; for G-code files use GcodeAnalyze before writing custom render scripts; do not trust filenames, comments, or one visual guess
|
|
1427
|
+
- ReadImage accepts compact Netpbm previews (\`.ppm\`, \`.pgm\`, \`.pbm\`) directly by converting them to PNG transport; use it for generated PPM/ray-tracing outputs instead of installing Pillow only to view them
|
|
1428
|
+
- for visual or temporal outputs, do at least two independent checks when possible, such as numeric analysis plus a rendered preview, or two distinct frame/threshold checks
|
|
1429
|
+
- if a visual, G-code, video, or artifact task asks for a flag, write the decoded flag token itself; never use a generic object label such as "text", "object", or "embossed text" as the final answer
|
|
1430
|
+
- for reverse-rendering source tasks, keep the submitted source file in the required final path; generate renders in temporary or required output locations without deleting the source artifact the verifier will compile
|
|
1431
|
+
- for compiler, emulator, cross-architecture, and polyglot tasks, identify the target toolchain and verifier command first, then build the smallest runnable candidate before attempting a complete implementation
|
|
1432
|
+
- for binary reverse-engineering or decompilation tasks, produce a compact independent reimplementation; never satisfy equivalence by preserving, embedding, invoking, execing, or shelling out to the original compiled artifact or a copied original
|
|
1433
|
+
- for binary reverse-engineering tasks with a compressed source-size limit, check the final source with the exact prompt-shaped command such as \`cat mystery.c | gzip | wc -c\`; image/output equality is not enough if the source violates the size contract
|
|
1434
|
+
- for binary reverse-engineering or decompilation tasks, compile/run success is not enough: run the original and the reimplementation in the same final-state shape, then compare stdout, stderr, generated files, image pixels/similarity, or protocol behavior; do not print SELF_CHECK_PASS until that equivalence check has zero mismatches or meets the task metric
|
|
1435
|
+
- for behavior-equivalence tasks with generated files, prefer ArtifactCompare over hand-written shell glue: run reference and candidate in isolated workdirs, compare relative output artifacts, use \`image_metric_profile: "strict"\` or \`min_cosine_similarity >= 0.995\` for visual identity/equivalence unless the task explicitly allows approximation, and audit compressed source-size/forbidden original invocation in the same check
|
|
1436
|
+
- for compression, solver, regex, or search-heavy tasks, make a correct verifier-shaped baseline first, bound search loops, and checkpoint the best candidate to the required output path before continuing optimization
|
|
1437
|
+
- for regex/chess/legal-move tasks, compare the final candidate against an independent oracle such as python-chess across every provided PGN/FEN and reject empty or narrow move sets before optimizing size
|
|
1438
|
+
- for security or sanitization tasks, prefer parser-based or allowlist-based solutions over regex-only filtering
|
|
1439
|
+
- for HTML/XSS sanitization tasks, validate browser-executed behavior with Selenium/Chromium, Playwright, Puppeteer, jsdom, DOMParser, or an equivalent DOM path; string scans alone do not prove alert-free behavior
|
|
1440
|
+
- for HTML/XSS sanitization tasks, after writing the final filter, prefer HtmlSanitizerAudit with the submitted command template such as \`python /app/filter.py {input}\`; use its failures to fix the implementation instead of hand-writing a tiny one-off checker
|
|
1441
|
+
- for HTML/XSS sanitization tasks, first attempt to download or use an established adversarial corpus such as html-sanitizer-testbed or OWASP XSS filter-evasion payloads and print the corpus/vector count; only fall back to a hand-built set if the download/network attempt clearly fails, and then make the substitute 300+ vectors covering malformed tags, comment breakouts, legacy protocol aliases, XML/XHTML namespace vectors, CSS import/escape cases, and attribute breakouts
|
|
1442
|
+
- for HTML/XSS browser checks, run the final submitted filter against corpus-scale payloads through browser/DOM alert detection, preferably in batches or with a bounded per-case timeout; one clean page plus one malicious sample is not enough
|
|
1443
|
+
- for HTML/XSS sanitizer clean-file checks, compare at least 10 benign samples against exact parser-normalized clean HTML such as str(BeautifulSoup(original, "html.parser")), html5lib, lxml, or parse5 output, print clean_mismatches=0, and cover void tags, entities, forms, media, and semantic elements
|
|
1444
|
+
- for async, process, signal, or cleanup tasks, explicitly test the target signal path and verify process termination, cleanup, and exit behavior through the same import path, CLI entrypoint, or subprocess shape a user/verifier will call
|
|
1445
|
+
- for asyncio cancellation tasks, prefer TaskGroup or explicit cancel-and-await/drain logic so started tasks can run their finally cleanup blocks before the outer interruption finishes; gather-plus-semaphore implementations often miss external KeyboardInterrupt cleanup when queued work exists
|
|
1446
|
+
- validate observable stdout/stderr cleanup evidence from the submitted artifact itself, not only surrogate labels or private log counters; do not add a top-level KeyboardInterrupt catch only in the validation harness unless the submitted user-facing entrypoint has the same catch
|
|
1447
|
+
- for async cleanup validation, make the task's finally block await before printing the cleanup marker, for example finally: await asyncio.sleep(...); print("Cleaned up."), so the check proves awaited finalizers are drained
|
|
1448
|
+
- for SQLite or SQL optimization tasks, avoid shell-output timing as your main evidence; instead use a read-only Python sqlite3 connection, warm both queries, fetch all rows, alternate baseline and candidate across multiple iterations, compare medians, and inspect EXPLAIN QUERY PLAN
|
|
1449
|
+
- for SQL optimization tasks, prefer set-based rewrites over correlated subqueries, reuse pre-aggregated CTEs instead of rescanning the same base table, and delay presentation-only joins until after top-k reduction when possible
|
|
1450
|
+
- for top-N SQL aggregate tasks, preserve the original ORDER BY and LIMIT semantics by materializing the smallest candidate set first; compute expensive per-row details, tie-breaker helpers, secondary counts, and display joins only for that reduced set instead of for every base row
|
|
1451
|
+
- do not globally precompute secondary detail aggregates unless they participate in ORDER BY/LIMIT; detail CTEs that only fill output columns after top-N selection should run after top-N reduction or as targeted lookups for the selected rows
|
|
1452
|
+
- for archive, password, hash, or decryption tasks, use format-specific tooling before broad searching: 7z/7zz for extraction, *2john scripts plus john/hashcat and bundled wordlists for cracking, and narrow missing helper modules when permitted; never finish with placeholder output such as UNKNOWN
|
|
1453
|
+
- for CSV/TSV/Parquet/JSONL conversion tasks, preserve source values exactly unless normalization is requested; do not trim field values, and validate by reading the produced artifact back and comparing exact cell values, row count, column order, nulls, and relevant dtypes
|
|
1454
|
+
- for CSV-to-Parquet or similar dataframe conversions, prefer pandas/pyarrow and run pd.testing.assert_frame_equal on pd.read_csv(source) versus pd.read_parquet(output); printed rows or row counts are not enough because whitespace can be significant
|
|
1455
|
+
- for scripts that generate CSV/JSON/JSONL artifacts, run the script or a verifier-shaped stub, then read the generated artifact back and assert required columns, row count, column order, parseability, scalar/list field types such as list versus tuple, and task-specific invariants; for list-valued CSV columns, parse strings with ast.literal_eval/json.loads and assert isinstance(parsed, list), not isinstance(parsed, (list, tuple)); file existence, py_compile, or --help is not enough
|
|
1456
|
+
- for constrained text-edit tasks, rendering or compiling is not enough; audit the edited file against the original and allowed substitution source, preserve token/word count, and prove illegal changes are zero
|
|
1457
|
+
- when Python dependencies are missing on Debian/Ubuntu, prefer a temporary virtual environment such as python3 -m venv /tmp/xeno-venv && /tmp/xeno-venv/bin/pip install ...; avoid repeated global pip attempts when PEP 668 blocks system installs
|
|
1458
|
+
- if a file is large, inspect it incrementally with targeted searches or partial reads instead of dumping the entire file into context at once
|
|
1459
|
+
- if the task expects a concrete output file, create it as soon as you have a strong candidate and then refine or overwrite it if later evidence improves it
|
|
1460
|
+
- prefer compiling or testing into temporary paths when the task requires an exact final directory or single-file deliverable
|
|
1461
|
+
- remove generated binaries, caches, logs, and other self-check artifacts from required output directories unless the task explicitly requires those files as final deliverables
|
|
1462
|
+
- before finishing exact-file or single-file tasks, list the required output directory and confirm it contains only the expected final deliverables
|
|
1463
|
+
- do not spend the whole budget chasing perfect certainty when the task expects a single best answer; benchmark tasks reward completed verified outputs, not endless analysis
|
|
1464
|
+
|
|
1465
|
+
Before you finish:
|
|
1466
|
+
- leave the environment in the state required by the task
|
|
1467
|
+
- if any self-check changed the required final state, restore it and verify the final positive condition again
|
|
1468
|
+
- keep any required background services running if the task depends on them
|
|
1469
|
+
- give a short completion summary only after the work is actually done
|
|
1470
|
+
"""
|
|
1471
|
+
|
|
1472
|
+
DEFAULT_BENCHMARK_API_MAX_RETRIES = "${zd}"
|
|
1473
|
+
DEFAULT_BENCHMARK_API_BASE_DELAY_MS = "${Wd}"
|
|
1474
|
+
DEFAULT_BENCHMARK_API_MAX_DELAY_MS = "${Xd}"
|
|
1475
|
+
DEFAULT_BENCHMARK_API_RETRY_JITTER_MS = "${Kd}"
|
|
1476
|
+
DEFAULT_BENCHMARK_API_REQUEST_TIMEOUT_MS = "${Gd}"
|
|
1477
|
+
DEFAULT_BENCHMARK_RUN_RESTART_MAX_ATTEMPTS = "${Yd}"
|
|
1478
|
+
DEFAULT_BENCHMARK_RUN_RESTART_BASE_DELAY_MS = "${Jd}"
|
|
1479
|
+
DEFAULT_BENCHMARK_RUN_RESTART_MAX_DELAY_MS = "${Qd}"
|
|
1480
|
+
|
|
1481
|
+
|
|
1482
|
+
class XenoTerminalBenchAgent(AbstractInstalledAgent):
|
|
1483
|
+
@staticmethod
|
|
1484
|
+
def name() -> str:
|
|
1485
|
+
return "xeno"
|
|
1486
|
+
|
|
1487
|
+
def __init__(
|
|
1488
|
+
self,
|
|
1489
|
+
model_name: str | None = None,
|
|
1490
|
+
base_url: str | None = None,
|
|
1491
|
+
delegate: bool = False,
|
|
1492
|
+
max_iterations: int | None = None,
|
|
1493
|
+
max_tokens: int | None = None,
|
|
1494
|
+
external_agent_timeout_sec: int | None = None,
|
|
1495
|
+
*args,
|
|
1496
|
+
**kwargs,
|
|
1497
|
+
):
|
|
1498
|
+
super().__init__(*args, **kwargs)
|
|
1499
|
+
self._model_name = model_name
|
|
1500
|
+
self._base_url = base_url
|
|
1501
|
+
self._delegate = delegate
|
|
1502
|
+
self._max_iterations = max_iterations
|
|
1503
|
+
self._max_tokens = max_tokens
|
|
1504
|
+
self._external_agent_timeout_sec = external_agent_timeout_sec
|
|
1505
|
+
|
|
1506
|
+
@property
|
|
1507
|
+
def _env(self) -> dict[str, str]:
|
|
1508
|
+
env = {
|
|
1509
|
+
"XENO_API_KEY": os.environ["XENO_API_KEY"],
|
|
1510
|
+
"XENO_BENCHMARK_MODE": "terminal-bench",
|
|
1511
|
+
"XENO_FORCE_EXIT_AFTER_RUN": "1",
|
|
1512
|
+
"XENO_ALLOW_UNSAFE_BYPASS": "1",
|
|
1513
|
+
"XENO_API_MAX_RETRIES": os.environ.get("XENO_API_MAX_RETRIES", DEFAULT_BENCHMARK_API_MAX_RETRIES),
|
|
1514
|
+
"XENO_API_BASE_DELAY_MS": os.environ.get("XENO_API_BASE_DELAY_MS", DEFAULT_BENCHMARK_API_BASE_DELAY_MS),
|
|
1515
|
+
"XENO_API_MAX_DELAY_MS": os.environ.get("XENO_API_MAX_DELAY_MS", DEFAULT_BENCHMARK_API_MAX_DELAY_MS),
|
|
1516
|
+
"XENO_API_RETRY_JITTER_MS": os.environ.get("XENO_API_RETRY_JITTER_MS", DEFAULT_BENCHMARK_API_RETRY_JITTER_MS),
|
|
1517
|
+
"XENO_API_REQUEST_TIMEOUT_MS": os.environ.get("XENO_API_REQUEST_TIMEOUT_MS", DEFAULT_BENCHMARK_API_REQUEST_TIMEOUT_MS),
|
|
1518
|
+
"XENO_RUN_RESTART_MAX_ATTEMPTS": os.environ.get("XENO_RUN_RESTART_MAX_ATTEMPTS", DEFAULT_BENCHMARK_RUN_RESTART_MAX_ATTEMPTS),
|
|
1519
|
+
"XENO_RUN_RESTART_BASE_DELAY_MS": os.environ.get("XENO_RUN_RESTART_BASE_DELAY_MS", DEFAULT_BENCHMARK_RUN_RESTART_BASE_DELAY_MS),
|
|
1520
|
+
"XENO_RUN_RESTART_MAX_DELAY_MS": os.environ.get("XENO_RUN_RESTART_MAX_DELAY_MS", DEFAULT_BENCHMARK_RUN_RESTART_MAX_DELAY_MS),
|
|
1521
|
+
"CI": "1",
|
|
1522
|
+
}
|
|
1523
|
+
outer_timeout_sec = self._resolve_outer_timeout_sec()
|
|
1524
|
+
env["XENO_EXTERNAL_AGENT_TIMEOUT_SEC"] = str(self._agent_soft_timeout_sec(outer_timeout_sec))
|
|
1525
|
+
started_at_ms = str(int(time.time() * 1000))
|
|
1526
|
+
env["XENO_AGENT_STARTED_AT_MS"] = started_at_ms
|
|
1527
|
+
env["XENO_RUN_STARTED_AT_MS"] = started_at_ms
|
|
1528
|
+
if self._base_url:
|
|
1529
|
+
env["XENO_BASE_URL"] = self._base_url
|
|
1530
|
+
elif "XENO_BASE_URL" not in env and not os.environ.get("XENO_BASE_URL"):
|
|
1531
|
+
env["XENO_BASE_URL"] = "${Dd}"
|
|
1532
|
+
package_sha = os.environ.get("XENO_TERMINAL_BENCH_PACKAGE_SHA256")
|
|
1533
|
+
if package_sha:
|
|
1534
|
+
env["XENO_TERMINAL_BENCH_PACKAGE_SHA256"] = package_sha
|
|
1535
|
+
package_version = os.environ.get("XENO_TERMINAL_BENCH_PACKAGE_VERSION")
|
|
1536
|
+
if package_version:
|
|
1537
|
+
env["XENO_TERMINAL_BENCH_PACKAGE_VERSION"] = package_version
|
|
1538
|
+
package_git_sha = os.environ.get("XENO_TERMINAL_BENCH_PACKAGE_GIT_SHA")
|
|
1539
|
+
if package_git_sha:
|
|
1540
|
+
env["XENO_TERMINAL_BENCH_PACKAGE_GIT_SHA"] = package_git_sha
|
|
1541
|
+
return env
|
|
1542
|
+
|
|
1543
|
+
@staticmethod
|
|
1544
|
+
def _positive_int(value: object, fallback: int) -> int:
|
|
1545
|
+
try:
|
|
1546
|
+
parsed = int(str(value).strip())
|
|
1547
|
+
except (TypeError, ValueError):
|
|
1548
|
+
return fallback
|
|
1549
|
+
return parsed if parsed > 0 else fallback
|
|
1550
|
+
|
|
1551
|
+
@staticmethod
|
|
1552
|
+
def _agent_soft_timeout_sec(outer_timeout_sec: int) -> int:
|
|
1553
|
+
if outer_timeout_sec > 120:
|
|
1554
|
+
return max(60, outer_timeout_sec - 75)
|
|
1555
|
+
return max(1, outer_timeout_sec)
|
|
1556
|
+
|
|
1557
|
+
def _resolve_outer_timeout_sec(self) -> int:
|
|
1558
|
+
if self._external_agent_timeout_sec:
|
|
1559
|
+
return self._positive_int(self._external_agent_timeout_sec, 900)
|
|
1560
|
+
return self._positive_int(os.environ.get("XENO_EXTERNAL_AGENT_TIMEOUT_SEC"), 900)
|
|
1561
|
+
|
|
1562
|
+
@property
|
|
1563
|
+
def _install_agent_script_path(self) -> Path:
|
|
1564
|
+
return Path(__file__).with_name("xeno-code-setup.sh")
|
|
1565
|
+
|
|
1566
|
+
def perform_task(self, instruction: str, session, logging_dir: Path | None = None):
|
|
1567
|
+
package_tarball = Path(os.environ["XENO_TERMINAL_BENCH_PACKAGE_TARBALL"])
|
|
1568
|
+
if not package_tarball.exists():
|
|
1569
|
+
return type(self)._agent_install_failed()
|
|
1570
|
+
|
|
1571
|
+
session.copy_to_container(
|
|
1572
|
+
package_tarball,
|
|
1573
|
+
container_dir="/installed-agent",
|
|
1574
|
+
container_filename="xeno-agent-cli.tgz",
|
|
1575
|
+
)
|
|
1576
|
+
rendered_instruction = self._render_instruction(instruction)
|
|
1577
|
+
prompt, required_output_paths = self._build_prompt(rendered_instruction)
|
|
1578
|
+
self._copy_text_to_container(session, "xeno-prompt.txt", prompt)
|
|
1579
|
+
self._copy_text_to_container(session, "xeno-required-output-paths.json", json.dumps(required_output_paths))
|
|
1580
|
+
self._copy_text_to_container(session, "xeno-api-smoke.js", self._build_api_smoke_script())
|
|
1581
|
+
self._copy_text_to_container(session, "xeno-runner.sh", self._build_runner_script(required_output_paths))
|
|
1582
|
+
return super().perform_task(instruction, session, logging_dir=logging_dir)
|
|
1583
|
+
|
|
1584
|
+
@staticmethod
|
|
1585
|
+
def _agent_install_failed():
|
|
1586
|
+
return AgentResult(
|
|
1587
|
+
total_input_tokens=0,
|
|
1588
|
+
total_output_tokens=0,
|
|
1589
|
+
failure_mode=FailureMode.AGENT_INSTALLATION_FAILED,
|
|
1590
|
+
)
|
|
1591
|
+
|
|
1592
|
+
@staticmethod
|
|
1593
|
+
def _copy_text_to_container(session, filename: str, content: str) -> None:
|
|
1594
|
+
temp_path: Path | None = None
|
|
1595
|
+
try:
|
|
1596
|
+
with tempfile.NamedTemporaryFile("w", encoding="utf-8", newline="\\n", delete=False) as handle:
|
|
1597
|
+
handle.write(content)
|
|
1598
|
+
temp_path = Path(handle.name)
|
|
1599
|
+
session.copy_to_container(
|
|
1600
|
+
temp_path,
|
|
1601
|
+
container_dir="/installed-agent",
|
|
1602
|
+
container_filename=filename,
|
|
1603
|
+
)
|
|
1604
|
+
finally:
|
|
1605
|
+
if temp_path is not None:
|
|
1606
|
+
try:
|
|
1607
|
+
temp_path.unlink(missing_ok=True)
|
|
1608
|
+
except OSError:
|
|
1609
|
+
pass
|
|
1610
|
+
|
|
1611
|
+
@staticmethod
|
|
1612
|
+
def _extract_required_output_paths(instruction: str) -> list[str]:
|
|
1613
|
+
def normalize_candidate(value: str) -> str | None:
|
|
1614
|
+
candidate = value.strip().rstrip(".,;:)]")
|
|
1615
|
+
if not candidate or candidate.endswith("/") or candidate.endswith("\\\\"):
|
|
1616
|
+
return None
|
|
1617
|
+
lowered = candidate.lower()
|
|
1618
|
+
if re.match(r"^[a-z][a-z0-9+.-]*://", lowered):
|
|
1619
|
+
return None
|
|
1620
|
+
if candidate.startswith("//"):
|
|
1621
|
+
return None
|
|
1622
|
+
if re.match(r"^/[a-z][a-z0-9+.-]*://", lowered):
|
|
1623
|
+
return None
|
|
1624
|
+
return candidate
|
|
1625
|
+
|
|
1626
|
+
def path_context(text: str, start: int, length: int) -> str:
|
|
1627
|
+
line_start = text.rfind("\\n", 0, start) + 1
|
|
1628
|
+
line_end = text.find("\\n", start + length)
|
|
1629
|
+
if line_end == -1:
|
|
1630
|
+
line_end = len(text)
|
|
1631
|
+
line = text[line_start:line_end]
|
|
1632
|
+
relative_start = max(0, start - line_start)
|
|
1633
|
+
relative_end = min(len(line), relative_start + length)
|
|
1634
|
+
|
|
1635
|
+
before = line[:relative_start]
|
|
1636
|
+
sentence_start = 0
|
|
1637
|
+
for boundary in re.finditer(r"[.!?]\\s+", before):
|
|
1638
|
+
sentence_start = boundary.end()
|
|
1639
|
+
|
|
1640
|
+
after = line[relative_end:]
|
|
1641
|
+
sentence_end = len(line)
|
|
1642
|
+
boundary = re.search(r"[.!?](?:\\s+|$)", after)
|
|
1643
|
+
if boundary is not None:
|
|
1644
|
+
sentence_end = relative_end + boundary.start() + 1
|
|
1645
|
+
|
|
1646
|
+
return line[sentence_start:sentence_end]
|
|
1647
|
+
|
|
1648
|
+
def line_at(text: str, start: int, length: int) -> str:
|
|
1649
|
+
line_start = text.rfind("\\n", 0, start) + 1
|
|
1650
|
+
line_end = text.find("\\n", start + length)
|
|
1651
|
+
if line_end == -1:
|
|
1652
|
+
line_end = len(text)
|
|
1653
|
+
return text[line_start:line_end]
|
|
1654
|
+
|
|
1655
|
+
def list_heading_context(text: str, start: int) -> str:
|
|
1656
|
+
line_start = text.rfind("\\n", 0, start) + 1
|
|
1657
|
+
previous_lines = text[:line_start].splitlines()
|
|
1658
|
+
context: list[str] = []
|
|
1659
|
+
nonempty = 0
|
|
1660
|
+
for line in reversed(previous_lines[-8:]):
|
|
1661
|
+
stripped = line.strip()
|
|
1662
|
+
if not stripped:
|
|
1663
|
+
continue
|
|
1664
|
+
nonempty += 1
|
|
1665
|
+
context.append(stripped)
|
|
1666
|
+
if stripped.endswith(":"):
|
|
1667
|
+
break
|
|
1668
|
+
if nonempty >= 5:
|
|
1669
|
+
break
|
|
1670
|
+
return " ".join(reversed(context))
|
|
1671
|
+
|
|
1672
|
+
patterns = [
|
|
1673
|
+
r"(?i)\\bwrite\\s+(?:the\\s+)?(?:output|result|answer|contents?)\\s+to\\s+(?:\\"|')?(/[^\\s\\"']+)(?:\\"|')?",
|
|
1674
|
+
r"(?i)\\bsave\\s+(?:it|them|the\\s+(?:output|result|answer|model|file))?\\s+as\\s+(?:\\"|')?(/[^\\s\\"']+)(?:\\"|')?",
|
|
1675
|
+
r"(?i)\\bsave\\s+(?:your\\s+)?(?:solution|answer|output|result|artifact)\\s+(?:in|to)\\s+(?:the\\s+file\\s+)?(?:\\"|')?(/[^\\s\\"']+)(?:\\"|')?",
|
|
1676
|
+
r"(?i)\\b(?:create|place)\\s+(?:a\\s+file\\s+(?:called|named)|the\\s+file)\\s+(?:\\"|')?(/[^\\s\\"']+)(?:\\"|')?",
|
|
1677
|
+
r"(?i)\\bconvert\\s+(?:the\\s+)?(?:file\\s+)?[^\\n]*?\\s+(?:into|to)\\s+(?:a\\s+)?(?:[\\w-]+\\s+)*file\\s+named\\s+(?:\\"|')?(/[^\\s\\"']+)(?:\\"|')?",
|
|
1678
|
+
r"(?i)\\b(?:must|should)\\s+be\\s+(?:saved|written|placed)\\s+(?:as|to|in)\\s+(?:\\"|')?(/[^\\s\\"']+)(?:\\"|')?",
|
|
1679
|
+
r"(?i)\\bfinal\\s+(?:model|output)\\s+should\\s+be\\s+saved\\s+as\\s+(?:\\"|')?(/[^\\s\\"']+)(?:\\"|')?",
|
|
1680
|
+
]
|
|
1681
|
+
required_paths: list[str] = []
|
|
1682
|
+
seen: set[str] = set()
|
|
1683
|
+
for pattern in patterns:
|
|
1684
|
+
for match in re.finditer(pattern, instruction):
|
|
1685
|
+
candidate = normalize_candidate(match.group(1))
|
|
1686
|
+
if candidate is None:
|
|
1687
|
+
continue
|
|
1688
|
+
if candidate not in seen:
|
|
1689
|
+
seen.add(candidate)
|
|
1690
|
+
required_paths.append(candidate)
|
|
1691
|
+
|
|
1692
|
+
for match in re.finditer(r"/[^\\s\\"'\\x60]+", instruction):
|
|
1693
|
+
candidate = normalize_candidate(match.group(0))
|
|
1694
|
+
if candidate is None:
|
|
1695
|
+
continue
|
|
1696
|
+
sanitized_length = len(candidate)
|
|
1697
|
+
snippet = path_context(instruction, match.start(), sanitized_length).lower()
|
|
1698
|
+
line = line_at(instruction, match.start(), sanitized_length)
|
|
1699
|
+
list_context = list_heading_context(instruction, match.start()).lower()
|
|
1700
|
+
is_list_item = re.match(r"\\s*(?:[-*+]|\\d+[.)])\\s+", line) is not None
|
|
1701
|
+
|
|
1702
|
+
output_score = 0
|
|
1703
|
+
reference_score = 0
|
|
1704
|
+
|
|
1705
|
+
if re.search(r"\\b(save|write|create|place|put|store|submit|final)\\b", snippet):
|
|
1706
|
+
output_score += 1
|
|
1707
|
+
if re.search(r"\\b(solution|answer|output|result|artifact|submission)\\b", snippet):
|
|
1708
|
+
output_score += 2
|
|
1709
|
+
if is_list_item and re.search(r"\\b(save|write|create|produce|generate|place|put|store|submit|final|deliverables?|required|results?|outputs?)\\b", list_context):
|
|
1710
|
+
output_score += 3
|
|
1711
|
+
if re.search(r"\\b(posterior|mean|estimate|estimation|stan model|r file|script|model file|solution file|answer file)\\b", snippet):
|
|
1712
|
+
output_score += 1
|
|
1713
|
+
if re.search(r"\\bin the file\\b|\\bto the file\\b|\\brequired output\\b", snippet):
|
|
1714
|
+
output_score += 2
|
|
1715
|
+
if re.search(r"\\bmust contain\\b|\\bshould contain\\b|\\bterminated by\\b", snippet):
|
|
1716
|
+
output_score += 1
|
|
1717
|
+
|
|
1718
|
+
if re.search(r"\\blocated at\\b|\\bdatabase\\b|\\bbaseline\\b|\\breference\\b|\\bgolden\\b|\\binput\\b", snippet):
|
|
1719
|
+
reference_score += 2
|
|
1720
|
+
if re.search(r"\\b(load|read|provided|given|available|dataset)\\b", snippet) and re.search(r"\\b(from|at|in)\\b", snippet):
|
|
1721
|
+
reference_score += 3
|
|
1722
|
+
if is_list_item and re.search(r"\\b(load|read|provided|given|available|dataset|input|reference|baseline)\\b", list_context):
|
|
1723
|
+
reference_score += 3
|
|
1724
|
+
if re.search(r"\\bcompiled\\b|\\b(?:program|binary|executable)\\s+at\\b|\\bprovided\\s+(?:program|binary|executable)\\b|\\boriginal\\s+(?:program|binary|executable)\\b", snippet):
|
|
1725
|
+
reference_score += 3
|
|
1726
|
+
if re.search(r"\\bsaved in\\b|\\bimplemented in\\b|\\bprovided in\\b|\\bstored in\\b", snippet):
|
|
1727
|
+
reference_score += 2
|
|
1728
|
+
if re.search(r"\\bquery\\b", snippet) and re.search(r"\\bimplemented\\b", snippet):
|
|
1729
|
+
reference_score += 1
|
|
1730
|
+
|
|
1731
|
+
if output_score > 0 and output_score > reference_score and candidate not in seen:
|
|
1732
|
+
seen.add(candidate)
|
|
1733
|
+
required_paths.append(candidate)
|
|
1734
|
+
return required_paths
|
|
1735
|
+
|
|
1736
|
+
def _build_prompt(self, instruction: str) -> tuple[str, list[str]]:
|
|
1737
|
+
required_output_paths = self._extract_required_output_paths(instruction)
|
|
1738
|
+
required_output_text = ""
|
|
1739
|
+
if required_output_paths:
|
|
1740
|
+
required_output_text = "\\n".join([
|
|
1741
|
+
"",
|
|
1742
|
+
"Required output paths:",
|
|
1743
|
+
*[f"- {path}" for path in required_output_paths],
|
|
1744
|
+
])
|
|
1745
|
+
prompt = (
|
|
1746
|
+
f"{TERMINAL_BENCH_PREAMBLE.strip()}"
|
|
1747
|
+
f"{required_output_text}\\n\\nTask:\\n{instruction}"
|
|
1748
|
+
)
|
|
1749
|
+
return prompt, required_output_paths
|
|
1750
|
+
|
|
1751
|
+
def _build_api_smoke_script(self) -> str:
|
|
1752
|
+
node_script = r"""
|
|
1753
|
+
const fs = require("node:fs");
|
|
1754
|
+
const path = require("node:path");
|
|
1755
|
+
const payload = JSON.parse(process.env.XENO_API_SMOKE_PAYLOAD || "{}");
|
|
1756
|
+
const outPath = process.env.XENO_API_SMOKE_OUTPUT || "/logs/agent/api-smoke.json";
|
|
1757
|
+
const baseUrl = (process.env.XENO_BASE_URL || "${Dd}").replace(/\\/$/, "");
|
|
1758
|
+
const apiKey = process.env.XENO_API_KEY || "";
|
|
1759
|
+
const startedAt = new Date().toISOString();
|
|
1760
|
+
const maxAttempts = Math.max(1, Number.parseInt(process.env.XENO_API_SMOKE_MAX_ATTEMPTS || "3", 10) || 3);
|
|
1761
|
+
const baseDelayMs = Math.max(0, Number.parseInt(process.env.XENO_API_SMOKE_BASE_DELAY_MS || "1000", 10) || 1000);
|
|
1762
|
+
const maxRetryAfterMs = Math.max(0, Number.parseInt(process.env.XENO_API_MAX_RETRY_AFTER_MS || "120000", 10) || 120000);
|
|
1763
|
+
const transientStatuses = new Set([408, 409, 425, 429, 500, 502, 503, 504]);
|
|
1764
|
+
|
|
1765
|
+
function sleep(ms) {
|
|
1766
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1767
|
+
}
|
|
1768
|
+
|
|
1769
|
+
function writeReport(report) {
|
|
1770
|
+
fs.mkdirSync(path.dirname(outPath), { recursive: true });
|
|
1771
|
+
fs.writeFileSync(outPath, JSON.stringify(report, null, 2));
|
|
1772
|
+
}
|
|
1773
|
+
|
|
1774
|
+
function isStrictSmoke() {
|
|
1775
|
+
return process.env.XENO_API_SMOKE_STRICT === "1";
|
|
1776
|
+
}
|
|
1777
|
+
|
|
1778
|
+
function shouldContinueAfterFailure(report) {
|
|
1779
|
+
return !isStrictSmoke() && report.transient === true;
|
|
1780
|
+
}
|
|
1781
|
+
|
|
1782
|
+
function extractProviderError(parsed, bodyText) {
|
|
1783
|
+
const candidates = [parsed];
|
|
1784
|
+
const nested = parsed && typeof parsed?.error?.message === "string" ? parsed.error.message : null;
|
|
1785
|
+
if (nested) {
|
|
1786
|
+
try {
|
|
1787
|
+
candidates.push(JSON.parse(nested));
|
|
1788
|
+
} catch {
|
|
1789
|
+
candidates.push({ error: { message: nested } });
|
|
1790
|
+
}
|
|
1791
|
+
}
|
|
1792
|
+
const normalizedBody = String(bodyText || "").replace(/\\\\"/g, '"');
|
|
1793
|
+
const resetMatch = normalizedBody.match(/"reset_seconds"s*:s*(d+)/i) || normalizedBody.match(/\breset_seconds\b[^d]{0,20}(d+)/i);
|
|
1794
|
+
for (const candidate of candidates) {
|
|
1795
|
+
const error = candidate?.error || candidate;
|
|
1796
|
+
if (!error) continue;
|
|
1797
|
+
const resetSeconds = Number.parseInt(String(error.reset_seconds || error.resetSeconds || ""), 10);
|
|
1798
|
+
return {
|
|
1799
|
+
code: error.code || candidate?.code,
|
|
1800
|
+
message: error.message || candidate?.message,
|
|
1801
|
+
resetSeconds: Number.isFinite(resetSeconds) && resetSeconds > 0
|
|
1802
|
+
? resetSeconds
|
|
1803
|
+
: resetMatch
|
|
1804
|
+
? Number.parseInt(resetMatch[1], 10)
|
|
1805
|
+
: undefined,
|
|
1806
|
+
};
|
|
1807
|
+
}
|
|
1808
|
+
return {
|
|
1809
|
+
code: normalizedBody.includes("model_cooldown") ? "model_cooldown" : undefined,
|
|
1810
|
+
message: undefined,
|
|
1811
|
+
resetSeconds: resetMatch ? Number.parseInt(resetMatch[1], 10) : undefined,
|
|
1812
|
+
};
|
|
1813
|
+
}
|
|
1814
|
+
|
|
1815
|
+
async function requestOnce(attempt) {
|
|
1816
|
+
const response = await fetch(baseUrl + "/v1/chat/completions", {
|
|
1817
|
+
method: "POST",
|
|
1818
|
+
headers: {
|
|
1819
|
+
"Content-Type": "application/json",
|
|
1820
|
+
Authorization: "Bearer " + apiKey,
|
|
1821
|
+
"User-Agent": "XenoTerminalBench/0.2.0",
|
|
1822
|
+
},
|
|
1823
|
+
body: JSON.stringify(payload),
|
|
1824
|
+
});
|
|
1825
|
+
const bodyText = await response.text();
|
|
1826
|
+
let parsed = null;
|
|
1827
|
+
try {
|
|
1828
|
+
parsed = JSON.parse(bodyText);
|
|
1829
|
+
} catch {
|
|
1830
|
+
parsed = null;
|
|
1831
|
+
}
|
|
1832
|
+
const providerError = extractProviderError(parsed, bodyText);
|
|
1833
|
+
const retryAfterMs = providerError.resetSeconds ? providerError.resetSeconds * 1000 : undefined;
|
|
1834
|
+
const longProviderCooldown = providerError.code === "model_cooldown" && retryAfterMs && retryAfterMs > maxRetryAfterMs;
|
|
1835
|
+
return {
|
|
1836
|
+
ok: response.ok,
|
|
1837
|
+
status: response.status,
|
|
1838
|
+
transient: transientStatuses.has(response.status) && !longProviderCooldown,
|
|
1839
|
+
code: providerError.code || parsed?.error?.code || parsed?.code,
|
|
1840
|
+
reset_seconds: providerError.resetSeconds,
|
|
1841
|
+
retry_after_ms: retryAfterMs,
|
|
1842
|
+
attempts: attempt,
|
|
1843
|
+
max_attempts: maxAttempts,
|
|
1844
|
+
request_id: response.headers.get("x-request-id") || response.headers.get("request-id"),
|
|
1845
|
+
cf_ray: response.headers.get("cf-ray"),
|
|
1846
|
+
started_at: startedAt,
|
|
1847
|
+
finished_at: new Date().toISOString(),
|
|
1848
|
+
base_url: baseUrl,
|
|
1849
|
+
model: payload.model,
|
|
1850
|
+
detail: providerError.message || parsed?.error?.message || parsed?.error || bodyText.slice(0, 400),
|
|
1851
|
+
};
|
|
1852
|
+
}
|
|
1853
|
+
|
|
1854
|
+
async function main() {
|
|
1855
|
+
let lastReport = null;
|
|
1856
|
+
for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
|
|
1857
|
+
try {
|
|
1858
|
+
lastReport = await requestOnce(attempt);
|
|
1859
|
+
} catch (error) {
|
|
1860
|
+
lastReport = {
|
|
1861
|
+
ok: false,
|
|
1862
|
+
status: null,
|
|
1863
|
+
transient: true,
|
|
1864
|
+
attempts: attempt,
|
|
1865
|
+
max_attempts: maxAttempts,
|
|
1866
|
+
started_at: startedAt,
|
|
1867
|
+
finished_at: new Date().toISOString(),
|
|
1868
|
+
base_url: baseUrl,
|
|
1869
|
+
model: payload.model,
|
|
1870
|
+
error: error instanceof Error ? error.message : String(error),
|
|
1871
|
+
};
|
|
1872
|
+
}
|
|
1873
|
+
|
|
1874
|
+
writeReport(lastReport);
|
|
1875
|
+
if (lastReport.ok) return;
|
|
1876
|
+
if (!lastReport.transient) process.exit(1);
|
|
1877
|
+
if (attempt < maxAttempts) {
|
|
1878
|
+
await sleep(baseDelayMs * attempt);
|
|
1879
|
+
}
|
|
1880
|
+
}
|
|
1881
|
+
|
|
1882
|
+
if (lastReport && shouldContinueAfterFailure(lastReport)) {
|
|
1883
|
+
lastReport.warning = "Transient API smoke failure after retries; continuing so the CLI retry/recovery path can handle the real request.";
|
|
1884
|
+
writeReport(lastReport);
|
|
1885
|
+
return;
|
|
1886
|
+
}
|
|
1887
|
+
process.exit(1);
|
|
1888
|
+
}
|
|
1889
|
+
|
|
1890
|
+
void main();
|
|
1891
|
+
""".strip()
|
|
1892
|
+
return node_script + "\\n"
|
|
1893
|
+
|
|
1894
|
+
def _build_api_smoke_command(self) -> str:
|
|
1895
|
+
smoke_payload = json.dumps({
|
|
1896
|
+
"model": self._model_name or "gpt-5.3-codex",
|
|
1897
|
+
"messages": [{"role": "user", "content": "Reply with exactly ok."}],
|
|
1898
|
+
"max_tokens": 8,
|
|
1899
|
+
"stream": False,
|
|
1900
|
+
})
|
|
1901
|
+
return (
|
|
1902
|
+
f"XENO_API_SMOKE_OUTPUT=/logs/agent/api-smoke.json "
|
|
1903
|
+
f"XENO_API_SMOKE_PAYLOAD={shlex.quote(smoke_payload)} "
|
|
1904
|
+
"node /installed-agent/xeno-api-smoke.js"
|
|
1905
|
+
)
|
|
1906
|
+
|
|
1907
|
+
def _build_runner_script(self, required_output_paths: list[str]) -> str:
|
|
1908
|
+
command_parts = [
|
|
1909
|
+
"xeno",
|
|
1910
|
+
"run",
|
|
1911
|
+
"--mode",
|
|
1912
|
+
"agent",
|
|
1913
|
+
"--json",
|
|
1914
|
+
"-y",
|
|
1915
|
+
"--bypass-permissions",
|
|
1916
|
+
]
|
|
1917
|
+
if self._model_name:
|
|
1918
|
+
command_parts.extend(["--model", self._model_name])
|
|
1919
|
+
if self._base_url:
|
|
1920
|
+
command_parts.extend(["--base-url", self._base_url])
|
|
1921
|
+
if self._delegate:
|
|
1922
|
+
command_parts.append("--delegate")
|
|
1923
|
+
if self._max_iterations is not None:
|
|
1924
|
+
command_parts.extend(["--max-iterations", str(self._max_iterations)])
|
|
1925
|
+
if self._max_tokens is not None:
|
|
1926
|
+
command_parts.extend(["--max-tokens", str(self._max_tokens)])
|
|
1927
|
+
required_paths_env = ""
|
|
1928
|
+
if required_output_paths:
|
|
1929
|
+
required_paths_env = f"export XENO_REQUIRED_OUTPUT_PATHS_JSON={shlex.quote(json.dumps(required_output_paths))}\\n"
|
|
1930
|
+
command_parts.append("$(cat /installed-agent/xeno-prompt.txt)")
|
|
1931
|
+
escaped = " ".join(shlex.quote(part) for part in command_parts)
|
|
1932
|
+
escaped = escaped.replace("'$(cat /installed-agent/xeno-prompt.txt)'", '"$(cat /installed-agent/xeno-prompt.txt)"')
|
|
1933
|
+
smoke_command = self._build_api_smoke_command()
|
|
1934
|
+
return f"""#!/bin/bash
|
|
1935
|
+
set -uo pipefail
|
|
1936
|
+
mkdir -p /logs/agent /logs/artifacts/xeno-audit /tmp/xeno-terminal-bench
|
|
1937
|
+
rm -f /logs/agent/xeno.txt /logs/agent/api-smoke.json
|
|
1938
|
+
rm -f /logs/artifacts/xeno-audit/*.jsonl 2>/dev/null || true
|
|
1939
|
+
|
|
1940
|
+
copy_xeno_audit() {{
|
|
1941
|
+
find /app -maxdepth 6 -path '*/.xeno/audit/*.jsonl' -type f -exec cp -f {{}} /logs/artifacts/xeno-audit/ \\\\; 2>/dev/null || true
|
|
1942
|
+
}}
|
|
1943
|
+
|
|
1944
|
+
(while true; do
|
|
1945
|
+
copy_xeno_audit
|
|
1946
|
+
sleep 2
|
|
1947
|
+
done) &
|
|
1948
|
+
sync_pid=$!
|
|
1949
|
+
|
|
1950
|
+
cleanup() {{
|
|
1951
|
+
kill "$sync_pid" >/dev/null 2>&1 || true
|
|
1952
|
+
copy_xeno_audit
|
|
1953
|
+
}}
|
|
1954
|
+
trap cleanup EXIT
|
|
1955
|
+
|
|
1956
|
+
if {smoke_command}; then
|
|
1957
|
+
{required_paths_env}set +e
|
|
1958
|
+
xeno_agent_timeout_sec="\${{XENO_EXTERNAL_AGENT_TIMEOUT_SEC:-0}}"
|
|
1959
|
+
if command -v timeout >/dev/null 2>&1 && [ "$xeno_agent_timeout_sec" -gt 0 ] 2>/dev/null; then
|
|
1960
|
+
timeout --kill-after=15s "\${{xeno_agent_timeout_sec}}s" {escaped} 2>&1 </dev/null | stdbuf -oL tee /logs/agent/xeno.txt
|
|
1961
|
+
else
|
|
1962
|
+
{escaped} 2>&1 </dev/null | stdbuf -oL tee /logs/agent/xeno.txt
|
|
1963
|
+
fi
|
|
1964
|
+
xeno_status=\${{PIPESTATUS[0]}}
|
|
1965
|
+
set -e
|
|
1966
|
+
if [ "$xeno_status" -eq 124 ]; then
|
|
1967
|
+
echo "XENO_AGENT_TIMEOUT_EXPIRED after $xeno_agent_timeout_sec seconds"
|
|
1968
|
+
fi
|
|
1969
|
+
if [ "$xeno_status" -ne 0 ]; then
|
|
1970
|
+
echo "XENO_EXIT_STATUS=$xeno_status"
|
|
1971
|
+
fi
|
|
1972
|
+
exit "$xeno_status"
|
|
1973
|
+
else
|
|
1974
|
+
smoke_status=$?
|
|
1975
|
+
echo "XENO_API_SMOKE_FAILED status=$smoke_status"
|
|
1976
|
+
cat /logs/agent/api-smoke.json 2>/dev/null || true
|
|
1977
|
+
exit "$smoke_status"
|
|
1978
|
+
fi
|
|
1979
|
+
"""
|
|
1980
|
+
|
|
1981
|
+
def _run_agent_commands(self, instruction: str) -> list[TerminalCommand]:
|
|
1982
|
+
return [
|
|
1983
|
+
TerminalCommand(
|
|
1984
|
+
command="chmod +x /installed-agent/xeno-runner.sh && /installed-agent/xeno-runner.sh",
|
|
1985
|
+
min_timeout_sec=0.0,
|
|
1986
|
+
max_timeout_sec=float("inf"),
|
|
1987
|
+
block=True,
|
|
1988
|
+
append_enter=True,
|
|
1989
|
+
),
|
|
1990
|
+
]
|
|
1991
|
+
`,rx=`#!/bin/bash
|
|
1992
|
+
set -euo pipefail
|
|
1993
|
+
|
|
1994
|
+
export DEBIAN_FRONTEND="\${DEBIAN_FRONTEND:-noninteractive}"
|
|
1995
|
+
|
|
1996
|
+
xeno_with_timeout() {
|
|
1997
|
+
if command -v timeout >/dev/null 2>&1; then
|
|
1998
|
+
timeout 240s "$@"
|
|
1999
|
+
else
|
|
2000
|
+
"$@"
|
|
2001
|
+
fi
|
|
2002
|
+
}
|
|
2003
|
+
|
|
2004
|
+
xeno_retry() {
|
|
2005
|
+
local attempt
|
|
2006
|
+
for attempt in 1 2 3; do
|
|
2007
|
+
if xeno_with_timeout "$@"; then
|
|
2008
|
+
return 0
|
|
2009
|
+
fi
|
|
2010
|
+
sleep $((attempt * 2))
|
|
2011
|
+
done
|
|
2012
|
+
return 1
|
|
2013
|
+
}
|
|
2014
|
+
|
|
2015
|
+
xeno_has() {
|
|
2016
|
+
command -v "$1" >/dev/null 2>&1
|
|
2017
|
+
}
|
|
2018
|
+
|
|
2019
|
+
xeno_add_package() {
|
|
2020
|
+
case " $missing_packages " in
|
|
2021
|
+
*" $1 "*) ;;
|
|
2022
|
+
*) missing_packages="$missing_packages $1" ;;
|
|
2023
|
+
esac
|
|
2024
|
+
}
|
|
2025
|
+
|
|
2026
|
+
xeno_apt_update_best_effort() {
|
|
2027
|
+
local attempt
|
|
2028
|
+
for attempt in 1 2 3; do
|
|
2029
|
+
if xeno_with_timeout apt-get update; then
|
|
2030
|
+
return 0
|
|
2031
|
+
fi
|
|
2032
|
+
echo "warning: apt-get update failed on attempt $attempt" >&2
|
|
2033
|
+
sleep $((attempt * 2))
|
|
2034
|
+
done
|
|
2035
|
+
echo "warning: apt-get update failed; continuing with currently available package metadata" >&2
|
|
2036
|
+
return 1
|
|
2037
|
+
}
|
|
2038
|
+
|
|
2039
|
+
xeno_node_ok() {
|
|
2040
|
+
command -v node >/dev/null 2>&1 &&
|
|
2041
|
+
command -v npm >/dev/null 2>&1 &&
|
|
2042
|
+
node -e 'const major = Number(process.versions.node.split(".")[0]); process.exit(major >= 20 ? 0 : 1);' >/dev/null 2>&1
|
|
2043
|
+
}
|
|
2044
|
+
|
|
2045
|
+
missing_packages=""
|
|
2046
|
+
xeno_has curl || xeno_add_package curl
|
|
2047
|
+
xeno_has git || xeno_add_package git
|
|
2048
|
+
xeno_has rg || xeno_add_package ripgrep
|
|
2049
|
+
xeno_has xz || xeno_add_package xz-utils
|
|
2050
|
+
xeno_has ssh || xeno_add_package openssh-client
|
|
2051
|
+
xeno_has nc || xeno_add_package netcat-openbsd
|
|
2052
|
+
xeno_has ss || xeno_add_package iproute2
|
|
2053
|
+
xeno_has ps || xeno_add_package procps
|
|
2054
|
+
xeno_has file || xeno_add_package file
|
|
2055
|
+
xeno_has xxd || xeno_add_package xxd
|
|
2056
|
+
xeno_has jq || xeno_add_package jq
|
|
2057
|
+
xeno_has python3 || xeno_add_package python3-minimal
|
|
2058
|
+
if ! xeno_node_ok; then
|
|
2059
|
+
xeno_add_package libstdc++6
|
|
2060
|
+
fi
|
|
2061
|
+
if xeno_has python3; then
|
|
2062
|
+
python3 -m pip --version >/dev/null 2>&1 || xeno_add_package python3-pip
|
|
2063
|
+
python3 -c 'import venv' >/dev/null 2>&1 || xeno_add_package python3-venv
|
|
2064
|
+
else
|
|
2065
|
+
xeno_add_package python3-pip
|
|
2066
|
+
xeno_add_package python3-venv
|
|
2067
|
+
fi
|
|
2068
|
+
[ -s /etc/ssl/certs/ca-certificates.crt ] || xeno_add_package ca-certificates
|
|
2069
|
+
|
|
2070
|
+
xeno_install_packages() {
|
|
2071
|
+
[ "$#" -gt 0 ] || return 0
|
|
2072
|
+
xeno_apt_update_best_effort || true
|
|
2073
|
+
if ! xeno_with_timeout apt-get install -y --no-install-recommends "$@"; then
|
|
2074
|
+
echo "warning: bulk package install failed; retrying packages individually" >&2
|
|
2075
|
+
local package_name
|
|
2076
|
+
for package_name in "$@"; do
|
|
2077
|
+
xeno_with_timeout apt-get install -y --no-install-recommends "$package_name" || {
|
|
2078
|
+
echo "warning: could not install setup package: $package_name" >&2
|
|
2079
|
+
}
|
|
2080
|
+
done
|
|
2081
|
+
fi
|
|
2082
|
+
}
|
|
2083
|
+
|
|
2084
|
+
if [ -n "$missing_packages" ]; then
|
|
2085
|
+
# Keep setup lean: install only the tools the CLI needs immediately. Heavier
|
|
2086
|
+
# terminal helpers are available through xeno-toolbox-install during the task.
|
|
2087
|
+
xeno_install_packages ca-certificates $missing_packages
|
|
2088
|
+
fi
|
|
2089
|
+
|
|
2090
|
+
cat >/usr/local/bin/xeno-toolbox-install <<'__XENO_TOOLBOX_INSTALL__'
|
|
2091
|
+
#!/bin/bash
|
|
2092
|
+
set -euo pipefail
|
|
2093
|
+
export DEBIAN_FRONTEND="\${DEBIAN_FRONTEND:-noninteractive}"
|
|
2094
|
+
|
|
2095
|
+
xeno_with_timeout() {
|
|
2096
|
+
if command -v timeout >/dev/null 2>&1; then
|
|
2097
|
+
timeout 240s "$@"
|
|
2098
|
+
else
|
|
2099
|
+
"$@"
|
|
2100
|
+
fi
|
|
2101
|
+
}
|
|
2102
|
+
|
|
2103
|
+
xeno_package_candidates() {
|
|
2104
|
+
case "$1" in
|
|
2105
|
+
7z|7zz|7zip) echo "7zip p7zip-full p7zip" ;;
|
|
2106
|
+
bsdtar) echo "libarchive-tools" ;;
|
|
2107
|
+
nc|netcat) echo "netcat-openbsd" ;;
|
|
2108
|
+
ssh) echo "openssh-client" ;;
|
|
2109
|
+
sshpass) echo "sshpass" ;;
|
|
2110
|
+
ss) echo "iproute2" ;;
|
|
2111
|
+
lsof) echo "lsof" ;;
|
|
2112
|
+
fuser|pkill) echo "psmisc procps" ;;
|
|
2113
|
+
expect) echo "expect" ;;
|
|
2114
|
+
telnet) echo "telnet" ;;
|
|
2115
|
+
socat) echo "socat" ;;
|
|
2116
|
+
modprobe) echo "kmod" ;;
|
|
2117
|
+
pip|pip3) echo "python3-pip python3-venv" ;;
|
|
2118
|
+
pexpect|python3-pexpect) echo "python3-pexpect" ;;
|
|
2119
|
+
lzma-perl|compress-raw-lzma) echo "libcompress-raw-lzma-perl" ;;
|
|
2120
|
+
*) echo "$1" ;;
|
|
2121
|
+
esac
|
|
2122
|
+
}
|
|
2123
|
+
|
|
2124
|
+
if [ "$#" -eq 0 ]; then
|
|
2125
|
+
echo "usage: xeno-toolbox-install <tool-or-package> [more...]" >&2
|
|
2126
|
+
exit 2
|
|
2127
|
+
fi
|
|
2128
|
+
|
|
2129
|
+
packages=""
|
|
2130
|
+
for requested in "$@"; do
|
|
2131
|
+
for package_name in $(xeno_package_candidates "$requested"); do
|
|
2132
|
+
case " $packages " in
|
|
2133
|
+
*" $package_name "*) ;;
|
|
2134
|
+
*) packages="$packages $package_name" ;;
|
|
2135
|
+
esac
|
|
2136
|
+
done
|
|
2137
|
+
done
|
|
2138
|
+
|
|
2139
|
+
xeno_with_timeout apt-get update || true
|
|
2140
|
+
xeno_with_timeout apt-get install -y --no-install-recommends $packages
|
|
2141
|
+
__XENO_TOOLBOX_INSTALL__
|
|
2142
|
+
chmod +x /usr/local/bin/xeno-toolbox-install
|
|
2143
|
+
|
|
2144
|
+
if ! xeno_node_ok; then
|
|
2145
|
+
if ! xeno_has curl || ! xeno_has xz; then
|
|
2146
|
+
xeno_apt_update_best_effort || true
|
|
2147
|
+
xeno_with_timeout apt-get install -y --no-install-recommends ca-certificates curl xz-utils || true
|
|
2148
|
+
fi
|
|
2149
|
+
if ! xeno_has curl || ! xeno_has xz; then
|
|
2150
|
+
echo "fatal: curl and xz are required to bootstrap Node.js, and package installation did not provide them" >&2
|
|
2151
|
+
exit 1
|
|
2152
|
+
fi
|
|
2153
|
+
|
|
2154
|
+
arch="$(uname -m)"
|
|
2155
|
+
case "$arch" in
|
|
2156
|
+
x86_64|amd64) node_arch="x64" ;;
|
|
2157
|
+
aarch64|arm64) node_arch="arm64" ;;
|
|
2158
|
+
*) echo "unsupported architecture for Node bootstrap: $arch" >&2; exit 1 ;;
|
|
2159
|
+
esac
|
|
2160
|
+
|
|
2161
|
+
node_shasums="/tmp/xeno-node-shasums.txt"
|
|
2162
|
+
if [ -n "\${XENO_NODE_DIST_BASE:-}" ]; then
|
|
2163
|
+
node_dist_bases="$XENO_NODE_DIST_BASE"
|
|
2164
|
+
else
|
|
2165
|
+
node_dist_bases="https://nodejs.org/dist/latest-v${Kk}.x https://nodejs.org/dist/latest-v22.x https://nodejs.org/dist/latest-v20.x"
|
|
2166
|
+
fi
|
|
2167
|
+
|
|
2168
|
+
node_bootstrap_success=0
|
|
2169
|
+
for node_dist_base in $node_dist_bases; do
|
|
2170
|
+
echo "Attempting Node bootstrap from $node_dist_base" >&2
|
|
2171
|
+
rm -f "$node_shasums"
|
|
2172
|
+
if ! xeno_retry curl -fsSL "$node_dist_base/SHASUMS256.txt" -o "$node_shasums"; then
|
|
2173
|
+
echo "warning: could not fetch Node shasums from $node_dist_base" >&2
|
|
2174
|
+
continue
|
|
2175
|
+
fi
|
|
2176
|
+
|
|
2177
|
+
node_tarball="$(awk -v suffix="linux-$node_arch.tar.xz" '$2 ~ suffix "$" { print $2; exit }' "$node_shasums")"
|
|
2178
|
+
if [ -z "$node_tarball" ]; then
|
|
2179
|
+
echo "warning: unable to find Node tarball for linux-$node_arch in $node_dist_base" >&2
|
|
2180
|
+
continue
|
|
2181
|
+
fi
|
|
2182
|
+
|
|
2183
|
+
if ! xeno_retry curl -fsSL "$node_dist_base/$node_tarball" -o "/tmp/$node_tarball"; then
|
|
2184
|
+
echo "warning: could not download $node_tarball from $node_dist_base" >&2
|
|
2185
|
+
continue
|
|
2186
|
+
fi
|
|
2187
|
+
|
|
2188
|
+
if ! (cd /tmp && grep " $node_tarball$" "$node_shasums" | sha256sum -c -); then
|
|
2189
|
+
echo "warning: checksum failed for $node_tarball from $node_dist_base" >&2
|
|
2190
|
+
continue
|
|
2191
|
+
fi
|
|
2192
|
+
|
|
2193
|
+
rm -rf /opt/xeno-node
|
|
2194
|
+
mkdir -p /opt/xeno-node
|
|
2195
|
+
tar -xJf "/tmp/$node_tarball" -C /opt/xeno-node --strip-components=1
|
|
2196
|
+
ln -sf /opt/xeno-node/bin/node /usr/local/bin/node
|
|
2197
|
+
ln -sf /opt/xeno-node/bin/npm /usr/local/bin/npm
|
|
2198
|
+
ln -sf /opt/xeno-node/bin/npx /usr/local/bin/npx
|
|
2199
|
+
ln -sf /opt/xeno-node/bin/node /usr/bin/node
|
|
2200
|
+
ln -sf /opt/xeno-node/bin/npm /usr/bin/npm
|
|
2201
|
+
ln -sf /opt/xeno-node/bin/npx /usr/bin/npx
|
|
2202
|
+
export PATH="/opt/xeno-node/bin:/usr/local/bin:/usr/bin:$PATH"
|
|
2203
|
+
if xeno_node_ok; then
|
|
2204
|
+
node_bootstrap_success=1
|
|
2205
|
+
break
|
|
2206
|
+
fi
|
|
2207
|
+
echo "warning: bootstrapped Node from $node_dist_base but node/npm did not pass validation" >&2
|
|
2208
|
+
done
|
|
2209
|
+
|
|
2210
|
+
if [ "$node_bootstrap_success" -ne 1 ]; then
|
|
2211
|
+
echo "fatal: unable to bootstrap Node.js >=20 with npm for Xeno CLI" >&2
|
|
2212
|
+
exit 1
|
|
2213
|
+
fi
|
|
2214
|
+
fi
|
|
2215
|
+
|
|
2216
|
+
xeno_node_ok || {
|
|
2217
|
+
echo "fatal: node/npm validation failed after setup" >&2
|
|
2218
|
+
command -v node >/dev/null 2>&1 && node --version >&2 || true
|
|
2219
|
+
command -v npm >/dev/null 2>&1 && npm --version >&2 || true
|
|
2220
|
+
exit 1
|
|
2221
|
+
}
|
|
2222
|
+
git --version >/dev/null || true
|
|
2223
|
+
rg --version >/dev/null || true
|
|
2224
|
+
node --version
|
|
2225
|
+
npm --version
|
|
2226
|
+
if [ -n "\${XENO_TERMINAL_BENCH_PACKAGE_SHA256:-}" ]; then
|
|
2227
|
+
actual_sha="$(sha256sum /installed-agent/xeno-agent-cli.tgz | awk '{print $1}')"
|
|
2228
|
+
if [ "$actual_sha" != "$XENO_TERMINAL_BENCH_PACKAGE_SHA256" ]; then
|
|
2229
|
+
echo "xeno-agent-cli.tgz sha256 mismatch: expected $XENO_TERMINAL_BENCH_PACKAGE_SHA256 got $actual_sha" >&2
|
|
2230
|
+
exit 1
|
|
2231
|
+
fi
|
|
2232
|
+
fi
|
|
2233
|
+
mkdir -p /tmp/xeno-terminal-bench
|
|
2234
|
+
printf 'package=/installed-agent/xeno-agent-cli.tgz
|
|
2235
|
+
sha256=%s
|
|
2236
|
+
version=%s
|
|
2237
|
+
git_sha=%s
|
|
2238
|
+
' "\${XENO_TERMINAL_BENCH_PACKAGE_SHA256:-unknown}" "\${XENO_TERMINAL_BENCH_PACKAGE_VERSION:-unknown}" "\${XENO_TERMINAL_BENCH_PACKAGE_GIT_SHA:-unknown}" >/tmp/xeno-terminal-bench/package-info.txt
|
|
2239
|
+
export NPM_CONFIG_UPDATE_NOTIFIER=false
|
|
2240
|
+
npm install -g /installed-agent/xeno-agent-cli.tgz
|
|
2241
|
+
npm_global_bin="$(npm prefix -g)/bin"
|
|
2242
|
+
for bin in xeno xeno-agent xeno-code; do
|
|
2243
|
+
if [ -x "$npm_global_bin/$bin" ]; then
|
|
2244
|
+
ln -sf "$npm_global_bin/$bin" "/usr/local/bin/$bin"
|
|
2245
|
+
fi
|
|
2246
|
+
done
|
|
2247
|
+
command -v xeno
|
|
2248
|
+
xeno --version
|
|
2249
|
+
`;function ox(t){let e=n=>String(n).padStart(2,"0");return[t.getFullYear(),e(t.getMonth()+1),e(t.getDate()),"-",e(t.getHours()),e(t.getMinutes()),e(t.getSeconds())].join("")}function ix(t){return(t??[]).map(e=>e.trim()).filter(e=>e.length>0)}function aa(t,e,n=0){let s=process.env[t],r=s?Number.parseInt(s,10):Number.NaN;return Number.isFinite(r)?Math.max(n,Math.floor(r)):e}function jd(t){return Math.max(1,t/ex).toFixed(3).replace(/\.?0+$/u,"")}function Vd(){return process.platform==="win32","npm"}function ax(t){return t.length===0?'""':/^[a-zA-Z0-9_./:=\\-]+$/.test(t)?t:JSON.stringify(t)}function lx(t){return t.length===0?'""':/[ \t"&()^<>|]/.test(t)?`"${t.replace(/"/g,'\\"')}"`:t}function ao(t){return dn(t,["--version"],{stdio:"ignore",timeout:1e4}).status===0}function dn(t,e,n){if(process.platform==="win32"){let s=process.env.ComSpec||"cmd.exe",r=[t,...e].map(lx).join(" ");return la(s,["/d","/s","/c",r],{...n,encoding:"utf-8",shell:!1})}return la(t,e,{...n,encoding:"utf-8",shell:!1})}function ep(){if(ao("uv"))return{command:"uv",args:[],display:"uv"};let t=["python","py"];for(let e of t)if(dn(e,["-m","uv","--version"],{stdio:"ignore",timeout:1e4}).status===0)return{command:e,args:["-m","uv"],display:`${e} -m uv`}}function fa(){if(ao("harbor"))return{command:"harbor",args:[],display:"harbor"}}function cx(t,e){let n=st(t);for(;;){if(e(n))return n;let s=ma(n);if(s===n)return;n=s}}function gs(t){return cx(t,e=>Qt(ct(e,"apps","xeno-agent-cli","package.json")))}function ux(t){return Qt(ct(t,"pyproject.toml"))&&Qt(ct(t,"terminal_bench"))}function tp(t,e){let n=gs(t),s=[e,process.env.XENO_TERMINAL_BENCH_PATH,st(t,"terminal-bench"),st(t,"..","terminal-bench"),st(t,"..","benchmarks","terminal-bench"),n?st(n,"..","benchmarks","terminal-bench"):void 0].filter(r=>typeof r=="string");for(let r of s){let o=st(r);if(ux(o))return o}}function dx(t){let e=t?.trim().toLowerCase();if(!e||e==="auto")return"auto";if(e==="harbor")return"harbor";if(e==="legacy"||e==="terminal-bench"||e==="tb")return"legacy";throw new Error(`Invalid Terminal-Bench runner: ${t}. Expected auto, harbor, or legacy.`)}function px(t,e){let n=dx(e.runner);return n!=="auto"?n:e.terminalBenchPath?.trim()?"legacy":fa()?"harbor":tp(t,e.terminalBenchPath)?"legacy":"harbor"}function mx(t){let e=t?.trim();if(!e)return Zd;let n=e.match(/^([^=@]+)==(.+)$/);return n?.[1]&&n[2]?`${n[1]}@${n[2]}`:e}function fx(t,e){if(e)return{path:st(e)};let n=process.env.XENO_TERMINAL_BENCH_DATASET_PATH;if(n)return{path:st(n)};let s=gs(t),r=[st(t,"..","benchmarks","terminal-bench-datasets","datasets","aider_polyglot"),s?st(s,"..","benchmarks","terminal-bench-datasets","datasets","aider_polyglot"):void 0].filter(o=>typeof o=="string");for(let o of r)if(Qt(o))return{path:o,warning:`No dataset path provided; defaulting to local smoke dataset at ${o}.`};return{}}function hs(t){return Uk(t,{recursive:!0}),t}function ua(t){return t.replace(/\r\n/g,`
|
|
2250
|
+
`).replace(/\r/g,`
|
|
2251
|
+
`)}function hx(t,e){let n=gs(e);if(!n)throw new Error("Could not locate the xeno-agent-cli workspace from the current directory. Run this command from the repo checkout or pass --package-tarball.");let s=ct(n,"apps","xeno-agent-cli");hs(t);let r=[{label:"SDK",args:["run","build:sdk"]},{label:"CLI",args:["run","build:cli"]}];for(let l of r){let c=dn(Vd(),[...l.args],{cwd:n,timeout:6e5});if(c.status!==0)throw new Error(`Failed to build the local XENO ${l.label} before packaging for Terminal-Bench.
|
|
2252
|
+
`+(c.stderr||c.stdout||`${l.args.join(" ")} failed without output.`))}let o=dn(Vd(),["pack","--pack-destination",t],{cwd:s,timeout:600*1e3});if(o.status!==0)throw new Error(`Failed to package the local XENO CLI for Terminal-Bench.
|
|
2253
|
+
`+(o.stderr||o.stdout||"npm pack failed without output."));let a=jk(t).filter(l=>l.endsWith(".tgz")).sort().at(-1);if(!a)throw new Error("npm pack completed but no tarball was produced.");return ct(t,a)}function gx(t){let e=Dk("sha256");return e.update(da(t)),e.digest("hex")}function bx(t,e){let n=st(t);if(!Qt(n))throw new Error(`Terminal-Bench package tarball not found: ${n}`);if(!Vk(n).isFile())throw new Error(`Terminal-Bench package tarball must be a file: ${n}`);if(!n.toLowerCase().endsWith(".tgz"))throw new Error(`Terminal-Bench package tarball must be a .tgz file: ${n}`);let s=st(e,pa(n));return n!==s&&Fk(n,s),s}function yx(t){return pa(t).match(/-(\d+\.\d+\.\d+(?:[-+][A-Za-z0-9.-]+)?)\.tgz$/i)?.[1]}function wx(t){let e=gs(t);if(e)try{let n=JSON.parse(da(ct(e,"apps","xeno-agent-cli","package.json"),"utf-8"));return typeof n.version=="string"&&n.version.trim().length>0?n.version.trim():void 0}catch{return}}function vx(t){if(process.env.XENO_ALLOW_STALE_BENCH_PACKAGE==="1"||!t.expectedVersion||!t.packageTarballVersion||t.packageTarballVersion===t.expectedVersion)return;let e=t.explicitTarball?"explicit --package-tarball":"local npm pack";throw new Error(`Refusing stale Terminal-Bench XENO package from ${e}: ${t.packageTarballPath} is version ${t.packageTarballVersion}, but the current workspace CLI is ${t.expectedVersion}. Build/package the current CLI or set XENO_ALLOW_STALE_BENCH_PACKAGE=1 only for intentional historical comparisons.`)}function Sx(t){let e=gs(t);if(!e||!ao("git"))return;let n=dn("git",["rev-parse","--short=12","HEAD"],{cwd:e,stdio:"pipe",timeout:1e4}),s=n.status===0?n.stdout.trim():"";return s.length>0?s:void 0}function kx(){if(!ao("docker"))throw new Error("Docker is required to run Terminal-Bench tasks.");let t=dn("docker",["info"],{stdio:"pipe",timeout:3e4});if(t.status===0)return;let e=(t.stderr||t.stdout||"").trim();throw/daemon is not running|error during connect|cannot connect|docker desktop is not running/i.test(e)?new Error(`Docker is installed but the daemon is not running. Start Docker Desktop or dockerd and retry.
|
|
2254
|
+
`+(e||"docker info failed.")):new Error(`Docker is installed but not ready for Terminal-Bench.
|
|
2255
|
+
`+(e||"docker info failed."))}function qd(){let t=dn("docker",["network","ls","--format","{{.Name}}"],{stdio:"pipe",timeout:3e4});return t.status!==0?[]:t.stdout.split(/\r?\n/).map(e=>e.trim()).filter(e=>e.length>0)}function xx(t){if(!t)return;let e=qd();if(e.length<tx)return;let n=dn("docker",["network","prune","-f"],{stdio:"pipe",timeout:12e4});if(n.status!==0)throw new Error("Docker has many networks and unused-network pruning failed before the benchmark launch.\nThis can cause `all predefined address pools have been fully subnetted` during Harbor/Terminal-Bench runs.\n"+(n.stderr||n.stdout||"docker network prune failed without output."));let s=qd();s.length<e.length&&process.stderr.write(`[docker] pruned unused Docker networks before benchmark launch (${e.length} -> ${s.length}).
|
|
2256
|
+
`)}function Px(t){hs(t);let e=ct(t,`${Hd}.py`),n=ct(t,"xeno-code-setup.sh");return sr(e,ua(sx),"utf-8"),sr(n,ua(rx),"utf-8"),{adapterDir:t,modulePath:e,setupScriptPath:n}}function Tx(t,e){hs(t);let n=gs(e);if(!n)throw new Error("Could not locate the xeno-agent-cli workspace from the current directory. Run this command from the repo checkout or pass --package-tarball.");let s=ct(n,"scripts","terminal-bench",`${ca}.py`);if(!Qt(s))throw new Error(`Harbor agent adapter source not found: ${s}`);let r=ct(t,`${ca}.py`);return sr(r,ua(da(s,"utf-8")),"utf-8"),{adapterDir:t,modulePath:r}}function np(t){let e=["Terminal-Bench run",`Run ID: ${t.runId}`,`Runner: ${t.runner}`,t.runner==="legacy"&&t.terminalBenchPath?`Terminal-Bench: ${t.terminalBenchPath}`:void 0,t.runner==="harbor"&&t.jobsDir?`Harbor jobs dir: ${t.jobsDir}`:void 0,t.datasetPath?`Dataset path: ${t.datasetPath}`:void 0,t.dataset?`Dataset: ${t.dataset}`:void 0,`Output: ${t.outputPath}`,`Package tarball: ${t.packageTarballPath}`,t.packageTarballVersion?`Package version: ${t.packageTarballVersion}`:void 0,`Package sha256: ${t.packageTarballSha256}`,`Adapter: ${t.agentImportPath}`,`Model: ${t.model}`,`Base URL: ${t.baseUrl}`,`Delegation: ${t.delegate?"enabled":"disabled"}`,t.promptTemplate?`Prompt template: ${t.promptTemplate}`:void 0,t.taskIds.length>0?`Tasks: ${t.taskIds.join(", ")}`:void 0,"","Command",t.commandString].filter(n=>typeof n=="string");return t.warnings.length>0&&e.push("","Warnings",...t.warnings.map(n=>`- ${n}`)),e.join(`
|
|
2257
|
+
`)}function _x(t){return/(?:API[_-]?KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|AUTH|JWT|PRIVATE[_-]?KEY)/i.test(t)}function Rx(t){return t.startsWith("XENO_")||zk.has(t)}function Ex(t,e){return e===void 0?e:_x(t)?Hk:e}function sp(t){let e=Object.fromEntries(Object.entries(t.env).filter(([n])=>Rx(n)).sort(([n],[s])=>n.localeCompare(s)).map(([n,s])=>[n,Ex(n,s)]));return{...t,env:e}}function rp(t){let e=st(t.cwd??process.cwd()),n=t.apiKey?.trim()||process.env.XENO_API_KEY?.trim()||Do();if(!n)throw new Error("Terminal-Bench runs require Xeno cloud credentials. Set XENO_API_KEY, pass --api-key, or sign in locally so ~/.xeno credentials are available.");let s=px(e,t),r=ix(t.taskIds),o=t.model?.trim()||Jk,i=rn({explicitBaseURL:t.baseUrl,benchmarkMode:!0}),a=t.delegate===!0,l=t.promptTemplate?st(t.promptTemplate):void 0;if(l&&!Qt(l))throw new Error(`Prompt template not found: ${l}`);let c=Number.isFinite(t.globalAgentTimeoutSec)?Math.max(1,Math.floor(t.globalAgentTimeoutSec)):Gk,u=Number.isFinite(t.globalTestTimeoutSec)?Math.max(1,Math.floor(t.globalTestTimeoutSec)):Yk,p=Number.isFinite(t.apiMaxRetries)?Math.max(0,Math.floor(t.apiMaxRetries)):zd,f=Number.isFinite(t.apiBaseDelayMs)?Math.max(50,Math.floor(t.apiBaseDelayMs)):Wd,m=Number.isFinite(t.apiMaxDelayMs)?Math.max(f,Math.floor(t.apiMaxDelayMs)):Xd,g=Number.isFinite(t.apiRetryJitterMs)?Math.max(0,Math.floor(t.apiRetryJitterMs)):Kd,b=Number.isFinite(t.apiRequestTimeoutMs)?Math.max(1e3,Math.floor(t.apiRequestTimeoutMs)):Gd,v=aa("XENO_RUN_RESTART_MAX_ATTEMPTS",Yd,0),w=aa("XENO_RUN_RESTART_BASE_DELAY_MS",Jd,100),P=Math.max(w,aa("XENO_RUN_RESTART_MAX_DELAY_MS",Qd,w)),C=Number.isFinite(t.harnessMaxRetries)?Math.max(0,Math.floor(t.harnessMaxRetries)):Qk,$=Number.isFinite(t.agentSetupTimeoutMultiplier)?Math.max(1,t.agentSetupTimeoutMultiplier):Zk,E=t.outputPath?st(t.outputPath):void 0,T=t.runId?.trim()||(s==="harbor"&&E?pa(E):ox(new Date)),I=s==="harbor"?st(E??ct(st(t.jobsDir??ct(e,".harbor-jobs")),T)):st(E??ct(e,".xeno","bench","terminal-bench",T)),re=s==="harbor"?st(t.jobsDir??ma(I)):void 0,ae=hs(ct(I,"artifacts")),N=hs(ct(ae,"package")),y=ct(ae,s==="harbor"?"harbor-agent":"terminal-bench-agent"),oe=t.packageTarballPath?bx(t.packageTarballPath,N):hx(N,e);if(!Qt(oe))throw new Error(`Terminal-Bench package tarball not found: ${oe}`);let K=gx(oe),W=yx(oe),Z=wx(e);vx({packageTarballPath:oe,packageTarballVersion:W,expectedVersion:Z,explicitTarball:!!t.packageTarballPath});let le=Sx(e);sr(ct(N,"package-metadata.json"),JSON.stringify({tarball:oe,sha256:K,version:W??null,gitSha:le??null,createdAt:new Date().toISOString()},null,2)+`
|
|
2258
|
+
`,"utf-8");let ce,X,q,Q,ye,ee,Se,me=[];if(s==="legacy"){if(ce=tp(e,t.terminalBenchPath),!ce)throw new Error("Could not find the Terminal-Bench checkout. Pass --terminal-bench-path, set XENO_TERMINAL_BENCH_PATH, or use --runner harbor.");X=t.dataset?.trim();let Ee=fx(e,t.datasetPath);if(q=X?void 0:Ee.path,Ee.warning&&me.push(Ee.warning),!X&&!q)throw new Error("Provide --dataset <name==version> or --dataset-path <path> for terminal-bench legacy runs.");if(q&&!Qt(q))throw new Error(`Terminal-Bench dataset path does not exist: ${q}`);Px(y),Q=`${Hd}:${Wk}`,Se=ce,ye=["run","tb","run","--agent-import-path",Q,"--output-path",I,"--run-id",T,"--model",o,...X?["--dataset",X]:["--dataset-path",q],...r.flatMap(pe=>["--task-id",pe]),...t.noRebuild?["--no-rebuild"]:[],...t.noCleanup?["--no-cleanup"]:[],...Number.isFinite(t.nConcurrent)?["--n-concurrent",String(Math.max(1,Math.floor(t.nConcurrent)))]:[],...Number.isFinite(t.nAttempts)?["--n-attempts",String(Math.max(1,Math.floor(t.nAttempts)))]:[],"--global-agent-timeout-sec",String(c),"--global-test-timeout-sec",String(u),"--agent-kwarg",`base_url=${i}`,"--agent-kwarg",`external_agent_timeout_sec=${String(c)}`,...a?["--agent-kwarg","delegate=True"]:[],...Number.isFinite(t.maxIterations)?["--agent-kwarg",`max_iterations=${String(Math.max(1,Math.floor(t.maxIterations)))}`]:[],...Number.isFinite(t.maxTokens)?["--agent-kwarg",`max_tokens=${String(Math.max(1,Math.floor(t.maxTokens)))}`]:[],...l?["--agent-kwarg",`prompt_template=${l}`]:[]],ee=ep()?.display??"uv"}else{if(q=t.datasetPath?st(t.datasetPath):void 0,q&&!Qt(q))throw new Error(`Harbor dataset path does not exist: ${q}`);X=q?void 0:mx(t.dataset),!t.dataset?.trim()&&!q&&me.push(`No dataset provided; defaulting to official Harbor dataset ${Zd}.`),Tx(y,e),Q=`${ca}:${Xk}`,Se=e,ye=["run","--yes","--jobs-dir",re,"--job-name",T,...q?["--path",q]:["--dataset",X],"--agent-import-path",Q,"--model",o,...Number.isFinite(t.nConcurrent)?["--n-concurrent",String(Math.max(1,Math.floor(t.nConcurrent)))]:[],...Number.isFinite(t.nAttempts)?["--n-attempts",String(Math.max(1,Math.floor(t.nAttempts)))]:[],"--max-retries",String(C),"--agent-timeout-multiplier",jd(c),"--verifier-timeout-multiplier",jd(u),"--agent-setup-timeout-multiplier",String($),...t.noCleanup?["--no-delete"]:[],...r.flatMap(Ee=>["--include-task-name",Ee]),"--agent-kwarg",`base_url=${i}`,"--agent-kwarg",`external_agent_timeout_sec=${String(c)}`,...a?["--agent-kwarg","delegate=True"]:[],...Number.isFinite(t.maxIterations)?["--agent-kwarg",`max_iterations=${String(Math.max(1,Math.floor(t.maxIterations)))}`]:[],...Number.isFinite(t.maxTokens)?["--agent-kwarg",`max_tokens=${String(Math.max(1,Math.floor(t.maxTokens)))}`]:[],...l?["--agent-kwarg",`prompt_template=${l}`]:[]],ee=fa()?.display??"harbor"}let de={...process.env,XENO_API_KEY:n,XENO_BASE_URL:i,XENO_BENCHMARK_MODE:"terminal-bench",XENO_FORCE_EXIT_AFTER_RUN:"1",XENO_ALLOW_UNSAFE_BYPASS:"1",XENO_API_MAX_RETRIES:String(p),XENO_API_BASE_DELAY_MS:String(f),XENO_API_MAX_DELAY_MS:String(m),XENO_API_RETRY_JITTER_MS:String(g),XENO_API_REQUEST_TIMEOUT_MS:String(b),XENO_RUN_RESTART_MAX_ATTEMPTS:String(v),XENO_RUN_RESTART_BASE_DELAY_MS:String(w),XENO_RUN_RESTART_MAX_DELAY_MS:String(P),XENO_TERMINAL_BENCH_PACKAGE_TARBALL:oe,XENO_TERMINAL_BENCH_PACKAGE_SHA256:K,...W?{XENO_TERMINAL_BENCH_PACKAGE_VERSION:W}:{},...le?{XENO_TERMINAL_BENCH_PACKAGE_GIT_SHA:le}:{},PYTHONIOENCODING:"utf-8",PYTHONUTF8:"1",FORCE_COLOR:"0",NO_COLOR:"1",UV_LINK_MODE:"copy",PYTHONPATH:process.env.PYTHONPATH?`${y}${qk}${process.env.PYTHONPATH}`:y};return{suite:"terminal-bench",runner:s,workingDirectory:Se,...ce?{terminalBenchPath:ce}:{},...re?{jobsDir:re}:{},...q?{datasetPath:q}:{},...X?{dataset:X}:{},outputPath:I,runId:T,packageTarballPath:oe,packageTarballSha256:K,...W?{packageTarballVersion:W}:{},...le?{packageGitSha:le}:{},adapterDir:y,agentImportPath:Q,model:o,baseUrl:i,delegate:a,...l?{promptTemplate:l}:{},taskIds:r,command:ye,commandString:[ee,...ye].map(ax).join(" "),env:de,pruneDockerNetworks:t.pruneDockerNetworks!==!1,warnings:me}}function Cx(){return process.env.XENO_TERMINAL_BENCH_SKIP_API_PREFLIGHT?.trim()==="1"}function io(t){return typeof t=="string"?t.trim():""}function op(t){return[io(t.code),io(t.detail),io(t.error)].filter(Boolean).join(" ")}function ip(t){if(typeof t.retryAfterMs=="number"&&Number.isFinite(t.retryAfterMs)&&t.retryAfterMs>0)return t.retryAfterMs;if(typeof t.resetSeconds=="number"&&Number.isFinite(t.resetSeconds)&&t.resetSeconds>0)return t.resetSeconds*1e3;let e=op(t).replace(/\\"/g,'"'),n=e.match(/"reset_seconds"\s*:\s*(\d+)/i)??e.match(/\breset_seconds\b[^\d]{0,20}(\d+)/i);if(!n)return;let s=Number.parseInt(n[1],10);return Number.isFinite(s)&&s>0?s*1e3:void 0}function fs(t){let e=[`Model: ${t.model||"unknown"}`,`Base URL: ${t.baseUrl||"unknown"}`];t.status!==void 0&&t.status!==null&&e.push(`Status: ${t.status}`),t.code&&e.push(`Code: ${t.code}`);let n=io(t.detail||t.error);n&&e.push(`Detail: ${n}`),t.requestId&&e.push(`Request ID: ${t.requestId}`),t.cfRay&&e.push(`Cloudflare Ray: ${t.cfRay}`);let s=ip(t);return s&&e.push(`Provider retry-after: ${Math.ceil(s/1e3)}s`),e.join(`
|
|
2259
|
+
`)}function Ax(t){if(t.ok)return{action:"pass"};let e=typeof t.status=="number"?t.status:void 0,n=op(t),s=n.toLowerCase(),r=ip(t),o=(t.code==="model_cooldown"||s.includes("model_cooldown"))&&r!==void 0&&r>nx,i=/usage[_ -]?limit|insufficient[_ -]?quota|quota[_ -]?exceeded|billing|payment|required|credits?|credit[_ -]?exhausted|auth[_ -]?unavailable|no auth|provider.*unavailable|model.*unavailable|token[_ -]?invalidated|invalid token/i.test(n);return e===401||e===403||e===402||s.includes("token_invalidated")?{action:"fail",reason:"auth",message:`Terminal-Bench API preflight failed before launching Harbor.
|
|
2260
|
+
${fs(t)}
|
|
2261
|
+
Refresh XENO_API_KEY or sign in again, then retry. The token value was not logged.`}:i?{action:"fail",reason:"provider-or-billing",message:`Terminal-Bench API preflight found a hard provider, quota, or billing failure before launching Harbor.
|
|
2262
|
+
${fs(t)}
|
|
2263
|
+
Fix the account/provider availability first, then rerun the benchmark.`}:o?{action:"fail",reason:"provider-cooldown",message:`Terminal-Bench API preflight found the selected model is in provider cooldown before launching Harbor.
|
|
2264
|
+
${fs(t)}
|
|
2265
|
+
Wait for the provider cooldown to expire or choose an available model before rerunning the benchmark.`}:e!==void 0&&e>=400&&e<500&&!Ud.has(e)?{action:"fail",reason:"client-error",message:`Terminal-Bench API preflight failed before launching Harbor.
|
|
2266
|
+
${fs(t)}
|
|
2267
|
+
Check the selected model, base URL, and account permissions before rerunning.`}:t.transient||e===void 0||Ud.has(e)?{action:"warn",reason:"transient",message:`Warning: Terminal-Bench API preflight hit a transient API/network failure; continuing so the CLI retry path can handle the real run.
|
|
2268
|
+
`+fs(t)}:{action:"fail",reason:"unknown",message:`Terminal-Bench API preflight failed before launching Harbor.
|
|
2269
|
+
${fs(t)}
|
|
2270
|
+
Check Xeno API connectivity and credentials before rerunning.`}}function Ix(t,e){let n=ct(t.outputPath,"artifacts","api-preflight.json");hs(ma(n)),sr(n,JSON.stringify(e,null,2))}function Mx(t){let e=Number.parseInt(t.env.XENO_API_REQUEST_TIMEOUT_MS||"",10);return Number.isFinite(e)?Math.min(Fd,Math.max(5e3,e)):Fd}function Ox(t){if(Cx())return;let e=Mx(t),n={model:t.model,messages:[{role:"user",content:"Reply with exactly ok."}],max_tokens:8,stream:!1},r=la(process.execPath,["-e",`
|
|
2271
|
+
const payload = JSON.parse(process.env.XENO_API_PREFLIGHT_PAYLOAD || "{}");
|
|
2272
|
+
const baseUrl = String(process.env.XENO_BASE_URL || "").replace(/\\/+$/, "");
|
|
2273
|
+
const apiKey = process.env.XENO_API_KEY || "";
|
|
2274
|
+
const timeoutMs = Math.max(1000, Number.parseInt(process.env.XENO_API_PREFLIGHT_TIMEOUT_MS || "60000", 10) || 60000);
|
|
2275
|
+
const maxRetryAfterMs = Math.max(0, Number.parseInt(process.env.XENO_API_MAX_RETRY_AFTER_MS || "120000", 10) || 120000);
|
|
2276
|
+
const startedAt = new Date().toISOString();
|
|
2277
|
+
const transientStatuses = new Set([408, 409, 425, 429, 500, 502, 503, 504]);
|
|
2278
|
+
|
|
2279
|
+
function extractProviderError(parsed, bodyText) {
|
|
2280
|
+
const candidates = [parsed];
|
|
2281
|
+
const nested = parsed && typeof parsed?.error?.message === "string" ? parsed.error.message : null;
|
|
2282
|
+
if (nested) {
|
|
2283
|
+
try {
|
|
2284
|
+
candidates.push(JSON.parse(nested));
|
|
2285
|
+
} catch {
|
|
2286
|
+
candidates.push({ error: { message: nested } });
|
|
2287
|
+
}
|
|
2288
|
+
}
|
|
2289
|
+
const normalizedBody = String(bodyText || "").replace(/\\\\"/g, '"');
|
|
2290
|
+
const resetMatch = normalizedBody.match(/"reset_seconds"\\s*:\\s*(\\d+)/i) || normalizedBody.match(/\\breset_seconds\\b[^\\d]{0,20}(\\d+)/i);
|
|
2291
|
+
for (const candidate of candidates) {
|
|
2292
|
+
const error = candidate?.error || candidate;
|
|
2293
|
+
if (!error) continue;
|
|
2294
|
+
const resetSeconds = Number.parseInt(String(error.reset_seconds || error.resetSeconds || ""), 10);
|
|
2295
|
+
return {
|
|
2296
|
+
code: error.code || candidate?.code,
|
|
2297
|
+
message: error.message || candidate?.message,
|
|
2298
|
+
resetSeconds: Number.isFinite(resetSeconds) && resetSeconds > 0
|
|
2299
|
+
? resetSeconds
|
|
2300
|
+
: resetMatch
|
|
2301
|
+
? Number.parseInt(resetMatch[1], 10)
|
|
2302
|
+
: undefined,
|
|
2303
|
+
};
|
|
2304
|
+
}
|
|
2305
|
+
return {
|
|
2306
|
+
code: normalizedBody.includes("model_cooldown") ? "model_cooldown" : undefined,
|
|
2307
|
+
message: undefined,
|
|
2308
|
+
resetSeconds: resetMatch ? Number.parseInt(resetMatch[1], 10) : undefined,
|
|
2309
|
+
};
|
|
2310
|
+
}
|
|
2311
|
+
|
|
2312
|
+
function finish(report) {
|
|
2313
|
+
process.stdout.write(JSON.stringify({
|
|
2314
|
+
model: payload.model,
|
|
2315
|
+
baseUrl,
|
|
2316
|
+
timeoutMs,
|
|
2317
|
+
startedAt,
|
|
2318
|
+
finishedAt: new Date().toISOString(),
|
|
2319
|
+
...report,
|
|
2320
|
+
}));
|
|
2321
|
+
}
|
|
2322
|
+
|
|
2323
|
+
(async () => {
|
|
2324
|
+
const controller = new AbortController();
|
|
2325
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
2326
|
+
try {
|
|
2327
|
+
const response = await fetch(baseUrl + "/v1/chat/completions", {
|
|
2328
|
+
method: "POST",
|
|
2329
|
+
signal: controller.signal,
|
|
2330
|
+
headers: {
|
|
2331
|
+
"Content-Type": "application/json",
|
|
2332
|
+
Authorization: "Bearer " + apiKey,
|
|
2333
|
+
"User-Agent": "XenoTerminalBenchPreflight/0.2.0",
|
|
2334
|
+
},
|
|
2335
|
+
body: JSON.stringify(payload),
|
|
2336
|
+
});
|
|
2337
|
+
const bodyText = await response.text();
|
|
2338
|
+
let parsed = null;
|
|
2339
|
+
try {
|
|
2340
|
+
parsed = JSON.parse(bodyText);
|
|
2341
|
+
} catch {
|
|
2342
|
+
parsed = null;
|
|
2343
|
+
}
|
|
2344
|
+
const providerError = extractProviderError(parsed, bodyText);
|
|
2345
|
+
const retryAfterMs = providerError.resetSeconds ? providerError.resetSeconds * 1000 : undefined;
|
|
2346
|
+
const longProviderCooldown = providerError.code === "model_cooldown" && retryAfterMs && retryAfterMs > maxRetryAfterMs;
|
|
2347
|
+
finish({
|
|
2348
|
+
ok: response.ok,
|
|
2349
|
+
status: response.status,
|
|
2350
|
+
transient: transientStatuses.has(response.status) && !longProviderCooldown,
|
|
2351
|
+
code: providerError.code || parsed?.error?.code || parsed?.code,
|
|
2352
|
+
detail: providerError.message || parsed?.error?.message || parsed?.message || parsed?.error || bodyText.slice(0, 400),
|
|
2353
|
+
retryAfterMs,
|
|
2354
|
+
resetSeconds: providerError.resetSeconds,
|
|
2355
|
+
requestId: response.headers.get("x-request-id") || response.headers.get("request-id"),
|
|
2356
|
+
cfRay: response.headers.get("cf-ray"),
|
|
2357
|
+
});
|
|
2358
|
+
} catch (error) {
|
|
2359
|
+
finish({
|
|
2360
|
+
ok: false,
|
|
2361
|
+
status: null,
|
|
2362
|
+
transient: true,
|
|
2363
|
+
error: error instanceof Error ? error.message : String(error),
|
|
2364
|
+
});
|
|
2365
|
+
} finally {
|
|
2366
|
+
clearTimeout(timer);
|
|
2367
|
+
}
|
|
2368
|
+
})().catch((error) => finish({
|
|
2369
|
+
ok: false,
|
|
2370
|
+
status: null,
|
|
2371
|
+
transient: true,
|
|
2372
|
+
error: error instanceof Error ? error.message : String(error),
|
|
2373
|
+
}));
|
|
2374
|
+
`],{cwd:t.workingDirectory,env:{...t.env,XENO_API_PREFLIGHT_PAYLOAD:JSON.stringify(n),XENO_API_PREFLIGHT_TIMEOUT_MS:String(e)},encoding:"utf-8",timeout:e+5e3,windowsHide:!0}),o;if(r.error)o={ok:!1,status:null,transient:!0,model:t.model,baseUrl:t.baseUrl,timeoutMs:e,error:r.error.message};else try{if(o=JSON.parse(r.stdout||"{}"),o.model||=t.model,o.baseUrl||=t.baseUrl,o.timeoutMs||=e,typeof o.ok!="boolean")throw new Error("missing ok field")}catch(a){o={ok:!1,status:null,transient:!0,model:t.model,baseUrl:t.baseUrl,timeoutMs:e,error:`Could not parse API preflight output: ${a instanceof Error?a.message:String(a)}`,detail:(r.stderr||r.stdout||"").slice(0,400)}}Ix(t,o);let i=Ax(o);if(i.action==="warn"){process.stderr.write(`${i.message||"Warning: Terminal-Bench API preflight was inconclusive; continuing."}
|
|
2375
|
+
`);return}if(i.action==="fail")throw new Error(i.message||"Terminal-Bench API preflight failed.")}function ap(t){Ox(t),kx(),xx(t.pruneDockerNetworks);let e=t.runner==="harbor"?fa():ep();if(!e)throw new Error(t.runner==="harbor"?"Harbor is required to run official Terminal-Bench 2.0. Install Harbor or use --runner legacy with a Terminal-Bench checkout.":"uv is required to run legacy Terminal-Bench. Install uv or use --runner harbor.");let n=dn(e.command,[...e.args,...t.command],{cwd:t.workingDirectory,env:t.env,stdio:"inherit"});return{prepared:t,exitCode:n.status??1}}On();hn();It();At();var bs={};Me(bs,eC);import*as eC from"@xeno-corporation/xeno-agent-sdk";Wt();var Zt={};cr(Zt,{shutdownBackgroundProcessesNonInteractive:()=>ha});Me(Zt,nC);import*as nC from"@xeno-corporation/xeno-agent-sdk";import{backgroundProcessManager as $x}from"@xeno-corporation/xeno-agent-sdk";var Lx=/\b(?:qemu-system(?:-[\w-]+)?|qemu-kvm|sshd?|ssh\b|python(?:3)?\s+-m\s+http\.server|python(?:3)?\s+(?:-u\s+)?(?:[^\s;&|]*\/)?(?:[\w.-]*(?:app|server|service|api|main)[\w.-]*)\.py\b|(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:dev|start|serve)|node\s+.*(?:server|app)|uvicorn|gunicorn|flask\s+run|fastapi\s+run|docker\s+run|docker\s+compose\s+up|kubectl\s+port-forward|socat\b|(?:nc|ncat|netcat)\b\s+.*(?:-[^\s]*l|--listen\b)|nginx\b|redis-server\b|postgres\b|mysqld\b|mongod\b|emulator\b|xvfb-run\b)/i;function Nx(t){return Lx.test(t.command)}function ha(t=$x){let e={stopped:[],preserved:[],failed:[]};for(let n of t.list())if(n.status==="running"){if(Nx(n)){e.preserved.push(n.id);continue}t.stop(n.id)?e.stopped.push(n.id):e.failed.push(n.id)}return e}var ga=["chat","run","cost","init","review","sessions","approved-tools","mcp","onboarding","release-notes","terminal-setup","listen","pr-comments","ctx-viz","system-prompt","bootstrap-plan","dump-manifests","trace","bench","update","completions"],ba=["--model","--api-key","--base-url","--mode","--role","--resume","--max-tokens","--max-iterations","--permission-mode","--color","--delegate","--delegate-max-total-tokens","--delegate-timeout-ms","--delegate-team","--delegate-role-precedence","--memory-context-sessions","--memory-context-tokens","--memory-context-chars","--mcp","--checkpoint","--json","--ndjson","--yes","--staged","--range","--files","--focus","--bypass-permissions","--date","--plugin-dir","--no-memory","--no-identity","--check","--dry-run","--force-global","--channel","--audit-file","--list","--replay","--iterations","--lines"],lp=["/help","/clear","/tokens","/cost","/memory","/model","/sessions","/audit","/mcp","/approved-tools","/doctor","/bug-report","/config","/plugins","/init","/review","/compact","/babysit","/ctx-viz","/onboarding","/release-notes","/terminal-setup","/listen","/pr-comments","/checkpoint","/remember"],ya=["gpt-5.5","gpt-5.4","gpt-5.3-codex","gpt-5.3-codex-spark","gpt-5.2","gpt-5.4-mini","composer-2.5","composer-2.5-fast","kimi-k2.6","kimi-k2.5","kimi-k2-thinking"];function cp(){return`# xeno bash completions
|
|
2376
|
+
# Add to ~/.bashrc:
|
|
2377
|
+
# eval "$(xeno completions bash)"
|
|
2378
|
+
|
|
2379
|
+
_xeno_completions() {
|
|
2380
|
+
local cur prev words cword
|
|
2381
|
+
_init_completion || return
|
|
2382
|
+
|
|
2383
|
+
local subcommands="${ga.join(" ")}"
|
|
2384
|
+
local flags="${ba.join(" ")}"
|
|
2385
|
+
local slash_commands="${lp.join(" ")}"
|
|
2386
|
+
local models="${ya.join(" ")}"
|
|
2387
|
+
|
|
2388
|
+
# Complete subcommands at position 1
|
|
2389
|
+
if [[ $cword -eq 1 ]]; then
|
|
2390
|
+
COMPREPLY=( $(compgen -W "$subcommands" -- "$cur") )
|
|
2391
|
+
return
|
|
2392
|
+
fi
|
|
2393
|
+
|
|
2394
|
+
# Complete flags after subcommand
|
|
2395
|
+
case "$prev" in
|
|
2396
|
+
--model|-m)
|
|
2397
|
+
COMPREPLY=( $(compgen -W "$models" -- "$cur") )
|
|
2398
|
+
return
|
|
2399
|
+
;;
|
|
2400
|
+
--mode)
|
|
2401
|
+
COMPREPLY=( $(compgen -W "agent chat" -- "$cur") )
|
|
2402
|
+
return
|
|
2403
|
+
;;
|
|
2404
|
+
--permission-mode)
|
|
2405
|
+
COMPREPLY=( $(compgen -W "default acceptEdits bypassPermissions" -- "$cur") )
|
|
2406
|
+
return
|
|
2407
|
+
;;
|
|
2408
|
+
--color)
|
|
2409
|
+
COMPREPLY=( $(compgen -W "blue green red yellow magenta cyan white" -- "$cur") )
|
|
2410
|
+
return
|
|
2411
|
+
;;
|
|
2412
|
+
--focus)
|
|
2413
|
+
COMPREPLY=( $(compgen -W "security performance" -- "$cur") )
|
|
2414
|
+
return
|
|
2415
|
+
;;
|
|
2416
|
+
--channel)
|
|
2417
|
+
COMPREPLY=( $(compgen -W "latest next" -- "$cur") )
|
|
2418
|
+
return
|
|
2419
|
+
;;
|
|
2420
|
+
completions)
|
|
2421
|
+
COMPREPLY=( $(compgen -W "bash zsh fish" -- "$cur") )
|
|
2422
|
+
return
|
|
2423
|
+
;;
|
|
2424
|
+
esac
|
|
2425
|
+
|
|
2426
|
+
# Slash commands when input starts with /
|
|
2427
|
+
if [[ "$cur" == /* ]]; then
|
|
2428
|
+
COMPREPLY=( $(compgen -W "$slash_commands" -- "$cur") )
|
|
2429
|
+
return
|
|
2430
|
+
fi
|
|
2431
|
+
|
|
2432
|
+
# Default to flags
|
|
2433
|
+
if [[ "$cur" == -* ]]; then
|
|
2434
|
+
COMPREPLY=( $(compgen -W "$flags" -- "$cur") )
|
|
2435
|
+
return
|
|
2436
|
+
fi
|
|
2437
|
+
}
|
|
2438
|
+
|
|
2439
|
+
complete -F _xeno_completions xeno
|
|
2440
|
+
`}function up(){return`#compdef xeno
|
|
2441
|
+
# xeno zsh completions
|
|
2442
|
+
# Add to ~/.zshrc:
|
|
2443
|
+
# eval "$(xeno completions zsh)"
|
|
2444
|
+
|
|
2445
|
+
_xeno() {
|
|
2446
|
+
local -a subcommands flags models shells slash_commands
|
|
2447
|
+
|
|
2448
|
+
subcommands=(
|
|
2449
|
+
${ga.map(e=>`'${e}:${pp(e)}'`).join(`
|
|
2450
|
+
`)}
|
|
2451
|
+
)
|
|
2452
|
+
|
|
2453
|
+
models=(${ya.map(e=>`'${e}'`).join(" ")})
|
|
2454
|
+
shells=('bash' 'zsh' 'fish')
|
|
2455
|
+
|
|
2456
|
+
flags=(
|
|
2457
|
+
${ba.map(e=>`'${e}'`).join(`
|
|
2458
|
+
`)}
|
|
2459
|
+
)
|
|
2460
|
+
|
|
2461
|
+
slash_commands=(
|
|
2462
|
+
${lp.map(e=>`'${e}'`).join(`
|
|
2463
|
+
`)}
|
|
2464
|
+
)
|
|
2465
|
+
|
|
2466
|
+
if (( CURRENT == 2 )); then
|
|
2467
|
+
_describe 'subcommand' subcommands
|
|
2468
|
+
return
|
|
2469
|
+
fi
|
|
2470
|
+
|
|
2471
|
+
case "\${words[2]}" in
|
|
2472
|
+
completions)
|
|
2473
|
+
if (( CURRENT == 3 )); then
|
|
2474
|
+
_describe 'shell' shells
|
|
2475
|
+
fi
|
|
2476
|
+
return
|
|
2477
|
+
;;
|
|
2478
|
+
esac
|
|
2479
|
+
|
|
2480
|
+
case "\${words[CURRENT-1]}" in
|
|
2481
|
+
--model|-m)
|
|
2482
|
+
_describe 'model' models
|
|
2483
|
+
return
|
|
2484
|
+
;;
|
|
2485
|
+
--mode)
|
|
2486
|
+
local -a modes=('agent' 'chat')
|
|
2487
|
+
_describe 'mode' modes
|
|
2488
|
+
return
|
|
2489
|
+
;;
|
|
2490
|
+
--permission-mode)
|
|
2491
|
+
local -a pmodes=('default' 'acceptEdits' 'bypassPermissions')
|
|
2492
|
+
_describe 'permission mode' pmodes
|
|
2493
|
+
return
|
|
2494
|
+
;;
|
|
2495
|
+
--color)
|
|
2496
|
+
local -a colors=('blue' 'green' 'red' 'yellow' 'magenta' 'cyan' 'white')
|
|
2497
|
+
_describe 'color' colors
|
|
2498
|
+
return
|
|
2499
|
+
;;
|
|
2500
|
+
--focus)
|
|
2501
|
+
local -a foci=('security' 'performance')
|
|
2502
|
+
_describe 'focus' foci
|
|
2503
|
+
return
|
|
2504
|
+
;;
|
|
2505
|
+
--channel)
|
|
2506
|
+
local -a channels=('latest' 'next')
|
|
2507
|
+
_describe 'channel' channels
|
|
2508
|
+
return
|
|
2509
|
+
;;
|
|
2510
|
+
esac
|
|
2511
|
+
|
|
2512
|
+
if [[ "\${words[CURRENT]}" == /* ]]; then
|
|
2513
|
+
_describe 'slash command' slash_commands
|
|
2514
|
+
return
|
|
2515
|
+
fi
|
|
2516
|
+
|
|
2517
|
+
if [[ "\${words[CURRENT]}" == -* ]]; then
|
|
2518
|
+
_describe 'flag' flags
|
|
2519
|
+
return
|
|
2520
|
+
fi
|
|
2521
|
+
}
|
|
2522
|
+
|
|
2523
|
+
compdef _xeno xeno
|
|
2524
|
+
`}function dp(){let t=["# xeno fish completions","# Run once:","# xeno completions fish | source","","# Disable file completions","complete -c xeno -f","","# Subcommands"];for(let e of ga)t.push(`complete -c xeno -n '__fish_use_subcommand' -a '${e}' -d '${pp(e)}'`);t.push("","# Completions subcommand shells");for(let e of["bash","zsh","fish"])t.push(`complete -c xeno -n '__fish_seen_subcommand_from completions' -a '${e}' -d '${e} completions'`);t.push("","# Flags");for(let e of ba){let n=e.replace(/^--/,"");t.push(`complete -c xeno -l '${n}'`)}t.push("","# Model names for --model");for(let e of ya)t.push(`complete -c xeno -n '__fish_seen_subcommand_from chat run review' -l model -xa '${e}'`);return t.push("","# Mode values"),t.push("complete -c xeno -l mode -xa 'agent chat'"),t.push("","# Permission mode values"),t.push("complete -c xeno -l permission-mode -xa 'default acceptEdits bypassPermissions'"),t.push("","# Color values"),t.push("complete -c xeno -l color -xa 'blue green red yellow magenta cyan white'"),t.push("","# Focus values"),t.push("complete -c xeno -l focus -xa 'security performance'"),t.push(""),t.join(`
|
|
2525
|
+
`)}function pp(t){switch(t){case"chat":return"Start interactive chat";case"run":return"Run a task non-interactively";case"cost":return"Show the last persisted session cost summary";case"init":return"Initialize project for AI-assisted development";case"review":return"AI code review of recent changes";case"sessions":return"Manage chat sessions";case"approved-tools":return"List or revoke remembered tool approvals";case"mcp":return"Manage configured MCP servers, prompts, and resources";case"onboarding":return"Show onboarding guidance for the current workspace";case"release-notes":return"Show current or requested release notes";case"terminal-setup":return"Install terminal Shift+Enter integration";case"listen":return"Start system dictation / voice typing";case"pr-comments":return"Fetch and render GitHub PR comments";case"ctx-viz":return"Inspect prompt, tool, and message context usage";case"system-prompt":return"Print the resolved system prompt";case"bootstrap-plan":return"Show what xeno init would scaffold";case"dump-manifests":return"Dump command, tool, plugin, and workspace manifests";case"trace":return"Inspect audit traces from workspace audit logs";case"bench":return"Run local coding-tool performance benchmarks";case"update":return"Check for updates and install the latest published CLI";case"completions":return"Generate shell completion scripts";default:return t}}$n();var rr=8192,co=50,Fx=1e3;async function mp(t,e=Fx){t.destroyed||!t.writable||await new Promise(n=>{let s=!1,r=null,o=()=>{s||(s=!0,r&&(clearTimeout(r),r=null),n())};r=setTimeout(o,e);try{t.write("",o)}catch{o()}})}function lo(t,e,n=0){let s=process.env[t],r=s?Number.parseInt(s,10):Number.NaN;return Number.isFinite(r)?Math.max(n,r):e}function fp(t,e){let n=process.env[t]?.trim();if(!n)return;let s=Number.parseInt(n,10);if(!(!Number.isFinite(s)||s<=0)&&!(s>e+6e4))return s}function Ux(t,e){if(!t)return e;let n=Date.now(),s=fp("XENO_RUN_STARTED_AT_MS",n)??fp("XENO_AGENT_STARTED_AT_MS",n);return typeof s=="number"?new Date(s):e}function jx(t){return new Promise(e=>setTimeout(e,t))}function Vx(t){let e=t.match(/retry-after-ms=(\d+)/i);if(!e)return;let n=Number.parseInt(e[1]??"",10);if(!(!Number.isFinite(n)||n<=0))return n}function qx(t){let e=t?2:1,n=lo("XENO_RUN_RESTART_BASE_DELAY_MS",t?1500:1e3,100),s=lo("XENO_RUN_RESTART_MAX_DELAY_MS",t?12e4:3e4,n);return{maxAttempts:lo("XENO_RUN_RESTART_MAX_ATTEMPTS",e,0),baseDelayMs:n,maxDelayMs:Math.max(n,s)}}function Hx(t,e,n){let s=Vx(e);return s&&s>0?Math.min(s,n.maxDelayMs):Math.min(n.baseDelayMs*Math.pow(2,t),n.maxDelayMs)}function gp(t){if(typeof t!="string")return;let e=t.trim().toLowerCase();if(e==="staged"||e==="stage")return"staged";if(e==="parallel")return"parallel"}function bp(t){if(typeof t=="string")return(0,R.parseSubagentRoleList)(t)}function yp(t){if(typeof t!="string")return;let e=t.trim().toLowerCase();if(e==="auto"||e==="default")return;let n=Number.parseInt(e,10);return Number.isInteger(n)?n:void 0}function wp(t){if(typeof t!="string")return;let e=(0,R.parseSubagentRemoteMcpPolicy)(t);return e===null?void 0:e}function vp(t){if(typeof t=="string")return(0,R.coerceSubagentTeamPreset)(t)??void 0}var Pe=(0,B.loadConfig)();{let t=process.env.XENO_SEARCH_API_KEY||Pe.searchApiKey,e=Pe.searchProvider??"duckduckgo";(0,bs.configureSearch)({provider:t?e:"duckduckgo",apiKey:t,searxngUrl:Pe.searxngUrl,googleCx:Pe.googleCx})}async function zx(){let t=[];for await(let e of process.stdin)t.push(Buffer.isBuffer(e)?e:Buffer.from(String(e)));return Buffer.concat(t).toString("utf-8")}async function Sp(t){let e=Dx({input:process.stdin,output:process.stderr});return await new Promise(n=>{e.question(t,s=>{e.close(),n(s.trim())})})}async function Wx(t){return!process.stdin.isTTY||typeof process.stdin.setRawMode!="function"?Sp(t):await new Promise((e,n)=>{let s="",r=process.stdin,o=()=>{r.setRawMode(!1),r.pause(),r.off("data",a)},i=()=>{o(),process.stderr.write(`
|
|
2526
|
+
`),e(s)},a=l=>{let c=String(l);for(let u of c){if(u===""){o(),process.stderr.write(`
|
|
2527
|
+
`),n(new Error("Login cancelled"));return}if(u==="\r"||u===`
|
|
2528
|
+
`){i();return}if(u==="\x7F"||u==="\b"){s.length>0&&(s=s.slice(0,-1),process.stderr.write("\b \b"));continue}s+=u,process.stderr.write("*")}};process.stderr.write(t),r.setRawMode(!0),r.resume(),r.setEncoding("utf-8"),r.on("data",a)})}function ys(t){return typeof t=="string"&&t.trim().length>0?t.trim():void 0}function Xx(){let t=Kt(),e=t?.user,n=on(t,{includeExpired:!0}),s=t?.accountToken?.trim()||t?.webToken?.trim(),r=!!(n&&!n.expired||s&&!gn(s)),o=["Xeno account"];return o.push(`Signed in: ${r?"yes":"no"}`),(e?.email||e?.username||e?.name)&&o.push(`User: ${e.email??e.username??e.name}`),n&&(o.push(`Credential: ${n.type}${n.expired?" (expired)":""}`),n.expiresAt&&o.push(`Expires: ${n.expiresAt}`)),`${o.join(`
|
|
2529
|
+
`)}
|
|
2530
|
+
`}async function Kx(t={}){let e=await Tt({validate:t.validate!==!1}),n=["Xeno auth doctor",""];return n.push(an(e).trimEnd()),n.push(""),n.push(`Auth base URL: ${t.authBaseURL??e.authBaseURL??ot}`),n.push(`Model API base URL: ${t.apiBaseURL??e.apiBaseURL??we.XENO_API_BASE}`),e.expired?n.push("Action: session is expired; run `xeno login` again."):e.signedIn?e.hasApiKey?e.valid===!1?n.push("Action: credential validation failed; run `xeno logout` then `xeno login`."):n.push("Action: auth state looks usable."):n.push("Action: no usable model credential is configured; run `xeno login` or `xeno login --api-key <key>`."):n.push("Action: run `xeno login`."),`${n.join(`
|
|
2531
|
+
`)}
|
|
2532
|
+
`}function Gx(t,e){let n=Math.max(0,Math.floor((e-_o(t))/2));return" ".repeat(n)+t}function wa(t){let e=Math.max(48,process.stdout.columns??80),n=Math.max(18,process.stdout.rows??24),s=Ke(),r=t.email?`Signed in to Xeno as ${t.email}`:"Signed in to Xeno",o=t.credentialsPath?`Credentials: ${t.credentialsPath}`:"Credentials stored locally",i=(c,u)=>d.moveTo(c,1)+d.eraseLine()+Gx(u,e),a=Math.max(6,Math.floor(n/2)),l=d.clearScreen();return l+=d.hideCursor(),l+=i(3,r),l+=i(a-1,s("XENO")),l+=i(a+1,"AI-native command-line agent"),l+=i(Math.max(1,n-4),o),l+=i(Math.max(1,n-2),"Run `xeno` to start. Use `xeno --tui` to test fullscreen mode."),l+=d.moveTo(n,1)+d.showCursor(),l}je.name("xeno").description("XENO AGENT - AI-powered terminal agent by Xeno Corporation").version(Ze);je.command("login").description("Sign in to Xeno or store a model API key for the CLI").option("--email <email>","Xeno account email").option("--password <password>","Xeno account password (prefer --stdin-password for automation)").option("--stdin-password","Read the account password from stdin").option("--api-key <key>","Store a Xeno model API key directly").option("--token <token>","Store an existing Xeno account token directly").option("--auth-base-url <url>","Authentication API base URL",ot).option("--api-base-url <url>","Model API base URL").option("--status","Show current auth status instead of signing in").option("--no-provision-api-key","Do not try to create/reuse a model API key after account login").option("--no-validate","Skip live validation after storing credentials").option("--json","Emit machine-readable JSON output").action(async t=>{let e=ys(t.authBaseUrl)??ot,n=ys(t.apiBaseUrl);if(t.status){let m=await Tt({validate:t.validate!==!1});process.stdout.write(t.json?JSON.stringify(m,null,2)+`
|
|
2533
|
+
`:an(m));return}let s=!(typeof t.email=="string"&&t.email.trim().length>0),r=!t.stdinPassword&&!(typeof t.password=="string"&&t.password.length>0),o=!(typeof t.apiKey=="string"&&t.apiKey.trim().length>0),i=!(typeof t.token=="string"&&t.token.trim().length>0);if(s&&r&&o&&i){let{runWelcomeAuthFlow:m}=await Promise.resolve().then(()=>(Ms(),_r)),g=await m({apiBaseURL:n??we.XENO_API_BASE,authBaseURL:e});if(g.kind==="exit"){t.json&&process.stdout.write(JSON.stringify({ok:!1,cancelled:!0},null,2)+`
|
|
2534
|
+
`);return}if(g.kind==="error"){t.json?process.stdout.write(JSON.stringify({ok:!1,error:g.message},null,2)+`
|
|
2535
|
+
`):process.stderr.write(`${g.message}
|
|
2536
|
+
`),process.exitCode=1;return}let b=await Tt({validate:!1});if(t.json)process.stdout.write(JSON.stringify({ok:!0,via:g.via,status:b},null,2)+`
|
|
2537
|
+
`);else{let v=g.user?.email??g.credentials.user?.email;process.stdout.write(wa({email:v,credentialsPath:Xt()}))}return}if(typeof t.apiKey=="string"&&t.apiKey.trim().length>0){let m=t.apiKey.trim(),g=t.validate===!1?{valid:!0}:await bn({apiKey:m,apiBaseURL:n});if(!g.valid){process.stderr.write(`API key validation failed: ${g.error??"unknown error"}
|
|
2538
|
+
`),process.exitCode=1;return}let b=bt({apiKey:m,...n?{apiBaseURL:n}:{},source:"api-key"}),v=await Tt({validate:!1});t.json?process.stdout.write(JSON.stringify({ok:!0,credentialsPath:Xt(),status:v},null,2)+`
|
|
2539
|
+
`):(process.stdout.write(`Stored Xeno API key in ${Xt()}.
|
|
2540
|
+
`),b.apiBaseURL&&process.stdout.write(`API base URL: ${b.apiBaseURL}
|
|
2541
|
+
`));return}if(typeof t.token=="string"&&t.token.trim().length>0){if(bt({accountToken:t.token.trim(),authBaseURL:e,...n?{apiBaseURL:n}:{},source:"token"}),t.provisionApiKey!==!1){let g=await Uo({accountToken:t.token.trim(),authBaseURL:e,name:"Xeno CLI"});g.apiKey&&bt({apiKey:g.apiKey,...n?{apiBaseURL:n}:{}})}let m=await Tt({validate:t.validate!==!1});process.stdout.write(t.json?JSON.stringify(m,null,2)+`
|
|
2542
|
+
`:an(m));return}let a=typeof t.email=="string"&&t.email.trim().length>0?t.email.trim():await Sp("Xeno email: "),l=t.stdinPassword?(await zx()).trim():typeof t.password=="string"&&t.password.length>0?t.password:await Wx("Xeno password: ");if(!a||!l){process.stderr.write(`Email and password are required.
|
|
2543
|
+
`),process.exitCode=1;return}let c=await cl({email:a,password:l,authBaseURL:e,...n?{apiBaseURL:n}:{}}),u=bt(c.credentials),p;if(!u.apiKey&&!u.llmApiKey&&t.provisionApiKey!==!1){let m=await Uo({accountToken:u.accountToken??"",authBaseURL:e,name:"Xeno CLI"});m.apiKey?u=bt({apiKey:m.apiKey,...n?{apiBaseURL:n}:{},source:"login"}):p=m.error}let f=await Tt({validate:t.validate!==!1});if(t.json){process.stdout.write(JSON.stringify({ok:!0,endpoint:c.endpoint,status:f,provisionError:p},null,2)+`
|
|
2544
|
+
`);return}process.stdout.write(wa({email:u.user?.email??a,credentialsPath:Xt()})),!u.apiKey&&!u.llmApiKey&&(process.stdout.write("Account login succeeded, but no model API key was returned. If model calls still return 401, run `xeno login --api-key <key>` from your Xeno API keys page.\n"),p&&process.stdout.write(`API key provisioning warning: ${p}
|
|
2545
|
+
`))});je.command("logout").description("Sign out of Xeno and remove local CLI credentials").option("--all","Deprecated: logout now always removes user-config apiKey").option("--json","Emit machine-readable JSON output").action(async t=>{let e=await jo();if(e.cleared||Zn(),es(),Qn(),(0,B.saveConfig)({apiKey:void 0}),t.json){process.stdout.write(JSON.stringify(e,null,2)+`
|
|
2546
|
+
`);return}process.stdout.write(e.cleared?`Signed out of Xeno CLI.
|
|
2547
|
+
`:`No Xeno CLI credentials were stored.
|
|
2548
|
+
`),e.error&&process.stdout.write(`Remote logout warning: ${e.error}
|
|
2549
|
+
`)});je.command("auth [action]").description("Inspect or repair Xeno CLI authentication (status, whoami, doctor, login, logout)").option("--auth-base-url <url>","Authentication API base URL",ot).option("--api-base-url <url>","Model API base URL").option("--no-validate","Skip live credential validation").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let n=typeof t=="string"&&t.trim().length>0?t.trim().toLowerCase():"status";if(n==="status"){let s=await Tt({validate:e.validate!==!1});process.stdout.write(e.json?JSON.stringify(s,null,2)+`
|
|
2550
|
+
`:an(s));return}if(n==="whoami"||n==="me"){let s=await Tt({validate:e.validate!==!1});e.json?process.stdout.write(JSON.stringify({signedIn:s.signedIn,user:s.user??null,credentialType:s.modelCredentialType??null,expiresAt:s.expiresAt??null,expired:s.expired??!1},null,2)+`
|
|
2551
|
+
`):process.stdout.write(Xx());return}if(n==="doctor"||n==="diagnose"){let s=await Kx({validate:e.validate!==!1,authBaseURL:ys(e.authBaseUrl),apiBaseURL:ys(e.apiBaseUrl)});process.stdout.write(e.json?JSON.stringify({report:s},null,2)+`
|
|
2552
|
+
`:s);return}if(n==="logout"||n==="signout"||n==="sign-out"){let s=await jo();es(),Qn(),(0,B.saveConfig)({apiKey:void 0}),process.stdout.write(e.json?JSON.stringify(s,null,2)+`
|
|
2553
|
+
`:`Signed out of Xeno CLI.
|
|
2554
|
+
`);return}if(n==="login"||n==="signin"||n==="sign-in"){let{runWelcomeAuthFlow:s}=await Promise.resolve().then(()=>(Ms(),_r)),r=await s({authBaseURL:ys(e.authBaseUrl)??ot,apiBaseURL:ys(e.apiBaseUrl)??we.XENO_API_BASE});if(r.kind==="success"){let o=r.user?.email??r.credentials.user?.email;process.stdout.write(e.json?JSON.stringify({ok:!0,via:r.via,user:r.user??null},null,2)+`
|
|
2555
|
+
`:wa({email:o,credentialsPath:Xt()}))}else r.kind==="exit"?process.stdout.write(e.json?JSON.stringify({ok:!1,cancelled:!0},null,2)+`
|
|
2556
|
+
`:`Sign-in cancelled.
|
|
2557
|
+
`):(process.stderr.write(`${r.message}
|
|
2558
|
+
`),process.exitCode=1);return}process.stderr.write(`Usage: xeno auth [status|whoami|doctor|login|logout]
|
|
2559
|
+
`),process.exitCode=1});je.command("update").description("Check for CLI updates and optionally install the latest published version").option("--check","Check only; do not install").option("--dry-run","Print the resolved install command without executing it").option("--force-global","Allow a global update even when running from a workspace checkout").option("--channel <name>","Release channel: latest or next","latest").option("--json","Emit machine-readable JSON output").action(async t=>{let e=t.channel==="next"?"next":"latest",n=await Br({channel:e});if(t.json){process.stdout.write(JSON.stringify(n,null,2)+`
|
|
2560
|
+
`);return}if(process.stdout.write(rc(n)+`
|
|
2561
|
+
`),!(t.check||t.dryRun||!n.updateAvailable)){if(n.installContext==="workspace"&&t.forceGlobal!==!0){process.stderr.write(`Refusing to run a global self-update from a workspace checkout. Use --force-global if you really want the global install command.
|
|
2562
|
+
`),process.exitCode=1;return}process.stdout.write(`Installing update...
|
|
2563
|
+
`),await oc({channel:e})}});je.command("trace [traceId]").description("Inspect audit traces from the latest workspace audit log or a specific audit file").option("--audit-file <path>","Path to a specific audit jsonl file").option("--list","List available traces instead of rendering one trace").option("--replay","Render a replay view for the selected trace").option("--markdown","Render the trace report as markdown").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let n=await Nd({cwd:process.cwd(),traceId:typeof t=="string"&&t.length>0?t:void 0,auditFilePath:typeof e.auditFile=="string"?e.auditFile:void 0,replay:e.replay===!0});if(e.json){process.stdout.write(JSON.stringify(n,null,2)+`
|
|
2564
|
+
`);return}process.stdout.write(Bd(n,{listOnly:e.list===!0,replay:e.replay===!0,markdown:e.markdown===!0})+`
|
|
2565
|
+
`)});je.command("app-server").description("Start the Xeno JSON-RPC app server over stdio").option("--cwd <path>","Working directory for thread.run requests").option("--model <model>","Default model for thread.run requests").option("--base-url <url>","Override Xeno API base URL").option("--max-tokens <count>","Default max output tokens").option("--max-iterations <count>","Default max agent iterations").action(async t=>{let e=typeof t.cwd=="string"?ws(t.cwd):process.cwd(),n=typeof t.model=="string"&&t.model.trim().length>0?t.model.trim():Pe.model??we.DEFAULT_MODEL,s=rn({explicitBaseURL:typeof t.baseUrl=="string"?t.baseUrl:void 0,configuredBaseURL:Pe.baseURL}),r=Number.parseInt(String(t.maxTokens??Pe.maxTokens??rr),10),o=Number.parseInt(String(t.maxIterations??Pe.maxIterations??co),10);await new R.XenoAppServer({defaultAgentOptions:{cwd:e,model:n,baseURL:s,apiKey:ts(process.env.XENO_API_KEY,Pe.apiKey,we.DEFAULT_API_KEY),maxTokens:Number.isFinite(r)?r:rr,maxIterations:Number.isFinite(o)?o:co}}).start(process.stdin,process.stdout)});je.command("bench [suite]").description("Run local coding-tool benchmarks or launch Terminal-Bench against the XENO CLI").option("--iterations <count>","Benchmark iterations per tool","5").option("--files <count>","Synthetic file count","180").option("--lines <count>","Synthetic lines per file","40").option("--terminal-bench-path <path>","Path to a terminal-bench checkout").option("--runner <auto|harbor|legacy>","Terminal-Bench runner. Defaults to Harbor when available.","auto").option("--dataset <name==version>","Terminal-Bench dataset spec, for example aider_polyglot==head").option("--dataset-path <path>","Terminal-Bench dataset path").option("--task-id <id>","Terminal-Bench task id or glob (repeatable)",(t,e=[])=>(e.push(t),e),[]).option("--output-path <path>","Terminal-Bench run output directory").option("--jobs-dir <path>","Harbor jobs directory for official Terminal-Bench runs").option("--run-id <id>","Explicit Terminal-Bench run identifier").option("--package-tarball <path>","Existing XENO CLI tarball to install inside Terminal-Bench containers").option("--prompt-template <path>","Custom Terminal-Bench prompt template for the XENO agent").option("--n-concurrent <count>","Terminal-Bench concurrent trial count","1").option("--n-attempts <count>","Terminal-Bench attempts per task","1").option("--global-agent-timeout-sec <seconds>","Global Terminal-Bench agent timeout in seconds").option("--global-test-timeout-sec <seconds>","Global Terminal-Bench test timeout in seconds").option("--agent-setup-timeout-multiplier <multiplier>","Harbor agent setup timeout multiplier","4").option("--harness-max-retries <count>","Harbor harness retry attempts for transient harness/container failures").option("--api-max-retries <count>","Xeno SDK API retry attempts").option("--api-base-delay-ms <ms>","Base API retry delay in milliseconds").option("--api-max-delay-ms <ms>","Maximum API retry delay in milliseconds").option("--api-retry-jitter-ms <ms>","API retry delay jitter in milliseconds").option("--api-request-timeout-ms <ms>","Per-request Xeno API timeout in milliseconds").option("--no-rebuild","Skip Terminal-Bench container rebuilds").option("--no-cleanup","Keep Terminal-Bench run images instead of removing them").option("--no-prune-docker-networks","Disable automatic pruning of unused Docker networks before large runs").option("--dry-run","Print the Terminal-Bench command and prepared artifacts without executing the harness").option("--delegate","Enable XENO delegation when running inside Terminal-Bench").option("-m, --model <model>","AI model to use for Terminal-Bench runs").option("--max-tokens <count>","Max response tokens for Terminal-Bench XENO runs").option("--max-iterations <count>","Max loop iterations for Terminal-Bench XENO runs").option("--markdown","Render the benchmark report as markdown").option("--enforce-thresholds","Exit non-zero if benchmark status is fail").option("--job-path <path>","Path to a Harbor job directory for offline benchmark analysis").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let n=typeof t=="string"&&t.trim().length>0?t.trim().toLowerCase():"coding-tools";if(n==="analyze-harbor"||n==="harbor-results"||n==="harbor"){if(typeof e.jobPath!="string"||e.jobPath.trim().length===0){process.stderr.write(`Pass --job-path <path> to analyze a Harbor job directory.
|
|
2566
|
+
`),process.exitCode=1;return}let r=ou(e.jobPath);e.json?process.stdout.write(JSON.stringify(r,null,2)+`
|
|
2567
|
+
`):e.markdown?process.stdout.write(au(r)+`
|
|
2568
|
+
`):process.stdout.write(iu(r)+`
|
|
2569
|
+
`);return}if(n==="terminal-bench"||n==="tb"){if(e.json&&e.dryRun!==!0){process.stderr.write(`Use --dry-run with --json for terminal-bench. Live harness runs stream directly to the terminal.
|
|
2570
|
+
`),process.exitCode=1;return}let r=rp({cwd:process.cwd(),runner:typeof e.runner=="string"?e.runner:void 0,terminalBenchPath:typeof e.terminalBenchPath=="string"?e.terminalBenchPath:void 0,jobsDir:typeof e.jobsDir=="string"?e.jobsDir:void 0,datasetPath:typeof e.datasetPath=="string"?e.datasetPath:void 0,dataset:typeof e.dataset=="string"?e.dataset:void 0,taskIds:Array.isArray(e.taskId)?e.taskId:[],outputPath:typeof e.outputPath=="string"?e.outputPath:void 0,runId:typeof e.runId=="string"?e.runId:void 0,packageTarballPath:typeof e.packageTarball=="string"?e.packageTarball:void 0,model:typeof e.model=="string"?e.model:void 0,apiKey:ts(process.env.XENO_API_KEY,Pe.apiKey,we.DEFAULT_API_KEY),baseUrl:rn({benchmarkMode:!0}),promptTemplate:typeof e.promptTemplate=="string"?e.promptTemplate:void 0,delegate:e.delegate===!0,maxIterations:typeof e.maxIterations=="string"?Number.parseInt(e.maxIterations,10):void 0,maxTokens:typeof e.maxTokens=="string"?Number.parseInt(e.maxTokens,10):void 0,nConcurrent:typeof e.nConcurrent=="string"?Number.parseInt(e.nConcurrent,10):void 0,nAttempts:typeof e.nAttempts=="string"?Number.parseInt(e.nAttempts,10):void 0,apiMaxRetries:typeof e.apiMaxRetries=="string"?Number.parseInt(e.apiMaxRetries,10):void 0,apiBaseDelayMs:typeof e.apiBaseDelayMs=="string"?Number.parseInt(e.apiBaseDelayMs,10):void 0,apiMaxDelayMs:typeof e.apiMaxDelayMs=="string"?Number.parseInt(e.apiMaxDelayMs,10):void 0,apiRetryJitterMs:typeof e.apiRetryJitterMs=="string"?Number.parseInt(e.apiRetryJitterMs,10):void 0,apiRequestTimeoutMs:typeof e.apiRequestTimeoutMs=="string"?Number.parseInt(e.apiRequestTimeoutMs,10):void 0,globalAgentTimeoutSec:typeof e.globalAgentTimeoutSec=="string"?Number.parseInt(e.globalAgentTimeoutSec,10):void 0,globalTestTimeoutSec:typeof e.globalTestTimeoutSec=="string"?Number.parseInt(e.globalTestTimeoutSec,10):void 0,agentSetupTimeoutMultiplier:typeof e.agentSetupTimeoutMultiplier=="string"?Number.parseFloat(e.agentSetupTimeoutMultiplier):void 0,harnessMaxRetries:typeof e.harnessMaxRetries=="string"?Number.parseInt(e.harnessMaxRetries,10):void 0,noRebuild:e.rebuild===!1,noCleanup:e.cleanup===!1,pruneDockerNetworks:e.pruneDockerNetworks!==!1,dryRun:e.dryRun===!0});if(e.json){process.stdout.write(JSON.stringify(sp(r),null,2)+`
|
|
2571
|
+
`);return}if(process.stdout.write(np(r)+`
|
|
2572
|
+
`),e.dryRun===!0)return;try{let o=ap(r);o.exitCode!==0&&(process.exitCode=o.exitCode)}catch(o){process.stderr.write(`Error: ${o instanceof Error?o.message:String(o)}
|
|
2573
|
+
`),process.exitCode=1}return}if(n!=="coding-tools"&&n!=="coding"){process.stderr.write(`Usage: xeno bench [coding-tools|terminal-bench|analyze-harbor] [--iterations N] [--files N] [--lines N]
|
|
2574
|
+
xeno bench terminal-bench [--runner harbor|legacy] [--dataset terminal-bench@2.0|--dataset-path <path>] [--task-id id] [--dry-run]
|
|
2575
|
+
`),process.exitCode=1;return}let s=await eu({iterations:Number.parseInt(String(e.iterations),10),fileCount:Number.parseInt(String(e.files),10),linesPerFile:Number.parseInt(String(e.lines),10)});e.json?process.stdout.write(JSON.stringify(s,null,2)+`
|
|
2576
|
+
`):e.markdown?process.stdout.write(nu(s)+`
|
|
2577
|
+
`):process.stdout.write(tu(s)+`
|
|
2578
|
+
`),e.enforceThresholds&&s.status==="fail"&&(process.exitCode=1)});je.command("doctor").description("Inspect local runtime, config, trust, and MCP health").option("--json","Emit machine-readable JSON output").option("--no-mcp","Skip MCP connectivity checks").action(async t=>{let e=await os({cwd:process.cwd(),connectMcp:t.mcp});if(t.json){process.stdout.write(JSON.stringify(e,null,2)+`
|
|
2579
|
+
`);return}process.stdout.write(Dr(e)+`
|
|
2580
|
+
`)});je.command("bug-report [outputPath]").description("Write a redacted diagnostic bundle for debugging CLI/runtime issues").option("--json","Emit the bundle to stdout instead of writing a file").action(async(t,e)=>{if(e.json){let s=await pi({cwd:process.cwd()});process.stdout.write(JSON.stringify(s,null,2)+`
|
|
2581
|
+
`);return}let n=await Ds({cwd:process.cwd(),...typeof t=="string"&&t.length>0?{outputPath:t}:{}});process.stdout.write(`Bug report bundle written to ${n.path}
|
|
2582
|
+
`)});je.command("approved-tools [action] [approvalKey...]").description("List or revoke remembered tool approvals for this workspace").option("--json","Emit machine-readable JSON output").action((t,e,n)=>{let s=(t??"list").toLowerCase(),r=process.cwd();if(s==="list"){let o=$r(r);if(n.json){process.stdout.write(JSON.stringify({cwd:r,entries:o},null,2)+`
|
|
2583
|
+
`);return}if(o.length===0){process.stdout.write(`No remembered tool approvals for this workspace
|
|
2584
|
+
`);return}process.stdout.write(`Remembered tool approvals
|
|
2585
|
+
`);for(let i of o)process.stdout.write(`- ${i.toolName}${i.matcher?` -> ${i.matcher}`:""}
|
|
2586
|
+
`),process.stdout.write(` key: ${i.approvalKey}
|
|
2587
|
+
`);return}if(s==="remove"){let o=Array.isArray(e)?e.join(" ").trim():"";if(!o){process.stderr.write(`Usage: xeno approved-tools remove <approval-key>
|
|
2588
|
+
`),process.exitCode=1;return}let i=Lr(r,o);n.json?process.stdout.write(JSON.stringify({approvalKey:o,removed:i},null,2)+`
|
|
2589
|
+
`):i?process.stdout.write(`Removed remembered approval ${o}
|
|
2590
|
+
`):(process.stderr.write(`Approval not found: ${o}
|
|
2591
|
+
`),process.exitCode=1);return}if(s==="clear"){let o=Nr(r);n.json?process.stdout.write(JSON.stringify({cleared:o},null,2)+`
|
|
2592
|
+
`):o>0?process.stdout.write(`Cleared ${o} remembered tool approval${o===1?"":"s"}
|
|
2593
|
+
`):process.stdout.write(`No remembered tool approvals to clear
|
|
2594
|
+
`);return}process.stderr.write(`Usage: xeno approved-tools [list|remove <approval-key>|clear] [--json]
|
|
2595
|
+
`),process.exitCode=1});je.command("config [action] [scope] [key] [value...]").description("Inspect or edit current user and project configuration").option("--json","Emit machine-readable JSON output").option("--json-value","Parse the provided value as JSON when using set").action(async(t,e,n,s,r)=>{let o=(t??"show").toLowerCase();if(o==="set"){if(e!=="user"&&e!=="project"||typeof n!="string"||!Array.isArray(s)||s.length===0){process.stderr.write(`Usage: xeno config set <user|project> <key.path> <value> [--json-value]
|
|
2596
|
+
`),process.exitCode=1;return}let a=await Fr({cwd:process.cwd(),scope:e,keyPath:n,rawValue:s.join(" "),parseAsJson:r.jsonValue===!0});r.json?process.stdout.write(JSON.stringify(a,null,2)+`
|
|
2597
|
+
`):(process.stdout.write(`Updated ${e} config at ${a.path}
|
|
2598
|
+
`),process.stdout.write(` ${n} = ${JSON.stringify(a.value)}
|
|
2599
|
+
`));return}if(o==="unset"){if(e!=="user"&&e!=="project"||typeof n!="string"){process.stderr.write(`Usage: xeno config unset <user|project> <key.path>
|
|
2600
|
+
`),process.exitCode=1;return}let a=await Ur({cwd:process.cwd(),scope:e,keyPath:n});r.json?process.stdout.write(JSON.stringify(a,null,2)+`
|
|
2601
|
+
`):process.stdout.write(`Removed ${n} from ${e} config at ${a.path}
|
|
2602
|
+
`);return}if(o!=="show"&&o!=="paths"){process.stderr.write(`Usage: xeno config [show|paths|set|unset] [--json]
|
|
2603
|
+
`),process.exitCode=1;return}let i={cwd:process.cwd(),userConfig:(0,B.loadConfig)(),projectState:(0,B.loadProjectState)(process.cwd()),userConfigPath:hp((0,B.getConfigDir)(),"config.json"),projectStatePath:(0,B.getProjectStatePath)(process.cwd())};if(r.json){process.stdout.write(JSON.stringify(i,null,2)+`
|
|
2604
|
+
`);return}if(o==="paths"){process.stdout.write(`User config: ${i.userConfigPath}
|
|
2605
|
+
`),process.stdout.write(`Project state: ${i.projectStatePath}
|
|
2606
|
+
`);return}process.stdout.write(`User config
|
|
2607
|
+
`),process.stdout.write(JSON.stringify(i.userConfig,null,2)+`
|
|
2608
|
+
|
|
2609
|
+
`),process.stdout.write(`User config path (${i.userConfigPath})
|
|
2610
|
+
|
|
2611
|
+
`),process.stdout.write(`Project state (${i.projectStatePath})
|
|
2612
|
+
`),process.stdout.write(JSON.stringify(i.projectState,null,2)+`
|
|
2613
|
+
`)});je.addCommand(cu());je.command("onboarding [action]").description("Show or update onboarding guidance for the current workspace").action(t=>{if(t==="done"){(0,B.setProjectOnboardingCompleted)(process.cwd(),!0),process.stdout.write(`Marked onboarding as completed for this workspace.
|
|
2614
|
+
`);return}if(t==="reset"){(0,B.setProjectOnboardingCompleted)(process.cwd(),!1),process.stdout.write(`Reset onboarding status for this workspace.
|
|
2615
|
+
`);return}process.stdout.write($s(Os(process.cwd()))+`
|
|
2616
|
+
`)});je.command("release-notes [version]").description("Show current or requested release notes").option("--no-mark-seen","Do not update the stored current-version marker").action((t,e)=>{!t&&e.markSeen!==!1&&rs(),process.stdout.write(Or(t??Ze)+`
|
|
2617
|
+
`)});je.command("terminal-setup").description("Install Shift+Enter terminal integration for supported terminals").option("--status","Inspect current terminal integration status").option("--vscode","Target VS Code terminal integration explicitly").option("--iterm","Target iTerm2 integration explicitly").action(t=>{let e=t.vscode?"vscode":t.iterm?"iterm2":ss();if(t.status){let n=Mr(e);process.stdout.write(`${n.detail}${n.configPath?` (${n.configPath})`:""}
|
|
2618
|
+
`);return}ai({cwd:process.cwd(),target:e,onOutput:n=>process.stdout.write(n)})});je.command("listen").description("Start system dictation / voice typing on supported platforms").action(()=>{let t=gi();process.stdout.write(t.message+`
|
|
2619
|
+
`),t.supported||(process.exitCode=1)});je.command("pr-comments [selector]").description("Fetch and render GitHub PR comments via gh").action(t=>{try{wi({cwd:process.cwd(),selector:t,onOutput:e=>process.stdout.write(e)})}catch(e){process.stderr.write(`Error: ${e instanceof Error?e.message:String(e)}
|
|
2620
|
+
`),process.exitCode=1}});je.command("ctx-viz").description("Inspect system prompt, tool definitions, and message-context usage").option("--cwd <path>","Workspace path to inspect").option("--date <yyyy-mm-dd>","Override the prompt date").option("--model <model>","Override the inspected model name").option("--mode <mode>","Execution mode: agent or chat").option("--role <name>","Resolve role-specific identity").option("--json","Emit machine-readable JSON output").option("--no-memory","Exclude persisted memory from the inspected prompt").option("--no-identity","Exclude identity layers from the inspected prompt").action(async t=>{let e=String(t.mode||Pe.executionMode||"agent").toLowerCase(),n=e==="chat"||e==="chatonly"?"chatOnly":e==="agent"?"agent":void 0;if(!n){process.stderr.write(`Invalid execution mode: ${t.mode}. Expected agent or chat.
|
|
2621
|
+
`),process.exitCode=1;return}let s=ws(t.cwd||process.cwd()),r=await(0,R.inspectSystemPrompt)({cwd:s,model:t.model||Pe.model||we.DEFAULT_MODEL,date:t.date,role:t.role,executionMode:n,identity:t.identity===!1?!1:void 0,memory:t.memory===!1?!1:void 0}),o=(0,R.createDefaultToolRegistry)({cwd:s}).getDefinitions(),i=fi({systemPrompt:r.systemPrompt,toolDefinitions:o,messages:[]});if(t.json){process.stdout.write(JSON.stringify(i,null,2)+`
|
|
2622
|
+
`);return}process.stdout.write(hi(i)+`
|
|
2623
|
+
`)});je.command("system-prompt").description("Print the fully resolved system prompt for the current workspace").option("--cwd <path>","Workspace path to inspect").option("--date <yyyy-mm-dd>","Override the prompt date").option("--model <model>","Override the inspected model name").option("--mode <mode>","Execution mode: agent or chat").option("--role <name>","Resolve role-specific identity").option("--json","Emit machine-readable JSON output").option("--no-memory","Exclude persisted memory from the inspected prompt").option("--no-identity","Exclude identity layers from the inspected prompt").action(async t=>{let e=String(t.mode||Pe.executionMode||"agent").toLowerCase(),n=e==="chat"||e==="chatonly"?"chatOnly":e==="agent"?"agent":void 0;if(!n){process.stderr.write(`Invalid execution mode: ${t.mode}. Expected agent or chat.
|
|
2624
|
+
`),process.exitCode=1;return}let s=await(0,R.inspectSystemPrompt)({cwd:ws(t.cwd||process.cwd()),model:t.model||Pe.model||we.DEFAULT_MODEL,date:t.date,role:t.role,executionMode:n,identity:t.identity===!1?!1:void 0,memory:t.memory===!1?!1:void 0});if(t.json){process.stdout.write(JSON.stringify(s,null,2)+`
|
|
2625
|
+
`);return}process.stdout.write(s.systemPrompt+`
|
|
2626
|
+
`)});je.command("bootstrap-plan").description("Show what `xeno init` would scaffold in the current workspace").option("--cwd <path>","Workspace path to inspect").option("--json","Emit machine-readable JSON output").action(t=>{let e=Cr(ws(t.cwd||process.cwd()));if(t.json){process.stdout.write(JSON.stringify(e,null,2)+`
|
|
2627
|
+
`);return}process.stdout.write(Od(e)+`
|
|
2628
|
+
`)});je.command("dump-manifests").description("Dump command, tool, plugin, and workspace manifest state").option("--cwd <path>","Workspace path to inspect").option("--plugin-dir <path>","Plugin directory to inspect").option("--json","Emit machine-readable JSON output").action(t=>{let n={...(0,R.inspectRuntimeManifests)({cwd:ws(t.cwd||process.cwd()),...t.pluginDir?{pluginDir:ws(t.pluginDir)}:{}}),commands:Md(je.commands)};if(t.json){process.stdout.write(JSON.stringify(n,null,2)+`
|
|
2629
|
+
`);return}process.stdout.write($d(n)+`
|
|
2630
|
+
`)});je.command("cost").description("Show the last persisted session token, duration, and cost summary for this workspace").option("--json","Emit machine-readable JSON output").action(t=>{let e=process.cwd(),n=(0,B.getProjectLastSessionSummary)(e);if(t.json){process.stdout.write(JSON.stringify({cwd:e,summary:n??null},null,2)+`
|
|
2631
|
+
`);return}if(!n){process.stdout.write(`No persisted session summary for this workspace.
|
|
2632
|
+
`);return}process.stdout.write(Pl(n)+`
|
|
2633
|
+
`)});je.command("chat",{isDefault:!0}).description("Start interactive chat with XENO AGENT").option("-m, --model <model>","AI model to use").option("-k, --api-key <key>","API key (optional for Xeno API)").option("--base-url <url>","API base URL").option("--max-tokens <n>","Max response tokens").option("--max-iterations <n>","Max agentic loop iterations").option("--memory-context-sessions <n>","Prior-session context entries for prompt memory (1-10)").option("--memory-context-tokens <n>","Token budget for prior-session prompt memory context").option("--memory-context-chars <n>","Per-session char budget for prior-session prompt memory context").option("--mode <mode>","Execution mode: agent, chat").option("--delegate","Enable planner/explorer/executor/reviewer delegation mode").option("--delegate-max-total-tokens <n>","Total token budget for delegated branches").option("--delegate-timeout-ms <n>","Wall-clock budget for delegated run (ms)").option("--delegate-mode <mode>","Delegation workflow mode: staged or parallel").option("--delegate-team <team>","Delegation team preset: balanced, explore, build, or review").option("--delegate-roles <csv>","Delegated branch roles (comma-separated)").option("--delegate-concurrency <n|auto>","Max concurrent delegated branches").option("--delegate-role-precedence <csv>","Reducer precedence list (comma-separated roles)").option("--delegate-remote <policy>","Delegated branch remote MCP policy: none, prompts, resources, context, all, or role=policy,...").option("--color <color>",`UI color: ${Dt.join(", ")}`).option("--permission-mode <mode>","Permission mode: default, acceptEdits, bypassPermissions").option("--resume [id]","Resume a previous session (latest if no ID)").option("--role <name>","Use specific role identity").option("--checkpoint <id>","Resume from a specific checkpoint").option("--mcp","Enable MCP server loading from config").option("--line-input","Use Windows-safe line input instead of the fullscreen raw TUI").option("--tui","Force the fullscreen raw TUI on Windows").action(async t=>{let e=t.model||Pe.model||we.DEFAULT_MODEL,n=typeof t.apiKey=="string"&&t.apiKey.trim().length>0,s=typeof process.env.XENO_API_KEY=="string"&&process.env.XENO_API_KEY.trim().length>0,r=typeof Pe.apiKey=="string"&&Pe.apiKey.trim().length>0,o=ts(t.apiKey,process.env.XENO_API_KEY,Pe.apiKey,we.DEFAULT_API_KEY),i=n?"explicit-api-key":s?"env-api-key":r?"config-api-key":"none",a=rn({explicitBaseURL:t.baseUrl,configuredBaseURL:Pe.baseURL}),l=t.maxTokens?parseInt(t.maxTokens,10):Pe.maxTokens??rr,c=t.maxIterations?parseInt(t.maxIterations,10):Pe.maxIterations??co,u=t.memoryContextSessions?parseInt(t.memoryContextSessions,10):Pe.memoryContextSessions,p=t.memoryContextTokens?parseInt(t.memoryContextTokens,10):Pe.memoryContextTokens,f=t.memoryContextChars?parseInt(t.memoryContextChars,10):Pe.memoryContextChars,m=t.mode||Pe.executionMode||"agent",g=String(m).toLowerCase()==="chat"?"chatOnly":m,b=!!t.delegate,v=t.delegateMaxTotalTokens?parseInt(t.delegateMaxTotalTokens,10):void 0,w=t.delegateTimeoutMs?parseInt(t.delegateTimeoutMs,10):void 0,P=gp(t.delegateMode),C=vp(t.delegateTeam),$=bp(t.delegateRoles),E=yp(t.delegateConcurrency),T=wp(t.delegateRemote),I=typeof t.delegateRolePrecedence=="string"?t.delegateRolePrecedence.split(",").map(Z=>Z.trim()).filter(Z=>Z.length>0):void 0,re=!!(t.mcp||Pe.mcpEnabled),ae=t.permissionMode||Pe.permissionMode||"default",N=String(t.color||Pe.uiColor||"blue").toLowerCase();Xn(N)||(console.error(`Invalid UI color: ${N}. Expected one of: ${Dt.join(", ")}`),process.exit(1)),En(N);let y=["default","acceptEdits","bypassPermissions"];(Z=>y.includes(Z))(ae)||(console.error(`Invalid permission mode: ${ae}`),process.exit(1));let K=["agent","chatOnly"];(Z=>K.includes(Z))(g)||(console.error(`Invalid execution mode: ${g}. Expected: agent or chat`),process.exit(1)),u!==void 0&&(!Number.isInteger(u)||u<1||u>10)&&(console.error(`Invalid memory context session count: ${u}. Expected 1-10.`),process.exit(1)),p!==void 0&&(!Number.isInteger(p)||p<120)&&(console.error(`Invalid memory context token budget: ${p}. Expected integer >= 120.`),process.exit(1)),f!==void 0&&(!Number.isInteger(f)||f<200)&&(console.error(`Invalid memory context char budget: ${f}. Expected integer >= 200.`),process.exit(1)),v!==void 0&&(!Number.isInteger(v)||v<300)&&(console.error(`Invalid delegation token budget: ${v}. Expected integer >= 300.`),process.exit(1)),w!==void 0&&(!Number.isInteger(w)||w<1e3)&&(console.error(`Invalid delegation timeout: ${w}. Expected integer >= 1000 ms.`),process.exit(1)),t.delegateMode!==void 0&&P===void 0&&(console.error(`Invalid delegation mode: ${t.delegateMode}. Expected staged or parallel.`),process.exit(1)),t.delegateTeam!==void 0&&C===void 0&&(console.error(`Invalid delegation team: ${t.delegateTeam}. Expected balanced, explore, build, or review.`),process.exit(1)),t.delegateRoles!==void 0&&$===void 0&&(console.error(`Invalid delegation roles: ${t.delegateRoles}. Expected comma-separated planner,explorer,executor,reviewer or aliases like worker,researcher.`),process.exit(1)),t.delegateConcurrency!==void 0&&E===void 0&&String(t.delegateConcurrency).trim().toLowerCase()!=="auto"&&String(t.delegateConcurrency).trim().toLowerCase()!=="default"&&(console.error(`Invalid delegation concurrency: ${t.delegateConcurrency}. Expected integer >= 1 or auto.`),process.exit(1)),E!==void 0&&E<1&&(console.error(`Invalid delegation concurrency: ${E}. Expected integer >= 1 or auto.`),process.exit(1)),t.delegateRemote!==void 0&&T===void 0&&(console.error(`Invalid delegation remote policy: ${t.delegateRemote}. Expected none, prompts, resources, context, all, or role=policy,...`),process.exit(1)),await Gc({model:e,apiKey:o,authBypassSource:i,baseURL:a,maxTokens:l,maxIterations:c,executionMode:g,delegationEnabled:b,delegationMaxTotalTokens:v,delegationTimeoutMs:w,delegationMode:P,delegationTeamPreset:C,delegationRoles:$,delegationRolePrecedence:I,delegationMaxConcurrentBranches:E,delegationRemoteMcpByRole:T,mcpEnabled:re,permissionMode:ae,memoryContextSessions:u,memoryContextTokens:p,memoryContextChars:f,resume:t.resume,role:t.role,checkpoint:t.checkpoint,lineInput:!!t.lineInput,rawTui:!!t.tui})});je.command("run <prompt>").description("Run a task non-interactively").option("-m, --model <model>","AI model to use").option("-k, --api-key <key>","API key (optional for Xeno API)").option("--base-url <url>","API base URL").option("--max-tokens <n>","Max response tokens").option("--max-iterations <n>","Max agentic loop iterations").option("--memory-context-sessions <n>","Prior-session context entries for prompt memory (1-10)").option("--memory-context-tokens <n>","Token budget for prior-session prompt memory context").option("--memory-context-chars <n>","Per-session char budget for prior-session prompt memory context").option("--mode <mode>","Execution mode: agent, chat").option("--color <color>",`UI color: ${Dt.join(", ")}`).option("--json","Emit machine-readable JSON output").option("--ndjson","Emit newline-delimited JSON events during execution").option("--mcp","Enable MCP server loading from config").option("--delegate","Enable planner/explorer/executor/reviewer delegation mode").option("--delegate-max-total-tokens <n>","Total token budget for delegated branches").option("--delegate-timeout-ms <n>","Wall-clock budget for delegated run (ms)").option("--delegate-mode <mode>","Delegation workflow mode: staged or parallel").option("--delegate-team <team>","Delegation team preset: balanced, explore, build, or review").option("--delegate-roles <csv>","Delegated branch roles (comma-separated)").option("--delegate-concurrency <n|auto>","Max concurrent delegated branches").option("--delegate-role-precedence <csv>","Reducer precedence list (comma-separated roles)").option("--delegate-remote <policy>","Delegated branch remote MCP policy: none, prompts, resources, context, all, or role=policy,...").option("-y, --yes","Auto-accept all prompts (still logs actions)").option("--bypass-permissions","UNSAFE: Bypass permission checks entirely").action(async(t,e)=>{let n=e.model||Pe.model||we.DEFAULT_MODEL,s=ts(e.apiKey,process.env.XENO_API_KEY,Pe.apiKey,we.DEFAULT_API_KEY),r=e.maxTokens?parseInt(e.maxTokens,10):Pe.maxTokens??rr,o=e.maxIterations?parseInt(e.maxIterations,10):Pe.maxIterations??co,i=e.memoryContextSessions?parseInt(e.memoryContextSessions,10):Pe.memoryContextSessions,a=e.memoryContextTokens?parseInt(e.memoryContextTokens,10):Pe.memoryContextTokens,l=e.memoryContextChars?parseInt(e.memoryContextChars,10):Pe.memoryContextChars,c=e.mode||Pe.executionMode||"agent",u=String(c).toLowerCase()==="chat"?"chatOnly":c,p=String(e.color||Pe.uiColor||"blue").toLowerCase(),f=!!e.json,m=!!e.ndjson,g=f||m,b=!!e.delegate,v=!!(e.mcp||Pe.mcpEnabled),w=e.delegateMaxTotalTokens?parseInt(e.delegateMaxTotalTokens,10):Math.max(r*3,1200),P=e.delegateTimeoutMs?parseInt(e.delegateTimeoutMs,10):12e4,C=gp(e.delegateMode),$=vp(e.delegateTeam),E=bp(e.delegateRoles),T=yp(e.delegateConcurrency),I=wp(e.delegateRemote),re=typeof e.delegateRolePrecedence=="string"?e.delegateRolePrecedence.split(",").map(ie=>ie.trim()).filter(ie=>ie.length>0):void 0;Xn(p)||(console.error(`Invalid UI color: ${p}. Expected one of: ${Dt.join(", ")}`),process.exit(1)),f&&m&&(console.error("Choose either --json or --ndjson, not both."),process.exit(1)),En(p),u!=="agent"&&u!=="chatOnly"&&(console.error(`Invalid execution mode: ${u}. Expected: agent or chat`),process.exit(1)),i!==void 0&&(!Number.isInteger(i)||i<1||i>10)&&(console.error(`Invalid memory context session count: ${i}. Expected 1-10.`),process.exit(1)),a!==void 0&&(!Number.isInteger(a)||a<120)&&(console.error(`Invalid memory context token budget: ${a}. Expected integer >= 120.`),process.exit(1)),l!==void 0&&(!Number.isInteger(l)||l<200)&&(console.error(`Invalid memory context char budget: ${l}. Expected integer >= 200.`),process.exit(1)),b&&(!Number.isInteger(w)||w<300)&&(console.error(`Invalid delegation token budget: ${w}. Expected integer >= 300.`),process.exit(1)),b&&(!Number.isInteger(P)||P<1e3)&&(console.error(`Invalid delegation timeout: ${P}. Expected integer >= 1000 ms.`),process.exit(1)),e.delegateMode!==void 0&&C===void 0&&(console.error(`Invalid delegation mode: ${e.delegateMode}. Expected staged or parallel.`),process.exit(1)),e.delegateTeam!==void 0&&$===void 0&&(console.error(`Invalid delegation team: ${e.delegateTeam}. Expected balanced, explore, build, or review.`),process.exit(1)),e.delegateRoles!==void 0&&E===void 0&&(console.error(`Invalid delegation roles: ${e.delegateRoles}. Expected comma-separated planner,explorer,executor,reviewer or aliases like worker,researcher.`),process.exit(1)),e.delegateConcurrency!==void 0&&T===void 0&&String(e.delegateConcurrency).trim().toLowerCase()!=="auto"&&String(e.delegateConcurrency).trim().toLowerCase()!=="default"&&(console.error(`Invalid delegation concurrency: ${e.delegateConcurrency}. Expected integer >= 1 or auto.`),process.exit(1)),T!==void 0&&T<1&&(console.error(`Invalid delegation concurrency: ${T}. Expected integer >= 1 or auto.`),process.exit(1)),e.delegateRemote!==void 0&&I===void 0&&(console.error(`Invalid delegation remote policy: ${e.delegateRemote}. Expected none, prompts, resources, context, all, or role=policy,...`),process.exit(1));let ae="default";e.bypassPermissions?(await uu("xeno run --bypass-permissions"),ae="bypassPermissions",g||(console.warn(`
|
|
2634
|
+
\u26A0\uFE0F WARNING: Running with --bypass-permissions (UNSAFE)`),console.warn(` All security checks are disabled. Use with caution.
|
|
2635
|
+
`))):e.yes&&(ae="acceptEdits",g||console.warn(`
|
|
2636
|
+
\u26A0\uFE0F Auto-accepting all prompts (--yes flag enabled)
|
|
2637
|
+
`));let{AgentInterruptedError:N,AuditLogger:y,calculateCost:oe,createDefaultToolRegistry:K,createAuditBackedPermissionEngine:W,createDelegatedXenoAgent:Z,createXenoAgent:le,MCPManager:ce,matchesMcpRegistryEntryPolicy:X,normalizeSubagentBranchPolicy:q,resolveSubagentRemoteMcpAccess:Q,resetAllPersistentShellSessions:ye,runDelegatedXenoTurn:ee,syncMcpToolsToRegistry:Se}=await Promise.resolve().then(()=>(Wt(),R)),me=process.cwd(),de=new Date,Ee=de.toISOString().replace(/[^0-9]/g,"").slice(0,14),pe=hp(me,".xeno","audit",`run-${Ee}-${process.pid}.jsonl`),te=new y({filePath:pe}),Re=pd(process.env.XENO_REQUIRED_OUTPUT_PATHS_JSON,me),Ce=Re.length>0?[]:md(t,me),Ae=un([...Re,...Ce],me),xe=process.env.XENO_BENCHMARK_MODE?.trim().toLowerCase()==="terminal-bench"||/\blive benchmark task container\b|\bterminal-bench\b/i.test(t),Te=Ux(xe,de),Ne=rn({explicitBaseURL:e.baseUrl,configuredBaseURL:xe?void 0:Pe.baseURL,benchmarkMode:xe}),Xe=lo("XENO_EXTERNAL_AGENT_TIMEOUT_SEC",0,0);xe&&(process.env.XENO_RUN_STARTED_AT_MS=String(Te.getTime()));let He=Ad({requiredOutputPaths:Ae,prompt:t,cwd:me,...xe?{benchmarkMode:!0}:{},startedAtMs:Te.getTime(),...xe&&Xe>0?{externalTimeoutMs:Xe*1e3}:{}}),rt=Ru({taskPrompt:t,benchmarkMode:xe,requiredOutputPaths:Ae}),Y={toolMiddleware:rt.toolMiddleware,promptSections:rt.promptSections,completionGuards:rt.completionGuards},D=ie=>{let ue=rt.getExecutionGovernanceSummary()?.completionDecision??null;return/\[Max iterations reached\]/.test(ie)?{status:"incomplete",reason:"max_iterations",finalStateVerified:ue?.finalStateVerified??!1,message:ue&&ue.action!=="complete"?`Agent stopped after reaching the max iterations limit. ${ue.message}`:"Agent stopped after reaching the max iterations limit without an explicit completion signal."}:ue?{status:ue.action==="complete"?"completed":"incomplete",reason:ue.reason,finalStateVerified:ue.finalStateVerified,message:ue.message}:{status:"completed",finalStateVerified:!1}},H=qx(xe),M=(ie,ue={})=>{m&&process.stdout.write(JSON.stringify({type:ie,...ue})+`
|
|
2638
|
+
`)},U=!process.stdin.isTTY||process.env.XENO_FORCE_AUTO_DENY_PROMPTS==="1",G=U?async()=>"deny":void 0;U&&ae!=="bypassPermissions"&&!g&&process.stderr.write(`[permissions] Non-interactive mode: prompt-required actions are auto-denied.
|
|
2639
|
+
`);let fe=W({mode:ae,cwd:me,promptFn:G,auditLogger:te,fallbackTraceId:`run-${Ee}`}),ze="",Vt=async({prompt:ie})=>(ze||(ze=(await le({cwd:me,apiKey:s,baseURL:Ne,model:n,maxTokens:r,maxIterations:o,requesterLabel:"Agent",executionMode:u,permissionEngine:fe,memory:{projectSessionContext:{limit:i,maxTokens:a,maxCharsPerSession:l}},session:{auditLogger:te},...Y})).systemPrompt),{output:await(await Z({cwd:me,apiKey:s,baseURL:Ne,model:n,maxTokens:Math.max(512,Math.min(r,4096)),maxIterations:Math.max(3,Math.min(o,12)),parentSystemPrompt:ze,parentExecutionMode:u,subagentRole:"explorer",permissionEngine:fe})).agent.run(ie)}),ut,Pt=()=>{let ie=K({cwd:me,dispatchAgent:Vt});return ut&&Se(ut,ie),ie},zn=(ie,ue)=>{let _e=K({cwd:me});if(ut){let h=Q(ue,ie);Se(ut,_e,[],O=>X(O,h))}return _e},pn=Pt();if(M("run_start",{cwd:me,model:n,prompt:t,execution_mode:u,delegation_enabled:b,mcp_enabled:v}),v){ut=new ce;let ie=await ut.connectConfiguredServers({cwd:me});if(Se(ut,pn),M("mcp_connect",{connected:ie.connected.length,skipped:ie.skipped.length,denied:ie.denied.length,errors:ie.errors.length}),!g){let ue=[];ie.connected.length>0&&ue.push(`connected ${ie.connected.length}`),ie.skipped.length>0&&ue.push(`skipped ${ie.skipped.length}`),ie.denied.length>0&&ue.push(`denied ${ie.denied.length}`),ie.errors.length>0&&ue.push(`errors ${ie.errors.length}`),ue.length>0&&process.stderr.write(`[mcp] ${ue.join(", ")}
|
|
2640
|
+
`)}}let wt="",at,vt=!1,qt=!1,$t=!1,ft=null,Lt=null,Rt={input:0,output:0,total:0},en,Ht,F,et=`run-${Ee}-${Bx().slice(0,8)}`,ht=q({mode:C,teamPreset:$,roles:E,rolePrecedence:re,remoteMcpByRole:I,...T!==void 0?{maxConcurrentBranches:T}:{}});try{if(b){ze||(ze=(await le({cwd:me,apiKey:s,baseURL:Ne,model:n,maxTokens:r,maxIterations:o,requesterLabel:"Agent",executionMode:u,permissionEngine:fe,memory:{projectSessionContext:{limit:i,maxTokens:a,maxCharsPerSession:l}},session:{auditLogger:te},...Y})).systemPrompt),g||process.stderr.write(`[delegate] multi-agent workflow enabled (${ht.mode}, max ${ht.maxConcurrentBranches??ht.roles.length} concurrent)
|
|
2641
|
+
`);let ie=await ee({userPrompt:t,cwd:me,apiKey:s,baseURL:Ne,model:n,maxIterations:o,maxTotalTokens:w,timeoutMs:P,rolePrecedence:re,branchPolicy:{mode:C,teamPreset:$,roles:E,remoteMcpByRole:I,...T!==void 0?{maxConcurrentBranches:T}:{}},parentSystemPrompt:ze,parentExecutionMode:u,permissionEngine:fe,auditLogger:te,rootTraceId:et,createBranchAgent:async({task:ue})=>(await Z({cwd:me,apiKey:s,baseURL:Ne,model:n,maxTokens:ue.maxTokens,maxIterations:ue.maxIterations,parentSystemPrompt:ze,parentExecutionMode:u,subagentRole:ue.role,permissionEngine:fe,toolRegistry:zn(ue.role,ht),...te?{session:{auditLogger:te}}:{},...m?{onIteration:(_e,h)=>{M("branch_iteration",{task_id:ue.id,role:ue.role,iteration:_e,total_tokens:h})},onToolStart:(_e,h)=>{M("branch_tool_start",{task_id:ue.id,role:ue.role,name:_e,input:h})},onToolEnd:(_e,h)=>{M("branch_tool_end",{task_id:ue.id,role:ue.role,name:_e,success:h.success,output:h.output,...h.error?{error:h.error}:{}})}}:{}})).agent,onBranchStart:async ue=>{M("branch_start",{task_id:ue.id,role:ue.role}),g||process.stderr.write(`[delegate] running ${ue.role}
|
|
2642
|
+
`)},onBranchComplete:async(ue,_e)=>{M("branch_complete",{task_id:ue.id,role:ue.role,trace_id:_e.traceId,token_usage:_e.tokenUsage})},onBranchError:async(ue,_e,h)=>{M("branch_error",{task_id:ue.id,role:ue.role,error:_e instanceof Error?_e.message:String(_e),token_usage:h.tokenUsage})}});F={enabled:!0,selected_from:ie.workflow.reduced.selectedFrom,summary:ie.summary},wt=ie.answer,Lt=ie.selectedTraceId??ie.rootTraceId,Rt=ie.tokenUsage,M("delegation_selected",{selected_from:ie.workflow.reduced.selectedFrom,confidence:ie.workflow.reduced.confidence,reason:ie.workflow.reduced.selectionReason}),!g&&ie.workflow.reduced.selectedFrom&&process.stderr.write(`[delegate] selected ${ie.workflow.reduced.selectedFrom.role} (${ie.workflow.reduced.selectedFrom.id})
|
|
2643
|
+
`)}else for(let ie=0;;ie+=1){let ue=(await le({cwd:me,apiKey:s,baseURL:Ne,model:n,maxTokens:r,maxIterations:o,requesterLabel:"Agent",executionMode:u,permissionEngine:fe,toolRegistry:pn,memory:{projectSessionContext:{limit:i,maxTokens:a,maxCharsPerSession:l}},session:{auditLogger:te},completionGuard:He,...Y,...He?{maxCompletionGuardReminders:xe?5:3}:{},...He?{progressGuardEveryIterations:xe?3:8}:{},...g?m?{onText:_e=>M("text",{delta:_e}),onIteration:_e=>M("iteration",{iteration:_e}),onToolStart:(_e,h)=>{M("tool_start",{name:_e,input:h})},onToolEnd:(_e,h)=>{M("tool_end",{name:_e,success:h.success,output:h.output,...h.error?{error:h.error}:{}})}}:{}:{onText:_e=>process.stdout.write(_e),onToolStart:_e=>{process.stderr.write(`[tool] ${_e}
|
|
2644
|
+
`)},onToolEnd:(_e,h)=>{process.stderr.write(`[tool] ${_e}: ${h.success?"ok":"error"}
|
|
2645
|
+
`)}}})).agent;ze=ue.systemPrompt;try{wt=await ue.run(t),Lt=ue.lastTraceId,Rt=ue.tokenUsage,Ht=ue.messages.length,ft=D(wt),en=rt.getExecutionGovernanceSummary()??void 0,ft?.status==="incomplete"?($t=!0,at=ft.message):xe&&He&&ft?.status==="completed"&&ft.finalStateVerified===!1&&($t=!0,at="Agent stopped without an explicit completion-guard final-state proof.");break}catch(_e){let h=_e instanceof Error?_e.message:String(_e);if(!(ue.tokenUsage.total===0&&ue.messages.length===0&&oa(h)&&ie<H.maxAttempts)){let A=He?await He({iteration:ue.messages.length,messages:[...ue.messages],stopReason:"transport_error",elapsedMs:Math.max(0,Date.now()-Te.getTime()),...xe&&Xe>0?{externalTimeoutMs:Xe*1e3}:{}}):null;if(Id({benchmarkMode:xe,errorMessage:h,requiredOutputPaths:Ae,completionGuardDecision:A})){wt=A&&typeof A!="string"&&A.stop?A.message:"Provider transport failed after required outputs were created. Preserving the current filesystem state for verification.",Lt=ue.lastTraceId,Rt=ue.tokenUsage,Ht=ue.messages.length,ft=D(wt??""),en=rt.getExecutionGovernanceSummary()??void 0,await te.append({trace_id:et,event_type:"run_transport_recovered",actor:"system",risk_level:"none",status:"ok",reason:"Recovered late provider transport failure after required outputs were present",metadata:{attempt:ie+1,raw_error:h,required_output_paths:Ae,completion_guard_stop:A&&typeof A!="string"?A.stop===!0:!1}});break}throw _e}let k=Hx(ie,h,H);await te.append({trace_id:et,event_type:"run_retry_scheduled",actor:"system",risk_level:"none",status:"error",reason:"Transient provider/bootstrap failure before work started",metadata:{attempt:ie+1,next_attempt:ie+2,delay_ms:k,raw_error:h}}),M("run_retry",{attempt:ie+1,next_attempt:ie+2,delay_ms:k,error:h}),g||process.stderr.write(`[run] transient provider failure before work started; retrying in ${k}ms (attempt ${ie+2}/${H.maxAttempts+1})
|
|
2646
|
+
`),await jx(k)}}}catch(ie){ie instanceof N?(vt=!0,at="Interrupted by user"):(qt=!0,at=ie instanceof Error?ie.message:String(ie))}finally{try{ye()}catch{}try{ut?.dispose()}catch{}await te.flush()}let zt=await te.read(),St=Yc(zt);!$t&&/\[Max iterations reached\]/.test(wt)&&($t=!0,at=at||"Agent reached max iterations before verified completion.");let Nt=Jc({interrupted:vt,hadError:qt,incomplete:$t,permissionDeniedCount:St.permission_denied}),Pn=xe&&Nt==="incomplete"&&!qt&&!vt&&ft?.status==="completed",tn=Qc(Nt,{nonFatalIncomplete:Pn}),vs=new Date().toISOString(),Tn=oe(n,Rt.input,Rt.output);(0,B.setProjectLastSessionSummary)(me,{mode:"run",status:Nt,model:n,startedAt:Te.toISOString(),endedAt:vs,durationMs:Math.max(0,Date.parse(vs)-Te.getTime()),...Ht!==void 0?{messageCount:Ht}:{},tokenUsage:Rt,estimatedCostUsd:Tn});let mn={status:Nt,answer:wt,...at?{error:at}:{},...ft?{termination:ft}:{},trace_id:Lt,audit_file:pe,token_usage:Rt,tool_summary:St,...en?{governance:en}:{},estimated_cost_usd:Tn,...F?{delegation:F}:{}};if(f?process.stdout.write(JSON.stringify(mn)+`
|
|
2647
|
+
`):m?M("run_complete",mn):(!qt&&!vt&&process.stdout.write(`
|
|
2648
|
+
`),qt&&at?console.error(`Error: ${at}`):vt?process.stderr.write(`Interrupted.
|
|
2649
|
+
`):Nt==="incomplete"&&at?process.stderr.write(`[run] Incomplete: ${at}
|
|
2650
|
+
`):Nt==="permission_denied"&&process.stderr.write(`[run] Completed with permission denials.
|
|
2651
|
+
`),process.stderr.write(`[audit] ${pe}
|
|
2652
|
+
`)),tn!==0&&(process.exitCode=tn),process.env.XENO_FORCE_EXIT_AFTER_RUN==="1"){let ie=ha(Zt.backgroundProcessManager);!g&&(ie.stopped.length>0||ie.failed.length>0)&&process.stderr.write(`[run] background shutdown: stopped ${ie.stopped.length}, preserved ${ie.preserved.length}, failed ${ie.failed.length}
|
|
2653
|
+
`),await Promise.allSettled([mp(process.stdout),mp(process.stderr)]),process.exit(tn)}});je.addCommand(Hs);je.command("init").description("Initialize project for AI-assisted development").option("-y, --yes","Use detected defaults without prompting").action(async t=>{await Ar({yes:!!t.yes,cwd:process.cwd()})});je.command("review").description("AI code review of recent changes").option("--staged","Review only staged changes").option("--range <range>","Review specific commit range (e.g. HEAD~5..HEAD)").option("--files <pattern>","Review specific files").option("--focus <area>","Focus on: security, performance").option("-m, --model <model>","AI model to use").option("-k, --api-key <key>","API key").option("--base-url <url>","API base URL").option("--max-tokens <n>","Max response tokens").action(async t=>{let e=t.model||Pe.model||we.DEFAULT_MODEL,n=ts(t.apiKey,process.env.XENO_API_KEY,Pe.apiKey,we.DEFAULT_API_KEY),s=rn({explicitBaseURL:t.baseUrl,configuredBaseURL:Pe.baseURL}),r=t.maxTokens?parseInt(t.maxTokens,10):Pe.maxTokens??rr;await jl({staged:!!t.staged,range:t.range,files:t.files,focus:t.focus,model:e,apiKey:n,baseURL:s,maxTokens:r,cwd:process.cwd()})});je.command("completions <shell>").description("Generate shell completion scripts (bash, zsh, fish)").action(t=>{switch(t.toLowerCase()){case"bash":process.stdout.write(cp());break;case"zsh":process.stdout.write(up());break;case"fish":process.stdout.write(dp());break;default:console.error(`Unknown shell: ${t}. Supported: bash, zsh, fish`),process.exit(1)}});(0,R.installSignalHandlers)();je.parseAsync().catch(t=>{let e=t instanceof Error?t.message:String(t);console.error(`Error: ${e}`),process.exitCode=1});
|