nex-code 0.3.43 → 0.3.56

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.
Files changed (3) hide show
  1. package/README.md +245 -37
  2. package/dist/nex-code.js +547 -405
  3. package/package.json +12 -2
package/dist/nex-code.js CHANGED
@@ -1,143 +1,150 @@
1
1
  #!/usr/bin/env node
2
- var L=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var In=L((j$,uu)=>{uu.exports={name:"nex-code",version:"0.3.43",description:"The open-source agentic coding CLI. Free with Ollama Cloud \u2014 switch to OpenAI, Anthropic or Gemini anytime. Alternative to Claude Code & Gemini CLI.",bin:{"nex-code":"./dist/nex-code.js"},files:["dist/","README.md","LICENSE"],engines:{node:">=18.0.0"},scripts:{start:"node dist/nex-code.js",build:"esbuild bin/nex-code.js --bundle --platform=node --target=node18 --outfile=dist/nex-code.js --minify --external:axios --external:dotenv --external:playwright",test:"jest --coverage","test:watch":"jest --watch",format:"prettier --write .","install-hooks":"ln -sf ../../hooks/pre-push .git/hooks/pre-push && chmod +x .git/hooks/pre-push && ln -sf ../../hooks/post-merge .git/hooks/post-merge && chmod +x .git/hooks/post-merge && echo 'Hooks installed (pre-push, post-merge).'",prepublishOnly:"npm run build && npm test",release:"npm version patch && git push --follow-tags && npm publish"},keywords:["ai","cli","coding","agent","ollama","ollama-cloud","openai","anthropic","claude","gemini","llm","gpt","agentic","terminal","coding-assistant","claude-code-alternative","gemini-cli-alternative","open-source","free","qwen3","devstral","kimi-k2","deepseek","local-llm","mcp","model-context-protocol","multi-provider"],repository:{type:"git",url:"https://github.com/hybridpicker/nex-code.git"},bugs:{url:"https://github.com/hybridpicker/nex-code/issues"},homepage:"https://github.com/hybridpicker/nex-code#readme",license:"MIT",dependencies:{axios:"^1.7.0",dotenv:"^16.4.0"},devDependencies:{esbuild:"^0.27.3",jest:"^29.7.0"}}});var Xr=L((F$,Vr)=>{var M={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",white:"\x1B[37m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",gray:"\x1B[90m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",brightCyan:"\x1B[96m",brightMagenta:"\x1B[95m",brightBlue:"\x1B[94m"},Ks=5,jn=(()=>{let t=[];for(let e=0;e<Ks;e++)t.push(e);for(let e=Ks-2;e>=1;e--)t.push(e);return t})(),Jr=["\u273D","\u2726","\u2727","\u2726"],Ys=class{constructor(e="Thinking..."){this.text=e,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let e=jn[this.frame%jn.length],s="";for(let o=0;o<Ks;o++)s+=o===e?`${M.cyan}\u25CF${M.reset}`:" ";let n="";if(this.startTime){let o=Math.floor((Date.now()-this.startTime)/1e3);if(o>=60){let r=Math.floor(o/60),i=o%60;n=` ${M.dim}${r}m ${String(i).padStart(2,"0")}s${M.reset}`}else o>=1&&(n=` ${M.dim}${o}s${M.reset}`)}process.stderr.write(`\x1B[2K\r${s} ${M.dim}${this.text}${M.reset}${n}`),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),process.stderr.isTTY&&(process.stderr.write("\x1B[?25l"),this._render(),this.interval=setInterval(()=>this._render(),100))}update(e){this.text=e}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),process.stderr.isTTY&&process.stderr.write("\x1B[2K\r\x1B[?25h"),this.startTime=null}},Js=class{constructor(e){this.labels=e,this.statuses=e.map(()=>"running"),this.frame=0,this.interval=null,this.startTime=null,this.lineCount=e.length}_formatElapsed(){if(!this.startTime)return"";let e=Math.floor((Date.now()-this.startTime)/1e3);if(e<1)return"";let s=Math.floor(e/60),n=e%60;return s>0?`${s}m ${String(n).padStart(2,"0")}s`:`${n}s`}_render(){if(this._stopped)return;let e=jn[this.frame%jn.length],s=`${M.cyan}\u25CF${M.reset}`,n=`${M.dim}\u25CB${M.reset}`,o=this._formatElapsed(),r=o?` ${M.dim}${o}${M.reset}`:"",i="";for(let c=0;c<this.labels.length;c++){let l,u;switch(this.statuses[c]){case"done":l=`${M.green}\u2713${M.reset}`,u=M.dim;break;case"error":l=`${M.red}\u2717${M.reset}`,u=M.dim;break;default:l=c===e?s:" ",u=""}let d=c===this.labels.length-1?r:"";i+=`\x1B[2K ${l} ${u}${this.labels[c]}${M.reset}${d}
2
+ var j=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var fs=j((i0,Dd)=>{Dd.exports={name:"nex-code",version:"0.3.56",description:"The open-source agentic coding CLI. Free with Ollama Cloud \u2014 switch to OpenAI, Anthropic or Gemini anytime. Alternative to Claude Code & Gemini CLI.",bin:{"nex-code":"./dist/nex-code.js"},files:["dist/","README.md","LICENSE"],engines:{node:">=18.0.0"},scripts:{start:"node dist/nex-code.js",build:"esbuild bin/nex-code.js --bundle --platform=node --target=node18 --outfile=dist/nex-code.js --minify --external:axios --external:dotenv --external:playwright",test:"jest --forceExit",coverage:"jest --coverage --forceExit","test:watch":"jest --watch",format:"prettier --write .","install-hooks":"ln -sf ../../hooks/pre-push .git/hooks/pre-push && chmod +x .git/hooks/pre-push && ln -sf ../../hooks/post-merge .git/hooks/post-merge && chmod +x .git/hooks/post-merge && echo 'Hooks installed (pre-push, post-merge).'",prepublishOnly:"npm run build && npm test",release:"npm version patch && git push --follow-tags && npm publish"},keywords:["ai","cli","coding","agent","ollama","ollama-cloud","openai","anthropic","claude","gemini","llm","gpt","agentic","terminal","coding-assistant","claude-code-alternative","gemini-cli-alternative","open-source","free","qwen3","devstral","kimi-k2","deepseek","local-llm","mcp","model-context-protocol","multi-provider"],repository:{type:"git",url:"https://github.com/hybridpicker/nex-code.git"},bugs:{url:"https://github.com/hybridpicker/nex-code/issues"},homepage:"https://github.com/hybridpicker/nex-code#readme",license:"MIT",dependencies:{axios:"^1.7.0",dotenv:"^16.4.0"},devDependencies:{esbuild:"^0.27.3",jest:"^29.7.0"},jest:{coverageThreshold:{"./cli/sub-agent.js":{lines:70,functions:65,branches:55}}}}});var Lt=j((a0,Gi)=>{"use strict";var qi="\x1B[0m",Fi="\x1B[1m",nn="\x1B[2m";function A(t,e,s){return`\x1B[38;2;${t};${e};${s}m`}function qd(){if(!process.stdout.isTTY)return null;try{let{execFileSync:t}=require("child_process"),e=["import sys,os,tty,termios,select","f=open('/dev/tty','r+b',buffering=0)","fd=f.fileno()","s=termios.tcgetattr(fd)","try:"," tty.setraw(fd)"," f.write(bytes([0x1b,0x5d,0x31,0x31,0x3b,0x3f,0x1b,0x5c]))"," r=select.select([fd],[],[],0.1)[0]"," d=b''"," if r:"," while True:"," r2=select.select([fd],[],[],0.05)[0]"," if not r2:break"," c=os.read(fd,1)"," d+=c"," if d[-1:]==bytes([0x07]) or d[-2:]==bytes([0x1b,0x5c]):break"," sys.stdout.buffer.write(d)","finally:"," termios.tcsetattr(fd,termios.TCSADRAIN,s)"," f.close()"].join(`
3
+ `),n=t("python3",["-c",e],{encoding:"buffer",timeout:400,stdio:["ignore","pipe","ignore"]}).toString("utf8").match(/rgb:([0-9a-fA-F]+)\/([0-9a-fA-F]+)\/([0-9a-fA-F]+)/);if(n){let r=parseInt(n[1].slice(0,2),16),i=parseInt(n[2].slice(0,2),16),c=parseInt(n[3].slice(0,2),16);return .299*r+.587*i+.114*c<128}}catch{}return null}function Ui(){let t=require("os");return require("path").join(t.homedir(),".nex-code",".theme_cache.json")}function Fd(t){try{let s=require("fs").readFileSync(Ui(),"utf8"),o=JSON.parse(s);if(o&&typeof o[t]=="boolean")return o[t]}catch{}return null}function Ud(t,e){try{let s=require("fs"),o=require("path"),n=Ui(),r=o.dirname(n),i={};try{i=JSON.parse(s.readFileSync(n,"utf8"))}catch{}i[t]=e;let c=Object.keys(i);c.length>50&&c.slice(0,c.length-50).forEach(l=>delete i[l]),s.existsSync(r)||s.mkdirSync(r,{recursive:!0}),s.writeFileSync(n,JSON.stringify(i),"utf8")}catch{}}function Wd(){let t=(process.env.NEX_THEME||"").toLowerCase();if(t==="light")return!1;if(t==="dark")return!0;let e=process.env.COLORFGBG;if(e){let i=e.split(";"),c=parseInt(i[i.length-1],10);if(!isNaN(c))return c<8}let s=process.env.TERM_SESSION_ID||"default",o=Fd(s);if(o!==null)return o;let n=qd(),r=n!==null?n:!0;return Ud(s,r),r}var Wi=Wd(),Bi={reset:qi,bold:Fi,dim:nn,primary:A(80,190,255),secondary:A(60,170,190),success:A(80,210,120),warning:A(245,175,50),error:A(230,80,80),muted:nn,subtle:A(130,130,145),tool_read:A(80,190,255),tool_write:A(245,165,55),tool_exec:A(185,100,235),tool_search:A(70,185,190),tool_git:A(90,210,100),tool_web:A(100,215,250),tool_sysadmin:A(225,150,75),tool_default:A(100,205,115),syn_keyword:A(185,100,235),syn_string:A(90,210,120),syn_number:A(245,175,50),syn_comment:nn,syn_key:A(80,190,255),diff_add:A(80,210,120),diff_rem:A(230,80,80),banner_logo:A(80,200,255),banner_name:A(80,200,255),banner_version:nn,banner_model:nn,banner_yolo:A(245,175,50),footer_sep:nn,footer_model:A(80,175,235),footer_branch:A(80,210,100),footer_project:A(130,130,145),footer_divider:A(80,80,95),white:"\x1B[37m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",gray:"\x1B[90m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",diff_add_bg:"\x1B[48;2;10;46;20m",diff_rem_bg:"\x1B[48;2;58;16;16m",brightCyan:"\x1B[96m",brightMagenta:"\x1B[95m",brightBlue:"\x1B[94m"},Hi={reset:qi,bold:Fi,dim:A(110,110,120),primary:A(0,110,190),secondary:A(0,125,148),success:A(0,148,62),warning:A(168,92,0),error:A(188,32,32),muted:A(110,110,120),subtle:A(155,155,165),tool_read:A(0,110,190),tool_write:A(168,92,0),tool_exec:A(128,42,188),tool_search:A(0,122,148),tool_git:A(0,138,62),tool_web:A(0,112,178),tool_sysadmin:A(168,82,0),tool_default:A(0,138,62),syn_keyword:A(128,42,188),syn_string:A(0,138,62),syn_number:A(168,92,0),syn_comment:A(135,135,148),syn_key:A(0,110,190),diff_add:A(0,148,62),diff_rem:A(188,32,32),banner_logo:A(0,122,205),banner_name:A(0,122,205),banner_version:A(100,100,118),banner_model:A(100,100,118),banner_yolo:A(168,62,0),footer_sep:A(168,168,178),footer_model:A(0,102,175),footer_branch:A(0,138,62),footer_project:A(135,135,148),footer_divider:A(168,168,178),white:A(40,40,52),red:A(188,32,32),green:A(0,148,62),yellow:A(168,92,0),blue:A(0,110,190),magenta:A(128,42,188),cyan:A(0,125,148),gray:A(132,132,142),bgRed:"\x1B[41m",bgGreen:"\x1B[42m",diff_add_bg:"\x1B[48;2;215;245;220m",diff_rem_bg:"\x1B[48;2;255;215;215m",brightCyan:A(0,158,182),brightMagenta:A(158,52,208),brightBlue:A(0,112,208)},Bd=Wi?Bi:Hi;Gi.exports={T:Bd,isDark:Wi,DARK:Bi,LIGHT:Hi}});var Cn=j((c0,zi)=>{var{T:P}=Lt(),hs=5,sn=(()=>{let t=[];for(let e=0;e<hs;e++)t.push(e);for(let e=hs-2;e>=1;e--)t.push(e);return t})(),Ki=["\u273D","\u2726","\u2727","\u2726"],No=class{constructor(e="Thinking..."){this.text=e,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let e=sn[this.frame%sn.length],s="";for(let n=0;n<hs;n++)s+=n===e?`${P.cyan}\u25CF${P.reset}`:" ";let o="";if(this.startTime){let n=Math.floor((Date.now()-this.startTime)/1e3);if(n>=60){let r=Math.floor(n/60),i=n%60;o=` ${P.dim}${r}m ${String(i).padStart(2,"0")}s${P.reset}`}else n>=1&&(o=` ${P.dim}${n}s${P.reset}`)}process.stderr.write(`\x1B[2K\r${s} ${P.dim}${this.text}${P.reset}${o}`),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),process.stderr.isTTY&&(process.stderr.write("\x1B[?25l"),this._render(),this.interval=setInterval(()=>this._render(),100))}update(e){this.text=e}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),process.stderr.isTTY&&process.stderr.write("\x1B[2K\r\x1B[?25h"),this.startTime=null}},Po=class{constructor(e){this.labels=e,this.statuses=e.map(()=>"running"),this.frame=0,this.interval=null,this.startTime=null,this.lineCount=e.length}_formatElapsed(){if(!this.startTime)return"";let e=Math.floor((Date.now()-this.startTime)/1e3);if(e<1)return"";let s=Math.floor(e/60),o=e%60;return s>0?`${s}m ${String(o).padStart(2,"0")}s`:`${o}s`}_render(){if(this._stopped)return;let e=sn[this.frame%sn.length],s=`${P.cyan}\u25CF${P.reset}`,o=`${P.dim}\u25CB${P.reset}`,n=this._formatElapsed(),r=n?` ${P.dim}${n}${P.reset}`:"",i="";for(let c=0;c<this.labels.length;c++){let l,u;switch(this.statuses[c]){case"done":l=`${P.green}\u2713${P.reset}`,u=P.dim;break;case"error":l=`${P.red}\u2717${P.reset}`,u=P.dim;break;default:l=c===e?s:" ",u=""}let d=c===this.labels.length-1?r:"";i+=`\x1B[2K ${l} ${u}${this.labels[c]}${P.reset}${d}
3
4
  `}this.lineCount>0&&(i+=`\x1B[${this.lineCount}A`),process.stderr.write(i),this.frame++}start(){this._stopped=!1,this.startTime=Date.now();let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
4
- `;this.lineCount>0&&(e+=`\x1B[${this.lineCount}A`),process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),100)}update(e,s){e>=0&&e<this.statuses.length&&(this.statuses[e]=s)}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),this._renderFinal(),process.stderr.write("\x1B[?25h")}_renderFinal(){let e=this._formatElapsed(),s=e?` ${M.dim}${e}${M.reset}`:"",n="";for(let o=0;o<this.labels.length;o++){let r;switch(this.statuses[o]){case"done":r=`${M.green}\u2713${M.reset}`;break;case"error":r=`${M.red}\u2717${M.reset}`;break;default:r=`${M.yellow}\u25CB${M.reset}`}let i=o===this.labels.length-1?s:"";n+=`\x1B[2K ${r} ${M.dim}${this.labels[o]}${M.reset}${i}
5
- `}process.stderr.write(n)}},qn={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},Dn={done:M.green,in_progress:M.cyan,pending:M.dim,failed:M.red},ut=null,Vs=class{constructor(e,s){this.name=e,this.tasks=s.map(n=>({id:n.id,description:n.description,status:n.status||"pending"})),this.frame=0,this.interval=null,this.startTime=null,this.tokens=0,this.lineCount=1+this.tasks.length,this._paused=!1}_formatElapsed(){if(!this.startTime)return"";let e=Math.floor((Date.now()-this.startTime)/1e3);if(e<1)return"";let s=Math.floor(e/60),n=e%60;return s>0?`${s}m ${String(n).padStart(2,"0")}s`:`${n}s`}_formatTokens(){return this.tokens<=0?"":this.tokens>=1e3?`${(this.tokens/1e3).toFixed(1)}k`:String(this.tokens)}_render(){if(this._stopped)return;let e=Jr[this.frame%Jr.length],s=this._formatElapsed(),n=this._formatTokens(),o=[s,n?`\u2193 ${n} tokens`:""].filter(Boolean).join(" \xB7 "),r=o?` ${M.dim}(${o})${M.reset}`:"",i=`\x1B[2K${M.cyan}${e}${M.reset} ${this.name}\u2026${r}
6
- `;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=qn[l.status]||qn.pending,p=Dn[l.status]||Dn.pending,f=l.description.length>55?l.description.substring(0,52)+"...":l.description;i+=`\x1B[2K ${M.dim}${u}${M.reset} ${p}${d}${M.reset} ${f}
5
+ `;this.lineCount>0&&(e+=`\x1B[${this.lineCount}A`),process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),100)}update(e,s){e>=0&&e<this.statuses.length&&(this.statuses[e]=s)}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),this._renderFinal(),process.stderr.write("\x1B[?25h")}_renderFinal(){let e=this._formatElapsed(),s=e?` ${P.dim}${e}${P.reset}`:"",o="";for(let n=0;n<this.labels.length;n++){let r;switch(this.statuses[n]){case"done":r=`${P.green}\u2713${P.reset}`;break;case"error":r=`${P.red}\u2717${P.reset}`;break;default:r=`${P.yellow}\u25CB${P.reset}`}let i=n===this.labels.length-1?s:"";o+=`\x1B[2K ${r} ${P.dim}${this.labels[n]}${P.reset}${i}
6
+ `}process.stderr.write(o)}},ps={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},ms={done:P.green,in_progress:P.cyan,pending:P.dim,failed:P.red},kt=null,Mo=class{constructor(e,s){this.name=e,this.tasks=s.map(o=>({id:o.id,description:o.description,status:o.status||"pending"})),this.frame=0,this.interval=null,this.startTime=null,this.tokens=0,this.lineCount=1+this.tasks.length,this._paused=!1}_formatElapsed(){if(!this.startTime)return"";let e=Math.floor((Date.now()-this.startTime)/1e3);if(e<1)return"";let s=Math.floor(e/60),o=e%60;return s>0?`${s}m ${String(o).padStart(2,"0")}s`:`${o}s`}_formatTokens(){return this.tokens<=0?"":this.tokens>=1e3?`${(this.tokens/1e3).toFixed(1)}k`:String(this.tokens)}_render(){if(this._stopped)return;let e=Ki[this.frame%Ki.length],s=this._formatElapsed(),o=this._formatTokens(),n=[s,o?`\u2193 ${o} tokens`:""].filter(Boolean).join(" \xB7 "),r=n?` ${P.dim}(${n})${P.reset}`:"",i=`\x1B[2K${P.cyan}${e}${P.reset} ${this.name}\u2026${r}
7
+ `;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=ps[l.status]||ps.pending,f=ms[l.status]||ms.pending,m=l.description.length>55?l.description.substring(0,52)+"...":l.description;i+=`\x1B[2K ${P.dim}${u}${P.reset} ${f}${d}${P.reset} ${m}
7
8
  `}i+=`\x1B[${this.lineCount}A`,process.stderr.write(i),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),this._paused=!1;let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
8
- `;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),ut=this}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),this._paused||this._renderFinal(),process.stderr.write("\x1B[?25h"),this._paused=!1,ut===this&&(ut=null)}pause(){if(this._paused)return;this.interval&&(clearInterval(this.interval),this.interval=null);let e="";for(let s=0;s<this.lineCount;s++)e+=`\x1B[2K
9
+ `;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),kt=this}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),this._paused||this._renderFinal(),process.stderr.write("\x1B[?25h"),this._paused=!1,kt===this&&(kt=null)}pause(){if(this._paused)return;this.interval&&(clearInterval(this.interval),this.interval=null);let e="";for(let s=0;s<this.lineCount;s++)e+=`\x1B[2K
9
10
  `;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._paused=!0}resume(){if(!this._paused)return;this._paused=!1;let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
10
- `;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120)}updateTask(e,s){let n=this.tasks.find(o=>o.id===e);n&&(n.status=s)}setStats({tokens:e}){e!==void 0&&(this.tokens=e)}isActive(){return this.interval!==null||this._paused}_renderFinal(){let e=this._formatElapsed(),s=this.tasks.filter(c=>c.status==="done").length,n=this.tasks.filter(c=>c.status==="failed").length,o=this.tasks.length,r=n>0?`${s}/${o} done, ${n} failed`:`${s}/${o} done`,i=`\x1B[2K${M.green}\u2714${M.reset} ${this.name} ${M.dim}(${e} \xB7 ${r})${M.reset}
11
- `;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=qn[l.status]||qn.pending,p=Dn[l.status]||Dn.pending,f=l.description.length>55?l.description.substring(0,52)+"...":l.description;i+=`\x1B[2K ${M.dim}${u}${M.reset} ${p}${d}${M.reset} ${M.dim}${f}${M.reset}
12
- `}process.stderr.write(i)}};function du(t){ut=t}function fu(){return ut}function pu(){ut&&(ut.stop(),ut=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}Vr.exports={C:M,Spinner:Ys,MultiProgress:Js,TaskProgress:Vs,setActiveTaskProgress:du,getActiveTaskProgress:fu,cleanupTerminal:pu}});var ei=L((U$,Zr)=>{var C={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",white:"\x1B[37m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",gray:"\x1B[90m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",brightCyan:"\x1B[96m",brightMagenta:"\x1B[95m",brightBlue:"\x1B[94m"};function Qr(t){if(!t)return"";let e=t.replace(/^\.\//,"").split("/");return e.length>1?e.slice(-2).join("/"):e[0]}var mu={read_file:"\x1B[36m",list_directory:"\x1B[36m",write_file:"\x1B[33m",edit_file:"\x1B[33m",patch_file:"\x1B[33m",bash:"\x1B[35m",grep:"\x1B[34m",search_files:"\x1B[34m",glob:"\x1B[34m",git_commit:"\x1B[32m",git_push:"\x1B[32m",git_pull:"\x1B[32m",git_status:"\x1B[32m",git_diff:"\x1B[32m",git_log:"\x1B[32m",git_branch:"\x1B[32m",git_stash:"\x1B[32m",web_fetch:"\x1B[96m",web_search:"\x1B[96m"},Xs={read_file:"Read file",write_file:"Write",edit_file:"Update",patch_file:"Update",list_directory:"List directory",bash:"Run command",grep:"Search code",search_files:"Search files",glob:"Find files",web_fetch:"Fetch URL",web_search:"Web search",git_status:"Git status",git_diff:"Git diff",git_log:"Git log",git_commit:"Git commit",git_push:"Git push",git_pull:"Git pull",git_branch:"Git branch",git_stash:"Git stash",task_list:"Task list",spawn_agents:"Spawn agents",ask_user:"Ask user",switch_model:"Switch model",gh_run_list:"GH Actions",gh_run_view:"GH Actions",gh_workflow_trigger:"GH trigger",browser_open:"Browser open",browser_screenshot:"Screenshot",browser_click:"Browser click",browser_fill:"Browser fill",ssh_exec:"SSH exec",ssh_upload:"SSH upload",ssh_download:"SSH download",service_manage:"Service",service_logs:"Service logs",container_list:"Containers",container_logs:"Container logs",container_exec:"Container exec",brain_write:"Brain write",deploy:"Deploy"};function Fn(t,e=!1,s=null){if(e)return`${C.red}\u25CF${C.reset}`;let n=mu[t]||C.green;return s==="blink"?`${n}\x1B[5m\u25CF\x1B[25m${C.reset}`:`${n}${s!==null?s:"\u25CF"}${C.reset}`}function hu(t,e,s=!1,n=null){let o=(t||[]).filter(l=>l&&l.canExecute!==!1);if(o.length===0)return`${Fn("",s,n)} Step ${e}`;if(o.length===1){let l=o[0],u=l.args||{},d=Xs[l.fnName]||l.fnName.replace(/_/g," "),p="";u.path?p=Qr(u.path):u.command?p=String(u.command).substring(0,60):u.query?p=String(u.query).substring(0,50):u.pattern&&(p=String(u.pattern).substring(0,50));let f=p?`${C.dim}(${p})${C.reset}`:"";return`${Fn(l.fnName,s,n)} ${C.bold}${d}${C.reset} ${f}`}let r=o[0].fnName,i=[...new Set(o.map(l=>Xs[l.fnName]||l.fnName.replace(/_/g," ")))],c=i.length<=3?i.join(" \xB7 "):`${o.length} actions`;return`${Fn(r,s,n)} ${c}`}function gu(t,e){let s;switch(t){case"write_file":case"edit_file":case"patch_file":case"read_file":case"list_directory":s=Qr(e.path);break;case"bash":s=(e.command||"").substring(0,80);break;case"grep":case"search_files":s=e.pattern?`"${e.pattern}"${e.path?` in ${e.path}`:""}`:"";break;case"glob":s=e.pattern||"";break;case"web_fetch":s=(e.url||"").substring(0,60);break;case"web_search":s=(e.query||"").substring(0,50);break;default:s=JSON.stringify(e).substring(0,80)}let n=Xs[t]||t.replace(/_/g," "),o=s?` ${C.dim}(${s})${C.reset}`:"";return`${Fn(t)} ${C.bold}${n}${C.reset}${o}`}function $u(t,e=8){let s=t.split(`
13
- `),n=s.slice(0,e),o=s.length-e,r=`${C.dim} \u2514 ${C.reset}`,i=" ",c=n.map((l,u)=>`${u===0?r:i}${C.green}${l}${C.reset}`).join(`
14
- `);return o>0&&(c+=`
15
- ${C.gray} \u2026 +${o} lines${C.reset}`),c}function yu(t,e){switch(t){case"bash":case"ask_user":case"write_file":case"edit_file":case"patch_file":case"task_list":case"spawn_agents":return null;case"read_file":return`Reading: ${e.path||"file"}`;case"list_directory":return`Listing: ${e.path||"."}`;case"search_files":return`Searching: ${e.pattern||"..."}`;case"glob":return`Glob: ${e.pattern||"..."}`;case"grep":return`Grep: ${e.pattern||"..."}`;case"web_fetch":return`Fetching: ${(e.url||"").substring(0,60)}`;case"web_search":return`Searching web: ${(e.query||"").substring(0,50)}`;case"git_status":return"Git status...";case"git_diff":return`Git diff${e.file?`: ${e.file}`:""}...`;case"git_log":return`Git log${e.file?`: ${e.file}`:""}...`;case"gh_run_list":return`GitHub Actions: listing runs${e.workflow?` (${e.workflow})`:""}...`;case"gh_run_view":return`GitHub Actions: run ${e.run_id}...`;case"gh_workflow_trigger":return`GitHub Actions: trigger ${e.workflow}...`;case"browser_open":return`Browser: opening ${(e.url||"").substring(0,60)}...`;case"browser_screenshot":return`Browser: screenshot ${(e.url||"").substring(0,60)}...`;case"browser_click":return`Browser: clicking ${e.text||e.selector||"element"}...`;case"browser_fill":return`Browser: filling ${e.selector||"field"}...`;default:return`Running: ${t}`}}function wu(t,e,s,n){let o=String(s||"");if(n){let i=o.split(`
16
- `)[0].replace(/^ERROR:\s*/i,"").substring(0,80),c=o.match(/\nHINT: (.+)/),l=c?`
17
- ${C.dim}${c[1].substring(0,100)}${C.reset}`:"";return` ${C.red}\u2514 ${i}${C.reset}${l}`}let r;switch(t){case"read_file":{let i=o.split(`
18
- `).filter(Boolean),c=i.length,l=i[i.length-1],u=l?parseInt(l.match(/^(\d+):/)?.[1]||"0"):0,d=e.line_start||e.line_end,p=(i[0]||"").replace(/^\d+:\s*/,"").trim(),f=p?` ${C.dim}\u2014 ${p.substring(0,60)}${p.length>60?"\u2026":""}${C.reset}`:"";d&&u>c?r=`Read lines ${e.line_start||1}\u2013${u}${f}`:r=`Read ${c} line${c!==1?"s":""}${f}`;break}case"write_file":{let i=(e.content||"").split(`
19
- `).length;r=`Wrote ${i} line${i!==1?"s":""}`;break}case"edit_file":{let i=(e.old_text||"").split(`
11
+ `;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120)}updateTask(e,s){let o=this.tasks.find(n=>n.id===e);o&&(o.status=s)}setStats({tokens:e}){e!==void 0&&(this.tokens=e)}isActive(){return this.interval!==null||this._paused}_renderFinal(){let e=this._formatElapsed(),s=this.tasks.filter(c=>c.status==="done").length,o=this.tasks.filter(c=>c.status==="failed").length,n=this.tasks.length,r=o>0?`${s}/${n} done, ${o} failed`:`${s}/${n} done`,i=`\x1B[2K${P.green}\u2714${P.reset} ${this.name} ${P.dim}(${e} \xB7 ${r})${P.reset}
12
+ `;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=ps[l.status]||ps.pending,f=ms[l.status]||ms.pending,m=l.description.length>55?l.description.substring(0,52)+"...":l.description;i+=`\x1B[2K ${P.dim}${u}${P.reset} ${f}${d}${P.reset} ${P.dim}${m}${P.reset}
13
+ `}process.stderr.write(i)}},Io=class{constructor(e,s){this.toolName=e,this.message=s||`Running ${e}...`,this.count=0,this.total=null,this.detail="",this.frame=0,this.interval=null,this.startTime=null,this._stopped=!1}_render(){if(this._stopped||!process.stderr.isTTY)return;let e=sn[this.frame%sn.length],s="";for(let r=0;r<hs;r++)s+=r===e?`${P.cyan}\u25CF${P.reset}`:" ";let o=this.message;this.count>0&&(o+=` ${P.cyan}${this.count}${P.reset}`,this.total&&(o+=`/${this.total}`),this.detail&&(o+=` ${P.dim}${this.detail}${P.reset}`));let n="";if(this.startTime){let r=Math.floor((Date.now()-this.startTime)/1e3);r>=1&&(n=` ${P.dim}${r}s${P.reset}`)}process.stderr.write(`\x1B[2K\r${s} ${P.dim}${o}${P.reset}${n}`),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),process.stderr.isTTY&&(process.stderr.write("\x1B[?25l"),this._render(),this.interval=setInterval(()=>this._render(),100))}update(e){e.count!==void 0&&(this.count=e.count),e.total!==void 0&&(this.total=e.total),e.detail!==void 0&&(this.detail=e.detail),e.message!==void 0&&(this.message=e.message)}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),process.stderr.isTTY&&process.stderr.write("\x1B[2K\r\x1B[?25h")}};function Hd(t){kt=t}function Gd(){return kt}function Kd(){kt&&(kt.stop(),kt=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}zi.exports={C:P,Spinner:No,MultiProgress:Po,TaskProgress:Mo,ToolProgress:Io,setActiveTaskProgress:Hd,getActiveTaskProgress:Gd,cleanupTerminal:Kd}});var Ji=j((l0,Xi)=>{var{T:v}=Lt(),Ye=v;function Yi(t){if(!t)return"";let e=t.replace(/^\.\//,"").split("/");return e.length>1?e.slice(-2).join("/"):e[0]}var zd={read_file:v.tool_read,list_directory:v.tool_read,write_file:v.tool_write,edit_file:v.tool_write,patch_file:v.tool_write,bash:v.tool_exec,grep:v.tool_search,search_files:v.tool_search,glob:v.tool_search,git_commit:v.tool_git,git_push:v.tool_git,git_pull:v.tool_git,git_status:v.tool_git,git_diff:v.tool_git,git_log:v.tool_git,git_branch:v.tool_git,git_stash:v.tool_git,web_fetch:v.tool_web,web_search:v.tool_web,sysadmin:v.tool_sysadmin,ssh_exec:v.tool_sysadmin,ssh_upload:v.tool_sysadmin,ssh_download:v.tool_sysadmin,deploy:v.tool_sysadmin},Lo={read_file:"Read file",write_file:"Write",edit_file:"Update",patch_file:"Update",list_directory:"List directory",bash:"Run command",grep:"Search code",search_files:"Search files",glob:"Find files",web_fetch:"Fetch URL",web_search:"Web search",git_status:"Git status",git_diff:"Git diff",git_log:"Git log",git_commit:"Git commit",git_push:"Git push",git_pull:"Git pull",git_branch:"Git branch",git_stash:"Git stash",task_list:"Task list",spawn_agents:"Spawn agents",ask_user:"Ask user",switch_model:"Switch model",gh_run_list:"GH Actions",gh_run_view:"GH Actions",gh_workflow_trigger:"GH trigger",browser_open:"Browser open",browser_screenshot:"Screenshot",browser_click:"Browser click",browser_fill:"Browser fill",ssh_exec:"SSH exec",ssh_upload:"SSH upload",ssh_download:"SSH download",service_manage:"Service",service_logs:"Service logs",container_list:"Containers",container_logs:"Container logs",container_exec:"Container exec",brain_write:"Brain write",deploy:"Deploy",frontend_recon:"Frontend recon"};function gs(t,e=!1,s=null){if(e)return`${v.error}\u25CF${v.reset}`;let o=zd[t]||v.tool_default;return s==="blink"?`${o}\x1B[5m\u25CF\x1B[25m${v.reset}`:`${o}${s!==null?s:"\u25CF"}${v.reset}`}function Yd(t,e,s=!1,o=null){let n=(t||[]).filter(l=>l&&l.canExecute!==!1);if(n.length===0)return`${gs("",s,o)} Step ${e}`;if(n.length===1){let l=n[0],u=l.args||{},d=Lo[l.fnName]||l.fnName.replace(/_/g," "),f="";u.path?f=Yi(u.path):u.command?f=String(u.command).substring(0,60):u.query?f=String(u.query).substring(0,50):u.pattern&&(f=String(u.pattern).substring(0,50));let m=f?`${Ye.dim}(${f})${Ye.reset}`:"";return`${gs(l.fnName,s,o)} ${Ye.bold}${d}${Ye.reset} ${m}`}let r=n[0].fnName,i=[...new Set(n.map(l=>Lo[l.fnName]||l.fnName.replace(/_/g," ")))],c=i.length<=3?i.join(" \xB7 "):`${n.length} actions`;return`${gs(r,s,o)} ${c}`}function Xd(t,e){let s;switch(t){case"write_file":case"edit_file":case"patch_file":case"read_file":case"list_directory":s=Yi(e.path);break;case"bash":s=(e.command||"").substring(0,80);break;case"grep":case"search_files":s=e.pattern?`"${e.pattern}"${e.path?` in ${e.path}`:""}`:"";break;case"glob":s=e.pattern||"";break;case"web_fetch":s=(e.url||"").substring(0,60);break;case"web_search":s=(e.query||"").substring(0,50);break;default:s=JSON.stringify(e).substring(0,80)}let o=Lo[t]||t.replace(/_/g," "),n=s?` ${Ye.dim}(${s})${Ye.reset}`:"";return`${gs(t)} ${Ye.bold}${o}${Ye.reset}${n}`}function Jd(t,e=8){let s=t.split(`
14
+ `),o=s.slice(0,e),n=s.length-e,r=`${v.muted} \u2514 ${v.reset}`,i=" ",c=o.map((l,u)=>`${u===0?r:i}${v.success}${l}${v.reset}`).join(`
15
+ `);return n>0&&(c+=`
16
+ ${v.subtle} \u2026 +${n} lines${v.reset}`),c}function Vd(t,e){switch(t){case"bash":case"ask_user":case"write_file":case"edit_file":case"patch_file":case"task_list":case"spawn_agents":return null;case"read_file":return`Reading: ${e.path||"file"}`;case"list_directory":return`Listing: ${e.path||"."}`;case"search_files":return`Searching: ${e.pattern||"..."}`;case"glob":return`Glob: ${e.pattern||"..."}`;case"grep":return`Grep: ${e.pattern||"..."}`;case"web_fetch":return`Fetching: ${(e.url||"").substring(0,60)}`;case"web_search":return`Searching web: ${(e.query||"").substring(0,50)}`;case"git_status":return"Git status...";case"git_diff":return`Git diff${e.file?`: ${e.file}`:""}...`;case"git_log":return`Git log${e.file?`: ${e.file}`:""}...`;case"gh_run_list":return`GitHub Actions: listing runs${e.workflow?` (${e.workflow})`:""}...`;case"gh_run_view":return`GitHub Actions: run ${e.run_id}...`;case"gh_workflow_trigger":return`GitHub Actions: trigger ${e.workflow}...`;case"browser_open":return`Browser: opening ${(e.url||"").substring(0,60)}...`;case"browser_screenshot":return`Browser: screenshot ${(e.url||"").substring(0,60)}...`;case"browser_click":return`Browser: clicking ${e.text||e.selector||"element"}...`;case"browser_fill":return`Browser: filling ${e.selector||"field"}...`;case"sysadmin":{let s=e.server&&e.server!=="local"?` [${e.server}]`:"";switch(e.action){case"audit":return`Sysadmin${s}: full audit...`;case"disk_usage":return`Sysadmin${s}: disk usage ${e.path||"/"}...`;case"process_list":return`Sysadmin${s}: top processes (${e.sort_by||"cpu"})...`;case"network_status":return`Sysadmin${s}: network status...`;case"ssl_check":return`Sysadmin${s}: SSL check ${e.domain||e.cert_path||""}...`;case"log_tail":return`Sysadmin${s}: tail ${e.path||"log"}...`;case"find_large":return`Sysadmin${s}: find large files in ${e.path||"/"}...`;case"service":return`Sysadmin${s}: service ${e.service_action||""} ${e.service_name||""}...`;case"kill_process":return`Sysadmin${s}: kill PID ${e.pid||e.process_name||"?"}...`;case"journalctl":return`Sysadmin${s}: journal ${e.unit?`[${e.unit}]`:""}${e.since?` since ${e.since}`:""}...`;case"package":return`Sysadmin${s}: package ${e.package_action||""} ${(e.packages||[]).join(" ")}...`;case"firewall":return`Sysadmin${s}: firewall ${e.firewall_action||""}...`;case"user_manage":return`Sysadmin${s}: user ${e.user_action||""} ${e.user||""}...`;case"cron":return`Sysadmin${s}: cron ${e.cron_action||""}...`;default:return`Sysadmin${s}: ${e.action}...`}}default:return`Running: ${t}`}}function Qd(t,e,s,o){let n=String(s||"");if(o){let i=n.split(`
17
+ `)[0].replace(/^ERROR:\s*/i,"").substring(0,80),c=n.match(/\nHINT: (.+)/),l=c?`
18
+ ${v.muted}${c[1].substring(0,100)}${v.reset}`:"";return` ${v.error}\u2514 ${i}${v.reset}${l}`}let r;switch(t){case"read_file":{let i=n.split(`
19
+ `).filter(Boolean),c=i.length,l=i[i.length-1],u=l?parseInt(l.match(/^(\d+):/)?.[1]||"0"):0,d=e.line_start||e.line_end,f=e.path?require("path").basename(e.path):null,m=f?` ${v.muted}from ${f}${v.reset}`:"",p=(i.filter($=>!/^File:\s/.test($))[0]||"").replace(/^\d+:\s*/,"").trim(),g=p?` ${Ye.dim}\u2014 ${p.substring(0,70)}${p.length>70?"\u2026":""}${Ye.reset}`:"";d&&u>c?r=`Read lines ${e.line_start||1}\u2013${u}${m}${g}`:r=`Read ${c} line${c!==1?"s":""}${m}${g}`;break}case"write_file":{let i=(e.content||"").split(`
20
+ `).length,c=e.path?require("path").basename(e.path):null;r=c?`Wrote ${c} \xB7 ${i} line${i!==1?"s":""}`:`Wrote ${i} line${i!==1?"s":""}`;break}case"edit_file":{let i=(e.old_text||"").split(`
20
21
  `),c=(e.new_text||"").split(`
21
- `),l=i.length,u=c.length,d=3,p=i.slice(0,d).filter(m=>m.trim()),f=c.slice(0,d).filter(m=>m.trim()),h=[];for(let m of p)h.push(`${C.red} - ${C.reset}${C.dim}${m.trimEnd().substring(0,72)}${C.reset}`);i.length>d&&h.push(`${C.dim} \u2026 +${i.length-d}${C.reset}`);for(let m of f)h.push(`${C.green} + ${C.reset}${C.dim}${m.trimEnd().substring(0,72)}${C.reset}`);c.length>d&&h.push(`${C.dim} \u2026 +${c.length-d}${C.reset}`),r=`${C.reset}${C.red}\u2212${l}${C.reset} ${C.green}+${u}${C.reset}`+(h.length>0?`
22
+ `),l=i.length,u=c.length,d=3,f=i.slice(0,d).filter(p=>p.trim()),m=c.slice(0,d).filter(p=>p.trim()),h=[];for(let p of f)h.push(`${v.diff_rem} - ${v.reset}${v.muted}${p.trimEnd().substring(0,72)}${v.reset}`);i.length>d&&h.push(`${v.muted} \u2026 +${i.length-d}${v.reset}`);for(let p of m)h.push(`${v.diff_add} + ${v.reset}${v.muted}${p.trimEnd().substring(0,72)}${v.reset}`);c.length>d&&h.push(`${v.muted} \u2026 +${c.length-d}${v.reset}`),r=`${v.reset}${v.diff_rem}\u2212${l}${v.reset} ${v.diff_add}+${u}${v.reset}`+(h.length>0?`
22
23
  `+h.join(`
23
24
  `):"");break}case"patch_file":{let i=e.patches||[],c=i.reduce((u,d)=>u+(d.old_text||"").split(`
24
25
  `).length,0),l=i.reduce((u,d)=>u+(d.new_text||"").split(`
25
- `).length,0);r=`${C.reset}${i.length} patch${i.length!==1?"es":""} ${C.red}\u2212${c}${C.reset} ${C.green}+${l}${C.reset}`;break}case"bash":{let i=o.match(/^EXIT (\d+)/);if(i){let c=i[1],l=o.match(/\nHINT: (.+)/);if(l)r=`${c==="0"?`${C.green}\u2713${C.reset}`:`${C.red}\u2717 Exit ${c}${C.reset}`} ${C.dim}\u2014 ${l[1].substring(0,60)}${C.reset}`;else{let u=o.split(`
26
- `).filter(h=>h&&!h.startsWith("EXIT ")&&h.trim()),d=u[0]?` ${C.dim}\xB7 ${u[0].substring(0,70)}${C.reset}`:"",p=u.length>1?` ${C.dim}+${u.length-1}${C.reset}`:"";r=`${c==="0"?`${C.green}\u2713${C.reset}`:`${C.red}\u2717 Exit ${c}${C.reset}`}${d}${p}`}}else{let c=o.split(`
27
- `).filter(Boolean);r=c.length>1?`${c[0].substring(0,60)} ${C.dim}+${c.length-1} more${C.reset}`:(c[0]||"").substring(0,70)||"Done"}break}case"grep":case"search_files":{if(o.includes("(no matches)")||o==="no matches")r="No matches";else{let i=o.split(`
28
- `).filter(Boolean),c=i.length,u=new Set(i.map(d=>d.split(":")[0]).filter(Boolean)).size;r=u>1?`${c} match${c!==1?"es":""} in ${u} files`:`${c} match${c!==1?"es":""}`}break}case"glob":{if(o==="(no matches)")r="No files found";else{let i=o.split(`
29
- `).filter(Boolean).length;r=`${i} file${i!==1?"s":""} found`}break}case"list_directory":{let i=o==="(empty)"?0:o.split(`
30
- `).filter(Boolean).length;r=`${i} entr${i!==1?"ies":"y"}`;break}case"git_status":{let i=o.match(/Branch:\s*(\S+)/),c=o.split(`
31
- `).filter(l=>/^\s*[MADRCU?!]/.test(l)).length;r=i?`${i[1]} \xB7 ${c} change${c!==1?"s":""}`:"Done";break}case"git_diff":{let i=(o.match(/^\+[^+]/gm)||[]).length,c=(o.match(/^-[^-]/gm)||[]).length;r=i||c?`+${i} \u2212${c} lines`:"No diff";break}case"git_log":{let i=o.split(`
32
- `).filter(c=>/^commit\s+[0-9a-f]{7}/.test(c)).length;r=i>0?`${i} commit${i!==1?"s":""}`:"Log retrieved";break}case"git_commit":{let i=o.match(/\[[\w./\-]+ ([0-9a-f]{7,})\]/),c=o.match(/\[[\w./\-]+ [0-9a-f]+\]\s+(.+)/);r=i?`${i[1]}${c?` \u2014 ${c[1].substring(0,55)}`:""}`:"Committed";break}case"git_push":{let i=o.match(/(?:->|→)\s*(\S+)/);r=i?`\u2192 ${i[1]}`:"Pushed";break}case"git_pull":{if(/Already up.to.date/i.test(o))r="Already up to date";else{let i=(o.match(/^\+/gm)||[]).length;r=i>0?`Pulled \xB7 +${i} lines`:"Pulled"}break}case"web_fetch":r="Fetched";break;case"web_search":{let i=o.split(`
33
-
34
- `).filter(Boolean).length;r=`${i} result${i!==1?"s":""}`;break}case"task_list":r="Done";break;case"spawn_agents":{let i=(o.match(/✓ Agent/g)||[]).length,c=(o.match(/✗ Agent/g)||[]).length;r=c>0?`${i} done, ${c} failed`:`${i} agent${i!==1?"s":""} done`;break}case"switch_model":{let i=o.match(/Switched to (.+)/);r=i?`\u2192 ${i[1]}`:"Done";break}default:r="Done"}return` ${C.dim}\u2514 ${r}${C.reset}`}Zr.exports={C,formatToolCall:gu,formatResult:$u,getToolSpinnerText:yu,formatToolSummary:wu,formatSectionHeader:hu}});var de=L((W$,ni)=>{var nn={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",white:"\x1B[37m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",gray:"\x1B[90m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",brightCyan:"\x1B[96m",brightMagenta:"\x1B[95m",brightBlue:"\x1B[94m"},ti=["01100110","01111110","01111110","01011010","01111110","00111100"];function bu(t){let e="\x1B[38;2;80;200;255m",s=[];for(let n=0;n<t.length;n+=2){let o="";for(let r=0;r<t[0].length;r++){let i=t[n][r]==="1",c=n+1<t.length&&t[n+1][r]==="1";i&&c?o+=`${e}\u2588\x1B[0m`:i&&!c?o+=`${e}\u2580\x1B[0m`:!i&&c?o+=`${e}\u2584\x1B[0m`:o+=" "}s.push(o)}return s}function xu(t,e,s={}){let n=nn.bold,o=nn.dim,r=nn.reset,i="\x1B[38;2;80;200;255m",c=bu(ti),l=s.yolo?` ${n}${nn.yellow}\u26A1 YOLO${r}`:"",u=In().version,d=[` ${i}${n}nex-code${r} ${o}v${u}${r}`,` ${o}${t} \xB7 /help${r}${l}`,""],p=Math.max(c.length,d.length),f=Math.floor((p-c.length)/2),h=Math.floor((p-d.length)/2),m=ti[0].length,g=[];for(let y=0;y<p;y++){let $=c[y-f]??" ".repeat(m),x=d[y-h]??"";g.push($+x)}console.log(`
35
- `+g.join(`
26
+ `).length,0);r=`${v.reset}${i.length} patch${i.length!==1?"es":""} ${v.diff_rem}\u2212${c}${v.reset} ${v.diff_add}+${l}${v.reset}`;break}case"bash":{let c=n.match(/^EXIT (\d+)/),l=n.split(`
27
+ `).filter(f=>f&&!f.startsWith("EXIT ")&&!f.startsWith("HINT:")&&f.trim()),u=c?c[1]==="0"?`${v.success}\u2713${v.reset}`:`${v.error}\u2717 Exit ${c[1]}${v.reset}`:`${v.success}\u2713${v.reset}`,d=n.match(/\nHINT: (.+)/);if(d)r=`${u} ${v.muted}\u2014 ${d[1].substring(0,100)}${v.reset}`;else if(l.length===0)r=u;else{let f=l.slice(0,6),m=l.length-6,h=f.map((p,g)=>g===0?`${u} ${v.muted}${p.substring(0,120)}${v.reset}`:` ${v.muted}${p.substring(0,120)}${v.reset}`);m>0&&h.push(` ${v.subtle}\u2026 +${m} lines${v.reset}`),r=h.join(`
28
+ `)}break}case"grep":case"search_files":{if(n.includes("(no matches)")||n==="no matches")r=`No matches${e.pattern?` ${v.muted}"${String(e.pattern).substring(0,40)}"${v.reset}`:""}`;else{let i=n.split(`
29
+ `).filter(Boolean),c=i.length,u=new Set(i.map(p=>p.split(":")[0]).filter(Boolean)).size,d=e.pattern?` ${v.muted}"${String(e.pattern).substring(0,40)}"${v.reset}`:"",f=u>1?`${c} match${c!==1?"es":""} in ${u} files${d}`:`${c} match${c!==1?"es":""}${d}`,m=i.slice(0,4).map((p,g)=>g===0?`${f}
30
+ ${v.muted}${p.substring(0,110)}${v.reset}`:` ${v.muted}${p.substring(0,110)}${v.reset}`),h=i.length-4;h>0&&m.push(` ${v.subtle}\u2026 +${h} lines${v.reset}`),r=m.join(`
31
+ `)}break}case"glob":{let i=e.pattern?` ${v.muted}${String(e.pattern).substring(0,50)}${v.reset}`:"";if(n==="(no matches)")r=`No files found${i}`;else{let c=require("path"),l=n.split(`
32
+ `).filter(Boolean),u=l.length,d=l.slice(0,5).map(h=>c.basename(h)),f=u-d.length,m=d.join(", ")+(f>0?`, +${f} more`:"");r=`${u} file${u!==1?"s":""}${i} \u2014 ${v.muted}${m}${v.reset}`}break}case"list_directory":{if(n==="(empty)")r="0 entries";else{let i=n.split(`
33
+ `).filter(Boolean),c=i.length,l=i.slice(0,6).join(", "),u=c-6;r=u>0?`${c} entries \u2014 ${v.muted}${l}, +${u} more${v.reset}`:`${c} entr${c!==1?"ies":"y"} \u2014 ${v.muted}${l}${v.reset}`}break}case"git_status":{let i=n.match(/Branch:\s*(\S+)/),c=n.split(`
34
+ `).filter(l=>/^\s*[MADRCU?!]/.test(l)).length;r=i?`${i[1]} \xB7 ${c} change${c!==1?"s":""}`:"Done";break}case"git_diff":{let i=(n.match(/^\+[^+]/gm)||[]).length,c=(n.match(/^-[^-]/gm)||[]).length;r=i||c?`+${i} \u2212${c} lines`:"No diff";break}case"git_log":{let i=n.split(`
35
+ `).filter(d=>/^commit\s+[0-9a-f]{7}/.test(d)),c=i.length,l=i[0]?i[0].replace(/^commit\s+/,"").substring(0,7):null,u=(()=>{let d=n.indexOf(i[0]||"\0");return d===-1?null:n.substring(d).split(`
36
+ `).find((m,h)=>h>0&&m.trim()&&!m.startsWith("Author:")&&!m.startsWith("Date:")&&!m.startsWith("Merge:"))})();if(c===0)r="Log retrieved";else if(l&&u){let d=c>1?` ${v.muted}+${c-1} more${v.reset}`:"";r=`${l} ${v.muted}${u.trim().substring(0,60)}${v.reset}${d}`}else r=`${c} commit${c!==1?"s":""}`;break}case"git_commit":{let i=n.match(/\[[\w./\-]+ ([0-9a-f]{7,})\]/),c=n.match(/\[[\w./\-]+ [0-9a-f]+\]\s+(.+)/);r=i?`${i[1]}${c?` \u2014 ${c[1].substring(0,55)}`:""}`:"Committed";break}case"git_push":{let i=n.match(/(?:->|→)\s*(\S+)/);r=i?`\u2192 ${i[1]}`:"Pushed";break}case"git_pull":{if(/Already up.to.date/i.test(n))r="Already up to date";else{let i=(n.match(/^\+/gm)||[]).length;r=i>0?`Pulled \xB7 +${i} lines`:"Pulled"}break}case"web_fetch":{let i=n.match(/<title[^>]*>([^<]{1,80})<\/title>/i),c=n.match(/^#\s+(.{1,80})/m),l=e.url||"",u="";try{u=new URL(l).hostname}catch{u=l.substring(0,60)}let d=i?i[1].trim():c?c[1].trim():null;r=d?`${u} \u2014 ${v.muted}${d.substring(0,70)}${v.reset}`:`Fetched ${u}`;break}case"web_search":{let i=n.split(`
37
+
38
+ `).filter(Boolean),c=i.length,l=i[0]?i[0].split(`
39
+ `)[0].replace(/^\d+\.\s*/,"").trim():null,u=l?` ${v.muted}\u2014 ${l.substring(0,70)}${v.reset}`:"";r=`${c} result${c!==1?"s":""}${u}`;break}case"task_list":r="Done";break;case"spawn_agents":{let i=(n.match(/✓ Agent/g)||[]).length,c=(n.match(/✗ Agent/g)||[]).length;r=c>0?`${i} done, ${c} failed`:`${i} agent${i!==1?"s":""} done`;break}case"switch_model":{let i=n.match(/Switched to (.+)/);r=i?`\u2192 ${i[1]}`:"Done";break}default:{let i=n.split(`
40
+ `).filter(c=>c.trim()&&!c.startsWith("EXIT ")&&!c.startsWith("HINT:"));if(i.length>0){let c=i[0].trim().substring(0,90),l=i.length>1?` ${v.subtle}+${i.length-1}${v.reset}`:"";r=`${v.muted}${c}${v.reset}${l}`}else r="Done"}}return` ${v.muted}\u2514 ${r}${v.reset}`}Xi.exports={C:Ye,formatToolCall:Xd,formatResult:Jd,getToolSpinnerText:Vd,formatToolSummary:Qd,formatSectionHeader:Yd}});var ye=j((u0,Qi)=>{var{T:jt}=Lt(),jo=jt,Vi=["01100110","01111110","01111110","01011010","01111110","00111100"];function Zd(t,e){let s=[];for(let o=0;o<t.length;o+=2){let n="";for(let r=0;r<t[0].length;r++){let i=t[o][r]==="1",c=o+1<t.length&&t[o+1][r]==="1";i&&c?n+=`${e}\u2588\x1B[0m`:i&&!c?n+=`${e}\u2580\x1B[0m`:!i&&c?n+=`${e}\u2584\x1B[0m`:n+=" "}s.push(n)}return s}function ef(t,e,s={}){let o=jo.bold,n=jo.reset,r=Zd(Vi,jt.banner_logo),i=s.yolo?` ${o}${jt.banner_yolo}\u26A1 YOLO${n}`:"",c=fs().version,l=[` ${jt.banner_name}${o}nex-code${n} ${jt.banner_version}v${c}${n}`,` ${jt.banner_model}${t}${n} ${jt.muted}\xB7 /help${n}${i}`,""],u=Math.max(r.length,l.length),d=Math.floor((u-r.length)/2),f=Math.floor((u-l.length)/2),m=Vi[0].length,h=[];for(let p=0;p<u;p++){let g=r[p-d]??" ".repeat(m),$=l[p-f]??"";h.push(g+$)}console.log(`
41
+ `+h.join(`
36
42
  `)+`
37
- `)}var{Spinner:_u,MultiProgress:ku,TaskProgress:vu,setActiveTaskProgress:Su,getActiveTaskProgress:Eu,cleanupTerminal:Tu}=Xr(),{formatToolCall:Ru,formatResult:Cu,getToolSpinnerText:Au,formatToolSummary:Ou,formatSectionHeader:Nu}=ei();ni.exports={C:nn,banner:xu,Spinner:_u,MultiProgress:ku,TaskProgress:vu,setActiveTaskProgress:Su,getActiveTaskProgress:Eu,cleanupTerminal:Tu,formatToolCall:Ru,formatResult:Cu,getToolSpinnerText:Au,formatToolSummary:Ou,formatSectionHeader:Nu}});var We=L((B$,ai)=>{var Mu=require("readline"),{C:Ue}=de(),si=[/rm\s+-rf\s+\/(?:\s|$)/,/rm\s+-rf\s+~(?:\/|\s|$)/,/rm\s+-rf\s+\.(?:\/|\s|$)/,/rm\s+-rf\s+\*(?:\s|$)/,/mkfs/,/dd\s+if=/,/:\(\)\s*\{/,/>\/dev\/sd/,/curl.*\|\s*(?:ba)?sh/,/wget.*\|\s*(?:ba)?sh/,/cat\s+.*\.env\b/,/cat\s+.*credentials/i,/chmod\s+777/,/chown\s+root/,/passwd/,/userdel/,/useradd/,/\beval\s*\(/,/base64.*\|.*bash/,/\bprintenv\b/,/cat\s+.*\.ssh\/id_/,/cat\s+.*\.ssh\/config/,/\bnc\s+-[el]/,/\bncat\b/,/\bsocat\b/,/python3?\s+-c\s/,/node\s+-e\s/,/perl\s+-e\s/,/ruby\s+-e\s/,/(?:^|[;&|]\s*)history(?:\s|$)/,/curl.*-X\s*POST/,/curl.*--data/],Qs=[/systemctl\s+(status|is-active|is-enabled|list-units|show)/,/journalctl\b/,/\btail\s/,/\bcat\s/,/\bhead\s/,/\bls\b/,/\bfind\s/,/\bgrep\s/,/\bwc\s/,/\bdf\b/,/\bfree\b/,/\buptime\b/,/\bwho\b/,/\bps\s/,/\bgit\s+(status|log|diff|branch|fetch)\b/,/\bgit\s+pull\b/,/\bss\s+-[tlnp]/,/\bnetstat\s/,/\bdu\s/,/\blscpu\b/,/\bnproc\b/,/\buname\b/,/\bhostname\b/,/\bgetent\b/,/\bid\b/,/psql\s.*-c\s/,/\bmysql\s.*-e\s/,/\bdnf\s+(check-update|list|info|history|repolist|updateinfo)\b/,/\brpm\s+-q/,/\bapt\s+list\b/,/\bopenssl\s+s_client\b/,/\bopenssl\s+x509\b/,/\bcertbot\s+certificates\b/,/\bcurl\s+-[sIkv]|curl\s+--head/,/\bdig\s/,/\bnslookup\s/,/\bping\s/,/\bgetenforce\b/,/\bsesearch\b/,/\bausearch\b/,/\bsealert\b/,/\bcrontab\s+-l\b/,/\btimedatectl\b/,/\bfirewall-cmd\s+--list/,/\bfirewall-cmd\s+--state/];function oi(t){let e=t.match(/ssh\s+[^"]*"([^"]+)"/)?.[1]||t.match(/ssh\s+[^']*'([^']+)'/)?.[1];if(!e)return!1;let n=e.replace(/\bfor\s[\s\S]*?\bdone\b/g,r=>r.replace(/;/g,"\0")).replace(/\bwhile\s[\s\S]*?\bdone\b/g,r=>r.replace(/;/g,"\0")).split(/\s*(?:&&|;)\s*/).map(r=>r.replace(/\x00/g,";").trim()).filter(Boolean);if(n.length===0)return!1;let o=r=>{let i=r.replace(/^sudo\s+(?:-[ugCD]\s+\S+\s+|-[A-Za-z]+\s+)*/,"");if(/^\s*(?:echo|printf)\s/.test(i))return!0;if(/^\s*for\s/.test(r)||/^\s*while\s/.test(r)){let c=r.match(/\bdo\s+([\s\S]*?)\s*(?:done|$)/)?.[1];return c?c.split(/\s*;\s*/).map(u=>u.trim()).filter(Boolean).every(u=>o(u)):Qs.some(l=>l.test(r))}return/^\w+=\$?\(/.test(i)||/^\w+=["']/.test(i)||/^\w+=\S/.test(i)?!0:Qs.some(c=>c.test(i))};return n.every(o)}var Zs=[/rm\s+-rf\s/,/docker\s+system\s+prune/,/kubectl\s+delete/,/sudo\s/],ri=[/git\s+push/,/npm\s+publish/,/npx\s+.*publish/,/docker\s+rm/,/ssh\s/,/wget\s/,/curl\s.*-o\s/,/pip\s+install/,/npm\s+install\s+-g/],ii=[...Zs,...ri],eo=!1,xt=null;function Pu(t){eo=t}function Lu(){return eo}function Iu(t){xt=t}function qu(t){for(let e of si)if(e.test(t))return e;return null}function Du(t){if(/ssh\s/.test(t)&&oi(t))return!1;for(let e of ii)if(e.test(t))return!0;return!1}function ju(t){for(let e of Zs)if(e.test(t))return!0;return!1}function Fu(t,e={}){if(eo)return Promise.resolve(!0);if(!process.stdout.isTTY||!process.stdin.isTTY)return Uu(t,e);let s=e.toolName?["Yes","No","Always allow"]:["Yes","No"];return new Promise(n=>{let o=0,r=!1;xt&&xt.pause();let i=()=>{r&&process.stdout.write(`\x1B[${s.length+1}A`),r=!0,process.stdout.write(`\r\x1B[K${Ue.yellow}${t}${Ue.reset}
38
- `);for(let d=0;d<s.length;d++){let p=d===o,f=p?`${Ue.yellow}\u276F${Ue.reset}`:" ",h=p?`${Ue.yellow}${s[d]}${Ue.reset}`:s[d];process.stdout.write(`\r\x1B[K ${f} ${h}
39
- `)}},c=d=>{process.stdin.setRawMode(!1),process.stdin.pause(),process.stdin.removeListener("data",u),process.stdout.write(`\x1B[${s.length+1}A`);for(let p=0;p<s.length+1;p++)process.stdout.write(`\r\x1B[K
40
- `);process.stdout.write(`\x1B[${s.length+1}A`),xt&&xt.resume(),n(d)},l=d=>{if(d===1){c(!1);return}d===2&&e.toolName&&Un(e.toolName),c(!0)},u=d=>{if(d[0]===3){c(!1);return}let p=d.toString();if(p==="\r"||p===`
41
- `){l(o);return}if(p==="\x1B[A"){o=(o-1+s.length)%s.length,i();return}if(p==="\x1B[B"){o=(o+1)%s.length,i();return}let f=p.toLowerCase().trim();if(f==="y"){c(!0);return}if(f==="n"){c(!1);return}if(f==="a"&&e.toolName){Un(e.toolName),c(!0);return}};i(),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",u)})}function Uu(t,e){let s=e.toolName?"[Y/n/a] ":"[Y/n] ";return new Promise(n=>{let o=r=>{let i=r.trim().toLowerCase();i==="a"&&e.toolName?(Un(e.toolName),n(!0)):n(i!=="n")};if(xt)xt.question(`${Ue.yellow}${t} ${s}${Ue.reset}`,o);else{let r=Mu.createInterface({input:process.stdin,output:process.stdout});r.question(`${Ue.yellow}${t} ${s}${Ue.reset}`,i=>{r.close(),o(i)})}})}var Un=()=>{};function Wu(t){Un=t}ai.exports={FORBIDDEN_PATTERNS:si,SSH_SAFE_PATTERNS:Qs,isSSHReadOnly:oi,DANGEROUS_BASH:ii,CRITICAL_BASH:Zs,NOTABLE_BASH:ri,isForbidden:qu,isDangerous:Du,isCritical:ju,confirm:Fu,setAutoConfirm:Pu,getAutoConfirm:Lu,setReadlineInterface:Iu,setAllowAlwaysHandler:Wu}});var Dt=L((H$,ci)=>{var to=class t{constructor(e={}){if(new.target===t)throw new Error("BaseProvider is abstract \u2014 use a concrete provider");this.name=e.name||"unknown",this.baseUrl=e.baseUrl||"",this.models=e.models||{},this.defaultModel=e.defaultModel||null}isConfigured(){throw new Error(`${this.name}: isConfigured() not implemented`)}getApiKey(){return null}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}getModel(e){return this.models[e]||null}async chat(e,s,n={}){throw new Error(`${this.name}: chat() not implemented`)}async stream(e,s,n={}){throw new Error(`${this.name}: stream() not implemented`)}formatMessages(e){return{messages:e}}formatTools(e){return e}normalizeResponse(e){throw new Error(`${this.name}: normalizeResponse() not implemented`)}};ci.exports={BaseProvider:to}});var di=L((G$,ui)=>{var Wn=require("axios"),Bu=require("http"),Hu=require("https"),{BaseProvider:Gu}=Dt(),Bn=new Bu.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Hn=new Hu.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),li={"qwen3-coder:480b":{id:"qwen3-coder:480b",name:"Qwen3 Coder 480B",maxTokens:16384,contextWindow:131072},"qwen3-coder-next":{id:"qwen3-coder-next",name:"Qwen3 Coder Next",maxTokens:16384,contextWindow:131072},"devstral-2:123b":{id:"devstral-2:123b",name:"Devstral 2 123B",maxTokens:16384,contextWindow:131072},"devstral-small-2:24b":{id:"devstral-small-2:24b",name:"Devstral Small 2 24B",maxTokens:16384,contextWindow:131072},"kimi-k2.5":{id:"kimi-k2.5",name:"Kimi K2.5",maxTokens:16384,contextWindow:256e3},"kimi-k2:1t":{id:"kimi-k2:1t",name:"Kimi K2 1T",maxTokens:16384,contextWindow:256e3},"kimi-k2-thinking":{id:"kimi-k2-thinking",name:"Kimi K2 Thinking",maxTokens:16384,contextWindow:256e3},"deepseek-v3.2":{id:"deepseek-v3.2",name:"DeepSeek V3.2",maxTokens:16384,contextWindow:131072},"deepseek-v3.1:671b":{id:"deepseek-v3.1:671b",name:"DeepSeek V3.1 671B",maxTokens:16384,contextWindow:131072},"cogito-2.1:671b":{id:"cogito-2.1:671b",name:"Cogito 2.1 671B",maxTokens:16384,contextWindow:131072},"qwen3.5:397b-cloud":{id:"qwen3.5:397b-cloud",name:"Qwen3.5 397B Cloud",maxTokens:16384,contextWindow:262144},"qwen3.5:397b":{id:"qwen3.5:397b",name:"Qwen3.5 397B",maxTokens:16384,contextWindow:262144},"qwen3.5:122b-a10b":{id:"qwen3.5:122b-a10b",name:"Qwen3.5 122B-A10B",maxTokens:16384,contextWindow:262144},"qwen3.5:35b-a3b":{id:"qwen3.5:35b-a3b",name:"Qwen3.5 35B-A3B",maxTokens:16384,contextWindow:262144},"qwen3.5:27b":{id:"qwen3.5:27b",name:"Qwen3.5 27B",maxTokens:16384,contextWindow:262144},"qwen3-next:80b":{id:"qwen3-next:80b",name:"Qwen3 Next 80B",maxTokens:16384,contextWindow:131072},"mistral-large-3:675b":{id:"mistral-large-3:675b",name:"Mistral Large 3 675B",maxTokens:16384,contextWindow:131072},"gpt-oss:120b":{id:"gpt-oss:120b",name:"GPT-OSS 120B",maxTokens:16384,contextWindow:131072},"minimax-m2.5":{id:"minimax-m2.5",name:"MiniMax M2.5",maxTokens:16384,contextWindow:131072},"glm-5":{id:"glm-5",name:"GLM 5",maxTokens:16384,contextWindow:128e3},"glm-4.7":{id:"glm-4.7",name:"GLM 4.7",maxTokens:16384,contextWindow:128e3},"qwen3.5:9b":{id:"qwen3.5:9b",name:"Qwen3.5 9B",maxTokens:8192,contextWindow:262144},"qwen3.5:4b":{id:"qwen3.5:4b",name:"Qwen3.5 4B",maxTokens:8192,contextWindow:262144},"qwen3.5:2b":{id:"qwen3.5:2b",name:"Qwen3.5 2B",maxTokens:8192,contextWindow:262144},"qwen3.5:0.8b":{id:"qwen3.5:0.8b",name:"Qwen3.5 0.8B",maxTokens:8192,contextWindow:262144},"gemma3:27b":{id:"gemma3:27b",name:"Gemma 3 27B",maxTokens:8192,contextWindow:131072},"gemma3:12b":{id:"gemma3:12b",name:"Gemma 3 12B",maxTokens:8192,contextWindow:131072},"gemma3:4b":{id:"gemma3:4b",name:"Gemma 3 4B",maxTokens:8192,contextWindow:131072},"ministral-3:14b":{id:"ministral-3:14b",name:"Ministral 3 14B",maxTokens:8192,contextWindow:131072},"ministral-3:8b":{id:"ministral-3:8b",name:"Ministral 3 8B",maxTokens:8192,contextWindow:131072},"gemini-3-flash-preview":{id:"gemini-3-flash-preview",name:"Gemini 3 Flash Preview",maxTokens:16384,contextWindow:131072}},no=class extends Gu{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||li,defaultModel:e.defaultModel||"qwen3-coder:480b",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this._discovered=!1}async discoverModels(){if(!this._discovered){if(this._discovered=!0,!process.stdout.isTTY){Wn.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Bn,httpsAgent:Hn}).then(e=>{let s=e.data?.models||[];for(let n of s){let o=(n.name||n.model||"").replace(/:latest$/,"");!o||this.models[o]||(this.models[o]={id:o,name:n.name||o,maxTokens:16384,contextWindow:131072})}}).catch(()=>{});return}try{let s=(await Wn.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Bn,httpsAgent:Hn})).data?.models||[];for(let n of s){let o=(n.name||n.model||"").replace(/:latest$/,"");!o||this.models[o]||(this.models[o]={id:o,name:n.name||o,maxTokens:16384,contextWindow:131072})}}catch{}}}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OLLAMA_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OLLAMA_API_KEY not set");return{Authorization:`Bearer ${e}`}}_formatMessages(e){return e.map(s=>{if(s.role==="user"&&Array.isArray(s.content)){let n=[],o=[];for(let i of s.content)i.type==="text"?n.push(i.text??""):i.type==="image"&&i.data&&o.push(i.data);let r={role:"user",content:n.join(`
42
- `)};return o.length>0&&(r.images=o),r}return s})}async chat(e,s,n={}){await this.discoverModels();let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||16384,c=await Wn.post(`${this.baseUrl}/api/chat`,{model:o,messages:this._formatMessages(e),tools:s&&s.length>0?s:void 0,stream:!1,options:{temperature:n.temperature??this.temperature,num_predict:i}},{timeout:n.timeout||this.timeout,headers:this._getHeaders(),httpAgent:Bn,httpsAgent:Hn});return this.normalizeResponse(c.data)}async stream(e,s,n={}){await this.discoverModels();let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||16384,c=n.onToken||(()=>{}),l=n.onThinkingToken||(()=>{}),u;try{u=await Wn.post(`${this.baseUrl}/api/chat`,{model:o,messages:this._formatMessages(e),tools:s&&s.length>0?s:void 0,stream:!0,options:{temperature:n.temperature??this.temperature,num_predict:i}},{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal,httpAgent:Bn,httpsAgent:Hn})}catch(d){if(d.name==="CanceledError"||d.name==="AbortError"||d.code==="ERR_CANCELED")throw d;let p=d.response?.data?.error||d.message;throw new Error(`API Error: ${p}`)}return new Promise((d,p)=>{let f="",h=[],m="";n.signal&&n.signal.addEventListener("abort",()=>{u.data.destroy(),p(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",g=>{m+=g.toString();let y=m.split(`
43
- `);m=y.pop()||"";for(let $ of y){if(!$.trim())continue;let x;try{x=JSON.parse($)}catch{continue}if(x.message?.thinking&&l(x.message.thinking),x.message?.content&&(c(x.message.content),f+=x.message.content),x.message?.tool_calls&&(h=h.concat(x.message.tool_calls)),x.done){d({content:f,tool_calls:this._normalizeToolCalls(h)});return}}}),u.data.on("error",g=>{n.signal?.aborted||p(new Error(`Stream error: ${g.message}`))}),u.data.on("end",()=>{if(m.trim())try{let g=JSON.parse(m);g.message?.thinking&&l(g.message.thinking),g.message?.content&&(c(g.message.content),f+=g.message.content),g.message?.tool_calls&&(h=h.concat(g.message.tool_calls))}catch{}d({content:f,tool_calls:this._normalizeToolCalls(h)})})})}normalizeResponse(e){let s=e.message||{};return{content:s.content||"",tool_calls:this._normalizeToolCalls(s.tool_calls||[])}}_normalizeToolCalls(e){return e.map((s,n)=>({id:s.id||`ollama-${Date.now()}-${n}`,function:{name:s.function?.name||s.name||"unknown",arguments:s.function?.arguments||s.arguments||{}}}))}};ui.exports={OllamaProvider:no,OLLAMA_MODELS:li}});var $i=L((z$,gi)=>{var{callChat:zu}=ge(),{estimateTokens:so}=De(),fi=process.env.NEX_COMPACTION!=="false",pi=6,mi=500,Ku=`Summarize this conversation history concisely. Focus on:
43
+ `)}var{Spinner:tf,MultiProgress:nf,TaskProgress:sf,ToolProgress:of,setActiveTaskProgress:rf,getActiveTaskProgress:af,cleanupTerminal:cf}=Cn(),{formatToolCall:lf,formatResult:uf,getToolSpinnerText:df,formatToolSummary:ff,formatSectionHeader:pf}=Ji();Qi.exports={C:jo,banner:ef,Spinner:tf,MultiProgress:nf,TaskProgress:sf,ToolProgress:of,setActiveTaskProgress:rf,getActiveTaskProgress:af,cleanupTerminal:cf,formatToolCall:lf,formatResult:uf,getToolSpinnerText:df,formatToolSummary:ff,formatSectionHeader:pf}});var Ae=j((d0,sa)=>{var mf=require("readline"),{C:st}=ye(),Zi=[/rm\s+-rf\s+\/(?:\s|$)/,/rm\s+-rf\s+~(?:\/|\s|$)/,/rm\s+-rf\s+\.(?:\/|\s|$)/,/rm\s+-rf\s+\*(?:\s|$)/,/mkfs/,/dd\s+if=/,/:\(\)\s*\{/,/>\/dev\/sd/,/curl.*\|\s*(?:ba)?sh/,/wget.*\|\s*(?:ba)?sh/,/cat\s+.*\.env\b/,/cat\s+.*credentials/i,/chmod\s+777/,/chown\s+root/,/passwd/,/userdel/,/useradd/,/\beval\s*\(/,/base64.*\|.*bash/,/\bprintenv\b/,/cat\s+.*\.ssh\/id_/,/cat\s+.*\.ssh\/config/,/\bnc\s+-[el]/,/\bncat\b/,/\bsocat\b/,/python3?\s+-c\s/,/node\s+-e\s/,/perl\s+-e\s/,/ruby\s+-e\s/,/(?:^|[;&|]\s*)history(?:\s|$)/,/curl.*-X\s*POST/,/curl.*--data/],Do=[/systemctl\s+(status|is-active|is-enabled|list-units|show)/,/journalctl\b/,/\btail\s/,/\bcat\s/,/\bhead\s/,/\bls\b/,/\bfind\s/,/\bgrep\s/,/\bwc\s/,/\bdf\b/,/\bfree\b/,/\buptime\b/,/\bwho\b/,/\bps\s/,/\bgit\s+(status|log|diff|branch|fetch)\b/,/\bgit\s+pull\b/,/\bss\s+-[tlnp]/,/\bnetstat\s/,/\bdu\s/,/\blscpu\b/,/\bnproc\b/,/\buname\b/,/\bhostname\b/,/\bgetent\b/,/\bid\b/,/psql\s.*-c\s/,/\bmysql\s.*-e\s/,/\bdnf\s+(check-update|list|info|history|repolist|updateinfo)\b/,/\brpm\s+-q/,/\bapt\s+list\b/,/\bopenssl\s+s_client\b/,/\bopenssl\s+x509\b/,/\bcertbot\s+certificates\b/,/\bcurl\s+-[sIkv]|curl\s+--head/,/\bdig\s/,/\bnslookup\s/,/\bping\s/,/\bgetenforce\b/,/\bsesearch\b/,/\bausearch\b/,/\bsealert\b/,/\bcrontab\s+-l\b/,/\btimedatectl\b/,/\bfirewall-cmd\s+--list/,/\bfirewall-cmd\s+--state/];function ea(t){let e=t.match(/ssh\s+[^"]*"([^"]+)"/)?.[1]||t.match(/ssh\s+[^']*'([^']+)'/)?.[1];if(!e)return!1;let o=e.replace(/\bfor\s[\s\S]*?\bdone\b/g,r=>r.replace(/;/g,"\0")).replace(/\bwhile\s[\s\S]*?\bdone\b/g,r=>r.replace(/;/g,"\0")).split(/\s*(?:&&|;)\s*/).map(r=>r.replace(/\x00/g,";").trim()).filter(Boolean);if(o.length===0)return!1;let n=r=>{let i=r.replace(/^sudo\s+(?:-[ugCD]\s+\S+\s+|-[A-Za-z]+\s+)*/,"");if(/^\s*(?:echo|printf)\s/.test(i))return!0;if(/^\s*for\s/.test(r)||/^\s*while\s/.test(r)){let c=r.match(/\bdo\s+([\s\S]*?)\s*(?:done|$)/)?.[1];return c?c.split(/\s*;\s*/).map(u=>u.trim()).filter(Boolean).every(u=>n(u)):Do.some(l=>l.test(r))}return/^\w+=\$?\(/.test(i)||/^\w+=["']/.test(i)||/^\w+=\S/.test(i)?!0:Do.some(c=>c.test(i))};return o.every(n)}var Fo=[/rm\s+-rf\s/,/docker\s+system\s+prune/,/kubectl\s+delete/,/sudo\s/,/--no-verify\b/,/git\s+reset\s+--hard\b/,/git\s+clean\s+-[a-z]*f/,/git\s+checkout\s+--\s/,/git\s+push\s+(?:--force\b|-f\b)/],ta=[/git\s+push/,/npm\s+publish/,/\bHUSKY=0\b/,/\bSKIP_HUSKY=1\b/,/\bSKIP_PREFLIGHT_CHECK=true\b/,/npx\s+.*publish/,/docker\s+rm/,/ssh\s/,/wget\s/,/curl\s.*-o\s/,/pip\s+install/,/npm\s+install\s+-g/],na=[...Fo,...ta],Uo=!1,Dt=null,qo=null;function hf(t){Uo=t}function gf(t){qo=t}function $f(){return Uo}function yf(t){Dt=t}function wf(t){for(let e of Zi)if(e.test(t))return e;return null}function bf(t){if(/ssh\s/.test(t)&&ea(t))return!1;for(let e of na)if(e.test(t))return!0;return!1}function _f(t){for(let e of Fo)if(e.test(t))return!0;return!1}function kf(t,e={}){if(Uo)return Promise.resolve(!0);if(qo)return qo(t,e);if(!process.stdout.isTTY||!process.stdin.isTTY)return xf(t,e);let s=e.toolName?["Yes","No","Always allow"]:["Yes","No"];return new Promise(o=>{let n=0,r=!1;Dt&&Dt.pause();let i=()=>{r&&process.stdout.write(`\x1B[${s.length+1}A`),r=!0,process.stdout.write(`\r\x1B[K${st.yellow}${t}${st.reset}
44
+ `);for(let d=0;d<s.length;d++){let f=d===n,m=f?`${st.yellow}\u276F${st.reset}`:" ",h=f?`${st.yellow}${s[d]}${st.reset}`:s[d];process.stdout.write(`\r\x1B[K ${m} ${h}
45
+ `)}},c=d=>{process.stdin.setRawMode(!1),process.stdin.pause(),process.stdin.removeListener("data",u),process.stdout.write(`\x1B[${s.length+1}A`);for(let f=0;f<s.length+1;f++)process.stdout.write(`\r\x1B[K
46
+ `);process.stdout.write(`\x1B[${s.length+1}A`),Dt&&Dt.resume(),o(d)},l=d=>{if(d===1){c(!1);return}d===2&&e.toolName&&$s(e.toolName),c(!0)},u=d=>{if(d[0]===3){c(!1);return}let f=d.toString();if(f==="\r"||f===`
47
+ `){l(n);return}if(f==="\x1B[A"){n=(n-1+s.length)%s.length,i();return}if(f==="\x1B[B"){n=(n+1)%s.length,i();return}let m=f.toLowerCase().trim();if(m==="y"){c(!0);return}if(m==="n"){c(!1);return}if(m==="a"&&e.toolName){$s(e.toolName),c(!0);return}};i(),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",u)})}function xf(t,e){let s=e.toolName?"[Y/n/a] ":"[Y/n] ";return new Promise(o=>{let n=r=>{let i=r.trim().toLowerCase();i==="a"&&e.toolName?($s(e.toolName),o(!0)):o(i!=="n")};if(Dt)Dt.question(`${st.yellow}${t} ${s}${st.reset}`,n);else{let r=mf.createInterface({input:process.stdin,output:process.stdout});r.question(`${st.yellow}${t} ${s}${st.reset}`,i=>{r.close(),n(i)})}})}var $s=()=>{};function vf(t){$s=t}sa.exports={FORBIDDEN_PATTERNS:Zi,SSH_SAFE_PATTERNS:Do,isSSHReadOnly:ea,DANGEROUS_BASH:na,CRITICAL_BASH:Fo,NOTABLE_BASH:ta,isForbidden:wf,isDangerous:bf,isCritical:_f,confirm:kf,setAutoConfirm:hf,getAutoConfirm:$f,setConfirmHook:gf,setReadlineInterface:yf,setAllowAlwaysHandler:vf}});var on=j((f0,oa)=>{var Wo=class t{constructor(e={}){if(new.target===t)throw new Error("BaseProvider is abstract \u2014 use a concrete provider");this.name=e.name||"unknown",this.baseUrl=e.baseUrl||"",this.models=e.models||{},this.defaultModel=e.defaultModel||null}isConfigured(){throw new Error(`${this.name}: isConfigured() not implemented`)}getApiKey(){return null}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}getModel(e){return this.models[e]||null}async chat(e,s,o={}){throw new Error(`${this.name}: chat() not implemented`)}async stream(e,s,o={}){throw new Error(`${this.name}: stream() not implemented`)}formatMessages(e){return{messages:e}}formatTools(e){return e}normalizeResponse(e){throw new Error(`${this.name}: normalizeResponse() not implemented`)}};oa.exports={BaseProvider:Wo}});var aa=j((p0,ia)=>{var ys=require("axios"),Sf=require("http"),Ef=require("https"),{BaseProvider:Tf}=on(),ws=new Sf.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),bs=new Ef.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),ra={"qwen3-coder:480b":{id:"qwen3-coder:480b",name:"Qwen3 Coder 480B",maxTokens:16384,contextWindow:131072},"qwen3-coder-next":{id:"qwen3-coder-next",name:"Qwen3 Coder Next",maxTokens:16384,contextWindow:131072},"devstral-2:123b":{id:"devstral-2:123b",name:"Devstral 2 123B",maxTokens:16384,contextWindow:131072},"devstral-small-2:24b":{id:"devstral-small-2:24b",name:"Devstral Small 2 24B",maxTokens:16384,contextWindow:131072},"kimi-k2.5":{id:"kimi-k2.5",name:"Kimi K2.5",maxTokens:16384,contextWindow:256e3},"kimi-k2:1t":{id:"kimi-k2:1t",name:"Kimi K2 1T",maxTokens:16384,contextWindow:256e3},"kimi-k2-thinking":{id:"kimi-k2-thinking",name:"Kimi K2 Thinking",maxTokens:16384,contextWindow:256e3},"deepseek-v3.2":{id:"deepseek-v3.2",name:"DeepSeek V3.2",maxTokens:16384,contextWindow:131072},"deepseek-v3.1:671b":{id:"deepseek-v3.1:671b",name:"DeepSeek V3.1 671B",maxTokens:16384,contextWindow:131072},"cogito-2.1:671b":{id:"cogito-2.1:671b",name:"Cogito 2.1 671B",maxTokens:16384,contextWindow:131072},"qwen3.5:397b-cloud":{id:"qwen3.5:397b-cloud",name:"Qwen3.5 397B Cloud",maxTokens:16384,contextWindow:262144},"qwen3.5:397b":{id:"qwen3.5:397b",name:"Qwen3.5 397B",maxTokens:16384,contextWindow:262144},"qwen3.5:122b-a10b":{id:"qwen3.5:122b-a10b",name:"Qwen3.5 122B-A10B",maxTokens:16384,contextWindow:262144},"qwen3.5:35b-a3b":{id:"qwen3.5:35b-a3b",name:"Qwen3.5 35B-A3B",maxTokens:16384,contextWindow:262144},"qwen3.5:27b":{id:"qwen3.5:27b",name:"Qwen3.5 27B",maxTokens:16384,contextWindow:262144},"qwen3-next:80b":{id:"qwen3-next:80b",name:"Qwen3 Next 80B",maxTokens:16384,contextWindow:131072},"mistral-large-3:675b":{id:"mistral-large-3:675b",name:"Mistral Large 3 675B",maxTokens:16384,contextWindow:131072},"gpt-oss:120b":{id:"gpt-oss:120b",name:"GPT-OSS 120B",maxTokens:16384,contextWindow:131072},"minimax-m2.5":{id:"minimax-m2.5",name:"MiniMax M2.5",maxTokens:16384,contextWindow:131072},"glm-5":{id:"glm-5",name:"GLM 5",maxTokens:16384,contextWindow:128e3},"glm-4.7":{id:"glm-4.7",name:"GLM 4.7",maxTokens:16384,contextWindow:128e3},"qwen3.5:9b":{id:"qwen3.5:9b",name:"Qwen3.5 9B",maxTokens:8192,contextWindow:262144},"qwen3.5:4b":{id:"qwen3.5:4b",name:"Qwen3.5 4B",maxTokens:8192,contextWindow:262144},"qwen3.5:2b":{id:"qwen3.5:2b",name:"Qwen3.5 2B",maxTokens:8192,contextWindow:262144},"qwen3.5:0.8b":{id:"qwen3.5:0.8b",name:"Qwen3.5 0.8B",maxTokens:8192,contextWindow:262144},"gemma3:27b":{id:"gemma3:27b",name:"Gemma 3 27B",maxTokens:8192,contextWindow:131072},"gemma3:12b":{id:"gemma3:12b",name:"Gemma 3 12B",maxTokens:8192,contextWindow:131072},"gemma3:4b":{id:"gemma3:4b",name:"Gemma 3 4B",maxTokens:8192,contextWindow:131072},"ministral-3:14b":{id:"ministral-3:14b",name:"Ministral 3 14B",maxTokens:8192,contextWindow:131072},"ministral-3:8b":{id:"ministral-3:8b",name:"Ministral 3 8B",maxTokens:8192,contextWindow:131072},"gemini-3-flash-preview":{id:"gemini-3-flash-preview",name:"Gemini 3 Flash Preview",maxTokens:16384,contextWindow:131072}},Bo=class extends Tf{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||ra,defaultModel:e.defaultModel||"qwen3-coder:480b",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this._discovered=!1}async discoverModels(){if(!this._discovered){if(this._discovered=!0,!process.stdout.isTTY){ys.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:ws,httpsAgent:bs}).then(e=>{let s=e.data?.models||[];for(let o of s){let n=(o.name||o.model||"").replace(/:latest$/,"");!n||this.models[n]||(this.models[n]={id:n,name:o.name||n,maxTokens:16384,contextWindow:131072})}}).catch(()=>{});return}try{let s=(await ys.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:ws,httpsAgent:bs})).data?.models||[];for(let o of s){let n=(o.name||o.model||"").replace(/:latest$/,"");!n||this.models[n]||(this.models[n]={id:n,name:o.name||n,maxTokens:16384,contextWindow:131072})}}catch{}}}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OLLAMA_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OLLAMA_API_KEY not set");return{Authorization:`Bearer ${e}`}}_formatMessages(e){return e.map(s=>{if(s.role==="user"&&Array.isArray(s.content)){let o=[],n=[];for(let i of s.content)i.type==="text"?o.push(i.text??""):i.type==="image"&&i.data&&n.push(i.data);let r={role:"user",content:o.join(`
48
+ `)};return n.length>0&&(r.images=n),r}return s})}async chat(e,s,o={}){await this.discoverModels();let n=o.model||this.defaultModel,r=this.getModel(n),i=o.maxTokens||r?.maxTokens||16384,c=await ys.post(`${this.baseUrl}/api/chat`,{model:n,messages:this._formatMessages(e),tools:s&&s.length>0?s:void 0,stream:!1,options:{temperature:o.temperature??this.temperature,num_predict:i}},{timeout:o.timeout||this.timeout,headers:this._getHeaders(),httpAgent:ws,httpsAgent:bs});return this.normalizeResponse(c.data)}async stream(e,s,o={}){await this.discoverModels();let n=o.model||this.defaultModel,r=this.getModel(n),i=o.maxTokens||r?.maxTokens||16384,c=o.onToken||(()=>{}),l=o.onThinkingToken||(()=>{}),u;try{u=await ys.post(`${this.baseUrl}/api/chat`,{model:n,messages:this._formatMessages(e),tools:s&&s.length>0?s:void 0,stream:!0,options:{temperature:o.temperature??this.temperature,num_predict:i}},{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal,httpAgent:ws,httpsAgent:bs})}catch(d){if(d.name==="CanceledError"||d.name==="AbortError"||d.code==="ERR_CANCELED")throw d;let f=d.response?.data?.error||d.message;throw new Error(`API Error: ${f}`)}return new Promise((d,f)=>{let m="",h=[],p="";o.signal&&o.signal.addEventListener("abort",()=>{u.data.destroy(),f(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",g=>{p+=g.toString();let $=p.split(`
49
+ `);p=$.pop()||"";for(let y of $){if(!y.trim())continue;let w;try{w=JSON.parse(y)}catch{continue}if(w.message?.thinking&&l(w.message.thinking),w.message?.content&&(c(w.message.content),m+=w.message.content),w.message?.tool_calls&&(h=h.concat(w.message.tool_calls)),w.done){d({content:m,tool_calls:this._normalizeToolCalls(h)});return}}}),u.data.on("error",g=>{o.signal?.aborted||f(new Error(`Stream error: ${g.message}`))}),u.data.on("end",()=>{if(p.trim())try{let g=JSON.parse(p);g.message?.thinking&&l(g.message.thinking),g.message?.content&&(c(g.message.content),m+=g.message.content),g.message?.tool_calls&&(h=h.concat(g.message.tool_calls))}catch{}d({content:m,tool_calls:this._normalizeToolCalls(h)})})})}normalizeResponse(e){let s=e.message||{};return{content:s.content||"",tool_calls:this._normalizeToolCalls(s.tool_calls||[])}}_normalizeToolCalls(e){return e.map((s,o)=>({id:s.id||`ollama-${Date.now()}-${o}`,function:{name:s.function?.name||s.name||"unknown",arguments:s.function?.arguments||s.arguments||{}}}))}};ia.exports={OllamaProvider:Bo,OLLAMA_MODELS:ra}});var pa=j((m0,fa)=>{var{callChat:Rf}=we(),{estimateTokens:Ho}=Xe(),ca=process.env.NEX_COMPACTION!=="false",la=6,ua=500,Cf=`Summarize this conversation history concisely. Focus on:
44
50
  - What files were read, created, or modified
45
51
  - Key decisions made and their rationale
46
52
  - Current state of the task (what's done, what's pending)
47
53
  - Any errors encountered and how they were resolved
48
- Be factual and brief. Use bullet points. Max 300 words.`;async function Yu(t){if(!fi||t.length<pi)return null;let e=[{role:"system",content:Ku},{role:"user",content:hi(t)}];try{let n=((await zu(e,[],{temperature:0,maxTokens:mi})).content||"").trim();if(!n)return null;let o=t.reduce((i,c)=>i+so(c.content||"")+(c.tool_calls?so(JSON.stringify(c.tool_calls)):0),0),r=so(n);return r>=o*.8?null:{message:{role:"system",content:`[Conversation Summary \u2014 ${t.length} messages compacted]
49
- ${n}`,_compacted:!0,_originalCount:t.length},tokensRemoved:o-r}}catch{return null}}function hi(t){return t.map(e=>{let s=e.role==="tool"?"tool_result":e.role,n=(e.content||"").substring(0,500);if(e.tool_calls){let o=e.tool_calls.map(r=>r.function?.name).join(", ");return`[${s}] ${n}
50
- tools: ${o}`}return`[${s}] ${n}`}).join(`
54
+ Be factual and brief. Use bullet points. Max 300 words.`;async function Af(t){if(!ca||t.length<la)return null;let e=[{role:"system",content:Cf},{role:"user",content:da(t)}];try{let o=((await Rf(e,[],{temperature:0,maxTokens:ua})).content||"").trim();if(!o)return null;let n=t.reduce((i,c)=>i+Ho(c.content||"")+(c.tool_calls?Ho(JSON.stringify(c.tool_calls)):0),0),r=Ho(o);return r>=n*.8?null:{message:{role:"system",content:`[Conversation Summary \u2014 ${t.length} messages compacted]
55
+ ${o}`,_compacted:!0,_originalCount:t.length},tokensRemoved:n-r}}catch{return null}}function da(t){return t.map(e=>{let s=e.role==="tool"?"tool_result":e.role,o=(e.content||"").substring(0,500);if(e.tool_calls){let n=e.tool_calls.map(r=>r.function?.name).join(", ");return`[${s}] ${o}
56
+ tools: ${n}`}return`[${s}] ${o}`}).join(`
51
57
 
52
- `)}gi.exports={compactMessages:Yu,formatMessagesForSummary:hi,COMPACTION_ENABLED:fi,COMPACTION_MIN_MESSAGES:pi,COMPACTION_SUMMARY_BUDGET:mi}});var De=L((K$,vi)=>{function wi(){return ge().getActiveModel()}var Ju={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},sn=new Map,yi=1e3,oo=new WeakMap,on=null;function Vu(){if(on!==null)return on;try{let e=wi()?.provider||"ollama";return on=Ju[e]||4,on}catch{return 4}}function Xu(){on=null}function kt(t){if(!t)return 0;typeof t!="string"&&(t=JSON.stringify(t));let e=t.length<=80?t:`${t.length}:${t.substring(0,60)}:${t.substring(t.length-20)}`,s=sn.get(e);if(s!==void 0)return s;let n=Math.ceil(t.length/Vu());if(sn.size>=yi){let o=yi>>1,r=sn.keys();for(let i=0;i<o;i++)sn.delete(r.next().value)}return sn.set(e,n),n}function Qu(t){if(oo.has(t))return oo.get(t);let e=JSON.stringify(t);return oo.set(t,e),e}function jt(t){let s=4;if(t.content&&(s+=kt(t.content)),t.tool_calls)for(let n of t.tool_calls){s+=4,s+=kt(n.function?.name||"");let o=n.function?.arguments;typeof o=="string"?s+=kt(o):o&&(s+=kt(JSON.stringify(o)))}return s}function je(t){let e=0;for(let s of t)e+=jt(s);return e}function Zu(t,e){if(t&&t.length===e.length){let r=!1;for(let i=0;i<e.length;i++)if(t[i]!==e[i]){r=!0;break}if(!r)return 0}let s=t?t.length:0,n=e.length,o=0;for(let r=s;r<n;r++)o+=jt(e[r]);return o}function Gn(t){return!t||t.length===0?0:kt(JSON.stringify(t))}function zn(){return wi()?.contextWindow||32768}function ed(t,e){let s=je(t),n=Gn(e),o=s+n,r=zn(),i=r>0?o/r*100:0,c=0,l=0,u=0;for(let d of t){let p=jt(d);d.role==="system"?c+=p:d.role==="tool"?u+=p:l+=p}return{used:o,limit:r,percentage:Math.round(i*10)/10,breakdown:{system:c,conversation:l,toolResults:u,toolDefinitions:n},messageCount:t.length}}var bi=.75,xi=.1,_i=10,td=200,nd=500;function ki(t,e){if(!t||t.length<=e)return t;let n=/^(ERROR|EXIT|BLOCKED|CANCELLED)/i.test(t)?e*3:e;if(t.length<=n)return t;let o=t.split(`
53
- `);if(o.length<=10){let m=Math.floor(n*.6),g=Math.floor(n*.4),y=t.substring(0,m),$=t.substring(t.length-g);return y+`
58
+ `)}fa.exports={compactMessages:Af,formatMessagesForSummary:da,COMPACTION_ENABLED:ca,COMPACTION_MIN_MESSAGES:la,COMPACTION_SUMMARY_BUDGET:ua}});var Xe=j((h0,ka)=>{var Of=require("path");function ha(){return we().getActiveModel()}var Nf={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},An=new Map,ma=1e3,Go=new WeakMap,On=null;function Pf(){if(On!==null)return On;try{let e=ha()?.provider||"ollama";return On=Nf[e]||4,On}catch{return 4}}function Mf(){On=null}function qt(t){if(!t)return 0;typeof t!="string"&&(t=JSON.stringify(t));let e=t.length<=80?t:`${t.length}:${t.substring(0,60)}:${t.substring(t.length-20)}`,s=An.get(e);if(s!==void 0)return s;let o=Math.ceil(t.length/Pf());if(An.size>=ma){let n=ma>>1,r=An.keys();for(let i=0;i<n;i++)An.delete(r.next().value)}return An.set(e,o),o}function If(t){if(Go.has(t))return Go.get(t);let e=JSON.stringify(t);return Go.set(t,e),e}function an(t){let s=4;if(t.content&&(s+=qt(t.content)),t.tool_calls)for(let o of t.tool_calls){s+=4,s+=qt(o.function?.name||"");let n=o.function?.arguments;typeof n=="string"?s+=qt(n):n&&(s+=qt(JSON.stringify(n)))}return s}function Ge(t){let e=0;for(let s of t)e+=an(s);return e}function Lf(t,e){if(t&&t.length===e.length){let r=!1;for(let i=0;i<e.length;i++)if(t[i]!==e[i]){r=!0;break}if(!r)return 0}let s=t?t.length:0,o=e.length,n=0;for(let r=s;r<o;r++)n+=an(e[r]);return n}function _s(t){return!t||t.length===0?0:qt(JSON.stringify(t))}function ks(){return ha()?.contextWindow||32768}function jf(t,e){let s=Ge(t),o=_s(e),n=s+o,r=ks(),i=r>0?n/r*100:0,c=0,l=0,u=0;for(let d of t){let f=an(d);d.role==="system"?c+=f:d.role==="tool"?u+=f:l+=f}return{used:n,limit:r,percentage:Math.round(i*10)/10,breakdown:{system:c,conversation:l,toolResults:u,toolDefinitions:o},messageCount:t.length}}var ga=parseFloat(process.env.NEX_COMPRESSION_THRESHOLD)||.75,$a=parseFloat(process.env.NEX_SAFETY_MARGIN)||.1,ya=parseInt(process.env.NEX_KEEP_RECENT,10)||10,Df=200,qf=500;function wa(t,e){if(!t||t.length<=e)return t;let o=/^(ERROR|EXIT|BLOCKED|CANCELLED)/i.test(t)?e*3:e;if(t.length<=o)return t;let n=t.split(`
59
+ `);if(n.length<=10){let p=Math.floor(o*.6),g=Math.floor(o*.4),$=t.substring(0,p),y=t.substring(t.length-g);return $+`
54
60
  ...(${t.length} chars total)...
55
- `+$}let r=Math.floor(o.length*.4),i=Math.floor(o.length*.4),c=[],l=0,u=Math.floor(n*.4);for(let m=0;m<r&&l<u;m++)if(l+o[m].length+1>u&&o[m].trim().startsWith("```")){c.push(o[m]),l+=o[m].length+1;let g=m+1;for(;g<o.length&&l<u*1.5&&!o[g].trim().startsWith("```");)c.push(o[g]),l+=o[g].length+1,g++;g<o.length&&o[g].trim().startsWith("```")&&(c.push(o[g]),l+=o[g].length+1),m=g}else c.push(o[m]),l+=o[m].length+1;let d=[],p=0,f=Math.floor(n*.4);for(let m=o.length-1;m>=o.length-i&&p<f;m--)if(p+o[m].length+1>f&&o[m].trim().startsWith("```")){d.push(o[m]),p+=o[m].length+1;let g=m-1;for(;g>=0&&p<f*1.5&&!o[g].trim().startsWith("```");)d.push(o[g]),p+=o[g].length+1,g--;g>=0&&o[g].trim().startsWith("```")&&(d.push(o[g]),p+=o[g].length+1),m=g}else d.push(o[m]),p+=o[m].length+1;d.reverse();let h=o.length-c.length-d.length;return c.join(`
61
+ `+y}let r=Math.floor(n.length*.4),i=Math.floor(n.length*.4),c=[],l=0,u=Math.floor(o*.4);for(let p=0;p<r&&l<u;p++)if(l+n[p].length+1>u&&n[p].trim().startsWith("```")){c.push(n[p]),l+=n[p].length+1;let g=p+1;for(;g<n.length&&l<u*1.5&&!n[g].trim().startsWith("```");)c.push(n[g]),l+=n[g].length+1,g++;g<n.length&&n[g].trim().startsWith("```")&&(c.push(n[g]),l+=n[g].length+1),p=g}else c.push(n[p]),l+=n[p].length+1;let d=[],f=0,m=Math.floor(o*.4);for(let p=n.length-1;p>=n.length-i&&f<m;p--)if(f+n[p].length+1>m&&n[p].trim().startsWith("```")){d.push(n[p]),f+=n[p].length+1;let g=p-1;for(;g>=0&&f<m*1.5&&!n[g].trim().startsWith("```");)d.push(n[g]),f+=n[g].length+1,g--;g>=0&&n[g].trim().startsWith("```")&&(d.push(n[g]),f+=n[g].length+1),p=g}else d.push(n[p]),f+=n[p].length+1;d.reverse();let h=n.length-c.length-d.length;return c.join(`
56
62
  `)+`
57
- ...(${h} lines omitted, ${o.length} total)...
63
+ ...(${h} lines omitted, ${n.length} total)...
58
64
  `+d.join(`
59
- `)}function rn(t,e="light"){let s=e==="aggressive"?100:e==="medium"?200:nd,n=e==="aggressive"?50:e==="medium"?100:td;if(t.role==="tool"){let o=typeof t.content=="string"?t.content:JSON.stringify(t.content);return o.length>n?{...t,content:ki(o,n)}:t}if(t.role==="assistant"){let o={...t};return o.content&&o.content.length>s&&(o.content=o.content.substring(0,s)+`
60
- ...(truncated)`),o.tool_calls&&e==="aggressive"&&(o.tool_calls=o.tool_calls.map(r=>({...r,function:{name:r.function.name,arguments:typeof r.function.arguments=="string"?r.function.arguments.substring(0,50):r.function.arguments}}))),o}return t}async function sd(t,e,s={}){let n=s.threshold??bi,o=s.safetyMargin??xi,r=s.keepRecent??_i,i=zn(),c=Gn(e),l=Math.floor(i*(n-o)),u=l-c,d=je(t),p=d+c;if(p<=l)return{messages:t,compressed:!1,compacted:!1,tokensRemoved:0};let f=d,h=null,m=0;t.length>0&&t[0].role==="system"&&(h=t[0],m=1);let g=Math.max(m,t.length-r),y=t.slice(m,g),$=t.slice(g),x=y.filter(A=>!A._compacted);if(x.length>=6)try{let{compactMessages:A}=$i(),E=await A(x);if(E){let j=[...y.filter(te=>te._compacted),E.message],Z=_t(h,j,$),G=je(Z);if(G+c<=l)return{messages:Z,compressed:!0,compacted:!0,tokensRemoved:f-G};y=j}}catch(A){process.env.NEX_DEBUG&&console.error("[context-engine] LLM compacting failed:",A.message)}let S=(p-l)/l,k=y.map(A=>rn(A,"light")),v=_t(h,k,$),T=je(v);if(T+c<=l)return{messages:v,compressed:!0,compacted:!1,tokensRemoved:f-T};if(k=y.map(A=>rn(A,"medium")),v=_t(h,k,$),T=je(v),T+c<=l)return{messages:v,compressed:!0,compacted:!1,tokensRemoved:f-T};if(k=y.map(A=>rn(A,"aggressive")),v=_t(h,k,$),T=je(v),T+c<=l)return{messages:v,compressed:!0,compacted:!1,tokensRemoved:f-T};for(;k.length>0&&T>u;){let A=k.shift();T-=jt(A)}return v=_t(h,k,$),T=je(v),{messages:v,compressed:!0,compacted:!1,tokensRemoved:f-T}}function _t(t,e,s){let n=[];return t&&n.push(t),n.push(...e,...s),n}function od(t,e){if(!t)return"";if(kt(t)<=e)return t;let n=e*4,o=t.split(`
61
- `),r=Math.floor(n*.6),i=Math.floor(n*.4),c="",l=0;for(let h of o){if(c.length+h.length+1>r)break;c+=(c?`
62
- `:"")+h,l++}let u="",d=0;for(let h=o.length-1;h>=l;h--){let m=o[h]+(u?`
63
- `:"")+u;if(m.length>i)break;u=m,d++}let f=`
64
-
65
- ... (${o.length-l-d} lines omitted, ${o.length} total) ...
66
-
67
- `;return c+f+u}var rd=6;function id(t,e){let s=zn(),n=Gn(e),o=Math.floor(s*.5)-n,r=je(t),i=null,c=0;t.length>0&&t[0].role==="system"&&(i=t[0],c=1);let l=Math.max(c,t.length-rd),u=t.slice(c,l),d=t.slice(l),p=u.map(m=>rn(m,"aggressive")),f=_t(i,p,d),h=je(f);for(;p.length>0&&h>o;){let m=p.shift();h-=jt(m)}return f=_t(i,p,d),h=je(f),{messages:f,tokensRemoved:r-h}}vi.exports={estimateTokens:kt,estimateMessageTokens:jt,estimateMessagesTokens:je,estimateDeltaTokens:Zu,estimateToolsTokens:Gn,serializeMessage:Qu,getContextWindow:zn,getUsage:ed,compressMessage:rn,compressToolResult:ki,fitToContext:sd,forceCompress:id,truncateFileContent:od,invalidateTokenRatioCache:Xu,COMPRESSION_THRESHOLD:bi,SAFETY_MARGIN:xi,KEEP_RECENT:_i}});var Ri=L((J$,Ti)=>{var Si=require("axios"),{BaseProvider:ad}=Dt(),{serializeMessage:Y$}=De(),Ei={"gpt-4o":{id:"gpt-4o",name:"GPT-4o",maxTokens:16384,contextWindow:128e3},"gpt-4o-mini":{id:"gpt-4o-mini",name:"GPT-4o Mini",maxTokens:16384,contextWindow:128e3},"gpt-4.1":{id:"gpt-4.1",name:"GPT-4.1",maxTokens:32768,contextWindow:128e3},"gpt-4.1-mini":{id:"gpt-4.1-mini",name:"GPT-4.1 Mini",maxTokens:32768,contextWindow:128e3},"gpt-4.1-nano":{id:"gpt-4.1-nano",name:"GPT-4.1 Nano",maxTokens:16384,contextWindow:128e3},o1:{id:"o1",name:"o1",maxTokens:1e5,contextWindow:2e5},o3:{id:"o3",name:"o3",maxTokens:1e5,contextWindow:2e5},"o3-mini":{id:"o3-mini",name:"o3 Mini",maxTokens:65536,contextWindow:2e5},"o4-mini":{id:"o4-mini",name:"o4 Mini",maxTokens:1e5,contextWindow:2e5}},ro=class extends ad{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||Ei,defaultModel:e.defaultModel||"gpt-4o",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OPENAI_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OPENAI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s=[];for(let n of e){if(this._messageFormatCache.has(n)){s.push(this._messageFormatCache.get(n));continue}let o=this._getMessageCacheKey(n);if(this._messageStringCache.has(o)){let i=this._messageStringCache.get(o);this._messageFormatCache.set(n,i),s.push(i);continue}let r=this._formatSingleMessage(n);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(o,r),this._messageFormatCache.set(n,r),s.push(r)}return{messages:s}}_getMessageCacheKey(e){let s=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${s}:${n.length}:${o}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||null,tool_calls:e.tool_calls.map(s=>({id:s.id||`call-${Date.now()}`,type:"function",function:{name:s.function.name,arguments:typeof s.function.arguments=="string"?s.function.arguments:JSON.stringify(s.function.arguments)}}))};if(e.role==="tool")return{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.tool_call_id};if(e.role==="user"&&Array.isArray(e.content)){let s=[];for(let n of e.content)if(n.type==="text")s.push({type:"text",text:n.text??""});else if(n.type==="image"&&n.data){let o=n.data.startsWith("data:")?n.data:`data:${n.media_type||"image/png"};base64,${n.data}`;s.push({type:"image_url",image_url:{url:o,detail:"auto"}})}return{role:"user",content:s}}return{role:e.role,content:e.content}}async chat(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||16384,{messages:c}=this.formatMessages(e),l={model:o,messages:c,max_tokens:i,temperature:n.temperature??this.temperature};s&&s.length>0&&(l.tools=s);let u=await Si.post(`${this.baseUrl}/chat/completions`,l,{timeout:n.timeout||this.timeout,headers:this._getHeaders()});return this.normalizeResponse(u.data)}async stream(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||16384,c=n.onToken||(()=>{}),{messages:l}=this.formatMessages(e),u={model:o,messages:l,max_tokens:i,temperature:n.temperature??this.temperature,stream:!0};s&&s.length>0&&(u.tools=s);let d;try{d=await Si.post(`${this.baseUrl}/chat/completions`,u,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(p){if(p.name==="CanceledError"||p.name==="AbortError"||p.code==="ERR_CANCELED")throw p;let f=p.response?.data?.error?.message||p.message;throw new Error(`API Error: ${f}`)}return new Promise((p,f)=>{let h="",m={},g="";n.signal&&n.signal.addEventListener("abort",()=>{d.data.destroy(),f(new DOMException("The operation was aborted","AbortError"))},{once:!0}),d.data.on("data",y=>{g+=y.toString();let $=g.split(`
68
- `);g=$.pop()||"";for(let x of $){let S=x.trim();if(!S||!S.startsWith("data: "))continue;let k=S.slice(6);if(k==="[DONE]"){p({content:h,tool_calls:this._buildToolCalls(m)});return}let v;try{v=JSON.parse(k)}catch{continue}let T=v.choices?.[0]?.delta;if(T&&(T.content&&(c(T.content),h+=T.content),T.tool_calls))for(let A of T.tool_calls){let E=A.index??0;m[E]||(m[E]={id:A.id||"",name:"",arguments:""}),A.id&&(m[E].id=A.id),A.function?.name&&(m[E].name+=A.function.name),A.function?.arguments&&(m[E].arguments+=A.function.arguments)}}}),d.data.on("error",y=>{n.signal?.aborted||f(new Error(`Stream error: ${y.message}`))}),d.data.on("end",()=>{p({content:h,tool_calls:this._buildToolCalls(m)})})})}normalizeResponse(e){let s=e.choices?.[0]?.message||{},n=(s.tool_calls||[]).map(o=>({id:o.id,function:{name:o.function.name,arguments:o.function.arguments}}));return{content:s.content||"",tool_calls:n}}_buildToolCalls(e){return Object.values(e).filter(s=>s.name).map(s=>({id:s.id||`openai-${Date.now()}`,function:{name:s.name,arguments:s.arguments}}))}};Ti.exports={OpenAIProvider:ro,OPENAI_MODELS:Ei}});var Ni=L((X$,Oi)=>{var Ci=require("axios"),{BaseProvider:cd}=Dt(),{serializeMessage:V$}=De(),Ai={"claude-sonnet":{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6",maxTokens:64e3,contextWindow:2e5},"claude-opus":{id:"claude-opus-4-6",name:"Claude Opus 4.6",maxTokens:128e3,contextWindow:2e5},"claude-haiku":{id:"claude-haiku-4-5-20251001",name:"Claude Haiku 4.5",maxTokens:64e3,contextWindow:2e5},"claude-sonnet-4-5":{id:"claude-sonnet-4-5-20250929",name:"Claude Sonnet 4.5",maxTokens:64e3,contextWindow:2e5},"claude-sonnet-4":{id:"claude-sonnet-4-20250514",name:"Claude Sonnet 4",maxTokens:64e3,contextWindow:2e5}},ld="2023-06-01",io=class extends cd{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||Ai,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||ld}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.ANTHROPIC_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("ANTHROPIC_API_KEY not set");return{"x-api-key":e,"anthropic-version":this.apiVersion,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s="",n=[];for(let o of e){if(o.role==="system"){s+=(s?`
69
-
70
- `:"")+o.content;continue}if(o.role!=="system"&&o.role!=="tool"&&this._messageFormatCache.has(o)){n.push(this._messageFormatCache.get(o));continue}let r=this._formatSingleMessage(o,n);if(r){if(o.role!=="system"&&o.role!=="tool"&&this._messageStringCache.size<this._maxCacheSize){let i=this._getMessageCacheKey(o);this._messageStringCache.set(i,r),this._messageFormatCache.set(o,r)}n.push(r)}}return{messages:n,system:s}}_getMessageCacheKey(e){let s=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${s}:${n.length}:${o}`}_formatSingleMessage(e,s=[]){if(e.role==="assistant"){let n=[];if(e.content&&n.push({type:"text",text:e.content}),e.tool_calls)for(let o of e.tool_calls)n.push({type:"tool_use",id:o.id||`toolu-${Date.now()}`,name:o.function.name,input:typeof o.function.arguments=="string"?JSON.parse(o.function.arguments||"{}"):o.function.arguments||{}});return{role:"assistant",content:n.length>0?n:[{type:"text",text:""}]}}if(e.role==="tool"){let n=s[s.length-1],o={type:"tool_result",tool_use_id:e.tool_call_id,content:typeof e.content=="string"?e.content:JSON.stringify(e.content)};return n&&n.role==="user"&&Array.isArray(n.content)&&n.content[0]?.type==="tool_result"?(n.content.push(o),null):{role:"user",content:[o]}}if(Array.isArray(e.content)){let n=[];for(let o of e.content)o.type==="text"?n.push({type:"text",text:o.text??""}):o.type==="image"&&o.data&&n.push({type:"image",source:{type:"base64",media_type:o.media_type||"image/png",data:o.data}});return{role:"user",content:n}}return{role:"user",content:e.content}}formatTools(e){return!e||e.length===0?[]:e.map(s=>({name:s.function.name,description:s.function.description||"",input_schema:s.function.parameters||{type:"object",properties:{}}}))}_resolveModelId(e){return this.getModel(e)?.id||e}async chat(e,s,n={}){let o=n.model||this.defaultModel,r=this._resolveModelId(o),i=this.getModel(o),c=n.maxTokens||i?.maxTokens||8192,{messages:l,system:u}=this.formatMessages(e),d={model:r,messages:l,max_tokens:c,temperature:n.temperature??this.temperature};u&&(d.system=u);let p=this.formatTools(s);p.length>0&&(d.tools=p);let f=await Ci.post(`${this.baseUrl}/messages`,d,{timeout:n.timeout||this.timeout,headers:this._getHeaders()});return this.normalizeResponse(f.data)}async stream(e,s,n={}){let o=n.model||this.defaultModel,r=this._resolveModelId(o),i=this.getModel(o),c=n.maxTokens||i?.maxTokens||8192,l=n.onToken||(()=>{}),{messages:u,system:d}=this.formatMessages(e),p={model:r,messages:u,max_tokens:c,temperature:n.temperature??this.temperature,stream:!0};d&&(p.system=d);let f=this.formatTools(s);f.length>0&&(p.tools=f);let h;try{h=await Ci.post(`${this.baseUrl}/messages`,p,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(m){if(m.name==="CanceledError"||m.name==="AbortError"||m.code==="ERR_CANCELED")throw m;let g=m.response?.data?.error?.message||m.message;throw new Error(`API Error: ${g}`)}return new Promise((m,g)=>{let y="",$=[],x=-1,S="";n.signal&&n.signal.addEventListener("abort",()=>{h.data.destroy(),g(new DOMException("The operation was aborted","AbortError"))},{once:!0}),h.data.on("data",k=>{S+=k.toString();let v=S.split(`
71
- `);S=v.pop()||"";for(let T of v){let A=T.trim();if(A.startsWith("data: ")){let E=A.slice(6),F;try{F=JSON.parse(E)}catch{continue}switch(F.type){case"content_block_start":{let j=F.content_block;j?.type==="tool_use"&&(x=$.length,$.push({id:j.id,name:j.name,inputJson:""}));break}case"content_block_delta":{let j=F.delta;j?.type==="text_delta"&&j.text&&(l(j.text),y+=j.text),j?.type==="input_json_delta"&&j.partial_json!==void 0&&x>=0&&($[x].inputJson+=j.partial_json);break}case"content_block_stop":x=-1;break;case"message_stop":m({content:y,tool_calls:this._buildToolCalls($)});return}}}}),h.data.on("error",k=>{n.signal?.aborted||g(new Error(`Stream error: ${k.message}`))}),h.data.on("end",()=>{m({content:y,tool_calls:this._buildToolCalls($)})})})}normalizeResponse(e){let s="",n=[];for(let o of e.content||[])o.type==="text"?s+=o.text:o.type==="tool_use"&&n.push({id:o.id,function:{name:o.name,arguments:o.input}});return{content:s,tool_calls:n}}_buildToolCalls(e){return e.filter(s=>s.name).map(s=>{let n={};if(s.inputJson)try{n=JSON.parse(s.inputJson)}catch{n=s.inputJson}return{id:s.id||`anthropic-${Date.now()}`,function:{name:s.name,arguments:n}}})}};Oi.exports={AnthropicProvider:io,ANTHROPIC_MODELS:Ai}});var Ii=L((Z$,Li)=>{var Mi=require("axios"),{BaseProvider:ud}=Dt(),{serializeMessage:Q$}=De(),Pi={"gemini-3.1-pro-preview":{id:"gemini-3.1-pro-preview",name:"Gemini 3.1 Pro Preview",maxTokens:65536,contextWindow:1048576},"gemini-3-flash-preview":{id:"gemini-3-flash-preview",name:"Gemini 3 Flash Preview",maxTokens:65536,contextWindow:1048576},"gemini-2.5-pro":{id:"gemini-2.5-pro",name:"Gemini 2.5 Pro",maxTokens:65536,contextWindow:1048576},"gemini-2.5-flash":{id:"gemini-2.5-flash",name:"Gemini 2.5 Flash",maxTokens:65536,contextWindow:1048576},"gemini-2.5-flash-lite":{id:"gemini-2.5-flash-lite",name:"Gemini 2.5 Flash Lite",maxTokens:65536,contextWindow:1048576},"gemini-2.0-flash":{id:"gemini-2.0-flash",name:"Gemini 2.0 Flash",maxTokens:8192,contextWindow:1048576},"gemini-2.0-flash-lite":{id:"gemini-2.0-flash-lite",name:"Gemini 2.0 Flash Lite",maxTokens:8192,contextWindow:1048576},"gemini-1.5-pro":{id:"gemini-1.5-pro",name:"Gemini 1.5 Pro",maxTokens:8192,contextWindow:1048576},"gemini-1.5-flash":{id:"gemini-1.5-flash",name:"Gemini 1.5 Flash",maxTokens:8192,contextWindow:1048576}},ao=class extends ud{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||Pi,defaultModel:e.defaultModel||"gemini-2.5-flash",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("GEMINI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s=[];for(let n of e){if(this._messageFormatCache.has(n)){s.push(this._messageFormatCache.get(n));continue}let o=this._getMessageCacheKey(n);if(this._messageStringCache.has(o)){let i=this._messageStringCache.get(o);this._messageFormatCache.set(n,i),s.push(i);continue}let r=this._formatSingleMessage(n);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(o,r),this._messageFormatCache.set(n,r),s.push(r)}return{messages:s}}_getMessageCacheKey(e){let s=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${s}:${n.length}:${o}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||"",tool_calls:e.tool_calls.map(s=>({id:s.id||`call-${Date.now()}`,type:"function",function:{name:s.function.name,arguments:typeof s.function.arguments=="string"?s.function.arguments:JSON.stringify(s.function.arguments)}}))};if(e.role==="tool")return{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.tool_call_id};if(e.role==="user"&&Array.isArray(e.content)){let s=[];for(let n of e.content)if(n.type==="text")s.push({type:"text",text:n.text??""});else if(n.type==="image"&&n.data){let o=n.data.startsWith("data:")?n.data:`data:${n.media_type||"image/png"};base64,${n.data}`;s.push({type:"image_url",image_url:{url:o,detail:"auto"}})}return{role:"user",content:s}}return{role:e.role,content:e.content}}async chat(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||8192,{messages:c}=this.formatMessages(e),l={model:o,messages:c,max_tokens:i,temperature:n.temperature??this.temperature};s&&s.length>0&&(l.tools=s);let u=await Mi.post(`${this.baseUrl}/chat/completions`,l,{timeout:n.timeout||this.timeout,headers:this._getHeaders()});return this.normalizeResponse(u.data)}async stream(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||8192,c=n.onToken||(()=>{}),{messages:l}=this.formatMessages(e),u={model:o,messages:l,max_tokens:i,temperature:n.temperature??this.temperature,stream:!0};s&&s.length>0&&(u.tools=s);let d;try{d=await Mi.post(`${this.baseUrl}/chat/completions`,u,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(p){if(p.name==="CanceledError"||p.name==="AbortError"||p.code==="ERR_CANCELED")throw p;let f=p.response?.data?.error?.message||p.message;throw new Error(`API Error: ${f}`)}return new Promise((p,f)=>{let h="",m={},g="";n.signal&&n.signal.addEventListener("abort",()=>{d.data.destroy(),f(new DOMException("The operation was aborted","AbortError"))},{once:!0}),d.data.on("data",y=>{g+=y.toString();let $=g.split(`
72
- `);g=$.pop()||"";for(let x of $){let S=x.trim();if(!S||!S.startsWith("data: "))continue;let k=S.slice(6);if(k==="[DONE]"){p({content:h,tool_calls:this._buildToolCalls(m)});return}let v;try{v=JSON.parse(k)}catch{continue}let T=v.choices?.[0]?.delta;if(T&&(T.content&&(c(T.content),h+=T.content),T.tool_calls))for(let A of T.tool_calls){let E=A.index??0;m[E]||(m[E]={id:A.id||"",name:"",arguments:""}),A.id&&(m[E].id=A.id),A.function?.name&&(m[E].name+=A.function.name),A.function?.arguments&&(m[E].arguments+=A.function.arguments)}}}),d.data.on("error",y=>{n.signal?.aborted||f(new Error(`Stream error: ${y.message}`))}),d.data.on("end",()=>{p({content:h,tool_calls:this._buildToolCalls(m)})})})}normalizeResponse(e){let s=e.choices?.[0]?.message||{},n=(s.tool_calls||[]).map(o=>({id:o.id,function:{name:o.function.name,arguments:o.function.arguments}}));return{content:s.content||"",tool_calls:n}}_buildToolCalls(e){return Object.values(e).filter(s=>s.name).map(s=>({id:s.id||`call-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,function:{name:s.name,arguments:s.arguments}}))}};Li.exports={GeminiProvider:ao,GEMINI_MODELS:Pi}});var ji=L((ey,Di)=>{var Kn=require("axios"),{BaseProvider:dd}=Dt(),qi="http://localhost:11434",co=class extends dd{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||qi,models:e.models||{},defaultModel:e.defaultModel||null,...e}),this.timeout=e.timeout||3e5,this.temperature=e.temperature??.2,this._modelsLoaded=!1}isConfigured(){return!0}async loadModels(){if(this._modelsLoaded)return this.models;try{let s=(await Kn.get(`${this.baseUrl}/api/tags`,{timeout:5e3})).data?.models||[];this.models={};for(let n of s){let o=n.name||n.model;if(!o)continue;let r=o.replace(/:latest$/,""),i=32768;try{let c=await Kn.post(`${this.baseUrl}/api/show`,{name:o},{timeout:5e3}),l=c.data?.model_info||c.data?.details||{};i=l["general.context_length"]||l["llama.context_length"]||this._parseContextFromModelfile(c.data?.modelfile)||32768}catch{}this.models[r]={id:r,name:n.name,maxTokens:Math.min(8192,Math.floor(i*.1)),contextWindow:i}}!this.defaultModel&&Object.keys(this.models).length>0&&(this.defaultModel=Object.keys(this.models)[0]),this._modelsLoaded=!0}catch{this.models={},this._modelsLoaded=!1}return this.models}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}_formatMessages(e){return e.map(s=>{if(s.role==="user"&&Array.isArray(s.content)){let n=[],o=[];for(let i of s.content)i.type==="text"?n.push(i.text??""):i.type==="image"&&i.data&&o.push(i.data);let r={role:"user",content:n.join(`
73
- `)};return o.length>0&&(r.images=o),r}return s})}async chat(e,s,n={}){this._modelsLoaded||await this.loadModels();let o=n.model||this.defaultModel;if(!o)throw new Error("No local model available. Is Ollama running?");let r=await Kn.post(`${this.baseUrl}/api/chat`,{model:o,messages:this._formatMessages(e),tools:s&&s.length>0?s:void 0,stream:!1,options:{temperature:n.temperature??this.temperature,num_predict:n.maxTokens||8192}},{timeout:n.timeout||this.timeout});return this.normalizeResponse(r.data)}async stream(e,s,n={}){this._modelsLoaded||await this.loadModels();let o=n.model||this.defaultModel;if(!o)throw new Error("No local model available. Is Ollama running?");let r=n.onToken||(()=>{}),i;try{i=await Kn.post(`${this.baseUrl}/api/chat`,{model:o,messages:this._formatMessages(e),tools:s&&s.length>0?s:void 0,stream:!0,options:{temperature:n.temperature??this.temperature,num_predict:n.maxTokens||8192}},{timeout:n.timeout||this.timeout,responseType:"stream",signal:n.signal})}catch(c){if(c.name==="CanceledError"||c.name==="AbortError"||c.code==="ERR_CANCELED")throw c;let l=c.response?.data?.error||c.message;throw new Error(`API Error: ${l}`)}return new Promise((c,l)=>{let u="",d=[],p="";n.signal&&n.signal.addEventListener("abort",()=>{i.data.destroy(),l(new DOMException("The operation was aborted","AbortError"))},{once:!0}),i.data.on("data",f=>{p+=f.toString();let h=p.split(`
74
- `);p=h.pop()||"";for(let m of h){if(!m.trim())continue;let g;try{g=JSON.parse(m)}catch{continue}if(g.message?.content&&(r(g.message.content),u+=g.message.content),g.message?.tool_calls&&(d=d.concat(g.message.tool_calls)),g.done){c({content:u,tool_calls:this._normalizeToolCalls(d)});return}}}),i.data.on("error",f=>{n.signal?.aborted||l(new Error(`Stream error: ${f.message}`))}),i.data.on("end",()=>{if(p.trim())try{let f=JSON.parse(p);f.message?.content&&(r(f.message.content),u+=f.message.content),f.message?.tool_calls&&(d=d.concat(f.message.tool_calls))}catch{}c({content:u,tool_calls:this._normalizeToolCalls(d)})})})}normalizeResponse(e){let s=e.message||{};return{content:s.content||"",tool_calls:this._normalizeToolCalls(s.tool_calls||[])}}_parseContextFromModelfile(e){if(!e)return null;let s=e.match(/PARAMETER\s+num_ctx\s+(\d+)/i);return s?parseInt(s[1],10):null}_normalizeToolCalls(e){return e.map((s,n)=>({id:s.id||`local-${Date.now()}-${n}`,function:{name:s.function?.name||s.name||"unknown",arguments:s.function?.arguments||s.arguments||{}}}))}};Di.exports={LocalProvider:co,DEFAULT_LOCAL_URL:qi}});var Ft=L((ty,zi)=>{var vt=require("fs"),lo=require("path"),Fi={openai:{"gpt-4o":{input:2.5,output:10},"gpt-4o-mini":{input:.15,output:.6},"gpt-4.1":{input:2,output:8},"gpt-4.1-mini":{input:.4,output:1.6},"gpt-4.1-nano":{input:.1,output:.4},o1:{input:15,output:60},o3:{input:10,output:40},"o3-mini":{input:1.1,output:4.4},"o4-mini":{input:1.1,output:4.4}},anthropic:{"claude-sonnet":{input:3,output:15},"claude-opus":{input:5,output:25},"claude-haiku":{input:.8,output:4},"claude-sonnet-4-5":{input:3,output:15},"claude-sonnet-4":{input:3,output:15}},gemini:{"gemini-2.5-pro":{input:1.25,output:10},"gemini-2.5-flash":{input:.15,output:.6},"gemini-2.0-flash":{input:.1,output:.4},"gemini-2.0-flash-lite":{input:.075,output:.3}},ollama:{"qwen3-coder:480b":{input:0,output:0},"qwen3-coder-next":{input:0,output:0},"devstral-2:123b":{input:0,output:0},"devstral-small-2:24b":{input:0,output:0},"kimi-k2.5":{input:0,output:0},"kimi-k2:1t":{input:0,output:0},"deepseek-v3.2":{input:0,output:0},"minimax-m2.5":{input:0,output:0},"glm-5":{input:0,output:0},"glm-4.7":{input:0,output:0},"gpt-oss:120b":{input:0,output:0}},local:{}},Yn=[],dt={};function fd(t,e,s,n){if(Yn.push({provider:t,model:e,input:s,output:n}),dt[t]!==void 0){let o=Hi(t);o.allowed||process.stderr.write(`\x1B[33m\u26A0 Budget limit reached for ${t}: $${o.spent.toFixed(2)} / $${o.limit.toFixed(2)}\x1B[0m
75
- `)}}function uo(t,e){let s=Fi[t];return s?s[e]||{input:0,output:0}:{input:0,output:0}}function Ui(t){let e=uo(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function Wi(){let t={};for(let r of Yn){let i=`${r.provider}:${r.model}`;t[i]||(t[i]={provider:r.provider,model:r.model,input:0,output:0}),t[i].input+=r.input,t[i].output+=r.output}let e=Object.values(t).map(r=>({...r,cost:Ui(r)})),s=e.reduce((r,i)=>r+i.cost,0),n=e.reduce((r,i)=>r+i.input,0),o=e.reduce((r,i)=>r+i.output,0);return{totalCost:s,totalInput:n,totalOutput:o,breakdown:e}}function pd(){let{totalCost:t,totalInput:e,totalOutput:s,breakdown:n}=Wi();if(n.length===0)return"No token usage recorded this session.";let o=[];o.push("Session Token Usage:"),o.push("");for(let r of n){let i=r.cost>0?`$${r.cost.toFixed(4)}`:"free";o.push(` ${r.provider}:${r.model}`),o.push(` Input: ${r.input.toLocaleString()} tokens`),o.push(` Output: ${r.output.toLocaleString()} tokens`),o.push(` Cost: ${i}`)}return o.push(""),o.push(` Total: ${e.toLocaleString()} in + ${s.toLocaleString()} out = $${t.toFixed(4)}`),o.join(`
76
- `)}function md(t,e,s,n){let o=uo(t,e),r=(s*o.input+n*o.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function hd(){Yn=[]}function gd(t,e){dt[t]=e}function $d(t){delete dt[t]}function yd(){return{...dt}}function Bi(t){let e=0;for(let s of Yn)s.provider===t&&(e+=Ui(s));return e}function Hi(t){let e=Bi(t),s=dt[t];if(s===void 0)return{allowed:!0,spent:e,limit:null,remaining:null};let n=Math.max(0,s-e);return{allowed:e<s,spent:e,limit:s,remaining:n}}function Gi(){let t=lo.join(process.cwd(),".nex","config.json");if(vt.existsSync(t))try{let e=JSON.parse(vt.readFileSync(t,"utf-8"));e.costLimits&&typeof e.costLimits=="object"&&(dt={...e.costLimits})}catch{}}function wd(){let t=lo.join(process.cwd(),".nex"),e=lo.join(t,"config.json"),s={};if(vt.existsSync(e))try{s=JSON.parse(vt.readFileSync(e,"utf-8"))}catch{s={}}s.costLimits=dt,vt.existsSync(t)||vt.mkdirSync(t,{recursive:!0}),vt.writeFileSync(e,JSON.stringify(s,null,2),"utf-8")}function bd(){dt={}}Gi();zi.exports={PRICING:Fi,trackUsage:fd,getSessionCosts:Wi,formatCosts:pd,formatCostHint:md,resetCosts:hd,getPricing:uo,setCostLimit:gd,removeCostLimit:$d,getCostLimits:yd,getProviderSpend:Bi,checkBudget:Hi,loadCostLimits:Gi,saveCostLimits:wd,resetCostLimits:bd}});var Jn=L((ny,Ki)=>{var an=ge(),xd={"kimi-k2.5":{id:"kimi-k2.5",name:"Kimi K2.5",max_tokens:16384},"qwen3-coder:480b":{id:"qwen3-coder:480b",name:"Qwen3 Coder 480B",max_tokens:16384}};function _d(){return an.getActiveModel()}function kd(t){return an.setActiveModel(t)}function vd(){return an.getModelNames()}function Sd(t){if(!t)return null;if(typeof t=="object")return t;try{return JSON.parse(t)}catch{}try{let n=t.replace(/,\s*([}\]])/g,"$1").replace(/'/g,'"');return JSON.parse(n)}catch{}let e=t.match(/\{[\s\S]*\}/);if(e)try{return JSON.parse(e[0])}catch{}try{let n=t.replace(/(\{|,)\s*([a-zA-Z_]\w*)\s*:/g,'$1"$2":');return JSON.parse(n)}catch{}let s=t.match(/```(?:json)?\s*([\s\S]*?)```/);if(s)try{return JSON.parse(s[1].trim())}catch{}return null}async function Ed(t,e){let{C:s}=de(),{Spinner:n}=de(),o=new n("Thinking...");o.start();let r=!0,i="";try{let c=await an.callStream(t,e,{onToken:l=>{r&&(o.stop(),process.stdout.write(`${s.blue}`),r=!1),process.stdout.write(l),i+=l}});return r?o.stop():process.stdout.write(`${s.reset}
77
- `),c}catch(c){throw o.stop(),c}}async function Td(t,e){return an.callChat(t,e)}Ki.exports={MODELS:xd,getActiveModel:_d,setActiveModel:kd,getModelNames:vd,callOllamaStream:Ed,callOllama:Td,parseToolArgs:Sd}});var Vi=L((sy,Ji)=>{var Vn=require("path"),{C:_}=de(),{confirm:Rd,getAutoConfirm:Cd}=We(),Yi=2e3;function cn(t,e){let s=t.split(`
78
- `),n=e.split(`
79
- `),o=[],r=s.length,i=n.length;if(r>Yi||i>Yi){for(let p of s)o.push({type:"remove",line:p});for(let p of n)o.push({type:"add",line:p});return o}let c=Array.from({length:r+1},()=>new Array(i+1).fill(0));for(let p=1;p<=r;p++)for(let f=1;f<=i;f++)s[p-1]===n[f-1]?c[p][f]=c[p-1][f-1]+1:c[p][f]=Math.max(c[p-1][f],c[p][f-1]);let l=r,u=i,d=[];for(;l>0||u>0;)l>0&&u>0&&s[l-1]===n[u-1]?(d.unshift({type:"same",line:s[l-1]}),l--,u--):u>0&&(l===0||c[l][u-1]>=c[l-1][u])?(d.unshift({type:"add",line:n[u-1]}),u--):(d.unshift({type:"remove",line:s[l-1]}),l--);return d}function Ad(t,e,s,n=3){console.log(`
80
- ${_.bold}${_.cyan} Diff: ${t}${_.reset}`);let o=cn(e,s),r=[];if(o.forEach((l,u)=>{l.type!=="same"&&r.push(u)}),r.length===0){console.log(`${_.gray} (no changes)${_.reset}`);return}let i=Math.max(0,r[0]-n),c=Math.min(o.length,r[r.length-1]+n+1);i>0&&console.log(`${_.gray} ...${_.reset}`);for(let l=i;l<c;l++){let u=o[l];switch(u.type){case"remove":console.log(`${_.red} - ${u.line}${_.reset}`);break;case"add":console.log(`${_.green} + ${u.line}${_.reset}`);break;default:console.log(`${_.gray} ${u.line}${_.reset}`)}}c<o.length&&console.log(`${_.gray} ...${_.reset}`),console.log()}function Od(t,e,s){console.log(`
81
- ${_.bold}${_.cyan} File exists \u2014 showing changes: ${t}${_.reset}`);let n=cn(e,s),o=0;for(let i of n)i.type!=="same"&&o++;if(o===0){console.log(`${_.gray} (identical content)${_.reset}`);return}let r=0;for(let i of n){if(r>=30){console.log(`${_.gray} ...(${o-r} more changes)${_.reset}`);break}switch(i.type){case"remove":console.log(`${_.red} - ${i.line}${_.reset}`),r++;break;case"add":console.log(`${_.green} + ${i.line}${_.reset}`),r++;break;default:r>0&&console.log(`${_.gray} ${i.line}${_.reset}`)}}console.log()}function Nd(t,e){console.log(`
82
- ${_.bold}${_.cyan} New file: ${t}${_.reset}`);let s=e.split(`
83
- `),n=s.slice(0,20);for(let o of n)console.log(`${_.green} + ${o}${_.reset}`);s.length>20&&console.log(`${_.gray} ...+${s.length-20} more lines${_.reset}`),console.log()}async function Md(t){return Cd()?!0:Rd(` ${t}?`)}function Pd(t,e,s,n){let o=n||process.stdout.columns||80,r=Math.floor((o-3)/2);console.log(`
84
- ${_.bold}${_.cyan} Side-by-side: ${t}${_.reset}`),console.log(` ${_.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${_.reset}`);let i=cn(e,s),c=[],l=0;for(;l<i.length;)if(i[l].type==="same")c.push({left:i[l].line,right:i[l].line,type:"same"}),l++;else if(i[l].type==="remove"){let h=[];for(;l<i.length&&i[l].type==="remove";)h.push(i[l].line),l++;let m=[];for(;l<i.length&&i[l].type==="add";)m.push(i[l].line),l++;let g=Math.max(h.length,m.length);for(let y=0;y<g;y++)c.push({left:y<h.length?h[y]:"",right:y<m.length?m[y]:"",type:"changed"})}else i[l].type==="add"&&(c.push({left:"",right:i[l].line,type:"changed"}),l++);let u=c.map((h,m)=>h.type!=="same"?m:-1).filter(h=>h>=0);if(u.length===0){console.log(` ${_.gray}(no changes)${_.reset}`);return}let d=Math.max(0,u[0]-2),p=Math.min(c.length,u[u.length-1]+3),f=(h,m)=>{let g=h.replace(/\x1b\[[0-9;]*m/g,"");return g.length>=m?h.substring(0,m):h+" ".repeat(m-g.length)};d>0&&console.log(` ${_.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${_.reset}`);for(let h=d;h<p;h++){let m=c[h];if(m.type==="same")console.log(` ${_.gray}${f(m.left,r)}${_.reset}\u2502${_.gray}${f(m.right,r)}${_.reset}`);else{let g=m.left?`${_.red}${f(m.left,r)}${_.reset}`:`${f("",r)}`,y=m.right?`${_.green}${f(m.right,r)}${_.reset}`:`${f("",r)}`;console.log(` ${g}\u2502${y}`)}}p<c.length&&console.log(` ${_.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${_.reset}`),console.log(` ${_.dim}${"\u2500".repeat(r)}\u2534${"\u2500".repeat(r)}${_.reset}
85
- `)}function Ld(t,e,s,n={}){let o=n.label||"Update",r=n.context||3,i=n.annotations||[],c=Vn.isAbsolute(t)?Vn.relative(process.cwd(),t):t,l=cn(e,s),u=1,d=1;for(let k of l)k.type==="same"?(k.oldLine=u++,k.newLine=d++):k.type==="remove"?(k.oldLine=u++,k.newLine=null):(k.oldLine=null,k.newLine=d++);let p=0,f=0;for(let k of l)k.type==="add"?p++:k.type==="remove"&&f++;if(console.log(`
86
- ${_.cyan}\u23FA${_.reset} ${_.bold}${o}(${c})${_.reset}`),p===0&&f===0){console.log(` ${_.dim}\u23BF (no changes)${_.reset}
87
- `);return}let h=[];if(p>0&&h.push(`Added ${p} line${p!==1?"s":""}`),f>0&&h.push(`removed ${f} line${f!==1?"s":""}`),i.length>0){let k=i.filter(E=>E.severity==="error").length,v=i.filter(E=>E.severity==="warn").length,T=i.filter(E=>E.severity==="info").length,A=[];k>0&&A.push(`${_.red}${k} error${k!==1?"s":""}${_.dim}`),v>0&&A.push(`${_.yellow}${v} warning${v!==1?"s":""}${_.dim}`),T>0&&A.push(`${_.cyan}${T} info${T!==1?"s":""}${_.dim}`),h.push(`found ${A.join(", ")}`)}console.log(` ${_.dim}\u23BF ${h.join(", ")}${_.reset}`);let g=[];l.forEach((k,v)=>{k.type!=="same"&&g.push(v)});let y=[],$=null,x=null;for(let k of g){let v=Math.max(0,k-r),T=Math.min(l.length-1,k+r);$===null?($=v,x=T):(v<=x+1||(y.push([$,x]),$=v),x=T)}$!==null&&y.push([$,x]);let S=" ";for(let k=0;k<y.length;k++){k>0&&console.log(`${S}${_.dim}\xB7\xB7\xB7${_.reset}`);let[v,T]=y[k];for(let A=v;A<=T;A++){let E=l[A],F=E.newLine!=null?E.newLine:E.oldLine,j=String(F).padStart(4),Z=E.type!=="remove"?i.filter(G=>G.line===E.newLine):[];E.type==="remove"?console.log(`${S}${_.red}${j} -${E.line}${_.reset}`):E.type==="add"?console.log(`${S}${_.green}${j} +${E.line}${_.reset}`):console.log(`${S}${_.dim}${j}${_.reset} ${E.line}`);for(let G of Z){let te=_.cyan,me="\u2139";G.severity==="error"?(te=_.red,me="\u2716"):G.severity==="warn"&&(te=_.yellow,me="\u26A0"),console.log(`${S} ${te}${me} ${G.message}${_.reset}`)}}}console.log()}function Id(t,e,s={}){let n=Vn.isAbsolute(t)?Vn.relative(process.cwd(),t):t,o=e.split(`
65
+ `)}function rn(t,e="light"){let s=e==="aggressive"?100:e==="medium"?200:qf,o=e==="aggressive"?50:e==="medium"?100:Df;if(t.role==="tool"){let n=typeof t.content=="string"?t.content:JSON.stringify(t.content);return n.length>o?{...t,content:wa(n,o)}:t}if(t.role==="assistant"){let n={...t};return n.content&&n.content.length>s&&(n.content=n.content.substring(0,s)+`
66
+ ...(truncated)`),n.tool_calls&&e==="aggressive"&&(n.tool_calls=n.tool_calls.map(r=>({...r,function:{name:r.function.name,arguments:typeof r.function.arguments=="string"?r.function.arguments.substring(0,50):r.function.arguments}}))),n}return t}function ba(t,e,s,o){let n=0;if(t.role==="system")return 100;if(t.role==="user")n+=35;else if(t.role==="tool"){let i=typeof t.content=="string"?t.content:JSON.stringify(t.content||"");/^(ERROR|BLOCKED|CANCELLED)/i.test(i)?n+=30:n+=15}else t.role==="assistant"&&(n+=t.tool_calls?20:10);let r=s>1?e/(s-1):1;if(n+=Math.round(r*30),o&&o.size>0){let i=typeof t.content=="string"?t.content:JSON.stringify(t.content||""),c=0;for(let l of o)(i.includes(l)||i.includes(Of.basename(l)))&&c++;n+=Math.min(30,c*10)}return Math.min(100,n)}function _a(t,e=10){let s=new Set,o=t.slice(-e),n=/(?:\/[\w.-]+)+\.\w+/g;for(let r of o){let c=(typeof r.content=="string"?r.content:JSON.stringify(r.content||"")).match(n);c&&c.forEach(l=>s.add(l))}return s}async function Ff(t,e,s={}){let o=s.threshold??ga,n=s.safetyMargin??$a,r=s.keepRecent??ya,i=ks(),c=_s(e),l=Math.floor(i*(o-n)),u=l-c,d=Ge(t),f=d+c;if(f<=l)return{messages:t,compressed:!1,compacted:!1,tokensRemoved:0};let m=d,h=null,p=0;t.length>0&&t[0].role==="system"&&(h=t[0],p=1);let g=Math.max(p,t.length-r),$=t.slice(p,g),y=t.slice(g),w=$.filter(I=>!I._compacted);if(w.length>=6)try{let{compactMessages:I}=pa(),D=await I(w);if(D){let z=[...$.filter(Y=>Y._compacted),D.message],Q=xt(h,z,y),Z=Ge(Q);if(Z+c<=l)return{messages:Q,compressed:!0,compacted:!0,tokensRemoved:m-Z};$=z}}catch(I){process.env.NEX_DEBUG&&console.error("[context-engine] LLM compacting failed:",I.message)}let T=(f-l)/l,_=$.map(I=>rn(I,"light")),x=xt(h,_,y),S=Ge(x);if(S+c<=l)return{messages:x,compressed:!0,compacted:!1,tokensRemoved:m-S};if(_=$.map(I=>rn(I,"medium")),x=xt(h,_,y),S=Ge(x),S+c<=l)return{messages:x,compressed:!0,compacted:!1,tokensRemoved:m-S};if(_=$.map(I=>rn(I,"aggressive")),x=xt(h,_,y),S=Ge(x),S+c<=l)return{messages:x,compressed:!0,compacted:!1,tokensRemoved:m-S};let R=_a([..._,...y]),C=_.map((I,D)=>({msg:I,score:ba(I,D,_.length,R),tokens:an(I)}));for(;C.length>0&&S>u;){let I=0;for(let D=1;D<C.length;D++)C[D].score<C[I].score&&(I=D);S-=C[I].tokens,C.splice(I,1)}return _=C.map(I=>I.msg),x=xt(h,_,y),S=Ge(x),{messages:x,compressed:!0,compacted:!1,tokensRemoved:m-S}}function xt(t,e,s){let o=[];return t&&o.push(t),o.push(...e,...s),o}function Uf(t,e){if(!t)return"";if(qt(t)<=e)return t;let o=e*4,n=t.split(`
67
+ `),r=Math.floor(o*.6),i=Math.floor(o*.4),c="",l=0;for(let h of n){if(c.length+h.length+1>r)break;c+=(c?`
68
+ `:"")+h,l++}let u="",d=0;for(let h=n.length-1;h>=l;h--){let p=n[h]+(u?`
69
+ `:"")+u;if(p.length>i)break;u=p,d++}let m=`
70
+
71
+ ... (${n.length-l-d} lines omitted, ${n.length} total) ...
72
+
73
+ `;return c+m+u}var Wf=6;function Bf(t,e,s=!1){let o=ks(),n=_s(e),r=Math.floor(o*(s?.35:.5))-n,i=Ge(t),c=Math.floor(i*(s?.5:.8));r>c&&(r=c);let l=null,u=0;t.length>0&&t[0].role==="system"&&(l=t[0],u=1);let d=s?2:Wf,f=Math.max(u,t.length-d),m=t.slice(u,f),h=t.slice(f),p=m.map(y=>rn(y,"aggressive"));s&&(h=h.map(y=>rn(y,"aggressive")));let g=xt(l,p,h),$=Ge(g);for(;p.length>0&&$>r;){let y=p.shift();$-=an(y)}return s&&$>r&&(h=h.filter(w=>w.role==="user").slice(-1),g=xt(l,[],h),$=Ge(g)),g=xt(l,p,h),{messages:g,tokensRemoved:i-Ge(g)}}ka.exports={estimateTokens:qt,estimateMessageTokens:an,estimateMessagesTokens:Ge,estimateDeltaTokens:Lf,estimateToolsTokens:_s,serializeMessage:If,getContextWindow:ks,getUsage:jf,compressMessage:rn,compressToolResult:wa,scoreMessageRelevance:ba,extractActiveFiles:_a,fitToContext:Ff,forceCompress:Bf,truncateFileContent:Uf,invalidateTokenRatioCache:Mf,COMPRESSION_THRESHOLD:ga,SAFETY_MARGIN:$a,KEEP_RECENT:ya}});var Ea=j(($0,Sa)=>{var xa=require("axios"),{BaseProvider:Hf}=on(),{serializeMessage:g0}=Xe(),va={"gpt-4o":{id:"gpt-4o",name:"GPT-4o",maxTokens:16384,contextWindow:128e3},"gpt-4o-mini":{id:"gpt-4o-mini",name:"GPT-4o Mini",maxTokens:16384,contextWindow:128e3},"gpt-4.1":{id:"gpt-4.1",name:"GPT-4.1",maxTokens:32768,contextWindow:128e3},"gpt-4.1-mini":{id:"gpt-4.1-mini",name:"GPT-4.1 Mini",maxTokens:32768,contextWindow:128e3},"gpt-4.1-nano":{id:"gpt-4.1-nano",name:"GPT-4.1 Nano",maxTokens:16384,contextWindow:128e3},o1:{id:"o1",name:"o1",maxTokens:1e5,contextWindow:2e5},o3:{id:"o3",name:"o3",maxTokens:1e5,contextWindow:2e5},"o3-mini":{id:"o3-mini",name:"o3 Mini",maxTokens:65536,contextWindow:2e5},"o4-mini":{id:"o4-mini",name:"o4 Mini",maxTokens:1e5,contextWindow:2e5}},Ko=class extends Hf{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||va,defaultModel:e.defaultModel||"gpt-4o",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OPENAI_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OPENAI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s=[];for(let o of e){if(this._messageFormatCache.has(o)){s.push(this._messageFormatCache.get(o));continue}let n=this._getMessageCacheKey(o);if(this._messageStringCache.has(n)){let i=this._messageStringCache.get(n);this._messageFormatCache.set(o,i),s.push(i);continue}let r=this._formatSingleMessage(o);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(n,r),this._messageFormatCache.set(o,r),s.push(r)}return{messages:s}}_getMessageCacheKey(e){let s=e.role||"",o=typeof e.content=="string"?e.content.substring(0,100):"",n=e.tool_calls?e.tool_calls.length:0;return`${s}:${o.length}:${n}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||null,tool_calls:e.tool_calls.map(s=>({id:s.id||`call-${Date.now()}`,type:"function",function:{name:s.function.name,arguments:typeof s.function.arguments=="string"?s.function.arguments:JSON.stringify(s.function.arguments)}}))};if(e.role==="tool")return{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.tool_call_id};if(e.role==="user"&&Array.isArray(e.content)){let s=[];for(let o of e.content)if(o.type==="text")s.push({type:"text",text:o.text??""});else if(o.type==="image"&&o.data){let n=o.data.startsWith("data:")?o.data:`data:${o.media_type||"image/png"};base64,${o.data}`;s.push({type:"image_url",image_url:{url:n,detail:"auto"}})}return{role:"user",content:s}}return{role:e.role,content:e.content}}async chat(e,s,o={}){let n=o.model||this.defaultModel,r=this.getModel(n),i=o.maxTokens||r?.maxTokens||16384,{messages:c}=this.formatMessages(e),l={model:n,messages:c,max_tokens:i,temperature:o.temperature??this.temperature};s&&s.length>0&&(l.tools=s);let u=await xa.post(`${this.baseUrl}/chat/completions`,l,{timeout:o.timeout||this.timeout,headers:this._getHeaders()});return this.normalizeResponse(u.data)}async stream(e,s,o={}){let n=o.model||this.defaultModel,r=this.getModel(n),i=o.maxTokens||r?.maxTokens||16384,c=o.onToken||(()=>{}),{messages:l}=this.formatMessages(e),u={model:n,messages:l,max_tokens:i,temperature:o.temperature??this.temperature,stream:!0};s&&s.length>0&&(u.tools=s);let d;try{d=await xa.post(`${this.baseUrl}/chat/completions`,u,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let m=f.response?.data?.error?.message||f.message;throw new Error(`API Error: ${m}`)}return new Promise((f,m)=>{let h="",p={},g="";o.signal&&o.signal.addEventListener("abort",()=>{d.data.destroy(),m(new DOMException("The operation was aborted","AbortError"))},{once:!0}),d.data.on("data",$=>{g+=$.toString();let y=g.split(`
74
+ `);g=y.pop()||"";for(let w of y){let T=w.trim();if(!T||!T.startsWith("data: "))continue;let _=T.slice(6);if(_==="[DONE]"){f({content:h,tool_calls:this._buildToolCalls(p)});return}let x;try{x=JSON.parse(_)}catch{continue}let S=x.choices?.[0]?.delta;if(S&&(S.content&&(c(S.content),h+=S.content),S.tool_calls))for(let R of S.tool_calls){let C=R.index??0;p[C]||(p[C]={id:R.id||"",name:"",arguments:""}),R.id&&(p[C].id=R.id),R.function?.name&&(p[C].name+=R.function.name),R.function?.arguments&&(p[C].arguments+=R.function.arguments)}}}),d.data.on("error",$=>{o.signal?.aborted||m(new Error(`Stream error: ${$.message}`))}),d.data.on("end",()=>{f({content:h,tool_calls:this._buildToolCalls(p)})})})}normalizeResponse(e){let s=e.choices?.[0]?.message||{},o=(s.tool_calls||[]).map(n=>({id:n.id,function:{name:n.function.name,arguments:n.function.arguments}}));return{content:s.content||"",tool_calls:o}}_buildToolCalls(e){return Object.values(e).filter(s=>s.name).map(s=>({id:s.id||`openai-${Date.now()}`,function:{name:s.name,arguments:s.arguments}}))}};Sa.exports={OpenAIProvider:Ko,OPENAI_MODELS:va}});var Aa=j((w0,Ca)=>{var Ta=require("axios"),{BaseProvider:Gf}=on(),{serializeMessage:y0}=Xe(),Ra={"claude-sonnet":{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6",maxTokens:64e3,contextWindow:2e5},"claude-opus":{id:"claude-opus-4-6",name:"Claude Opus 4.6",maxTokens:128e3,contextWindow:2e5},"claude-haiku":{id:"claude-haiku-4-5-20251001",name:"Claude Haiku 4.5",maxTokens:64e3,contextWindow:2e5},"claude-sonnet-4-5":{id:"claude-sonnet-4-5-20250929",name:"Claude Sonnet 4.5",maxTokens:64e3,contextWindow:2e5},"claude-sonnet-4":{id:"claude-sonnet-4-20250514",name:"Claude Sonnet 4",maxTokens:64e3,contextWindow:2e5}},Kf="2023-06-01",zo=class extends Gf{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||Ra,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||Kf}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.ANTHROPIC_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("ANTHROPIC_API_KEY not set");return{"x-api-key":e,"anthropic-version":this.apiVersion,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s="",o=[];for(let n of e){if(n.role==="system"){s+=(s?`
75
+
76
+ `:"")+n.content;continue}if(n.role!=="system"&&n.role!=="tool"&&this._messageFormatCache.has(n)){o.push(this._messageFormatCache.get(n));continue}let r=this._formatSingleMessage(n,o);if(r){if(n.role!=="system"&&n.role!=="tool"&&this._messageStringCache.size<this._maxCacheSize){let i=this._getMessageCacheKey(n);this._messageStringCache.set(i,r),this._messageFormatCache.set(n,r)}o.push(r)}}return{messages:o,system:s}}_getMessageCacheKey(e){let s=e.role||"",o=typeof e.content=="string"?e.content.substring(0,100):"",n=e.tool_calls?e.tool_calls.length:0;return`${s}:${o.length}:${n}`}_formatSingleMessage(e,s=[]){if(e.role==="assistant"){let o=[];if(e.content&&o.push({type:"text",text:e.content}),e.tool_calls)for(let n of e.tool_calls)o.push({type:"tool_use",id:n.id||`toolu-${Date.now()}`,name:n.function.name,input:typeof n.function.arguments=="string"?JSON.parse(n.function.arguments||"{}"):n.function.arguments||{}});return{role:"assistant",content:o.length>0?o:[{type:"text",text:""}]}}if(e.role==="tool"){let o=s[s.length-1],n={type:"tool_result",tool_use_id:e.tool_call_id,content:typeof e.content=="string"?e.content:JSON.stringify(e.content)};return o&&o.role==="user"&&Array.isArray(o.content)&&o.content[0]?.type==="tool_result"?(o.content.push(n),null):{role:"user",content:[n]}}if(Array.isArray(e.content)){let o=[];for(let n of e.content)n.type==="text"?o.push({type:"text",text:n.text??""}):n.type==="image"&&n.data&&o.push({type:"image",source:{type:"base64",media_type:n.media_type||"image/png",data:n.data}});return{role:"user",content:o}}return{role:"user",content:e.content}}formatTools(e){return!e||e.length===0?[]:e.map(s=>({name:s.function.name,description:s.function.description||"",input_schema:s.function.parameters||{type:"object",properties:{}}}))}_resolveModelId(e){return this.getModel(e)?.id||e}async chat(e,s,o={}){let n=o.model||this.defaultModel,r=this._resolveModelId(n),i=this.getModel(n),c=o.maxTokens||i?.maxTokens||8192,{messages:l,system:u}=this.formatMessages(e),d={model:r,messages:l,max_tokens:c,temperature:o.temperature??this.temperature};u&&(d.system=u);let f=this.formatTools(s);f.length>0&&(d.tools=f);let m=await Ta.post(`${this.baseUrl}/messages`,d,{timeout:o.timeout||this.timeout,headers:this._getHeaders()});return this.normalizeResponse(m.data)}async stream(e,s,o={}){let n=o.model||this.defaultModel,r=this._resolveModelId(n),i=this.getModel(n),c=o.maxTokens||i?.maxTokens||8192,l=o.onToken||(()=>{}),{messages:u,system:d}=this.formatMessages(e),f={model:r,messages:u,max_tokens:c,temperature:o.temperature??this.temperature,stream:!0};d&&(f.system=d);let m=this.formatTools(s);m.length>0&&(f.tools=m);let h;try{h=await Ta.post(`${this.baseUrl}/messages`,f,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(p){if(p.name==="CanceledError"||p.name==="AbortError"||p.code==="ERR_CANCELED")throw p;let g=p.response?.data?.error?.message||p.message;throw new Error(`API Error: ${g}`)}return new Promise((p,g)=>{let $="",y=[],w=-1,T="";o.signal&&o.signal.addEventListener("abort",()=>{h.data.destroy(),g(new DOMException("The operation was aborted","AbortError"))},{once:!0}),h.data.on("data",_=>{T+=_.toString();let x=T.split(`
77
+ `);T=x.pop()||"";for(let S of x){let R=S.trim();if(R.startsWith("data: ")){let C=R.slice(6),I;try{I=JSON.parse(C)}catch{continue}switch(I.type){case"content_block_start":{let D=I.content_block;D?.type==="tool_use"&&(w=y.length,y.push({id:D.id,name:D.name,inputJson:""}));break}case"content_block_delta":{let D=I.delta;D?.type==="text_delta"&&D.text&&(l(D.text),$+=D.text),D?.type==="input_json_delta"&&D.partial_json!==void 0&&w>=0&&(y[w].inputJson+=D.partial_json);break}case"content_block_stop":w=-1;break;case"message_stop":p({content:$,tool_calls:this._buildToolCalls(y)});return}}}}),h.data.on("error",_=>{o.signal?.aborted||g(new Error(`Stream error: ${_.message}`))}),h.data.on("end",()=>{p({content:$,tool_calls:this._buildToolCalls(y)})})})}normalizeResponse(e){let s="",o=[];for(let n of e.content||[])n.type==="text"?s+=n.text:n.type==="tool_use"&&o.push({id:n.id,function:{name:n.name,arguments:n.input}});return{content:s,tool_calls:o}}_buildToolCalls(e){return e.filter(s=>s.name).map(s=>{let o={};if(s.inputJson)try{o=JSON.parse(s.inputJson)}catch{o=s.inputJson}return{id:s.id||`anthropic-${Date.now()}`,function:{name:s.name,arguments:o}}})}};Ca.exports={AnthropicProvider:zo,ANTHROPIC_MODELS:Ra}});var Ma=j((_0,Pa)=>{var Oa=require("axios"),{BaseProvider:zf}=on(),{serializeMessage:b0}=Xe(),Na={"gemini-3.1-pro-preview":{id:"gemini-3.1-pro-preview",name:"Gemini 3.1 Pro Preview",maxTokens:65536,contextWindow:1048576},"gemini-3-flash-preview":{id:"gemini-3-flash-preview",name:"Gemini 3 Flash Preview",maxTokens:65536,contextWindow:1048576},"gemini-2.5-pro":{id:"gemini-2.5-pro",name:"Gemini 2.5 Pro",maxTokens:65536,contextWindow:1048576},"gemini-2.5-flash":{id:"gemini-2.5-flash",name:"Gemini 2.5 Flash",maxTokens:65536,contextWindow:1048576},"gemini-2.5-flash-lite":{id:"gemini-2.5-flash-lite",name:"Gemini 2.5 Flash Lite",maxTokens:65536,contextWindow:1048576},"gemini-2.0-flash":{id:"gemini-2.0-flash",name:"Gemini 2.0 Flash",maxTokens:8192,contextWindow:1048576},"gemini-2.0-flash-lite":{id:"gemini-2.0-flash-lite",name:"Gemini 2.0 Flash Lite",maxTokens:8192,contextWindow:1048576},"gemini-1.5-pro":{id:"gemini-1.5-pro",name:"Gemini 1.5 Pro",maxTokens:8192,contextWindow:1048576},"gemini-1.5-flash":{id:"gemini-1.5-flash",name:"Gemini 1.5 Flash",maxTokens:8192,contextWindow:1048576}},Yo=class extends zf{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||Na,defaultModel:e.defaultModel||"gemini-2.5-flash",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("GEMINI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s=[];for(let o of e){if(this._messageFormatCache.has(o)){s.push(this._messageFormatCache.get(o));continue}let n=this._getMessageCacheKey(o);if(this._messageStringCache.has(n)){let i=this._messageStringCache.get(n);this._messageFormatCache.set(o,i),s.push(i);continue}let r=this._formatSingleMessage(o);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(n,r),this._messageFormatCache.set(o,r),s.push(r)}return{messages:s}}_getMessageCacheKey(e){let s=e.role||"",o=typeof e.content=="string"?e.content.substring(0,100):"",n=e.tool_calls?e.tool_calls.length:0;return`${s}:${o.length}:${n}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||"",tool_calls:e.tool_calls.map(s=>({id:s.id||`call-${Date.now()}`,type:"function",function:{name:s.function.name,arguments:typeof s.function.arguments=="string"?s.function.arguments:JSON.stringify(s.function.arguments)}}))};if(e.role==="tool")return{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.tool_call_id};if(e.role==="user"&&Array.isArray(e.content)){let s=[];for(let o of e.content)if(o.type==="text")s.push({type:"text",text:o.text??""});else if(o.type==="image"&&o.data){let n=o.data.startsWith("data:")?o.data:`data:${o.media_type||"image/png"};base64,${o.data}`;s.push({type:"image_url",image_url:{url:n,detail:"auto"}})}return{role:"user",content:s}}return{role:e.role,content:e.content}}async chat(e,s,o={}){let n=o.model||this.defaultModel,r=this.getModel(n),i=o.maxTokens||r?.maxTokens||8192,{messages:c}=this.formatMessages(e),l={model:n,messages:c,max_tokens:i,temperature:o.temperature??this.temperature};s&&s.length>0&&(l.tools=s);let u=await Oa.post(`${this.baseUrl}/chat/completions`,l,{timeout:o.timeout||this.timeout,headers:this._getHeaders()});return this.normalizeResponse(u.data)}async stream(e,s,o={}){let n=o.model||this.defaultModel,r=this.getModel(n),i=o.maxTokens||r?.maxTokens||8192,c=o.onToken||(()=>{}),{messages:l}=this.formatMessages(e),u={model:n,messages:l,max_tokens:i,temperature:o.temperature??this.temperature,stream:!0};s&&s.length>0&&(u.tools=s);let d;try{d=await Oa.post(`${this.baseUrl}/chat/completions`,u,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let m=f.response?.data?.error?.message||f.message;throw new Error(`API Error: ${m}`)}return new Promise((f,m)=>{let h="",p={},g="";o.signal&&o.signal.addEventListener("abort",()=>{d.data.destroy(),m(new DOMException("The operation was aborted","AbortError"))},{once:!0}),d.data.on("data",$=>{g+=$.toString();let y=g.split(`
78
+ `);g=y.pop()||"";for(let w of y){let T=w.trim();if(!T||!T.startsWith("data: "))continue;let _=T.slice(6);if(_==="[DONE]"){f({content:h,tool_calls:this._buildToolCalls(p)});return}let x;try{x=JSON.parse(_)}catch{continue}let S=x.choices?.[0]?.delta;if(S&&(S.content&&(c(S.content),h+=S.content),S.tool_calls))for(let R of S.tool_calls){let C=R.index??0;p[C]||(p[C]={id:R.id||"",name:"",arguments:""}),R.id&&(p[C].id=R.id),R.function?.name&&(p[C].name+=R.function.name),R.function?.arguments&&(p[C].arguments+=R.function.arguments)}}}),d.data.on("error",$=>{o.signal?.aborted||m(new Error(`Stream error: ${$.message}`))}),d.data.on("end",()=>{f({content:h,tool_calls:this._buildToolCalls(p)})})})}normalizeResponse(e){let s=e.choices?.[0]?.message||{},o=(s.tool_calls||[]).map(n=>({id:n.id,function:{name:n.function.name,arguments:n.function.arguments}}));return{content:s.content||"",tool_calls:o}}_buildToolCalls(e){return Object.values(e).filter(s=>s.name).map(s=>({id:s.id||`call-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,function:{name:s.name,arguments:s.arguments}}))}};Pa.exports={GeminiProvider:Yo,GEMINI_MODELS:Na}});var ja=j((k0,La)=>{var xs=require("axios"),{BaseProvider:Yf}=on(),Ia="http://localhost:11434",Xo=class extends Yf{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||Ia,models:e.models||{},defaultModel:e.defaultModel||null,...e}),this.timeout=e.timeout||3e5,this.temperature=e.temperature??.2,this._modelsLoaded=!1}isConfigured(){return!0}async loadModels(){if(this._modelsLoaded)return this.models;try{let s=(await xs.get(`${this.baseUrl}/api/tags`,{timeout:5e3})).data?.models||[];this.models={};for(let o of s){let n=o.name||o.model;if(!n)continue;let r=n.replace(/:latest$/,""),i=32768;try{let c=await xs.post(`${this.baseUrl}/api/show`,{name:n},{timeout:5e3}),l=c.data?.model_info||c.data?.details||{};i=l["general.context_length"]||l["llama.context_length"]||this._parseContextFromModelfile(c.data?.modelfile)||32768}catch{}this.models[r]={id:r,name:o.name,maxTokens:Math.min(8192,Math.floor(i*.1)),contextWindow:i}}!this.defaultModel&&Object.keys(this.models).length>0&&(this.defaultModel=Object.keys(this.models)[0]),this._modelsLoaded=!0}catch{this.models={},this._modelsLoaded=!1}return this.models}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}_formatMessages(e){return e.map(s=>{if(s.role==="user"&&Array.isArray(s.content)){let o=[],n=[];for(let i of s.content)i.type==="text"?o.push(i.text??""):i.type==="image"&&i.data&&n.push(i.data);let r={role:"user",content:o.join(`
79
+ `)};return n.length>0&&(r.images=n),r}return s})}async chat(e,s,o={}){this._modelsLoaded||await this.loadModels();let n=o.model||this.defaultModel;if(!n)throw new Error("No local model available. Is Ollama running?");let r=await xs.post(`${this.baseUrl}/api/chat`,{model:n,messages:this._formatMessages(e),tools:s&&s.length>0?s:void 0,stream:!1,options:{temperature:o.temperature??this.temperature,num_predict:o.maxTokens||8192}},{timeout:o.timeout||this.timeout});return this.normalizeResponse(r.data)}async stream(e,s,o={}){this._modelsLoaded||await this.loadModels();let n=o.model||this.defaultModel;if(!n)throw new Error("No local model available. Is Ollama running?");let r=o.onToken||(()=>{}),i;try{i=await xs.post(`${this.baseUrl}/api/chat`,{model:n,messages:this._formatMessages(e),tools:s&&s.length>0?s:void 0,stream:!0,options:{temperature:o.temperature??this.temperature,num_predict:o.maxTokens||8192}},{timeout:o.timeout||this.timeout,responseType:"stream",signal:o.signal})}catch(c){if(c.name==="CanceledError"||c.name==="AbortError"||c.code==="ERR_CANCELED")throw c;let l=c.response?.data?.error||c.message;throw new Error(`API Error: ${l}`)}return new Promise((c,l)=>{let u="",d=[],f="";o.signal&&o.signal.addEventListener("abort",()=>{i.data.destroy(),l(new DOMException("The operation was aborted","AbortError"))},{once:!0}),i.data.on("data",m=>{f+=m.toString();let h=f.split(`
80
+ `);f=h.pop()||"";for(let p of h){if(!p.trim())continue;let g;try{g=JSON.parse(p)}catch{continue}if(g.message?.content&&(r(g.message.content),u+=g.message.content),g.message?.tool_calls&&(d=d.concat(g.message.tool_calls)),g.done){c({content:u,tool_calls:this._normalizeToolCalls(d)});return}}}),i.data.on("error",m=>{o.signal?.aborted||l(new Error(`Stream error: ${m.message}`))}),i.data.on("end",()=>{if(f.trim())try{let m=JSON.parse(f);m.message?.content&&(r(m.message.content),u+=m.message.content),m.message?.tool_calls&&(d=d.concat(m.message.tool_calls))}catch{}c({content:u,tool_calls:this._normalizeToolCalls(d)})})})}normalizeResponse(e){let s=e.message||{};return{content:s.content||"",tool_calls:this._normalizeToolCalls(s.tool_calls||[])}}_parseContextFromModelfile(e){if(!e)return null;let s=e.match(/PARAMETER\s+num_ctx\s+(\d+)/i);return s?parseInt(s[1],10):null}_normalizeToolCalls(e){return e.map((s,o)=>({id:s.id||`local-${Date.now()}-${o}`,function:{name:s.function?.name||s.name||"unknown",arguments:s.function?.arguments||s.arguments||{}}}))}};La.exports={LocalProvider:Xo,DEFAULT_LOCAL_URL:Ia}});var vt=j((x0,qa)=>{"use strict";var qe=require("fs"),Da=require("path");function Xf(t){if(!t||isNaN(t))return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function Jf(t){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}catch{let e=Date.now()+t;for(;Date.now()<e;);}}function Vf(t,e){let s=Da.dirname(t),o=Da.join(s,`.nex-tmp.${process.pid}.${Date.now()}`);try{qe.existsSync(s)||qe.mkdirSync(s,{recursive:!0}),qe.writeFileSync(o,e,"utf-8"),qe.renameSync(o,t)}catch(n){try{qe.unlinkSync(o)}catch{}throw n}}function Qf(t,e,{timeout:s=5e3,retryMs:o=50}={}){let n=t+".lock",r=Date.now()+s;for(;;){let i=-1;try{i=qe.openSync(n,"wx"),qe.writeSync(i,Buffer.from(String(process.pid))),qe.closeSync(i),i=-1;try{return e()}finally{try{qe.unlinkSync(n)}catch{}}}catch(c){if(i!==-1)try{qe.closeSync(i)}catch{}if(c.code!=="EEXIST")throw c;try{let l=qe.readFileSync(n,"utf-8").trim(),u=parseInt(l,10);if(!Xf(u)){try{qe.unlinkSync(n)}catch{}continue}}catch{continue}if(Date.now()>=r){try{qe.unlinkSync(n)}catch{}return e()}Jf(o)}}}qa.exports={atomicWrite:Vf,withFileLockSync:Qf}});var ln=j((v0,Ka)=>{var cn=require("fs"),Jo=require("path"),{atomicWrite:Zf,withFileLockSync:ep}=vt(),Fa={openai:{"gpt-4o":{input:2.5,output:10},"gpt-4o-mini":{input:.15,output:.6},"gpt-4.1":{input:2,output:8},"gpt-4.1-mini":{input:.4,output:1.6},"gpt-4.1-nano":{input:.1,output:.4},o1:{input:15,output:60},o3:{input:10,output:40},"o3-mini":{input:1.1,output:4.4},"o4-mini":{input:1.1,output:4.4}},anthropic:{"claude-sonnet":{input:3,output:15},"claude-opus":{input:5,output:25},"claude-haiku":{input:.8,output:4},"claude-sonnet-4-5":{input:3,output:15},"claude-sonnet-4":{input:3,output:15}},gemini:{"gemini-2.5-pro":{input:1.25,output:10},"gemini-2.5-flash":{input:.15,output:.6},"gemini-2.0-flash":{input:.1,output:.4},"gemini-2.0-flash-lite":{input:.075,output:.3}},ollama:{"qwen3-coder:480b":{input:0,output:0},"qwen3-coder-next":{input:0,output:0},"devstral-2:123b":{input:0,output:0},"devstral-small-2:24b":{input:0,output:0},"kimi-k2.5":{input:0,output:0},"kimi-k2:1t":{input:0,output:0},"deepseek-v3.2":{input:0,output:0},"minimax-m2.5":{input:0,output:0},"glm-5":{input:0,output:0},"glm-4.7":{input:0,output:0},"gpt-oss:120b":{input:0,output:0}},local:{}},vs=[],St={};function tp(t,e,s,o){if(vs.push({provider:t,model:e,input:s,output:o}),St[t]!==void 0){let n=Ha(t);n.allowed||process.stderr.write(`\x1B[33m\u26A0 Budget limit reached for ${t}: $${n.spent.toFixed(2)} / $${n.limit.toFixed(2)}\x1B[0m
81
+ `)}}function Vo(t,e){let s=Fa[t];return s?s[e]||{input:0,output:0}:{input:0,output:0}}function Ua(t){let e=Vo(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function Wa(){let t={};for(let r of vs){let i=`${r.provider}:${r.model}`;t[i]||(t[i]={provider:r.provider,model:r.model,input:0,output:0}),t[i].input+=r.input,t[i].output+=r.output}let e=Object.values(t).map(r=>({...r,cost:Ua(r)})),s=e.reduce((r,i)=>r+i.cost,0),o=e.reduce((r,i)=>r+i.input,0),n=e.reduce((r,i)=>r+i.output,0);return{totalCost:s,totalInput:o,totalOutput:n,breakdown:e}}function np(){let{totalCost:t,totalInput:e,totalOutput:s,breakdown:o}=Wa();if(o.length===0)return"No token usage recorded this session.";let n=[];n.push("Session Token Usage:"),n.push("");for(let r of o){let i=r.cost>0?`$${r.cost.toFixed(4)}`:"free";n.push(` ${r.provider}:${r.model}`),n.push(` Input: ${r.input.toLocaleString()} tokens`),n.push(` Output: ${r.output.toLocaleString()} tokens`),n.push(` Cost: ${i}`)}return n.push(""),n.push(` Total: ${e.toLocaleString()} in + ${s.toLocaleString()} out = $${t.toFixed(4)}`),n.join(`
82
+ `)}function sp(t,e,s,o){let n=Vo(t,e),r=(s*n.input+o*n.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function op(){vs=[]}function rp(t,e){St[t]=e}function ip(t){delete St[t]}function ap(){return{...St}}function Ba(t){let e=0;for(let s of vs)s.provider===t&&(e+=Ua(s));return e}function Ha(t){let e=Ba(t),s=St[t];if(s===void 0)return{allowed:!0,spent:e,limit:null,remaining:null};let o=Math.max(0,s-e);return{allowed:e<s,spent:e,limit:s,remaining:o}}function Ga(){let t=Jo.join(process.cwd(),".nex","config.json");if(cn.existsSync(t))try{let e=JSON.parse(cn.readFileSync(t,"utf-8"));e.costLimits&&typeof e.costLimits=="object"&&(St={...e.costLimits})}catch{}}function cp(){let t=Jo.join(process.cwd(),".nex"),e=Jo.join(t,"config.json");cn.existsSync(t)||cn.mkdirSync(t,{recursive:!0}),ep(e,()=>{let s={};if(cn.existsSync(e))try{s=JSON.parse(cn.readFileSync(e,"utf-8"))}catch{s={}}s.costLimits=St,Zf(e,JSON.stringify(s,null,2))})}function lp(){St={}}Ga();Ka.exports={PRICING:Fa,trackUsage:tp,getSessionCosts:Wa,formatCosts:np,formatCostHint:sp,resetCosts:op,getPricing:Vo,setCostLimit:rp,removeCostLimit:ip,getCostLimits:ap,getProviderSpend:Ba,checkBudget:Ha,loadCostLimits:Ga,saveCostLimits:cp,resetCostLimits:lp}});var Ss=j((S0,za)=>{var Nn=we(),up={"kimi-k2.5":{id:"kimi-k2.5",name:"Kimi K2.5",max_tokens:16384},"qwen3-coder:480b":{id:"qwen3-coder:480b",name:"Qwen3 Coder 480B",max_tokens:16384}};function dp(){return Nn.getActiveModel()}function fp(t){return Nn.setActiveModel(t)}function pp(){return Nn.getModelNames()}function mp(t){if(!t)return null;if(typeof t=="object")return t;try{return JSON.parse(t)}catch{}try{let o=t.replace(/,\s*([}\]])/g,"$1").replace(/'/g,'"');return JSON.parse(o)}catch{}let e=t.match(/\{[\s\S]*\}/);if(e)try{return JSON.parse(e[0])}catch{}try{let o=t.replace(/(\{|,)\s*([a-zA-Z_]\w*)\s*:/g,'$1"$2":');return JSON.parse(o)}catch{}let s=t.match(/```(?:json)?\s*([\s\S]*?)```/);if(s)try{return JSON.parse(s[1].trim())}catch{}return null}async function hp(t,e){let{C:s}=ye(),{Spinner:o}=ye(),n=new o("Thinking...");n.start();let r=!0,i="";try{let c=await Nn.callStream(t,e,{onToken:l=>{r&&(n.stop(),process.stdout.write(`${s.blue}`),r=!1),process.stdout.write(l),i+=l}});return r?n.stop():process.stdout.write(`${s.reset}
83
+ `),c}catch(c){throw n.stop(),c}}async function gp(t,e){return Nn.callChat(t,e)}za.exports={MODELS:up,getActiveModel:dp,setActiveModel:fp,getModelNames:pp,callOllamaStream:hp,callOllama:gp,parseToolArgs:mp}});var Ja=j((T0,Xa)=>{var Es=require("path"),{C:E}=ye(),{T:Qo,isDark:E0}=Lt(),{confirm:$p,getAutoConfirm:yp}=Ae(),Ya=2e3;function Pn(t,e){let s=t.split(`
84
+ `),o=e.split(`
85
+ `),n=[],r=s.length,i=o.length;if(r>Ya||i>Ya){for(let f of s)n.push({type:"remove",line:f});for(let f of o)n.push({type:"add",line:f});return n}let c=Array.from({length:r+1},()=>new Array(i+1).fill(0));for(let f=1;f<=r;f++)for(let m=1;m<=i;m++)s[f-1]===o[m-1]?c[f][m]=c[f-1][m-1]+1:c[f][m]=Math.max(c[f-1][m],c[f][m-1]);let l=r,u=i,d=[];for(;l>0||u>0;)l>0&&u>0&&s[l-1]===o[u-1]?(d.unshift({type:"same",line:s[l-1]}),l--,u--):u>0&&(l===0||c[l][u-1]>=c[l-1][u])?(d.unshift({type:"add",line:o[u-1]}),u--):(d.unshift({type:"remove",line:s[l-1]}),l--);return d}function wp(t,e,s,o=3){console.log(`
86
+ ${E.bold}${E.cyan} Diff: ${t}${E.reset}`);let n=Pn(e,s),r=[];if(n.forEach((l,u)=>{l.type!=="same"&&r.push(u)}),r.length===0){console.log(`${E.gray} (no changes)${E.reset}`);return}let i=Math.max(0,r[0]-o),c=Math.min(n.length,r[r.length-1]+o+1);i>0&&console.log(`${E.gray} ...${E.reset}`);for(let l=i;l<c;l++){let u=n[l];switch(u.type){case"remove":console.log(`${E.red} - ${u.line}${E.reset}`);break;case"add":console.log(`${E.green} + ${u.line}${E.reset}`);break;default:console.log(`${E.gray} ${u.line}${E.reset}`)}}c<n.length&&console.log(`${E.gray} ...${E.reset}`),console.log()}function bp(t,e,s){console.log(`
87
+ ${E.bold}${E.cyan} File exists \u2014 showing changes: ${t}${E.reset}`);let o=Pn(e,s),n=0;for(let i of o)i.type!=="same"&&n++;if(n===0){console.log(`${E.gray} (identical content)${E.reset}`);return}let r=0;for(let i of o){if(r>=30){console.log(`${E.gray} ...(${n-r} more changes)${E.reset}`);break}switch(i.type){case"remove":console.log(`${E.red} - ${i.line}${E.reset}`),r++;break;case"add":console.log(`${E.green} + ${i.line}${E.reset}`),r++;break;default:r>0&&console.log(`${E.gray} ${i.line}${E.reset}`)}}console.log()}function _p(t,e){console.log(`
88
+ ${E.bold}${E.cyan} New file: ${t}${E.reset}`);let s=e.split(`
89
+ `),o=s.slice(0,20);for(let n of o)console.log(`${E.green} + ${n}${E.reset}`);s.length>20&&console.log(`${E.gray} ...+${s.length-20} more lines${E.reset}`),console.log()}async function kp(t){return yp()?!0:$p(` ${t}?`)}function xp(t,e,s,o){let n=o||process.stdout.columns||80,r=Math.floor((n-3)/2);console.log(`
90
+ ${E.bold}${E.cyan} Side-by-side: ${t}${E.reset}`),console.log(` ${E.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${E.reset}`);let i=Pn(e,s),c=[],l=0;for(;l<i.length;)if(i[l].type==="same")c.push({left:i[l].line,right:i[l].line,type:"same"}),l++;else if(i[l].type==="remove"){let h=[];for(;l<i.length&&i[l].type==="remove";)h.push(i[l].line),l++;let p=[];for(;l<i.length&&i[l].type==="add";)p.push(i[l].line),l++;let g=Math.max(h.length,p.length);for(let $=0;$<g;$++)c.push({left:$<h.length?h[$]:"",right:$<p.length?p[$]:"",type:"changed"})}else i[l].type==="add"&&(c.push({left:"",right:i[l].line,type:"changed"}),l++);let u=c.map((h,p)=>h.type!=="same"?p:-1).filter(h=>h>=0);if(u.length===0){console.log(` ${E.gray}(no changes)${E.reset}`);return}let d=Math.max(0,u[0]-2),f=Math.min(c.length,u[u.length-1]+3),m=(h,p)=>{let g=h.replace(/\x1b\[[0-9;]*m/g,"");return g.length>=p?h.substring(0,p):h+" ".repeat(p-g.length)};d>0&&console.log(` ${E.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${E.reset}`);for(let h=d;h<f;h++){let p=c[h];if(p.type==="same")console.log(` ${E.gray}${m(p.left,r)}${E.reset}\u2502${E.gray}${m(p.right,r)}${E.reset}`);else{let g=p.left?`${E.red}${m(p.left,r)}${E.reset}`:`${m("",r)}`,$=p.right?`${E.green}${m(p.right,r)}${E.reset}`:`${m("",r)}`;console.log(` ${g}\u2502${$}`)}}f<c.length&&console.log(` ${E.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${E.reset}`),console.log(` ${E.dim}${"\u2500".repeat(r)}\u2534${"\u2500".repeat(r)}${E.reset}
91
+ `)}function vp(t,e,s,o={}){let n=o.label||"Update",r=o.context||3,i=o.annotations||[],c=Es.isAbsolute(t)?Es.relative(process.cwd(),t):t,l=Pn(e,s),u=1,d=1;for(let S of l)S.type==="same"?(S.oldLine=u++,S.newLine=d++):S.type==="remove"?(S.oldLine=u++,S.newLine=null):(S.oldLine=null,S.newLine=d++);let f=0,m=0;for(let S of l)S.type==="add"?f++:S.type==="remove"&&m++;if(console.log(`
92
+ ${E.green}\u25CF${E.reset} ${E.bold}${n}(${c})${E.reset}`),f===0&&m===0){console.log(` ${E.dim}\u2514 (no changes)${E.reset}
93
+ `);return}let h=[];if(f>0&&h.push(`Added ${f} line${f!==1?"s":""}`),m>0&&h.push(`removed ${m} line${m!==1?"s":""}`),i.length>0){let S=i.filter(D=>D.severity==="error").length,R=i.filter(D=>D.severity==="warn").length,C=i.filter(D=>D.severity==="info").length,I=[];S>0&&I.push(`${E.red}${S} error${S!==1?"s":""}${E.dim}`),R>0&&I.push(`${E.yellow}${R} warning${R!==1?"s":""}${E.dim}`),C>0&&I.push(`${E.cyan}${C} info${C!==1?"s":""}${E.dim}`),h.push(`found ${I.join(", ")}`)}console.log(` ${E.dim}\u2514 ${h.join(", ")}${E.reset}`);let g=[];l.forEach((S,R)=>{S.type!=="same"&&g.push(R)});let $=[],y=null,w=null;for(let S of g){let R=Math.max(0,S-r),C=Math.min(l.length-1,S+r);y===null?(y=R,w=C):(R<=w+1||($.push([y,w]),y=R),w=C)}y!==null&&$.push([y,w]);let T=" ",_=process.stdout.columns||120;function x(S,R,C){let I=C.replace(/\x1b\[[0-9;]*m/g,""),D=C+" ".repeat(Math.max(0,_-I.length));return`${S}${R}${D}${E.reset}`}for(let S=0;S<$.length;S++){S>0&&console.log(`${T}${E.dim}\xB7\xB7\xB7${E.reset}`);let[R,C]=$[S];for(let I=R;I<=C;I++){let D=l[I],K=D.newLine!=null?D.newLine:D.oldLine,z=String(K).padStart(4),Q=D.type!=="remove"?i.filter(Z=>Z.line===D.newLine):[];D.type==="remove"?console.log(x(Qo.diff_rem_bg,E.red,`${T}${z} - ${D.line}`)):D.type==="add"?console.log(x(Qo.diff_add_bg,E.green,`${T}${z} + ${D.line}`)):console.log(`${T}${E.dim}${z} ${E.reset}${D.line}`);for(let Z of Q){let Y=E.cyan,et="\u2139";Z.severity==="error"?(Y=E.red,et="\u2716"):Z.severity==="warn"&&(Y=E.yellow,et="\u26A0"),console.log(`${T} ${Y}${et} ${Z.message}${E.reset}`)}}}console.log()}function Sp(t,e,s={}){let o=Es.isAbsolute(t)?Es.relative(process.cwd(),t):t,n=e.split(`
88
94
  `),r=s.annotations||[];console.log(`
89
- ${_.cyan}\u23FA${_.reset} ${_.bold}Create(${n})${_.reset}`);let i=[`${o.length} line${o.length!==1?"s":""}`];if(r.length>0){let d=r.filter(m=>m.severity==="error").length,p=r.filter(m=>m.severity==="warn").length,f=r.filter(m=>m.severity==="info").length,h=[];d>0&&h.push(`${_.red}${d} error${d!==1?"s":""}${_.dim}`),p>0&&h.push(`${_.yellow}${p} warning${p!==1?"s":""}${_.dim}`),f>0&&h.push(`${_.cyan}${f} info${f!==1?"s":""}${_.dim}`),i.push(`found ${h.join(", ")}`)}console.log(` ${_.dim}\u23BF ${i.join(", ")}${_.reset}`);let l=" ",u=Math.min(o.length,20);for(let d=0;d<u;d++){let p=String(d+1).padStart(4),f=d+1,h=r.filter(m=>m.line===f);console.log(`${l}${_.green}${p} +${o[d]}${_.reset}`);for(let m of h){let g=_.cyan,y="\u2139";m.severity==="error"?(g=_.red,y="\u2716"):m.severity==="warn"&&(g=_.yellow,y="\u26A0"),console.log(`${l} ${g}${y} ${m.message}${_.reset}`)}}o.length>20&&console.log(`${l}${_.dim} ...+${o.length-20} more lines${_.reset}`),console.log()}Ji.exports={diffLines:cn,showEditDiff:Ad,showWriteDiff:Od,showNewFilePreview:Nd,confirmFileChange:Md,showSideBySideDiff:Pd,showClaudeDiff:Ld,showClaudeNewFile:Id}});var St=L((oy,Zi)=>{var Xi=require("util").promisify(require("child_process").exec),qd=require("util").promisify(require("child_process").execFile),{C:ie}=de();async function fo(t){try{let{stdout:e}=await Xi(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Xn(...t){try{let{stdout:e}=await qd("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Dd(){return await fo("git rev-parse --is-inside-work-tree")==="true"}async function jd(){return await fo("git branch --show-current")}async function po(){try{let{stdout:t}=await Xi("git status --porcelain",{cwd:process.cwd(),timeout:3e4});return!t||!t.trim()?[]:t.split(`
90
- `).filter(Boolean).map(e=>{let s=e.substring(0,2).trim(),n=e.substring(3);return{status:s,file:n}})}catch{return[]}}async function Qn(t=!1){return await fo(`git diff ${t?"--cached":""}`)||""}async function mo(){return(await po()).map(e=>e.file)}async function Qi(){let t=await mo();if(t.length===0)return null;let e=await Qn(),n=await Qn(!0)||e,o=0,r=0;if(n){let d=n.split(`
91
- `);for(let p of d)p.startsWith("+")&&!p.startsWith("+++")&&o++,p.startsWith("-")&&!p.startsWith("---")&&r++}else o=t.length;let i="chore",c=t.join(" ").toLowerCase();c.includes("test")?i="test":c.includes("readme")||c.includes("doc")?i="docs":o>r*2?i="feat":r>o?i="refactor":i="fix";let l=t.slice(0,3).map(d=>d.split("/").pop());return{summary:`${i}: update ${l.join(", ")}${t.length>3?` (+${t.length-3} more)`:""}`,type:i,files:t,stats:{additions:o,deletions:r}}}async function Fd(t){let s=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await Xn("checkout","-b",s)!==null?s:null}async function Ud(t){return await Xn("add","-A"),await Xn("commit","-m",t)?await Xn("rev-parse","--short","HEAD"):null}async function Wd(){let t=await Qi();if(!t)return`${ie.dim}No changes${ie.reset}`;let e=[];e.push(`
92
- ${ie.bold}${ie.cyan}Git Diff Summary:${ie.reset}`),e.push(` ${ie.green}+${t.stats.additions}${ie.reset} ${ie.red}-${t.stats.deletions}${ie.reset} in ${t.files.length} file(s)`),e.push(`
93
- ${ie.bold}${ie.cyan}Files:${ie.reset}`);for(let s of t.files.slice(0,20))e.push(` ${ie.dim}${s}${ie.reset}`);return t.files.length>20&&e.push(` ${ie.dim}...+${t.files.length-20} more${ie.reset}`),e.push(`
94
- ${ie.bold}${ie.cyan}Suggested message:${ie.reset}`),e.push(` ${ie.cyan}${t.summary}${ie.reset}
95
+ ${E.green}\u25CF${E.reset} ${E.bold}Create(${o})${E.reset}`);let i=[`${n.length} line${n.length!==1?"s":""}`];if(r.length>0){let f=r.filter(g=>g.severity==="error").length,m=r.filter(g=>g.severity==="warn").length,h=r.filter(g=>g.severity==="info").length,p=[];f>0&&p.push(`${E.red}${f} error${f!==1?"s":""}${E.dim}`),m>0&&p.push(`${E.yellow}${m} warning${m!==1?"s":""}${E.dim}`),h>0&&p.push(`${E.cyan}${h} info${h!==1?"s":""}${E.dim}`),i.push(`found ${p.join(", ")}`)}console.log(` ${E.dim}\u2514 ${i.join(", ")}${E.reset}`);let l=" ",u=process.stdout.columns||120,d=Math.min(n.length,20);for(let f=0;f<d;f++){let m=String(f+1).padStart(4),h=f+1,p=r.filter(w=>w.line===h),g=`${l}${m} + ${n[f]}`,$=g.replace(/\x1b\[[0-9;]*m/g,""),y=g+" ".repeat(Math.max(0,u-$.length));console.log(`${Qo.diff_add_bg}${E.green}${y}${E.reset}`);for(let w of p){let T=E.cyan,_="\u2139";w.severity==="error"?(T=E.red,_="\u2716"):w.severity==="warn"&&(T=E.yellow,_="\u26A0"),console.log(`${l} ${T}${_} ${w.message}${E.reset}`)}}n.length>20&&console.log(`${l}${E.dim} ...+${n.length-20} more lines${E.reset}`),console.log()}Xa.exports={diffLines:Pn,showEditDiff:wp,showWriteDiff:bp,showNewFilePreview:_p,confirmFileChange:kp,showSideBySideDiff:xp,showClaudeDiff:vp,showClaudeNewFile:Sp}});var Ft=j((R0,Za)=>{var Va=require("util").promisify(require("child_process").exec),Ep=require("util").promisify(require("child_process").execFile),{C:ge}=ye();async function Zo(t){try{let{stdout:e}=await Va(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Ts(...t){try{let{stdout:e}=await Ep("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Tp(){return await Zo("git rev-parse --is-inside-work-tree")==="true"}async function Rp(){return await Zo("git branch --show-current")}async function er(){try{let{stdout:t}=await Va("git status --porcelain",{cwd:process.cwd(),timeout:3e4});return!t||!t.trim()?[]:t.split(`
96
+ `).filter(Boolean).map(e=>{let s=e.substring(0,2).trim(),o=e.substring(3);return{status:s,file:o}})}catch{return[]}}async function Rs(t=!1){return await Zo(`git diff ${t?"--cached":""}`)||""}async function tr(){return(await er()).map(e=>e.file)}async function Qa(){let t=await tr();if(t.length===0)return null;let e=await Rs(),o=await Rs(!0)||e,n=0,r=0;if(o){let d=o.split(`
97
+ `);for(let f of d)f.startsWith("+")&&!f.startsWith("+++")&&n++,f.startsWith("-")&&!f.startsWith("---")&&r++}else n=t.length;let i="chore",c=t.join(" ").toLowerCase();c.includes("test")?i="test":c.includes("readme")||c.includes("doc")?i="docs":n>r*2?i="feat":r>n?i="refactor":i="fix";let l=t.slice(0,3).map(d=>d.split("/").pop());return{summary:`${i}: update ${l.join(", ")}${t.length>3?` (+${t.length-3} more)`:""}`,type:i,files:t,stats:{additions:n,deletions:r}}}async function Cp(t){let s=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await Ts("checkout","-b",s)!==null?s:null}async function Ap(t){return await Ts("add","-A"),await Ts("commit","-m",t)?await Ts("rev-parse","--short","HEAD"):null}async function Op(){let t=await Qa();if(!t)return`${ge.dim}No changes${ge.reset}`;let e=[];e.push(`
98
+ ${ge.bold}${ge.cyan}Git Diff Summary:${ge.reset}`),e.push(` ${ge.green}+${t.stats.additions}${ge.reset} ${ge.red}-${t.stats.deletions}${ge.reset} in ${t.files.length} file(s)`),e.push(`
99
+ ${ge.bold}${ge.cyan}Files:${ge.reset}`);for(let s of t.files.slice(0,20))e.push(` ${ge.dim}${s}${ge.reset}`);return t.files.length>20&&e.push(` ${ge.dim}...+${t.files.length-20} more${ge.reset}`),e.push(`
100
+ ${ge.bold}${ge.cyan}Suggested message:${ge.reset}`),e.push(` ${ge.cyan}${t.summary}${ge.reset}
95
101
  `),e.join(`
96
- `)}async function Bd(){return(await po()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function Hd(){let t=await mo();if(t.length===0)return"";let e=[`CHANGED FILES (${t.length}):`];for(let n of t.slice(0,10))e.push(` ${n}`);let s=await Qn();if(s){let n=s.length>5e3?s.substring(0,5e3)+`
102
+ `)}async function Np(){return(await er()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function Pp(){let t=await tr();if(t.length===0)return"";let e=[`CHANGED FILES (${t.length}):`];for(let o of t.slice(0,10))e.push(` ${o}`);let s=await Rs();if(s){let o=s.length>5e3?s.substring(0,5e3)+`
97
103
  ...(truncated)`:s;e.push(`
98
104
  DIFF:
99
- ${n}`)}return e.join(`
100
- `)}Zi.exports={isGitRepo:Dd,getCurrentBranch:jd,getStatus:po,getDiff:Qn,getChangedFiles:mo,analyzeDiff:Qi,createBranch:Fd,commit:Ud,formatDiffSummary:Wd,getDiffContext:Hd,getMergeConflicts:Bd}});var ft=L((ry,ta)=>{var ho=require("fs").promises,{execSync:ln}=require("child_process"),Gd=50,Ze=[],Ut=[];function zd(t,e,s,n){for(Ze.push({tool:t,filePath:e,oldContent:s,newContent:n,timestamp:Date.now()});Ze.length>Gd;)Ze.shift();Ut.length=0}async function Kd(){if(Ze.length===0)return null;let t=Ze.pop();if(t.oldContent===null)try{await ho.unlink(t.filePath)}catch{}else await ho.writeFile(t.filePath,t.oldContent,"utf-8");return Ut.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function Yd(){if(Ut.length===0)return null;let t=Ut.pop();return await ho.writeFile(t.filePath,t.newContent,"utf-8"),Ze.push(t),{tool:t.tool,filePath:t.filePath}}function Jd(t=10){return Ze.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function Vd(){return Ze.length}function Xd(){return Ut.length}function Qd(){Ze.length=0,Ut.length=0}var Zn="nex-snapshot";function Zd(t,e=process.cwd()){let s=t?`${Zn}-${t.replace(/[^a-zA-Z0-9_-]/g,"-")}`:`${Zn}-${Date.now()}`;try{return ln("git status --porcelain",{cwd:e,timeout:1e4}).toString().trim()?(ln(`git stash push -u -m "${s}"`,{cwd:e,timeout:15e3}),ln("git stash pop",{cwd:e,timeout:1e4}),{name:s,label:s,ok:!0}):{name:s,label:s,ok:!1,error:"No changes to snapshot (working tree clean)"}}catch(n){return{name:s,label:s,ok:!1,error:n.message}}}function ea(t=process.cwd()){try{let e=ln("git stash list",{cwd:t,timeout:1e4}).toString().trim();return e?e.split(`
101
- `).map(s=>{let n=s.match(/^stash@\{(\d+)\}:\s+(?:WIP on [^:]+:\s+\S+\s+|On \S+:\s+)(.*)/);if(!n)return null;let o=n[2].trim();return o.startsWith(Zn)?{index:parseInt(n[1],10),label:o,shortName:o.replace(`${Zn}-`,""),date:s}:null}).filter(Boolean):[]}catch{return[]}}function ef(t,e=process.cwd()){try{let s=ea(e);if(s.length===0)return{ok:!1,error:"No snapshots found"};let n;return t===void 0||t==="last"?n=s[0]:typeof t=="number"?n=s.find(o=>o.index===t):n=s.find(o=>o.label===t||o.shortName===t||o.shortName.includes(String(t))),n?(ln(`git stash apply stash@{${n.index}}`,{cwd:e,timeout:15e3}),{ok:!0,label:n.label}):{ok:!1,error:`Snapshot not found: ${t}`}}catch(s){return{ok:!1,error:s.message}}}ta.exports={recordChange:zd,undo:Kd,redo:Yd,getHistory:Jd,getUndoCount:Vd,getRedoCount:Xd,clearHistory:Qd,createSnapshot:Zd,listSnapshots:ea,restoreSnapshot:ef}});var un=L((iy,aa)=>{var Ce=require("fs"),Wt=require("path"),ve=[];function go(){return Wt.join(process.cwd(),".nex","skills")}function na(){return Wt.join(process.cwd(),".nex","config.json")}function tf(){let t=go();return Ce.existsSync(t)||Ce.mkdirSync(t,{recursive:!0}),t}function $o(){let t=na();if(!Ce.existsSync(t))return[];try{let e=JSON.parse(Ce.readFileSync(t,"utf-8"));return e.skills&&Array.isArray(e.skills.disabled)?e.skills.disabled:[]}catch{return[]}}function sa(t){let e=na(),s={};if(Ce.existsSync(e))try{s=JSON.parse(Ce.readFileSync(e,"utf-8"))}catch{s={}}s.skills||(s.skills={}),s.skills.disabled=t;let n=Wt.dirname(e);Ce.existsSync(n)||Ce.mkdirSync(n,{recursive:!0}),Ce.writeFileSync(e,JSON.stringify(s,null,2),"utf-8")}function oa(t,e){let s=[];if(typeof t!="object"||t===null)return{valid:!1,errors:["Module must export an object"]};if(t.name!==void 0&&typeof t.name!="string"&&s.push("name must be a string"),t.description!==void 0&&typeof t.description!="string"&&s.push("description must be a string"),t.instructions!==void 0&&typeof t.instructions!="string"&&s.push("instructions must be a string"),t.commands!==void 0)if(!Array.isArray(t.commands))s.push("commands must be an array");else for(let n=0;n<t.commands.length;n++){let o=t.commands[n];(!o.cmd||typeof o.cmd!="string")&&s.push(`commands[${n}].cmd must be a non-empty string`),o.handler!==void 0&&typeof o.handler!="function"&&s.push(`commands[${n}].handler must be a function`)}if(t.tools!==void 0)if(!Array.isArray(t.tools))s.push("tools must be an array");else for(let n=0;n<t.tools.length;n++){let o=t.tools[n];(!o.function||!o.function.name||typeof o.function.name!="string")&&s.push(`tools[${n}].function.name must be a non-empty string`),o.execute!==void 0&&typeof o.execute!="function"&&s.push(`tools[${n}].execute must be a function`)}return{valid:s.length===0,errors:s}}function ra(t){try{let e=Ce.readFileSync(t,"utf-8").trim();return e?{name:Wt.basename(t,".md"),type:"prompt",filePath:t,instructions:e,commands:[],tools:[]}:null}catch{return null}}function ia(t){try{let e=require(t),{valid:s,errors:n}=oa(e,t);return s?{name:e.name||Wt.basename(t,".js"),type:"script",filePath:t,description:e.description||"",instructions:e.instructions||"",commands:(e.commands||[]).map(r=>({cmd:r.cmd.startsWith("/")?r.cmd:`/${r.cmd}`,desc:r.desc||r.description||"",handler:r.handler||null})),tools:(e.tools||[]).map(r=>({type:r.type||"function",function:{name:r.function.name,description:r.function.description||"",parameters:r.function.parameters||{type:"object",properties:{}}},execute:r.execute||null}))}:(console.error(`Skill validation failed: ${t}
102
- ${n.join(`
103
- `)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function nf(){ve=[];let t=go();if(!Ce.existsSync(t))return ve;let e=$o(),s;try{s=Ce.readdirSync(t)}catch{return ve}for(let n of s){let o=Wt.join(t,n),r;try{r=Ce.statSync(o)}catch{continue}if(!r.isFile())continue;let i=null;n.endsWith(".md")?i=ra(o):n.endsWith(".js")&&(i=ia(o)),i&&(i.enabled=!e.includes(i.name),ve.push(i))}return ve}function sf(){let t=[];for(let e of ve)!e.enabled||!e.instructions||t.push(`[Skill: ${e.name}]
105
+ ${o}`)}return e.join(`
106
+ `)}Za.exports={isGitRepo:Tp,getCurrentBranch:Rp,getStatus:er,getDiff:Rs,getChangedFiles:tr,analyzeDiff:Qa,createBranch:Cp,commit:Ap,formatDiffSummary:Op,getDiffContext:Pp,getMergeConflicts:Np}});var pt=j((A0,rc)=>{var ve=require("fs").promises,C0=require("fs"),Je=require("path"),Mp=require("crypto"),{execSync:Mn}=require("child_process"),Ip=100*1024,nc=50,Oe=[],un=[];function Lp(t,e,s,o){for(Oe.push({tool:t,filePath:e,oldContent:s,newContent:o,timestamp:Date.now()});Oe.length>nc;)Oe.shift();un.length=0,sc(Oe[Oe.length-1]).catch(()=>{})}async function jp(){if(Oe.length===0)return null;let t=Oe.pop();if(t.oldContent===null)try{await ve.unlink(t.filePath)}catch{}else await ve.writeFile(t.filePath,t.oldContent,"utf-8");return un.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function Dp(){if(un.length===0)return null;let t=un.pop();return await ve.writeFile(t.filePath,t.newContent,"utf-8"),Oe.push(t),{tool:t.tool,filePath:t.filePath}}function qp(t=10){return Oe.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function Fp(){return Oe.length}function Up(){return un.length}function Wp(){Oe.length=0,un.length=0}function nr(){return Je.join(process.cwd(),".nex","history")}async function ec(t,e){if(t==null)return{inline:!0,content:t};if(Buffer.byteLength(t,"utf-8")<=Ip)return{inline:!0,content:t};let s=Mp.createHash("sha256").update(t,"utf-8").digest("hex"),o=Je.join(e,"blobs");return await ve.mkdir(o,{recursive:!0}),await ve.writeFile(Je.join(o,s),t,"utf-8"),{inline:!1,hash:s}}async function sc(t){let e=nr();await ve.mkdir(e,{recursive:!0});let s=Je.basename(t.filePath).replace(/[^a-zA-Z0-9]/g,"-"),o=`${t.timestamp}-${s}.json`,n=await ec(t.oldContent,e),r=await ec(t.newContent,e),i={tool:t.tool,filePath:t.filePath,timestamp:t.timestamp,oldContent:n.inline?{inline:!0,content:n.content}:{inline:!1,hash:n.hash},newContent:r.inline?{inline:!0,content:r.content}:{inline:!1,hash:r.hash}};await ve.writeFile(Je.join(e,o),JSON.stringify(i),"utf-8")}async function tc(t,e){if(!t)return null;if(t.inline)return t.content;let s=Je.join(e,"blobs",t.hash);return ve.readFile(s,"utf-8")}async function Bp(){let t=nr(),e;try{e=await ve.readdir(t)}catch{return 0}let s=e.filter(n=>n.endsWith(".json")).sort(),o=0;for(let n of s)try{let r=await ve.readFile(Je.join(t,n),"utf-8"),i=JSON.parse(r),c=await tc(i.oldContent,t),l=await tc(i.newContent,t);Oe.push({tool:i.tool,filePath:i.filePath,timestamp:i.timestamp,oldContent:c,newContent:l}),o++}catch{}for(;Oe.length>nc;)Oe.shift();return o}async function Hp(t=7){let e=nr(),s;try{s=await ve.readdir(e)}catch{return 0}let o=Date.now()-t*24*60*60*1e3,n=s.filter(u=>u.endsWith(".json")),r=0,i=new Set,c=[];for(let u of n)try{let d=await ve.readFile(Je.join(e,u),"utf-8"),f=JSON.parse(d);f.timestamp<o?(c.push(u),r++):(f.oldContent&&!f.oldContent.inline&&f.oldContent.hash&&i.add(f.oldContent.hash),f.newContent&&!f.newContent.inline&&f.newContent.hash&&i.add(f.newContent.hash))}catch{}for(let u of c)try{await ve.unlink(Je.join(e,u))}catch{}let l=Je.join(e,"blobs");try{let u=await ve.readdir(l);for(let d of u)if(!i.has(d))try{await ve.unlink(Je.join(l,d))}catch{}}catch{}return r}var Cs="nex-snapshot";function Gp(t,e=process.cwd()){let s=t?`${Cs}-${t.replace(/[^a-zA-Z0-9_-]/g,"-")}`:`${Cs}-${Date.now()}`;try{return Mn("git status --porcelain",{cwd:e,timeout:1e4}).toString().trim()?(Mn(`git stash push -u -m "${s}"`,{cwd:e,timeout:15e3}),Mn("git stash pop",{cwd:e,timeout:1e4}),{name:s,label:s,ok:!0}):{name:s,label:s,ok:!1,error:"No changes to snapshot (working tree clean)"}}catch(o){return{name:s,label:s,ok:!1,error:o.message}}}function oc(t=process.cwd()){try{let e=Mn("git stash list",{cwd:t,timeout:1e4}).toString().trim();return e?e.split(`
107
+ `).map(s=>{let o=s.match(/^stash@\{(\d+)\}:\s+(?:WIP on [^:]+:\s+\S+\s+|On \S+:\s+)(.*)/);if(!o)return null;let n=o[2].trim();return n.startsWith(Cs)?{index:parseInt(o[1],10),label:n,shortName:n.replace(`${Cs}-`,""),date:s}:null}).filter(Boolean):[]}catch{return[]}}function Kp(t,e=process.cwd()){try{let s=oc(e);if(s.length===0)return{ok:!1,error:"No snapshots found"};let o;return t===void 0||t==="last"?o=s[0]:typeof t=="number"?o=s.find(n=>n.index===t):o=s.find(n=>n.label===t||n.shortName===t||n.shortName.includes(String(t))),o?(Mn(`git stash apply stash@{${o.index}}`,{cwd:e,timeout:15e3}),{ok:!0,label:o.label}):{ok:!1,error:`Snapshot not found: ${t}`}}catch(s){return{ok:!1,error:s.message}}}rc.exports={recordChange:Lp,undo:jp,redo:Dp,getHistory:qp,getUndoCount:Fp,getRedoCount:Up,clearHistory:Wp,persistEntry:sc,loadPersistedHistory:Bp,pruneHistory:Hp,createSnapshot:Gp,listSnapshots:oc,restoreSnapshot:Kp}});var Et=j((O0,uc)=>{var ue=require("fs"),Ne=require("path"),{atomicWrite:zp,withFileLockSync:Yp}=vt(),Pe=[];function In(){return Ne.join(process.cwd(),".nex","skills")}function ic(){return Ne.join(process.cwd(),".nex","config.json")}function ac(){let t=In();return ue.existsSync(t)||ue.mkdirSync(t,{recursive:!0}),t}function rr(){let t=ic();if(!ue.existsSync(t))return[];try{let e=JSON.parse(ue.readFileSync(t,"utf-8"));return e.skills&&Array.isArray(e.skills.disabled)?e.skills.disabled:[]}catch{return[]}}function cc(t){let e=ic(),s=Ne.dirname(e);ue.existsSync(s)||ue.mkdirSync(s,{recursive:!0}),Yp(e,()=>{let o={};if(ue.existsSync(e))try{o=JSON.parse(ue.readFileSync(e,"utf-8"))}catch{o={}}o.skills||(o.skills={}),o.skills.disabled=t,zp(e,JSON.stringify(o,null,2))})}function lc(t,e){let s=[];if(typeof t!="object"||t===null)return{valid:!1,errors:["Module must export an object"]};if(t.name!==void 0&&typeof t.name!="string"&&s.push("name must be a string"),t.description!==void 0&&typeof t.description!="string"&&s.push("description must be a string"),t.instructions!==void 0&&typeof t.instructions!="string"&&s.push("instructions must be a string"),t.commands!==void 0)if(!Array.isArray(t.commands))s.push("commands must be an array");else for(let o=0;o<t.commands.length;o++){let n=t.commands[o];(!n.cmd||typeof n.cmd!="string")&&s.push(`commands[${o}].cmd must be a non-empty string`),n.handler!==void 0&&typeof n.handler!="function"&&s.push(`commands[${o}].handler must be a function`)}if(t.tools!==void 0)if(!Array.isArray(t.tools))s.push("tools must be an array");else for(let o=0;o<t.tools.length;o++){let n=t.tools[o];(!n.function||!n.function.name||typeof n.function.name!="string")&&s.push(`tools[${o}].function.name must be a non-empty string`),n.execute!==void 0&&typeof n.execute!="function"&&s.push(`tools[${o}].execute must be a function`)}return{valid:s.length===0,errors:s}}function sr(t){try{let e=ue.readFileSync(t,"utf-8").trim();return e?{name:Ne.basename(t,".md"),type:"prompt",filePath:t,instructions:e,commands:[],tools:[]}:null}catch{return null}}function or(t){try{let e=require(t),{valid:s,errors:o}=lc(e,t);return s?{name:e.name||Ne.basename(t,".js"),type:"script",filePath:t,description:e.description||"",instructions:e.instructions||"",commands:(e.commands||[]).map(r=>({cmd:r.cmd.startsWith("/")?r.cmd:`/${r.cmd}`,desc:r.desc||r.description||"",handler:r.handler||null})),tools:(e.tools||[]).map(r=>({type:r.type||"function",function:{name:r.function.name,description:r.function.description||"",parameters:r.function.parameters||{type:"object",properties:{}}},execute:r.execute||null}))}:(console.error(`Skill validation failed: ${t}
108
+ ${o.join(`
109
+ `)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function ir(){Pe=[];let t=rr(),e=In(),s=[];if(ue.existsSync(e))try{s=ue.readdirSync(e)}catch{s=[]}for(let n of s){let r=Ne.join(e,n),i;try{i=ue.statSync(r)}catch{continue}if(!i.isFile())continue;let c=null;n.endsWith(".md")?c=sr(r):n.endsWith(".js")&&(c=or(r)),c&&(c.enabled=!t.includes(c.name),Pe.push(c))}let o=Ne.join(__dirname,"skills");if(!process.env.NEX_SKIP_BUILTIN_SKILLS&&ue.existsSync(o)){let n;try{n=ue.readdirSync(o).filter(r=>r.endsWith(".md")||r.endsWith(".js"))}catch{n=[]}for(let r of n){let i=Ne.join(o,r),c=Ne.basename(r,Ne.extname(r));if(Pe.some(d=>d.name===c))continue;let l;try{l=ue.statSync(i)}catch{continue}if(!l.isFile())continue;let u=r.endsWith(".md")?sr(i):or(i);u&&(u._builtin=!0,u.enabled=!t.includes(u.name),Pe.push(u))}}return Pe}function Xp(){let t=[];for(let e of Pe)!e.enabled||!e.instructions||t.push(`[Skill: ${e.name}]
104
110
  ${e.instructions}`);return t.length===0?"":`SKILL INSTRUCTIONS:
105
111
  ${t.join(`
106
112
 
107
- `)}`}function of(){let t=[];for(let e of ve)if(e.enabled)for(let s of e.commands)t.push({cmd:s.cmd,desc:s.desc||`[skill: ${e.name}]`});return t}function rf(){let t=[];for(let e of ve)if(e.enabled)for(let s of e.tools)t.push({type:"function",function:{name:`skill_${s.function.name}`,description:`[Skill:${e.name}] ${s.function.description}`,parameters:s.function.parameters}});return t}async function af(t,e){if(!t.startsWith("skill_"))return null;let s=t.substring(6);for(let n of ve)if(n.enabled){for(let o of n.tools)if(o.function.name===s&&o.execute)try{let r=await o.execute(e);return typeof r=="string"?r:JSON.stringify(r)}catch(r){return`ERROR: Skill tool '${s}' failed: ${r.message}`}}return`ERROR: Skill tool '${s}' not found`}function cf(t){let[e,...s]=t.split(/\s+/),n=s.join(" ").trim();for(let o of ve)if(o.enabled){for(let r of o.commands)if(r.cmd===e&&r.handler){try{r.handler(n)}catch(i){console.error(`Skill command error (${e}): ${i.message}`)}return!0}}return!1}function lf(){return ve.map(t=>({name:t.name,type:t.type,enabled:t.enabled,description:t.description||"",commands:t.commands.length,tools:t.tools.length,filePath:t.filePath}))}function uf(t){let e=ve.find(n=>n.name===t);if(!e)return!1;e.enabled=!0;let s=$o().filter(n=>n!==t);return sa(s),!0}function df(t){let e=ve.find(n=>n.name===t);if(!e)return!1;e.enabled=!1;let s=$o();return s.includes(t)||(s.push(t),sa(s)),!0}function ff(){return ve}aa.exports={initSkillsDir:tf,loadAllSkills:nf,getSkillInstructions:sf,getSkillCommands:of,getSkillToolDefinitions:rf,routeSkillCall:af,handleSkillCommand:cf,listSkills:lf,enableSkill:uf,disableSkill:df,getLoadedSkills:ff,_getSkillsDir:go,_validateScriptSkill:oa,_loadMarkdownSkill:ra,_loadScriptSkill:ia}});var ts=L((ay,pa)=>{var{spawn:pf}=require("child_process"),mf=require("path"),ca=require("fs"),et=new Map;function hf(){return mf.join(process.cwd(),".nex","config.json")}function yo(){let t=hf();if(!ca.existsSync(t))return{};try{return JSON.parse(ca.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function es(t,e,s={},n=1e4){return new Promise((o,r)=>{let i=`${Date.now()}-${Math.random().toString(36).slice(2,6)}`,c=JSON.stringify({jsonrpc:"2.0",id:i,method:e,params:s})+`
108
- `,l="",u=setTimeout(()=>{p(),r(new Error(`MCP request timeout: ${e}`))},n);function d(f){l+=f.toString();let h=l.split(`
109
- `);for(let m of h)if(m.trim())try{let g=JSON.parse(m);if(g.id===i){p(),g.error?r(new Error(`MCP error: ${g.error.message||JSON.stringify(g.error)}`)):o(g.result);return}}catch{}l=h[h.length-1]||""}function p(){clearTimeout(u),t.stdout.removeListener("data",d)}t.stdout.on("data",d);try{t.stdin.write(c)}catch(f){p(),r(new Error(`MCP write failed: ${f.message}`))}})}async function la(t,e){if(et.has(t))return et.get(t);let s=["PATH","HOME","USER","SHELL","LANG","TERM","NODE_ENV"],n={};for(let i of s)process.env[i]&&(n[i]=process.env[i]);let o=pf(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...n,...e.env||{}}}),r={name:t,proc:o,tools:[],config:e};try{await es(o,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let i=await es(o,"tools/list",{});return r.tools=i&&i.tools||[],et.set(t,r),r}catch(i){throw o.kill(),new Error(`Failed to connect MCP server '${t}': ${i.message}`)}}function ua(t){let e=et.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return et.delete(t),!0}function gf(){for(let[t]of et)ua(t)}async function da(t,e,s={}){let n=et.get(t);if(!n)throw new Error(`MCP server not connected: ${t}`);let o=await es(n.proc,"tools/call",{name:e,arguments:s});return o&&Array.isArray(o.content)?o.content.filter(r=>r.type==="text").map(r=>r.text).join(`
110
- `):JSON.stringify(o)}function fa(){let t=[];for(let[e,s]of et)for(let n of s.tools)t.push({server:e,name:n.name,description:n.description||"",inputSchema:n.inputSchema||{type:"object",properties:{}}});return t}function $f(){return fa().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function yf(t,e){if(!t.startsWith("mcp_"))return null;let s=t.substring(4).split("_");if(s.length<2)return null;let n=s[0],o=s.slice(1).join("_");return da(n,o,e)}function wf(){let t=yo();return Object.entries(t).map(([e,s])=>{let n=et.get(e);return{name:e,command:s.command,connected:!!n,toolCount:n?n.tools.length:0}})}async function bf(){let t=yo(),e=[];for(let[s,n]of Object.entries(t))try{let o=await la(s,n);e.push({name:s,tools:o.tools.length})}catch(o){e.push({name:s,tools:0,error:o.message})}return e}pa.exports={loadMCPConfig:yo,sendRequest:es,connectServer:la,disconnectServer:ua,disconnectAll:gf,callTool:da,getAllTools:fa,getMCPToolDefinitions:$f,routeMCPCall:yf,listServers:wf,connectAll:bf}});var wo=L((cy,$a)=>{var{getSkillToolDefinitions:xf}=un(),{getMCPToolDefinitions:_f}=ts(),ns=new Map;function ma(){let{TOOL_DEFINITIONS:t}=Be();return[...t,...xf(),..._f()]}function ha(t){if(ns.has(t))return ns.get(t);let s=ma().find(o=>o.function.name===t);if(!s)return null;let n=s.function.parameters;return ns.set(t,n),n}function kf(){ns.clear()}function ss(t,e){if(!t||e.length===0)return null;let s=null,n=1/0;for(let o of e){let r=ga(t.toLowerCase(),o.toLowerCase());r<n&&(n=r,s=o)}return n<=Math.ceil(t.length/2)?s:null}function ga(t,e){let s=t.length,n=e.length,o=Array.from({length:s+1},()=>Array(n+1).fill(0));for(let r=0;r<=s;r++)o[r][0]=r;for(let r=0;r<=n;r++)o[0][r]=r;for(let r=1;r<=s;r++)for(let i=1;i<=n;i++)o[r][i]=t[r-1]===e[i-1]?o[r-1][i-1]:1+Math.min(o[r-1][i],o[r][i-1],o[r-1][i-1]);return o[s][n]}function vf(t,e){let s=ha(t);if(s===null){let d=ma().map(f=>f.function.name),p=ss(t,d);return{valid:!1,error:`Unknown tool "${t}".${p?` Did you mean "${p}"?`:""}
111
- Available tools: ${d.join(", ")}`}}if(!s||!s.properties)return{valid:!0};let n=s.required||[],o=Object.keys(s.properties),r=Object.keys(e),i=[],c={...e},l=!1;for(let u of n)if(!(u in e)||e[u]===void 0||e[u]===null){let d=ss(u,r);d&&!o.includes(d)?(c[u]=e[d],delete c[d],l=!0):i.push(`Missing required parameter "${u}" (${s.properties[u]?.description||s.properties[u]?.type||"unknown"})`)}for(let u of r)if(!o.includes(u)){let d=ss(u,o);d&&!(d in c)?(c[d]=e[u],delete c[u],l=!0):l||i.push(`Unknown parameter "${u}".${d?` Did you mean "${d}"?`:""}`)}for(let u of Object.keys(c)){if(!s.properties[u])continue;let d=s.properties[u].type,p=typeof c[u];d==="string"&&p==="number"?(c[u]=String(c[u]),l=!0):d==="number"&&p==="string"&&!isNaN(c[u])?(c[u]=Number(c[u]),l=!0):d==="boolean"&&p==="string"&&(c[u]=c[u]==="true",l=!0)}return i.length>0&&!l?{valid:!1,error:`Tool "${t}" argument errors:
113
+ `)}`}function Jp(){let t=[];for(let e of Pe)if(e.enabled)for(let s of e.commands)t.push({cmd:s.cmd,desc:s.desc||`[skill: ${e.name}]`});return t}function Vp(){let t=[];for(let e of Pe)if(e.enabled)for(let s of e.tools)t.push({type:"function",function:{name:`skill_${s.function.name}`,description:`[Skill:${e.name}] ${s.function.description}`,parameters:s.function.parameters}});return t}async function Qp(t,e){if(!t.startsWith("skill_"))return null;let s=t.substring(6);for(let o of Pe)if(o.enabled){for(let n of o.tools)if(n.function.name===s&&n.execute)try{let r=await n.execute(e);return typeof r=="string"?r:JSON.stringify(r)}catch(r){return`ERROR: Skill tool '${s}' failed: ${r.message}`}}return`ERROR: Skill tool '${s}' not found`}function Zp(t){let[e,...s]=t.split(/\s+/),o=s.join(" ").trim();for(let n of Pe)if(n.enabled){for(let r of n.commands)if(r.cmd===e&&r.handler){try{r.handler(o)}catch(i){console.error(`Skill command error (${e}): ${i.message}`)}return!0}}return!1}function em(){return Pe.map(t=>({name:t.name,type:t.type,enabled:t.enabled,description:t.description||"",commands:t.commands.length,tools:t.tools.length,filePath:t.filePath}))}function tm(t){let e=Pe.find(o=>o.name===t);if(!e)return!1;e.enabled=!0;let s=rr().filter(o=>o!==t);return cc(s),!0}function nm(t){let e=Pe.find(o=>o.name===t);if(!e)return!1;e.enabled=!1;let s=rr();return s.includes(t)||(s.push(t),cc(s)),!0}function sm(){return Pe}async function om(t,e={}){let{execSync:s}=require("child_process"),o=ac(),n=t;/^[\w-]+\/[\w.-]+$/.test(t)&&(n=`https://github.com/${t}.git`);let r=e.name||Ne.basename(n,".git").replace(/^nex-skill-/,""),i=Ne.join(o,r);if(ue.existsSync(i))return{ok:!1,name:r,error:`Skill "${r}" is already installed at ${i}. Remove it first to reinstall.`};try{s(`git clone --depth 1 ${n} ${i}`,{timeout:3e4,stdio:"pipe"})}catch(d){return{ok:!1,name:r,error:`Git clone failed: ${d.stderr?.toString().trim()||d.message}`}}let c=Ne.join(i,"skill.json"),l=ue.existsSync(c),u=ue.readdirSync(i).some(d=>(d.endsWith(".md")||d.endsWith(".js"))&&!d.startsWith("."));if(!l&&!u){try{ue.rmSync(i,{recursive:!0,force:!0})}catch{}return{ok:!1,name:r,error:"No skill.json manifest or .md/.js skill file found in repository"}}if(l)try{let d=JSON.parse(ue.readFileSync(c,"utf-8"));d.name||(d.name=r)}catch{try{ue.rmSync(i,{recursive:!0,force:!0})}catch{}return{ok:!1,name:r,error:"Invalid skill.json \u2014 not valid JSON"}}return ir(),{ok:!0,name:r}}async function rm(t){let e=require("axios");try{let s=encodeURIComponent(`nex-skill ${t} OR nex-code-skill ${t}`);return((await e.get(`https://api.github.com/search/repositories?q=${s}&sort=stars&per_page=10`,{timeout:1e4,headers:{Accept:"application/vnd.github.v3+json"}})).data.items||[]).map(n=>({name:n.name.replace(/^nex-skill-/,""),description:n.description||"(no description)",url:n.clone_url,stars:n.stargazers_count,owner:n.owner.login}))}catch(s){return[{name:"error",description:`Search failed: ${s.message}`,url:"",stars:0,owner:""}]}}function im(t){let e=Ne.join(In(),t);if(!ue.existsSync(e))return{ok:!1,error:`Skill "${t}" not found in ${In()}`};try{return ue.rmSync(e,{recursive:!0,force:!0}),ir(),{ok:!0}}catch(s){return{ok:!1,error:s.message}}}uc.exports={initSkillsDir:ac,loadAllSkills:ir,getSkillInstructions:Xp,getSkillCommands:Jp,getSkillToolDefinitions:Vp,routeSkillCall:Qp,handleSkillCommand:Zp,listSkills:em,enableSkill:tm,disableSkill:nm,getLoadedSkills:sm,installSkill:om,searchSkills:rm,removeSkill:im,_getSkillsDir:In,_validateScriptSkill:lc,_loadMarkdownSkill:sr,_loadScriptSkill:or}});var Os=j((N0,gc)=>{var{spawn:am}=require("child_process"),cm=require("path"),dc=require("fs"),mt=new Map;function lm(){return cm.join(process.cwd(),".nex","config.json")}function ar(){let t=lm();if(!dc.existsSync(t))return{};try{return JSON.parse(dc.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function As(t,e,s={},o=1e4){return new Promise((n,r)=>{let i=`${Date.now()}-${Math.random().toString(36).slice(2,6)}`,c=JSON.stringify({jsonrpc:"2.0",id:i,method:e,params:s})+`
114
+ `,l="",u=setTimeout(()=>{f(),r(new Error(`MCP request timeout: ${e}`))},o);function d(m){l+=m.toString();let h=l.split(`
115
+ `);for(let p of h)if(p.trim())try{let g=JSON.parse(p);if(g.id===i){f(),g.error?r(new Error(`MCP error: ${g.error.message||JSON.stringify(g.error)}`)):n(g.result);return}}catch{}l=h[h.length-1]||""}function f(){clearTimeout(u),t.stdout.removeListener("data",d)}t.stdout.on("data",d);try{t.stdin.write(c)}catch(m){f(),r(new Error(`MCP write failed: ${m.message}`))}})}async function fc(t,e){if(mt.has(t))return mt.get(t);let s=["PATH","HOME","USER","SHELL","LANG","TERM","NODE_ENV"],o={};for(let i of s)process.env[i]&&(o[i]=process.env[i]);let n=am(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...o,...e.env||{}}}),r={name:t,proc:n,tools:[],config:e};try{await As(n,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let i=await As(n,"tools/list",{});return r.tools=i&&i.tools||[],mt.set(t,r),r}catch(i){throw n.kill(),new Error(`Failed to connect MCP server '${t}': ${i.message}`)}}function pc(t){let e=mt.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return mt.delete(t),!0}function um(){for(let[t]of mt)pc(t)}async function mc(t,e,s={}){let o=mt.get(t);if(!o)throw new Error(`MCP server not connected: ${t}`);let n=await As(o.proc,"tools/call",{name:e,arguments:s});return n&&Array.isArray(n.content)?n.content.filter(r=>r.type==="text").map(r=>r.text).join(`
116
+ `):JSON.stringify(n)}function hc(){let t=[];for(let[e,s]of mt)for(let o of s.tools)t.push({server:e,name:o.name,description:o.description||"",inputSchema:o.inputSchema||{type:"object",properties:{}}});return t}function dm(){return hc().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function fm(t,e){if(!t.startsWith("mcp_"))return null;let s=t.substring(4).split("_");if(s.length<2)return null;let o=s[0],n=s.slice(1).join("_");return mc(o,n,e)}function pm(){let t=ar();return Object.entries(t).map(([e,s])=>{let o=mt.get(e);return{name:e,command:s.command,connected:!!o,toolCount:o?o.tools.length:0}})}async function mm(){let t=ar(),e=[];for(let[s,o]of Object.entries(t))try{let n=await fc(s,o);e.push({name:s,tools:n.tools.length})}catch(n){e.push({name:s,tools:0,error:n.message})}return e}gc.exports={loadMCPConfig:ar,sendRequest:As,connectServer:fc,disconnectServer:pc,disconnectAll:um,callTool:mc,getAllTools:hc,getMCPToolDefinitions:dm,routeMCPCall:fm,listServers:pm,connectAll:mm}});var Ps=j((P0,bc)=>{var $c=require("fs"),cr=require("path"),Ns=[],Ln=[],Ut={},jn=["onToolResult","onModelResponse","onSessionStart","onSessionEnd","onFileChange","beforeToolExec","afterToolExec"];function yc(t,e){if(!t||!t.function||!t.function.name)return{ok:!1,error:"Tool definition must have function.name"};if(typeof e!="function")return{ok:!1,error:"Handler must be a function"};let s=t.function.name;return Ln.some(o=>o.definition.function.name===s)?{ok:!1,error:`Tool "${s}" is already registered`}:(Ln.push({definition:{type:"function",...t},handler:e}),{ok:!0})}function wc(t,e){return jn.includes(t)?typeof e!="function"?{ok:!1,error:"Handler must be a function"}:(Ut[t]||(Ut[t]=[]),Ut[t].push(e),{ok:!0}):{ok:!1,error:`Unknown event "${t}". Available: ${jn.join(", ")}`}}async function lr(t,e){let s=Ut[t]||[],o=e;for(let n of s)try{let r=await n(o);r!==void 0&&(o=r)}catch(r){process.env.NEX_DEBUG&&console.error(`[plugin] Hook error on ${t}: ${r.message}`)}return o}function hm(){let t=cr.join(process.cwd(),".nex","plugins"),e=[];if(!$c.existsSync(t))return{loaded:0,errors:[]};let s=$c.readdirSync(t).filter(n=>n.endsWith(".js")),o={registerTool:yc,registerHook:wc,EVENTS:jn};for(let n of s){let r=cr.join(t,n);try{let i=require(r);if(typeof i=="function")i(o);else if(typeof i.setup=="function")i.setup(o);else{e.push(`${n}: Plugin must export a function or { setup: function }`);continue}Ns.push({name:i.name||cr.basename(n,".js"),filePath:r})}catch(i){e.push(`${n}: ${i.message}`)}}return{loaded:Ns.length,errors:e}}function gm(){return Ln.map(t=>t.definition)}async function $m(t,e,s={}){let o=Ln.find(c=>c.definition.function.name===t);if(!o)return null;let n=await lr("beforeToolExec",{name:t,args:e,options:s}),r=await o.handler(n.args||e,s);return(await lr("afterToolExec",{name:t,args:e,result:r})).result||r}function ym(){return[...Ns]}function wm(){let t={};for(let e of jn)t[e]=(Ut[e]||[]).length;return t}function bm(){Ns.length=0,Ln.length=0;for(let t of Object.keys(Ut))delete Ut[t]}bc.exports={registerTool:yc,registerHook:wc,emit:lr,loadPlugins:hm,getPluginToolDefinitions:gm,executePluginTool:$m,getLoadedPlugins:ym,getHookCounts:wm,clearPlugins:bm,EVENTS:jn}});var ur=j((M0,vc)=>{var{getSkillToolDefinitions:_m}=Et(),{getMCPToolDefinitions:km}=Os(),{getPluginToolDefinitions:xm}=Ps(),Ms=new Map;function _c(){let{TOOL_DEFINITIONS:t}=ot();return[...t,..._m(),...km(),...xm()]}function kc(t){if(Ms.has(t))return Ms.get(t);let s=_c().find(n=>n.function.name===t);if(!s)return null;let o=s.function.parameters;return Ms.set(t,o),o}function vm(){Ms.clear()}function Is(t,e){if(!t||e.length===0)return null;let s=null,o=1/0;for(let n of e){let r=xc(t.toLowerCase(),n.toLowerCase());r<o&&(o=r,s=n)}return o<=Math.ceil(t.length/2)?s:null}function xc(t,e){let s=t.length,o=e.length,n=Array.from({length:s+1},()=>Array(o+1).fill(0));for(let r=0;r<=s;r++)n[r][0]=r;for(let r=0;r<=o;r++)n[0][r]=r;for(let r=1;r<=s;r++)for(let i=1;i<=o;i++)n[r][i]=t[r-1]===e[i-1]?n[r-1][i-1]:1+Math.min(n[r-1][i],n[r][i-1],n[r-1][i-1]);return n[s][o]}function Sm(t,e){let s=kc(t);if(s===null){let d=_c().map(m=>m.function.name),f=Is(t,d);return{valid:!1,error:`Unknown tool "${t}".${f?` Did you mean "${f}"?`:""}
117
+ Available tools: ${d.join(", ")}`}}if(!s||!s.properties)return{valid:!0};let o=s.required||[],n=Object.keys(s.properties),r=Object.keys(e),i=[],c={...e},l=!1;for(let u of o)if(!(u in e)||e[u]===void 0||e[u]===null){let d=Is(u,r);d&&!n.includes(d)?(c[u]=e[d],delete c[d],l=!0):i.push(`Missing required parameter "${u}" (${s.properties[u]?.description||s.properties[u]?.type||"unknown"})`)}for(let u of r)if(!n.includes(u)){let d=Is(u,n);d&&!(d in c)?(c[d]=e[u],delete c[u],l=!0):l||i.push(`Unknown parameter "${u}".${d?` Did you mean "${d}"?`:""}`)}for(let u of Object.keys(c)){if(!s.properties[u])continue;let d=s.properties[u].type,f=typeof c[u];d==="string"&&f==="number"?(c[u]=String(c[u]),l=!0):d==="number"&&f==="string"&&!isNaN(c[u])?(c[u]=Number(c[u]),l=!0):d==="boolean"&&f==="string"&&(c[u]=c[u]==="true",l=!0)}return i.length>0&&!l?{valid:!1,error:`Tool "${t}" argument errors:
112
118
  `+i.map(u=>` - ${u}`).join(`
113
119
  `)+`
114
120
 
115
- Expected parameters: ${JSON.stringify(s.properties,null,2)}`}:{valid:!0,corrected:l?c:null}}$a.exports={validateToolArgs:vf,closestMatch:ss,levenshtein:ga,getCachedSchema:ha,clearSchemaCache:kf}});var xa=L((ly,ba)=>{var{levenshtein:os}=wo(),Sf=200,Ef=.3,Tf=2;function bo(t){return t.replace(/\r\n/g,`
121
+ Expected parameters: ${JSON.stringify(s.properties,null,2)}`}:{valid:!0,corrected:l?c:null}}function Em(t,e){let s=[],o={...t};if(!o.function&&!o.name)return s.push('Tool call missing both "function" and "name" fields'),{valid:!1,normalized:o,errors:s};if(!o.function&&o.name&&(o.function={name:o.name,arguments:o.arguments||o.args||{}},delete o.name,delete o.args),o.function&&o.function.args!==void 0&&o.function.arguments===void 0&&(o.function.arguments=o.function.args,delete o.function.args),o.function&&(o.function.arguments===void 0||o.function.arguments===null)&&(o.function.arguments={}),o.function&&typeof o.function.arguments=="string"){let n=o.function.arguments;if(n.trim()==="")o.function.arguments={};else try{o.function.arguments=JSON.parse(n)}catch(r){return s.push(`Invalid JSON in arguments${e?` (${e})`:""}: ${r.message}`),{valid:!1,normalized:o,errors:s}}}return o.function&&typeof o.function.arguments!="object"?(s.push(`Arguments must be an object, got ${typeof o.function.arguments}`),{valid:!1,normalized:o,errors:s}):!o.function.name||typeof o.function.name!="string"?(s.push("Tool call function name must be a non-empty string"),{valid:!1,normalized:o,errors:s}):{valid:s.length===0,normalized:o,errors:s}}vc.exports={validateToolArgs:Sm,validateToolCallFormat:Em,closestMatch:Is,levenshtein:xc,getCachedSchema:kc,clearSchemaCache:vm}});var Rc=j((I0,Tc)=>{var{levenshtein:Ls}=ur(),Tm=200,Rm=.3,Cm=2;function dr(t){return t.replace(/\r\n/g,`
116
122
  `).replace(/\r/g,`
117
- `).replace(/\t/g," ".repeat(Tf)).split(`
118
- `).map(e=>{let s=e.replace(/\s+$/,""),n=s.match(/^(\s*)(.*)/);if(!n)return s;let[,o,r]=n;return o+r.replace(/ {2,}/g," ")}).join(`
119
- `)}function Rf(t,e){if(t.includes(e))return e;if(e.length<10)return null;let s=bo(t),n=bo(e);if(!s.includes(n))return null;let o=t.split(`
123
+ `).replace(/\t/g," ".repeat(Cm)).split(`
124
+ `).map(e=>{let s=e.replace(/\s+$/,""),o=s.match(/^(\s*)(.*)/);if(!o)return s;let[,n,r]=o;return n+r.replace(/ {2,}/g," ")}).join(`
125
+ `)}function Am(t,e){if(t.includes(e))return e;if(e.length<10)return null;let s=dr(t),o=dr(e);if(!s.includes(o))return null;let n=t.split(`
120
126
  `),r=s.split(`
121
- `),i=n.split(`
122
- `),c=i[0],l=i[i.length-1];for(let u=0;u<=r.length-i.length;u++){let d=!0;for(let p=0;p<i.length;p++)if(r[u+p]!==i[p]){d=!1;break}if(d)return o.slice(u,u+i.length).join(`
123
- `)}if(i.length===1){for(let u=0;u<r.length;u++)if(r[u].indexOf(n)!==-1)return o[u]}return null}function Cf(t,e){if(!t||!e)return null;let s=t.split(`
124
- `),o=e.split(`
125
- `).length;return s.length===0||o===0?null:o===1?Af(s,e):Nf(s,e,o)}function ya(t){return Math.max(1,Math.floor(t/Sf))}function wa(t,e){return t<=Math.ceil(e*Ef)}function Af(t,e){let s=e.trim(),n=ya(t.length),o=null,r=1/0;for(let i=0;i<t.length;i+=n){let c=t[i];if(!c.trim())continue;let l=os(c.trim(),s);l<r&&(r=l,o={text:c,distance:l,line:i+1})}return o&&n>1&&(o=Of(t,s,o,n)||o,r=o.distance),wa(r,e.length)?o:null}function Of(t,e,s,n){let o=s.line-1,r=Math.max(0,o-n),i=Math.min(t.length-1,o+n),c=s.distance,l=null;for(let u=r;u<=i;u++){let d=t[u];if(!d.trim())continue;let p=os(d.trim(),e);p<c&&(c=p,l={text:d,distance:p,line:u+1})}return l}function Nf(t,e,s){let n=t.length-s+1;if(n<=0)return null;let o=ya(n),r=null,i=1/0;for(let c=0;c<n;c+=o){let l=t.slice(c,c+s).join(`
126
- `),u=os(l,e);u<i&&(i=u,r={text:l,distance:u,line:c+1})}return r&&o>1&&(r=Mf(t,e,r,o,s,n)||r,i=r.distance),wa(i,e.length)?r:null}function Mf(t,e,s,n,o,r){let i=s.line-1,c=Math.max(0,i-n),l=Math.min(r-1,i+n),u=s.distance,d=null;for(let p=c;p<=l;p++){let f=t.slice(p,p+o).join(`
127
- `),h=os(f,e);h<u&&(u=h,d={text:f,distance:h,line:p+1})}return d}ba.exports={normalizeWhitespace:bo,fuzzyFindText:Rf,findMostSimilar:Cf}});var ka=L((dy,_a)=>{var{C:uy}=de(),Pf=[{name:"OpenAI API Key",regex:/sk-[a-zA-Z0-9]{20,}/i},{name:"Anthropic API Key",regex:/sk-ant-api03-[a-zA-Z0-9-]{90,}/i},{name:"Google Gemini API Key",regex:/AIzaSy[a-zA-Z0-9_-]{30,45}/i},{name:"Slack Token",regex:/xox[bpors]-[a-zA-Z0-9-]+/i},{name:"AWS Access Key",regex:/AKIA[A-Z0-9]{16}/i},{name:"GitHub Token",regex:/ghp_[a-zA-Z0-9]{36}/i},{name:"Private Key",regex:/BEGIN (RSA|EC|DSA|OPENSSH|PGP) PRIVATE KEY/i},{name:"Database URL",regex:/\b(postgres|mongodb|mysql|redis):\/\/[^"'\s]+/i},{name:"Hardcoded Secret",regex:/(password|secret|token|api_key|apikey|api_secret|access_token|auth_token|credentials)\s*[:=]\s*['"'][^'"']{8,}/i}],Lf=[{name:"TODO",regex:/\bTODO\b/i,severity:"warn"},{name:"FIXME",regex:/\bFIXME\b/i,severity:"warn"},{name:"Debugger",regex:/\bdebugger\b/,severity:"error",ext:[".js",".ts",".jsx",".tsx"]},{name:"eval()",regex:/\beval\s*\(/,severity:"warn",ext:[".js",".ts",".jsx",".tsx"]},{name:"Console Log",regex:/\bconsole\.log\(/,severity:"info",ext:[".js",".ts",".jsx",".tsx"]},{name:"ANSI Code",regex:/\\x1b\[[0-9;]*m/,severity:"warn",message:"Avoid hardcoded ANSI codes; use cli/ui.js instead."}];function If(t,e){let s=e.split(`
128
- `),n=[],o=t?`.${t.split(".").pop()}`:"";for(let r=0;r<s.length;r++){let i=s[r],c=r+1;for(let l of Pf)l.regex.test(i)&&n.push({line:c,message:`Potential secret detected: ${l.name}`,severity:"error"});for(let l of Lf)l.ext&&!l.ext.includes(o)||l.regex.test(i)&&n.push({line:c,message:l.message||`Found ${l.name}`,severity:l.severity||"warn"})}return s.length>500&&n.push({line:0,message:`Large file detected (${s.length} lines). Consider refactoring.`,severity:"info"}),n}_a.exports={runDiagnostics:If}});var ko=L((fy,Ea)=>{var qf=require("fs").promises,va=require("path"),{exec:Df}=require("util").promisify(require("child_process").exec),Bt=[],_o=null,rs=!1,xo=0,jf=6e4;function Sa(t){return!(Bt.length===0||_o!==t||Date.now()-xo>jf)}async function Ff(t){if(!rs&&!Sa(t)){rs=!0,_o=t;try{try{let{stdout:n}=await Df("rg --files",{cwd:t,timeout:5e3});Bt=n.split(`
129
- `).filter(Boolean),xo=Date.now(),rs=!1;return}catch{}let e=[],s=async(n,o)=>{let r;try{r=await qf.readdir(n,{withFileTypes:!0})}catch{return}for(let i of r){if(i.name==="node_modules"||i.name===".git"||i.name.startsWith("."))continue;let c=o?`${o}/${i.name}`:i.name;i.isDirectory()?await s(va.join(n,i.name),c):e.push(c)}};await s(t,""),Bt=e,xo=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{rs=!1}}}function Uf(){return Bt}function Wf(){return _o}function Bf(t){return Bt.filter(e=>va.basename(e)===t)}function Hf(t){let e=t.toLowerCase();return Bt.filter(s=>s.toLowerCase().includes(e)).slice(0,20)}Ea.exports={refreshIndex:Ff,getFileIndex:Uf,getIndexedCwd:Wf,findFileInIndex:Bf,searchIndex:Hf,isIndexValid:Sa}});var Ht=L((py,Aa)=>{var is=require("fs"),cs=require("path"),vo=require("os"),{execFile:Gf}=require("child_process"),{promisify:zf}=require("util"),So=zf(Gf),Kf=cs.join(".nex","servers.json"),as=cs.join(vo.tmpdir(),"nex-ssh-sockets");function Yf(){return cs.join(process.cwd(),Kf)}function Ta(){let t=Yf();if(!is.existsSync(t))return{};try{return JSON.parse(is.readFileSync(t,"utf-8"))}catch{return{}}}function Jf(t){let e=Ta();if(e[t])return{...e[t],_name:t};if(/^[\w.-]+@[\w.-]+$/.test(t)||/[\w-]+\.[\w.-]+/.test(t)||t==="localhost"){let[o,r]=t.includes("@")?t.split("@"):[void 0,t];return{host:r,user:o}}let s=Object.keys(e),n=s.length?`Available profiles: ${s.join(", ")}`:"No profiles configured. Create .nex/servers.json";throw new Error(`Unknown server: "${t}". ${n}`)}function Vf(){is.existsSync(as)||is.mkdirSync(as,{recursive:!0})}function Ra(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-o","ServerAliveInterval=30"];t.key&&e.push("-i",t.key.replace(/^~/,vo.homedir())),t.port&&Number(t.port)!==22&&e.push("-p",String(t.port)),Vf();let s=t.user?`${t.user}@${t.host}`:t.host,n=cs.join(as,s.replace(/[@.:]/g,"_"));return e.push("-o","ControlMaster=auto","-o",`ControlPath=${n}`,"-o","ControlPersist=120"),e.push(s),{args:e,target:s}}function Ca(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-r"];return t.key&&e.push("-i",t.key.replace(/^~/,vo.homedir())),t.port&&Number(t.port)!==22&&e.push("-P",String(t.port)),e}async function Xf(t,e,{timeout:s=3e4,sudo:n=!1}={}){let{args:o}=Ra(t),r=n&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:i,stderr:c}=await So("ssh",[...o,r],{timeout:s,maxBuffer:4194304});return{stdout:i||"",stderr:c||"",exitCode:0}}catch(i){let c=typeof i.code=="number"?i.code:1,l=(i.stderr||i.message||"").toString();return{stdout:(i.stdout||"").toString(),stderr:l,exitCode:c,error:ls(l,t)}}}async function Qf(t,e,s,{timeout:n=12e4}={}){let o=Ca(t),r=t.user?`${t.user}@${t.host}`:t.host;o.push(e,`${r}:${s}`);try{let{stdout:i,stderr:c}=await So("scp",o,{timeout:n,maxBuffer:1048576});return i||c||`Uploaded ${e} \u2192 ${r}:${s}`}catch(i){let c=(i.stderr||i.message||"").toString();throw new Error(ls(c,t)||c)}}async function Zf(t,e,s,{timeout:n=12e4}={}){let o=Ca(t),r=t.user?`${t.user}@${t.host}`:t.host;o.push(`${r}:${e}`,s);try{let{stdout:i,stderr:c}=await So("scp",o,{timeout:n,maxBuffer:1048576});return i||c||`Downloaded ${r}:${e} \u2192 ${s}`}catch(i){let c=(i.stderr||i.message||"").toString();throw new Error(ls(c,t)||c)}}function ls(t,e){if(!t)return"";if(/connection refused/i.test(t)){let s=e.port||22;return`${t}
127
+ `),i=o.split(`
128
+ `),c=i[0],l=i[i.length-1];for(let u=0;u<=r.length-i.length;u++){let d=!0;for(let f=0;f<i.length;f++)if(r[u+f]!==i[f]){d=!1;break}if(d)return n.slice(u,u+i.length).join(`
129
+ `)}if(i.length===1){for(let u=0;u<r.length;u++)if(r[u].indexOf(o)!==-1)return n[u]}return null}function Om(t,e){if(!t||!e)return null;let s=t.split(`
130
+ `),n=e.split(`
131
+ `).length;return s.length===0||n===0?null:n===1?Nm(s,e):Mm(s,e,n)}function Sc(t){return Math.max(1,Math.floor(t/Tm))}function Ec(t,e){return t<=Math.ceil(e*Rm)}function Nm(t,e){let s=e.trim(),o=Sc(t.length),n=null,r=1/0;for(let i=0;i<t.length;i+=o){let c=t[i];if(!c.trim())continue;let l=Ls(c.trim(),s);l<r&&(r=l,n={text:c,distance:l,line:i+1})}return n&&o>1&&(n=Pm(t,s,n,o)||n,r=n.distance),Ec(r,e.length)?n:null}function Pm(t,e,s,o){let n=s.line-1,r=Math.max(0,n-o),i=Math.min(t.length-1,n+o),c=s.distance,l=null;for(let u=r;u<=i;u++){let d=t[u];if(!d.trim())continue;let f=Ls(d.trim(),e);f<c&&(c=f,l={text:d,distance:f,line:u+1})}return l}function Mm(t,e,s){let o=t.length-s+1;if(o<=0)return null;let n=Sc(o),r=null,i=1/0;for(let c=0;c<o;c+=n){let l=t.slice(c,c+s).join(`
132
+ `),u=Ls(l,e);u<i&&(i=u,r={text:l,distance:u,line:c+1})}return r&&n>1&&(r=Im(t,e,r,n,s,o)||r,i=r.distance),Ec(i,e.length)?r:null}function Im(t,e,s,o,n,r){let i=s.line-1,c=Math.max(0,i-o),l=Math.min(r-1,i+o),u=s.distance,d=null;for(let f=c;f<=l;f++){let m=t.slice(f,f+n).join(`
133
+ `),h=Ls(m,e);h<u&&(u=h,d={text:m,distance:h,line:f+1})}return d}Tc.exports={normalizeWhitespace:dr,fuzzyFindText:Am,findMostSimilar:Om}});var Ac=j((j0,Cc)=>{var{C:L0}=ye(),Lm=[{name:"OpenAI API Key",regex:/sk-[a-zA-Z0-9]{20,}/i},{name:"Anthropic API Key",regex:/sk-ant-api03-[a-zA-Z0-9-]{90,}/i},{name:"Google Gemini API Key",regex:/AIzaSy[a-zA-Z0-9_-]{30,45}/i},{name:"Slack Token",regex:/xox[bpors]-[a-zA-Z0-9-]+/i},{name:"AWS Access Key",regex:/AKIA[A-Z0-9]{16}/i},{name:"GitHub Token",regex:/ghp_[a-zA-Z0-9]{36}/i},{name:"Private Key",regex:/BEGIN (RSA|EC|DSA|OPENSSH|PGP) PRIVATE KEY/i},{name:"Database URL",regex:/\b(postgres|mongodb|mysql|redis):\/\/[^"'\s]+/i},{name:"Hardcoded Secret",regex:/(password|secret|token|api_key|apikey|api_secret|access_token|auth_token|credentials)\s*[:=]\s*['"'][^'"']{8,}/i}],jm=[{name:"TODO",regex:/\bTODO\b/i,severity:"warn"},{name:"FIXME",regex:/\bFIXME\b/i,severity:"warn"},{name:"Debugger",regex:/\bdebugger\b/,severity:"error",ext:[".js",".ts",".jsx",".tsx"]},{name:"eval()",regex:/\beval\s*\(/,severity:"warn",ext:[".js",".ts",".jsx",".tsx"]},{name:"Console Log",regex:/\bconsole\.log\(/,severity:"info",ext:[".js",".ts",".jsx",".tsx"]},{name:"ANSI Code",regex:/\\x1b\[[0-9;]*m/,severity:"warn",message:"Avoid hardcoded ANSI codes; use cli/ui.js instead."}];function Dm(t,e){let s=e.split(`
134
+ `),o=[],n=t?`.${t.split(".").pop()}`:"";for(let r=0;r<s.length;r++){let i=s[r],c=r+1;for(let l of Lm)l.regex.test(i)&&o.push({line:c,message:`Potential secret detected: ${l.name}`,severity:"error"});for(let l of jm)l.ext&&!l.ext.includes(n)||l.regex.test(i)&&o.push({line:c,message:l.message||`Found ${l.name}`,severity:l.severity||"warn"})}return s.length>500&&o.push({line:0,message:`Large file detected (${s.length} lines). Consider refactoring.`,severity:"info"}),o}Cc.exports={runDiagnostics:Dm}});var gr=j((D0,Lc)=>{var dn=require("fs").promises,fn=require("path"),{exec:qm}=require("util").promisify(require("child_process").exec),pn=[],hr=null,js=!1,pr=0,Fm=6e4;function Nc(t){return!(pn.length===0||hr!==t||Date.now()-pr>Fm)}async function Pc(t){if(!js&&!Nc(t)){js=!0,hr=t;try{try{let{stdout:o}=await qm("rg --files",{cwd:t,timeout:5e3});pn=o.split(`
135
+ `).filter(Boolean),pr=Date.now(),js=!1;return}catch{}let e=[],s=async(o,n)=>{let r;try{r=await dn.readdir(o,{withFileTypes:!0})}catch{return}for(let i of r){if(i.name==="node_modules"||i.name===".git"||i.name.startsWith("."))continue;let c=n?`${n}/${i.name}`:i.name;i.isDirectory()?await s(fn.join(o,i.name),c):e.push(c)}};await s(t,""),pn=e,pr=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{js=!1}}}function mr(){return pn}function Um(){return hr}function Wm(t){return pn.filter(e=>fn.basename(e)===t)}function Bm(t){let e=t.toLowerCase();return pn.filter(s=>s.toLowerCase().includes(e)).slice(0,20)}var fr=null,Oc=0,Hm=12e4,Gm=new Set([".js",".ts",".jsx",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".rb"]);function Mc(t,e){let s=[],o=t.split(`
136
+ `);for(let n=0;n<o.length;n++){let r=o[n],i=n+1;if([".js",".ts",".jsx",".tsx",".mjs",".cjs"].includes(e)){let c=r.match(/(?:export\s+)?(?:async\s+)?function\s+(\w+)/);c&&s.push({type:"function",name:c[1],line:i});let l=r.match(/(?:export\s+)?class\s+(\w+)/);l&&s.push({type:"class",name:l[1],line:i});let u=r.match(/(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?(?:\([^)]*\)|[\w$]+)\s*=>/);u&&s.push({type:"function",name:u[1],line:i});let d=r.match(/module\.exports\s*=\s*\{([^}]+)\}/);if(d){let m=d[1].split(",").map(h=>h.trim().split(":")[0].trim()).filter(Boolean);for(let h of m)/^\w+$/.test(h)&&s.push({type:"export",name:h,line:i})}let f=r.match(/(?:require\(['"]([^'"]+)['"]\)|from\s+['"]([^'"]+)['"])/);if(f){let m=f[1]||f[2];s.push({type:"import",name:m,line:i})}}if(e===".py"){let c=r.match(/^(?:async\s+)?def\s+(\w+)/);c&&s.push({type:"function",name:c[1],line:i});let l=r.match(/^class\s+(\w+)/);l&&s.push({type:"class",name:l[1],line:i});let u=r.match(/^(?:from\s+(\S+)\s+)?import\s+(\S+)/);u&&s.push({type:"import",name:u[1]||u[2],line:i})}if(e===".go"){let c=r.match(/^func\s+(?:\([^)]+\)\s+)?(\w+)/);c&&s.push({type:"function",name:c[1],line:i});let l=r.match(/^type\s+(\w+)\s+struct/);l&&s.push({type:"class",name:l[1],line:i})}}return s}async function Ic(t){t=t||process.cwd();let e=fn.join(t,".nex","index","content-index.json"),s={};if(fr&&Date.now()-Oc<Hm)return fr;try{let i=await dn.readFile(e,"utf-8");s=JSON.parse(i)}catch{s={files:{}}}mr().length===0&&await Pc(t);let n={files:{}},r=!1;for(let i of mr()){let c=fn.extname(i);if(!Gm.has(c))continue;let l=fn.join(t,i);try{let d=(await dn.stat(l)).mtimeMs;if(s.files[i]&&s.files[i].mtime===d){n.files[i]=s.files[i];continue}let f=await dn.readFile(l,"utf-8"),m=Mc(f,c);n.files[i]={defs:m,mtime:d},r=!0}catch{}}if(r){let i=fn.join(t,".nex","index");await dn.mkdir(i,{recursive:!0}),await dn.writeFile(e,JSON.stringify(n),"utf-8")}return fr=n,Oc=Date.now(),n}async function Km(t,e){let s=await Ic(),o=[],n=t.toLowerCase();for(let[r,i]of Object.entries(s.files))for(let c of i.defs)e&&c.type!==e||c.name.toLowerCase().includes(n)&&o.push({file:r,type:c.type,name:c.name,line:c.line});return o.sort((r,i)=>{let c=r.name.toLowerCase()===n?0:1,l=i.name.toLowerCase()===n?0:1;if(c!==l)return c-l;let u=r.name.toLowerCase().startsWith(n)?0:1,d=i.name.toLowerCase().startsWith(n)?0:1;return u-d}),o.slice(0,50)}Lc.exports={refreshIndex:Pc,getFileIndex:mr,getIndexedCwd:Um,findFileInIndex:Wm,searchIndex:Bm,isIndexValid:Nc,buildContentIndex:Ic,searchContentIndex:Km,extractDefinitions:Mc}});var mn=j((q0,Fc)=>{var Ds=require("fs"),Fs=require("path"),Us=require("os"),{execFile:zm}=require("child_process"),{promisify:Ym}=require("util"),$r=Ym(zm),Xm=Fs.join(Us.homedir(),".nex","servers.json"),qs=Fs.join(Us.tmpdir(),"nex-ssh-sockets");function Jm(){return Fs.join(process.cwd(),".nex","servers.json")}function jc(){let t=o=>{if(!Ds.existsSync(o))return{};try{return JSON.parse(Ds.readFileSync(o,"utf-8"))}catch{return{}}},e=t(Xm),s=t(Jm());return{...e,...s}}function Vm(t){let e=jc();if(e[t])return{...e[t],_name:t};if(/^[\w.-]+@[\w.-]+$/.test(t)||/[\w-]+\.[\w.-]+/.test(t)||t==="localhost"){let[n,r]=t.includes("@")?t.split("@"):[void 0,t];return{host:r,user:n}}let s=Object.keys(e),o=s.length?`Available profiles: ${s.join(", ")}`:"No profiles configured. Create .nex/servers.json (project) or ~/.nex/servers.json (global)";throw new Error(`Unknown server: "${t}". ${o}`)}function Qm(){Ds.existsSync(qs)||Ds.mkdirSync(qs,{recursive:!0})}function Dc(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-o","ServerAliveInterval=30"];t.key&&e.push("-i",t.key.replace(/^~/,Us.homedir())),t.port&&Number(t.port)!==22&&e.push("-p",String(t.port)),Qm();let s=t.user?`${t.user}@${t.host}`:t.host,o=Fs.join(qs,s.replace(/[@.:]/g,"_"));return e.push("-o","ControlMaster=auto","-o",`ControlPath=${o}`,"-o","ControlPersist=120"),e.push(s),{args:e,target:s}}function qc(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-r"];return t.key&&e.push("-i",t.key.replace(/^~/,Us.homedir())),t.port&&Number(t.port)!==22&&e.push("-P",String(t.port)),e}async function Zm(t,e,{timeout:s=3e4,sudo:o=!1}={}){let{args:n}=Dc(t),r=o&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:i,stderr:c}=await $r("ssh",[...n,r],{timeout:s,maxBuffer:4194304});return{stdout:i||"",stderr:c||"",exitCode:0}}catch(i){let c=typeof i.code=="number"?i.code:1,l=(i.stderr||i.message||"").toString();return{stdout:(i.stdout||"").toString(),stderr:l,exitCode:c,error:Ws(l,t)}}}async function eh(t,e,s,{timeout:o=12e4}={}){let n=qc(t),r=t.user?`${t.user}@${t.host}`:t.host;n.push(e,`${r}:${s}`);try{let{stdout:i,stderr:c}=await $r("scp",n,{timeout:o,maxBuffer:1048576});return i||c||`Uploaded ${e} \u2192 ${r}:${s}`}catch(i){let c=(i.stderr||i.message||"").toString();throw new Error(Ws(c,t)||c)}}async function th(t,e,s,{timeout:o=12e4}={}){let n=qc(t),r=t.user?`${t.user}@${t.host}`:t.host;n.push(`${r}:${e}`,s);try{let{stdout:i,stderr:c}=await $r("scp",n,{timeout:o,maxBuffer:1048576});return i||c||`Downloaded ${r}:${e} \u2192 ${s}`}catch(i){let c=(i.stderr||i.message||"").toString();throw new Error(Ws(c,t)||c)}}function Ws(t,e){if(!t)return"";if(/connection refused/i.test(t)){let s=e.port||22;return`${t}
130
137
  HINT: Connection refused on ${e.host}:${s}. Check: server is running, SSH service is active (systemctl status sshd), firewall allows port ${s} (firewall-cmd --list-ports).`}if(/permission denied/i.test(t)){let s=e.key?`key: ${e.key}`:"SSH agent";return`${t}
131
138
  HINT: Auth failed using ${s} as user "${e.user||"root"}". Check: authorized_keys on server, correct username, key passphrase.`}return/no route to host|network unreachable|name or service not known/i.test(t)?`${t}
132
139
  HINT: Cannot reach ${e.host}. Check: network connection, correct hostname/IP, DNS resolution.`:/host key verification failed/i.test(t)?`${t}
133
140
  HINT: Host key changed for ${e.host}. To reset: ssh-keygen -R ${e.host}`:/timed out/i.test(t)?`${t}
134
141
  HINT: Connection timed out to ${e.host}. Check firewall rules and network connectivity.`:/too many authentication failures/i.test(t)?`${t}
135
- HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function ep(t,e){let s=e.user?`${e.user}@${e.host}`:e.host,n=e.port&&Number(e.port)!==22?`:${e.port}`:"",o=e.os?` [${e.os}]`:"",r=e.key?` key:${e.key}`:"",i=e.sudo?" sudo:yes":"";return`${t}: ${s}${n}${o}${r}${i}`}Aa.exports={loadServerProfiles:Ta,resolveProfile:Jf,buildSSHArgs:Ra,sshExec:Xf,scpUpload:Qf,scpDownload:Zf,enrichSSHError:ls,formatProfile:ep,SSH_SOCKET_DIR:as}});var Ro=L((my,Na)=>{var dn=require("fs"),Eo=require("path"),tp=Eo.join(".nex","deploy.json");function To(){return Eo.join(process.cwd(),tp)}function Oa(){let t=To();if(!dn.existsSync(t))return{};try{return JSON.parse(dn.readFileSync(t,"utf-8"))}catch{return{}}}function np(t){let e=Oa();if(e[t])return{...e[t],_name:t};let s=Object.keys(e),n=s.length?`Available: ${s.join(", ")}`:"No deploy configs found. Create .nex/deploy.json or use explicit params.";throw new Error(`Unknown deploy config: "${t}". ${n}`)}function sp(t){let e=Eo.join(process.cwd(),".nex");dn.existsSync(e)||dn.mkdirSync(e,{recursive:!0}),dn.writeFileSync(To(),JSON.stringify(t,null,2)+`
136
- `,"utf-8")}Na.exports={loadDeployConfigs:Oa,resolveDeployConfig:np,saveDeployConfigs:sp,getDeployConfigPath:To}});var pn=L((hy,La)=>{var Co=null,tt=null,fn=null,Ma=`Playwright is not installed. Install with:
142
+ HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function nh(t,e){let s=e.user?`${e.user}@${e.host}`:e.host,o=e.port&&Number(e.port)!==22?`:${e.port}`:"",n=e.os?` [${e.os}]`:"",r=e.key?` key:${e.key}`:"",i=e.sudo?" sudo:yes":"";return`${t}: ${s}${o}${n}${r}${i}`}Fc.exports={loadServerProfiles:jc,resolveProfile:Vm,buildSSHArgs:Dc,sshExec:Zm,scpUpload:eh,scpDownload:th,enrichSSHError:Ws,formatProfile:nh,SSH_SOCKET_DIR:qs}});var br=j((F0,Wc)=>{var Dn=require("fs"),yr=require("path"),sh=yr.join(".nex","deploy.json");function wr(){return yr.join(process.cwd(),sh)}function Uc(){let t=wr();if(!Dn.existsSync(t))return{};try{return JSON.parse(Dn.readFileSync(t,"utf-8"))}catch{return{}}}function oh(t){let e=Uc();if(e[t])return{...e[t],_name:t};let s=Object.keys(e),o=s.length?`Available: ${s.join(", ")}`:"No deploy configs found. Create .nex/deploy.json or use explicit params.";throw new Error(`Unknown deploy config: "${t}". ${o}`)}function rh(t){let e=yr.join(process.cwd(),".nex");Dn.existsSync(e)||Dn.mkdirSync(e,{recursive:!0}),Dn.writeFileSync(wr(),JSON.stringify(t,null,2)+`
143
+ `,"utf-8")}Wc.exports={loadDeployConfigs:Uc,resolveDeployConfig:oh,saveDeployConfigs:rh,getDeployConfigPath:wr}});var Bs=j((U0,Gc)=>{var{getActiveModel:ih,getActiveProviderName:ah}=we(),qn={essential:["bash","read_file","write_file","edit_file","list_directory"],standard:["bash","read_file","write_file","edit_file","list_directory","search_files","glob","grep","ask_user","git_status","git_diff","git_log","task_list","ssh_exec","service_manage","service_logs","container_list","container_logs","container_exec","container_manage","deploy"],full:null},Fn={"qwen3-coder:480b":"full","qwen3-coder-next":"full","kimi-k2.5":"full","kimi-k2:1t":"full","kimi-k2-thinking":"full","deepseek-v3.2":"full","deepseek-v3.1:671b":"full","devstral-2:123b":"full","devstral-small-2:24b":"standard","cogito-2.1:671b":"full","qwen3-next:80b":"full","qwen3.5:397b-cloud":"full","qwen3.5:397b":"full","qwen3.5:122b-a10b":"full","qwen3.5:35b-a3b":"full","qwen3.5:27b":"full","qwen3.5:9b":"standard","qwen3.5:4b":"essential","qwen3.5:2b":"essential","qwen3.5:0.8b":"essential","mistral-large-3:675b":"full","gpt-oss:120b":"full","minimax-m2.5":"full","glm-5":"full","glm-4.7":"standard","gemma3:27b":"standard","gemma3:12b":"essential","gemma3:4b":"essential","ministral-3:14b":"standard","ministral-3:8b":"essential","gpt-4o":"full","gpt-4.1":"full",o1:"full",o3:"full","o4-mini":"full","claude-sonnet":"full","claude-sonnet-4-5":"full","claude-opus":"full","claude-haiku":"standard","claude-sonnet-4":"full","gemini-3.1-pro-preview":"full","gemini-3-flash-preview":"full","gemini-2.5-pro":"full","gemini-2.5-flash":"full","gemini-2.0-flash":"standard","gemini-2.0-flash-lite":"essential"},Un={ollama:"full",openai:"full",anthropic:"full",gemini:"full",local:"essential"},rt={};function Hc(){try{let t=require("fs"),s=require("path").join(process.cwd(),".nex","config.json");t.existsSync(s)&&(rt=JSON.parse(t.readFileSync(s,"utf-8")).toolTiers||{})}catch{rt={}}}Hc();function _r(){let e=ih()?.id,s=ah();return e&&rt[e]?rt[e]:s&&rt[`${s}:*`]?rt[`${s}:*`]:e&&Fn[e]?Fn[e]:s&&Un[s]?Un[s]:"full"}var ch=new Set(["claude-sonnet","claude-sonnet-4-5","claude-sonnet-4","claude-opus","claude-haiku","gpt-4o","gpt-4.1","o1","o3","o4-mini","kimi-k2:1t","kimi-k2.5","kimi-k2-thinking","qwen3-coder:480b","qwen3-coder-next","deepseek-v3.2","deepseek-v3.1:671b"]),Bc={anthropic:"strict",openai:"strict",gemini:"strict",ollama:"fuzzy",local:"fuzzy"};function lh(t,e){return t&&(ch.has(t)||t.startsWith("claude-"))?"strict":e&&Bc[e]?Bc[e]:"fuzzy"}function uh(t,e){return t&&rt[t]?rt[t]:e&&rt[`${e}:*`]?rt[`${e}:*`]:t&&Fn[t]?Fn[t]:e&&Un[e]?Un[e]:"full"}function dh(t,e){let s=e||_r();if(s==="full"||!qn[s])return t;let o=new Set(qn[s]);return t.filter(n=>o.has(n.function.name))}function fh(){let t=_r(),e=qn[t]?qn[t].length:"all";return{tier:t,toolCount:e}}Gc.exports={filterToolsForModel:dh,getActiveTier:_r,getModelTier:uh,getEditMode:lh,getTierInfo:fh,TIERS:qn,MODEL_TIERS:Fn,PROVIDER_DEFAULT_TIER:Un,loadConfigOverrides:Hc}});var Bn=j((W0,Yc)=>{var kr=null,ht=null,Wn=null,Kc=`Playwright is not installed. Install with:
137
144
  npm install playwright && npx playwright install chromium
138
- Then restart nex-code.`;function Pa(){if(fn!==null)return fn;try{require("playwright"),fn=!0}catch{fn=!1}return fn}async function us(){if(!Pa())throw new Error(Ma);return Co||(Co=require("playwright")),(!tt||!tt.isConnected())&&(tt=await Co.chromium.launch({headless:!0})),tt}async function op(){if(tt){try{await tt.close()}catch{}tt=null}}process.on("exit",()=>{if(tt)try{tt.close()}catch{}});async function rp(t,{timeout:e=3e4,waitFor:s="domcontentloaded"}={}){let o=await(await us()).newPage();try{await o.goto(t,{waitUntil:s,timeout:e});let r=await o.title(),i=await o.evaluate(()=>(document.querySelectorAll("script,style,nav,footer,header,aside,[role=navigation]").forEach(u=>u.remove()),document.body?.innerText||"")),c=await o.evaluate(()=>Array.from(document.querySelectorAll("a[href]")).slice(0,30).map(l=>({text:(l.innerText||l.textContent||"").trim().substring(0,80),href:l.href})).filter(l=>l.text&&l.href&&!l.href.startsWith("javascript:")));return{title:r,url:o.url(),text:i.substring(0,8e3)+(i.length>8e3?`
139
- ...(truncated)`:""),links:c.slice(0,20)}}finally{await o.close()}}async function ip(t,{width:e=1280,height:s=800,fullPage:n=!1,timeout:o=3e4}={}){let i=await(await us()).newPage();try{await i.setViewportSize({width:e,height:s}),await i.goto(t,{waitUntil:"networkidle",timeout:o});let c=await i.screenshot({type:"png",fullPage:n}),l=require("os"),u=require("path"),d=require("fs"),p=u.join(l.tmpdir(),`nex-screenshot-${Date.now()}.png`);return d.writeFileSync(p,c),{path:p,base64:c.toString("base64"),media_type:"image/png",title:await i.title(),url:i.url()}}finally{await i.close()}}async function ap(t,{selector:e,text:s,timeout:n=3e4}={}){if(!e&&!s)throw new Error("selector or text is required");let r=await(await us()).newPage();try{await r.goto(t,{waitUntil:"domcontentloaded",timeout:n}),s?await r.getByText(s,{exact:!1}).first().click({timeout:1e4}):await r.locator(e).first().click({timeout:1e4}),await r.waitForLoadState("domcontentloaded");let i=await r.title();return`Clicked \u2014 now at: ${r.url()} (${i})`}finally{await r.close()}}async function cp(t,{selector:e,value:s,submit:n=!1,timeout:o=3e4}={}){if(!e||s===void 0)throw new Error("selector and value are required");let i=await(await us()).newPage();try{return await i.goto(t,{waitUntil:"domcontentloaded",timeout:o}),await i.fill(e,String(s)),n&&(await i.keyboard.press("Enter"),await i.waitForLoadState("domcontentloaded")),`Filled "${e}" with value. ${n?`Submitted \u2192 ${i.url()}`:"Not submitted."}`}finally{await i.close()}}La.exports={isPlaywrightAvailable:Pa,browserNavigate:rp,browserScreenshot:ip,browserClick:ap,browserFill:cp,closeBrowser:op,INSTALL_MSG:Ma}});var ds=L((gy,Ia)=>{var{C:ne}=de(),hn="",xe=[],mn=0,Et=null;function lp(t){Et=t}function up(t,e){hn=t,xe=[],mn=0;for(let n of e){mn++;let o=`t${mn}`;xe.push({id:o,description:n.description||n.title||n.name||n.task||`Task ${mn}`,status:"pending",dependsOn:n.depends_on||[],result:null})}let s=xe.map(n=>({...n}));return Et&&Et("create",{name:t,tasks:s}),s}function dp(t,e,s){let n=xe.find(o=>o.id===t);return n?(n.status=e,s!==void 0&&(n.result=s),Et&&Et("update",{id:t,status:e,result:s}),{...n}):null}function fp(){return{name:hn,tasks:xe.map(t=>({...t}))}}function pp(){hn="",xe=[],mn=0,Et&&Et("clear",{})}function mp(){return xe.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let s=xe.find(n=>n.id===e);return s&&s.status==="done"}))}function hp(){if(xe.length===0)return`${ne.dim}No active tasks${ne.reset}`;let t=[];hn&&(t.push(` ${ne.bold}${ne.cyan}Tasks: ${hn}${ne.reset}`),t.push(` ${ne.dim}${"\u2500".repeat(40)}${ne.reset}`));for(let o of xe){let r,i;switch(o.status){case"done":r="\u2713",i=ne.green;break;case"in_progress":r="\u2192",i=ne.cyan;break;case"failed":r="\u2717",i=ne.red;break;default:r="\xB7",i=ne.dim}let c=o.dependsOn.length>0?` ${ne.dim}(after: ${o.dependsOn.join(", ")})${ne.reset}`:"",l=`[${o.status}]`,u=o.description.length>50?o.description.substring(0,47)+"...":o.description;if(t.push(` ${i}${r}${ne.reset} ${ne.bold}${o.id}${ne.reset} ${u.padEnd(40)} ${i}${l}${ne.reset}${c}`),o.result&&o.status==="done"){let d=o.result.length>60?o.result.substring(0,57)+"...":o.result;t.push(` ${ne.dim}\u2192 ${d}${ne.reset}`)}}let e=xe.filter(o=>o.status==="done").length,s=xe.filter(o=>o.status==="failed").length,n=xe.length;return t.push(` ${ne.dim}${"\u2500".repeat(40)}${ne.reset}`),t.push(` ${ne.dim}${e}/${n} done${s>0?`, ${s} failed`:""}${ne.reset}`),t.join(`
140
- `)}function gp(){return xe.length>0&&xe.some(t=>t.status==="pending"||t.status==="in_progress")}Ia.exports={createTasks:up,updateTask:dp,getTaskList:fp,clearTasks:pp,getReadyTasks:mp,renderTaskList:hp,setOnChange:lp,hasActiveTasks:gp}});var Oo=L(($y,Da)=>{var{getActiveModel:$p,getActiveProviderName:yp}=ge(),gn={essential:["bash","read_file","write_file","edit_file","list_directory"],standard:["bash","read_file","write_file","edit_file","list_directory","search_files","glob","grep","ask_user","git_status","git_diff","git_log","task_list","ssh_exec","service_manage","service_logs","container_list","container_logs","container_exec","container_manage","deploy"],full:null},$n={"qwen3-coder:480b":"full","qwen3-coder-next":"full","kimi-k2.5":"full","kimi-k2:1t":"full","kimi-k2-thinking":"full","deepseek-v3.2":"full","deepseek-v3.1:671b":"full","devstral-2:123b":"full","devstral-small-2:24b":"standard","cogito-2.1:671b":"full","qwen3-next:80b":"full","qwen3.5:397b-cloud":"full","qwen3.5:397b":"full","qwen3.5:122b-a10b":"full","qwen3.5:35b-a3b":"full","qwen3.5:27b":"full","qwen3.5:9b":"standard","qwen3.5:4b":"essential","qwen3.5:2b":"essential","qwen3.5:0.8b":"essential","mistral-large-3:675b":"full","gpt-oss:120b":"full","minimax-m2.5":"full","glm-5":"full","glm-4.7":"standard","gemma3:27b":"standard","gemma3:12b":"essential","gemma3:4b":"essential","ministral-3:14b":"standard","ministral-3:8b":"essential","gpt-4o":"full","gpt-4.1":"full",o1:"full",o3:"full","o4-mini":"full","claude-sonnet":"full","claude-sonnet-4-5":"full","claude-opus":"full","claude-haiku":"standard","claude-sonnet-4":"full","gemini-3.1-pro-preview":"full","gemini-3-flash-preview":"full","gemini-2.5-pro":"full","gemini-2.5-flash":"full","gemini-2.0-flash":"standard","gemini-2.0-flash-lite":"essential"},yn={ollama:"full",openai:"full",anthropic:"full",gemini:"full",local:"essential"},He={};function qa(){try{let t=require("fs"),s=require("path").join(process.cwd(),".nex","config.json");t.existsSync(s)&&(He=JSON.parse(t.readFileSync(s,"utf-8")).toolTiers||{})}catch{He={}}}qa();function Ao(){let e=$p()?.id,s=yp();return e&&He[e]?He[e]:s&&He[`${s}:*`]?He[`${s}:*`]:e&&$n[e]?$n[e]:s&&yn[s]?yn[s]:"full"}function wp(t,e){return t&&He[t]?He[t]:e&&He[`${e}:*`]?He[`${e}:*`]:t&&$n[t]?$n[t]:e&&yn[e]?yn[e]:"full"}function bp(t,e){let s=e||Ao();if(s==="full"||!gn[s])return t;let n=new Set(gn[s]);return t.filter(o=>n.has(o.function.name))}function xp(){let t=Ao(),e=gn[t]?gn[t].length:"all";return{tier:t,toolCount:e}}Da.exports={filterToolsForModel:bp,getActiveTier:Ao,getModelTier:wp,getTierInfo:xp,TIERS:gn,MODEL_TIERS:$n,PROVIDER_DEFAULT_TIER:yn,loadConfigOverrides:qa}});var Va=L((wy,Ja)=>{var{callStream:_p,getActiveProviderName:ps,getActiveModelId:kp,getConfiguredProviders:vp,getProvider:ja,getActiveProvider:Fa,parseModelSpec:Ua}=ge(),{parseToolArgs:Sp}=Jn(),{filterToolsForModel:Ep,getModelTier:fs}=Oo(),{trackUsage:Tp}=Ft(),{MultiProgress:Rp,C:yy}=de(),Cp=15,Wa=5,Ba=3,ms=new Map;function Ap(t,e){let s=ms.get(t);return s&&s!==e?!1:(ms.set(t,e),!0)}function wn(t){ms.delete(t)}function No(){ms.clear()}function Ha(t){let e=t.message||"",s=t.code||"";return!!(e.includes("429")||e.includes("500")||e.includes("502")||e.includes("503")||e.includes("504")||s==="ECONNRESET"||s==="ECONNABORTED"||s==="ETIMEDOUT"||s==="ECONNREFUSED"||e.includes("socket disconnected")||e.includes("TLS")||e.includes("ECONNRESET")||e.includes("fetch failed")||e.includes("ETIMEDOUT")||e.includes("ENOTFOUND"))}async function Ga(t,e,s){let n;for(let o=0;o<=Ba;o++)try{return await _p(t,e,s)}catch(r){if(n=r,o<Ba&&Ha(r)){let c=(r.message||"").includes("429")?Math.min(2e3*Math.pow(2,o),15e3):Math.min(500*Math.pow(2,o),4e3);await new Promise(l=>setTimeout(l,c).unref());continue}throw r}throw n}var Op=new Set(["ask_user","task_list","spawn_agents"]),Np=new Set(["write_file","edit_file","patch_file"]),Mp=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,Pp=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function za(t){return Pp.test(t)?"full":Mp.test(t)?"essential":"standard"}function Ka(t){let e=vp(),s=ps(),n=[...e].sort((o,r)=>(o.name===s?-1:1)-(r.name===s?-1:1));for(let o of n)for(let r of o.models)if(fs(r.id,o.name)===t)return{provider:o.name,model:r.id};return null}var Lp={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function Mo(t){if(t.model){let{provider:o,model:r}=Ua(t.model),i=o?ja(o):Fa(),c=o||ps();if(i&&i.isConfigured()&&(i.getModel(r)||c==="local")){let l=fs(r,c);return{provider:c,model:r,tier:l}}}let e=za(t.task),s=Lp[e];if(s){let{provider:o,model:r}=Ua(s),i=o?ja(o):Fa(),c=o||ps();if(i&&i.isConfigured()&&(i.getModel(r)||c==="local")){let l=fs(r,c);return{provider:c,model:r,tier:l}}}let n=Ka(e);if(n){let o=fs(n.model,n.provider);return{provider:n.provider,model:n.model,tier:o}}return{provider:null,model:null,tier:null}}async function Ya(t,e={}){let s=Math.min(t.max_iterations||10,Cp),n=`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,o=[],r={input:0,output:0},i=new Set,l=[{role:"system",content:`You are a focused sub-agent. Complete this specific task efficiently.
145
+ Then restart nex-code.`;function zc(){if(Wn!==null)return Wn;try{require("playwright"),Wn=!0}catch{Wn=!1}return Wn}async function Hs(){if(!zc())throw new Error(Kc);return kr||(kr=require("playwright")),(!ht||!ht.isConnected())&&(ht=await kr.chromium.launch({headless:!0})),ht}async function ph(){if(ht){try{await ht.close()}catch{}ht=null}}process.on("exit",()=>{if(ht)try{ht.close()}catch{}});async function mh(t,{timeout:e=3e4,waitFor:s="domcontentloaded"}={}){let n=await(await Hs()).newPage();try{await n.goto(t,{waitUntil:s,timeout:e});let r=await n.title(),i=await n.evaluate(()=>(document.querySelectorAll("script,style,nav,footer,header,aside,[role=navigation]").forEach(u=>u.remove()),document.body?.innerText||"")),c=await n.evaluate(()=>Array.from(document.querySelectorAll("a[href]")).slice(0,30).map(l=>({text:(l.innerText||l.textContent||"").trim().substring(0,80),href:l.href})).filter(l=>l.text&&l.href&&!l.href.startsWith("javascript:")));return{title:r,url:n.url(),text:i.substring(0,8e3)+(i.length>8e3?`
146
+ ...(truncated)`:""),links:c.slice(0,20)}}finally{await n.close()}}async function hh(t,{width:e=1280,height:s=800,fullPage:o=!1,timeout:n=3e4}={}){let i=await(await Hs()).newPage();try{await i.setViewportSize({width:e,height:s}),await i.goto(t,{waitUntil:"networkidle",timeout:n});let c=await i.screenshot({type:"png",fullPage:o}),l=require("os"),u=require("path"),d=require("fs"),f=u.join(l.tmpdir(),`nex-screenshot-${Date.now()}.png`);return d.writeFileSync(f,c),{path:f,base64:c.toString("base64"),media_type:"image/png",title:await i.title(),url:i.url()}}finally{await i.close()}}async function gh(t,{selector:e,text:s,timeout:o=3e4}={}){if(!e&&!s)throw new Error("selector or text is required");let r=await(await Hs()).newPage();try{await r.goto(t,{waitUntil:"domcontentloaded",timeout:o}),s?await r.getByText(s,{exact:!1}).first().click({timeout:1e4}):await r.locator(e).first().click({timeout:1e4}),await r.waitForLoadState("domcontentloaded");let i=await r.title();return`Clicked \u2014 now at: ${r.url()} (${i})`}finally{await r.close()}}async function $h(t,{selector:e,value:s,submit:o=!1,timeout:n=3e4}={}){if(!e||s===void 0)throw new Error("selector and value are required");let i=await(await Hs()).newPage();try{return await i.goto(t,{waitUntil:"domcontentloaded",timeout:n}),await i.fill(e,String(s)),o&&(await i.keyboard.press("Enter"),await i.waitForLoadState("domcontentloaded")),`Filled "${e}" with value. ${o?`Submitted \u2192 ${i.url()}`:"Not submitted."}`}finally{await i.close()}}Yc.exports={isPlaywrightAvailable:zc,browserNavigate:mh,browserScreenshot:hh,browserClick:gh,browserFill:$h,closeBrowser:ph,INSTALL_MSG:Kc}});var Gs=j((B0,Xc)=>{var{C:de}=ye(),Gn="",Se=[],Hn=0,Wt=null;function yh(t){Wt=t}function wh(t,e){Gn=t,Se=[],Hn=0;for(let o of e){Hn++;let n=`t${Hn}`;Se.push({id:n,description:o.description||o.title||o.name||o.task||`Task ${Hn}`,status:"pending",dependsOn:o.depends_on||[],result:null})}let s=Se.map(o=>({...o}));return Wt&&Wt("create",{name:t,tasks:s}),s}function bh(t,e,s){let o=Se.find(n=>n.id===t);return o?(o.status=e,s!==void 0&&(o.result=s),Wt&&Wt("update",{id:t,status:e,result:s}),{...o}):null}function _h(){return{name:Gn,tasks:Se.map(t=>({...t}))}}function kh(){Gn="",Se=[],Hn=0,Wt&&Wt("clear",{})}function xh(){return Se.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let s=Se.find(o=>o.id===e);return s&&s.status==="done"}))}function vh(){if(Se.length===0)return`${de.dim}No active tasks${de.reset}`;let t=[];Gn&&(t.push(` ${de.bold}${de.cyan}Tasks: ${Gn}${de.reset}`),t.push(` ${de.dim}${"\u2500".repeat(40)}${de.reset}`));for(let n of Se){let r,i;switch(n.status){case"done":r="\u2713",i=de.green;break;case"in_progress":r="\u2192",i=de.cyan;break;case"failed":r="\u2717",i=de.red;break;default:r="\xB7",i=de.dim}let c=n.dependsOn.length>0?` ${de.dim}(after: ${n.dependsOn.join(", ")})${de.reset}`:"",l=`[${n.status}]`,u=n.description.length>50?n.description.substring(0,47)+"...":n.description;if(t.push(` ${i}${r}${de.reset} ${de.bold}${n.id}${de.reset} ${u.padEnd(40)} ${i}${l}${de.reset}${c}`),n.result&&n.status==="done"){let d=n.result.length>60?n.result.substring(0,57)+"...":n.result;t.push(` ${de.dim}\u2192 ${d}${de.reset}`)}}let e=Se.filter(n=>n.status==="done").length,s=Se.filter(n=>n.status==="failed").length,o=Se.length;return t.push(` ${de.dim}${"\u2500".repeat(40)}${de.reset}`),t.push(` ${de.dim}${e}/${o} done${s>0?`, ${s} failed`:""}${de.reset}`),t.join(`
147
+ `)}function Sh(){return Se.length>0&&Se.some(t=>t.status==="pending"||t.status==="in_progress")}Xc.exports={createTasks:wh,updateTask:bh,getTaskList:_h,clearTasks:kh,getReadyTasks:xh,renderTaskList:vh,setOnChange:yh,hasActiveTasks:Sh}});var dl=j((G0,ul)=>{var{callStream:Eh,getActiveProviderName:zs,getActiveModelId:Th,getConfiguredProviders:Rh,getProvider:Jc,getActiveProvider:Vc,parseModelSpec:Qc}=we(),{parseToolArgs:Ch}=Ss(),{filterToolsForModel:Ah,getModelTier:Ks}=Bs(),{trackUsage:Oh}=ln(),{MultiProgress:Nh,C:H0}=ye(),tl=15,Ph=5,Zc=3,nl=8,Mh=2,Ys=new Map;function Ih(t,e){let s=Ys.get(t);return s&&s!==e?!1:(Ys.set(t,e),!0)}function Kn(t){Ys.delete(t)}function xr(){Ys.clear()}function sl(t){let e=t.message||"",s=t.code||"";return!!(e.includes("429")||e.includes("500")||e.includes("502")||e.includes("503")||e.includes("504")||s==="ECONNRESET"||s==="ECONNABORTED"||s==="ETIMEDOUT"||s==="ECONNREFUSED"||e.includes("socket disconnected")||e.includes("TLS")||e.includes("ECONNRESET")||e.includes("fetch failed")||e.includes("ETIMEDOUT")||e.includes("ENOTFOUND"))}async function ol(t,e,s){let o;for(let n=0;n<=Zc;n++)try{return await Eh(t,e,s)}catch(r){if(o=r,n<Zc&&sl(r)){let c=(r.message||"").includes("429")?Math.min(2e3*Math.pow(2,n),15e3):Math.min(500*Math.pow(2,n),4e3);await new Promise(l=>setTimeout(l,c).unref());continue}throw r}throw o}var el=new Set(["ask_user","task_list"]);function rl(t){return t>=2?new Set([...el,"spawn_agents"]):el}var Lh=new Set(["write_file","edit_file","patch_file"]),jh=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,Dh=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function il(t){return Dh.test(t)?"full":jh.test(t)?"essential":"standard"}function al(t){let e=Rh(),s=zs(),o=[...e].sort((n,r)=>(n.name===s?-1:1)-(r.name===s?-1:1));for(let n of o)for(let r of n.models)if(Ks(r.id,n.name)===t)return{provider:n.name,model:r.id};return null}var qh={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function vr(t){if(t.model){let{provider:n,model:r}=Qc(t.model),i=n?Jc(n):Vc(),c=n||zs();if(i&&i.isConfigured()&&(i.getModel(r)||c==="local")){let l=Ks(r,c);return{provider:c,model:r,tier:l}}}let e=il(t.task),s=qh[e];if(s){let{provider:n,model:r}=Qc(s),i=n?Jc(n):Vc(),c=n||zs();if(i&&i.isConfigured()&&(i.getModel(r)||c==="local")){let l=Ks(r,c);return{provider:c,model:r,tier:l}}}let o=al(e);if(o){let n=Ks(o.model,o.provider);return{provider:o.provider,model:o.model,tier:n}}return{provider:null,model:null,tier:null}}async function cl(t,e={},s=0){let o=s===0?tl:nl,n=Math.min(t.max_iterations||10,o),r=`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,i=[],c={input:0,output:0},l=new Set,d=[{role:"system",content:`You are a focused sub-agent. Complete this specific task efficiently.
141
148
 
142
149
  TASK: ${t.task}
143
150
  ${t.context?`
@@ -159,155 +166,259 @@ TOOL STRATEGY:
159
166
  ERROR RECOVERY:
160
167
  - If edit_file fails with "old_text not found": read the file again, compare, and retry with exact text.
161
168
  - If bash fails: read the error, fix the root cause, then retry.
162
- - After 2 failed attempts at the same operation, summarize the issue and stop.`}];l.push({role:"user",content:t.task});let u=Mo(t),d=u.provider,p=u.model,f=u.tier,{TOOL_DEFINITIONS:h,executeTool:m}=Be(),g=Ep(h.filter($=>!Op.has($.function.name)),f);if(p&&!t._skipLog){let $=f?` (${f})`:"";process.stderr.write(` [sub-agent: ${d}:${p}${$}]
163
- `)}let y={};d&&(y.provider=d),p&&(y.model=p);try{for(let $=0;$<s;$++){let x=await Ga(l,g,y);if(!x||typeof x!="object")throw new Error("Empty or invalid response from provider");if(x.usage){let E=x.usage.prompt_tokens||0,F=x.usage.completion_tokens||0;r.input+=E,r.output+=F;let j=d||ps(),Z=p||kp();Tp(j,Z,E,F)}let S=x.content||"",k=x.tool_calls,v={role:"assistant",content:S||""};if(k&&k.length>0&&(v.tool_calls=k),l.push(v),!k||k.length===0){for(let E of i)wn(E);return{task:t.task,status:"done",result:S||"(no response)",toolsUsed:o,tokensUsed:r,modelSpec:d&&p?`${d}:${p}`:null}}let T=k.map(E=>{let F=E.function.name,j=Sp(E.function.arguments),Z=E.id||`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!j)return Promise.resolve({role:"tool",content:`ERROR: Malformed tool arguments for ${F}`,tool_call_id:Z});let G=null;if(Np.has(F)&&j.path){let te=require("path"),me=te.isAbsolute(j.path)?j.path:te.resolve(process.cwd(),j.path);if(i.has(me)||!Ap(me,n))return Promise.resolve({role:"tool",content:`ERROR: File '${j.path}' is locked by another operation. Try a different approach or skip this file.`,tool_call_id:Z});i.add(me),G=me}return o.push(F),m(F,j,{autoConfirm:!0,silent:!0}).then(te=>{G&&(wn(G),i.delete(G));let me=String(te??"");return{role:"tool",content:me.length>2e4?me.substring(0,2e4)+`
164
- ...(truncated)`:me,tool_call_id:Z}}).catch(te=>(G&&(wn(G),i.delete(G)),{role:"tool",content:`ERROR: ${te.message}`,tool_call_id:Z}))}),A=await Promise.all(T);l.push(...A),e.onUpdate&&e.onUpdate(`step ${$+1}/${s}`)}for(let $ of i)wn($);return{task:t.task,status:"truncated",abortReason:"iteration_limit",result:l[l.length-1]?.content||"(max iterations reached)",toolsUsed:o,tokensUsed:r,modelSpec:d&&p?`${d}:${p}`:null}}catch($){for(let x of i)wn(x);return{task:t.task,status:"failed",result:`Error: ${$.message}`,toolsUsed:o,tokensUsed:r,modelSpec:d&&p?`${d}:${p}`:null}}}async function Ip(t){let e=t.agents||[];if(e.length===0)return"ERROR: No agents specified";if(e.length>Wa)return`ERROR: Max ${Wa} parallel agents allowed, got ${e.length}`;let s=e.map(r=>Mo(r)),n=e.map((r,i)=>{let c=s[i],l=c.model?` [${c.model}]`:"",u=r.task.substring(0,44-l.length);return`Agent ${i+1}${l}: ${u}${r.task.length>u.length?"...":""}`}),o=new Rp(n);o.start();try{let r=e.map((d,p)=>{let f=s[p],h=f.model?{...d,model:`${f.provider}:${f.model}`,_skipLog:!0}:{...d,_skipLog:!0};return Ya(h,{onUpdate:()=>{}}).then(m=>(o.update(p,m.status==="failed"?"error":"done"),m)).catch(m=>(o.update(p,"error"),{task:d.task,status:"failed",result:`Error: ${m.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))}),i=await Promise.all(r);o.stop(),No();let c=["Sub-agent results:",""],l=0,u=0;for(let d=0;d<i.length;d++){let p=i[d],f=p.status==="done"?"\u2713":p.status==="truncated"?"\u26A0":"\u2717",h=p.modelSpec?` [${p.modelSpec}]`:"";c.push(`${f} Agent ${d+1}${h}: ${p.task}`),c.push(` Status: ${p.status}`),c.push(` Tools used: ${p.toolsUsed.length>0?p.toolsUsed.join(", "):"none"}`),c.push(` Result: ${p.result}`),c.push(""),l+=p.tokensUsed.input,u+=p.tokensUsed.output}return c.push(`Total sub-agent tokens: ${l} input + ${u} output`),c.join(`
165
- `)}catch(r){return o.stop(),No(),`ERROR: Sub-agent execution failed: ${r.message}`}}Ja.exports={runSubAgent:Ya,executeSpawnAgents:Ip,clearAllLocks:No,classifyTask:za,pickModelForTier:Ka,resolveSubAgentModel:Mo,isRetryableError:Ha,callWithRetry:Ga}});var _n=L((by,lc)=>{var oe=require("fs"),nt=require("path"),qp=new Set(["the","a","an","is","are","and","or","but","in","on","at","to","for","of","with","this","that","it","as","be","by","from","was","were","has","have","had","not","do","does","did","so","if","its","my","me","we","you","he","she","they","our","your","their","can","will","would","could","should","may","might","then","than","also","which","when","where","how","what","who","all","any","each","more","most","use","used","using","get","set","new","add","make","der","die","das","den","dem","des","ein","eine","einen","einem","eines","und","oder","aber","von","zu","mit","auf","bei","nach","aus","vor","ist","sind","war","hat","haben","wird","kann","soll","muss","nicht","auch","als","durch"]);function Gt(){let t=nt.join(process.cwd(),".nex","brain");return oe.existsSync(t)||oe.mkdirSync(t,{recursive:!0}),t}function Xa(){return nt.join(Gt(),".brain-index.json")}function Io(){return nt.join(Gt(),".embeddings.json")}function bn(){let t=nt.join(process.cwd(),".nex","brain");if(!oe.existsSync(t))return[];try{return oe.readdirSync(t).filter(e=>e.endsWith(".md")&&!e.startsWith(".")).map(e=>{let s=nt.join(t,e),n=oe.statSync(s);return{name:e.replace(/\.md$/,""),path:s,size:n.size,modified:new Date(n.mtimeMs)}}).sort((e,s)=>s.modified-e.modified)}catch{return[]}}function xn(t){let e={},s=t,n=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(n){let o=n[1].split(`
166
- `);for(let r of o){let i=r.match(/^(\w+):\s*(.+)$/);if(!i)continue;let c=i[1].trim(),l=i[2].trim();l.startsWith("[")&&l.endsWith("]")?e[c]=l.slice(1,-1).split(",").map(u=>u.trim()).filter(Boolean):e[c]=l}s=n[2]}return{frontmatter:e,body:s}}function Qa(t){let e=nt.join(Gt(),`${t}.md`);if(!oe.existsSync(e))return{name:t,content:"",body:"",frontmatter:{}};let s=oe.readFileSync(e,"utf-8"),{frontmatter:n,body:o}=xn(s);return{name:t,content:s,body:o,frontmatter:n}}function Dp(t,e){let s=nt.join(Gt(),`${t}.md`);oe.writeFileSync(s,e,"utf-8"),Up(t,e),jp()}function jp(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=Io();oe.existsSync(t)&&setImmediate(async()=>{try{await rc()}catch{}})}function Fp(t){let e=nt.join(Gt(),`${t}.md`);return oe.existsSync(e)?(oe.unlinkSync(e),Wp(t),!0):!1}function hs(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!qp.has(e))}function qo(t){let e={},{frontmatter:s,body:n}=xn(t),o=Array.isArray(s.tags)?s.tags:[];for(let i of o){let c=i.toLowerCase().replace(/[^a-z0-9-]/g,"");c.length>1&&(e[c]=(e[c]||0)+5)}let r=(n||t).split(`
167
- `);for(let i of r)if(i.startsWith("#")){let c=i.replace(/^#+\s*/,"");for(let l of hs(c))e[l]=(e[l]||0)+3}for(let i of hs(n||t))e[i]=(e[i]||0)+1;return e}function Do(){let t=Xa();if(!oe.existsSync(t))return{documents:{}};try{return JSON.parse(oe.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function jo(t){oe.writeFileSync(Xa(),JSON.stringify(t,null,2),"utf-8")}function Up(t,e){let s=Do(),{frontmatter:n}=xn(e),o=Array.isArray(n.tags)?n.tags:[];s.documents[t]={keywords:qo(e),tags:o,modified:new Date().toISOString()},jo(s)}function Wp(t){let e=Do();delete e.documents[t],jo(e)}function Lo(){let t=bn(),e={documents:{}};for(let s of t){let n=oe.readFileSync(s.path,"utf-8"),{frontmatter:o}=xn(n),r=Array.isArray(o.tags)?o.tags:[];e.documents[s.name]={keywords:qo(n),tags:r,modified:s.modified.toISOString()}}return jo(e),e}function Za(){let t=Do(),e=bn();for(let s of e){let n=t.documents[s.name];if(!n||new Date(n.modified)<s.modified)return Lo()}for(let s of Object.keys(t.documents))if(!e.some(n=>n.name===s))return Lo();return t}function ec(t,e={}){let{topK:s=3,minScore:n=.1}=e,o=hs(t);if(o.length===0)return[];let r=Za(),i=[];for(let[c,l]of Object.entries(r.documents)){let u=0;for(let d of o){l.keywords[d]&&(u+=l.keywords[d]);for(let[p,f]of Object.entries(l.keywords))p!==d&&p.length>3&&d.length>3&&(p.includes(d)||d.includes(p))&&(u+=f*.3)}u>=n&&i.push({name:c,score:u})}return i.sort((c,l)=>l.score-c.score),i.slice(0,s)}var tc=process.env.NEX_EMBED_MODEL||"nomic-embed-text",Po=400,Bp=50;async function nc(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return!1;try{let t=process.env.OLLAMA_HOST||"http://localhost:11434",e=require("http"),s=require("https"),n=new URL(`${t}/api/tags`),o=n.protocol==="https:"?s:e;return((await new Promise((c,l)=>{let u=o.get(n.toString(),{timeout:2e3},d=>{let p="";d.on("data",f=>p+=f),d.on("end",()=>{try{c(JSON.parse(p))}catch{l(new Error("bad json"))}})});u.on("error",l),u.on("timeout",()=>{u.destroy(),l(new Error("timeout"))})})).models||[]).map(c=>c.name).some(c=>c.startsWith(tc.split(":")[0]))}catch{return!1}}async function Fo(t){let e=process.env.OLLAMA_HOST||"http://localhost:11434",s=require("http"),n=require("https"),o=new URL(`${e}/api/embeddings`),r=o.protocol==="https:"?n:s,i=JSON.stringify({model:tc,prompt:t});return new Promise((c,l)=>{let u=r.request(o,{method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(i)},timeout:3e4},d=>{let p="";d.on("data",f=>p+=f),d.on("end",()=>{try{c(JSON.parse(p).embedding||[])}catch(f){l(f)}})});u.on("error",l),u.on("timeout",()=>{u.destroy(),l(new Error("embedding timeout"))}),u.write(i),u.end()})}function sc(t,e){if(!t||!e||t.length!==e.length)return 0;let s=0,n=0,o=0;for(let i=0;i<t.length;i++)s+=t[i]*e[i],n+=t[i]*t[i],o+=e[i]*e[i];let r=Math.sqrt(n)*Math.sqrt(o);return r===0?0:s/r}function oc(t){let e=t.split(/\s+/),s=[],n=0;for(;n<e.length;){let o=e.slice(n,n+Po).join(" ");if(s.push({text:o,offset:n}),n+Po>=e.length)break;n+=Po-Bp}return s}async function rc(){let t=bn(),e={documents:{}},s=Io();if(oe.existsSync(s))try{e=JSON.parse(oe.readFileSync(s,"utf-8"))}catch{}for(let n of t){let o=e.documents[n.name];if(o&&new Date(o.modified)>=n.modified)continue;let r=oe.readFileSync(n.path,"utf-8"),i=oc(r),c=[];for(let l of i){let u=await Fo(l.text);c.push({text:l.text,embedding:u,offset:l.offset})}e.documents[n.name]={chunks:c,modified:n.modified.toISOString()}}for(let n of Object.keys(e.documents))t.some(o=>o.name===n)||delete e.documents[n];return oe.writeFileSync(s,JSON.stringify(e),"utf-8"),e}async function ic(t,e={}){let{topK:s=3,minSimilarity:n=.3}=e,o=Io();if(!oe.existsSync(o))return[];let r;try{r=JSON.parse(oe.readFileSync(o,"utf-8"))}catch{return[]}let i=await Fo(t),c=[];for(let[l,u]of Object.entries(r.documents||{})){let d=0,p="";for(let f of u.chunks||[]){let h=sc(i,f.embedding);h>d&&(d=h,p=f.text)}d>=n&&c.push({name:l,score:d,bestChunk:p})}return c.sort((l,u)=>u.score-l.score),c.slice(0,s)}function ac(t,e,s={}){let{k:n=60,topK:o=3}=s,r={};return t.forEach((i,c)=>{r[i.name]=(r[i.name]||0)+1/(n+c+1)}),e.forEach((i,c)=>{r[i.name]=(r[i.name]||0)+1/(n+c+1)}),Object.entries(r).map(([i,c])=>({name:i,score:c})).sort((i,c)=>c.score-i.score).slice(0,o)}async function cc(t,e={}){let{topK:s=3,minScore:n=.1}=e,o=ec(t,{topK:s,minScore:n}),r=o;if(process.env.NEX_BRAIN_EMBEDDINGS!=="false")try{if(await nc()){let c=await ic(t,{topK:s});r=ac(o,c,{topK:s})}}catch{}return r.map(i=>{let c=Qa(i.name),l=(c.body||c.content||"").slice(0,300).replace(/\n+/g," ")+"...";return{name:i.name,score:i.score,content:c.content,excerpt:l}})}async function Hp(t){if(!t||!t.trim())return"";let e=nt.join(process.cwd(),".nex","brain");if(!oe.existsSync(e)||bn().length===0)return"";let n;try{n=await cc(t,{topK:3})}catch{return""}if(!n||n.length===0)return"";let o;try{o=De().estimateTokens}catch{o=l=>Math.ceil(l.length/4)}let r=25e3,i=[],c=0;for(let l of n){let u=l.content||"",d=o(u);if(c+d>r){let f=r-c;if(f<100)break;let h=f/d;u=u.slice(0,Math.floor(u.length*h))+`
168
- ...(truncated)`}let p=typeof l.score=="number"?l.score.toFixed(2):String(l.score);if(i.push(`--- ${l.name} (relevance: ${p}) ---
169
- ${u}`),c+=o(u),c>=r)break}return i.length===0?"":`KNOWLEDGE BASE (auto-selected):
169
+ - After 2 failed attempts at the same operation, summarize the issue and stop.`}];d.push({role:"user",content:t.task});let f=vr(t),m=f.provider,h=f.model,p=f.tier,{TOOL_DEFINITIONS:g,executeTool:$}=ot(),y=rl(s),w=Ah(g.filter(_=>!y.has(_.function.name)),p);if(h&&!t._skipLog){let _=p?` (${p})`:"";process.stderr.write(` [sub-agent: ${m}:${h}${_}]
170
+ `)}let T={};m&&(T.provider=m),h&&(T.model=h);try{for(let _=0;_<n;_++){let x=await ol(d,w,T);if(!x||typeof x!="object")throw new Error("Empty or invalid response from provider");if(x.usage){let K=x.usage.prompt_tokens||0,z=x.usage.completion_tokens||0;c.input+=K,c.output+=z;let Q=m||zs(),Z=h||Th();Oh(Q,Z,K,z)}let S=x.content||"",R=x.tool_calls,C={role:"assistant",content:S||""};if(R&&R.length>0&&(C.tool_calls=R),d.push(C),!R||R.length===0){for(let K of l)Kn(K);return{task:t.task,status:"done",result:S||"(no response)",toolsUsed:i,tokensUsed:c,modelSpec:m&&h?`${m}:${h}`:null}}let I=R.map(K=>{let z=K.function.name,Q=Ch(K.function.arguments),Z=K.id||`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!Q)return Promise.resolve({role:"tool",content:`ERROR: Malformed tool arguments for ${z}`,tool_call_id:Z});let Y=null;if(Lh.has(z)&&Q.path){let tt=require("path"),ce=tt.isAbsolute(Q.path)?Q.path:tt.resolve(process.cwd(),Q.path);if(l.has(ce)||!Ih(ce,r))return Promise.resolve({role:"tool",content:`ERROR: File '${Q.path}' is locked by another operation. Try a different approach or skip this file.`,tool_call_id:Z});l.add(ce),Y=ce}return i.push(z),(z==="spawn_agents"?ll(Q,s+1):$(z,Q,{autoConfirm:!0,silent:!0})).then(tt=>{Y&&(Kn(Y),l.delete(Y));let ce=String(tt??"");return{role:"tool",content:ce.length>2e4?ce.substring(0,2e4)+`
171
+ ...(truncated)`:ce,tool_call_id:Z}}).catch(tt=>(Y&&(Kn(Y),l.delete(Y)),{role:"tool",content:`ERROR: ${tt.message}`,tool_call_id:Z}))}),D=await Promise.all(I);d.push(...D),e.onUpdate&&e.onUpdate(`step ${_+1}/${n}`)}for(let _ of l)Kn(_);return{task:t.task,status:"truncated",abortReason:"iteration_limit",result:d[d.length-1]?.content||"(max iterations reached)",toolsUsed:i,tokensUsed:c,modelSpec:m&&h?`${m}:${h}`:null}}catch(_){for(let x of l)Kn(x);return{task:t.task,status:"failed",result:`Error: ${_.message}`,toolsUsed:i,tokensUsed:c,modelSpec:m&&h?`${m}:${h}`:null}}}async function ll(t,e=0){if(e>=2)return"ERROR: max agent nesting depth (2) reached \u2014 reviewer agents cannot spawn further agents.";let s=e===0?Ph:Mh,o=e===0?tl:nl,n=(t.agents||[]).slice(0,s);if(n.length===0)return"ERROR: No agents specified";let r=e>0?" \u21B3 ":"",i=e>0?38:44,c=n.map(d=>vr(d)),l=n.map((d,f)=>{let m=c[f],h=m.model?` [${m.model}]`:"",p=d.task.substring(0,i-h.length);return`${r}Agent ${f+1}${h}: ${p}${d.task.length>p.length?"...":""}`}),u=new Nh(l);u.start();try{let d=n.map((g,$)=>{let y=c[$],w=Math.min(g.max_iterations||o,o),T=y.model?{...g,model:`${y.provider}:${y.model}`,_skipLog:!0,max_iterations:w}:{...g,_skipLog:!0,max_iterations:w};return cl(T,{onUpdate:()=>{}},e).then(_=>(u.update($,_.status==="failed"?"error":"done"),_)).catch(_=>(u.update($,"error"),{task:g.task,status:"failed",result:`Error: ${_.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))}),f=await Promise.all(d);u.stop(),xr();let m=["Sub-agent results:",""],h=0,p=0;for(let g=0;g<f.length;g++){let $=f[g],y=$.status==="done"?"\u2713":$.status==="truncated"?"\u26A0":"\u2717",w=$.modelSpec?` [${$.modelSpec}]`:"";m.push(`${y} Agent ${g+1}${w}: ${$.task}`),m.push(` Status: ${$.status}`),m.push(` Tools used: ${$.toolsUsed.length>0?$.toolsUsed.join(", "):"none"}`),m.push(` Result: ${$.result}`),m.push(""),h+=$.tokensUsed.input,p+=$.tokensUsed.output}return m.push(`Total sub-agent tokens: ${h} input + ${p} output`),m.join(`
172
+ `)}catch(d){return u.stop(),xr(),`ERROR: Sub-agent execution failed: ${d.message}`}}ul.exports={runSubAgent:cl,executeSpawnAgents:ll,clearAllLocks:xr,classifyTask:il,pickModelForTier:al,resolveSubAgentModel:vr,isRetryableError:sl,callWithRetry:ol,getExcludedTools:rl}});var Xn=j((K0,Sl)=>{var $e=require("fs"),gt=require("path"),{atomicWrite:fl,withFileLockSync:pl}=vt(),Fh=new Set(["the","a","an","is","are","and","or","but","in","on","at","to","for","of","with","this","that","it","as","be","by","from","was","were","has","have","had","not","do","does","did","so","if","its","my","me","we","you","he","she","they","our","your","their","can","will","would","could","should","may","might","then","than","also","which","when","where","how","what","who","all","any","each","more","most","use","used","using","get","set","new","add","make","der","die","das","den","dem","des","ein","eine","einen","einem","eines","und","oder","aber","von","zu","mit","auf","bei","nach","aus","vor","ist","sind","war","hat","haben","wird","kann","soll","muss","nicht","auch","als","durch"]);function hn(){let t=gt.join(process.cwd(),".nex","brain");return $e.existsSync(t)||$e.mkdirSync(t,{recursive:!0}),t}function Js(){return gt.join(hn(),".brain-index.json")}function Tr(){return gt.join(hn(),".embeddings.json")}function zn(){let t=gt.join(process.cwd(),".nex","brain");if(!$e.existsSync(t))return[];try{return $e.readdirSync(t).filter(e=>e.endsWith(".md")&&!e.startsWith(".")).map(e=>{let s=gt.join(t,e),o=$e.statSync(s);return{name:e.replace(/\.md$/,""),path:s,size:o.size,modified:new Date(o.mtimeMs)}}).sort((e,s)=>s.modified-e.modified)}catch{return[]}}function Yn(t){let e={},s=t,o=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(o){let n=o[1].split(`
173
+ `);for(let r of n){let i=r.match(/^(\w+):\s*(.+)$/);if(!i)continue;let c=i[1].trim(),l=i[2].trim();l.startsWith("[")&&l.endsWith("]")?e[c]=l.slice(1,-1).split(",").map(u=>u.trim()).filter(Boolean):e[c]=l}s=o[2]}return{frontmatter:e,body:s}}function ml(t){let e=gt.join(hn(),`${t}.md`);if(!$e.existsSync(e))return{name:t,content:"",body:"",frontmatter:{}};let s=$e.readFileSync(e,"utf-8"),{frontmatter:o,body:n}=Yn(s);return{name:t,content:s,body:n,frontmatter:o}}function Uh(t,e){let s=gt.join(hn(),`${t}.md`);fl(s,e),Hh(t,e),Wh()}function Wh(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=Tr();$e.existsSync(t)&&setImmediate(async()=>{try{await _l()}catch{}})}function Bh(t){let e=gt.join(hn(),`${t}.md`);return $e.existsSync(e)?($e.unlinkSync(e),Gh(t),!0):!1}function Xs(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!Fh.has(e))}function Rr(t){let e={},{frontmatter:s,body:o}=Yn(t),n=Array.isArray(s.tags)?s.tags:[];for(let i of n){let c=i.toLowerCase().replace(/[^a-z0-9-]/g,"");c.length>1&&(e[c]=(e[c]||0)+5)}let r=(o||t).split(`
174
+ `);for(let i of r)if(i.startsWith("#")){let c=i.replace(/^#+\s*/,"");for(let l of Xs(c))e[l]=(e[l]||0)+3}for(let i of Xs(o||t))e[i]=(e[i]||0)+1;return e}function Cr(){let t=Js();if(!$e.existsSync(t))return{documents:{}};try{return JSON.parse($e.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function Ar(t){fl(Js(),JSON.stringify(t,null,2))}function Hh(t,e){pl(Js(),()=>{let s=Cr(),{frontmatter:o}=Yn(e),n=Array.isArray(o.tags)?o.tags:[];s.documents[t]={keywords:Rr(e),tags:n,modified:new Date().toISOString()},Ar(s)})}function Gh(t){pl(Js(),()=>{let e=Cr();delete e.documents[t],Ar(e)})}function Er(){let t=zn(),e={documents:{}};for(let s of t){let o=$e.readFileSync(s.path,"utf-8"),{frontmatter:n}=Yn(o),r=Array.isArray(n.tags)?n.tags:[];e.documents[s.name]={keywords:Rr(o),tags:r,modified:s.modified.toISOString()}}return Ar(e),e}function hl(){let t=Cr(),e=zn();for(let s of e){let o=t.documents[s.name];if(!o||new Date(o.modified)<s.modified)return Er()}for(let s of Object.keys(t.documents))if(!e.some(o=>o.name===s))return Er();return t}function gl(t,e={}){let{topK:s=3,minScore:o=.1}=e,n=Xs(t);if(n.length===0)return[];let r=hl(),i=[];for(let[c,l]of Object.entries(r.documents)){let u=0;for(let d of n){l.keywords[d]&&(u+=l.keywords[d]);for(let[f,m]of Object.entries(l.keywords))f!==d&&f.length>3&&d.length>3&&(f.includes(d)||d.includes(f))&&(u+=m*.3)}u>=o&&i.push({name:c,score:u})}return i.sort((c,l)=>l.score-c.score),i.slice(0,s)}var $l=process.env.NEX_EMBED_MODEL||"nomic-embed-text",Sr=400,Kh=50;async function yl(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return!1;try{let t=process.env.OLLAMA_HOST||"http://localhost:11434",e=require("http"),s=require("https"),o=new URL(`${t}/api/tags`),n=o.protocol==="https:"?s:e;return((await new Promise((c,l)=>{let u=n.get(o.toString(),{timeout:2e3},d=>{let f="";d.on("data",m=>f+=m),d.on("end",()=>{try{c(JSON.parse(f))}catch{l(new Error("bad json"))}})});u.on("error",l),u.on("timeout",()=>{u.destroy(),l(new Error("timeout"))})})).models||[]).map(c=>c.name).some(c=>c.startsWith($l.split(":")[0]))}catch{return!1}}async function Or(t){let e=process.env.OLLAMA_HOST||"http://localhost:11434",s=require("http"),o=require("https"),n=new URL(`${e}/api/embeddings`),r=n.protocol==="https:"?o:s,i=JSON.stringify({model:$l,prompt:t});return new Promise((c,l)=>{let u=r.request(n,{method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(i)},timeout:3e4},d=>{let f="";d.on("data",m=>f+=m),d.on("end",()=>{try{c(JSON.parse(f).embedding||[])}catch(m){l(m)}})});u.on("error",l),u.on("timeout",()=>{u.destroy(),l(new Error("embedding timeout"))}),u.write(i),u.end()})}function wl(t,e){if(!t||!e||t.length!==e.length)return 0;let s=0,o=0,n=0;for(let i=0;i<t.length;i++)s+=t[i]*e[i],o+=t[i]*t[i],n+=e[i]*e[i];let r=Math.sqrt(o)*Math.sqrt(n);return r===0?0:s/r}function bl(t){let e=t.split(/\s+/),s=[],o=0;for(;o<e.length;){let n=e.slice(o,o+Sr).join(" ");if(s.push({text:n,offset:o}),o+Sr>=e.length)break;o+=Sr-Kh}return s}async function _l(){let t=zn(),e={documents:{}},s=Tr();if($e.existsSync(s))try{e=JSON.parse($e.readFileSync(s,"utf-8"))}catch{}for(let o of t){let n=e.documents[o.name];if(n&&new Date(n.modified)>=o.modified)continue;let r=$e.readFileSync(o.path,"utf-8"),i=bl(r),c=[];for(let l of i){let u=await Or(l.text);c.push({text:l.text,embedding:u,offset:l.offset})}e.documents[o.name]={chunks:c,modified:o.modified.toISOString()}}for(let o of Object.keys(e.documents))t.some(n=>n.name===o)||delete e.documents[o];return $e.writeFileSync(s,JSON.stringify(e),"utf-8"),e}async function kl(t,e={}){let{topK:s=3,minSimilarity:o=.3}=e,n=Tr();if(!$e.existsSync(n))return[];let r;try{r=JSON.parse($e.readFileSync(n,"utf-8"))}catch{return[]}let i=await Or(t),c=[];for(let[l,u]of Object.entries(r.documents||{})){let d=0,f="";for(let m of u.chunks||[]){let h=wl(i,m.embedding);h>d&&(d=h,f=m.text)}d>=o&&c.push({name:l,score:d,bestChunk:f})}return c.sort((l,u)=>u.score-l.score),c.slice(0,s)}function xl(t,e,s={}){let{k:o=60,topK:n=3}=s,r={};return t.forEach((i,c)=>{r[i.name]=(r[i.name]||0)+1/(o+c+1)}),e.forEach((i,c)=>{r[i.name]=(r[i.name]||0)+1/(o+c+1)}),Object.entries(r).map(([i,c])=>({name:i,score:c})).sort((i,c)=>c.score-i.score).slice(0,n)}async function vl(t,e={}){let{topK:s=3,minScore:o=.1}=e,n=gl(t,{topK:s,minScore:o}),r=n;if(process.env.NEX_BRAIN_EMBEDDINGS!=="false")try{if(await yl()){let c=await kl(t,{topK:s});r=xl(n,c,{topK:s})}}catch{}return r.map(i=>{let c=ml(i.name),l=(c.body||c.content||"").slice(0,300).replace(/\n+/g," ")+"...";return{name:i.name,score:i.score,content:c.content,excerpt:l}})}async function zh(t){if(!t||!t.trim())return"";let e=gt.join(process.cwd(),".nex","brain");if(!$e.existsSync(e)||zn().length===0)return"";let o;try{o=await vl(t,{topK:3})}catch{return""}if(!o||o.length===0)return"";let n;try{n=Xe().estimateTokens}catch{n=l=>Math.ceil(l.length/4)}let r=25e3,i=[],c=0;for(let l of o){let u=l.content||"",d=n(u);if(c+d>r){let m=r-c;if(m<100)break;let h=m/d;u=u.slice(0,Math.floor(u.length*h))+`
175
+ ...(truncated)`}let f=typeof l.score=="number"?l.score.toFixed(2):String(l.score);if(i.push(`--- ${l.name} (relevance: ${f}) ---
176
+ ${u}`),c+=n(u),c>=r)break}return i.length===0?"":`KNOWLEDGE BASE (auto-selected):
170
177
 
171
178
  ${i.join(`
172
179
 
173
- `)}`}lc.exports={getBrainDir:Gt,listDocuments:bn,readDocument:Qa,writeDocument:Dp,removeDocument:Fp,buildIndex:Lo,getIndex:Za,query:cc,getBrainContext:Hp,isEmbeddingAvailable:nc,generateEmbedding:Fo,buildEmbeddingIndex:rc,semanticQuery:ic,cosineSimilarity:sc,_keywordQuery:ec,_extractKeywords:qo,_chunkText:oc,parseFrontmatter:xn,tokenize:hs,_fuseResults:ac}});var Be=L((vy,bc)=>{var re=require("fs").promises,uc=require("fs"),Ee=require("path"),ae=require("util").promisify(require("child_process").exec),dc=require("util").promisify(require("child_process").execFile),{spawnSync:Gp}=require("child_process"),Uo=require("axios"),{isForbidden:zp,isDangerous:Kp,isCritical:fc,confirm:Ge}=We(),{showClaudeDiff:gs,showClaudeNewFile:Yp,showEditDiff:xy,confirmFileChange:kn}=Vi(),{C:I,Spinner:$c,getToolSpinnerText:Jp}=de(),{isGitRepo:Wo,getCurrentBranch:pc,getStatus:Vp,getDiff:Xp}=St(),{recordChange:$s}=ft(),{fuzzyFindText:mc,findMostSimilar:Ho}=xa(),{runDiagnostics:vn}=ka(),{findFileInIndex:Qp,getFileIndex:_y}=ko(),{resolveProfile:ze,sshExec:pt,scpUpload:Zp,scpDownload:em}=Ht(),{resolveDeployConfig:tm,loadDeployConfigs:ky}=Ro(),nm=/^(vim?|nano|emacs|pico|less|more|top|htop|iftop|iotop|glances|telnet\s|screen|tmux|fzf|gum|dialog|whiptail|man\s|node\s*$|python3?\s*$|irb\s*$|rails\s*c|psql\s|mysql\s|redis-cli|mongosh?|sqlite3)\b/,sm=/^ssh\s/,om=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/;async function ys(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),s=Se(e);if(s&&await re.access(s).then(()=>!0).catch(()=>!1))return{fixedPath:s,message:`(auto-fixed path: ${t} \u2192 ${e})`};let n=[".js",".ts",".jsx",".tsx",".mjs",".cjs",".json"],o=Ee.extname(t);if(!o)for(let i of n){let c=Se(t+i);if(c&&await re.access(c).then(()=>!0).catch(()=>!1))return{fixedPath:c,message:`(auto-fixed: added ${i} extension)`}}if(o){let i=t.replace(/\.[^.]+$/,"");for(let c of n){if(c===o)continue;let l=Se(i+c);if(l&&await re.access(l).then(()=>!0).catch(()=>!1))return{fixedPath:l,message:`(auto-fixed: ${o} \u2192 ${c})`}}}let r=Ee.basename(t);if(r&&r.length>2)try{let i=Qp(r).map(c=>Se(c));if(i.length===1)return{fixedPath:i[0],message:`(auto-fixed: found ${r} at ${Ee.relative(process.cwd(),i[0])})`};if(i.length>1&&i.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
174
- ${i.map(l=>Ee.relative(process.cwd(),l)).map(l=>` - ${l}`).join(`
175
- `)}`}}catch{}return{fixedPath:null,message:""}}function rm(t){return/\bprintenv\b/.test(t)?"printenv exposes all secrets. Use `echo $VAR_NAME` for a single variable, or `env | grep PATTERN` for filtered output.":/cat\s+.*\.env\b/.test(t)?'Reading .env directly is blocked. Use `grep -v "KEY=" .env` to inspect non-secret entries, or ask the user to share specific values.':/cat\s+.*credentials/i.test(t)?"Credentials files are blocked. Reference the variable name from the application config instead.":/python3?\s+-c\s/.test(t)?"Inline python -c is blocked. Write a temporary script file and run it with `python3 script.py` instead.":/node\s+-e\s/.test(t)?"Inline node -e is blocked. Write a temporary script file and run it with `node script.js` instead.":/curl.*-X\s*POST|curl.*--data/.test(t)?"curl POST is blocked to prevent data exfiltration. Use the application's own API client or ask the user to run the request.":/base64.*\|.*bash/.test(t)?"Piping base64-decoded content to bash is blocked. Decode the content first, inspect it, then run explicitly.":/\beval\s*\(/.test(t)?"eval is blocked. Execute the command directly without eval.":/(?:^|[;&|]\s*)history(?:\s|$)/.test(t)?"Shell history is blocked. Look at git log or project files for context instead.":""}function yc(t,e){let s=[];if(/command not found|not recognized/i.test(t)){let n=e.match(/^(\S+)/),o=n?n[1]:"";/^(npx|npm|node|yarn|pnpm|bun)$/.test(o)?s.push("HINT: Node.js/npm may not be in PATH. Check your Node.js installation."):/^(python|python3|pip|pip3)$/.test(o)?s.push("HINT: Python may not be installed. Try: brew install python3 (macOS) or apt install python3 (Linux)"):s.push(`HINT: "${o}" is not installed. Try installing it with your package manager.`)}if(/Cannot find module|MODULE_NOT_FOUND/i.test(t)){let n=t.match(/Cannot find module '([^']+)'/),o=n?n[1]:"";o&&!o.startsWith(".")&&!o.startsWith("/")?s.push(`HINT: Missing npm package "${o}". Run: npm install ${o}`):s.push("HINT: Module not found. Check the import path or run npm install.")}if(/permission denied|EACCES/i.test(t)&&s.push("HINT: Permission denied. Check file permissions or try a different approach."),/EADDRINUSE|address already in use/i.test(t)){let n=t.match(/port (\d+)|:(\d+)/),o=n?n[1]||n[2]:"";s.push(`HINT: Port ${o||""} is already in use. Kill the process or use a different port.`)}if(/SyntaxError|Unexpected token/i.test(t)&&s.push("HINT: Syntax error in the code. Check the file at the line number shown above."),/TS\d{4}:/i.test(t)&&s.push("HINT: TypeScript compilation error. Fix the type issue at the indicated line."),/Test Suites:.*failed|Tests:.*failed/i.test(t)&&s.push("HINT: Test failures detected. Read the error output above to identify failing tests."),/fatal: not a git repository/i.test(t)&&s.push("HINT: Not inside a git repository. Run git init or cd to a git project."),/^curl\b/.test(e)){let n=t.match(/curl:\s*\((\d+)\)/),o=n?parseInt(n[1],10):null;o===6||/Could not resolve host/i.test(t)?s.push("HINT: Hostname could not be resolved. Check DNS or use an IP address directly."):o===7||/Failed to connect|Connection refused/i.test(t)?s.push("HINT: Service not running or port wrong. Check if the service is up and the port is correct."):o===22||/HTTP error/i.test(t)?s.push("HINT: HTTP 4xx/5xx response. The endpoint exists but returned an error status."):o===28||/timed out/i.test(t)?s.push("HINT: Request timed out. The host may be unreachable or the service is slow."):(o===35||/SSL.*error/i.test(t))&&s.push("HINT: SSL/TLS handshake failed. Try with --insecure to bypass, or check the certificate.")}if(/remote port forwarding failed/i.test(t)){let n=t.match(/port (\d+)/),o=n?n[1]:"";s.push(`HINT: SSH remote port forwarding failed for port ${o}. The port may already be bound on the server. Check with: ssh server "ss -tuln | grep ${o}" and kill any lingering process with that port.`)}return/bind.*Cannot assign requested address|Address already in use/i.test(t)&&s.push("HINT: Port is already in use. Find the process with: ss -tuln | grep <port> and kill it, then retry."),/Connection.*timed out|ssh.*timeout/i.test(t)&&/^ssh\b/.test(e)&&s.push("HINT: SSH connection timed out. Check if the host is reachable: ping <host> and verify the port with: nc -zv <host> 22"),/cp.*\$f.*\$f\.bak.*sed.*-i\.bak|sed.*-i\.bak.*cp.*\$f.*\$f\.bak/i.test(e)&&s.push('HINT: Using both cp with .bak and sed -i.bak creates double backups (.bak.bak). Choose one method: either cp "$f" "$f.bak" OR sed -i.bak, not both.'),s.length===0?t:t+`
180
+ `)}`}Sl.exports={getBrainDir:hn,listDocuments:zn,readDocument:ml,writeDocument:Uh,removeDocument:Bh,buildIndex:Er,getIndex:hl,query:vl,getBrainContext:zh,isEmbeddingAvailable:yl,generateEmbedding:Or,buildEmbeddingIndex:_l,semanticQuery:kl,cosineSimilarity:wl,_keywordQuery:gl,_extractKeywords:Rr,_chunkText:bl,parseFrontmatter:Yn,tokenize:Xs,_fuseResults:xl}});var Mr=j((z0,Al)=>{var Jn=require("fs"),Nr=require("path"),Pr=process.env.NEX_AUDIT!=="false",Bt=null;function El(){return Bt||(Bt=Nr.join(process.cwd(),".nex","audit"),Jn.existsSync(Bt)||Jn.mkdirSync(Bt,{recursive:!0}),Bt)}function Tl(){let t=new Date().toISOString().split("T")[0];return Nr.join(El(),`${t}.jsonl`)}function Yh(t){if(Pr)try{let e={timestamp:new Date().toISOString(),tool:t.tool,args:Rl(t.args),resultLength:typeof t.result=="string"?t.result.length:0,resultPreview:typeof t.result=="string"?t.result.substring(0,200):"",duration:t.duration||0,success:t.success!==!1,model:t.model||null,provider:t.provider||null},s=JSON.stringify(e)+`
181
+ `;Jn.appendFileSync(Tl(),s,"utf-8")}catch{}}function Rl(t){if(!t||typeof t!="object")return{};let e={};for(let[s,o]of Object.entries(t))/key|token|password|secret|credential/i.test(s)?e[s]="***":typeof o=="string"&&o.length>500?e[s]=o.substring(0,500)+`... (${o.length} chars)`:e[s]=o;return e}function Cl(t={}){let e=El(),s=t.days||1,o=[];for(let n=0;n<s;n++){let r=t.date||new Date(Date.now()-n*864e5).toISOString().split("T")[0],i=Nr.join(e,`${r}.jsonl`);if(!Jn.existsSync(i))continue;let c=Jn.readFileSync(i,"utf-8").split(`
182
+ `).filter(l=>l.trim());for(let l of c)try{let u=JSON.parse(l);if(t.tool&&u.tool!==t.tool)continue;o.push(u)}catch{}if(t.date)break}return o}function Xh(t=1){let e=Cl({days:t});if(e.length===0)return{totalCalls:0,byTool:{},avgDuration:0,successRate:1};let s={},o=0,n=0;for(let r of e)s[r.tool]=(s[r.tool]||0)+1,o+=r.duration||0,r.success&&n++;return{totalCalls:e.length,byTool:s,avgDuration:Math.round(o/e.length),successRate:n/e.length}}function Jh(t){Pr=t}function Vh(){return Pr}function Qh(){Bt=null}Al.exports={logToolExecution:Yh,sanitizeArgs:Rl,readAuditLog:Cl,getAuditSummary:Xh,setAuditEnabled:Jh,isAuditEnabled:Vh,getAuditLogPath:Tl,_reset:Qh}});var ot=j((J0,Ul)=>{var V=require("fs").promises,Ol=require("fs"),ae=require("path"),ie=require("util").promisify(require("child_process").exec),Nl=require("util").promisify(require("child_process").execFile),{spawnSync:Zh}=require("child_process"),Ir=require("axios"),{isForbidden:eg,isDangerous:tg,isCritical:Pl,confirm:Ve}=Ae(),{showClaudeDiff:Vs,showClaudeNewFile:ng,showEditDiff:Y0,confirmFileChange:Vn}=Ja(),{C:F,Spinner:sg,getToolSpinnerText:og}=ye(),{isGitRepo:Lr,getCurrentBranch:Ml,getStatus:rg,getDiff:ig}=Ft(),{recordChange:Qs}=pt(),{fuzzyFindText:Il,findMostSimilar:es}=Rc(),{runDiagnostics:Qn}=Ac(),{findFileInIndex:ag,getFileIndex:X0}=gr(),{resolveProfile:Ke,sshExec:Me,scpUpload:cg,scpDownload:lg}=mn(),{resolveDeployConfig:ug,loadDeployConfigs:dg}=br(),{getEditMode:Ll}=Bs(),fg=/^(vim?|nano|emacs|pico|less|more|top|htop|iftop|iotop|glances|telnet\s|screen|tmux|fzf|gum|dialog|whiptail|man\s|node\s*$|python3?\s*$|irb\s*$|rails\s*c|psql\s|mysql\s|redis-cli|mongosh?|sqlite3)\b/,pg=/^ssh\s/,mg=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/;async function Zs(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),s=Ie(e);if(s&&await V.access(s).then(()=>!0).catch(()=>!1))return{fixedPath:s,message:`(auto-fixed path: ${t} \u2192 ${e})`};let o=[".js",".ts",".jsx",".tsx",".mjs",".cjs",".json"],n=ae.extname(t);if(!n)for(let i of o){let c=Ie(t+i);if(c&&await V.access(c).then(()=>!0).catch(()=>!1))return{fixedPath:c,message:`(auto-fixed: added ${i} extension)`}}if(n){let i=t.replace(/\.[^.]+$/,"");for(let c of o){if(c===n)continue;let l=Ie(i+c);if(l&&await V.access(l).then(()=>!0).catch(()=>!1))return{fixedPath:l,message:`(auto-fixed: ${n} \u2192 ${c})`}}}let r=ae.basename(t);if(r&&r.length>2)try{let i=ag(r).map(c=>Ie(c));if(i.length===1)return{fixedPath:i[0],message:`(auto-fixed: found ${r} at ${ae.relative(process.cwd(),i[0])})`};if(i.length>1&&i.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
183
+ ${i.map(l=>ae.relative(process.cwd(),l)).map(l=>` - ${l}`).join(`
184
+ `)}`}}catch{}return{fixedPath:null,message:""}}function hg(t){return/\bprintenv\b/.test(t)?"printenv exposes all secrets. Use `echo $VAR_NAME` for a single variable, or `env | grep PATTERN` for filtered output.":/cat\s+.*\.env\b/.test(t)?'Reading .env directly is blocked. Use `grep -v "KEY=" .env` to inspect non-secret entries, or ask the user to share specific values.':/cat\s+.*credentials/i.test(t)?"Credentials files are blocked. Reference the variable name from the application config instead.":/python3?\s+-c\s/.test(t)?"Inline python -c is blocked. Write a temporary script file and run it with `python3 script.py` instead.":/node\s+-e\s/.test(t)?"Inline node -e is blocked. Write a temporary script file and run it with `node script.js` instead.":/curl.*-X\s*POST|curl.*--data/.test(t)?"curl POST is blocked to prevent data exfiltration. Use the application's own API client or ask the user to run the request.":/base64.*\|.*bash/.test(t)?"Piping base64-decoded content to bash is blocked. Decode the content first, inspect it, then run explicitly.":/\beval\s*\(/.test(t)?"eval is blocked. Execute the command directly without eval.":/(?:^|[;&|]\s*)history(?:\s|$)/.test(t)?"Shell history is blocked. Look at git log or project files for context instead.":""}function ql(t,e){let s=[];if(/command not found|not recognized/i.test(t)){let o=e.match(/^(\S+)/),n=o?o[1]:"";/^(npx|npm|node|yarn|pnpm|bun)$/.test(n)?s.push("HINT: Node.js/npm may not be in PATH. Check your Node.js installation."):/^(python|python3|pip|pip3)$/.test(n)?s.push("HINT: Python may not be installed. Try: brew install python3 (macOS) or apt install python3 (Linux)"):s.push(`HINT: "${n}" is not installed. Try installing it with your package manager.`)}if(/Cannot find module|MODULE_NOT_FOUND/i.test(t)){let o=t.match(/Cannot find module '([^']+)'/),n=o?o[1]:"";n&&!n.startsWith(".")&&!n.startsWith("/")?s.push(`HINT: Missing npm package "${n}". Run: npm install ${n}`):s.push("HINT: Module not found. Check the import path or run npm install.")}if(/permission denied|EACCES/i.test(t)&&s.push("HINT: Permission denied. Check file permissions or try a different approach."),/EADDRINUSE|address already in use/i.test(t)){let o=t.match(/port (\d+)|:(\d+)/),n=o?o[1]||o[2]:"";s.push(`HINT: Port ${n||""} is already in use. Kill the process or use a different port.`)}if(/SyntaxError|Unexpected token/i.test(t)&&s.push("HINT: Syntax error in the code. Check the file at the line number shown above."),/TS\d{4}:/i.test(t)&&s.push("HINT: TypeScript compilation error. Fix the type issue at the indicated line."),/Test Suites:.*failed|Tests:.*failed/i.test(t)&&s.push("HINT: Test failures detected. Read the error output above to identify failing tests."),/fatal: not a git repository/i.test(t)&&s.push("HINT: Not inside a git repository. Run git init or cd to a git project."),/^curl\b/.test(e)){let o=t.match(/curl:\s*\((\d+)\)/),n=o?parseInt(o[1],10):null;n===6||/Could not resolve host/i.test(t)?s.push("HINT: Hostname could not be resolved. Check DNS or use an IP address directly."):n===7||/Failed to connect|Connection refused/i.test(t)?s.push("HINT: Service not running or port wrong. Check if the service is up and the port is correct."):n===22||/HTTP error/i.test(t)?s.push("HINT: HTTP 4xx/5xx response. The endpoint exists but returned an error status."):n===28||/timed out/i.test(t)?s.push("HINT: Request timed out. The host may be unreachable or the service is slow."):(n===35||/SSL.*error/i.test(t))&&s.push("HINT: SSL/TLS handshake failed. Try with --insecure to bypass, or check the certificate.")}if(/remote port forwarding failed/i.test(t)){let o=t.match(/port (\d+)/),n=o?o[1]:"";s.push(`HINT: SSH remote port forwarding failed for port ${n}. The port may already be bound on the server. Check with: ssh server "ss -tuln | grep ${n}" and kill any lingering process with that port.`)}return/bind.*Cannot assign requested address|Address already in use/i.test(t)&&s.push("HINT: Port is already in use. Find the process with: ss -tuln | grep <port> and kill it, then retry."),/Connection.*timed out|ssh.*timeout/i.test(t)&&/^ssh\b/.test(e)&&s.push("HINT: SSH connection timed out. Check if the host is reachable: ping <host> and verify the port with: nc -zv <host> 22"),/cp.*\$f.*\$f\.bak.*sed.*-i\.bak|sed.*-i\.bak.*cp.*\$f.*\$f\.bak/i.test(e)&&s.push('HINT: Using both cp with .bak and sed -i.bak creates double backups (.bak.bak). Choose one method: either cp "$f" "$f.bak" OR sed -i.bak, not both.'),s.length===0?t:t+`
176
185
 
177
186
  `+s.join(`
178
- `)}function wc(t,e,s){let n=Ho(t,e);if(!n)return null;let o=Math.max(2,Math.ceil(e.length*.03));return n.distance>o?null:{autoFixed:!0,matchText:n.text,content:t.split(n.text).join(s),distance:n.distance,line:n.line}}var hc=!1,Tt=null;function im(){Tt&&(Tt(),Tt=null)}var Go=null;function am(t){Go=t}async function Bo(){if(!hc){hc=!0;try{let{stdout:t}=await ae("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await ae('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await ae("git stash pop",{cwd:process.cwd(),timeout:1e4}),await ae("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var cm=[/\.ssh\//i,/\.gnupg\//i,/\.aws\//i,/\.config\/gcloud/i,/\/etc\/shadow/,/\/etc\/passwd/,/\/etc\/sudoers/,/\.env(?:\.|$)/,/credentials/i,/\.npmrc$/,/\.docker\/config\.json/,/\.kube\/config/];function Se(t){let e=Ee.isAbsolute(t)?Ee.resolve(t):Ee.resolve(process.cwd(),t);for(let s of cm)if(s.test(e))return null;return e}var lm=[{type:"function",function:{name:"bash",description:"Execute a bash command in the project directory. Timeout: 90s. Use for: running tests, installing packages, git commands, build tools, starting servers. Do NOT use bash for file operations when a dedicated tool exists \u2014 use read_file instead of cat, edit_file instead of sed, glob instead of find, grep instead of grep/rg. Always quote paths with spaces. Prefer specific commands over rm -rf. Destructive or dangerous commands require user confirmation.",parameters:{type:"object",properties:{command:{type:"string",description:"The bash command to execute"}},required:["command"]}}},{type:"function",function:{name:"read_file",description:"Read a file's contents with line numbers. Always read a file BEFORE editing it to see exact content. Use line_start/line_end for large files to read specific sections. Prefer this over bash cat/head/tail. Files are read with UTF-8 encoding. For binary files, use bash with appropriate flags. Alternative: use util.promisify(fs.readFile) for programmatic access.",parameters:{type:"object",properties:{path:{type:"string",description:"File path (relative or absolute)"},line_start:{type:"number",description:"Start line (1-based, optional)"},line_end:{type:"number",description:"End line (1-based, optional)"}},required:["path"]}}},{type:"function",function:{name:"write_file",description:"Create a new file or completely overwrite an existing file. For targeted changes to existing files, prefer edit_file or patch_file instead \u2014 they only send the diff and are safer. Only use write_file when creating new files or when the entire content needs to be replaced.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},content:{type:"string",description:"Full file content"}},required:["path","content"]}}},{type:"function",function:{name:"edit_file",description:"Replace specific text in a file. IMPORTANT: old_text must match the file content EXACTLY \u2014 including all whitespace, indentation (tabs vs spaces), and newlines. Always read_file first to see the exact content before editing. If old_text is not found, the edit fails. For multiple changes to the same file, prefer patch_file instead.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},old_text:{type:"string",description:"Exact text to find (must match file content precisely)"},new_text:{type:"string",description:"Replacement text"}},required:["path","old_text","new_text"]}}},{type:"function",function:{name:"list_directory",description:"List files and directories in a tree view. Use this to understand project structure. For finding specific files by pattern, prefer glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory path"},max_depth:{type:"number",description:"Max depth (default: 2)"},pattern:{type:"string",description:"File filter glob (e.g. '*.js')"}},required:["path"]}}},{type:"function",function:{name:"search_files",description:"Search for a text pattern across files (regex). Returns matching lines with file paths. For simple content search, grep is equivalent. For finding files by name, use glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory to search"},pattern:{type:"string",description:"Search pattern (regex)"},file_pattern:{type:"string",description:"File filter (e.g. '*.js')"}},required:["path","pattern"]}}},{type:"function",function:{name:"glob",description:"Find files matching a glob pattern. Fast file search by name/extension. Use this to find files before reading them. Examples: '**/*.test.js' (all test files), 'src/**/*.ts' (all TypeScript in src). Prefer this over bash find/ls.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Glob pattern (e.g. '**/*.ts', 'src/**/*.test.js')"},path:{type:"string",description:"Base directory (default: project root)"}},required:["pattern"]}}},{type:"function",function:{name:"grep",description:"Search file contents with regex. Returns matching lines with file paths and line numbers. Use this to find where functions/variables/classes are defined or used. Prefer this over bash grep/rg.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Regex pattern to search for"},path:{type:"string",description:"Directory or file to search (default: project root)"},include:{type:"string",description:"File filter (e.g. '*.js', '*.ts')"},ignore_case:{type:"boolean",description:"Case-insensitive search"}},required:["pattern"]}}},{type:"function",function:{name:"patch_file",description:"Apply multiple text replacements to a file atomically. All patches are validated before any are applied \u2014 if one fails, none are written. Prefer this over multiple edit_file calls when making several changes to the same file. Like edit_file, all old_text values must match exactly.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},patches:{type:"array",description:"Array of { old_text, new_text } replacements to apply in order",items:{type:"object",properties:{old_text:{type:"string",description:"Text to find"},new_text:{type:"string",description:"Replacement text"}},required:["old_text","new_text"]}}},required:["path","patches"]}}},{type:"function",function:{name:"web_fetch",description:"Fetch content from a URL and return text. HTML tags are stripped. Use for reading documentation, API responses, or web pages. Will not work with authenticated/private URLs.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to fetch"},max_length:{type:"number",description:"Max response length in chars (default: 10000)"}},required:["url"]}}},{type:"function",function:{name:"web_search",description:"Search the web. Uses Perplexity (grounded, AI-summarized) if PERPLEXITY_API_KEY is set, otherwise DuckDuckGo. Returns titles, URLs, and summaries. Use to find documentation, solutions, or current information beyond your knowledge cutoff.",parameters:{type:"object",properties:{query:{type:"string",description:"Search query"},max_results:{type:"number",description:"Max results (default: 5)"}},required:["query"]}}},{type:"function",function:{name:"browser_open",description:"Open a URL in a headless browser and return the page title, text content, and links. More reliable than web_fetch for JavaScript-heavy pages. Requires playwright (npm install playwright && npx playwright install chromium).",parameters:{type:"object",properties:{url:{type:"string",description:"URL to open"},wait_for:{type:"string",enum:["domcontentloaded","networkidle","load"],description:"When to consider page loaded (default: domcontentloaded)"}},required:["url"]}}},{type:"function",function:{name:"browser_screenshot",description:"Take a screenshot of a URL in a headless browser. Returns the screenshot file path. The path can be pasted into the next message for visual analysis. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot"},full_page:{type:"boolean",description:"Capture full page (default: false \u2014 viewport only)"},width:{type:"number",description:"Viewport width in px (default: 1280)"},height:{type:"number",description:"Viewport height in px (default: 800)"}},required:["url"]}}},{type:"function",function:{name:"browser_click",description:"Click an element on a web page (by CSS selector or visible text). Returns the new URL after navigation. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of element to click (mutually exclusive with text)"},text:{type:"string",description:"Visible text of element to click (mutually exclusive with selector)"}},required:["url"]}}},{type:"function",function:{name:"browser_fill",description:"Fill a form field on a web page and optionally submit. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of the input field"},value:{type:"string",description:"Value to fill in"},submit:{type:"boolean",description:"Press Enter to submit after filling (default: false)"}},required:["url","selector","value"]}}},{type:"function",function:{name:"ask_user",description:"Ask the user a clarifying question with 2-3 specific options. Use when the user's intent is ambiguous. Always provide concrete, actionable options. The user can select an option or type a custom answer.",parameters:{type:"object",properties:{question:{type:"string",description:"The clarifying question to ask"},options:{type:"array",items:{type:"string"},description:"2-3 specific, actionable answer options for the user to choose from",minItems:1,maxItems:3}},required:["question","options"]}}},{type:"function",function:{name:"git_status",description:"Get git status: current branch, changed files, staged/unstaged state. Use before git operations to understand the current state.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"git_diff",description:"Get git diff for changed files. Shows additions and deletions.",parameters:{type:"object",properties:{staged:{type:"boolean",description:"Show only staged changes (default: false)"},file:{type:"string",description:"Diff specific file only (optional)"}},required:[]}}},{type:"function",function:{name:"git_log",description:"Show recent git commits (short format).",parameters:{type:"object",properties:{count:{type:"number",description:"Number of commits to show (default: 10)"},file:{type:"string",description:"Show commits for specific file (optional)"}},required:[]}}},{type:"function",function:{name:"task_list",description:"Create and manage a task list for complex multi-step tasks. Use for tasks with 3+ steps to track progress. Actions: create (new list with tasks), update (mark task in_progress/done/failed), get (view current list). Always update task status as you work.",parameters:{type:"object",properties:{action:{type:"string",enum:["create","update","get"],description:"Action to perform"},name:{type:"string",description:"Task list name (for create)"},tasks:{type:"array",description:"Array of tasks to create (for create)",items:{type:"object",properties:{description:{type:"string",description:"Task description"},depends_on:{type:"array",items:{type:"string"},description:"IDs of prerequisite tasks"}},required:["description"]}},task_id:{type:"string",description:"Task ID to update (for update)"},status:{type:"string",enum:["in_progress","done","failed"],description:"New status (for update)"},result:{type:"string",description:"Result summary (for update, optional)"}},required:["action"]}}},{type:"function",function:{name:"gh_run_list",description:"List recent GitHub Actions workflow runs for this repository. Shows run status, conclusion, branch, and timing. Use to check CI/CD status or find a run ID.",parameters:{type:"object",properties:{limit:{type:"number",description:"Number of runs to show (default: 10, max: 30)"},workflow:{type:"string",description:"Filter by workflow name or filename (optional)"},branch:{type:"string",description:"Filter by branch name (optional)"},status:{type:"string",enum:["completed","in_progress","queued","failure","success"],description:"Filter by status (optional)"}},required:[]}}},{type:"function",function:{name:"gh_run_view",description:"View details of a specific GitHub Actions workflow run: steps, logs, errors. Use gh_run_list first to get the run ID.",parameters:{type:"object",properties:{run_id:{type:"string",description:"The run ID (from gh_run_list)"},log:{type:"boolean",description:"Include full log output (default: false \u2014 shows step summary only)"}},required:["run_id"]}}},{type:"function",function:{name:"gh_workflow_trigger",description:"Trigger a GitHub Actions workflow dispatch event. Only works for workflows with workflow_dispatch trigger. Requires user confirmation.",parameters:{type:"object",properties:{workflow:{type:"string",description:"Workflow filename (e.g. ci.yml) or name"},branch:{type:"string",description:"Branch to run on (default: current branch)"},inputs:{type:"object",description:"Workflow input parameters as key-value pairs (optional)"}},required:["workflow"]}}},{type:"function",function:{name:"spawn_agents",description:"Run multiple independent sub-agents in parallel (max 5). Each agent has its own conversation context. Use when 2+ tasks can run simultaneously \u2014 e.g. reading multiple files, analyzing separate modules, independent research. Do NOT use for tasks that depend on each other or modify the same file. Keep task descriptions specific and self-contained.",parameters:{type:"object",properties:{agents:{type:"array",description:"Array of agent definitions to run in parallel (max 5)",items:{type:"object",properties:{task:{type:"string",description:"Task description for the agent"},context:{type:"string",description:"Additional context (optional)"},max_iterations:{type:"number",description:"Max iterations (default: 10, max: 15)"},model:{type:"string",description:'Override model for this agent (provider:model, e.g. "anthropic:claude-haiku"). Auto-selected if omitted.'}},required:["task"]}}},required:["agents"]}}},{type:"function",function:{name:"switch_model",description:"Switch the active AI model mid-conversation. Use when a different model is better for the next steps \u2014 e.g. switch to a fast model for simple lookups, or a more capable model for complex refactoring. The switch persists for all subsequent turns.",parameters:{type:"object",properties:{model:{type:"string",description:'Model spec: "provider:model" (e.g. "ollama:devstral-small-2:24b") or just model name'}},required:["model"]}}},{type:"function",function:{name:"k8s_pods",description:"List Kubernetes pods. Shows pod name, status, restarts, and age. Runs kubectl locally or via SSH on a remote server. Use namespace to filter, or omit for all namespaces.",parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to list pods in (default: all namespaces)"},label:{type:"string",description:'Label selector filter (e.g. "app=nginx")'},context:{type:"string",description:"kubectl context to use (optional)"},server:{type:"string",description:"Remote server as user@host to run kubectl via SSH (optional, local kubectl if omitted)"}},required:[]}}},{type:"function",function:{name:"k8s_logs",description:'Fetch logs from a Kubernetes pod. Use tail to limit output, since for time-based filtering (e.g. "1h", "30m").',parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (required if pod has multiple containers)"},tail:{type:"number",description:"Number of recent lines to show (default: 100)"},since:{type:"string",description:'Show logs since duration (e.g. "1h", "30m", "5s")'},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod"]}}},{type:"function",function:{name:"k8s_exec",description:"Execute a command inside a running Kubernetes pod (kubectl exec). Requires user confirmation. Use for inspecting container state, reading configs, or debugging.",parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},command:{type:"string",description:'Command to run in the pod (e.g. "env", "ls /app", "cat /etc/config.yaml")'},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (optional)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod","command"]}}},{type:"function",function:{name:"k8s_apply",description:"Apply a Kubernetes manifest file (kubectl apply -f). Requires confirmation before applying to the cluster. Use dry_run=true to validate without applying.",parameters:{type:"object",properties:{file:{type:"string",description:"Path to manifest YAML file (relative or absolute)"},namespace:{type:"string",description:"Override namespace (optional)"},dry_run:{type:"boolean",description:"Validate only without applying (default: false)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["file"]}}},{type:"function",function:{name:"k8s_rollout",description:"Manage Kubernetes deployment rollouts: check status, restart (rolling update), view history, or undo (rollback). Restart and undo require confirmation.",parameters:{type:"object",properties:{action:{type:"string",enum:["status","restart","history","undo"],description:"Action: status (check rollout progress), restart (rolling restart), history (show revision history), undo (rollback to previous revision)"},deployment:{type:"string",description:"Deployment name"},namespace:{type:"string",description:"Namespace (default: default)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["action","deployment"]}}},{type:"function",function:{name:"brain_write",description:"Write or update a knowledge document in the project brain (.nex/brain/). Use this to persist important findings, architecture decisions, debugging insights, or conventions discovered during the session. The user can review changes via /brain review or git diff.",parameters:{type:"object",properties:{name:{type:"string",description:'Document name (without .md extension). Use kebab-case. Examples: "api-auth-flow", "db-schema-notes", "deployment-checklist"'},content:{type:"string",description:"Full Markdown content. Use headings (#), lists (-), and code blocks. Include optional YAML frontmatter with tags."},mode:{type:"string",enum:["create","update","append"],description:"create: new document (fails if exists). update: overwrite existing. append: add to end of existing document."}},required:["name","content","mode"]}}},{type:"function",function:{name:"ssh_exec",description:'Execute a command on a remote server via SSH. Server is a profile name from .nex/servers.json (e.g. "prod") or "user@host". Use for: checking status, reading logs, running deployments. Destructive commands (restart, delete, modify config) require confirmation. For service management prefer service_manage; for logs prefer service_logs.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name (from .nex/servers.json) or "user@host"'},command:{type:"string",description:"Shell command to run on the remote server"},sudo:{type:"boolean",description:"Run command with sudo (only if profile has sudo:true). Default: false"},timeout:{type:"number",description:"Timeout in seconds. Default: 30"}},required:["server","command"]}}},{type:"function",function:{name:"ssh_upload",description:"Upload a local file or directory to a remote server via SCP. Recursive for directories. Requires confirmation before upload.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},local_path:{type:"string",description:"Local path to upload (file or directory)"},remote_path:{type:"string",description:"Destination path on the remote server (absolute preferred)"}},required:["server","local_path","remote_path"]}}},{type:"function",function:{name:"ssh_download",description:"Download a file or directory from a remote server via SCP. Recursive for directories.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},remote_path:{type:"string",description:"Path on the remote server to download"},local_path:{type:"string",description:"Local destination path"}},required:["server","remote_path","local_path"]}}},{type:"function",function:{name:"service_manage",description:"Manage a systemd service on a remote (or local) server. Uses systemctl. Status is read-only; start/stop/restart/reload/enable/disable require confirmation. For AlmaLinux 9: runs via SSH with sudo if configured.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn", "postgresql")'},action:{type:"string",enum:["status","start","stop","restart","reload","enable","disable"],description:"systemctl action to perform"}},required:["service","action"]}}},{type:"function",function:{name:"service_logs",description:"Fetch systemd service logs via journalctl. Works on AlmaLinux 9 and any systemd Linux. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn")'},lines:{type:"number",description:"Number of recent log lines to fetch. Default: 50"},since:{type:"string",description:'Time filter, e.g. "1 hour ago", "today", "2024-01-01 12:00". Optional.'},follow:{type:"boolean",description:"Tail logs in real-time (follow mode). Default: false"}},required:["service"]}}},{type:"function",function:{name:"container_list",description:"List Docker containers on a server (or locally). Shows container ID, name, image, status, and ports. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},all:{type:"boolean",description:"Show all containers including stopped ones. Default: false (running only)."}},required:[]}}},{type:"function",function:{name:"container_logs",description:"Fetch logs from a Docker container on a server (or locally). Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},lines:{type:"number",description:"Number of recent log lines. Default: 50."},since:{type:"string",description:'Time filter, e.g. "1h", "30m", "2024-01-01T12:00:00". Optional.'}},required:["container"]}}},{type:"function",function:{name:"container_exec",description:"Execute a command inside a running Docker container. Destructive or state-changing commands require confirmation.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},command:{type:"string",description:'Command to run inside the container (e.g. "cat /etc/nginx/nginx.conf").'}},required:["container","command"]}}},{type:"function",function:{name:"container_manage",description:'Start, stop, restart, or remove a Docker container. All actions except "inspect" require confirmation.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},action:{type:"string",enum:["start","stop","restart","remove","inspect"],description:"Action to perform on the container."}},required:["container","action"]}}},{type:"function",function:{name:"deploy",description:'Deploy files to a remote server via rsync + optional remote script. Can use a named config from .nex/deploy.json (e.g. deploy("prod")) or explicit params. Requires confirmation before executing.',parameters:{type:"object",properties:{config:{type:"string",description:'Named deploy config from .nex/deploy.json (e.g. "prod"). Overrides all other params if provided.'},server:{type:"string",description:'Profile name or "user@host". Required if no config.'},local_path:{type:"string",description:'Local directory or file to sync (e.g. "dist/", "./build"). Required if no config.'},remote_path:{type:"string",description:'Remote destination path (e.g. "/var/www/app"). Required if no config.'},deploy_script:{type:"string",description:"Shell command to run on the remote after sync. Optional."},exclude:{type:"array",items:{type:"string"},description:"Paths to exclude from sync. Optional."},dry_run:{type:"boolean",description:"Show what would be synced without actually syncing. Default: false."}},required:[]}}}];function Sn(t,{server:e,context:s}={}){let n=e?e.replace(/[^a-zA-Z0-9@._-]/g,""):null,o=s?s.replace(/[^a-zA-Z0-9._/-]/g,""):null,r="kubectl";if(o&&(r+=` --context ${o}`),r+=` ${t}`,n){let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`ssh -o ConnectTimeout=10 -o BatchMode=yes ${n} "${i}"`}return r}async function gc(t,e,s={}){switch(t){case"bash":{let n=e.command,o=zp(n);if(o){let u=rm(n);return`BLOCKED: Command matches forbidden pattern: ${o}${u?`
179
- HINT: ${u}`:""}`}if(s.autoConfirm?fc(n):Kp(n)){let u=fc(n)?" \u26D4 Critical command":" \u26A0 Dangerous command";if(console.log(`
180
- ${I.yellow}${u}: ${n}${I.reset}`),!await Ge(" Execute?"))return"CANCELLED: User declined to execute this command."}let i=process.cwd();try{uc.accessSync(i)}catch{i=require("os").homedir(),s.silent||console.log(`${I.yellow} \u26A0 Working directory no longer exists \u2014 running in ${i}${I.reset}`)}let c=sm.test(n.trim())&&!om.test(n.trim());if(nm.test(n.trim())||c){s.silent||console.log(`${I.dim} \u25B6 interactive: ${n}${I.reset}`);let u=Gp("sh",["-c",n],{stdio:"inherit",cwd:i});return u.error?`ERROR: ${u.error.message}`:u.status===0?"(interactive command completed successfully)":`(interactive command exited with code ${u.status})`}let l=s.silent?null:new $c(`Running: ${n.substring(0,60)}${n.length>60?"...":""}`);l&&l.start();try{let{stdout:u,stderr:d}=await ae(n,{cwd:i,timeout:9e4,maxBuffer:5242880});return l&&l.stop(),u||d||"(no output)"}catch(u){l&&l.stop();let d=(u.stderr||u.stdout||u.message||"").toString().substring(0,5e3),p=yc(d,n);return`EXIT ${u.code||1}
181
- ${p}`}}case"read_file":{let n=Se(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await re.access(n).then(()=>!0).catch(()=>!1)){let f=await ys(e.path);if(f.fixedPath)n=f.fixedPath,console.log(`${I.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${Ee.relative(process.cwd(),n)}${I.reset}`);else return`ERROR: File not found: ${e.path}${f.message?`
182
- `+f.message:""}`}let r=Buffer.alloc(8192),i=await uc.promises.open(n,"r"),{bytesRead:c}=await i.read(r,0,8192,0);await i.close();for(let f=0;f<c;f++)if(r[f]===0)return`ERROR: ${n} is a binary file (not readable as text)`;let l=await re.readFile(n,"utf-8");if(!l&&(await re.stat(n)).size>0)return`WARNING: ${n} is empty or unreadable`;let u=l.split(`
183
- `),d=(e.line_start||1)-1,p=e.line_end||u.length;return u.slice(d,p).map((f,h)=>`${d+h+1}: ${f}`).join(`
184
- `)}case"write_file":{await Bo();let n=Se(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let o=await re.access(n).then(()=>!0).catch(()=>!1),r=null;if(s.autoConfirm)o&&(r=await re.readFile(n,"utf-8"));else if(o){r=await re.readFile(n,"utf-8");let l=await vn(n,e.content);if(gs(n,r,e.content,{annotations:l}),!await kn("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let l=await vn(n,e.content);if(Yp(n,e.content,{annotations:l}),!await kn("Create"))return"CANCELLED: User declined to create file."}let i=Ee.dirname(n);return await re.access(i).then(()=>!0).catch(()=>!1)||await re.mkdir(i,{recursive:!0}),await re.writeFile(n,e.content,"utf-8"),$s("write_file",n,r,e.content),`Written: ${n} (${e.content.length} chars)`}case"edit_file":{await Bo();let n=Se(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await re.access(n).then(()=>!0).catch(()=>!1)){let d=await ys(e.path);if(d.fixedPath)n=d.fixedPath,console.log(`${I.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${Ee.relative(process.cwd(),n)}${I.reset}`);else return`ERROR: File not found: ${e.path}${d.message?`
185
- `+d.message:""}`}let r=await re.readFile(n,"utf-8"),i=e.old_text,c=!1,l=!1;if(!r.includes(e.old_text)){let d=mc(r,e.old_text);if(d)i=d,c=!0,console.log(`${I.dim} \u2713 fuzzy whitespace match applied${I.reset}`);else{let p=wc(r,e.old_text,e.new_text);if(p){if(!s.autoConfirm){let m=await vn(n,p.content);if(gs(n,r,p.content,{annotations:m}),!await kn(`Apply (auto-fix, line ${p.line}, distance ${p.distance})`))return"CANCELLED: User declined to apply edit."}await re.writeFile(n,p.content,"utf-8"),$s("edit_file",n,r,p.content);let h=p.matchText.length>80?p.matchText.substring(0,77)+"...":p.matchText;return console.log(`${I.dim} \u2713 auto-fixed edit: line ${p.line}, distance ${p.distance}${I.reset}`),`Edited: ${n} (auto-fixed, line ${p.line}, distance ${p.distance}, matched: "${h}")`}let f=Ho(r,e.old_text);return f?`ERROR: old_text not found in ${n}
186
- Most similar text (line ${f.line}, distance ${f.distance}):
187
- ${f.text}`:`ERROR: old_text not found in ${n}`}}if(!s.autoConfirm){let d=r.split(i).join(e.new_text),p=await vn(n,d);if(gs(n,r,d,{annotations:p}),!await kn(c?"Apply (fuzzy match)":"Apply"))return"CANCELLED: User declined to apply edit."}let u=r.split(i).join(e.new_text);return await re.writeFile(n,u,"utf-8"),$s("edit_file",n,r,u),c?`Edited: ${n} (fuzzy match)`:`Edited: ${n}`}case"list_directory":{let n=Se(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await re.access(n).then(()=>!0).catch(()=>!1)){let u=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),d=Se(u),p=await re.access(d).then(()=>!0).catch(()=>!1);if(d&&p)n=d;else return`ERROR: Directory not found: ${e.path}`}let r=e.max_depth||2,i=null;if(e.pattern)try{let u=e.pattern.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");i=new RegExp(`^${u}$`)}catch{return`ERROR: Invalid pattern: ${e.pattern}`}let c=[],l=async(u,d,p)=>{if(d>r)return;let f;try{f=await re.readdir(u,{withFileTypes:!0})}catch{return}f=f.filter(h=>!h.name.startsWith(".")&&h.name!=="node_modules");for(let h of f){if(i&&!h.isDirectory()&&!i.test(h.name))continue;let m=h.isDirectory()?"/":"";c.push(`${p}${h.name}${m}`),h.isDirectory()&&await l(Ee.join(u,h.name),d+1,p+" ")}};return await l(n,1,""),c.join(`
188
- `)||"(empty)"}case"search_files":{let n=Se(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let o=["-rn","--null","-H"];e.file_pattern&&o.push(`--include=${e.file_pattern}`),o.push(e.pattern,n);try{let{stdout:r}=await dc("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),i=r.split("\0"),c=[];for(let l=0;l<i.length;l+=2){let u=i[l],d=i[l+1];if(u&&d){let p=d.split(`
189
- `).filter(f=>f.trim());for(let f of p)if(c.push(`${u}:${f}`),c.length>=50)break}if(c.length>=50)break}return c.join(`
190
- `)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let o=process.cwd(),r=e.path?Se(e.path):o,i=e.pattern,c=k=>{let v=k.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${v}$`)},l=c(i),u=i.split("/").pop(),d=c(u),{getFileIndex:p,getIndexedCwd:f,refreshIndex:h,isIndexValid:m}=ko(),g=p(),y=f();m(r)||(await h(r),g=p());let $=g.filter(k=>l.test(k)||d.test(Ee.basename(k))).map(k=>Ee.join(r,k));if($.length===0)return"(no matches)";let x=$.length>200,S=$.slice(0,200).join(`
191
- `);return x?`${S}
192
-
193
- \u26A0 Results truncated at 200. Use a more specific pattern.`:S}case"grep":{let n=e.path?Se(e.path):process.cwd(),o=["-rn","-E","--null","-H"];e.ignore_case&&o.push("-i"),e.include&&o.push(`--include=${e.include}`),o.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage"),o.push(e.pattern,n);try{let{stdout:r}=await dc("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),i=r.split("\0"),c=[];for(let l=0;l<i.length;l+=2){let u=i[l],d=i[l+1];if(u&&d){let p=d.split(`
194
- `).filter(f=>f.trim());for(let f of p)if(c.push(`${u}:${f}`),c.length>=100)break}if(c.length>=100)break}return c.join(`
195
- `).trim()||"(no matches)"}catch(r){return r.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await Bo();let n=Se(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await re.access(n).then(()=>!0).catch(()=>!1)){let f=await ys(e.path);if(f.fixedPath)n=f.fixedPath,console.log(`${I.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${Ee.relative(process.cwd(),n)}${I.reset}`);else return`ERROR: File not found: ${e.path}${f.message?`
196
- `+f.message:""}`}let r=e.patches;if(!Array.isArray(r)||r.length===0)return"ERROR: No patches provided";let i=await re.readFile(n,"utf-8"),c=[],l=!1,u=!1;for(let f=0;f<r.length;f++){let{old_text:h,new_text:m}=r[f];if(i.includes(h))c.push({old_text:h,new_text:m});else{let g=mc(i,h);if(g)c.push({old_text:g,new_text:m}),l=!0;else{let y=Ho(i,h);if(y){let $=Math.max(3,Math.ceil(h.length*.05));if(y.distance<=$)c.push({old_text:y.text,new_text:m}),u=!0;else return`ERROR: Patch ${f+1} old_text not found in ${n}
197
- Most similar text (line ${y.line}, distance ${y.distance}):
198
- ${y.text}`}else return`ERROR: Patch ${f+1} old_text not found in ${n}`}}}let d=i;for(let{old_text:f,new_text:h}of c)d=d.split(f).join(h);if(!s.autoConfirm){let f=await vn(n,d);if(gs(n,i,d,{annotations:f}),!await kn(l?"Apply patches (fuzzy match)":"Apply patches"))return"CANCELLED: User declined to apply patches."}await re.writeFile(n,d,"utf-8"),$s("patch_file",n,i,d);let p=u?" (auto-fixed)":l?" (fuzzy match)":"";return`Patched: ${n} (${r.length} replacements)${p}`}case"web_fetch":{let n=e.url,o=e.max_length||1e4;try{let r=await Uo.get(n,{timeout:15e3,maxContentLength:1048576,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}});return(typeof r.data=="string"?r.data:JSON.stringify(r.data)).replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim().substring(0,o)||"(empty response)"}catch(r){return`ERROR: Failed to fetch ${n}: ${r.message}`}}case"web_search":{let n=e.max_results||5;if(process.env.PERPLEXITY_API_KEY)try{let o=await Uo.post("https://api.perplexity.ai/chat/completions",{model:"sonar",messages:[{role:"user",content:e.query}],max_tokens:1024,search_recency_filter:"month",return_citations:!0},{timeout:2e4,headers:{Authorization:`Bearer ${process.env.PERPLEXITY_API_KEY}`,"Content-Type":"application/json"}}),r=o.data?.choices?.[0]?.message?.content||"",i=o.data?.citations||[],c=`[Perplexity grounded search]
187
+ `)}function Fl(t,e,s){let o=es(t,e);if(!o)return null;let n=Math.max(2,Math.ceil(e.length*.03));return o.distance>n?null:{autoFixed:!0,matchText:o.text,content:t.split(o.text).join(s),distance:o.distance,line:o.line}}var jl=!1,Ht=null;function gg(){Ht&&(Ht(),Ht=null)}var Dr=null;function $g(t){Dr=t}async function jr(){if(!jl){jl=!0;try{let{stdout:t}=await ie("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await ie('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await ie("git stash pop",{cwd:process.cwd(),timeout:1e4}),await ie("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var yg=[/\.ssh\//i,/\.gnupg\//i,/\.aws\//i,/\.config\/gcloud/i,/\/etc\/shadow/,/\/etc\/passwd/,/\/etc\/sudoers/,/\.env(?:\.|$)/,/credentials/i,/\.npmrc$/,/\.docker\/config\.json/,/\.kube\/config/];function Ie(t){let e=ae.isAbsolute(t)?ae.resolve(t):ae.resolve(process.cwd(),t);for(let s of yg)if(s.test(e))return null;return e}var wg=[{type:"function",function:{name:"bash",description:"Execute a bash command in the project directory. Timeout: 90s. Use for: running tests, installing packages, git commands, build tools, starting servers. Do NOT use bash for file operations when a dedicated tool exists \u2014 use read_file instead of cat, edit_file instead of sed, glob instead of find, grep instead of grep/rg. Always quote paths with spaces. Prefer specific commands over rm -rf. Destructive or dangerous commands require user confirmation.",parameters:{type:"object",properties:{command:{type:"string",description:"The bash command to execute"}},required:["command"]}}},{type:"function",function:{name:"read_file",description:"Read a file's contents with line numbers. Always read a file BEFORE editing it to see exact content. Use line_start/line_end for large files to read specific sections. Prefer this over bash cat/head/tail. Files are read with UTF-8 encoding. For binary files, use bash with appropriate flags. Alternative: use util.promisify(fs.readFile) for programmatic access.",parameters:{type:"object",properties:{path:{type:"string",description:"File path (relative or absolute)"},line_start:{type:"number",description:"Start line (1-based, optional)"},line_end:{type:"number",description:"End line (1-based, optional)"}},required:["path"]}}},{type:"function",function:{name:"write_file",description:"Create a new file or completely overwrite an existing file. For targeted changes to existing files, prefer edit_file or patch_file instead \u2014 they only send the diff and are safer. Only use write_file when creating new files or when the entire content needs to be replaced.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},content:{type:"string",description:"Full file content"}},required:["path","content"]}}},{type:"function",function:{name:"edit_file",description:"Replace specific text in a file. IMPORTANT: old_text must match the file content EXACTLY \u2014 including all whitespace, indentation (tabs vs spaces), and newlines. Always read_file first to see the exact content before editing. If old_text is not found, the edit fails. For multiple changes to the same file, prefer patch_file instead.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},old_text:{type:"string",description:"Exact text to find (must match file content precisely)"},new_text:{type:"string",description:"Replacement text"}},required:["path","old_text","new_text"]}}},{type:"function",function:{name:"list_directory",description:"List files and directories in a tree view. Use this to understand project structure. For finding specific files by pattern, prefer glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory path"},max_depth:{type:"number",description:"Max depth (default: 2)"},pattern:{type:"string",description:"File filter glob (e.g. '*.js')"}},required:["path"]}}},{type:"function",function:{name:"search_files",description:"Search for a text pattern across files (regex). Returns matching lines with file paths. For simple content search, grep is equivalent. For finding files by name, use glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory to search"},pattern:{type:"string",description:"Search pattern (regex)"},file_pattern:{type:"string",description:"File filter (e.g. '*.js')"}},required:["path","pattern"]}}},{type:"function",function:{name:"glob",description:"Find files matching a glob pattern. Fast file search by name/extension. Use this to find files before reading them. Examples: '**/*.test.js' (all test files), 'src/**/*.ts' (all TypeScript in src). Prefer this over bash find/ls.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Glob pattern (e.g. '**/*.ts', 'src/**/*.test.js')"},path:{type:"string",description:"Base directory (default: project root)"}},required:["pattern"]}}},{type:"function",function:{name:"grep",description:"Search file contents with regex. Returns matching lines with file paths and line numbers. Supports output modes (content/files_with_matches/count), context lines, head_limit, offset, type filter, and multiline. Prefer this over bash grep/rg.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Regex pattern to search for"},path:{type:"string",description:"Directory or file to search (default: project root)"},include:{type:"string",description:"File filter glob (e.g. '*.js', '*.ts')"},ignore_case:{type:"boolean",description:"Case-insensitive search"},output_mode:{type:"string",enum:["content","files_with_matches","count"],description:"Output mode: content (matching lines), files_with_matches (file paths only), count (match counts). Default: content"},context:{type:"number",description:"Lines of context around each match (like grep -C)"},before_context:{type:"number",description:"Lines before each match (like grep -B)"},after_context:{type:"number",description:"Lines after each match (like grep -A)"},head_limit:{type:"number",description:"Limit output to first N results"},offset:{type:"number",description:"Skip first N results"},type:{type:"string",description:"File type filter (e.g. 'js', 'py', 'ts') \u2014 maps to --include='*.ext'"},multiline:{type:"boolean",description:"Enable multiline matching (grep -Pz)"}},required:["pattern"]}}},{type:"function",function:{name:"patch_file",description:"Apply multiple text replacements to a file atomically. All patches are validated before any are applied \u2014 if one fails, none are written. Prefer this over multiple edit_file calls when making several changes to the same file. Like edit_file, all old_text values must match exactly.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},patches:{type:"array",description:"Array of { old_text, new_text } replacements to apply in order",items:{type:"object",properties:{old_text:{type:"string",description:"Text to find"},new_text:{type:"string",description:"Replacement text"}},required:["old_text","new_text"]}}},required:["path","patches"]}}},{type:"function",function:{name:"web_fetch",description:"Fetch content from a URL and return text. HTML tags are stripped. Use for reading documentation, API responses, or web pages. Will not work with authenticated/private URLs.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to fetch"},max_length:{type:"number",description:"Max response length in chars (default: 10000)"}},required:["url"]}}},{type:"function",function:{name:"web_search",description:"Search the web. Uses Perplexity (grounded, AI-summarized) if PERPLEXITY_API_KEY is set, otherwise DuckDuckGo. Returns titles, URLs, and summaries. Use to find documentation, solutions, or current information beyond your knowledge cutoff.",parameters:{type:"object",properties:{query:{type:"string",description:"Search query"},max_results:{type:"number",description:"Max results (default: 5)"}},required:["query"]}}},{type:"function",function:{name:"browser_open",description:"Open a URL in a headless browser and return the page title, text content, and links. More reliable than web_fetch for JavaScript-heavy pages. Requires playwright (npm install playwright && npx playwright install chromium).",parameters:{type:"object",properties:{url:{type:"string",description:"URL to open"},wait_for:{type:"string",enum:["domcontentloaded","networkidle","load"],description:"When to consider page loaded (default: domcontentloaded)"}},required:["url"]}}},{type:"function",function:{name:"browser_screenshot",description:"Take a screenshot of a URL in a headless browser. Returns the screenshot file path. The path can be pasted into the next message for visual analysis. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot"},full_page:{type:"boolean",description:"Capture full page (default: false \u2014 viewport only)"},width:{type:"number",description:"Viewport width in px (default: 1280)"},height:{type:"number",description:"Viewport height in px (default: 800)"}},required:["url"]}}},{type:"function",function:{name:"browser_click",description:"Click an element on a web page (by CSS selector or visible text). Returns the new URL after navigation. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of element to click (mutually exclusive with text)"},text:{type:"string",description:"Visible text of element to click (mutually exclusive with selector)"}},required:["url"]}}},{type:"function",function:{name:"browser_fill",description:"Fill a form field on a web page and optionally submit. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of the input field"},value:{type:"string",description:"Value to fill in"},submit:{type:"boolean",description:"Press Enter to submit after filling (default: false)"}},required:["url","selector","value"]}}},{type:"function",function:{name:"ask_user",description:"Ask the user a clarifying question with 2-3 specific options. Use when the user's intent is ambiguous. Always provide concrete, actionable options. The user can select an option or type a custom answer.",parameters:{type:"object",properties:{question:{type:"string",description:"The clarifying question to ask"},options:{type:"array",items:{type:"string"},description:"2-3 specific, actionable answer options for the user to choose from",minItems:1,maxItems:3}},required:["question","options"]}}},{type:"function",function:{name:"git_status",description:"Get git status: current branch, changed files, staged/unstaged state. Use before git operations to understand the current state.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"git_diff",description:"Get git diff for changed files. Shows additions and deletions.",parameters:{type:"object",properties:{staged:{type:"boolean",description:"Show only staged changes (default: false)"},file:{type:"string",description:"Diff specific file only (optional)"}},required:[]}}},{type:"function",function:{name:"git_log",description:"Show recent git commits (short format).",parameters:{type:"object",properties:{count:{type:"number",description:"Number of commits to show (default: 10)"},file:{type:"string",description:"Show commits for specific file (optional)"}},required:[]}}},{type:"function",function:{name:"task_list",description:"Create and manage a task list for complex multi-step tasks. Use for tasks with 3+ steps to track progress. Actions: create (new list with tasks), update (mark task in_progress/done/failed), get (view current list). Always update task status as you work.",parameters:{type:"object",properties:{action:{type:"string",enum:["create","update","get"],description:"Action to perform"},name:{type:"string",description:"Task list name (for create)"},tasks:{type:"array",description:"Array of tasks to create (for create)",items:{type:"object",properties:{description:{type:"string",description:"Task description"},depends_on:{type:"array",items:{type:"string"},description:"IDs of prerequisite tasks"}},required:["description"]}},task_id:{type:"string",description:"Task ID to update (for update)"},status:{type:"string",enum:["in_progress","done","failed"],description:"New status (for update)"},result:{type:"string",description:"Result summary (for update, optional)"}},required:["action"]}}},{type:"function",function:{name:"gh_run_list",description:"List recent GitHub Actions workflow runs for this repository. Shows run status, conclusion, branch, and timing. Use to check CI/CD status or find a run ID.",parameters:{type:"object",properties:{limit:{type:"number",description:"Number of runs to show (default: 10, max: 30)"},workflow:{type:"string",description:"Filter by workflow name or filename (optional)"},branch:{type:"string",description:"Filter by branch name (optional)"},status:{type:"string",enum:["completed","in_progress","queued","failure","success"],description:"Filter by status (optional)"}},required:[]}}},{type:"function",function:{name:"gh_run_view",description:"View details of a specific GitHub Actions workflow run: steps, logs, errors. Use gh_run_list first to get the run ID.",parameters:{type:"object",properties:{run_id:{type:"string",description:"The run ID (from gh_run_list)"},log:{type:"boolean",description:"Include full log output (default: false \u2014 shows step summary only)"}},required:["run_id"]}}},{type:"function",function:{name:"gh_workflow_trigger",description:"Trigger a GitHub Actions workflow dispatch event. Only works for workflows with workflow_dispatch trigger. Requires user confirmation.",parameters:{type:"object",properties:{workflow:{type:"string",description:"Workflow filename (e.g. ci.yml) or name"},branch:{type:"string",description:"Branch to run on (default: current branch)"},inputs:{type:"object",description:"Workflow input parameters as key-value pairs (optional)"}},required:["workflow"]}}},{type:"function",function:{name:"spawn_agents",description:"Run multiple independent sub-agents in parallel (max 5 at top level, max 2 when called from within a sub-agent). Each agent has its own conversation context. Use when 2+ tasks can run simultaneously \u2014 e.g. reading multiple files, analyzing separate modules, independent research. Do NOT use for tasks that depend on each other or modify the same file. Keep task descriptions specific and self-contained. SWARM PATTERN: Sub-agents can call spawn_agents once (max nesting depth 2) to enable Architect\u2192Coder\u2192Reviewer pipelines: a coder agent spawns 1-2 reviewer agents that validate and fix its own output before returning results to the parent.",parameters:{type:"object",properties:{agents:{type:"array",description:"Array of agent definitions to run in parallel (max 5)",items:{type:"object",properties:{task:{type:"string",description:"Task description for the agent"},context:{type:"string",description:"Additional context (optional)"},max_iterations:{type:"number",description:"Max iterations (default: 10, max: 15)"},model:{type:"string",description:'Override model for this agent (provider:model, e.g. "anthropic:claude-haiku"). Auto-selected if omitted.'}},required:["task"]}}},required:["agents"]}}},{type:"function",function:{name:"switch_model",description:"Switch the active AI model mid-conversation. Use when a different model is better for the next steps \u2014 e.g. switch to a fast model for simple lookups, or a more capable model for complex refactoring. The switch persists for all subsequent turns.",parameters:{type:"object",properties:{model:{type:"string",description:'Model spec: "provider:model" (e.g. "ollama:devstral-small-2:24b") or just model name'}},required:["model"]}}},{type:"function",function:{name:"k8s_pods",description:"List Kubernetes pods. Shows pod name, status, restarts, and age. Runs kubectl locally or via SSH on a remote server. Use namespace to filter, or omit for all namespaces.",parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to list pods in (default: all namespaces)"},label:{type:"string",description:'Label selector filter (e.g. "app=nginx")'},context:{type:"string",description:"kubectl context to use (optional)"},server:{type:"string",description:"Remote server as user@host to run kubectl via SSH (optional, local kubectl if omitted)"}},required:[]}}},{type:"function",function:{name:"k8s_logs",description:'Fetch logs from a Kubernetes pod. Use tail to limit output, since for time-based filtering (e.g. "1h", "30m").',parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (required if pod has multiple containers)"},tail:{type:"number",description:"Number of recent lines to show (default: 100)"},since:{type:"string",description:'Show logs since duration (e.g. "1h", "30m", "5s")'},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod"]}}},{type:"function",function:{name:"k8s_exec",description:"Execute a command inside a running Kubernetes pod (kubectl exec). Requires user confirmation. Use for inspecting container state, reading configs, or debugging.",parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},command:{type:"string",description:'Command to run in the pod (e.g. "env", "ls /app", "cat /etc/config.yaml")'},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (optional)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod","command"]}}},{type:"function",function:{name:"k8s_apply",description:"Apply a Kubernetes manifest file (kubectl apply -f). Requires confirmation before applying to the cluster. Use dry_run=true to validate without applying.",parameters:{type:"object",properties:{file:{type:"string",description:"Path to manifest YAML file (relative or absolute)"},namespace:{type:"string",description:"Override namespace (optional)"},dry_run:{type:"boolean",description:"Validate only without applying (default: false)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["file"]}}},{type:"function",function:{name:"k8s_rollout",description:"Manage Kubernetes deployment rollouts: check status, restart (rolling update), view history, or undo (rollback). Restart and undo require confirmation.",parameters:{type:"object",properties:{action:{type:"string",enum:["status","restart","history","undo"],description:"Action: status (check rollout progress), restart (rolling restart), history (show revision history), undo (rollback to previous revision)"},deployment:{type:"string",description:"Deployment name"},namespace:{type:"string",description:"Namespace (default: default)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["action","deployment"]}}},{type:"function",function:{name:"brain_write",description:"Write or update a knowledge document in the project brain (.nex/brain/). Use this to persist important findings, architecture decisions, debugging insights, or conventions discovered during the session. The user can review changes via /brain review or git diff.",parameters:{type:"object",properties:{name:{type:"string",description:'Document name (without .md extension). Use kebab-case. Examples: "api-auth-flow", "db-schema-notes", "deployment-checklist"'},content:{type:"string",description:"Full Markdown content. Use headings (#), lists (-), and code blocks. Include optional YAML frontmatter with tags."},mode:{type:"string",enum:["create","update","append"],description:"create: new document (fails if exists). update: overwrite existing. append: add to end of existing document."}},required:["name","content","mode"]}}},{type:"function",function:{name:"ssh_exec",description:'Execute a command on a remote server via SSH. Server is a profile name from .nex/servers.json (e.g. "prod") or "user@host". Use for: checking status, reading logs, running deployments. Destructive commands (restart, delete, modify config) require confirmation. For service management prefer service_manage; for logs prefer service_logs.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name (from .nex/servers.json) or "user@host"'},command:{type:"string",description:"Shell command to run on the remote server"},sudo:{type:"boolean",description:"Run command with sudo (only if profile has sudo:true). Default: false"},timeout:{type:"number",description:"Timeout in seconds. Default: 30"}},required:["server","command"]}}},{type:"function",function:{name:"ssh_upload",description:"Upload a local file or directory to a remote server via SCP. Recursive for directories. Requires confirmation before upload.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},local_path:{type:"string",description:"Local path to upload (file or directory)"},remote_path:{type:"string",description:"Destination path on the remote server (absolute preferred)"}},required:["server","local_path","remote_path"]}}},{type:"function",function:{name:"ssh_download",description:"Download a file or directory from a remote server via SCP. Recursive for directories.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},remote_path:{type:"string",description:"Path on the remote server to download"},local_path:{type:"string",description:"Local destination path"}},required:["server","remote_path","local_path"]}}},{type:"function",function:{name:"remote_agent",description:'Delegate a coding task to nex-code running on a remote server. Use this when the task involves server-side projects (musikschule, stadtkapelle, cahill, schoensgibl, jarvis) that live on almalinux9/jarvis. Runs nex-code --auto on the server and streams output. Server is a profile name from .nex/servers.json or "user@host".',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name from .nex/servers.json (e.g. "almalinux9") or "user@host"'},task:{type:"string",description:"The full task description to run on the remote nex-code"},project_path:{type:"string",description:"Working directory on the remote server (e.g. /home/jarvis/jarvis-agent). Defaults to home directory."},model:{type:"string",description:"Model to use on remote nex-code (e.g. qwen3-coder:480b). Defaults to server default."}},required:["server","task"]}}},{type:"function",function:{name:"service_manage",description:"Manage a systemd service on a remote (or local) server. Uses systemctl. Status is read-only; start/stop/restart/reload/enable/disable require confirmation. For AlmaLinux 9: runs via SSH with sudo if configured.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn", "postgresql")'},action:{type:"string",enum:["status","start","stop","restart","reload","enable","disable"],description:"systemctl action to perform"}},required:["service","action"]}}},{type:"function",function:{name:"service_logs",description:"Fetch systemd service logs via journalctl. Works on AlmaLinux 9 and any systemd Linux. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn")'},lines:{type:"number",description:"Number of recent log lines to fetch. Default: 50"},since:{type:"string",description:'Time filter, e.g. "1 hour ago", "today", "2024-01-01 12:00". Optional.'},follow:{type:"boolean",description:"Tail logs in real-time (follow mode). Default: false"}},required:["service"]}}},{type:"function",function:{name:"container_list",description:"List Docker containers on a server (or locally). Shows container ID, name, image, status, and ports. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},all:{type:"boolean",description:"Show all containers including stopped ones. Default: false (running only)."}},required:[]}}},{type:"function",function:{name:"container_logs",description:"Fetch logs from a Docker container on a server (or locally). Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},lines:{type:"number",description:"Number of recent log lines. Default: 50."},since:{type:"string",description:'Time filter, e.g. "1h", "30m", "2024-01-01T12:00:00". Optional.'}},required:["container"]}}},{type:"function",function:{name:"container_exec",description:"Execute a command inside a running Docker container. Destructive or state-changing commands require confirmation.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},command:{type:"string",description:'Command to run inside the container (e.g. "cat /etc/nginx/nginx.conf").'}},required:["container","command"]}}},{type:"function",function:{name:"container_manage",description:'Start, stop, restart, or remove a Docker container. All actions except "inspect" require confirmation.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},action:{type:"string",enum:["start","stop","restart","remove","inspect"],description:"Action to perform on the container."}},required:["container","action"]}}},{type:"function",function:{name:"frontend_recon",description:"MANDATORY first step before creating or significantly modifying any frontend file (HTML template, Vue/React component, CSS). Scans the project and returns: (1) design tokens \u2014 CSS variables, Tailwind theme colors/fonts, (2) main layout/index page structure, (3) a reference component of the same type, (4) detected JS/CSS framework stack. Call this BEFORE writing any markup or styles. Never skip it for frontend tasks.",parameters:{type:"object",properties:{type:{type:"string",description:'Type of frontend file you are about to create. Used to find a relevant reference component. Examples: "list", "form", "detail", "dashboard", "modal", "component". Optional but improves reference quality.'}},required:[]}}},{type:"function",function:{name:"deploy",description:'Deploy to a remote server. Supports two methods: "rsync" (sync local files) and "git" (git pull on remote). Can use a named config from .nex/deploy.json. Requires confirmation before executing.',parameters:{type:"object",properties:{config:{type:"string",description:'Named deploy config from .nex/deploy.json (e.g. "prod"). Overrides all other params if provided.'},method:{type:"string",enum:["rsync","git"],description:'Deploy method: "rsync" syncs local files (default), "git" runs git pull on the remote.'},server:{type:"string",description:'Profile name or "user@host". Required if no config.'},remote_path:{type:"string",description:"Remote project directory. Required for git method; destination path for rsync."},local_path:{type:"string",description:"Local directory or file to sync. Required for rsync method."},branch:{type:"string",description:"Branch to pull (git method only). Defaults to current remote branch."},deploy_script:{type:"string",description:'Shell command(s) to run on the remote after sync/pull (e.g. "npm ci && systemctl restart myapp"). Optional.'},health_check:{type:"string",description:"URL (HTTP GET) or shell command to verify the service is healthy after deploy. If it fails, the deploy is marked as failed. Optional."},exclude:{type:"array",items:{type:"string"},description:"Paths to exclude from rsync. Optional."},dry_run:{type:"boolean",description:"Show what would happen without executing. Default: false."}},required:[]}}},{type:"function",function:{name:"deployment_status",description:"Check deployment status across all configured servers. Reads .nex/deploy.json configs and checks service health on each server. Returns a status summary table.",parameters:{type:"object",properties:{config:{type:"string",description:"Specific deploy config name to check (optional \u2014 checks all if omitted)"}},required:[]}}},{type:"function",function:{name:"sysadmin",description:"Senior sysadmin operations on a remote (or local) Linux server. Covers: system audit, disk_usage, process_list, network_status, package management (dnf/apt), user management, firewall (firewalld/ufw/iptables), cron, SSL cert checks, log tailing, large file discovery, systemd service management, process kill, journalctl log querying. Read-only actions run without confirmation; state-changing actions require user approval.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},action:{type:"string",enum:["audit","disk_usage","process_list","network_status","package","user_manage","firewall","cron","ssl_check","log_tail","find_large","service","kill_process","journalctl"],description:"Sysadmin operation. audit=full health overview; disk_usage=df+du; process_list=top procs; network_status=open ports; package=dnf/apt; user_manage=users/keys; firewall=rules; cron=crontab; ssl_check=cert expiry+days; log_tail=tail any log; find_large=big files; service=systemd unit management; kill_process=kill by PID or name; journalctl=query system journal."},path:{type:"string",description:"File or directory path. For disk_usage (default /), log_tail (required), find_large (default /)."},lines:{type:"number",description:"Lines to tail for log_tail or journalctl. Default: 100."},limit:{type:"number",description:"Result count for process_list (default 20) or find_large (default 20)."},sort_by:{type:"string",enum:["cpu","mem"],description:"Sort order for process_list. Default: cpu."},min_size:{type:"string",description:'Minimum file size for find_large. Default: "100M". Examples: "50M", "1G".'},package_action:{type:"string",enum:["install","remove","update","list","upgrade"],description:"Package sub-action for action=package."},packages:{type:"array",items:{type:"string"},description:"Package name(s) for install/remove/update."},user_action:{type:"string",enum:["list","create","delete","add_ssh_key","info"],description:"User sub-action for action=user_manage."},user:{type:"string",description:"Linux username for user_manage or cron."},groups:{type:"array",items:{type:"string"},description:'Groups to assign on user create (e.g. ["sudo", "docker"]).'},ssh_key:{type:"string",description:"SSH public key string to add for user_action=add_ssh_key."},firewall_action:{type:"string",enum:["status","allow","deny","remove","reload"],description:"Firewall sub-action for action=firewall."},port:{type:"string",description:'Port/protocol for firewall rules, e.g. "80/tcp", "443", "8080/udp".'},cron_action:{type:"string",enum:["list","add","remove"],description:"Cron sub-action for action=cron."},schedule:{type:"string",description:'Cron schedule expression for cron add, e.g. "0 2 * * *".'},command:{type:"string",description:"Command for cron add, or substring to match for cron remove."},domain:{type:"string",description:`Domain for ssl_check (e.g. "example.com"). Auto-detects Let's Encrypt cert on server; falls back to live TLS probe.`},cert_path:{type:"string",description:'Explicit path to cert file on server for ssl_check (e.g. "/etc/letsencrypt/live/x/cert.pem").'},service_name:{type:"string",description:'Systemd unit name for action=service (e.g. "nginx", "jarvis-api", "gunicorn"). .service suffix optional.'},service_action:{type:"string",enum:["status","start","stop","restart","reload","enable","disable","list_failed"],description:"Sub-action for action=service. list_failed shows all failed units."},pid:{type:"number",description:"Process ID to kill for action=kill_process."},process_name:{type:"string",description:"Process name to kill (uses pkill) for action=kill_process. Use with pid for safety."},signal:{type:"string",enum:["SIGTERM","SIGKILL","SIGHUP","SIGINT"],description:"Signal for kill_process. Default: SIGTERM."},unit:{type:"string",description:'Systemd unit to filter for journalctl (e.g. "nginx", "jarvis-api"). Omit for system-wide.'},since:{type:"string",description:'Time filter for journalctl, e.g. "1 hour ago", "today", "2026-03-17 10:00". Default: last 200 lines.'},priority:{type:"string",enum:["emerg","alert","crit","err","warning","notice","info","debug"],description:"Minimum log priority for journalctl. Default: no filter."}},required:["action"]}}}];function Zn(t,{server:e,context:s}={}){let o=e?e.replace(/[^a-zA-Z0-9@._-]/g,""):null,n=s?s.replace(/[^a-zA-Z0-9._/-]/g,""):null,r="kubectl";if(n&&(r+=` --context ${n}`),r+=` ${t}`,o){let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`ssh -o ConnectTimeout=10 -o BatchMode=yes ${o} "${i}"`}return r}async function Dl(t,e,s={}){switch(t){case"bash":{let o=e.command,n=eg(o);if(n){let d=hg(o);return`BLOCKED: Command matches forbidden pattern: ${n}${d?`
188
+ HINT: ${d}`:""}`}if(s.autoConfirm?Pl(o):tg(o)){let d=Pl(o)?" \u26D4 Critical command":" \u26A0 Dangerous command";if(console.log(`
189
+ ${F.yellow}${d}: ${o}${F.reset}`),!await Ve(" Execute?"))return"CANCELLED: User declined to execute this command."}let i;try{i=process.cwd(),Ol.accessSync(i)}catch{i=require("os").homedir(),s.silent||console.log(`${F.yellow} \u26A0 Working directory no longer exists \u2014 running in ${i}${F.reset}`)}let c=pg.test(o.trim())&&!mg.test(o.trim());if(fg.test(o.trim())||c){s.silent||console.log(`${F.dim} \u25B6 interactive: ${o}${F.reset}`);let d=Zh("sh",["-c",o],{stdio:"inherit",cwd:i});return d.error?`ERROR: ${d.error.message}`:d.status===0?"(interactive command completed successfully)":`(interactive command exited with code ${d.status})`}let{ToolProgress:l}=Cn(),u=s.silent?null:new l("bash",o.substring(0,40));u&&u.start();try{let{stdout:d,stderr:f}=await ie(o,{cwd:i,timeout:9e4,maxBuffer:5242880});return u&&u.stop(),d||f||"(no output)"}catch(d){u&&u.stop();let f=(d.stderr||d.stdout||d.message||"").toString().substring(0,5e3),m=ql(f,o);return`EXIT ${d.code||1}
190
+ ${m}`}}case"read_file":{let o=Ie(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await V.access(o).then(()=>!0).catch(()=>!1)){let $=await Zs(e.path);if($.fixedPath)o=$.fixedPath,console.log(`${F.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ae.relative(process.cwd(),o)}${F.reset}`);else return`ERROR: File not found: ${e.path}${$.message?`
191
+ `+$.message:""}`}let r=Buffer.alloc(8192),i=await Ol.promises.open(o,"r"),{bytesRead:c}=await i.read(r,0,8192,0);await i.close();for(let $=0;$<c;$++)if(r[$]===0)return`ERROR: ${o} is a binary file (not readable as text)`;let l=await V.readFile(o,"utf-8");if(!l&&(await V.stat(o)).size>0)return`WARNING: ${o} is empty or unreadable`;let u=l.split(`
192
+ `),d=(e.line_start||1)-1,f=e.line_end||u.length,m=await V.stat(o),h=u.length,p=`File: ${ae.relative(process.cwd(),o)} (${h} lines, ${m.size} bytes)`,g=u.slice(d,f).map(($,y)=>`${d+y+1}: ${$}`).join(`
193
+ `);return`${p}
194
+ ${g}`}case"write_file":{await jr();let o=Ie(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let n=await V.access(o).then(()=>!0).catch(()=>!1),r=null;if(s.autoConfirm)n&&(r=await V.readFile(o,"utf-8"));else if(n){r=await V.readFile(o,"utf-8");let d=await Qn(o,e.content);if(Vs(o,r,e.content,{annotations:d}),!await Vn("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let d=await Qn(o,e.content);if(ng(o,e.content,{annotations:d}),!await Vn("Create"))return"CANCELLED: User declined to create file."}let i=ae.dirname(o);await V.access(i).then(()=>!0).catch(()=>!1)||await V.mkdir(i,{recursive:!0}),await V.writeFile(o,e.content,"utf-8");let l=/[/\\]\.git[/\\]hooks[/\\]/.test(o)||o.endsWith(".sh")||e.content.startsWith("#!");l&&await V.chmod(o,493),Qs("write_file",o,r,e.content);let u=l?" [chmod +x applied]":"";return`Written: ${o} (${e.content.length} chars)${u}`}case"edit_file":{await jr();let o=Ie(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await V.access(o).then(()=>!0).catch(()=>!1)){let d=await Zs(e.path);if(d.fixedPath)o=d.fixedPath,console.log(`${F.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ae.relative(process.cwd(),o)}${F.reset}`);else return`ERROR: File not found: ${e.path}${d.message?`
195
+ `+d.message:""}`}let r=await V.readFile(o,"utf-8"),i=e.old_text,c=!1,l=!1;if(!r.includes(e.old_text)){let{getActiveModelId:d,getActiveProviderName:f}=we();if(Ll(d(),f())==="strict"){let p=es(r,e.old_text);return p?`ERROR: old_text not found in ${o} (strict mode \u2014 exact match required)
196
+ Most similar text (line ${p.line}, distance ${p.distance}):
197
+ ${p.text}`:`ERROR: old_text not found in ${o} (strict mode \u2014 exact match required)`}let h=Il(r,e.old_text);if(h)i=h,c=!0,console.log(`${F.dim} \u2713 fuzzy whitespace match applied${F.reset}`);else{let p=Fl(r,e.old_text,e.new_text);if(p){if(!s.autoConfirm){let y=await Qn(o,p.content);if(Vs(o,r,p.content,{annotations:y}),!await Vn(`Apply (auto-fix, line ${p.line}, distance ${p.distance})`))return"CANCELLED: User declined to apply edit."}await V.writeFile(o,p.content,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(o)||o.endsWith(".sh")||p.content.startsWith("#!"))&&await V.chmod(o,493),Qs("edit_file",o,r,p.content);let $=p.matchText.length>80?p.matchText.substring(0,77)+"...":p.matchText;return console.log(`${F.dim} \u2713 auto-fixed edit: line ${p.line}, distance ${p.distance}${F.reset}`),`Edited: ${o} (auto-fixed, line ${p.line}, distance ${p.distance}, matched: "${$}")`}let g=es(r,e.old_text);return g?`ERROR: old_text not found in ${o}
198
+ Most similar text (line ${g.line}, distance ${g.distance}):
199
+ ${g.text}`:`ERROR: old_text not found in ${o}`}}if(!s.autoConfirm){let d=r.split(i).join(e.new_text),f=await Qn(o,d);if(Vs(o,r,d,{annotations:f}),!await Vn(c?"Apply (fuzzy match)":"Apply"))return"CANCELLED: User declined to apply edit."}let u=r.split(i).join(e.new_text);return await V.writeFile(o,u,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(o)||o.endsWith(".sh")||u.startsWith("#!"))&&await V.chmod(o,493),Qs("edit_file",o,r,u),c?`Edited: ${o} (fuzzy match)`:`Edited: ${o}`}case"list_directory":{let o=Ie(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await V.access(o).then(()=>!0).catch(()=>!1)){let u=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),d=Ie(u),f=await V.access(d).then(()=>!0).catch(()=>!1);if(d&&f)o=d;else return`ERROR: Directory not found: ${e.path}`}let r=e.max_depth||2,i=null;if(e.pattern)try{let u=e.pattern.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");i=new RegExp(`^${u}$`)}catch{return`ERROR: Invalid pattern: ${e.pattern}`}let c=[],l=async(u,d,f)=>{if(d>r)return;let m;try{m=await V.readdir(u,{withFileTypes:!0})}catch{return}m=m.filter(h=>!h.name.startsWith(".")&&h.name!=="node_modules");for(let h of m){if(i&&!h.isDirectory()&&!i.test(h.name))continue;let p=h.isDirectory()?"/":"";c.push(`${f}${h.name}${p}`),h.isDirectory()&&await l(ae.join(u,h.name),d+1,f+" ")}};return await l(o,1,""),c.join(`
200
+ `)||"(empty)"}case"search_files":{let o=Ie(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let n=["-rn","--null","-H"];e.file_pattern&&n.push(`--include=${e.file_pattern}`),n.push(e.pattern,o);try{let{stdout:r}=await Nl("grep",n,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),i=r.split("\0"),c=[];for(let l=0;l<i.length;l+=2){let u=i[l],d=i[l+1];if(u&&d){let f=d.split(`
201
+ `).filter(m=>m.trim());for(let m of f)if(c.push(`${u}:${m}`),c.length>=50)break}if(c.length>=50)break}return c.join(`
202
+ `)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let n=process.cwd(),r=e.path?Ie(e.path):n,i=e.pattern,c=C=>{let I=C.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${I}$`)},l=c(i),u=i.split("/").pop(),d=c(u),{ToolProgress:f}=Cn(),m=new f("glob","Finding files...");m.start();let{getFileIndex:h,getIndexedCwd:p,refreshIndex:g,isIndexValid:$}=gr(),y=h(),w=p();$(r)||(await g(r),y=h());let T=y.filter(C=>l.test(C)||d.test(ae.basename(C))).map(C=>ae.join(r,C));if(T.length===0)return m.stop(),"(no matches)";let _=await Promise.all(T.slice(0,210).map(async C=>{try{let I=await V.stat(C);return{path:C,mtime:I.mtimeMs}}catch{return{path:C,mtime:0}}}));_.sort((C,I)=>I.mtime-C.mtime);let x=_.map(C=>C.path),S=T.length>200,R=x.slice(0,200).join(`
203
+ `);return m.update({count:T.length,detail:e.pattern}),m.stop(),S?`${R}
204
+
205
+ \u26A0 Results truncated at 200. Use a more specific pattern.`:R}case"grep":{let o=e.path?Ie(e.path):process.cwd(),n=["-rn","-E","--null","-H"];e.ignore_case&&n.push("-i"),e.include&&n.push(`--include=${e.include}`),e.type&&n.push(`--include=*.${e.type}`),e.context?n.push("-C",String(e.context)):(e.before_context&&n.push("-B",String(e.before_context)),e.after_context&&n.push("-A",String(e.after_context))),e.output_mode==="files_with_matches"?n.push("-l"):e.output_mode==="count"&&n.push("-c"),n.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage"),n.push(e.pattern,o);let{ToolProgress:r}=Cn(),i=new r("grep","Searching...");i.start();try{let{stdout:c}=await Nl("grep",n,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),l;if(e.output_mode==="files_with_matches"||e.output_mode==="count")l=c.trim().split(`
206
+ `).filter(f=>f.trim());else{let f=c.split("\0");l=[];for(let m=0;m<f.length;m+=2){let h=f[m],p=f[m+1];if(h&&p){let g=p.split(`
207
+ `).filter($=>$.trim());for(let $ of g)l.push(`${h}:${$}`)}}}let u=e.offset||0,d=e.head_limit||(e.output_mode==="files_with_matches"?200:100);return l=l.slice(u,u+d),i.update({count:l.length,detail:`in ${o}`}),i.stop(),l.join(`
208
+ `).trim()||"(no matches)"}catch(c){return i.stop(),c.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await jr();let o=Ie(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await V.access(o).then(()=>!0).catch(()=>!1)){let y=await Zs(e.path);if(y.fixedPath)o=y.fixedPath,console.log(`${F.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ae.relative(process.cwd(),o)}${F.reset}`);else return`ERROR: File not found: ${e.path}${y.message?`
209
+ `+y.message:""}`}let r=e.patches;if(!Array.isArray(r)||r.length===0)return"ERROR: No patches provided";let i=await V.readFile(o,"utf-8"),{getActiveModelId:c,getActiveProviderName:l}=we(),u=Ll(c(),l()),d=[],f=!1,m=!1;for(let y=0;y<r.length;y++){let{old_text:w,new_text:T}=r[y];if(i.includes(w))d.push({old_text:w,new_text:T});else if(u==="strict"){let _=es(i,w);return _?`ERROR: Patch ${y+1} old_text not found in ${o} (strict mode \u2014 exact match required)
210
+ Most similar text (line ${_.line}, distance ${_.distance}):
211
+ ${_.text}`:`ERROR: Patch ${y+1} old_text not found in ${o} (strict mode \u2014 exact match required)`}else{let _=Il(i,w);if(_)d.push({old_text:_,new_text:T}),f=!0;else{let x=es(i,w);if(x){let S=Math.max(3,Math.ceil(w.length*.05));if(x.distance<=S)d.push({old_text:x.text,new_text:T}),m=!0;else return`ERROR: Patch ${y+1} old_text not found in ${o}
212
+ Most similar text (line ${x.line}, distance ${x.distance}):
213
+ ${x.text}`}else return`ERROR: Patch ${y+1} old_text not found in ${o}`}}}let h=i;for(let{old_text:y,new_text:w}of d)h=h.split(y).join(w);if(!s.autoConfirm){let y=await Qn(o,h);if(Vs(o,i,h,{annotations:y}),!await Vn(f?"Apply patches (fuzzy match)":"Apply patches"))return"CANCELLED: User declined to apply patches."}await V.writeFile(o,h,"utf-8");let p=/[/\\]\.git[/\\]hooks[/\\]/.test(o)||o.endsWith(".sh")||h.startsWith("#!");p&&await V.chmod(o,493),Qs("patch_file",o,i,h);let g=m?" (auto-fixed)":f?" (fuzzy match)":"",$=p?" [chmod +x applied]":"";return`Patched: ${o} (${r.length} replacements)${g}${$}`}case"web_fetch":{let o=e.url,n=e.max_length||1e4;try{let r=await Ir.get(o,{timeout:15e3,maxContentLength:1048576,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}});return(typeof r.data=="string"?r.data:JSON.stringify(r.data)).replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim().substring(0,n)||"(empty response)"}catch(r){return`ERROR: Failed to fetch ${o}: ${r.message}`}}case"web_search":{let o=e.max_results||5;if(process.env.PERPLEXITY_API_KEY)try{let n=await Ir.post("https://api.perplexity.ai/chat/completions",{model:"sonar",messages:[{role:"user",content:e.query}],max_tokens:1024,search_recency_filter:"month",return_citations:!0},{timeout:2e4,headers:{Authorization:`Bearer ${process.env.PERPLEXITY_API_KEY}`,"Content-Type":"application/json"}}),r=n.data?.choices?.[0]?.message?.content||"",i=n.data?.citations||[],c=`[Perplexity grounded search]
199
214
 
200
215
  ${r}`;return i.length>0&&(c+=`
201
216
 
202
217
  Sources:
203
- `+i.slice(0,n).map((l,u)=>`${u+1}. ${l}`).join(`
204
- `)),c}catch(o){console.error(`${I.dim} Perplexity search failed (${o.message}), falling back to DuckDuckGo${I.reset}`)}try{let r=(await Uo.get("https://html.duckduckgo.com/html/",{params:{q:e.query},timeout:1e4,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}})).data,i=[],c=/<a[^>]*class="result__a"[^>]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/gi,l;for(;(l=c.exec(r))!==null&&i.length<n;){let u=l[1].replace(/.*uddg=/,"").split("&")[0],d=l[2].replace(/<[^>]+>/g,"").trim();try{i.push({title:d,url:decodeURIComponent(u)})}catch{i.push({title:d,url:u})}}return i.length===0?"(no results)":i.map((u,d)=>`${d+1}. ${u.title}
218
+ `+i.slice(0,o).map((l,u)=>`${u+1}. ${l}`).join(`
219
+ `)),c}catch(n){console.error(`${F.dim} Perplexity search failed (${n.message}), falling back to DuckDuckGo${F.reset}`)}try{let r=(await Ir.get("https://html.duckduckgo.com/html/",{params:{q:e.query},timeout:1e4,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}})).data,i=[],c=/<a[^>]*class="result__a"[^>]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/gi,l;for(;(l=c.exec(r))!==null&&i.length<o;){let u=l[1].replace(/.*uddg=/,"").split("&")[0],d=l[2].replace(/<[^>]+>/g,"").trim();try{i.push({title:d,url:decodeURIComponent(u)})}catch{i.push({title:d,url:u})}}return i.length===0?"(no results)":i.map((u,d)=>`${d+1}. ${u.title}
205
220
  ${u.url}`).join(`
206
221
 
207
- `)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:n}=pn();try{let o=await n(e.url,{waitFor:e.wait_for}),r=o.links.length>0?`
222
+ `)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:o}=Bn();try{let n=await o(e.url,{waitFor:e.wait_for}),r=n.links.length>0?`
208
223
 
209
224
  Links:
210
- `+o.links.map(i=>` ${i.text} \u2192 ${i.href}`).join(`
211
- `):"";return`Title: ${o.title}
212
- URL: ${o.url}
225
+ `+n.links.map(i=>` ${i.text} \u2192 ${i.href}`).join(`
226
+ `):"";return`Title: ${n.title}
227
+ URL: ${n.url}
213
228
 
214
- ${o.text}${r}`}catch(o){return`ERROR: ${o.message}`}}case"browser_screenshot":{let{browserScreenshot:n}=pn();try{let o=await n(e.url,{width:e.width,height:e.height,fullPage:e.full_page});return`Screenshot saved: ${o.path}
215
- Title: ${o.title}
216
- URL: ${o.url}
229
+ ${n.text}${r}`}catch(n){return`ERROR: ${n.message}`}}case"browser_screenshot":{let{browserScreenshot:o}=Bn();try{let n=await o(e.url,{width:e.width,height:e.height,fullPage:e.full_page});return`Screenshot saved: ${n.path}
230
+ Title: ${n.title}
231
+ URL: ${n.url}
217
232
 
218
- To analyze visually, paste the path into your next message: ${o.path}`}catch(o){return`ERROR: ${o.message}`}}case"browser_click":{let{browserClick:n}=pn();try{return await n(e.url,{selector:e.selector,text:e.text})}catch(o){return`ERROR: ${o.message}`}}case"browser_fill":{let{browserFill:n}=pn();try{return await n(e.url,{selector:e.selector,value:e.value,submit:e.submit})}catch(o){return`ERROR: ${o.message}`}}case"ask_user":{let{question:n,options:o=[]}=e;return Go?new Promise(r=>{Tt=()=>r("CANCELLED"),Go(n,o).then(i=>{Tt=null,r(i||"User did not answer")})}):new Promise(r=>{let i=require("readline").createInterface({input:process.stdin,output:process.stdout});Tt=()=>{i.close(),r("CANCELLED")};let c=o.length>0?`
219
- ${o.map((l,u)=>` ${u+1}. ${l}`).join(`
233
+ To analyze visually, paste the path into your next message: ${n.path}`}catch(n){return`ERROR: ${n.message}`}}case"browser_click":{let{browserClick:o}=Bn();try{return await o(e.url,{selector:e.selector,text:e.text})}catch(n){return`ERROR: ${n.message}`}}case"browser_fill":{let{browserFill:o}=Bn();try{return await o(e.url,{selector:e.selector,value:e.value,submit:e.submit})}catch(n){return`ERROR: ${n.message}`}}case"ask_user":{let{question:o,options:n=[]}=e;return Dr?new Promise(r=>{Ht=()=>r("CANCELLED"),Dr(o,n).then(i=>{Ht=null,r(i||"User did not answer")})}):new Promise(r=>{let i=require("readline").createInterface({input:process.stdin,output:process.stdout});Ht=()=>{i.close(),r("CANCELLED")};let c=n.length>0?`
234
+ ${n.map((l,u)=>` ${u+1}. ${l}`).join(`
220
235
  `)}
221
236
  `:"";console.log(`
222
- ${I.cyan}${I.bold} ? ${n}${I.reset}${c}`),i.question(`${I.cyan} > ${I.reset}`,l=>{Tt=null,i.close(),r(l.trim()||"(no response)")})})}case"git_status":{if(!await Wo())return"ERROR: Not a git repository";let n=await pc()||"(detached)",o=await Vp();if(o.length===0)return`Branch: ${n}
223
- Clean working tree (no changes)`;let r=[`Branch: ${n}`,`Changed files (${o.length}):`];for(let i of o){let c=i.status==="M"?"modified":i.status==="A"?"added":i.status==="D"?"deleted":i.status==="??"?"untracked":i.status;r.push(` ${c}: ${i.file}`)}return r.join(`
224
- `)}case"git_diff":{if(!await Wo())return"ERROR: Not a git repository";let n;if(e.file){let o=["diff"];e.staged&&o.push("--cached"),o.push("--",e.file);try{n=execFileSync("git",o,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()}catch{n=""}}else n=await Xp(!!e.staged);return n||"(no diff)"}case"git_log":{if(!await Wo())return"ERROR: Not a git repository";let o=["log","--oneline",`-${Math.min(e.count||10,50)}`];e.file&&o.push("--",e.file);try{return execFileSync("git",o,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()||"(no commits)"}catch{return"(no commits)"}}case"task_list":{let{createTasks:n,updateTask:o,getTaskList:r,renderTaskList:i,hasActiveTasks:c}=ds(),{getActiveTaskProgress:l}=de(),u=l();switch(e.action){case"create":{if(!e.name||!e.tasks)return"ERROR: task_list create requires name and tasks";let d=n(e.name,e.tasks);return u||console.log(`
237
+ ${F.cyan}${F.bold} ? ${o}${F.reset}${c}`),i.question(`${F.cyan} > ${F.reset}`,l=>{Ht=null,i.close(),r(l.trim()||"(no response)")})})}case"git_status":{if(!await Lr())return"ERROR: Not a git repository";let o=await Ml()||"(detached)",n=await rg();if(n.length===0)return`Branch: ${o}
238
+ Clean working tree (no changes)`;let r=[`Branch: ${o}`,`Changed files (${n.length}):`];for(let i of n){let c=i.status==="M"?"modified":i.status==="A"?"added":i.status==="D"?"deleted":i.status==="??"?"untracked":i.status;r.push(` ${c}: ${i.file}`)}return r.join(`
239
+ `)}case"git_diff":{if(!await Lr())return"ERROR: Not a git repository";let o;if(e.file){let n=["diff"];e.staged&&n.push("--cached"),n.push("--",e.file);try{o=execFileSync("git",n,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()}catch{o=""}}else o=await ig(!!e.staged);return o||"(no diff)"}case"git_log":{if(!await Lr())return"ERROR: Not a git repository";let n=["log","--oneline",`-${Math.min(e.count||10,50)}`];e.file&&n.push("--",e.file);try{return execFileSync("git",n,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()||"(no commits)"}catch{return"(no commits)"}}case"task_list":{let{createTasks:o,updateTask:n,getTaskList:r,renderTaskList:i,hasActiveTasks:c}=Gs(),{getActiveTaskProgress:l}=ye(),u=l();switch(e.action){case"create":{if(!e.name||!e.tasks)return"ERROR: task_list create requires name and tasks";let d=o(e.name,e.tasks);return u||console.log(`
225
240
  `+i()),`Created task list "${e.name}" with ${d.length} tasks:
226
- `+d.map(p=>` ${p.id}: ${p.description}`).join(`
227
- `)}case"update":return!e.task_id||!e.status?"ERROR: task_list update requires task_id and status":o(e.task_id,e.status,e.result)?(u||console.log(`
241
+ `+d.map(f=>` ${f.id}: ${f.description}`).join(`
242
+ `)}case"update":return!e.task_id||!e.status?"ERROR: task_list update requires task_id and status":n(e.task_id,e.status,e.result)?(u||console.log(`
228
243
  `+i()),`Updated ${e.task_id}: ${e.status}${e.result?" \u2014 "+e.result:""}`):`ERROR: Task not found: ${e.task_id}`;case"get":{let d=r();return d.tasks.length===0?"No active tasks":(u||console.log(`
229
- `+i()),JSON.stringify(d,null,2))}default:return`ERROR: Unknown task_list action: ${e.action}. Use: create, update, get`}}case"spawn_agents":{let{executeSpawnAgents:n}=Va();return n(e)}case"switch_model":{let{setActiveModel:n,getActiveProviderName:o,getActiveModelId:r}=ge();return n(e.model)?`Switched to ${o()}:${r()}`:`ERROR: Unknown model: ${e.model}. Use /providers to see available models.`}case"gh_run_list":{let n=Math.min(e.limit||10,30),o=["run","list","--limit",String(n),"--json","databaseId,status,conclusion,name,headBranch,createdAt,updatedAt,event"];e.workflow&&o.push("--workflow",e.workflow),e.branch&&o.push("--branch",e.branch),e.status&&o.push("--status",e.status);try{let{stdout:r}=await ae(`gh ${o.join(" ")}`,{cwd:process.cwd(),timeout:3e4}),i=JSON.parse(r||"[]");return i.length===0?"No workflow runs found.":i.map(l=>{let u=l.conclusion||l.status||"unknown",d=u==="success"?"\u2713":u==="failure"?"\u2717":u==="in_progress"?"\u283F":"\u25CB",p=l.updatedAt?new Date(l.updatedAt).toISOString().slice(0,16).replace("T"," "):"";return`${d} [${l.databaseId}] ${l.name} \xB7 ${l.headBranch} \xB7 ${u} \xB7 ${p}`}).join(`
244
+ `+i()),JSON.stringify(d,null,2))}default:return`ERROR: Unknown task_list action: ${e.action}. Use: create, update, get`}}case"spawn_agents":{let{executeSpawnAgents:o}=dl();return o(e)}case"switch_model":{let{setActiveModel:o,getActiveProviderName:n,getActiveModelId:r}=we();return o(e.model)?`Switched to ${n()}:${r()}`:`ERROR: Unknown model: ${e.model}. Use /providers to see available models.`}case"gh_run_list":{let o=Math.min(e.limit||10,30),n=["run","list","--limit",String(o),"--json","databaseId,status,conclusion,name,headBranch,createdAt,updatedAt,event"];e.workflow&&n.push("--workflow",e.workflow),e.branch&&n.push("--branch",e.branch),e.status&&n.push("--status",e.status);try{let{stdout:r}=await ie(`gh ${n.join(" ")}`,{cwd:process.cwd(),timeout:3e4}),i=JSON.parse(r||"[]");return i.length===0?"No workflow runs found.":i.map(l=>{let u=l.conclusion||l.status||"unknown",d=u==="success"?"\u2713":u==="failure"?"\u2717":u==="in_progress"?"\u283F":"\u25CB",f=l.updatedAt?new Date(l.updatedAt).toISOString().slice(0,16).replace("T"," "):"";return`${d} [${l.databaseId}] ${l.name} \xB7 ${l.headBranch} \xB7 ${u} \xB7 ${f}`}).join(`
230
245
  `)}catch(r){let i=(r.stderr||r.message||"").toString();return i.includes("not found")||i.includes("not logged")?"ERROR: gh CLI not found or not authenticated. Run: gh auth login":`ERROR: ${i.split(`
231
- `)[0]}`}}case"gh_run_view":{if(!e.run_id)return"ERROR: run_id is required";try{if(e.log){let{stdout:i}=await ae(`gh run view ${e.run_id} --log`,{cwd:process.cwd(),timeout:6e4,maxBuffer:5242880});return i.substring(0,8e3)+(i.length>8e3?`
232
- ...(truncated)`:"")}let{stdout:n}=await ae(`gh run view ${e.run_id} --json status,conclusion,name,headBranch,createdAt,updatedAt,jobs`,{cwd:process.cwd(),timeout:3e4}),o=JSON.parse(n),r=[`Run: ${o.name} [${e.run_id}]`,`Branch: ${o.headBranch} Status: ${o.conclusion||o.status}`,`Started: ${o.createdAt} Finished: ${o.updatedAt||"\u2014"}`,"","Jobs:"];for(let i of o.jobs||[]){let c=i.conclusion==="success"?"\u2713":i.conclusion==="failure"?"\u2717":"\u25CB";r.push(` ${c} ${i.name} (${i.conclusion||i.status})`);for(let l of i.steps||[]){if(l.conclusion==="failure"||l.conclusion==="skipped")continue;let u=l.conclusion==="success"?" \u2713":l.conclusion==="failure"?" \u2717":" \u25CB";r.push(` ${u} ${l.name}`)}}return r.join(`
233
- `)}catch(n){return`ERROR: ${(n.stderr||n.message||"").toString().split(`
234
- `)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";let{confirm:n}=We(),o=e.branch||await pc()||"main",r=e.inputs?Object.entries(e.inputs).map(([l,u])=>`-f ${l}=${u}`).join(" "):"",i=`gh workflow run ${e.workflow} --ref ${o} ${r}`.trim();if(console.log(`
235
- ${I.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${o}${I.reset}`),!await n(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await ae(i,{cwd:process.cwd(),timeout:3e4}),`Workflow "${e.workflow}" triggered on branch "${o}". Check status with gh_run_list.`}catch(l){return`ERROR: ${(l.stderr||l.message||"").toString().split(`
236
- `)[0]}`}}case"k8s_pods":{let n=e.namespace?`-n ${e.namespace}`:"-A",o=e.label?`-l ${e.label}`:"",r=Sn(`get pods ${n} ${o} -o wide`.trim(),e);try{let{stdout:i,stderr:c}=await ae(r,{timeout:3e4,maxBuffer:2097152});return(i||c||"(no pods)").trim()}catch(i){let c=(i.stderr||i.message||"").toString().split(`
237
- `)[0];return c.includes("command not found")?"ERROR: kubectl not found. Install kubectl or provide a server with kubectl.":`ERROR: ${c}`}}case"k8s_logs":{if(!e.pod)return"ERROR: pod is required";let n=e.namespace||"default",o=e.tail||100,r=`logs ${e.pod} -n ${n} --tail=${o}`;e.since&&(r+=` --since=${e.since}`),e.container&&(r+=` -c ${e.container}`);let i=Sn(r,e);try{let{stdout:c,stderr:l}=await ae(i,{timeout:6e4,maxBuffer:5242880}),u=(c||l||"(no logs)").trim();return u.substring(0,2e4)+(u.length>2e4?`
246
+ `)[0]}`}}case"gh_run_view":{if(!e.run_id)return"ERROR: run_id is required";try{if(e.log){let{stdout:i}=await ie(`gh run view ${e.run_id} --log`,{cwd:process.cwd(),timeout:6e4,maxBuffer:5242880});return i.substring(0,8e3)+(i.length>8e3?`
247
+ ...(truncated)`:"")}let{stdout:o}=await ie(`gh run view ${e.run_id} --json status,conclusion,name,headBranch,createdAt,updatedAt,jobs`,{cwd:process.cwd(),timeout:3e4}),n=JSON.parse(o),r=[`Run: ${n.name} [${e.run_id}]`,`Branch: ${n.headBranch} Status: ${n.conclusion||n.status}`,`Started: ${n.createdAt} Finished: ${n.updatedAt||"\u2014"}`,"","Jobs:"];for(let i of n.jobs||[]){let c=i.conclusion==="success"?"\u2713":i.conclusion==="failure"?"\u2717":"\u25CB";r.push(` ${c} ${i.name} (${i.conclusion||i.status})`);for(let l of i.steps||[]){if(l.conclusion==="failure"||l.conclusion==="skipped")continue;let u=l.conclusion==="success"?" \u2713":l.conclusion==="failure"?" \u2717":" \u25CB";r.push(` ${u} ${l.name}`)}}return r.join(`
248
+ `)}catch(o){return`ERROR: ${(o.stderr||o.message||"").toString().split(`
249
+ `)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";let{confirm:o}=Ae(),n=e.branch||await Ml()||"main",r=e.inputs?Object.entries(e.inputs).map(([l,u])=>`-f ${l}=${u}`).join(" "):"",i=`gh workflow run ${e.workflow} --ref ${n} ${r}`.trim();if(console.log(`
250
+ ${F.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${n}${F.reset}`),!await o(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await ie(i,{cwd:process.cwd(),timeout:3e4}),`Workflow "${e.workflow}" triggered on branch "${n}". Check status with gh_run_list.`}catch(l){return`ERROR: ${(l.stderr||l.message||"").toString().split(`
251
+ `)[0]}`}}case"k8s_pods":{let o=e.namespace?`-n ${e.namespace}`:"-A",n=e.label?`-l ${e.label}`:"",r=Zn(`get pods ${o} ${n} -o wide`.trim(),e);try{let{stdout:i,stderr:c}=await ie(r,{timeout:3e4,maxBuffer:2097152});return(i||c||"(no pods)").trim()}catch(i){let c=(i.stderr||i.message||"").toString().split(`
252
+ `)[0];return c.includes("command not found")?"ERROR: kubectl not found. Install kubectl or provide a server with kubectl.":`ERROR: ${c}`}}case"k8s_logs":{if(!e.pod)return"ERROR: pod is required";let o=e.namespace||"default",n=e.tail||100,r=`logs ${e.pod} -n ${o} --tail=${n}`;e.since&&(r+=` --since=${e.since}`),e.container&&(r+=` -c ${e.container}`);let i=Zn(r,e);try{let{stdout:c,stderr:l}=await ie(i,{timeout:6e4,maxBuffer:5242880}),u=(c||l||"(no logs)").trim();return u.substring(0,2e4)+(u.length>2e4?`
238
253
  ...(truncated)`:"")}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
239
- `)[0]}`}}case"k8s_exec":{if(!e.pod)return"ERROR: pod is required";if(!e.command)return"ERROR: command is required";let n=e.namespace||"default";if(console.log(`
240
- ${I.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${n})${I.reset}`),console.log(`${I.dim} Command: ${e.command}${I.reset}`),!await Ge(" Execute in pod?"))return"CANCELLED: User declined.";let r=`exec ${e.pod} -n ${n}`;e.container&&(r+=` -c ${e.container}`),r+=` -- sh -c ${JSON.stringify(e.command)}`;let i=Sn(r,e);try{let{stdout:c,stderr:l}=await ae(i,{timeout:6e4,maxBuffer:2097152});return(c||l||"(no output)").trim()}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
241
- `)[0]}`}}case"k8s_apply":{if(!e.file)return"ERROR: file is required";let n=!!e.dry_run;if(!n){let i=e.file;if(console.log(`
242
- ${I.yellow} \u26A0 kubectl apply: ${i}${e.namespace?` (ns: ${e.namespace})`:""}${I.reset}`),!await Ge(" Apply to cluster?"))return"CANCELLED: User declined."}let o=`apply -f ${e.file}`;e.namespace&&(o+=` -n ${e.namespace}`),n&&(o+=" --dry-run=client");let r=Sn(o,e);try{let{stdout:i,stderr:c}=await ae(r,{timeout:12e4,maxBuffer:2097152});return(i||c||"(no output)").trim()}catch(i){return`ERROR: ${(i.stderr||i.message||"").toString().split(`
243
- `)[0]}`}}case"k8s_rollout":{if(!e.action)return"ERROR: action is required";if(!e.deployment)return"ERROR: deployment is required";let n=e.namespace||"default";if(e.action==="restart"||e.action==="undo"){let c=e.action==="restart"?"Rolling restart":"Rollback (undo)";if(console.log(`
244
- ${I.yellow} \u26A0 ${c}: deployment/${e.deployment} (ns: ${n})${I.reset}`),!await Ge(` ${c}?`))return"CANCELLED: User declined."}let r=`rollout ${e.action} deployment/${e.deployment} -n ${n}`,i=Sn(r,e);try{let{stdout:c,stderr:l}=await ae(i,{timeout:12e4,maxBuffer:2097152});return(c||l||"(no output)").trim()}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
245
- `)[0]}`}}case"brain_write":{if(!e.name)return"ERROR: name is required";if(!e.content)return"ERROR: content is required";if(!e.mode)return"ERROR: mode is required (create, update, append)";let{writeDocument:n,readDocument:o}=_n(),{name:r,content:i,mode:c}=e;if(c==="create"&&o(r).content)return`ERROR: Document "${r}" already exists. Use mode "update" to overwrite.`;if(c==="append"){let l=o(r),u=l.content?l.content+`
246
-
247
- `+i:i;return n(r,u),`Appended to brain document: ${r}.md`}return n(r,i),`${c==="create"?"Created":"Updated"} brain document: ${r}.md`}case"ssh_exec":{if(!e.server)return"ERROR: server is required";if(!e.command)return"ERROR: command is required";let n;try{n=ze(e.server)}catch(h){return`ERROR: ${h.message}`}let o=e.command,r=!!e.sudo,i=(e.timeout||30)*1e3;if(/\b(rm|rmdir|mv|cp|chmod|chown|dd|mkfs|systemctl\s+(start|stop|restart|reload|enable|disable)|dnf\s+(install|remove|update|upgrade)|yum\s+(install|remove)|apt(-get)?\s+(install|remove|purge)|pip\s+install|pip3\s+install|firewall-cmd\s+--permanent|semanage|setsebool|passwd|userdel|useradd|nginx\s+-s\s+(reload|stop)|service\s+\w+\s+(start|stop|restart))\b/.test(o)){let h=n.user?`${n.user}@${n.host}`:n.host;if(console.log(`
248
- ${I.yellow} \u26A0 Remote command on ${h}: ${o}${I.reset}`),!await Ge(" Execute on remote server?"))return"CANCELLED: User declined to execute remote command."}let{stdout:l,stderr:u,exitCode:d,error:p}=await pt(n,o,{timeout:i,sudo:r}),f=[l,u].filter(Boolean).join(`
254
+ `)[0]}`}}case"k8s_exec":{if(!e.pod)return"ERROR: pod is required";if(!e.command)return"ERROR: command is required";let o=e.namespace||"default";if(console.log(`
255
+ ${F.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${o})${F.reset}`),console.log(`${F.dim} Command: ${e.command}${F.reset}`),!await Ve(" Execute in pod?"))return"CANCELLED: User declined.";let r=`exec ${e.pod} -n ${o}`;e.container&&(r+=` -c ${e.container}`),r+=` -- sh -c ${JSON.stringify(e.command)}`;let i=Zn(r,e);try{let{stdout:c,stderr:l}=await ie(i,{timeout:6e4,maxBuffer:2097152});return(c||l||"(no output)").trim()}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
256
+ `)[0]}`}}case"k8s_apply":{if(!e.file)return"ERROR: file is required";let o=!!e.dry_run;if(!o){let i=e.file;if(console.log(`
257
+ ${F.yellow} \u26A0 kubectl apply: ${i}${e.namespace?` (ns: ${e.namespace})`:""}${F.reset}`),!await Ve(" Apply to cluster?"))return"CANCELLED: User declined."}let n=`apply -f ${e.file}`;e.namespace&&(n+=` -n ${e.namespace}`),o&&(n+=" --dry-run=client");let r=Zn(n,e);try{let{stdout:i,stderr:c}=await ie(r,{timeout:12e4,maxBuffer:2097152});return(i||c||"(no output)").trim()}catch(i){return`ERROR: ${(i.stderr||i.message||"").toString().split(`
258
+ `)[0]}`}}case"k8s_rollout":{if(!e.action)return"ERROR: action is required";if(!e.deployment)return"ERROR: deployment is required";let o=e.namespace||"default";if(e.action==="restart"||e.action==="undo"){let c=e.action==="restart"?"Rolling restart":"Rollback (undo)";if(console.log(`
259
+ ${F.yellow} \u26A0 ${c}: deployment/${e.deployment} (ns: ${o})${F.reset}`),!await Ve(` ${c}?`))return"CANCELLED: User declined."}let r=`rollout ${e.action} deployment/${e.deployment} -n ${o}`,i=Zn(r,e);try{let{stdout:c,stderr:l}=await ie(i,{timeout:12e4,maxBuffer:2097152});return(c||l||"(no output)").trim()}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
260
+ `)[0]}`}}case"brain_write":{if(!e.name)return"ERROR: name is required";if(!e.content)return"ERROR: content is required";if(!e.mode)return"ERROR: mode is required (create, update, append)";let{writeDocument:o,readDocument:n}=Xn(),{name:r,content:i,mode:c}=e;if(c==="create"&&n(r).content)return`ERROR: Document "${r}" already exists. Use mode "update" to overwrite.`;if(c==="append"){let l=n(r),u=l.content?l.content+`
261
+
262
+ `+i:i;return o(r,u),`Appended to brain document: ${r}.md`}return o(r,i),`${c==="create"?"Created":"Updated"} brain document: ${r}.md`}case"ssh_exec":{if(!e.server)return"ERROR: server is required";if(!e.command)return"ERROR: command is required";let o;try{o=Ke(e.server)}catch(h){return`ERROR: ${h.message}`}let n=e.command,r=!!e.sudo,i=(e.timeout||30)*1e3;if(/\b(rm|rmdir|mv|cp|chmod|chown|dd|mkfs|systemctl\s+(start|stop|restart|reload|enable|disable)|dnf\s+(install|remove|update|upgrade)|yum\s+(install|remove)|apt(-get)?\s+(install|remove|purge)|pip\s+install|pip3\s+install|firewall-cmd\s+--permanent|semanage|setsebool|passwd|userdel|useradd|nginx\s+-s\s+(reload|stop)|service\s+\w+\s+(start|stop|restart))\b/.test(n)){let h=o.user?`${o.user}@${o.host}`:o.host;if(console.log(`
263
+ ${F.yellow} \u26A0 Remote command on ${h}: ${n}${F.reset}`),!await Ve(" Execute on remote server?"))return"CANCELLED: User declined to execute remote command."}let{stdout:l,stderr:u,exitCode:d,error:f}=await Me(o,n,{timeout:i,sudo:r}),m=[l,u].filter(Boolean).join(`
249
264
  `).trim();return d!==0?`EXIT ${d}
250
- ${p||f||"(no output)"}`:f||"(command completed, no output)"}case"ssh_upload":{if(!e.server||!e.local_path||!e.remote_path)return"ERROR: server, local_path, and remote_path are required";let n;try{n=ze(e.server)}catch(i){return`ERROR: ${i.message}`}let o=n.user?`${n.user}@${n.host}`:n.host;if(console.log(`
251
- ${I.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${o}:${e.remote_path}${I.reset}`),!await Ge(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{return await Zp(n,e.local_path,e.remote_path)}catch(i){return`ERROR: ${i.message}`}}case"ssh_download":{if(!e.server||!e.remote_path||!e.local_path)return"ERROR: server, remote_path, and local_path are required";let n;try{n=ze(e.server)}catch(o){return`ERROR: ${o.message}`}try{return await em(n,e.remote_path,e.local_path)}catch(o){return`ERROR: ${o.message}`}}case"service_manage":{if(!e.service)return"ERROR: service is required";if(!e.action)return"ERROR: action is required";let n=["status","start","stop","restart","reload","enable","disable"];if(!n.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${n.join(", ")}`;let o=!e.server||e.server==="local"||e.server==="localhost",r=e.action==="status",i=null;if(!o)try{i=ze(e.server)}catch(l){return`ERROR: ${l.message}`}if(!r){let l=o?"local machine":i.user?`${i.user}@${i.host}`:i.host;if(console.log(`
252
- ${I.yellow} \u26A0 Service: systemctl ${e.action} ${e.service} on ${l}${I.reset}`),!await Ge(" Execute?"))return"CANCELLED: User declined service action."}let c=`systemctl ${e.action} ${e.service}`;if(o){let u=e.action!=="status"?`sudo ${c}`:c;try{let{stdout:d,stderr:p}=await ae(u,{timeout:15e3});return(d||p||`systemctl ${e.action} ${e.service}: OK`).trim()}catch(d){let p=(d.stderr||d.message||"").toString().trim();return/not found|loaded.*not-found/i.test(p)?`ERROR: Service "${e.service}" not found. Check: systemctl list-units --type=service`:`EXIT ${d.code||1}
253
- ${p}`}}else{let{stdout:l,stderr:u,exitCode:d,error:p}=await pt(i,c,{timeout:15e3,sudo:!0}),f=[l,u].filter(Boolean).join(`
254
- `).trim();return d!==0?/not found|loaded.*not-found/i.test(f)?`ERROR: Service "${e.service}" not found on ${i.host}. Check: ssh_exec to run "systemctl list-units --type=service"`:`EXIT ${d}
255
- ${p||f||"(no output)"}`:f||`systemctl ${e.action} ${e.service}: OK`}}case"service_logs":{if(!e.service)return"ERROR: service is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=e.lines||50,r=e.since?`--since "${e.since}"`:"",i=e.follow?"-f":"",c=`journalctl -u ${e.service} -n ${o} ${r} ${i} --no-pager`.trim().replace(/\s+/g," ");if(n)try{let{stdout:m,stderr:g}=await ae(c,{timeout:15e3});return(m||g||"(no log output)").trim()}catch(m){return`EXIT ${m.code||1}
256
- ${(m.stderr||m.message||"").toString().trim()}`}let l;try{l=ze(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:u,stderr:d,exitCode:p,error:f}=await pt(l,c,{timeout:2e4}),h=[u,d].filter(Boolean).join(`
257
- `).trim();return p!==0?`EXIT ${p}
258
- ${f||h||"(no output)"}`:h||"(no log output)"}case"container_list":{let n=!e.server||e.server==="local"||e.server==="localhost",r=`docker ps ${e.all?"-a":""} --format "table {{.ID}}\\t{{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"`.trim().replace(/\s+/g," ");if(n)try{let{stdout:f,stderr:h}=await ae(r,{timeout:1e4});return(f||h||"(no containers)").trim()}catch(f){return`EXIT ${f.code||1}
259
- ${(f.stderr||f.message||"").toString().trim()}`}let i;try{i=ze(e.server)}catch(f){return`ERROR: ${f.message}`}let{stdout:c,stderr:l,exitCode:u,error:d}=await pt(i,r,{timeout:15e3}),p=[c,l].filter(Boolean).join(`
265
+ ${f||m||"(no output)"}`:m||"(command completed, no output)"}case"ssh_upload":{if(!e.server||!e.local_path||!e.remote_path)return"ERROR: server, local_path, and remote_path are required";let o;try{o=Ke(e.server)}catch(i){return`ERROR: ${i.message}`}let n=o.user?`${o.user}@${o.host}`:o.host;if(console.log(`
266
+ ${F.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${n}:${e.remote_path}${F.reset}`),!await Ve(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{return await cg(o,e.local_path,e.remote_path)}catch(i){return`ERROR: ${i.message}`}}case"ssh_download":{if(!e.server||!e.remote_path||!e.local_path)return"ERROR: server, remote_path, and local_path are required";let o;try{o=Ke(e.server)}catch(n){return`ERROR: ${n.message}`}try{return await lg(o,e.remote_path,e.local_path)}catch(n){return`ERROR: ${n.message}`}}case"remote_agent":{let o=require("path").join(process.cwd(),".nex","servers.json"),n=null;try{n=JSON.parse(require("fs").readFileSync(o,"utf-8"))[e.server]||null}catch{}let r=n?`${n.user||"root"}@${n.host}`:e.server,i=n?.key?["-i",n.key]:[],c=e.project_path||n?.home||"~",l=e.model||"",d=["TMPFILE=$(mktemp /tmp/nexcode-XXXXXX.txt)",`echo "${Buffer.from(e.task).toString("base64")}" | base64 -d > "$TMPFILE"`,`cd "${c}" 2>/dev/null || true`,l?`nex-code --prompt-file "$TMPFILE" --auto --model "${l}" 2>&1`:'nex-code --prompt-file "$TMPFILE" --auto 2>&1',"EXIT_CODE=$?",'rm -f "$TMPFILE"',"exit $EXIT_CODE"].join(" && "),{spawnSync:f}=require("child_process"),m=f("ssh",[...i,"-o","StrictHostKeyChecking=no","-o","ConnectTimeout=10",r,`bash -c '${d}'`],{encoding:"utf-8",maxBuffer:10*1024*1024,timeout:3e5});if(m.error)return`ERROR: SSH connection failed: ${m.error.message}`;let h=(m.stdout||"")+(m.stderr||"");return m.status!==0?`Remote nex-code exited with code ${m.status}.
267
+ ${h.slice(-2e3)}`:h.slice(-5e3)||"Remote nex-code completed (no output)"}case"service_manage":{if(!e.service)return"ERROR: service is required";if(!e.action)return"ERROR: action is required";let o=["status","start","stop","restart","reload","enable","disable"];if(!o.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${o.join(", ")}`;let n=!e.server||e.server==="local"||e.server==="localhost",r=e.action==="status",i=null;if(!n)try{i=Ke(e.server)}catch(l){return`ERROR: ${l.message}`}if(!r){let l=n?"local machine":i.user?`${i.user}@${i.host}`:i.host;if(console.log(`
268
+ ${F.yellow} \u26A0 Service: systemctl ${e.action} ${e.service} on ${l}${F.reset}`),!await Ve(" Execute?"))return"CANCELLED: User declined service action."}let c=`systemctl ${e.action} ${e.service}`;if(n){let u=e.action!=="status"?`sudo ${c}`:c;try{let{stdout:d,stderr:f}=await ie(u,{timeout:15e3});return(d||f||`systemctl ${e.action} ${e.service}: OK`).trim()}catch(d){let f=(d.stderr||d.message||"").toString().trim();return/not found|loaded.*not-found/i.test(f)?`ERROR: Service "${e.service}" not found. Check: systemctl list-units --type=service`:`EXIT ${d.code||1}
269
+ ${f}`}}else{let{stdout:l,stderr:u,exitCode:d,error:f}=await Me(i,c,{timeout:15e3,sudo:!0}),m=[l,u].filter(Boolean).join(`
270
+ `).trim();return d!==0?/not found|loaded.*not-found/i.test(m)?`ERROR: Service "${e.service}" not found on ${i.host}. Check: ssh_exec to run "systemctl list-units --type=service"`:`EXIT ${d}
271
+ ${f||m||"(no output)"}`:m||`systemctl ${e.action} ${e.service}: OK`}}case"service_logs":{if(!e.service)return"ERROR: service is required";let o=!e.server||e.server==="local"||e.server==="localhost",n=e.lines||50,r=e.since?`--since "${e.since}"`:"",i=e.follow?"-f":"",c=`journalctl -u ${e.service} -n ${n} ${r} ${i} --no-pager`.trim().replace(/\s+/g," ");if(o)try{let{stdout:p,stderr:g}=await ie(c,{timeout:15e3});return(p||g||"(no log output)").trim()}catch(p){return`EXIT ${p.code||1}
272
+ ${(p.stderr||p.message||"").toString().trim()}`}let l;try{l=Ke(e.server)}catch(p){return`ERROR: ${p.message}`}let{stdout:u,stderr:d,exitCode:f,error:m}=await Me(l,c,{timeout:2e4}),h=[u,d].filter(Boolean).join(`
273
+ `).trim();return f!==0?`EXIT ${f}
274
+ ${m||h||"(no output)"}`:h||"(no log output)"}case"container_list":{let o=!e.server||e.server==="local"||e.server==="localhost",r=`docker ps ${e.all?"-a":""} --format "table {{.ID}}\\t{{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"`.trim().replace(/\s+/g," ");if(o)try{let{stdout:m,stderr:h}=await ie(r,{timeout:1e4});return(m||h||"(no containers)").trim()}catch(m){return`EXIT ${m.code||1}
275
+ ${(m.stderr||m.message||"").toString().trim()}`}let i;try{i=Ke(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:c,stderr:l,exitCode:u,error:d}=await Me(i,r,{timeout:15e3}),f=[c,l].filter(Boolean).join(`
260
276
  `).trim();return u!==0?`EXIT ${u}
261
- ${d||p}`:p||"(no containers)"}case"container_logs":{if(!e.container)return"ERROR: container is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=e.lines||50,r=e.since?`--since "${e.since}"`:"",i=`docker logs --tail ${o} ${r} ${e.container} 2>&1`.trim().replace(/\s+/g," ");if(n)try{let{stdout:h,stderr:m}=await ae(i,{timeout:15e3});return(h||m||"(no log output)").trim()}catch(h){return`EXIT ${h.code||1}
262
- ${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=ze(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:l,stderr:u,exitCode:d,error:p}=await pt(c,i,{timeout:2e4}),f=[l,u].filter(Boolean).join(`
277
+ ${d||f}`:f||"(no containers)"}case"container_logs":{if(!e.container)return"ERROR: container is required";let o=!e.server||e.server==="local"||e.server==="localhost",n=e.lines||50,r=e.since?`--since "${e.since}"`:"",i=`docker logs --tail ${n} ${r} ${e.container} 2>&1`.trim().replace(/\s+/g," ");if(o)try{let{stdout:h,stderr:p}=await ie(i,{timeout:15e3});return(h||p||"(no log output)").trim()}catch(h){return`EXIT ${h.code||1}
278
+ ${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=Ke(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:l,stderr:u,exitCode:d,error:f}=await Me(c,i,{timeout:2e4}),m=[l,u].filter(Boolean).join(`
263
279
  `).trim();return d!==0?`EXIT ${d}
264
- ${p||f}`:f||"(no log output)"}case"container_exec":{if(!e.container)return"ERROR: container is required";if(!e.command)return"ERROR: command is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=/^(cat|ls|echo|env|printenv|df|du|ps|id|whoami|uname|hostname|date|pwd|which|find\s|head\s|tail\s|grep\s|curl\s+-[A-Za-z]*G|curl\s+https?:\/\/[^\s]+$)/;if(!s.autoConfirm&&!o.test(e.command.trim())){let h=n?"local":e.server;if(console.log(`
265
- ${I.yellow} \u26A0 docker exec in ${e.container} on ${h}: ${e.command}${I.reset}`),!await Ge(" Execute?"))return"CANCELLED: User declined."}let i=`docker exec ${e.container} sh -c ${JSON.stringify(e.command)}`;if(n)try{let{stdout:h,stderr:m}=await ae(i,{timeout:3e4});return(h||m||"(no output)").trim()}catch(h){return`EXIT ${h.code||1}
266
- ${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=ze(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:l,stderr:u,exitCode:d,error:p}=await pt(c,i,{timeout:35e3}),f=[l,u].filter(Boolean).join(`
280
+ ${f||m}`:m||"(no log output)"}case"container_exec":{if(!e.container)return"ERROR: container is required";if(!e.command)return"ERROR: command is required";let o=!e.server||e.server==="local"||e.server==="localhost",n=/^(cat|ls|echo|env|printenv|df|du|ps|id|whoami|uname|hostname|date|pwd|which|find\s|head\s|tail\s|grep\s|curl\s+-[A-Za-z]*G|curl\s+https?:\/\/[^\s]+$)/;if(!s.autoConfirm&&!n.test(e.command.trim())){let h=o?"local":e.server;if(console.log(`
281
+ ${F.yellow} \u26A0 docker exec in ${e.container} on ${h}: ${e.command}${F.reset}`),!await Ve(" Execute?"))return"CANCELLED: User declined."}let i=`docker exec ${e.container} sh -c ${JSON.stringify(e.command)}`;if(o)try{let{stdout:h,stderr:p}=await ie(i,{timeout:3e4});return(h||p||"(no output)").trim()}catch(h){return`EXIT ${h.code||1}
282
+ ${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=Ke(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:l,stderr:u,exitCode:d,error:f}=await Me(c,i,{timeout:35e3}),m=[l,u].filter(Boolean).join(`
267
283
  `).trim();return d!==0?`EXIT ${d}
268
- ${p||f}`:f||"(no output)"}case"container_manage":{if(!e.container)return"ERROR: container is required";if(!e.action)return"ERROR: action is required";let n=["start","stop","restart","remove","inspect"];if(!n.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${n.join(", ")}`;let o=!e.server||e.server==="local"||e.server==="localhost";if(!(e.action==="inspect")&&!s.autoConfirm){let m=o?"local":e.server;if(console.log(`
269
- ${I.yellow} \u26A0 docker ${e.action} ${e.container} on ${m}${I.reset}`),!await Ge(" Execute?"))return"CANCELLED: User declined."}let i=e.action==="remove"?"rm":e.action,c=e.action==="inspect"?`docker inspect ${e.container}`:`docker ${i} ${e.container}`;if(o)try{let{stdout:m,stderr:g}=await ae(c,{timeout:3e4});return(m||g||`docker ${e.action} ${e.container}: OK`).trim()}catch(m){return`EXIT ${m.code||1}
270
- ${(m.stderr||m.message||"").toString().trim()}`}let l;try{l=ze(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:u,stderr:d,exitCode:p,error:f}=await pt(l,c,{timeout:35e3}),h=[u,d].filter(Boolean).join(`
271
- `).trim();return p!==0?`EXIT ${p}
272
- ${f||h}`:h||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...tm(e.config),...e},delete e.config,delete e._name}catch(m){return`ERROR: ${m.message}`}if(!e.server)return'ERROR: server is required (or use config: "<name>")';if(!e.local_path)return"ERROR: local_path is required";if(!e.remote_path)return"ERROR: remote_path is required";let n;try{n=ze(e.server)}catch(m){return`ERROR: ${m.message}`}let o=n.user?`${n.user}@${n.host}`:n.host,r=n.port&&Number(n.port)!==22?`-e "ssh -p ${n.port}"`:"",i=n.key?`-e "ssh -i ${n.key.replace(/^~/,require("os").homedir())}"`:"",c=n.key?`-e "ssh -i ${n.key.replace(/^~/,require("os").homedir())}${n.port&&Number(n.port)!==22?` -p ${n.port}`:""}"`:r,l=(e.exclude||[]).map(m=>`--exclude="${m}"`).join(" "),u=e.dry_run?"--dry-run":"",d=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`,p=`rsync -avz --delete ${u} ${l} ${c} ${d} ${o}:${e.remote_path}`.trim().replace(/\s+/g," ");if(!e.dry_run&&!s.autoConfirm&&(console.log(`
273
- ${I.yellow} \u26A0 Deploy: ${d} \u2192 ${o}:${e.remote_path}${I.reset}`),e.deploy_script&&console.log(`${I.yellow} Then run: ${e.deploy_script}${I.reset}`),!await Ge(" Proceed with deployment?")))return"CANCELLED: User declined.";let f="";try{let{stdout:m,stderr:g}=await ae(p,{timeout:12e4});f=(m||g||"").trim()}catch(m){return`ERROR (rsync): ${(m.stderr||m.message||"").toString().trim()}`}if(e.dry_run)return`DRY RUN:
274
- ${f||"(nothing to sync)"}`;let h="";if(e.deploy_script){let{stdout:m,stderr:g,exitCode:y,error:$}=await pt(n,e.deploy_script,{timeout:6e4}),x=[m,g].filter(Boolean).join(`
275
- `).trim();if(y!==0)return`rsync OK
276
-
277
- ERROR (deploy_script, exit ${y}):
278
- ${$||x}`;h=`
279
-
280
- Remote script output:
281
- ${x||"(no output)"}`}return`Deployed ${d} \u2192 ${o}:${e.remote_path}
282
- ${f}${h}`.trim()}default:return`ERROR: Unknown tool: ${t}`}}async function um(t,e,s={}){let n=s.silent?null:Jp(t,e);if(!n)return gc(t,e,s);let o=new $c(n);o.start();try{let r=await gc(t,e,s);return o.stop(),r}catch(r){throw o.stop(),r}}bc.exports={TOOL_DEFINITIONS:lm,executeTool:um,resolvePath:Se,autoFixPath:ys,autoFixEdit:wc,enrichBashError:yc,cancelPendingAskUser:im,setAskUserHandler:am}});var _c=L((Sy,xc)=>{var{loadServerProfiles:Ko}=Ht(),zo={almalinux9:["Package manager: dnf (NOT apt). Install: dnf install <pkg>. Update: dnf update.","Service manager: systemctl. Logs: journalctl -u <service> -n 50.","Firewall: firewalld. Check: firewall-cmd --list-all. Open port: firewall-cmd --permanent --add-port=PORT/tcp && firewall-cmd --reload.","SELinux is active by default. Check: getenforce. Diagnose: ausearch -m avc -ts recent | audit2why. Fix context: restorecon -Rv /path.","Nginx config: /etc/nginx/. Test: nginx -t. Reload: systemctl reload nginx.","Process list: ps aux. Ports: ss -tuln.","Python: python3. Pip: pip3. Virtualenv: python3 -m venv."],almalinux8:["Package manager: dnf (NOT apt). Install: dnf install <pkg>. Update: dnf update.","Service manager: systemctl. Logs: journalctl -u <service> -n 50.","Firewall: firewalld. Check: firewall-cmd --list-all.","SELinux is active by default. Check: getenforce. Diagnose: ausearch -m avc -ts recent."],ubuntu:["Package manager: apt. Install: apt install <pkg>. Update: apt update && apt upgrade.","Service manager: systemctl. Logs: journalctl -u <service> -n 50.","Firewall: ufw. Status: ufw status. Allow port: ufw allow PORT/tcp.","SELinux NOT active by default (AppArmor instead). Check: aa-status."],debian:["Package manager: apt. Install: apt install <pkg>. Update: apt update && apt upgrade.","Service manager: systemctl. Logs: journalctl -u <service> -n 50.","Firewall: ufw or iptables."],macos:["Package manager: Homebrew (brew). Install: brew install <pkg>. Update: brew update && brew upgrade.","Service manager: launchctl (NOT systemctl). Start: brew services start <name>. List: brew services list.",`No systemd. No journalctl. Use: log show --predicate 'process == "nginx"' --last 1h instead.`,"Firewall: macOS built-in (pfctl or System Settings). Check: pfctl -s rules.","Process list: ps aux. Ports: lsof -i -n -P | grep LISTEN."]};function dm(){let t=Ko();if(Object.keys(t).length===0)return null;let s=["## Remote Servers (.nex/servers.json)"];s.push(""),s.push("Available server profiles (use with ssh_exec, ssh_upload, ssh_download, service_manage, service_logs, container_list, container_logs, container_exec, container_manage, deploy):");for(let[o,r]of Object.entries(t)){let i=r.user?`${r.user}@${r.host}`:r.host,c=r.port&&Number(r.port)!==22?`:${r.port}`:"",l=r.os?` \u2014 OS: ${r.os}`:"",u=r.sudo?", sudo available":"";s.push(`- **${o}**: ${i}${c}${l}${u}`)}let n=new Set;for(let o of Object.values(t))o.os&&zo[o.os]&&n.add(o.os);if(n.size>0){s.push("");for(let o of n){let r={almalinux9:"AlmaLinux 9",almalinux8:"AlmaLinux 8",ubuntu:"Ubuntu",debian:"Debian",macos:"macOS"}[o]||o;s.push(`### ${r} Notes`);for(let i of zo[o])s.push(`- ${i}`)}}return s.join(`
283
- `)}function fm(t){let e=Ko();return Object.values(e).some(s=>s.os&&s.os.startsWith(t))}function pm(){return Object.keys(Ko())}xc.exports={getServerContext:dm,hasServerOS:fm,getProfileNames:pm,OS_HINTS:zo}});var xs=L((Ey,Sc)=>{var Fe=require("fs").promises,kc=require("fs"),_e=require("path"),ws=require("util").promisify(require("child_process").exec),{C:Ke}=de(),{getMergeConflicts:vc}=St(),{getServerContext:mm}=_c(),hm=new Set(["node_modules",".git",".svn","dist","build","coverage",".nyc_output","__pycache__",".DS_Store",".next",".nuxt",".turbo",".cache","vendor","tmp","temp"]);function gm(t){try{return kc.readFileSync(t,"utf-8").split(`
284
- `).map(s=>s.trim()).filter(s=>s&&!s.startsWith("#")&&!s.startsWith("!")).map(s=>s.replace(/\/$/,""))}catch{return[]}}function $m(t,e){for(let s of e)if(s===t||s.includes("*")&&new RegExp("^"+s.replace(/\./g,"\\.").replace(/\*/g,".*")+"$").test(t))return!0;return!1}function ym(t,{maxDepth:e=3,maxFiles:s=200,giPatterns:n=[]}={}){let o=_e.join(t,".gitignore"),r=[...n,...gm(o)],i=0,c=[_e.basename(t)+"/"];function l(u,d,p){if(p>e||i>=s)return;let f;try{f=kc.readdirSync(u,{withFileTypes:!0})}catch{return}f.sort((m,g)=>m.isDirectory()!==g.isDirectory()?m.isDirectory()?-1:1:m.name.localeCompare(g.name));let h=f.filter(m=>!(hm.has(m.name)||m.name.startsWith(".")&&m.name!==".env.example"||$m(m.name,r)));for(let m=0;m<h.length;m++){if(i>=s){c.push(`${d}\u2514\u2500\u2500 \u2026 (truncated)`);break}let g=h[m],y=m===h.length-1,$=y?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",x=d+(y?" ":"\u2502 "),S=g.isDirectory()?g.name+"/":g.name;c.push(`${d}${$}${S}`),i++,g.isDirectory()&&l(_e.join(u,g.name),x,p+1)}}return l(t,"",1),c.join(`
285
- `)}var Yo=new Map,zt=new Map,bs=null,wm=3e4;async function mt(t){try{return await t()}catch{return null}}async function bm(){if(!bs||Date.now()>bs)return!1;let t=[_e.join(process.cwd(),"package.json"),_e.join(process.cwd(),"README.md"),_e.join(process.cwd(),".gitignore")];for(let e of t)try{let s=await Fe.stat(e),n=zt.get(e);if(!n||s.mtimeMs!==n)return!1}catch{if(zt.has(e))return!1}try{let e=_e.join(process.cwd(),".git","HEAD"),s=await Fe.stat(e),n=zt.get(e);if(!n||s.mtimeMs!==n)return!1}catch{}return!0}async function xm(){let t=[_e.join(process.cwd(),"package.json"),_e.join(process.cwd(),"README.md"),_e.join(process.cwd(),".gitignore"),_e.join(process.cwd(),".git","HEAD")];for(let e of t)try{let s=await Fe.stat(e);zt.set(e,s.mtimeMs)}catch{zt.delete(e)}}async function _m(t){let e="fileContext",s=Yo.get(e),n=!1;if(s&&await bm()&&(n=!0),!n){let u=[],d=_e.join(t,"package.json");if(await mt(()=>Fe.access(d).then(()=>!0).catch(()=>!1)))try{let y=await Fe.readFile(d,"utf-8"),$=JSON.parse(y),x={name:$.name,version:$.version};$.scripts&&(x.scripts=Object.keys($.scripts).slice(0,15)),$.dependencies&&(x.deps=Object.keys($.dependencies).length),$.devDependencies&&(x.devDeps=Object.keys($.devDependencies).length),u.push(`PACKAGE: ${JSON.stringify(x)}`)}catch{}let f=_e.join(t,"README.md");if(await mt(()=>Fe.access(f).then(()=>!0).catch(()=>!1))){let $=(await Fe.readFile(f,"utf-8")).split(`
284
+ ${f||m}`:m||"(no output)"}case"container_manage":{if(!e.container)return"ERROR: container is required";if(!e.action)return"ERROR: action is required";let o=["start","stop","restart","remove","inspect"];if(!o.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${o.join(", ")}`;let n=!e.server||e.server==="local"||e.server==="localhost";if(!(e.action==="inspect")&&!s.autoConfirm){let p=n?"local":e.server;if(console.log(`
285
+ ${F.yellow} \u26A0 docker ${e.action} ${e.container} on ${p}${F.reset}`),!await Ve(" Execute?"))return"CANCELLED: User declined."}let i=e.action==="remove"?"rm":e.action,c=e.action==="inspect"?`docker inspect ${e.container}`:`docker ${i} ${e.container}`;if(n)try{let{stdout:p,stderr:g}=await ie(c,{timeout:3e4});return(p||g||`docker ${e.action} ${e.container}: OK`).trim()}catch(p){return`EXIT ${p.code||1}
286
+ ${(p.stderr||p.message||"").toString().trim()}`}let l;try{l=Ke(e.server)}catch(p){return`ERROR: ${p.message}`}let{stdout:u,stderr:d,exitCode:f,error:m}=await Me(l,c,{timeout:35e3}),h=[u,d].filter(Boolean).join(`
287
+ `).trim();return f!==0?`EXIT ${f}
288
+ ${m||h}`:h||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...ug(e.config),...e},delete e.config,delete e._name}catch(d){return`ERROR: ${d.message}`}if(!e.server)return'ERROR: server is required (or use config: "<name>")';if(!e.remote_path)return"ERROR: remote_path is required";let o=e.method||"rsync";if(o==="rsync"&&!e.local_path)return"ERROR: local_path is required for rsync method";let n;try{n=Ke(e.server)}catch(d){return`ERROR: ${d.message}`}let r=n.user?`${n.user}@${n.host}`:n.host;if(!e.dry_run&&!s.autoConfirm){if(o==="git"){let f=e.branch?` (branch: ${e.branch})`:"";console.log(`
289
+ ${F.yellow} \u26A0 Deploy [git pull]: ${r}:${e.remote_path}${f}${F.reset}`)}else{let f=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`;console.log(`
290
+ ${F.yellow} \u26A0 Deploy [rsync]: ${f} \u2192 ${r}:${e.remote_path}${F.reset}`)}if(e.deploy_script&&console.log(`${F.yellow} Then run: ${e.deploy_script}${F.reset}`),e.health_check&&console.log(`${F.yellow} Health check: ${e.health_check}${F.reset}`),!await Ve(" Proceed with deployment?"))return"CANCELLED: User declined."}let i="";if(o==="git"){let d=e.branch?`cd ${e.remote_path} && git fetch origin && git checkout ${e.branch} && git pull origin ${e.branch}`:`cd ${e.remote_path} && git pull`;if(e.dry_run)return`DRY RUN [git]: would run on ${r}:
291
+ ${d}${e.deploy_script?`
292
+ ${e.deploy_script}`:""}`;let{stdout:f,stderr:m,exitCode:h,error:p}=await Me(n,d,{timeout:12e4});if(i=[f,m].filter(Boolean).join(`
293
+ `).trim(),h!==0)return`ERROR (git pull, exit ${h}):
294
+ ${p||i}`}else{let d=n.key?`-e "ssh -i ${n.key.replace(/^~/,require("os").homedir())}${n.port&&Number(n.port)!==22?` -p ${n.port}`:""}"`:n.port&&Number(n.port)!==22?`-e "ssh -p ${n.port}"`:"",f=(e.exclude||[]).map(g=>`--exclude="${g}"`).join(" "),m=e.dry_run?"--dry-run":"",h=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`,p=`rsync -avz --delete ${m} ${f} ${d} ${h} ${r}:${e.remote_path}`.trim().replace(/\s+/g," ");try{let{stdout:g,stderr:$}=await ie(p,{timeout:12e4});i=(g||$||"").trim()}catch(g){return`ERROR (rsync): ${(g.stderr||g.message||"").toString().trim()}`}if(e.dry_run)return`DRY RUN [rsync]:
295
+ ${i||"(nothing to sync)"}`}let c="";if(e.deploy_script){let{stdout:d,stderr:f,exitCode:m,error:h}=await Me(n,e.deploy_script,{timeout:12e4}),p=[d,f].filter(Boolean).join(`
296
+ `).trim();if(m!==0)return`${o==="git"?"git pull":"rsync"} OK
297
+
298
+ ERROR (deploy_script, exit ${m}):
299
+ ${h||p}`;c=`
300
+
301
+ Deploy script output:
302
+ ${p||"(no output)"}`}let l="";if(e.health_check){let d=e.health_check.trim();if(/^https?:\/\//.test(d))try{let m=require("node-fetch"),h=await Promise.race([m(d),new Promise((p,g)=>setTimeout(()=>g(new Error("timeout")),15e3))]);if(h.ok)l=`
303
+
304
+ Health check: \u2713 ${d} \u2192 ${h.status}`;else return l=`
305
+
306
+ Health check FAILED: ${d} \u2192 HTTP ${h.status}`,(o==="git"?"git pull OK":"rsync OK")+i+c+l}catch(m){return l=`
307
+
308
+ Health check FAILED: ${d} \u2192 ${m.message}`,(o==="git"?"git pull OK":"rsync OK")+i+c+l}else{let{stdout:m,stderr:h,exitCode:p}=await Me(n,d,{timeout:15e3}),g=[m,h].filter(Boolean).join(`
309
+ `).trim();if(p!==0)return l=`
310
+
311
+ Health check FAILED (exit ${p}): ${g}`,(o==="git"?"git pull OK":"rsync OK")+i+c+l;l=`
312
+
313
+ Health check: \u2713 ${g||"(exit 0)"}`}}let u=o==="git"?`${r}:${e.remote_path}`:`${e.local_path} \u2192 ${r}:${e.remote_path}`;return`Deployed [${o}] ${u}
314
+ ${i}${c}${l}`.trim()}case"deployment_status":{let o=dg(),n=e.config?[e.config]:Object.keys(o);if(n.length===0)return"No deploy configs found. Create .nex/deploy.json to configure deployments.";let r=[];for(let i of n){let c=o[i];if(!c){r.push(`${i}: NOT FOUND`);continue}try{let l=Ke(c.server||i),d=(await Me(l,"echo OK",{timeout:1e4})).stdout.trim()==="OK",f="unknown";if(d&&c.deploy_script){let h=c.deploy_script.match(/systemctl\s+\w+\s+(\S+)/);if(h)try{f=(await Me(l,`systemctl is-active ${h[1]}`,{timeout:1e4})).stdout.trim()}catch{f="inactive"}}let m="N/A";if(c.health_check){let h=c.health_check.trim();if(/^https?:\/\//.test(h))try{let p=require("node-fetch"),g=await Promise.race([p(h),new Promise(($,y)=>setTimeout(()=>y(new Error("timeout")),1e4))]);m=g.ok?"healthy":`HTTP ${g.status}`}catch(p){m=`unhealthy: ${p.message.substring(0,50)}`}else try{m=(await Me(l,h,{timeout:1e4})).exitCode===0?"healthy":"unhealthy"}catch{m="unhealthy"}}r.push(`${i}: server=${d?"reachable":"unreachable"} service=${f} health=${m}`)}catch(l){r.push(`${i}: ERROR \u2014 ${l.message}`)}}return`Deployment Status:
315
+ ${r.join(`
316
+ `)}`}case"frontend_recon":{let o=process.cwd(),n=(e.type||"").toLowerCase(),r=[],i=async(_,x=120)=>{try{let S=ae.isAbsolute(_)?_:ae.join(o,_),C=(await V.readFile(S,"utf8")).split(`
317
+ `),I=C.slice(0,x).join(`
318
+ `);return C.length>x?I+`
319
+ ... (${C.length-x} more lines \u2014 use read_file for full content)`:I}catch{return null}},l=["node_modules",".git","dist","build","vendor",".next","__pycache__","venv",".venv"].map(_=>`-not -path "*/${_}/*"`).join(" "),u=async _=>{try{let{stdout:x}=await ie(`find "${o}" -type f -name "${_}" ${l} 2>/dev/null | head -10`,{timeout:8e3});return x.trim().split(`
320
+ `).filter(Boolean)}catch{return[]}},d=async(_,x)=>{try{let{stdout:S}=await ie(`grep -rl "${_}" "${o}" --include="${x}" --exclude-dir=node_modules --exclude-dir=.git --exclude-dir=dist --exclude-dir=build 2>/dev/null | head -5`,{timeout:8e3});return S.trim().split(`
321
+ `).filter(Boolean)}catch{return[]}};r.push(`## STEP 1: Design Tokens
322
+ `);let f=[...await u("tailwind.config.js"),...await u("tailwind.config.ts"),...await u("tailwind.config.mjs")];if(f.length>0){let _=await i(f[0],80);_&&r.push(`### Tailwind config (${ae.relative(o,f[0])})
323
+ \`\`\`js
324
+ ${_}
325
+ \`\`\``)}else r.push("(no tailwind.config found)");let m=["variables.css","_variables.scss","tokens.css","base.css","global.css","main.css","index.css","app.css","style.css","styles.css"],h=!1;for(let _ of m){let x=await u(_);for(let S of x){let R=await i(S,100);if(R&&R.includes(":root")){r.push(`### CSS Variables (${ae.relative(o,S)})
326
+ \`\`\`css
327
+ ${R}
328
+ \`\`\``),h=!0;break}}if(h)break}if(!h){let _=await d(":root","*.css");if(_.length>0){let x=await i(_[0],100);x&&r.push(`### CSS Variables (${ae.relative(o,_[0])})
329
+ \`\`\`css
330
+ ${x}
331
+ \`\`\``),h=!0}}h||r.push("(no CSS custom properties / :root found)"),r.push(`
332
+ ## STEP 2: Main Layout / Index Page
333
+ `);let p=["base.html","_base.html","layout.html","base.jinja","App.vue","App.jsx","App.tsx","_app.jsx","_app.tsx","_app.js","layout.vue","index.html"],g=!1;for(let _ of p){let x=await u(_);if(x.length>0){let S=await i(x[0],150);if(S){r.push(`### Main layout: ${ae.relative(o,x[0])}
334
+ \`\`\`html
335
+ ${S}
336
+ \`\`\``),g=!0;break}}}g||r.push("(no main layout/index file found \u2014 try read_file on your root template manually)"),r.push(`
337
+ ## STEP 3: Reference Component (same type)
338
+ `);let $=[];if(n){for(let _ of["*.html","*.vue","*.jsx","*.tsx"])if($=await d(n,_),$.length>0)break}if($.length===0)try{let{stdout:_}=await ie(`find "${o}" -type f \\( -name "*.html" -o -name "*.vue" -o -name "*.jsx" -o -name "*.tsx" \\) -not -path "*/node_modules/*" -not -path "*/.git/*" -not -path "*/dist/*" -not -path "*/build/*" -not -name "base.html" -not -name "_base.html" -not -name "layout.html" -not -name "App.vue" -not -name "App.jsx" 2>/dev/null | head -20`,{timeout:8e3});$=_.trim().split(`
339
+ `).filter(Boolean)}catch{$=[]}if($.length>0){let _=$[0],x=await i(_,150);x?r.push(`### Reference: ${ae.relative(o,_)}
340
+ \`\`\`html
341
+ ${x}
342
+ \`\`\``):r.push("(reference file found but could not be read)")}else r.push("(no reference component found \u2014 check manually with glob or list_directory)");r.push(`
343
+ ## STEP 4: Framework Stack
344
+ `);let y=[],w=await i(ae.join(o,"package.json"),999);if(w){if((w.includes('"react"')||w.includes("'react'"))&&y.push("React"),w.includes('"vue"')||w.includes("'vue'")){let x=w.match(/"vue":\s*"[\^~]?(\d+)/);y.push(x?`Vue.js v${x[1]}`:"Vue.js")}let _=w.match(/"alpinejs":\s*"[\^~]?(\d+)/);_&&y.push(`Alpine.js v${_[1]} (\u26A0 v2 vs v3 API differs!)`),(w.includes('"htmx')||w.includes("'htmx"))&&y.push("HTMX"),w.includes('"tailwindcss"')&&y.push("Tailwind CSS"),w.includes('"bootstrap"')&&y.push("Bootstrap")}if((await V.access(ae.join(o,"manage.py")).then(()=>!0).catch(()=>!1)||(await i(ae.join(o,"requirements.txt"),50)||"").includes("Django"))&&y.push("Django (server-rendered templates)"),!y.some(_=>_.includes("Alpine"))){let _=await d("alpinejs","*.html");if(_.length>0){let S=(await i(_[0],30)||"").match(/alpinejs[@/]v?(\d)/);y.push(S?`Alpine.js v${S[1]} (via CDN \u2014 \u26A0 v2 vs v3 API differs!)`:"Alpine.js (via CDN \u2014 check version!)")}}return y.some(_=>_.includes("HTMX"))||(await d("htmx","*.html")).length>0&&y.push("HTMX (via CDN)"),y.length>0?(r.push(y.map(_=>`- ${_}`).join(`
345
+ `)),r.push(`
346
+ \u26A0 Use ONLY the frameworks listed above. Do NOT mix (e.g. no fetch() when HTMX is used for the same action).`)):r.push("(framework not detected \u2014 check package.json or script tags manually)"),r.push(`
347
+ ---
348
+ \u2705 Design recon complete. Now build consistently with the patterns above.`),r.join(`
349
+ `)}case"sysadmin":{if(!e.action)return"ERROR: action is required";let o=!e.server||e.server==="local"||e.server==="localhost",n;if(!o)try{n=Ke(e.server)}catch(l){return`ERROR: ${l.message}`}let r=async(l,u=3e4)=>{if(o)try{let{stdout:d,stderr:f}=await ie(l,{timeout:u});return{out:(d||f||"").trim(),exitCode:0}}catch(d){return{out:(d.stderr||d.message||"").toString().trim(),exitCode:d.code||1}}else{let{stdout:d,stderr:f,exitCode:m,error:h}=await Me(n,l,{timeout:u}),p=[d,f].filter(Boolean).join(`
350
+ `).trim();return{out:h&&m!==0?(h+`
351
+ `+p).trim():p,exitCode:m}}};if(!(["audit","disk_usage","process_list","network_status","ssl_check","log_tail","find_large","journalctl"].includes(e.action)||e.action==="package"&&e.package_action==="list"||e.action==="user_manage"&&["list","info"].includes(e.user_action)||e.action==="firewall"&&e.firewall_action==="status"||e.action==="cron"&&e.cron_action==="list"||e.action==="service"&&["status","list_failed"].includes(e.service_action))&&!s.autoConfirm){let l=o?"local":e.server;if(!await Ve(`sysadmin [${e.action}] on ${l} \u2014 proceed?`))return"Cancelled."}switch(e.action){case"audit":{let l=["echo '=== OS / KERNEL ==='","cat /etc/os-release 2>/dev/null | grep -E '^(NAME|VERSION)=' || uname -a","echo '=== UPTIME / LOAD ==='","uptime","echo '=== MEMORY / SWAP ==='","free -h","echo '=== DISK ==='","df -h --output=target,size,used,avail,pcent 2>/dev/null || df -h","echo '=== TOP 10 PROCESSES (CPU) ==='","ps aux --sort=-%cpu | head -11","echo '=== FAILED SYSTEMD UNITS ==='","systemctl list-units --state=failed --no-legend 2>/dev/null || echo '(systemctl not available)'","echo '=== RECENT ERRORS (journalctl) ==='","journalctl -p err --no-pager -n 15 2>/dev/null || echo '(journalctl not available)'","echo '=== LISTENING PORTS ==='","ss -tlnp 2>/dev/null || netstat -tlnp 2>/dev/null || echo '(ss/netstat not available)'"].join(" && "),{out:u,exitCode:d}=await r(l,45e3);return u||`EXIT ${d}
352
+ (no output)`}case"disk_usage":{let l=e.path||"/",u=`df -h ${l}; echo '--- Top subdirs ---'; du -d1 -x -h ${l} 2>/dev/null | sort -rh | head -20`,{out:d,exitCode:f}=await r(u,3e4);return f!==0?`EXIT ${f}
353
+ ${d}`:d}case"process_list":{let l=e.sort_by==="mem"?"4":"3",u=(e.limit||20)+1,d=`ps aux --sort=-${e.sort_by==="mem"?"%mem":"%cpu"} 2>/dev/null | head -${u} || ps aux | awk 'NR==1{print; next} {print | "sort -k${l} -rn"}' | head -${u}`,{out:f,exitCode:m}=await r(d,15e3);return m!==0?`EXIT ${m}
354
+ ${f}`:f}case"network_status":{let l="ss -tlnp 2>/dev/null || netstat -tlnp 2>/dev/null; echo '--- Active connections ---'; ss -tnp 2>/dev/null | head -30",{out:u,exitCode:d}=await r(l,15e3);return d!==0?`EXIT ${d}
355
+ ${u}`:u}case"package":{if(!e.package_action)return"ERROR: package_action is required for action=package";let{out:l}=await r("which dnf 2>/dev/null && echo dnf || (which apt-get 2>/dev/null && echo apt) || echo unknown",1e4),u=l.includes("dnf")?"dnf":l.includes("apt")?"apt":null;if(!u)return"ERROR: No supported package manager found (dnf/apt)";let d=(e.packages||[]).join(" "),f;switch(e.package_action){case"list":f=u==="dnf"?"dnf list installed 2>/dev/null | head -60":"dpkg -l | head -60";break;case"install":if(!d)return"ERROR: packages required for install";f=u==="dnf"?`dnf install -y ${d}`:`apt-get install -y ${d}`;break;case"remove":if(!d)return"ERROR: packages required for remove";f=u==="dnf"?`dnf remove -y ${d}`:`apt-get remove -y ${d}`;break;case"update":if(!d)return"ERROR: packages required for update (use upgrade for full system upgrade)";f=u==="dnf"?`dnf update -y ${d}`:`apt-get install -y --only-upgrade ${d}`;break;case"upgrade":f=u==="dnf"?"dnf upgrade -y":"DEBIAN_FRONTEND=noninteractive apt-get upgrade -y";break;default:return`ERROR: Unknown package_action: ${e.package_action}`}let{out:m,exitCode:h}=await r(f,12e4);return h!==0?`EXIT ${h}
356
+ ${m}`:m||`${e.package_action} OK`}case"user_manage":{if(!e.user_action)return"ERROR: user_action is required for action=user_manage";switch(e.user_action){case"list":{let l=`awk -F: '$3 >= 1000 && $1 != "nobody" {print $1, "uid="$3, "gid="$4, "shell="$7}' /etc/passwd`,{out:u,exitCode:d}=await r(l,1e4);return d!==0?`EXIT ${d}
357
+ ${u}`:u||"(no regular users)"}case"info":{if(!e.user)return"ERROR: user is required for user_action=info";let l=`id ${e.user} && echo '--- Groups ---' && groups ${e.user} && echo '--- Last login ---' && lastlog -u ${e.user} 2>/dev/null`,{out:u,exitCode:d}=await r(l,1e4);return d!==0?`EXIT ${d}
358
+ ${u}`:u}case"create":{if(!e.user)return"ERROR: user is required for user_action=create";let u=`useradd -m ${(e.groups||[]).map(m=>`-G ${m}`).join(" ")} ${e.user} && echo "User ${e.user} created"`,{out:d,exitCode:f}=await r(u,15e3);return f!==0?`EXIT ${f}
359
+ ${d}`:d}case"delete":{if(!e.user)return"ERROR: user is required for user_action=delete";let l=`userdel -r ${e.user} && echo "User ${e.user} deleted"`,{out:u,exitCode:d}=await r(l,15e3);return d!==0?`EXIT ${d}
360
+ ${u}`:u}case"add_ssh_key":{if(!e.user)return"ERROR: user is required for user_action=add_ssh_key";if(!e.ssh_key)return"ERROR: ssh_key is required for user_action=add_ssh_key";let l=e.ssh_key.replace(/'/g,"'\\''"),u=`mkdir -p /home/${e.user}/.ssh && chmod 700 /home/${e.user}/.ssh && echo '${l}' >> /home/${e.user}/.ssh/authorized_keys && chmod 600 /home/${e.user}/.ssh/authorized_keys && chown -R ${e.user}:${e.user} /home/${e.user}/.ssh && echo "SSH key added for ${e.user}"`,{out:d,exitCode:f}=await r(u,15e3);return f!==0?`EXIT ${f}
361
+ ${d}`:d}default:return`ERROR: Unknown user_action: ${e.user_action}`}}case"firewall":{if(!e.firewall_action)return"ERROR: firewall_action is required for action=firewall";let{out:l}=await r("which firewall-cmd 2>/dev/null && echo firewalld || (which ufw 2>/dev/null && echo ufw) || echo iptables",1e4),u=l.includes("firewalld")?"firewalld":l.includes("ufw")?"ufw":"iptables",d;switch(e.firewall_action){case"status":d=u==="firewalld"?"firewall-cmd --state && firewall-cmd --list-all":u==="ufw"?"ufw status verbose":"iptables -L -n --line-numbers | head -60";break;case"allow":if(!e.port)return'ERROR: port is required for firewall allow (e.g. "80/tcp")';d=u==="firewalld"?`firewall-cmd --permanent --add-port=${e.port} && firewall-cmd --reload`:u==="ufw"?`ufw allow ${e.port}`:`iptables -A INPUT -p ${e.port.includes("/")?e.port.split("/")[1]:"tcp"} --dport ${e.port.split("/")[0]} -j ACCEPT`;break;case"deny":if(!e.port)return"ERROR: port is required for firewall deny";d=u==="firewalld"?`firewall-cmd --permanent --remove-port=${e.port} && firewall-cmd --reload`:u==="ufw"?`ufw deny ${e.port}`:`iptables -A INPUT -p ${e.port.includes("/")?e.port.split("/")[1]:"tcp"} --dport ${e.port.split("/")[0]} -j DROP`;break;case"remove":if(!e.port)return"ERROR: port is required for firewall remove";d=u==="firewalld"?`firewall-cmd --permanent --remove-port=${e.port} && firewall-cmd --reload`:u==="ufw"?`ufw delete allow ${e.port}`:`iptables -D INPUT -p ${e.port.includes("/")?e.port.split("/")[1]:"tcp"} --dport ${e.port.split("/")[0]} -j ACCEPT 2>/dev/null || true`;break;case"reload":d=u==="firewalld"?"firewall-cmd --reload":u==="ufw"?"ufw reload":'iptables-restore < /etc/iptables/rules.v4 2>/dev/null || echo "iptables: manual reload not available"';break;default:return`ERROR: Unknown firewall_action: ${e.firewall_action}`}let{out:f,exitCode:m}=await r(d,3e4);return m!==0?`EXIT ${m}
362
+ ${f}`:f||`firewall ${e.firewall_action} OK`}case"cron":{if(!e.cron_action)return"ERROR: cron_action is required for action=cron";let l=e.user?`-u ${e.user}`:"";switch(e.cron_action){case"list":{let u=`crontab ${l} -l 2>/dev/null || echo '(no crontab for ${e.user||"current user"})'`,{out:d}=await r(u,1e4);return d||"(empty crontab)"}case"add":{if(!e.schedule)return"ERROR: schedule is required for cron add";if(!e.command)return"ERROR: command is required for cron add";let u=`${e.schedule} ${e.command}`,d=`(crontab ${l} -l 2>/dev/null; echo "${u}") | crontab ${l} - && echo "Cron entry added: ${u}"`,{out:f,exitCode:m}=await r(d,15e3);return m!==0?`EXIT ${m}
363
+ ${f}`:f}case"remove":{if(!e.command)return"ERROR: command (substring to match) is required for cron remove";let u=e.command.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),d=`crontab ${l} -l 2>/dev/null | grep -v "${u}" | crontab ${l} - && echo "Matching cron entries removed"`,{out:f,exitCode:m}=await r(d,15e3);return m!==0?`EXIT ${m}
364
+ ${f}`:f}default:return`ERROR: Unknown cron_action: ${e.cron_action}`}}case"ssl_check":{if(!e.domain&&!e.cert_path)return"ERROR: domain or cert_path is required for ssl_check";let l;e.cert_path?l=`
365
+ CERT="${e.cert_path}"
366
+ openssl x509 -in "$CERT" -noout -subject -issuer -startdate -enddate -ext subjectAltName 2>&1 && EXPIRY=$(openssl x509 -in "$CERT" -noout -enddate 2>/dev/null | cut -d= -f2) && DAYS=$(( ( $(date -d "$EXPIRY" +%s 2>/dev/null || date -j -f "%b %d %T %Y %Z" "$EXPIRY" +%s 2>/dev/null) - $(date +%s) ) / 86400 )) && echo "Days until expiry: $DAYS"
367
+ `.trim():l=`
368
+ DOMAIN="${e.domain}"
369
+ LECP="/etc/letsencrypt/live/$DOMAIN/cert.pem"
370
+ if [ -f "$LECP" ]; then
371
+ echo "Source: Let's Encrypt $LECP"
372
+ openssl x509 -in "$LECP" -noout -subject -issuer -startdate -enddate -ext subjectAltName 2>&1
373
+ EXPIRY=$(openssl x509 -in "$LECP" -noout -enddate 2>/dev/null | cut -d= -f2)
374
+ else
375
+ echo "Source: live TLS probe"
376
+ CERT=$(echo | openssl s_client -connect "$DOMAIN":443 -servername "$DOMAIN" 2>/dev/null)
377
+ if [ -z "$CERT" ]; then echo "ERROR: Could not connect to $DOMAIN:443 (port closed or DNS unresolvable)"; exit 1; fi
378
+ echo "$CERT" | openssl x509 -noout -subject -issuer -startdate -enddate -ext subjectAltName 2>&1
379
+ EXPIRY=$(echo "$CERT" | openssl x509 -noout -enddate 2>/dev/null | cut -d= -f2)
380
+ fi
381
+ if [ -n "$EXPIRY" ]; then
382
+ DAYS=$(( ( $(date -d "$EXPIRY" +%s 2>/dev/null || date -j -f "%b %d %T %Y %Z" "$EXPIRY" +%s 2>/dev/null) - $(date +%s) ) / 86400 ))
383
+ echo "Days until expiry: $DAYS"
384
+ [ "$DAYS" -lt 14 ] && echo "WARNING: Certificate expires in less than 14 days!"
385
+ [ "$DAYS" -lt 0 ] && echo "CRITICAL: Certificate has EXPIRED!"
386
+ fi
387
+ `.trim();let{out:u,exitCode:d}=await r(l,25e3);return d!==0?`EXIT ${d}
388
+ ${u}`:u||"(no cert info returned)"}case"log_tail":{if(!e.path)return"ERROR: path is required for log_tail";let u=`tail -n ${e.lines||100} ${e.path} 2>&1`,{out:d,exitCode:f}=await r(u,15e3);return f!==0?`EXIT ${f}
389
+ ${d}`:d||"(empty log)"}case"find_large":{let l=e.path||"/",u=e.limit||20,d=e.min_size||"100M",f=`find ${l} -xdev -type f -size +${d} 2>/dev/null | xargs du -sh 2>/dev/null | sort -rh | head -${u}`,{out:m,exitCode:h}=await r(f,6e4);return h!==0?`EXIT ${h}
390
+ ${m}`:m||`(no files larger than ${d} in ${l})`}case"service":{if(!e.service_action)return"ERROR: service_action is required for action=service";if(e.service_action!=="list_failed"&&!e.service_name)return"ERROR: service_name is required (except for list_failed)";let l=e.service_name?e.service_name.includes(".")?e.service_name:`${e.service_name}.service`:"",u;switch(e.service_action){case"status":u=`systemctl status ${l} --no-pager -l 2>&1 | head -40`;break;case"list_failed":u="systemctl list-units --state=failed --no-legend 2>/dev/null";break;case"start":u=`systemctl start ${l} && systemctl status ${l} --no-pager -l 2>&1 | head -20`;break;case"stop":u=`systemctl stop ${l} && echo "${l} stopped"`;break;case"restart":u=`systemctl restart ${l} && systemctl status ${l} --no-pager -l 2>&1 | head -20`;break;case"reload":u=`systemctl reload ${l} 2>&1 || systemctl reload-or-restart ${l} 2>&1`;break;case"enable":u=`systemctl enable ${l} && echo "${l} enabled"`;break;case"disable":u=`systemctl disable ${l} && echo "${l} disabled"`;break;default:return`ERROR: Unknown service_action: ${e.service_action}`}let{out:d,exitCode:f}=await r(u,3e4);return f!==0?`EXIT ${f}
391
+ ${d}`:d||`service ${e.service_action} OK`}case"kill_process":{if(!e.pid&&!e.process_name)return"ERROR: pid or process_name is required for kill_process";let l=e.signal||"SIGTERM",u;e.pid?u=`ps -p ${e.pid} -o pid,user,%cpu,%mem,etime,cmd 2>/dev/null && kill -${l} ${e.pid} && echo "Sent ${l} to PID ${e.pid}"`:u=`pgrep -a "${e.process_name}" 2>/dev/null | head -5 && pkill -${l} "${e.process_name}" && echo "Sent ${l} to all '${e.process_name}' processes"`;let{out:d,exitCode:f}=await r(u,15e3);return f!==0?`EXIT ${f}
392
+ ${d}`:d}case"journalctl":{let l=e.lines||100,u=["journalctl","--no-pager","-n",String(l)];e.unit&&u.push("-u",e.unit.includes(".")?e.unit:`${e.unit}.service`),e.priority&&u.push("-p",e.priority),e.since&&u.push(`--since="${e.since}"`),u.push('2>/dev/null || echo "(journalctl not available)"');let{out:d,exitCode:f}=await r(u.join(" "),2e4);return f!==0?`EXIT ${f}
393
+ ${d}`:d||"(no log entries)"}default:return`ERROR: Unknown sysadmin action: ${e.action}`}}default:{let{executePluginTool:o}=Ps(),n=await o(t,e,s);return n!==null?n:`ERROR: Unknown tool: ${t}`}}}async function bg(t,e,s={}){let{emit:o}=Ps(),{logToolExecution:n}=Mr(),r=Date.now(),i=s.silent?null:og(t,e);if(!i){let l=await Dl(t,e,s);return n({tool:t,args:e,result:l,duration:Date.now()-r,success:!l.startsWith?.("ERROR")}),await o("onToolResult",{tool:t,args:e,result:l}),l}let c=new sg(i);c.start();try{let l=await Dl(t,e,s);return c.stop(),n({tool:t,args:e,result:l,duration:Date.now()-r,success:!l.startsWith?.("ERROR")}),await o("onToolResult",{tool:t,args:e,result:l}),l}catch(l){throw c.stop(),n({tool:t,args:e,result:l.message,duration:Date.now()-r,success:!1}),l}}Ul.exports={TOOL_DEFINITIONS:wg,executeTool:bg,resolvePath:Ie,autoFixPath:Zs,autoFixEdit:Fl,enrichBashError:ql,cancelPendingAskUser:gg,setAskUserHandler:$g}});var Bl=j((V0,Wl)=>{var{loadServerProfiles:Fr}=mn(),qr={almalinux9:["Package manager: dnf (NOT apt). Install: dnf install <pkg>. Update: dnf update.","Service manager: systemctl. Logs: journalctl -u <service> -n 50.","Firewall: firewalld. Check: firewall-cmd --list-all. Open port: firewall-cmd --permanent --add-port=PORT/tcp && firewall-cmd --reload.","SELinux is active by default. Check: getenforce. Diagnose: ausearch -m avc -ts recent | audit2why. Fix context: restorecon -Rv /path.","Nginx config: /etc/nginx/. Test: nginx -t. Reload: systemctl reload nginx.","Process list: ps aux. Ports: ss -tuln.","Python: python3. Pip: pip3. Virtualenv: python3 -m venv."],almalinux8:["Package manager: dnf (NOT apt). Install: dnf install <pkg>. Update: dnf update.","Service manager: systemctl. Logs: journalctl -u <service> -n 50.","Firewall: firewalld. Check: firewall-cmd --list-all.","SELinux is active by default. Check: getenforce. Diagnose: ausearch -m avc -ts recent."],ubuntu:["Package manager: apt. Install: apt install <pkg>. Update: apt update && apt upgrade.","Service manager: systemctl. Logs: journalctl -u <service> -n 50.","Firewall: ufw. Status: ufw status. Allow port: ufw allow PORT/tcp.","SELinux NOT active by default (AppArmor instead). Check: aa-status."],debian:["Package manager: apt. Install: apt install <pkg>. Update: apt update && apt upgrade.","Service manager: systemctl. Logs: journalctl -u <service> -n 50.","Firewall: ufw or iptables."],macos:["Package manager: Homebrew (brew). Install: brew install <pkg>. Update: brew update && brew upgrade.","Service manager: launchctl (NOT systemctl). Start: brew services start <name>. List: brew services list.",`No systemd. No journalctl. Use: log show --predicate 'process == "nginx"' --last 1h instead.`,"Firewall: macOS built-in (pfctl or System Settings). Check: pfctl -s rules.","Process list: ps aux. Ports: lsof -i -n -P | grep LISTEN."]};function _g(){let t=Fr();if(Object.keys(t).length===0)return null;let s=["## Remote Servers (.nex/servers.json)"];s.push(""),s.push("Available server profiles (use with ssh_exec, ssh_upload, ssh_download, service_manage, service_logs, container_list, container_logs, container_exec, container_manage, deploy):");for(let[n,r]of Object.entries(t)){let i=r.user?`${r.user}@${r.host}`:r.host,c=r.port&&Number(r.port)!==22?`:${r.port}`:"",l=r.os?` \u2014 OS: ${r.os}`:"",u=r.sudo?", sudo available":"";s.push(`- **${n}**: ${i}${c}${l}${u}`)}let o=new Set;for(let n of Object.values(t))n.os&&qr[n.os]&&o.add(n.os);if(o.size>0){s.push("");for(let n of o){let r={almalinux9:"AlmaLinux 9",almalinux8:"AlmaLinux 8",ubuntu:"Ubuntu",debian:"Debian",macos:"macOS"}[n]||n;s.push(`### ${r} Notes`);for(let i of qr[n])s.push(`- ${i}`)}}return s.join(`
394
+ `)}function kg(t){let e=Fr();return Object.values(e).some(s=>s.os&&s.os.startsWith(t))}function xg(){return Object.keys(Fr())}Wl.exports={getServerContext:_g,hasServerOS:kg,getProfileNames:xg,OS_HINTS:qr}});var no=j((Q0,Kl)=>{var Qe=require("fs").promises,Hl=require("fs"),Ee=require("path"),eo=require("util").promisify(require("child_process").exec),{C:gn}=ye(),{getMergeConflicts:Gl}=Ft(),{getServerContext:vg}=Bl(),Sg=new Set(["node_modules",".git",".svn","dist","build","coverage",".nyc_output","__pycache__",".DS_Store",".next",".nuxt",".turbo",".cache","vendor","tmp","temp"]);function Eg(t){try{return Hl.readFileSync(t,"utf-8").split(`
395
+ `).map(s=>s.trim()).filter(s=>s&&!s.startsWith("#")&&!s.startsWith("!")).map(s=>s.replace(/\/$/,""))}catch{return[]}}function Tg(t,e){for(let s of e)if(s===t||s.includes("*")&&new RegExp("^"+s.replace(/\./g,"\\.").replace(/\*/g,".*")+"$").test(t))return!0;return!1}function Rg(t,{maxDepth:e=3,maxFiles:s=200,giPatterns:o=[]}={}){let n=Ee.join(t,".gitignore"),r=[...o,...Eg(n)],i=0,c=[Ee.basename(t)+"/"];function l(u,d,f){if(f>e||i>=s)return;let m;try{m=Hl.readdirSync(u,{withFileTypes:!0})}catch{return}m.sort((p,g)=>p.isDirectory()!==g.isDirectory()?p.isDirectory()?-1:1:p.name.localeCompare(g.name));let h=m.filter(p=>!(Sg.has(p.name)||p.name.startsWith(".")&&p.name!==".env.example"||Tg(p.name,r)));for(let p=0;p<h.length;p++){if(i>=s){c.push(`${d}\u2514\u2500\u2500 \u2026 (truncated)`);break}let g=h[p],$=p===h.length-1,y=$?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",w=d+($?" ":"\u2502 "),T=g.isDirectory()?g.name+"/":g.name;c.push(`${d}${y}${T}`),i++,g.isDirectory()&&l(Ee.join(u,g.name),w,f+1)}}return l(t,"",1),c.join(`
396
+ `)}var Ur=new Map,$n=new Map,to=null,Cg=3e4;async function Tt(t){try{return await t()}catch{return null}}async function Ag(){if(!to||Date.now()>to)return!1;let t=[Ee.join(process.cwd(),"package.json"),Ee.join(process.cwd(),"README.md"),Ee.join(process.cwd(),".gitignore")];for(let e of t)try{let s=await Qe.stat(e),o=$n.get(e);if(!o||s.mtimeMs!==o)return!1}catch{if($n.has(e))return!1}try{let e=Ee.join(process.cwd(),".git","HEAD"),s=await Qe.stat(e),o=$n.get(e);if(!o||s.mtimeMs!==o)return!1}catch{}return!0}async function Og(){let t=[Ee.join(process.cwd(),"package.json"),Ee.join(process.cwd(),"README.md"),Ee.join(process.cwd(),".gitignore"),Ee.join(process.cwd(),".git","HEAD")];for(let e of t)try{let s=await Qe.stat(e);$n.set(e,s.mtimeMs)}catch{$n.delete(e)}}async function Ng(t){let e="fileContext",s=Ur.get(e),o=!1;if(s&&await Ag()&&(o=!0),!o){let u=[],d=Ee.join(t,"package.json");if(await Tt(()=>Qe.access(d).then(()=>!0).catch(()=>!1)))try{let $=await Qe.readFile(d,"utf-8"),y=JSON.parse($),w={name:y.name,version:y.version};y.scripts&&(w.scripts=Object.keys(y.scripts).slice(0,15)),y.dependencies&&(w.deps=Object.keys(y.dependencies).length),y.devDependencies&&(w.devDeps=Object.keys(y.devDependencies).length),u.push(`PACKAGE: ${JSON.stringify(w)}`)}catch{}let m=Ee.join(t,"README.md");if(await Tt(()=>Qe.access(m).then(()=>!0).catch(()=>!1))){let y=(await Qe.readFile(m,"utf-8")).split(`
286
397
  `).slice(0,50);u.push(`README (first 50 lines):
287
- ${$.join(`
288
- `)}`)}let m=_e.join(t,".gitignore");if(await mt(()=>Fe.access(m).then(()=>!0).catch(()=>!1))){let y=await Fe.readFile(m,"utf-8");u.push(`GITIGNORE:
289
- ${y.trim()}`)}s=u.join(`
398
+ ${y.join(`
399
+ `)}`)}let p=Ee.join(t,".gitignore");if(await Tt(()=>Qe.access(p).then(()=>!0).catch(()=>!1))){let $=await Qe.readFile(p,"utf-8");u.push(`GITIGNORE:
400
+ ${$.trim()}`)}s=u.join(`
290
401
 
291
- `),Yo.set(e,s),bs=Date.now()+wm,await xm()}let o=[s],[r,i,c,l]=await Promise.all([mt(async()=>{let{stdout:u}=await ws("git branch --show-current",{cwd:t,timeout:5e3});return u.trim()}),mt(async()=>{let{stdout:u}=await ws("git status --short",{cwd:t,timeout:5e3});return u.trim()}),mt(async()=>{let{stdout:u}=await ws("git log --oneline -5",{cwd:t,timeout:5e3});return u.trim()}),vc()]);if(r&&o.push(`GIT BRANCH: ${r}`),i&&o.push(`GIT STATUS:
292
- ${i}`),c&&o.push(`RECENT COMMITS:
402
+ `),Ur.set(e,s),to=Date.now()+Cg,await Og()}let n=[s],[r,i,c,l]=await Promise.all([Tt(async()=>{let{stdout:u}=await eo("git branch --show-current",{cwd:t,timeout:5e3});return u.trim()}),Tt(async()=>{let{stdout:u}=await eo("git status --short",{cwd:t,timeout:5e3});return u.trim()}),Tt(async()=>{let{stdout:u}=await eo("git log --oneline -5",{cwd:t,timeout:5e3});return u.trim()}),Gl()]);if(r&&n.push(`GIT BRANCH: ${r}`),i&&n.push(`GIT STATUS:
403
+ ${i}`),c&&n.push(`RECENT COMMITS:
293
404
  ${c}`),l&&l.length>0){let u=l.map(d=>` ${d.file}`).join(`
294
- `);o.push(`MERGE CONFLICTS (resolve before editing these files):
295
- ${u}`)}try{let u=mm();u&&o.push(u)}catch{}return o.join(`
405
+ `);n.push(`MERGE CONFLICTS (resolve before editing these files):
406
+ ${u}`)}try{let u=vg();u&&n.push(u)}catch{}return n.join(`
296
407
 
297
- `)}async function km(t){let e=_e.join(t,"package.json"),s="";if(await mt(()=>Fe.access(e).then(()=>!0).catch(()=>!1)))try{let i=await Fe.readFile(e,"utf-8"),c=JSON.parse(i);s=`${c.name||"?"} v${c.version||"?"}`}catch{}let[o,r]=await Promise.all([mt(async()=>{let{stdout:i}=await ws("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),vc()]);if(s&&console.log(`${Ke.dim} project: ${s}${Ke.reset}`),o&&console.log(`${Ke.dim} branch: ${o}${Ke.reset}`),r&&r.length>0){console.log(`${Ke.red} \u26A0 ${r.length} unresolved merge conflict(s):${Ke.reset}`);for(let i of r)console.log(`${Ke.red} ${i.file}${Ke.reset}`);console.log(`${Ke.yellow} \u2192 Resolve conflicts before starting tasks${Ke.reset}`)}console.log()}Sc.exports={gatherProjectContext:_m,printContext:km,generateFileTree:ym,_clearContextCache:()=>{Yo.clear(),zt.clear(),bs=null}}});var Ct=L((Ty,Cc)=>{var ot=require("fs"),Jo=require("path");function _s(){return Jo.join(process.cwd(),".nex","sessions")}function Ec(){let t=_s();ot.existsSync(t)||ot.mkdirSync(t,{recursive:!0})}function Vo(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return Jo.join(_s(),`${e}.json`)}function Xo(t,e,s={}){Ec();let n=Vo(t),o={name:t,createdAt:s.createdAt||new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:e.length,model:s.model||null,provider:s.provider||null,messages:e};return ot.writeFileSync(n,JSON.stringify(o,null,2),"utf-8"),{path:n,name:t}}function Tc(t){let e=Vo(t);if(!ot.existsSync(e))return null;try{return JSON.parse(ot.readFileSync(e,"utf-8"))}catch{return null}}function Rc(){Ec();let t=_s(),e=ot.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(ot.readFileSync(Jo.join(t,n),"utf-8"));s.push({name:o.name||n.replace(".json",""),createdAt:o.createdAt,updatedAt:o.updatedAt,messageCount:o.messageCount||0,model:o.model,provider:o.provider})}catch{}return s.sort((n,o)=>(o.updatedAt||"").localeCompare(n.updatedAt||""))}function vm(t){let e=Vo(t);return ot.existsSync(e)?(ot.unlinkSync(e),!0):!1}function Sm(){let t=Rc();return t.length===0?null:Tc(t[0].name)}var Rt=null,st=null,En=null;function Em(t,e={}){t.length!==0&&(Rt&&clearTimeout(Rt),st=t,En=e||{},Rt=setTimeout(()=>{st&&st.length>0&&Xo("_autosave",st,En),Rt=null,st=null,En=null},5e3))}function Tm(){Rt&&(clearTimeout(Rt),Rt=null),st&&st.length>0&&(Xo("_autosave",st,En),st=null,En=null)}Cc.exports={saveSession:Xo,loadSession:Tc,listSessions:Rc,deleteSession:vm,getLastSession:Sm,autoSave:Em,flushAutoSave:Tm,_getSessionsDir:_s}});var ht=L((Ry,Lc)=>{var rt=require("fs"),ks=require("path"),Rm=require("os");function Qo(){return ks.join(process.cwd(),".nex","memory")}function Zo(){return ks.join(Qo(),"memory.json")}function Cm(){return ks.join(process.cwd(),"NEX.md")}function Ac(){return ks.join(Rm.homedir(),".nex","NEX.md")}function Am(){let t=Qo();rt.existsSync(t)||rt.mkdirSync(t,{recursive:!0})}function vs(){let t=Zo();if(!rt.existsSync(t))return{};try{return JSON.parse(rt.readFileSync(t,"utf-8"))}catch{return{}}}function Oc(t){Am(),rt.writeFileSync(Zo(),JSON.stringify(t,null,2),"utf-8")}function Om(t,e){let s=vs();s[t]={value:e,updatedAt:new Date().toISOString()},Oc(s)}function Nm(t){let e=vs();return e[t]?e[t].value:null}function Mm(t){let e=vs();return t in e?(delete e[t],Oc(e),!0):!1}function Nc(){let t=vs();return Object.entries(t).map(([e,s])=>({key:e,value:s.value,updatedAt:s.updatedAt}))}function Mc(){let t=Ac();if(!rt.existsSync(t))return"";try{return rt.readFileSync(t,"utf-8").trim()}catch{return""}}function Pc(){let t=Cm();if(!rt.existsSync(t))return"";try{return rt.readFileSync(t,"utf-8").trim()}catch{return""}}function Pm(){let t=[],e=Mc();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
298
- ${e}`);let s=Pc();s&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
299
- ${s}`);let n=Nc();if(n.length>0){let o=n.map(r=>` ${r.key}: ${r.value}`).join(`
408
+ `)}async function Pg(t){let e=Ee.join(t,"package.json"),s="";if(await Tt(()=>Qe.access(e).then(()=>!0).catch(()=>!1)))try{let i=await Qe.readFile(e,"utf-8"),c=JSON.parse(i);s=`${c.name||"?"} v${c.version||"?"}`}catch{}let[n,r]=await Promise.all([Tt(async()=>{let{stdout:i}=await eo("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),Gl()]);if(r&&r.length>0){console.log(`${gn.red} \u26A0 ${r.length} unresolved merge conflict(s):${gn.reset}`);for(let i of r)console.log(`${gn.red} ${i.file}${gn.reset}`);console.log(`${gn.yellow} \u2192 Resolve conflicts before starting tasks${gn.reset}`)}console.log()}Kl.exports={gatherProjectContext:Ng,printContext:Pg,generateFileTree:Rg,_clearContextCache:()=>{Ur.clear(),$n.clear(),to=null}}});var Ct=j((Z0,Jl)=>{var Rt=require("fs"),Wr=require("path"),{atomicWrite:Mg}=vt();function so(){return Wr.join(process.cwd(),".nex","sessions")}function zl(){let t=so();Rt.existsSync(t)||Rt.mkdirSync(t,{recursive:!0})}function Br(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return Wr.join(so(),`${e}.json`)}function Hr(t,e,s={}){zl();let o=Br(t),n={name:t,createdAt:s.createdAt||new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:e.length,model:s.model||null,provider:s.provider||null,messages:e};return Mg(o,JSON.stringify(n,null,2)),{path:o,name:t}}function Yl(t){let e=Br(t);if(!Rt.existsSync(e))return null;try{return JSON.parse(Rt.readFileSync(e,"utf-8"))}catch{return null}}function Xl(){zl();let t=so(),e=Rt.readdirSync(t).filter(o=>o.endsWith(".json")),s=[];for(let o of e)try{let n=JSON.parse(Rt.readFileSync(Wr.join(t,o),"utf-8"));s.push({name:n.name||o.replace(".json",""),createdAt:n.createdAt,updatedAt:n.updatedAt,messageCount:n.messageCount||0,model:n.model,provider:n.provider})}catch{}return s.sort((o,n)=>(n.updatedAt||"").localeCompare(o.updatedAt||""))}function Ig(t){let e=Br(t);return Rt.existsSync(e)?(Rt.unlinkSync(e),!0):!1}function Lg(){let t=Xl();return t.length===0?null:Yl(t[0].name)}var Gt=null,$t=null,ts=null;function jg(t,e={}){t.length!==0&&(Gt&&clearTimeout(Gt),$t=t,ts=e||{},Gt=setTimeout(()=>{$t&&$t.length>0&&Hr("_autosave",$t,ts),Gt=null,$t=null,ts=null},5e3))}function Dg(){Gt&&(clearTimeout(Gt),Gt=null),$t&&$t.length>0&&(Hr("_autosave",$t,ts),$t=null,ts=null)}Jl.exports={saveSession:Hr,loadSession:Yl,listSessions:Xl,deleteSession:Ig,getLastSession:Lg,autoSave:jg,flushAutoSave:Dg,_getSessionsDir:so}});var Ot=j((eb,su)=>{var At=require("fs"),oo=require("path"),qg=require("os"),{atomicWrite:Fg,withFileLockSync:Vl}=vt();function Gr(){return oo.join(process.cwd(),".nex","memory")}function ns(){return oo.join(Gr(),"memory.json")}function Ug(){return oo.join(process.cwd(),"NEX.md")}function Ql(){return oo.join(qg.homedir(),".nex","NEX.md")}function Kr(){let t=Gr();At.existsSync(t)||At.mkdirSync(t,{recursive:!0})}function ro(){let t=ns();if(!At.existsSync(t))return{};try{return JSON.parse(At.readFileSync(t,"utf-8"))}catch{return{}}}function Zl(t){Kr(),Fg(ns(),JSON.stringify(t,null,2))}function Wg(t,e){Kr(),Vl(ns(),()=>{let s=ro();s[t]={value:e,updatedAt:new Date().toISOString()},Zl(s)})}function Bg(t){let e=ro();return e[t]?e[t].value:null}function Hg(t){return Kr(),Vl(ns(),()=>{let e=ro();return t in e?(delete e[t],Zl(e),!0):!1})}function eu(){let t=ro();return Object.entries(t).map(([e,s])=>({key:e,value:s.value,updatedAt:s.updatedAt}))}function tu(){let t=Ql();if(!At.existsSync(t))return"";try{return At.readFileSync(t,"utf-8").trim()}catch{return""}}function nu(){let t=Ug();if(!At.existsSync(t))return"";try{return At.readFileSync(t,"utf-8").trim()}catch{return""}}function Gg(){let t=[],e=tu();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
409
+ ${e}`);let s=nu();s&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
410
+ ${s}`);let o=eu();if(o.length>0){let n=o.map(r=>` ${r.key}: ${r.value}`).join(`
300
411
  `);t.push(`PROJECT MEMORY:
301
- ${o}`)}return t.join(`
412
+ ${n}`)}return t.join(`
302
413
 
303
- `)}Lc.exports={remember:Om,recall:Nm,forget:Mm,listMemories:Nc,loadGlobalInstructions:Mc,loadProjectInstructions:Pc,getMemoryContext:Pm,_getMemoryDir:Qo,_getMemoryFile:Zo,_getGlobalNexMdPath:Ac}});var Tn=L((Ay,Dc)=>{var At=require("fs"),er=require("path"),{C:Cy}=de(),Ss={bash:"ask",read_file:"allow",write_file:"ask",edit_file:"ask",list_directory:"allow",search_files:"allow",glob:"allow",grep:"allow",patch_file:"ask",web_fetch:"allow",web_search:"allow",ask_user:"allow",task_list:"allow",spawn_agents:"ask"},Kt={...Ss};function Ic(){let t=er.join(process.cwd(),".nex","config.json");if(At.existsSync(t))try{let e=JSON.parse(At.readFileSync(t,"utf-8"));e.permissions&&(Kt={...Ss,...e.permissions})}catch{}}function Lm(){let t=er.join(process.cwd(),".nex"),e=er.join(t,"config.json"),s={};if(At.existsSync(e))try{s=JSON.parse(At.readFileSync(e,"utf-8"))}catch{s={}}s.permissions=Kt,At.existsSync(t)||At.mkdirSync(t,{recursive:!0}),At.writeFileSync(e,JSON.stringify(s,null,2),"utf-8")}function qc(t){return Kt[t]||"ask"}function Im(t,e){return["allow","ask","deny"].includes(e)?(Kt[t]=e,!0):!1}function qm(t){return qc(t)}function Dm(){return Object.entries(Kt).map(([t,e])=>({tool:t,mode:e}))}function jm(){Kt={...Ss}}Ic();Dc.exports={getPermission:qc,setPermission:Im,checkPermission:qm,listPermissions:Dm,loadPermissions:Ic,savePermissions:Lm,resetPermissions:jm,DEFAULT_PERMISSIONS:Ss}});var Mt=L((Ny,Bc)=>{var Nt=require("fs"),Es=require("path"),Oy=require("readline"),{C:X}=de(),K=null,nr=!1,sr=null,jc=new Set(["read_file","list_directory","search_files","glob","grep","web_search","web_fetch","git_status","git_diff","git_log","git_show","ask_user"]);function Ts(){return Es.join(process.cwd(),".nex","plans")}function Fc(){let t=Ts();Nt.existsSync(t)||Nt.mkdirSync(t,{recursive:!0})}function Fm(t,e=[]){return K={name:`plan-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,task:t,steps:e.map(s=>({description:s.description||s,files:s.files||[],status:"pending"})),status:"draft",createdAt:new Date().toISOString()},K}function Um(){return K}function Wm(t){nr=t}function Bm(){return nr}function Hm(){return!K||K.status!=="draft"?!1:(K.status="approved",K.updatedAt=new Date().toISOString(),!0)}function Gm(){return!K||K.status!=="approved"?!1:(K.status="executing",!0)}function tr(t,e){return!K||t<0||t>=K.steps.length?!1:(K.steps[t].status=e,K.updatedAt=new Date().toISOString(),K.steps.every(s=>s.status==="done"||s.status==="skipped")&&(K.status="completed"),!0)}function zm(t){if(!t)return`${X.dim}No active plan${X.reset}`;let e={draft:`${X.yellow}DRAFT${X.reset}`,approved:`${X.green}APPROVED${X.reset}`,executing:`${X.blue}EXECUTING${X.reset}`,completed:`${X.green}COMPLETED${X.reset}`},s=[];s.push(`
304
- ${X.bold}${X.cyan}Plan: ${t.task}${X.reset}`),s.push(`${X.dim}Status: ${e[t.status]||t.status}${X.reset}
305
- `);for(let n=0;n<t.steps.length;n++){let o=t.steps[n],r;switch(o.status){case"done":r=`${X.green}\u2713${X.reset}`;break;case"in_progress":r=`${X.blue}\u2192${X.reset}`;break;case"skipped":r=`${X.dim}\u25CB${X.reset}`;break;default:r=`${X.dim} ${X.reset}`}s.push(` ${r} ${X.bold}Step ${n+1}:${X.reset} ${o.description}`),o.files.length>0&&s.push(` ${X.dim}Files: ${o.files.join(", ")}${X.reset}`)}return s.push(""),s.join(`
306
- `)}function Km(t){if(t||(t=K),!t)return null;Fc();let e=Es.join(Ts(),`${t.name}.json`);return Nt.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function Ym(t){let e=Es.join(Ts(),`${t}.json`);if(!Nt.existsSync(e))return null;try{let s=JSON.parse(Nt.readFileSync(e,"utf-8"));return K=s,s}catch{return null}}function Jm(){Fc();let t=Ts(),e=Nt.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(Nt.readFileSync(Es.join(t,n),"utf-8"));s.push({name:o.name,task:o.task,status:o.status,steps:o.steps?o.steps.length:0,createdAt:o.createdAt})}catch{}return s.sort((n,o)=>(o.createdAt||"").localeCompare(n.createdAt||""))}function Vm(t){if(!t)return[];let e=[],s=t.match(/##\s+Steps?\s*\n([\s\S]*?)(?:\n##|\s*$)/i),n=s?s[1]:t,o=/^\s*(\d+)[.)]\s+(.+)/gm,r;for(;(r=o.exec(n))!==null;){let c=r[2].trim().replace(/^\*\*What\*\*:\s*/i,"").replace(/^\*\*\d+\.\*\*\s*/,"").replace(/\*\*/g,"").trim();c.length>3&&e.push({description:c,files:[],status:"pending"})}if(e.length===0){let i=/\*\*Step\s+\d+[:.]\*\*\s*(.+)/gi;for(;(r=i.exec(t))!==null;){let c=r[1].replace(/\*\*/g,"").trim();c.length>3&&e.push({description:c,files:[],status:"pending"})}}if(e.length>0){let i=/\*\*(?:Where|Files?)\*\*:\s*(.+)/gi,c=[...t.matchAll(i)];for(let l=0;l<Math.min(e.length,c.length);l++){let u=c[l][1];e[l].files=u.split(/[,\s]+/).filter(d=>/[./]/.test(d)).slice(0,5)}}return e}function Xm(t){sr=t}function Qm(){return sr}function Zm(){K=null,nr=!1,sr=null,sh()}function eh(){return`
414
+ `)}su.exports={remember:Wg,recall:Bg,forget:Hg,listMemories:eu,loadGlobalInstructions:tu,loadProjectInstructions:nu,getMemoryContext:Gg,_getMemoryDir:Gr,_getMemoryFile:ns,_getGlobalNexMdPath:Ql}});var os=j((nb,cu)=>{var Fe=require("fs"),yn=require("path"),{C:tb}=ye(),{atomicWrite:Kg,withFileLockSync:zg}=vt(),io={bash:"ask",read_file:"allow",write_file:"ask",edit_file:"ask",list_directory:"allow",search_files:"allow",glob:"allow",grep:"allow",patch_file:"ask",web_fetch:"allow",web_search:"allow",ask_user:"allow",task_list:"allow",spawn_agents:"ask"},wn={...io};function ou(){let t=yn.join(process.cwd(),".nex","config.json");if(Fe.existsSync(t))try{let e=JSON.parse(Fe.readFileSync(t,"utf-8"));e.permissions&&(wn={...io,...e.permissions})}catch{}}function Yg(){let t=yn.join(process.cwd(),".nex"),e=yn.join(t,"config.json");Fe.existsSync(t)||Fe.mkdirSync(t,{recursive:!0}),zg(e,()=>{let s={};if(Fe.existsSync(e))try{s=JSON.parse(Fe.readFileSync(e,"utf-8"))}catch{s={}}s.permissions=wn,Kg(e,JSON.stringify(s,null,2))})}function ru(t){return wn[t]||"ask"}function Xg(t,e){return["allow","ask","deny"].includes(e)?(wn[t]=e,!0):!1}function Jg(t){return ru(t)}function Vg(){return Object.entries(wn).map(([t,e])=>({tool:t,mode:e}))}function Qg(){wn={...io}}var ss={readonly:{description:"Read-only access \u2014 can search and read but not modify",allowedTools:["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","ask_user","web_fetch","web_search","browser_open","browser_screenshot","task_list"],blockedTools:["bash","write_file","edit_file","patch_file","deploy","ssh_exec","service_manage","container_manage","container_exec","remote_agent"],autoConfirm:!1,allowDangerous:!1},developer:{description:"Standard developer access \u2014 can read, write, and run commands",allowedTools:null,blockedTools:["deploy","service_manage","container_manage","remote_agent"],autoConfirm:!1,allowDangerous:!1},admin:{description:"Full access \u2014 all tools, including deployment and infrastructure",allowedTools:null,blockedTools:[],autoConfirm:!1,allowDangerous:!0}};function iu(){let t=yn.join(process.cwd(),".nex","config.json");try{return Fe.existsSync(t)&&JSON.parse(Fe.readFileSync(t,"utf-8")).teamPermissions||null}catch{return null}}function Zg(t){let e=yn.join(process.cwd(),".nex"),s=yn.join(e,"config.json");Fe.existsSync(e)||Fe.mkdirSync(e,{recursive:!0});let o={};try{Fe.existsSync(s)&&(o=JSON.parse(Fe.readFileSync(s,"utf-8")))}catch{o={}}o.teamPermissions=t,Fe.writeFileSync(s,JSON.stringify(o,null,2),"utf-8")}function au(){let t=iu();if(!t)return ss.admin;let e=t.role||"admin",s=ss[e]||ss.admin;return{...s,...t.overrides,blockedTools:[...s.blockedTools||[],...t.overrides?.blockedTools||[]]}}function e$(t){let e=au();return e.blockedTools&&e.blockedTools.includes(t)?{allowed:!1,reason:`Tool "${t}" is blocked by permission preset "${e.description||"custom"}"`}:e.allowedTools&&!e.allowedTools.includes(t)?{allowed:!1,reason:`Tool "${t}" is not in the allowed list for this permission level`}:{allowed:!0}}function t$(){return Object.entries(ss).map(([t,e])=>({name:t,description:e.description,toolCount:e.allowedTools?`${e.allowedTools.length} allowed`:"all allowed",blockedCount:e.blockedTools.length}))}ou();cu.exports={getPermission:ru,setPermission:Xg,checkPermission:Jg,listPermissions:Vg,loadPermissions:ou,savePermissions:Yg,resetPermissions:Qg,DEFAULT_PERMISSIONS:io,PERMISSION_PRESETS:ss,loadPresetConfig:iu,savePresetConfig:Zg,getEffectivePreset:au,isToolAllowed:e$,listPresets:t$}});var Nt=j((ob,pu)=>{var zt=require("fs"),ao=require("path"),sb=require("readline"),{C:se}=ye(),ee=null,Yr=!1,Xr=null,lu=new Set(["read_file","list_directory","search_files","glob","grep","web_search","web_fetch","git_status","git_diff","git_log","git_show","ask_user"]);function co(){return ao.join(process.cwd(),".nex","plans")}function uu(){let t=co();zt.existsSync(t)||zt.mkdirSync(t,{recursive:!0})}function n$(t,e=[]){return ee={name:`plan-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,task:t,steps:e.map(s=>({description:s.description||s,files:s.files||[],status:"pending"})),status:"draft",createdAt:new Date().toISOString()},ee}function s$(){return ee}function o$(t){Yr=t}function r$(){return Yr}function i$(){return!ee||ee.status!=="draft"?!1:(ee.status="approved",ee.updatedAt=new Date().toISOString(),!0)}function a$(){return!ee||ee.status!=="approved"?!1:(ee.status="executing",!0)}function zr(t,e){return!ee||t<0||t>=ee.steps.length?!1:(ee.steps[t].status=e,ee.updatedAt=new Date().toISOString(),ee.steps.every(s=>s.status==="done"||s.status==="skipped")&&(ee.status="completed"),!0)}function c$(t){if(!t)return`${se.dim}No active plan${se.reset}`;let e={draft:`${se.yellow}DRAFT${se.reset}`,approved:`${se.green}APPROVED${se.reset}`,executing:`${se.blue}EXECUTING${se.reset}`,completed:`${se.green}COMPLETED${se.reset}`},s=[];s.push(`
415
+ ${se.bold}${se.cyan}Plan: ${t.task}${se.reset}`),s.push(`${se.dim}Status: ${e[t.status]||t.status}${se.reset}
416
+ `);for(let o=0;o<t.steps.length;o++){let n=t.steps[o],r;switch(n.status){case"done":r=`${se.green}\u2713${se.reset}`;break;case"in_progress":r=`${se.blue}\u2192${se.reset}`;break;case"skipped":r=`${se.dim}\u25CB${se.reset}`;break;default:r=`${se.dim} ${se.reset}`}s.push(` ${r} ${se.bold}Step ${o+1}:${se.reset} ${n.description}`),n.files.length>0&&s.push(` ${se.dim}Files: ${n.files.join(", ")}${se.reset}`)}return s.push(""),s.join(`
417
+ `)}function l$(t){if(t||(t=ee),!t)return null;uu();let e=ao.join(co(),`${t.name}.json`);return zt.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function u$(t){let e=ao.join(co(),`${t}.json`);if(!zt.existsSync(e))return null;try{let s=JSON.parse(zt.readFileSync(e,"utf-8"));return ee=s,s}catch{return null}}function d$(){uu();let t=co(),e=zt.readdirSync(t).filter(o=>o.endsWith(".json")),s=[];for(let o of e)try{let n=JSON.parse(zt.readFileSync(ao.join(t,o),"utf-8"));s.push({name:n.name,task:n.task,status:n.status,steps:n.steps?n.steps.length:0,createdAt:n.createdAt})}catch{}return s.sort((o,n)=>(n.createdAt||"").localeCompare(o.createdAt||""))}function f$(t){if(!t)return[];let e=[],s=t.match(/##\s+Steps?\s*\n([\s\S]*?)(?:\n##|\s*$)/i),o=s?s[1]:t,n=/^\s*(\d+)[.)]\s+(.+)/gm,r;for(;(r=n.exec(o))!==null;){let c=r[2].trim().replace(/^\*\*What\*\*:\s*/i,"").replace(/^\*\*\d+\.\*\*\s*/,"").replace(/\*\*/g,"").trim();c.length>3&&e.push({description:c,files:[],status:"pending"})}if(e.length===0){let i=/\*\*Step\s+\d+[:.]\*\*\s*(.+)/gi;for(;(r=i.exec(t))!==null;){let c=r[1].replace(/\*\*/g,"").trim();c.length>3&&e.push({description:c,files:[],status:"pending"})}}if(e.length>0){let i=/\*\*(?:Where|Files?)\*\*:\s*(.+)/gi,c=[...t.matchAll(i)];for(let l=0;l<Math.min(e.length,c.length);l++){let u=c[l][1];e[l].files=u.split(/[,\s]+/).filter(d=>/[./]/.test(d)).slice(0,5)}}return e}function p$(t){Xr=t}function m$(){return Xr}function h$(){ee=null,Yr=!1,Xr=null,w$()}function g$(){return`
307
418
  PLAN MODE ACTIVE: You are in analysis-only mode. You MUST NOT execute any changes.
308
419
 
309
420
  # Allowed Tools (read-only)
310
- You may ONLY use these tools: ${[...jc].join(", ")}
421
+ You may ONLY use these tools: ${[...lu].join(", ")}
311
422
  Any other tool call will be blocked and returned with an error.
312
423
 
313
424
  # Analysis Phase
@@ -338,42 +449,44 @@ Bullet list of potential issues and mitigations.
338
449
  # Important
339
450
  - Order steps by dependency (later steps may depend on earlier ones).
340
451
  - After presenting the plan, tell the user to type \`/plan approve\` to proceed.
341
- - Do NOT make any file changes \u2014 your role is analysis and planning only.`}var Ot=0;function th(){!K||K.status!=="executing"||(Ot>0&&tr(Ot-1,"done"),Ot<K.steps.length&&(tr(Ot,"in_progress"),Ot++))}function nh(){if(!K||K.status!=="executing"||K.steps.length===0)return null;let t=Math.min(Ot,K.steps.length),e=K.steps.length,s=Math.max(0,t-1),n=K.steps[s]?.description||"";return{current:t,total:e,description:n}}function sh(){Ot=0}var Uc=["interactive","semi-auto","autonomous"],Wc="interactive";function oh(t){return Uc.includes(t)?(Wc=t,!0):!1}function rh(){return Wc}Bc.exports={createPlan:Fm,getActivePlan:Um,setPlanMode:Wm,isPlanMode:Bm,approvePlan:Hm,startExecution:Gm,updateStep:tr,formatPlan:zm,savePlan:Km,loadPlan:Ym,listPlans:Jm,clearPlan:Zm,getPlanModePrompt:eh,setPlanContent:Xm,getPlanContent:Qm,extractStepsFromText:Vm,advancePlanStep:th,getPlanStepInfo:nh,PLAN_MODE_ALLOWED_TOOLS:jc,setAutonomyLevel:oh,getAutonomyLevel:rh,AUTONOMY_LEVELS:Uc}});var Zc=L((My,Qc)=>{var{C:w}=de();function ih(t){if(!t)return"";let e=t.split(`
342
- `),s=[],n=!1,o="";for(let r of e){if(r.trim().startsWith("```")){if(n)s.push(`${w.dim}${"\u2500".repeat(40)}${w.reset}`),n=!1,o="";else{n=!0,o=r.trim().substring(3).trim();let i=o?` ${o} `:"";s.push(`${w.dim}${"\u2500".repeat(3)}${i}${"\u2500".repeat(Math.max(0,37-i.length))}${w.reset}`)}continue}if(n){s.push(` ${rr(r,o)}`);continue}if(r.startsWith("### ")){s.push(`${w.bold}${w.cyan} ${Pt(r.substring(4))}${w.reset}`);continue}if(r.startsWith("## ")){s.push(`${w.bold}${w.cyan} ${Pt(r.substring(3))}${w.reset}`);continue}if(r.startsWith("# ")){s.push(`${w.bold}${w.cyan}${Pt(r.substring(2))}${w.reset}`);continue}if(/^\s*[-*]\s/.test(r)){let i=r.match(/^(\s*)/)[1],c=r.replace(/^\s*[-*]\s/,"");s.push(`${i}${w.cyan}\u2022${w.reset} ${Lt(c)}`);continue}if(/^\s*\d+\.\s/.test(r)){let i=r.match(/^(\s*)(\d+)\.\s(.*)/);if(i){s.push(`${i[1]}${w.cyan}${i[2]}.${w.reset} ${Lt(i[3])}`);continue}}s.push(Lt(r))}return s.join(`
343
- `)}function Pt(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function Lt(t){return t?t.replace(/`([^`]+)`/g,`${w.cyan}$1${w.reset}`).replace(/\*\*([^*]+)\*\*/g,`${w.bold}$1${w.reset}`).replace(/\*([^*]+)\*/g,`${w.dim}$1${w.reset}`).replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${w.cyan}$1${w.reset} ${w.dim}($2)${w.reset}`):""}function rr(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?Hc(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?Gc(t):e==="json"||e==="jsonc"?zc(t):e==="python"||e==="py"?Kc(t):e==="go"||e==="golang"?Yc(t):e==="rust"||e==="rs"?Jc(t):e==="css"||e==="scss"||e==="less"?Vc(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?Xc(t):t:""}function Hc(t){let e=/\b(const|let|var|function|return|if|else|for|while|class|import|export|from|require|async|await|new|this|throw|try|catch|switch|case|break|default|typeof|instanceof)\b/g,s=/(["'`])(?:(?=(\\?))\2.)*?\1/g,n=/(\/\/.*$)/,o=/\b(\d+\.?\d*)\b/g,r=t;return r=r.replace(o,`${w.yellow}$1${w.reset}`),r=r.replace(e,`${w.magenta}$1${w.reset}`),r=r.replace(s,`${w.green}$&${w.reset}`),r=r.replace(n,`${w.dim}$1${w.reset}`),r}function Gc(t){let e=/^(\s*)([\w-]+)/,s=/(--?\w[\w-]*)/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(#.*$)/,r=t;return r=r.replace(s,`${w.cyan}$1${w.reset}`),r=r.replace(e,`$1${w.green}$2${w.reset}`),r=r.replace(n,`${w.yellow}$&${w.reset}`),r=r.replace(o,`${w.dim}$1${w.reset}`),r}function zc(t){let e=/("[\w-]+")\s*:/g,s=/:\s*("(?:[^"\\]|\\.)*")/g,n=/:\s*(\d+\.?\d*)/g,o=/:\s*(true|false|null)/g,r=t;return r=r.replace(e,`${w.cyan}$1${w.reset}:`),r=r.replace(s,`: ${w.green}$1${w.reset}`),r=r.replace(n,`: ${w.yellow}$1${w.reset}`),r=r.replace(o,`: ${w.magenta}$1${w.reset}`),r}function Kc(t){let e=/\b(def|class|if|elif|else|for|while|return|import|from|as|try|except|finally|raise|with|yield|lambda|pass|break|continue|and|or|not|in|is|None|True|False|self|async|await|nonlocal|global)\b/g,s=/("""[\s\S]*?"""|'''[\s\S]*?'''|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')/g,n=/(#.*$)/,o=/\b(\d+\.?\d*)\b/g,r=/^(\s*@\w+)/,i=t;return i=i.replace(o,`${w.yellow}$1${w.reset}`),i=i.replace(e,`${w.magenta}$1${w.reset}`),i=i.replace(r,`${w.cyan}$1${w.reset}`),i=i.replace(s,`${w.green}$&${w.reset}`),i=i.replace(n,`${w.dim}$1${w.reset}`),i}function Yc(t){let e=/\b(func|package|import|var|const|type|struct|interface|map|chan|go|defer|return|if|else|for|range|switch|case|default|break|continue|select|fallthrough|nil|true|false|make|new|len|cap|append|copy|delete|panic|recover)\b/g,s=/\b(string|int|int8|int16|int32|int64|uint|uint8|uint16|uint32|uint64|float32|float64|bool|byte|rune|error|any)\b/g,n=/(["'`])(?:(?=(\\?))\2.)*?\1/g,o=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,i=t;return i=i.replace(r,`${w.yellow}$1${w.reset}`),i=i.replace(s,`${w.cyan}$1${w.reset}`),i=i.replace(e,`${w.magenta}$1${w.reset}`),i=i.replace(n,`${w.green}$&${w.reset}`),i=i.replace(o,`${w.dim}$1${w.reset}`),i}function Jc(t){let e=/\b(fn|let|mut|const|struct|enum|impl|trait|pub|use|mod|crate|self|super|match|if|else|for|while|loop|return|break|continue|where|as|in|ref|move|async|await|unsafe|extern|type|static|dyn|macro_rules)\b/g,s=/\b(i8|i16|i32|i64|i128|u8|u16|u32|u64|u128|f32|f64|bool|char|str|String|Vec|Option|Result|Box|Rc|Arc|Self|Some|None|Ok|Err|true|false)\b/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,i=/\b(\w+!)/g,c=t;return c=c.replace(r,`${w.yellow}$1${w.reset}`),c=c.replace(s,`${w.cyan}$1${w.reset}`),c=c.replace(e,`${w.magenta}$1${w.reset}`),c=c.replace(i,`${w.yellow}$1${w.reset}`),c=c.replace(n,`${w.green}$&${w.reset}`),c=c.replace(o,`${w.dim}$1${w.reset}`),c}function Vc(t){let e=/^(\s*)([\w-]+)\s*:/,s=/:\s*([^;]+)/,n=/^(\s*[.#@][\w-]+)/,o=/\b(\d+\.?\d*(px|em|rem|%|vh|vw|s|ms|deg|fr)?)\b/g,r=/(\/\*.*?\*\/|\/\/.*$)/,i=/(#[0-9a-fA-F]{3,8})\b/g,c=t;return c=c.replace(i,`${w.yellow}$1${w.reset}`),c=c.replace(o,`${w.yellow}$1${w.reset}`),c=c.replace(e,`$1${w.cyan}$2${w.reset}:`),c=c.replace(n,`$1${w.magenta}$&${w.reset}`),c=c.replace(r,`${w.dim}$1${w.reset}`),c}function Xc(t){let e=/<\/?(\w[\w-]*)/g,s=/\s([\w-]+)=/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(<!--.*?-->)/g,r=/(&\w+;)/g,i=t;return i=i.replace(o,`${w.dim}$1${w.reset}`),i=i.replace(n,`${w.green}$&${w.reset}`),i=i.replace(e,`<${w.magenta}$1${w.reset}`),i=i.replace(s,` ${w.cyan}$1${w.reset}=`),i=i.replace(r,`${w.yellow}$1${w.reset}`),i}function ah(t,e){if(!t||t.length===0)return"";let s=t.map((i,c)=>{let l=e.reduce((u,d)=>Math.max(u,(d[c]||"").length),0);return Math.max(i.length,l)}),n=s.map(i=>"\u2500".repeat(i+2)).join("\u253C"),o=t.map((i,c)=>` ${w.bold}${i.padEnd(s[c])}${w.reset} `).join("\u2502"),r=[];r.push(`${w.dim}\u250C${n.replace(/┼/g,"\u252C")}\u2510${w.reset}`),r.push(`${w.dim}\u2502${w.reset}${o}${w.dim}\u2502${w.reset}`),r.push(`${w.dim}\u251C${n}\u2524${w.reset}`);for(let i of e){let c=t.map((l,u)=>` ${(i[u]||"").padEnd(s[u])} `).join(`${w.dim}\u2502${w.reset}`);r.push(`${w.dim}\u2502${w.reset}${c}${w.dim}\u2502${w.reset}`)}return r.push(`${w.dim}\u2514${n.replace(/┼/g,"\u2534")}\u2518${w.reset}`),r.join(`
344
- `)}function ch(t,e,s,n=30){let o=s>0?Math.round(e/s*100):0,r=Math.round(o/100*n),i=n-r,c=o>=100?w.green:o>50?w.yellow:w.cyan;return` ${t} ${c}${"\u2588".repeat(r)}${w.dim}${"\u2591".repeat(i)}${w.reset} ${o}% (${e}/${s})`}var or=class{constructor(){this.buffer="",this.inCodeBlock=!1,this.codeBlockLang="",this.lineCount=0,this._cursorTimer=null,this._cursorFrame=0,this._cursorActive=!1}_safeWrite(e){try{process.stdout.write(e)}catch(s){if(s.code!=="EPIPE")throw s}}_cursorWrite(e){try{process.stderr.write(e)}catch(s){if(s.code!=="EPIPE")throw s}}startCursor(){process.stderr.isTTY&&(this._cursorActive=!0,this._cursorFrame=0,this._cursorWrite("\x1B[?25l"),this._renderCursor(),this._cursorTimer=setInterval(()=>this._renderCursor(),100))}_renderCursor(){let s=[0,1,2,3,4,3,2,1],n=s[this._cursorFrame%s.length],o="";for(let r=0;r<5;r++)o+=r===n?"\x1B[36m\u25CF\x1B[0m":" ";this._cursorWrite(`\x1B[2K\r${o}`),this._cursorFrame++}_clearCursorLine(){this._cursorActive&&this._cursorWrite("\x1B[2K\r")}stopCursor(){this._cursorTimer&&(clearInterval(this._cursorTimer),this._cursorTimer=null),this._cursorActive&&(this._cursorWrite("\x1B[2K\r\x1B[?25h"),this._cursorActive=!1)}push(e){if(!e)return;this._clearCursorLine(),this.buffer+=e;let s;for(;(s=this.buffer.indexOf(`
345
- `))!==-1;){let n=this.buffer.substring(0,s);this.buffer=this.buffer.substring(s+1),this._renderLine(n)}this._cursorActive&&(this._renderCursor(),this._cursorTimer&&clearInterval(this._cursorTimer),this._cursorTimer=setInterval(()=>this._renderCursor(),100))}flush(){this.stopCursor(),this.buffer&&(this._renderLine(this.buffer),this.buffer=""),this.inCodeBlock&&(this._safeWrite(`${w.dim}${"\u2500".repeat(40)}${w.reset}
346
- `),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${w.dim}${"\u2500".repeat(40)}${w.reset}
347
- `),this.inCodeBlock=!1,this.codeBlockLang="";else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let s=this.codeBlockLang?` ${this.codeBlockLang} `:"";this._safeWrite(`${w.dim}${"\u2500".repeat(3)}${s}${"\u2500".repeat(Math.max(0,37-s.length))}${w.reset}
348
- `)}return}if(this.inCodeBlock){this._safeWrite(` ${rr(e,this.codeBlockLang)}
349
- `);return}if(e.startsWith("### ")){this._safeWrite(`${w.bold}${w.cyan} ${Pt(e.substring(4))}${w.reset}
350
- `);return}if(e.startsWith("## ")){this._safeWrite(`${w.bold}${w.cyan} ${Pt(e.substring(3))}${w.reset}
351
- `);return}if(e.startsWith("# ")){this._safeWrite(`${w.bold}${w.cyan}${Pt(e.substring(2))}${w.reset}
352
- `);return}if(/^\s*[-*]\s/.test(e)){let s=e.match(/^(\s*)/)[1],n=e.replace(/^\s*[-*]\s/,"");this._safeWrite(`${s}${w.cyan}\u2022${w.reset} ${Lt(n)}
353
- `);return}if(/^\s*\d+\.\s/.test(e)){let s=e.match(/^(\s*)(\d+)\.\s(.*)/);if(s){this._safeWrite(`${s[1]}${w.cyan}${s[2]}.${w.reset} ${Lt(s[3])}
354
- `);return}}this._safeWrite(`${Lt(e)}
355
- `)}};Qc.exports={renderMarkdown:ih,renderInline:Lt,stripHeadingMarkers:Pt,highlightCode:rr,highlightJS:Hc,highlightBash:Gc,highlightJSON:zc,highlightPython:Kc,highlightGo:Yc,highlightRust:Jc,highlightCSS:Vc,highlightHTML:Xc,renderTable:ah,renderProgress:ch,StreamRenderer:or}});var cr=L((Py,sl)=>{var{execSync:lh}=require("child_process"),ir=require("path"),Rn=require("fs"),ar=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function el(){return ir.join(process.cwd(),".nex","hooks")}function uh(){return ir.join(process.cwd(),".nex","config.json")}function tl(){let t=uh();if(!Rn.existsSync(t))return{};try{return JSON.parse(Rn.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function Rs(t){if(!ar.includes(t))return[];let e=[],s=el(),n=ir.join(s,t);Rn.existsSync(n)&&e.push(n);let o=tl();if(o[t]){let r=Array.isArray(o[t])?o[t]:[o[t]];e.push(...r)}return e}function nl(t,e={},s=3e4){try{return{success:!0,output:lh(t,{cwd:process.cwd(),encoding:"utf-8",timeout:s,env:{...process.env,...e},stdio:["pipe","pipe","pipe"]}).trim()}}catch(n){return{success:!1,error:n.stderr?n.stderr.trim():n.message}}}function dh(t,e={}){let s=Rs(t);if(s.length===0)return[];let n={};for(let[r,i]of Object.entries(e))n[`NEX_${r.toUpperCase()}`]=String(i);let o=[];for(let r of s){let i=nl(r,n);if(o.push({command:r,...i}),!i.success&&t.startsWith("pre-"))break}return o}function fh(t){return Rs(t).length>0}function ph(){let t=[];for(let e of ar){let s=Rs(e);s.length>0&&t.push({event:e,commands:s})}return t}function mh(){let t=el();return Rn.existsSync(t)||Rn.mkdirSync(t,{recursive:!0}),t}sl.exports={HOOK_EVENTS:ar,loadHookConfig:tl,getHooksForEvent:Rs,executeHook:nl,runHooks:dh,hasHooks:fh,listHooks:ph,initHooksDir:mh}});var fe=L((jy,gl)=>{var{C:b,Spinner:Yt,TaskProgress:hh,formatToolCall:gh,formatResult:$h,formatToolSummary:ll,formatSectionHeader:lr,setActiveTaskProgress:Ly}=de(),{callStream:yh}=ge(),{parseToolArgs:wh}=Jn(),{executeTool:bh}=Be(),{gatherProjectContext:xh}=xs(),{fitToContext:_h,forceCompress:ur,getUsage:kh,estimateTokens:vh}=De(),{autoSave:Sh,flushAutoSave:Eh}=Ct();function Ye(t){Sh(t),Eh()}var{getMemoryContext:Th}=ht(),{checkPermission:Rh,setPermission:Ch,savePermissions:Ah}=Tn(),{confirm:ul,setAllowAlwaysHandler:Oh}=We(),{isPlanMode:Ms,getPlanModePrompt:Nh,PLAN_MODE_ALLOWED_TOOLS:dl,setPlanContent:Mh,extractStepsFromText:Ph,createPlan:Lh,getActivePlan:Iy,startExecution:qy,advancePlanStep:Ih,getPlanStepInfo:qh}=Mt(),{StreamRenderer:Dh}=Zc(),{runHooks:ol}=cr(),{routeMCPCall:jh,getMCPToolDefinitions:Fh}=ts(),{getSkillInstructions:Uh,getSkillToolDefinitions:Wh,routeSkillCall:Bh}=un(),{trackUsage:Hh}=Ft(),{validateToolArgs:Gh}=wo(),{filterToolsForModel:rl,getModelTier:zh,PROVIDER_DEFAULT_TIER:Dy}=Oo(),{getConfiguredProviders:Kh,getActiveProviderName:Cn,getActiveModelId:Cs,setActiveModel:il,MODEL_EQUIVALENTS:Ps}=ge(),br=require("fs"),xr=require("path"),al=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi;function Yh(t){let e=[],s;for(al.lastIndex=0;(s=al.exec(t))!==null;){let n=s[1].trim(),o=n.startsWith("~")?n.replace("~",process.env.HOME||""):xr.resolve(n);br.existsSync(o)&&e.push({raw:n,abs:o})}return e}function Jh(t){let e=br.readFileSync(t),s=xr.extname(t).toLowerCase().replace(".",""),n=s==="jpg"||s==="jpeg"?"image/jpeg":s==="png"?"image/png":s==="gif"?"image/gif":s==="webp"?"image/webp":"image/png";return{data:e.toString("base64"),media_type:n}}function fl(t){let e=Yh(t);if(e.length===0)return t;let s=[{type:"text",text:t}];for(let n of e)try{let{data:o,media_type:r}=Jh(n.abs);s.push({type:"image",media_type:r,data:o})}catch{}return s.length>1?s:t}var dr=null,fr=null,pr=null;function Jt(){if(dr===null){let{TOOL_DEFINITIONS:t}=Be();dr=t}return fr===null&&(fr=Wh()),pr===null&&(pr=Fh()),[...dr,...fr,...pr]}var yr=50;function Vh(t){Number.isFinite(t)&&t>0&&(yr=t)}var As=()=>null;function Xh(t){As=t}var An=null,wr=null,Vt=null,Os=new Map,Qh=1e4,Zh=6e3,eg=/\b((?:API|ACCESS|AUTH|BEARER|CLIENT|GITHUB|GITLAB|SLACK|STRIPE|TWILIO|SENDGRID|AWS|GCP|AZURE|OPENAI|ANTHROPIC|GEMINI|OLLAMA)[_A-Z0-9]*(?:KEY|TOKEN|SECRET|PASS(?:WORD)?|CREDENTIAL)[_A-Z0-9]*)\s*=\s*["']?([A-Za-z0-9\-_.+/=]{10,})["']?/g;function tg(t){return!t||typeof t!="string"?t:t.replace(eg,(e,s)=>`${s}=***REDACTED***`)}function ng(t){let e=tg(t);if(vh(e)>Qh)try{let{compressToolResult:n}=De();return n(e,Zh)}catch{return e}return e}function pl(t){try{let{getActiveModel:e}=ge(),s=e(),n=s?`${s.provider}:${s.id}`:"default";if(Os.has(n))return Os.get(n);let o=rl(t);return Os.set(n,o),o}catch{return rl(t)}}function sg(){Os.clear()}async function ml(){try{let t=require("fs").promises,e=require("path"),s=[e.join(process.cwd(),"package.json"),e.join(process.cwd(),".git","HEAD"),e.join(process.cwd(),"README.md"),e.join(process.cwd(),"NEX.md")],o=(await Promise.allSettled(s.map(r=>t.stat(r).then(i=>`${r}:${i.mtimeMs}`)))).filter(r=>r.status==="fulfilled").map(r=>r.value);try{let{getMemoryContextHash:r}=ht(),i=r();i&&o.push(`memory:${i}`)}catch{}try{let r=e.join(process.cwd(),".nex","brain");if(br.existsSync(r)){let i=await t.stat(r);o.push(`brain:${i.mtimeMs}`)}}catch{}return o.join("|")}catch{return`fallback:${Date.now()}`}}function og(){An=null,wr=null,Vt=null}var rg=new Set(["spawn_agents"]),mr=5,hr=3,gr=2,ig=parseInt(process.env.NEX_STALE_WARN_MS||"60000",10),ag=parseInt(process.env.NEX_STALE_ABORT_MS||"120000",10),cg=process.env.NEX_STALE_AUTO_SWITCH!=="0";function lg(t){try{let e=require("fs"),s=require("path"),n=s.join(process.cwd(),".nex","plans");e.existsSync(n)||e.mkdirSync(n,{recursive:!0});let o=s.join(n,"current-plan.md");e.writeFileSync(o,t,"utf-8")}catch{}}Oh(t=>{Ch(t,"allow"),Ah(),console.log(`${b.green} \u2713 ${t}: always allow${b.reset}`)});async function ug(t){let e=t.function.name,s=wh(t.function.arguments),n=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!s){let l=Jt().find(d=>d.function.name===e),u=l?JSON.stringify(l.function.parameters,null,2):"unknown";return console.log(`${b.yellow} \u26A0 ${e}: malformed arguments, sending schema hint${b.reset}`),{callId:n,fnName:e,args:null,canExecute:!1,errorResult:{role:"tool",content:`ERROR: Malformed tool arguments. Could not parse your arguments as JSON.
452
+ - Do NOT make any file changes \u2014 your role is analysis and planning only.`}var Kt=0;function $$(){!ee||ee.status!=="executing"||(Kt>0&&zr(Kt-1,"done"),Kt<ee.steps.length&&(zr(Kt,"in_progress"),Kt++))}function y$(){if(!ee||ee.status!=="executing"||ee.steps.length===0)return null;let t=Math.min(Kt,ee.steps.length),e=ee.steps.length,s=Math.max(0,t-1),o=ee.steps[s]?.description||"";return{current:t,total:e,description:o}}function w$(){Kt=0}var du=["interactive","semi-auto","autonomous"],fu="interactive";function b$(t){return du.includes(t)?(fu=t,!0):!1}function _$(){return fu}pu.exports={createPlan:n$,getActivePlan:s$,setPlanMode:o$,isPlanMode:r$,approvePlan:i$,startExecution:a$,updateStep:zr,formatPlan:c$,savePlan:l$,loadPlan:u$,listPlans:d$,clearPlan:h$,getPlanModePrompt:g$,setPlanContent:p$,getPlanContent:m$,extractStepsFromText:f$,advancePlanStep:$$,getPlanStepInfo:y$,PLAN_MODE_ALLOWED_TOOLS:lu,setAutonomyLevel:b$,getAutonomyLevel:_$,AUTONOMY_LEVELS:du}});var vu=j((rb,xu)=>{var{C:b}=ye();function mu(){return Math.max(10,(process.stdout.columns||80)-2)}function k$(t){if(!t)return"";let e=t.split(`
453
+ `),s=[],o=!1,n="";for(let r of e){let i=mu();if(r.trim().startsWith("```")){if(o)s.push(`${b.dim}${"\u2500".repeat(40)}${b.reset}`),o=!1,n="";else{o=!0,n=r.trim().substring(3).trim();let c=n?` ${n} `:"";s.push(`${b.dim}${"\u2500".repeat(3)}${c}${"\u2500".repeat(Math.max(0,37-c.length))}${b.reset}`)}continue}if(o){s.push(` ${Vr(r,n)}`);continue}if(r.startsWith("### ")){s.push(`${b.bold}${b.cyan} ${Yt(r.substring(4))}${b.reset}`);continue}if(r.startsWith("## ")){s.push(`${b.bold}${b.cyan} ${Yt(r.substring(3))}${b.reset}`);continue}if(r.startsWith("# ")){s.push(`${b.bold}${b.cyan}${Yt(r.substring(2))}${b.reset}`);continue}if(/^\s*[-*]\s/.test(r)){let c=r.match(/^(\s*)/)[1],l=r.replace(/^\s*[-*]\s/,""),u=`${c}${b.cyan}\u2022${b.reset} ${Xt(l)}`;s.push(Jt(u,i,c+" "));continue}if(/^\s*\d+\.\s/.test(r)){let c=r.match(/^(\s*)(\d+)\.\s(.*)/);if(c){let l=c[1],u=c[2],d=c[3],f=`${l}${b.cyan}${u}.${b.reset} ${Xt(d)}`,m=l+" ".repeat(u.length+2);s.push(Jt(f,i,m));continue}}s.push(Jt(Xt(r),i))}return s.join(`
454
+ `)}function Yt(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function Xt(t){return t?t.replace(/`([^`]+)`/g,`${b.cyan}$1${b.reset}`).replace(/\*\*([^*]+)\*\*/g,`${b.bold}$1${b.reset}`).replace(/\*([^*]+)\*/g,`${b.dim}$1${b.reset}`).replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${b.cyan}$1${b.reset} ${b.dim}($2)${b.reset}`):""}function Vr(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?hu(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?gu(t):e==="json"||e==="jsonc"?$u(t):e==="python"||e==="py"?yu(t):e==="go"||e==="golang"?wu(t):e==="rust"||e==="rs"?bu(t):e==="css"||e==="scss"||e==="less"?_u(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?ku(t):t:""}function hu(t){let e=/\b(const|let|var|function|return|if|else|for|while|class|import|export|from|require|async|await|new|this|throw|try|catch|switch|case|break|default|typeof|instanceof)\b/g,s=/(["'`])(?:(?=(\\?))\2.)*?\1/g,o=/(\/\/.*$)/,n=/\b(\d+\.?\d*)\b/g,r=t;return r=r.replace(n,`${b.yellow}$1${b.reset}`),r=r.replace(e,`${b.magenta}$1${b.reset}`),r=r.replace(s,`${b.green}$&${b.reset}`),r=r.replace(o,`${b.dim}$1${b.reset}`),r}function gu(t){let e=/^(\s*)([\w-]+)/,s=/(--?\w[\w-]*)/g,o=/(["'])(?:(?=(\\?))\2.)*?\1/g,n=/(#.*$)/,r=t;return r=r.replace(s,`${b.cyan}$1${b.reset}`),r=r.replace(e,`$1${b.green}$2${b.reset}`),r=r.replace(o,`${b.yellow}$&${b.reset}`),r=r.replace(n,`${b.dim}$1${b.reset}`),r}function $u(t){let e=/("[\w-]+")\s*:/g,s=/:\s*("(?:[^"\\]|\\.)*")/g,o=/:\s*(\d+\.?\d*)/g,n=/:\s*(true|false|null)/g,r=t;return r=r.replace(e,`${b.cyan}$1${b.reset}:`),r=r.replace(s,`: ${b.green}$1${b.reset}`),r=r.replace(o,`: ${b.yellow}$1${b.reset}`),r=r.replace(n,`: ${b.magenta}$1${b.reset}`),r}function yu(t){let e=/\b(def|class|if|elif|else|for|while|return|import|from|as|try|except|finally|raise|with|yield|lambda|pass|break|continue|and|or|not|in|is|None|True|False|self|async|await|nonlocal|global)\b/g,s=/("""[\s\S]*?"""|'''[\s\S]*?'''|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')/g,o=/(#.*$)/,n=/\b(\d+\.?\d*)\b/g,r=/^(\s*@\w+)/,i=t;return i=i.replace(n,`${b.yellow}$1${b.reset}`),i=i.replace(e,`${b.magenta}$1${b.reset}`),i=i.replace(r,`${b.cyan}$1${b.reset}`),i=i.replace(s,`${b.green}$&${b.reset}`),i=i.replace(o,`${b.dim}$1${b.reset}`),i}function wu(t){let e=/\b(func|package|import|var|const|type|struct|interface|map|chan|go|defer|return|if|else|for|range|switch|case|default|break|continue|select|fallthrough|nil|true|false|make|new|len|cap|append|copy|delete|panic|recover)\b/g,s=/\b(string|int|int8|int16|int32|int64|uint|uint8|uint16|uint32|uint64|float32|float64|bool|byte|rune|error|any)\b/g,o=/(["'`])(?:(?=(\\?))\2.)*?\1/g,n=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,i=t;return i=i.replace(r,`${b.yellow}$1${b.reset}`),i=i.replace(s,`${b.cyan}$1${b.reset}`),i=i.replace(e,`${b.magenta}$1${b.reset}`),i=i.replace(o,`${b.green}$&${b.reset}`),i=i.replace(n,`${b.dim}$1${b.reset}`),i}function bu(t){let e=/\b(fn|let|mut|const|struct|enum|impl|trait|pub|use|mod|crate|self|super|match|if|else|for|while|loop|return|break|continue|where|as|in|ref|move|async|await|unsafe|extern|type|static|dyn|macro_rules)\b/g,s=/\b(i8|i16|i32|i64|i128|u8|u16|u32|u64|u128|f32|f64|bool|char|str|String|Vec|Option|Result|Box|Rc|Arc|Self|Some|None|Ok|Err|true|false)\b/g,o=/(["'])(?:(?=(\\?))\2.)*?\1/g,n=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,i=/\b(\w+!)/g,c=t;return c=c.replace(r,`${b.yellow}$1${b.reset}`),c=c.replace(s,`${b.cyan}$1${b.reset}`),c=c.replace(e,`${b.magenta}$1${b.reset}`),c=c.replace(i,`${b.yellow}$1${b.reset}`),c=c.replace(o,`${b.green}$&${b.reset}`),c=c.replace(n,`${b.dim}$1${b.reset}`),c}function _u(t){let e=/^(\s*)([\w-]+)\s*:/,s=/:\s*([^;]+)/,o=/^(\s*[.#@][\w-]+)/,n=/\b(\d+\.?\d*(px|em|rem|%|vh|vw|s|ms|deg|fr)?)\b/g,r=/(\/\*.*?\*\/|\/\/.*$)/,i=/(#[0-9a-fA-F]{3,8})\b/g,c=t;return c=c.replace(i,`${b.yellow}$1${b.reset}`),c=c.replace(n,`${b.yellow}$1${b.reset}`),c=c.replace(e,`$1${b.cyan}$2${b.reset}:`),c=c.replace(o,`$1${b.magenta}$&${b.reset}`),c=c.replace(r,`${b.dim}$1${b.reset}`),c}function ku(t){let e=/<\/?(\w[\w-]*)/g,s=/\s([\w-]+)=/g,o=/(["'])(?:(?=(\\?))\2.)*?\1/g,n=/(<!--.*?-->)/g,r=/(&\w+;)/g,i=t;return i=i.replace(n,`${b.dim}$1${b.reset}`),i=i.replace(o,`${b.green}$&${b.reset}`),i=i.replace(e,`<${b.magenta}$1${b.reset}`),i=i.replace(s,` ${b.cyan}$1${b.reset}=`),i=i.replace(r,`${b.yellow}$1${b.reset}`),i}function Jt(t,e,s=""){if(!e||e<10)return t;let o="",n=0,r=-1,i=0,c=0,l=t.length;for(;i<l;){if(t[i]==="\x1B"){let u=i+1;if(u<l&&t[u]==="["){for(u++;u<l&&!/[a-zA-Z]/.test(t[u]);)u++;u<l&&u++}i=u;continue}if(t[i]===" "&&(r=i),n++,n>e&&r!==-1){o+=t.slice(c,r)+`
455
+ `+s,c=r+1,i=c,n=s.length,r=-1;continue}n>e&&r===-1&&(o+=t.slice(c,i)+`
456
+ `+s,c=i,n=s.length+1),i++}return o+=t.slice(c),o}function x$(t,e){if(!t||t.length===0)return"";let s=t.map((i,c)=>{let l=e.reduce((u,d)=>Math.max(u,(d[c]||"").length),0);return Math.max(i.length,l)}),o=s.map(i=>"\u2500".repeat(i+2)).join("\u253C"),n=t.map((i,c)=>` ${b.bold}${i.padEnd(s[c])}${b.reset} `).join("\u2502"),r=[];r.push(`${b.dim}\u250C${o.replace(/┼/g,"\u252C")}\u2510${b.reset}`),r.push(`${b.dim}\u2502${b.reset}${n}${b.dim}\u2502${b.reset}`),r.push(`${b.dim}\u251C${o}\u2524${b.reset}`);for(let i of e){let c=t.map((l,u)=>` ${(i[u]||"").padEnd(s[u])} `).join(`${b.dim}\u2502${b.reset}`);r.push(`${b.dim}\u2502${b.reset}${c}${b.dim}\u2502${b.reset}`)}return r.push(`${b.dim}\u2514${o.replace(/┼/g,"\u2534")}\u2518${b.reset}`),r.join(`
457
+ `)}function v$(t,e,s,o=30){let n=s>0?Math.round(e/s*100):0,r=Math.round(n/100*o),i=o-r,c=n>=100?b.green:n>50?b.yellow:b.cyan;return` ${t} ${c}${"\u2588".repeat(r)}${b.dim}${"\u2591".repeat(i)}${b.reset} ${n}% (${e}/${s})`}var Jr=class{constructor(){this.buffer="",this.inCodeBlock=!1,this.codeBlockLang="",this.lineCount=0,this._cursorTimer=null,this._cursorFrame=0,this._cursorActive=!1}_safeWrite(e){try{process.stdout.write(e)}catch(s){if(s.code!=="EPIPE")throw s}}_cursorWrite(e){try{process.stderr.write(e)}catch(s){if(s.code!=="EPIPE")throw s}}startCursor(){process.stderr.isTTY&&(this._cursorActive=!0,this._cursorFrame=0,this._cursorWrite("\x1B[?25l"),this._renderCursor(),this._cursorTimer=setInterval(()=>this._renderCursor(),100))}_renderCursor(){let s=[0,1,2,3,4,3,2,1],o=s[this._cursorFrame%s.length],n="";for(let r=0;r<5;r++)n+=r===o?"\x1B[36m\u25CF\x1B[0m":" ";this._cursorWrite(`\x1B[2K\r${n}`),this._cursorFrame++}_clearCursorLine(){this._cursorActive&&this._cursorWrite("\x1B[2K\r")}stopCursor(){this._cursorTimer&&(clearInterval(this._cursorTimer),this._cursorTimer=null),this._cursorActive&&(this._cursorWrite("\x1B[2K\r\x1B[?25h"),this._cursorActive=!1)}push(e){if(!e)return;this._clearCursorLine(),this.buffer+=e;let s;for(;(s=this.buffer.indexOf(`
458
+ `))!==-1;){let o=this.buffer.substring(0,s);this.buffer=this.buffer.substring(s+1),this._renderLine(o)}this._cursorActive&&(this._renderCursor(),this._cursorTimer&&clearInterval(this._cursorTimer),this._cursorTimer=setInterval(()=>this._renderCursor(),100))}flush(){this.stopCursor(),this.buffer&&(this._renderLine(this.buffer),this.buffer=""),this.inCodeBlock&&(this._safeWrite(`${b.dim}${"\u2500".repeat(40)}${b.reset}
459
+ `),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){let s=mu();if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${b.dim}${"\u2500".repeat(40)}${b.reset}
460
+ `),this.inCodeBlock=!1,this.codeBlockLang="";else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let n=this.codeBlockLang?` ${this.codeBlockLang} `:"";this._safeWrite(`${b.dim}${"\u2500".repeat(3)}${n}${"\u2500".repeat(Math.max(0,37-n.length))}${b.reset}
461
+ `)}return}if(this.inCodeBlock){this._safeWrite(` ${Vr(e,this.codeBlockLang)}
462
+ `);return}if(e.startsWith("### ")){this._safeWrite(`${b.bold}${b.cyan} ${Yt(e.substring(4))}${b.reset}
463
+ `);return}if(e.startsWith("## ")){this._safeWrite(`${b.bold}${b.cyan} ${Yt(e.substring(3))}${b.reset}
464
+ `);return}if(e.startsWith("# ")){this._safeWrite(`${b.bold}${b.cyan}${Yt(e.substring(2))}${b.reset}
465
+ `);return}if(/^\s*[-*]\s/.test(e)){let n=e.match(/^(\s*)/)[1],r=e.replace(/^\s*[-*]\s/,""),i=`${n}${b.cyan}\u2022${b.reset} ${Xt(r)}`,c=Jt(i,s,n+" ");this._safeWrite(`${c}
466
+ `);return}if(/^\s*\d+\.\s/.test(e)){let n=e.match(/^(\s*)(\d+)\.\s(.*)/);if(n){let r=n[1],i=n[2],c=n[3],l=`${r}${b.cyan}${i}.${b.reset} ${Xt(c)}`,u=r+" ".repeat(i.length+2),d=Jt(l,s,u);this._safeWrite(`${d}
467
+ `);return}}let o=Jt(Xt(e),s);this._safeWrite(`${o}
468
+ `)}};xu.exports={renderMarkdown:k$,renderInline:Xt,stripHeadingMarkers:Yt,highlightCode:Vr,highlightJS:hu,highlightBash:gu,highlightJSON:$u,highlightPython:yu,highlightGo:wu,highlightRust:bu,highlightCSS:_u,highlightHTML:ku,renderTable:x$,renderProgress:v$,wrapAnsi:Jt,StreamRenderer:Jr}});var ei=j((ib,Ru)=>{var{execSync:S$}=require("child_process"),Qr=require("path"),rs=require("fs"),Zr=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function Su(){return Qr.join(process.cwd(),".nex","hooks")}function E$(){return Qr.join(process.cwd(),".nex","config.json")}function Eu(){let t=E$();if(!rs.existsSync(t))return{};try{return JSON.parse(rs.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function lo(t){if(!Zr.includes(t))return[];let e=[],s=Su(),o=Qr.join(s,t);rs.existsSync(o)&&e.push(o);let n=Eu();if(n[t]){let r=Array.isArray(n[t])?n[t]:[n[t]];e.push(...r)}return e}function Tu(t,e={},s=3e4){try{return{success:!0,output:S$(t,{cwd:process.cwd(),encoding:"utf-8",timeout:s,env:{...process.env,...e},stdio:["pipe","pipe","pipe"]}).trim()}}catch(o){return{success:!1,error:o.stderr?o.stderr.trim():o.message}}}function T$(t,e={}){let s=lo(t);if(s.length===0)return[];let o={};for(let[r,i]of Object.entries(e))o[`NEX_${r.toUpperCase()}`]=String(i);let n=[];for(let r of s){let i=Tu(r,o);if(n.push({command:r,...i}),!i.success&&t.startsWith("pre-"))break}return n}function R$(t){return lo(t).length>0}function C$(){let t=[];for(let e of Zr){let s=lo(e);s.length>0&&t.push({event:e,commands:s})}return t}function A$(){let t=Su();return rs.existsSync(t)||rs.mkdirSync(t,{recursive:!0}),t}Ru.exports={HOOK_EVENTS:Zr,loadHookConfig:Eu,getHooksForEvent:lo,executeHook:Tu,runHooks:T$,hasHooks:R$,listHooks:C$,initHooksDir:A$}});var me=j((db,Wu)=>{var{C:k,Spinner:bn,TaskProgress:O$,formatToolCall:N$,formatResult:P$,formatToolSummary:Iu,formatSectionHeader:ti,setActiveTaskProgress:ab}=ye(),{callStream:M$}=we(),{parseToolArgs:I$}=Ss(),{executeTool:L$}=ot(),{gatherProjectContext:j$}=no(),{fitToContext:D$,forceCompress:ni,getUsage:q$,estimateTokens:F$}=Xe(),{autoSave:U$,flushAutoSave:W$}=Ct();function it(t){U$(t),W$()}var{getMemoryContext:B$}=Ot(),{checkPermission:H$,setPermission:G$,savePermissions:K$}=os(),{confirm:Lu,setAllowAlwaysHandler:z$}=Ae(),{isPlanMode:go,getPlanModePrompt:Y$,PLAN_MODE_ALLOWED_TOOLS:ju,setPlanContent:X$,extractStepsFromText:J$,createPlan:V$,getActivePlan:cb,startExecution:lb,advancePlanStep:Q$,getPlanStepInfo:Z$}=Nt(),{StreamRenderer:ey}=vu(),{runHooks:Cu}=ei(),{routeMCPCall:ty,getMCPToolDefinitions:ny}=Os(),{getSkillInstructions:sy,getSkillToolDefinitions:oy,routeSkillCall:ry}=Et(),{trackUsage:iy}=ln(),{validateToolArgs:ay}=ur(),{filterToolsForModel:Au,getModelTier:cy,PROVIDER_DEFAULT_TIER:ub}=Bs(),{getConfiguredProviders:ly,getActiveProviderName:is,getActiveModelId:fo,setActiveModel:Ou,MODEL_EQUIVALENTS:$o}=we(),di=require("fs"),fi=require("path"),Nu=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi;function uy(t){let e=[],s;for(Nu.lastIndex=0;(s=Nu.exec(t))!==null;){let o=s[1].trim(),n=o.startsWith("~")?o.replace("~",process.env.HOME||""):fi.resolve(o);di.existsSync(n)&&e.push({raw:o,abs:n})}return e}function dy(t){let e=di.readFileSync(t),s=fi.extname(t).toLowerCase().replace(".",""),o=s==="jpg"||s==="jpeg"?"image/jpeg":s==="png"?"image/png":s==="gif"?"image/gif":s==="webp"?"image/webp":"image/png";return{data:e.toString("base64"),media_type:o}}function Du(t){let e=uy(t);if(e.length===0)return t;let s=[{type:"text",text:t}];for(let o of e)try{let{data:n,media_type:r}=dy(o.abs);s.push({type:"image",media_type:r,data:n})}catch{}return s.length>1?s:t}var si=null,oi=null,ri=null;function _n(){if(si===null){let{TOOL_DEFINITIONS:t}=ot();si=t}return oi===null&&(oi=oy()),ri===null&&(ri=ny()),[...si,...oi,...ri]}var li=50;function fy(t){Number.isFinite(t)&&t>0&&(li=t)}var po=()=>null;function py(t){po=t}var as=null,ui=null,kn=null,mo=new Map,my=1e4,hy=6e3,gy=/\b((?:API|ACCESS|AUTH|BEARER|CLIENT|GITHUB|GITLAB|SLACK|STRIPE|TWILIO|SENDGRID|AWS|GCP|AZURE|OPENAI|ANTHROPIC|GEMINI|OLLAMA)[_A-Z0-9]*(?:KEY|TOKEN|SECRET|PASS(?:WORD)?|CREDENTIAL)[_A-Z0-9]*)\s*=\s*["']?([A-Za-z0-9\-_.+/=]{10,})["']?/g;function $y(t){return!t||typeof t!="string"?t:t.replace(gy,(e,s)=>`${s}=***REDACTED***`)}function yy(t){let e=$y(t);if(F$(e)>my)try{let{compressToolResult:o}=Xe();return o(e,hy)}catch{return e}return e}function qu(t){try{let{getActiveModel:e}=we(),s=e(),o=s?`${s.provider}:${s.id}`:"default";if(mo.has(o))return mo.get(o);let n=Au(t);return mo.set(o,n),n}catch{return Au(t)}}function wy(){mo.clear()}async function Fu(){try{let t=require("fs").promises,e=require("path"),s=[e.join(process.cwd(),"package.json"),e.join(process.cwd(),".git","HEAD"),e.join(process.cwd(),"README.md"),e.join(process.cwd(),"NEX.md")],n=(await Promise.allSettled(s.map(r=>t.stat(r).then(i=>`${r}:${i.mtimeMs}`)))).filter(r=>r.status==="fulfilled").map(r=>r.value);try{let{getMemoryContextHash:r}=Ot(),i=r();i&&n.push(`memory:${i}`)}catch{}try{let r=e.join(process.cwd(),".nex","brain");if(di.existsSync(r)){let i=await t.stat(r);n.push(`brain:${i.mtimeMs}`)}}catch{}return n.join("|")}catch{return`fallback:${Date.now()}`}}function by(){as=null,ui=null,kn=null}var _y=new Set(["spawn_agents"]),ii=5,ai=3,uo=2,ky=parseInt(process.env.NEX_STALE_WARN_MS||"60000",10),Pu=parseInt(process.env.NEX_STALE_ABORT_MS||"120000",10),xy=process.env.NEX_STALE_AUTO_SWITCH!=="0";function vy(t){try{let e=require("fs"),s=require("path"),o=s.join(process.cwd(),".nex","plans");e.existsSync(o)||e.mkdirSync(o,{recursive:!0});let n=s.join(o,"current-plan.md");e.writeFileSync(n,t,"utf-8")}catch{}}z$(t=>{G$(t,"allow"),K$(),console.log(`${k.green} \u2713 ${t}: always allow${k.reset}`)});async function Sy(t){let e=t.function.name,s=I$(t.function.arguments),o=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!s){let l=_n().find(d=>d.function.name===e),u=l?JSON.stringify(l.function.parameters,null,2):"unknown";return console.log(`${k.yellow} \u26A0 ${e}: malformed arguments, sending schema hint${k.reset}`),{callId:o,fnName:e,args:null,canExecute:!1,errorResult:{role:"tool",content:`ERROR: Malformed tool arguments. Could not parse your arguments as JSON.
356
469
  Raw input: ${typeof t.function.arguments=="string"?t.function.arguments.substring(0,200):"N/A"}
357
470
 
358
471
  Expected JSON schema for "${e}":
359
472
  ${u}
360
473
 
361
- Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:n}}}let o=Gh(e,s);if(!o.valid)return console.log(`${b.yellow} \u26A0 ${e}: ${o.error.split(`
362
- `)[0]}${b.reset}`),{callId:n,fnName:e,args:s,canExecute:!1,errorResult:{role:"tool",content:o.error,tool_call_id:n}};let r=o.corrected||s;if(o.corrected){let c=Object.keys(s),l=Object.keys(o.corrected),u=c.filter(d=>!l.includes(d));u.length&&console.log(`${b.dim} \u2713 ${e}: corrected args (${u.join(", ")})${b.reset}`)}if(Ms()&&!dl.has(e))return console.log(`${b.yellow} \u2717 ${e}: blocked in plan mode${b.reset}`),{callId:n,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`PLAN MODE: '${e}' is blocked. Only read-only tools are allowed. Present your plan as text output instead of making changes.`,tool_call_id:n}};let i=Rh(e);if(i==="deny")return console.log(`${b.red} \u2717 ${e}: denied by permissions${b.reset}`),{callId:n,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`DENIED: Tool '${e}' is blocked by permissions`,tool_call_id:n}};if(i==="ask"){let c=` Allow ${e}?`;return e==="bash"&&r.command&&(c=` bash: \`${r.command.substring(0,80)}${r.command.length>80?"\u2026":""}\`?`),await ul(c,{toolName:e})?{callId:n,fnName:e,args:r,canExecute:!0,confirmedByUser:!0,errorResult:null}:{callId:n,fnName:e,args:r,canExecute:!1,confirmedByUser:!1,errorResult:{role:"tool",content:`CANCELLED: User declined ${e}`,tool_call_id:n}}}return{callId:n,fnName:e,args:r,canExecute:!0,confirmedByUser:!0,errorResult:null}}async function dg(t,e,s={}){let n=await Bh(t,e);if(n!==null)return n;let o=await jh(t,e);return o!==null?o:bh(t,e,s)}function fg(t,e){switch(t){case"read_file":case"write_file":case"edit_file":case"patch_file":case"list_directory":return e.path||"";case"bash":return(e.command||"").substring(0,60);case"grep":case"search_files":case"glob":return e.pattern||"";case"web_fetch":return(e.url||"").substring(0,50);case"web_search":return(e.query||"").substring(0,40);default:return""}}async function $r(t,e=!1){e||console.log(gh(t.fnName,t.args));let s=ol("pre-tool",{tool_name:t.fnName});if(!e&&s.length>0)for(let f of s)f.success?console.log(`${b.dim} [hook pre-tool] ${f.command} \u2192 ${f.output||"ok"}${b.reset}`):console.log(`${b.yellow} [hook pre-tool] ${f.command} \u2192 ERROR: ${f.error}${b.reset}`);let n=await dg(t.fnName,t.args,{silent:!0,autoConfirm:t.confirmedByUser===!0}),o=String(n??""),r=o.length>5e4?o.substring(0,5e4)+`
363
- ...(truncated ${o.length-5e4} chars)`:o,i=r.split(`
364
- `)[0],c=i.startsWith("ERROR")||i.includes("CANCELLED")||i.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(r)&&/✗ Agent/.test(r),l=ll(t.fnName,t.args,r,c);e||(console.log($h(r)),console.log(l));let u=ol("post-tool",{tool_name:t.fnName});if(!e&&u.length>0)for(let f of u)f.success?console.log(`${b.dim} [hook post-tool] ${f.command} \u2192 ${f.output||"ok"}${b.reset}`):console.log(`${b.yellow} [hook post-tool] ${f.command} \u2192 ERROR: ${f.error}${b.reset}`);return{msg:{role:"tool",content:ng(r),tool_call_id:t.callId},summary:l}}async function pg(t,e=!1,s={}){let n=new Array(t.length),o=[],r=[],i=null;if(e&&!s.skipSpinner){let l=t.filter(u=>u.canExecute);if(l.length>0){let u;if(l.length===1){let d=l[0],p=fg(d.fnName,d.args);u=`\u25CF ${d.fnName}${p?`(${p})`:""}`}else{let d=l.map(p=>p.fnName).join(", ");u=`\u25CF ${l.length} tools: ${d.length>60?d.substring(0,57)+"\u2026":d}`}i=new Yt(u),i.start()}}async function c(){if(r.length!==0){if(r.length===1){let l=r[0],{msg:u,summary:d}=await $r(t[l],e);n[l]=u,o.push(d)}else{let l=r.map(d=>$r(t[d],e)),u=await Promise.all(l);for(let d=0;d<r.length;d++)n[r[d]]=u[d].msg,o.push(u[d].summary)}r=[]}}for(let l=0;l<t.length;l++){let u=t[l];if(!u.canExecute){await c(),n[l]=u.errorResult,o.push(ll(u.fnName,u.args||{},u.errorResult.content,!0));continue}if(rg.has(u.fnName)){await c(),u.fnName==="spawn_agents"&&i&&(i.stop(),i=null);let{msg:d,summary:p}=await $r(u,e);n[l]=d,o.push(p)}else r.push(l)}if(await c(),i&&i.stop(),e&&o.length>0&&!s.skipSummaries)for(let l of o)console.log(l);return{results:n,summaries:o}}var Y=[],cl=300,Ns=[];function mg(t){Ns.push(t.trim())}function hg(){return Ns.length===0?null:Ns.splice(0,Ns.length).join(`
365
- `)}function gg(){let t=process.env.NEX_LANGUAGE,e=process.env.NEX_CODE_LANGUAGE,s=process.env.NEX_COMMIT_LANGUAGE,n=!t||t==="auto"?null:t,o=[`# Language Rules (CRITICAL \u2014 enforce strictly)
366
- `];n?o.push(`RESPONSE LANGUAGE: You MUST always respond in ${n}. This overrides any language defaults from your training. Never output Chinese, Japanese, or any other language in your responses \u2014 even when summarizing or thinking. ${n} only.`):o.push("RESPONSE LANGUAGE: Always respond in the same language as the user's message. If the user writes in German, respond in German; if in English, respond in English; etc."),o.push("CODE EXAMPLES: Always show actual, working code examples \u2014 never pseudocode or placeholder snippets."),o.push("COMPLETENESS RULES:"),o.push(" \u2022 ALWAYS show actual code when explaining implementations \u2014 never describe without showing"),o.push(" \u2022 Include complete examples with full context (imports, function signatures, error handling)"),o.push(' \u2022 Show alternative approaches when relevant (e.g., "Alternative: use util.promisify instead")'),o.push(" \u2022 Include edge cases in explanations (empty input, null values, boundary conditions)"),o.push(" \u2022 Provide platform-specific guidance when commands differ by OS (Linux/macOS/Windows)"),o.push(' \u2022 For Makefiles, paste the COMPLETE Makefile code DIRECTLY in your text response \u2014 every target, recipe, dependency, and .PHONY line. Writing the Makefile with a tool does NOT count as showing it. The Makefile MUST appear verbatim in your chat text as a code block, even if you also wrote it to a file. Never describe structure without showing the actual code. CRITICAL: use EXACTLY the command specified \u2014 if the task says "runs jest", write "jest" in the recipe, NEVER "npm test". npm test is NOT jest. Recipes need real TAB indentation. ONE .PHONY line listing ALL phony targets.'),o.push(" \u2022 For dataclasses, paste the COMPLETE dataclass code DIRECTLY in your text response \u2014 @dataclass decorator, all fields with types and defaults, full __post_init__ validation. Writing the file with a tool does NOT count as showing the code. The code MUST appear verbatim in your chat text, even if you also wrote it to a file."),o.push(" \u2022 For cron expressions, re-read the exact time boundaries in the task before writing. If asked for 8-18h, the range is 8,9,...,18 \u2014 write exactly what was asked, not an approximation."),o.push(' \u2022 When a task explicitly specifies a tool (e.g., "use tsc"), NEVER mention alternatives (e.g., "swc build") \u2014 use exactly what was requested.'),o.push(' \u2022 In Makefile prerequisites, NEVER use shell glob patterns like src/**/*.ts \u2014 make does not expand these natively. Keep prerequisite lists explicit or omit them. When a Makefile target says "runs jest", call jest directly in the recipe (not npm test).'),o.push(" \u2022 For bash in-place text replacements with backups: use ONLY ONE backup method \u2014 either sed -i.bak (let sed create the backup) OR cp file file.bak followed by sed -i (no extension). Never use both cp and sed -i.bak together \u2014 that produces redundant double backups (file.bak and file.bak.bak)."),o.push(" \u2022 For iterative array-flattening (flattenDeep): use push() and reverse() at the end \u2014 NEVER unshift(). unshift is O(n) per call making the whole function O(n^2). The iterative version MUST use a loop (while/for) and an explicit stack array \u2014 zero recursive calls. If a function calls itself, it is recursive regardless of its name. Never label a recursive function as iterative."),o.push(" \u2022 FORBIDDEN: when refactoring callbacks to async/await, NEVER write try { ... } catch(e) { throw e } \u2014 this is an explicit anti-pattern. WRONG: async function f() { try { const d = await readFile(..); await writeFile(.., d); } catch(e) { throw e; } } \u2014 RIGHT: async function f() { const d = await readFile(..); await writeFile(.., d); } \u2014 omit the try-catch entirely, let rejections propagate."),o.push(' \u2022 Docker HEALTHCHECK: always include --start-period=30s (or appropriate startup time) so the container has time to initialise before failures are counted. Also note that curl may not be available in minimal Node.js images \u2014 offer wget or "node -e" as alternatives.'),o.push(' \u2022 When fixing a bash word-splitting bug like "for f in $(ls *.txt)": replace the entire $(ls *.txt) with a bare glob directly \u2014 "for f in *.txt". The fix is eliminating the ls command and $() subshell entirely. Emphasise this in the explanation: the glob in the for loop prevents word splitting because the shell expands the glob into separate words before the loop \u2014 there is no subshell output to split. CRITICAL: NEVER suggest "ls -N" or any ls variant as a fix \u2014 ls -N outputs filenames one per line, but word splitting still occurs on each line when used in a subshell expansion. The only correct fix is the bare glob pattern.');let r=e||(n?"English":null);r&&o.push(`CODE LANGUAGE: Write all code comments, docstrings, variable descriptions, and inline documentation in ${r}.`);let i=s||(n?"English":null);return i&&o.push(`COMMIT MESSAGES: Write all git commit messages in ${i}.`),n&&o.push(`
367
- This is a hard requirement. Do NOT fall back to English or any other language for your responses, even if the user writes in a different language first.`),o.join(`
474
+ Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:o}}}let n=ay(e,s);if(!n.valid)return console.log(`${k.yellow} \u26A0 ${e}: ${n.error.split(`
475
+ `)[0]}${k.reset}`),{callId:o,fnName:e,args:s,canExecute:!1,errorResult:{role:"tool",content:n.error,tool_call_id:o}};let r=n.corrected||s;if(n.corrected){let c=Object.keys(s),l=Object.keys(n.corrected),u=c.filter(d=>!l.includes(d));u.length&&console.log(`${k.dim} \u2713 ${e}: corrected args (${u.join(", ")})${k.reset}`)}if(go()&&!ju.has(e))return console.log(`${k.yellow} \u2717 ${e}: blocked in plan mode${k.reset}`),{callId:o,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`PLAN MODE: '${e}' is blocked. Only read-only tools are allowed. Present your plan as text output instead of making changes.`,tool_call_id:o}};let i=H$(e);if(i==="deny")return console.log(`${k.red} \u2717 ${e}: denied by permissions${k.reset}`),{callId:o,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`DENIED: Tool '${e}' is blocked by permissions`,tool_call_id:o}};if(i==="ask"){let c=` Allow ${e}?`;return e==="bash"&&r.command&&(c=` bash: \`${r.command.substring(0,80)}${r.command.length>80?"\u2026":""}\`?`),await Lu(c,{toolName:e})?{callId:o,fnName:e,args:r,canExecute:!0,confirmedByUser:!0,errorResult:null}:{callId:o,fnName:e,args:r,canExecute:!1,confirmedByUser:!1,errorResult:{role:"tool",content:`CANCELLED: User declined ${e}`,tool_call_id:o}}}return{callId:o,fnName:e,args:r,canExecute:!0,confirmedByUser:!0,errorResult:null}}async function Ey(t,e,s={}){let o=await ry(t,e);if(o!==null)return o;let n=await ty(t,e);return n!==null?n:L$(t,e,s)}function Ty(t,e){switch(t){case"read_file":case"write_file":case"edit_file":case"patch_file":case"list_directory":return e.path||"";case"bash":return(e.command||"").substring(0,60);case"grep":case"search_files":case"glob":return e.pattern||"";case"web_fetch":return(e.url||"").substring(0,50);case"web_search":return(e.query||"").substring(0,40);default:return""}}async function ci(t,e=!1){e||console.log(N$(t.fnName,t.args));let s=Cu("pre-tool",{tool_name:t.fnName});if(!e&&s.length>0)for(let m of s)m.success?console.log(`${k.dim} [hook pre-tool] ${m.command} \u2192 ${m.output||"ok"}${k.reset}`):console.log(`${k.yellow} [hook pre-tool] ${m.command} \u2192 ERROR: ${m.error}${k.reset}`);ct?.onToolStart&&ct.onToolStart(t.fnName,t.args);let o=await Ey(t.fnName,t.args,{silent:!0,autoConfirm:t.confirmedByUser===!0}),n=String(o??""),r=n.length>5e4?n.substring(0,5e4)+`
476
+ ...(truncated ${n.length-5e4} chars)`:n,i=r.split(`
477
+ `)[0],c=i.startsWith("ERROR")||i.includes("CANCELLED")||i.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(r)&&/✗ Agent/.test(r),l=Iu(t.fnName,t.args,r,c);e||(console.log(P$(r)),console.log(l)),ct?.onToolEnd&&ct.onToolEnd(t.fnName,l,!c);let u=Cu("post-tool",{tool_name:t.fnName});if(!e&&u.length>0)for(let m of u)m.success?console.log(`${k.dim} [hook post-tool] ${m.command} \u2192 ${m.output||"ok"}${k.reset}`):console.log(`${k.yellow} [hook post-tool] ${m.command} \u2192 ERROR: ${m.error}${k.reset}`);return{msg:{role:"tool",content:yy(r),tool_call_id:t.callId},summary:l}}async function Ry(t,e=!1,s={}){let o=new Array(t.length),n=[],r=[],i=null;if(e&&!s.skipSpinner){let l=t.filter(u=>u.canExecute);if(l.length>0){let u;if(l.length===1){let d=l[0],f=Ty(d.fnName,d.args);u=`\u25CF ${d.fnName}${f?`(${f})`:""}`}else{let d=l.map(f=>f.fnName).join(", ");u=`\u25CF ${l.length} tools: ${d.length>60?d.substring(0,57)+"\u2026":d}`}i=new bn(u),i.start()}}async function c(){if(r.length!==0){if(r.length===1){let l=r[0],{msg:u,summary:d}=await ci(t[l],e);o[l]=u,n.push(d)}else{let l=r.map(d=>ci(t[d],e)),u=await Promise.all(l);for(let d=0;d<r.length;d++)o[r[d]]=u[d].msg,n.push(u[d].summary)}r=[]}}for(let l=0;l<t.length;l++){let u=t[l];if(!u.canExecute){await c(),o[l]=u.errorResult,n.push(Iu(u.fnName,u.args||{},u.errorResult.content,!0));continue}if(_y.has(u.fnName)){await c(),u.fnName==="spawn_agents"&&i&&(i.stop(),i=null);let{msg:d,summary:f}=await ci(u,e);o[l]=d,n.push(f)}else r.push(l)}if(await c(),i&&i.stop(),e&&n.length>0&&!s.skipSummaries)for(let l of n)console.log(l);return{results:o,summaries:n}}var te=[],Mu=300,ho=[];function Cy(t){ho.push(t.trim())}function Ay(){return ho.length===0?null:ho.splice(0,ho.length).join(`
478
+ `)}function Oy(){let t=process.env.NEX_LANGUAGE,e=process.env.NEX_CODE_LANGUAGE,s=process.env.NEX_COMMIT_LANGUAGE,o=!t||t==="auto"?"English":t,n=[`# Language Rules (CRITICAL \u2014 enforce strictly)
479
+ `];o?n.push(`RESPONSE LANGUAGE: You MUST always respond in ${o}. This overrides any language defaults from your training. Never output Chinese, Japanese, or any other language in your responses \u2014 even when summarizing or thinking. ${o} only.`):n.push("RESPONSE LANGUAGE: Always respond in the same language as the user's message. If the user writes in German, respond in German; if in English, respond in English; etc."),n.push("CODE EXAMPLES: Always show actual, working code examples \u2014 never pseudocode or placeholder snippets."),n.push("COMPLETENESS RULES:"),n.push(" \u2022 ALWAYS show actual code when explaining implementations \u2014 never describe without showing"),n.push(" \u2022 Include complete examples with full context (imports, function signatures, error handling)"),n.push(' \u2022 Show alternative approaches when relevant (e.g., "Alternative: use util.promisify instead")'),n.push(" \u2022 Include edge cases in explanations (empty input, null values, boundary conditions)"),n.push(" \u2022 Provide platform-specific guidance when commands differ by OS (Linux/macOS/Windows)"),n.push(' \u2022 For Makefiles, paste the COMPLETE Makefile code DIRECTLY in your text response \u2014 every target, recipe, dependency, and .PHONY line. Writing the Makefile with a tool does NOT count as showing it. The Makefile MUST appear verbatim in your chat text as a code block, even if you also wrote it to a file. Never describe structure without showing the actual code. CRITICAL: use EXACTLY the command specified \u2014 if the task says "runs jest", write "jest" in the recipe, NEVER "npm test". npm test is NOT jest. Recipes need real TAB indentation. ONE .PHONY line listing ALL phony targets.'),n.push(" \u2022 For dataclasses, paste the COMPLETE dataclass code DIRECTLY in your text response \u2014 @dataclass decorator, all fields with types and defaults, full __post_init__ validation. Writing the file with a tool does NOT count as showing the code. The code MUST appear verbatim in your chat text, even if you also wrote it to a file."),n.push(" \u2022 For cron expressions, re-read the exact time boundaries in the task before writing. If asked for 8-18h, the range is 8,9,...,18 \u2014 write exactly what was asked, not an approximation."),n.push(' \u2022 When a task explicitly specifies a tool (e.g., "use tsc"), NEVER mention alternatives (e.g., "swc build") \u2014 use exactly what was requested.'),n.push(' \u2022 In Makefile prerequisites, NEVER use shell glob patterns like src/**/*.ts \u2014 make does not expand these natively. Keep prerequisite lists explicit or omit them. When a Makefile target says "runs jest", call jest directly in the recipe (not npm test).'),n.push(" \u2022 For bash in-place text replacements with backups: use ONLY ONE backup method \u2014 either sed -i.bak (let sed create the backup) OR cp file file.bak followed by sed -i (no extension). Never use both cp and sed -i.bak together \u2014 that produces redundant double backups (file.bak and file.bak.bak)."),n.push(" \u2022 For iterative array-flattening (flattenDeep): use push() and reverse() at the end \u2014 NEVER unshift(). unshift is O(n) per call making the whole function O(n^2). The iterative version MUST use a loop (while/for) and an explicit stack array \u2014 zero recursive calls. If a function calls itself, it is recursive regardless of its name. Never label a recursive function as iterative."),n.push(" \u2022 FORBIDDEN: when refactoring callbacks to async/await, NEVER write try { ... } catch(e) { throw e } \u2014 this is an explicit anti-pattern. WRONG: async function f() { try { const d = await readFile(..); await writeFile(.., d); } catch(e) { throw e; } } \u2014 RIGHT: async function f() { const d = await readFile(..); await writeFile(.., d); } \u2014 omit the try-catch entirely, let rejections propagate."),n.push(' \u2022 Docker HEALTHCHECK: always include --start-period=30s (or appropriate startup time) so the container has time to initialise before failures are counted. Also note that curl may not be available in minimal Node.js images \u2014 offer wget or "node -e" as alternatives.'),n.push(' \u2022 When fixing a bash word-splitting bug like "for f in $(ls *.txt)": replace the entire $(ls *.txt) with a bare glob directly \u2014 "for f in *.txt". The fix is eliminating the ls command and $() subshell entirely. Emphasise this in the explanation: the glob in the for loop prevents word splitting because the shell expands the glob into separate words before the loop \u2014 there is no subshell output to split. CRITICAL: NEVER suggest "ls -N" or any ls variant as a fix \u2014 ls -N outputs filenames one per line, but word splitting still occurs on each line when used in a subshell expansion. The only correct fix is the bare glob pattern.');let r=e||(o?"English":null);r&&n.push(`CODE LANGUAGE: Write all code comments, docstrings, variable descriptions, and inline documentation in ${r}.`);let i=s||(o?"English":null);return i&&n.push(`COMMIT MESSAGES: Write all git commit messages in ${i}.`),o&&n.push(`
480
+ This is a hard requirement. Always respond in ${o}. Do NOT switch to any other language \u2014 even if the user writes to you in German, French, or any other language, your reply MUST be in ${o}.`),n.join(`
368
481
  `)+`
369
482
 
370
- `}function $g(){if(Vt!==null)return Vt;try{let e=Kh().flatMap(o=>o.models.map(r=>({spec:`${o.name}:${r.id}`,tier:zh(r.id,o.name),name:r.name})));if(e.length<2)return Vt="","";let s={full:"complex tasks (refactor, implement, generate)",standard:"regular tasks (edit, fix, analyze)",essential:"simple tasks (read, search, list)"},n=`
483
+ `}function Ny(){if(kn!==null)return kn;try{let e=ly().flatMap(n=>n.models.map(r=>({spec:`${n.name}:${r.id}`,tier:cy(r.id,n.name),name:r.name})));if(e.length<2)return kn="","";let s={full:"complex tasks (refactor, implement, generate)",standard:"regular tasks (edit, fix, analyze)",essential:"simple tasks (read, search, list)"},o=`
371
484
  # Sub-Agent Model Routing
372
485
 
373
- `;n+='Sub-agents auto-select models by task complexity. Override with `model: "provider:model"` in agent definition.\n\n',n+=`| Model | Tier | Auto-assigned for |
486
+ `;o+='Sub-agents auto-select models by task complexity. Override with `model: "provider:model"` in agent definition.\n\n',o+=`| Model | Tier | Auto-assigned for |
374
487
  |---|---|---|
375
- `;for(let o of e)n+=`| ${o.spec} | ${o.tier} | ${s[o.tier]||o.tier} |
376
- `;return Vt=n,n}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),Vt="",""}}async function hl(){let t=await ml();if(An!==null&&t===wr)return An;let e=await xh(process.cwd()),s=Th(),n=Uh(),o=Ms()?Nh():"",r=gg();return An=`You are Nex Code, an expert coding assistant. You help with programming tasks by reading, writing, and editing files, running commands, and answering questions.
488
+ `;for(let n of e)o+=`| ${n.spec} | ${n.tier} | ${s[n.tier]||n.tier} |
489
+ `;return kn=o,o}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),kn="",""}}async function Uu(){let t=await Fu();if(as!==null&&t===ui)return as;let e=await j$(process.cwd()),s=B$(),o=sy(),n=go()?Y$():"",r=Oy();return as=`You are Nex Code, an expert coding assistant. You help with programming tasks by reading, writing, and editing files, running commands, and answering questions.
377
490
 
378
491
  WORKING DIRECTORY: ${process.cwd()}
379
492
  All relative paths resolve from this directory.
@@ -381,10 +494,10 @@ PROJECT CONTEXT:
381
494
  ${e}
382
495
  ${s?`
383
496
  ${s}
384
- `:""}${n?`
385
- ${n}
386
497
  `:""}${o?`
387
498
  ${o}
499
+ `:""}${n?`
500
+ ${n}
388
501
  `:""}
389
502
  ${r?`${r}
390
503
  `:""}# Core Behavior
@@ -423,9 +536,9 @@ Response patterns by request type:
423
536
  - **Encoding/buffer handling**: When discussing file operations, mention utf8 encoding or buffer considerations. Use correct flags like --zero instead of -0 for null-delimited output.
424
537
  - **Hook implementations (Git, bash scripts)**: Answer ENTIRELY in text \u2014 do NOT use any tools. Write the complete, correct script in your first and only response. Think through ALL edge cases (e.g. console.log in comments or strings vs real calls) before writing \u2014 handle them in the initial script, never iterate. Show the full file content and how to install it (chmod +x, correct .git/hooks/ path). For pre-commit hooks that check staged content: always use 'git diff --cached' to get only staged changes \u2014 never grep full file content, which would catch unstaged lines. Use '--diff-filter=ACM' to target added/copied/modified files \u2014 NEVER use '--diff-filter=D' (that shows ONLY deleted files, opposite of intent). NEVER use 'set -e' in pre-commit hooks \u2014 grep exits 1 on no match, which kills the entire script under set -e. Use explicit 'if git diff --cached ... | grep -q ...; then' flow control instead, and check exit codes explicitly. REGEX FALSE POSITIVES: When writing a regex to detect calls like console.log(), the pattern must exclude comment lines \u2014 pipe through 'grep -v "^s*//"' before the pattern match so that lines like "// console.log(x)" do not trigger a false positive. CONSOLE METHODS: When a task asks to block console.log, explicitly address whether console.warn, console.error, console.debug, and console.info should also be blocked \u2014 if the intent is "no console output in production", block all console methods with a single pattern like 'console.(log|warn|error|debug|info)'.
425
538
  - **Memory leak explanations**: Show the problematic code, then present the primary fix (move emitter.on() outside the loop, registered once) with the original setInterval kept intact for its intended purpose. Then briefly mention 2 alternatives: (1) emitter.once() if only one event needs handling, (2) removeAllListeners() (or emitter.off(event, handler)) BEFORE re-registering inside the loop. CRITICAL for alternative 2: you MUST call removeAllListeners() or off() BEFORE the new emitter.on() \u2014 if you call emitter.on() inside an interval without first removing the previous listener, a new listener accumulates on every tick, which is the same leak as the original. Always show the removal step explicitly. Do NOT replace the setInterval body with an empty callback \u2014 keep the interval doing its original work.
426
- - **Makefile tasks**: ALWAYS follow this exact order: (1) paste the COMPLETE Makefile in a fenced code block in your text response FIRST, (2) THEN optionally write it to a file with a tool. The user cannot see files you write \u2014 your text response is the ONLY output they receive. Never describe the Makefile in prose \u2014 paste the actual code. Every target, every recipe, every .PHONY line. Use EXACTLY the tools specified (jest means jest directly, not npm test; tsc means tsc). Never put glob patterns like src/**/*.ts in prerequisites \u2014 make does not expand them. MAKEFILE SYNTAX RULES (hard requirements): (a) Recipe lines MUST be indented with a real TAB character \u2014 never spaces; a space-indented recipe causes "missing separator" errors. (b) Declare ALL phony targets in a SINGLE .PHONY line at the top \u2014 NEVER split .PHONY across multiple declarations. (c) NEVER define the same target name twice \u2014 duplicate targets silently override each other and produce contradictory behaviour. (d) Do NOT add @echo lines unless the task explicitly asks for output messages.
539
+ - **Makefile tasks**: ALWAYS follow this exact order: (1) paste the COMPLETE Makefile in a fenced code block in your text response FIRST, (2) THEN optionally write it to a file with a tool. The user cannot see files you write \u2014 your text response is the ONLY output they receive. Never describe the Makefile in prose \u2014 paste the actual code. Every target, every recipe, every .PHONY line. Use EXACTLY the tools specified (jest means jest directly, not npm test; tsc means tsc). Never put glob patterns like src/**/*.ts in prerequisites \u2014 make does not expand them. MAKEFILE SYNTAX RULES (hard requirements): (a) Recipe lines MUST be indented with a real TAB character \u2014 never spaces; a space-indented recipe causes "missing separator" errors. (b) Declare ALL phony targets in a SINGLE .PHONY line at the top \u2014 NEVER split .PHONY across multiple declarations. (c) NEVER define the same target name twice \u2014 duplicate targets silently override each other and produce contradictory behaviour. (d) Do NOT add @echo lines unless the task explicitly asks for output messages. (e) DEPENDENCY CHAIN: if the task describes a test target that runs tests after compilation/building, the test target MUST declare an explicit dependency on build (e.g. "test: build") \u2014 otherwise make test runs against stale or missing binaries. When in doubt, add the dependency; omitting it is always the wrong default.
427
540
  - **Dataclass definitions**: Paste the COMPLETE dataclass code directly in your text response \u2014 @dataclass decorator, all fields with type annotations and defaults, full __post_init__ validation block. The code must appear verbatim in your chat text. Writing a file with a tool does NOT satisfy this \u2014 always also paste the code in text.
428
- - **Cron expressions**: Before writing each expression, quote the exact constraint from the task, then derive the expression. Double-check boundary values match exactly what was asked. NEVER put cron expressions inside markdown tables \u2014 asterisks (*) in table cells are consumed as bold/italic markers and disappear. Always present each cron expression in its own fenced code block. For "every N minutes between X-Yh": only present both interpretations (inclusive vs. exclusive endpoint) when the task is genuinely ambiguous about whether the endpoint fires. If the task explicitly states "8-18h" or "until 18h" without qualification, write the expression with 8-18 directly \u2014 do NOT second-guess or add a confusing dual-interpretation note that contradicts the explicit request. The note is only appropriate when the task says something like "during business hours" or "until approximately 18h" where intent is unclear.
541
+ - **Cron expressions**: Before writing each expression, quote the exact constraint from the task, then derive the expression. Double-check boundary values match exactly what was asked. NEVER put cron expressions inside markdown tables \u2014 asterisks (*) in table cells are consumed as bold/italic markers and disappear. Always present each cron expression in its own fenced code block. For "every N minutes between X-Yh": only present both interpretations (inclusive vs. exclusive endpoint) when the task is genuinely ambiguous about whether the endpoint fires. If the task explicitly states "8-18h" or "until 18h" without qualification, write the expression with 8-18 directly \u2014 do NOT second-guess or add a confusing dual-interpretation note that contradicts the explicit request. The note is only appropriate when the task says something like "during business hours" or "until approximately 18h" where intent is unclear. CRITICAL OFF-BY-ONE: "8-18h" means the hour field is 8-18 (runs fire AT 18:00 are INCLUDED). Writing 8-17 silently drops the 18:00 run \u2014 this is WRONG. If you notice mid-response that you wrote 8-17 for an 8-18h spec, CORRECT THE EXPRESSION in-place immediately \u2014 do NOT leave both versions and add a contradictory note.
429
542
  - **Express/fetch error handling**: When adding error handling to an Express route that fetches by ID: (1) validate the ID parameter first (check it exists and is a valid format), (2) wrap fetch in try-catch, (3) check response.ok and handle 404 specifically, (4) call next(error) to pass errors to Express error-handling middleware \u2014 do not just send a raw 500 response.
430
543
  - **Command suggestions**: Always use correct command flags and syntax. For null-delimited output, use --zero or find/printf instead of non-existent flags like -0.
431
544
  - **sed -i portability**: When showing 'sed -i' for in-place file editing, always note the macOS/BSD vs GNU difference: on macOS/BSD, '-i' requires an explicit backup suffix argument (e.g. 'sed -i "" "s/old/new/" file' for no backup, or 'sed -i.bak ...' for a backup); on GNU/Linux, 'sed -i "s/old/new/" file' works without the extra argument. When the user's platform is unknown or macOS, show the macOS-compatible form first. For cross-platform scripts, suggest 'perl -i -pe' as a portable alternative.
@@ -467,9 +580,20 @@ When performing audits, code reviews, bug hunts, or security reviews:
467
580
  - **Preserve existing behavior**: When refactoring or fixing code, maintain the original encoding, error handling, and API behavior unless explicitly instructed to change it.
468
581
  - **Be complete**: Ensure responses include all necessary information and are not truncated. If a response would be very long, summarize key points and offer to provide more detail if needed.
469
582
 
583
+ # Frontend Design
584
+
585
+ Before creating or significantly modifying any frontend file (.html, .vue, .jsx, .tsx, .css, templates, components): **call frontend_recon first.** It returns the project's design tokens (colors, fonts, CSS variables), the main layout page, a reference component of the same type, and the detected framework stack (Alpine.js version, HTMX, Tailwind, etc.). Pass type= the kind of page you are building (e.g. "list", "form", "dashboard").
586
+
587
+ After frontend_recon returns:
588
+ - Use ONLY the colors, fonts, and spacing tokens it found \u2014 never invent values.
589
+ - Copy the exact HTML structure and class names from the reference component \u2014 do not create alternative patterns.
590
+ - Use ONLY the framework(s) it detected. Never mix (e.g. no fetch() when HTMX is used, no Vue syntax in an Alpine.js project).
591
+ - The finished page must be visually indistinguishable from existing pages.
592
+
470
593
  # Doing Tasks
471
594
 
472
595
  - For non-trivial tasks, briefly state your approach before starting (1 sentence). This helps the user know what to expect.
596
+ - **Understand intent before acting** \u2014 every prompt has a reason behind it. Before executing, ask yourself: what is the user actually trying to achieve? Then gather the current state first (read relevant files, run git status/diff). If what you find contradicts or already satisfies the task \u2014 ask the user instead of proceeding blindly. Examples: asked to implement something that already exists \u2192 ask whether to extend or replace it. Asked to reset/clean state \u2192 ask what problem that's supposed to solve. Never invent work and never silently execute when the situation is ambiguous.
473
597
  - ALWAYS read code before modifying it. Never propose changes to code you haven't read.
474
598
  - Prefer edit_file for targeted changes over write_file for full rewrites.
475
599
  - Do not create new files unless absolutely necessary. Edit existing files instead.
@@ -498,7 +622,7 @@ When performing audits, code reviews, bug hunts, or security reviews:
498
622
  - Good for: reading multiple files, analyzing separate modules.
499
623
  - Bad for: tasks that depend on each other or modify the same file.
500
624
  - Max 5 parallel agents.
501
- ${$g()}
625
+ ${Ny()}
502
626
 
503
627
  # Edit Reliability (Critical)
504
628
 
@@ -549,50 +673,54 @@ You have access to a persistent knowledge base in .nex/brain/.
549
673
  - Include tags in frontmatter for better retrieval
550
674
  - The user reviews all brain writes via /brain review or git diff
551
675
 
552
- `,wr=t,An}function yg(){Y=[]}function wg(){Y.length>cl&&Y.splice(0,Y.length-cl)}function bg(){return Y.length}function xg(){return Y}function _g(t){Y=t}async function kg(){let{execFile:t}=require("child_process"),e=require("fs"),s=process.cwd(),n=(p,f)=>new Promise(h=>{t(p,f,{cwd:s,timeout:3e3},(m,g)=>{h(m?"":(g||"").trim())})}),[o]=await Promise.all([n("find",[".","-type","f","-not","-path","*/node_modules/*","-not","-path","*/.git/*","-not","-path","*/dist/*","-not","-path","*/.next/*","-not","-path","*/build/*","-not","-path","*/__pycache__/*","-not","-path","*/vendor/*"])]),r=new Set(["js","ts","jsx","tsx","py","go","rs","rb","java","cpp","c","cs"]),i=(o?o.split(`
553
- `):[]).filter(p=>{let f=p.split(".").pop();return r.has(f)});if(i.length<3)return null;let c={};for(let p of i){let f=p.split(".").pop();c[f]=(c[f]||0)+1}let u=` \u{1F4C1} ${Object.entries(c).sort((p,f)=>f[1]-p[1]).slice(0,4).map(([p,f])=>`${f} .${p}`).join(" \xB7 ")}`,d=xr.join(s,"package.json");if(e.existsSync(d))try{let p=JSON.parse(e.readFileSync(d,"utf-8")),f=Object.keys({...p.dependencies||{},...p.devDependencies||{}});if(f.length>0){let h=f.slice(0,5).join(" \xB7 "),m=f.length>5?` +${f.length-5}`:"";u+=`
554
- \u{1F4E6} ${h}${m}`}}catch{}return u}function vg(t){if(process.platform==="darwin")try{let{execFileSync:e}=require("child_process");e("osascript",["-e",`display notification "${t.replace(/"/g,'\\"')}" with title "nex-code"`],{timeout:3e3,stdio:"ignore"})}catch{}}function Je(t,e,s,n,o){if(t<1)return;let r=[...e.values()].reduce((l,u)=>l+u,0),i=`\u2500\u2500 ${t} ${t===1?"step":"steps"} \xB7 ${r} ${r===1?"tool":"tools"}`,c=0;if(o){let l=Date.now()-o;c=Math.round(l/1e3),i+=c>=60?` \xB7 ${Math.floor(c/60)}m ${c%60}s`:` \xB7 ${c}s`}if(s.size>0&&(i+=` \xB7 ${s.size} ${s.size===1?"file":"files"} modified`),i+=" \u2500\u2500",console.log(`
555
- ${b.dim} ${i}${b.reset}`),c>=30&&process.stdout.isTTY){let l=s.size>0?`Done \u2014 ${s.size} ${s.size===1?"file":"files"} modified in ${c}s`:`Done \u2014 ${t} ${t===1?"step":"steps"} in ${c}s`;vg(l)}s.size>0?console.log(`${b.dim} \u{1F4A1} /diff \xB7 /commit \xB7 /undo${b.reset}`):n.size>=5&&s.size===0&&t>=3?console.log(`${b.dim} \u{1F4A1} Found issues? Say "fix 1" or "apply all fixes"${b.reset}`):n.size>0&&t>=2&&console.log(`${b.dim} \u{1F4A1} /save \xB7 /clear${b.reset}`)}async function Sg(){if(!process.stdout.isTTY)return{action:"quit"};let t=Cn(),e=Cs(),s=Ps.fast?.[t],n=Ps.strong?.[t],o=s&&s!==e,r=n&&n!==e&&n!==s,i=[];i.push({key:"r",label:`Retry with current model ${b.dim}(${e})${b.reset}`}),o&&i.push({key:"f",label:`Switch to ${b.bold}${s}${b.reset} ${b.dim}\u2014 fast, low latency${b.reset}`,model:s}),r&&i.push({key:"s",label:`Switch to ${b.bold}${n}${b.reset} ${b.dim}\u2014 reliable tool-calling, medium speed${b.reset}`,model:n}),i.push({key:"q",label:`${b.dim}Quit${b.reset}`}),console.log(),console.log(`${b.yellow} Stream stale \u2014 all retries exhausted.${b.reset} What would you like to do?`);for(let c of i)console.log(` ${b.cyan}[${c.key}]${b.reset} ${c.label}`);return process.stdout.write(` ${b.yellow}> ${b.reset}`),new Promise(c=>{let l=process.stdin,u=l.isRaw;l.setRawMode(!0),l.resume(),l.setEncoding("utf8");let d=!1,p=f=>{if(d)return;d=!0,l.removeListener("data",p),l.setRawMode(u||!1),l.pause();let h=f.toLowerCase().trim();if(process.stdout.write(`${h}
556
- `),f==="")return c({action:"quit"});let m=i.find(g=>g.key===h);!m||m.key==="q"||!m.model&&m.key!=="r"?c({action:"quit"}):m.key==="r"?c({action:"retry"}):c({action:"switch",model:m.model,provider:t})};l.on("data",p)})}async function Eg(t){let e=fl(t);Y.push({role:"user",content:e}),wg();let{setOnChange:s}=ds(),n=null,o=0;s((U,ee)=>{U==="create"?(n&&n.stop(),n=new hh(ee.name,ee.tasks),n.setStats({tokens:o}),n.start()):U==="update"&&n?n.updateTask(ee.id,ee.status):U==="clear"&&n&&(n.stop(),n=null)});let r=await hl(),i=r;try{let{getBrainContext:U}=_n(),ee=await U(t);ee&&(i=r+`
557
- `+ee+`
558
- `)}catch(U){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",U.message)}let c=[{role:"system",content:i},...Y],l=new Yt("Thinking...");l.start();let d=Y.length===1?kg().catch(()=>null):Promise.resolve(null),p=Jt(),[{messages:f,compressed:h,compacted:m,tokensRemoved:g},y]=await Promise.all([_h(c,p),d]),$=kh(c,p);if(l.stop(),y&&console.log(`${b.dim}${y}${b.reset}`),m)console.log(`${b.dim} [context compacted \u2014 summary (~${g} tokens freed)]${b.reset}`);else if(h){let U=$.limit>0?Math.round(g/$.limit*100):0;console.log(`${b.dim} [context compressed \u2014 ~${g} tokens freed (${U}%)]${b.reset}`)}$.percentage>85&&console.log(`${b.yellow} \u26A0 Context ${Math.round($.percentage)}% full \u2014 consider /clear or /save + start fresh${b.reset}`);let x=f,S=0,k=0,v=0,T=0,A=0,E=0,F=new Map,j=new Set,Z=new Set,G=Date.now(),te=new Map,me=3,Pn=5,ye=new Map,It=5,q=8,P=0,B=6,V=10,D,Q=yr,z=0,le=10;e:for(;;){for(D=0;D<Q&&!As()?.aborted;D++){let ee=!0;E>0&&Ih();let be=null;if(n&&n.isActive())n._paused&&n.resume();else if(!n){let R,N=qh();if(N&&N.total>1){let qe=N.description.length>40?N.description.slice(0,37)+"\u2026":N.description;R=`Plan step ${N.current}/${N.total}: ${qe}`}else R=E>0?`Thinking... (step ${E+1})`:"Thinking...";be=new Yt(R),be.start()}let Me=!0,Pe="",we=new Dh,lt,Ws=Date.now(),Ln=!1,Bs=new AbortController,Hr=setInterval(()=>{let R=Date.now()-Ws;if(R>=ag)we._clearCursorLine(),console.log(`${b.yellow} \u26A0 Stream stale for ${Math.round(R/1e3)}s \u2014 aborting and retrying${b.reset}`),Bs.abort();else if(R>=ig&&!Ln){Ln=!0,we._clearCursorLine();let N=Ps.fast?.[Cn()];console.log(`${b.yellow} \u26A0 No tokens received for ${Math.round(R/1e3)}s \u2014 waiting...${b.reset}`),N&&N!==Cs()?console.log(`${b.dim} \u{1F4A1} Will auto-switch to ${N} if no tokens arrive before abort${b.reset}`):N&&console.log(`${b.dim} \u{1F4A1} Ctrl+C to abort and retry${b.reset}`)}},5e3),Le="",Xe=null;try{let R=pl(Jt()),N=Ms()?R.filter(ue=>dl.has(ue.function.name)):R,qe=As(),H=new AbortController;qe&&qe.addEventListener("abort",()=>H.abort(),{once:!0}),Bs.signal.addEventListener("abort",()=>H.abort(),{once:!0}),lt=await yh(x,N,{signal:H.signal,onThinkingToken:()=>{Ws=Date.now(),Ln=!1},onToken:ue=>{Ws=Date.now(),Ln=!1,Le+=ue,process.stdout.isTTY?Xe||(Xe=setTimeout(()=>{Le&&we&&we.push(Le),Le="",Xe=null},50)):(we.push(Le),Le=""),Me&&(n&&!n._paused?n.pause():be&&be.stop(),ee||(ee=!0),we.startCursor(),Me=!1),Pe+=ue}})}catch(R){if(clearInterval(Hr),Xe&&(clearTimeout(Xe),Xe=null),Le&&we&&(we.push(Le),Le=""),n&&!n._paused&&n.pause(),be&&be.stop(),we.stopCursor(),Bs.signal.aborted&&!As()?.aborted){if(v++,v>gr){if(T<1){T++,console.log(`${b.yellow} \u26A0 Stale retries exhausted \u2014 last-resort force-compress...${b.reset}`);let he=Jt(),{messages:Re,tokensRemoved:qt}=ur(x,he);x=Re,console.log(`${b.dim} [force-compressed \u2014 ~${qt} tokens freed]${b.reset}`),v=0,D--;continue}n&&(n.stop(),n=null);let W=await Sg();if(W.action==="quit"){s(null),Je(E,F,j,Z,G),Ye(Y);break}W.action==="switch"&&(il(`${W.provider}:${W.model}`),console.log(`${b.green} \u2713 Switched to ${W.provider}:${W.model}${b.reset}`)),v=0,T=0,D--;continue}let H=v===1?3e3:5e3;if(v>=1&&A<1){A++,console.log(`${b.yellow} \u26A0 Stale retry ${v}/${gr} \u2014 force-compressing before retry...${b.reset}`);let W=Jt(),{messages:he,tokensRemoved:Re}=ur(x,W);if(x=he,Re>0&&console.log(`${b.dim} [force-compressed \u2014 ~${Re} tokens freed]${b.reset}`),cg){let qt=Ps.fast?.[Cn()];qt&&qt!==Cs()&&(il(`${Cn()}:${qt}`),console.log(`${b.cyan} \u26A1 Auto-switched to ${qt} to avoid further stale timeouts${b.reset}`),console.log(`${b.dim} (disable with NEX_STALE_AUTO_SWITCH=0)${b.reset}`))}}else console.log(`${b.yellow} \u26A0 Stale retry ${v}/${gr} \u2014 retrying in ${H/1e3}s...${b.reset}`);let ue=new Yt(`Waiting ${H/1e3}s before retry...`);ue.start(),await new Promise(W=>setTimeout(W,H)),ue.stop(),D--;continue}if(R.name==="AbortError"||R.name==="CanceledError"||R.message?.includes("canceled")||R.message?.includes("aborted")){n&&(n.stop(),n=null),s(null),Je(E,F,j,Z,G),Ye(Y);break}let N=R.message;if(R.code==="ECONNREFUSED"||R.message.includes("ECONNREFUSED"))N="Connection refused \u2014 please check your internet connection or API endpoint";else if(R.code==="ENOTFOUND"||R.message.includes("ENOTFOUND"))N="Network error \u2014 could not reach the API server. Please check your connection";else if(R.code==="ETIMEDOUT"||R.message.includes("timeout"))N="Request timed out \u2014 the API server took too long to respond. Please try again";else if(R.message.includes("401")||R.message.includes("Unauthorized"))N="Authentication failed \u2014 please check your API key in the .env file";else if(R.message.includes("403")||R.message.includes("Forbidden"))N="Access denied \u2014 your API key may not have permission for this model";else if(R.message.includes("400")){if(T<2){T++,console.log(`${b.yellow} \u26A0 Bad request (400) \u2014 force-compressing and retrying... (attempt ${T}/2)${b.reset}`);let W=Jt(),{messages:he,tokensRemoved:Re}=ur(x,W);x=he,Re>0&&console.log(`${b.dim} [force-compressed \u2014 ~${Re} tokens freed]${b.reset}`),D--;continue}let H=(R.message||"").toLowerCase();H.includes("context")||H.includes("token")||H.includes("length")||H.includes("too long")||H.includes("too many")||H.includes("prompt")||H.includes("size")||H.includes("exceeds")||H.includes("num_ctx")||H.includes("input")?N="Context too long \u2014 force compression exhausted. Use /clear to start fresh":N="Bad request \u2014 compression did not help. Use /clear and retry"}else R.message.includes("500")||R.message.includes("502")||R.message.includes("503")||R.message.includes("504")?N="API server error \u2014 the provider is experiencing issues. Please try again in a moment":(R.message.includes("fetch failed")||R.message.includes("fetch"))&&(N="Network request failed \u2014 please check your internet connection");if(console.log(`${b.red} \u2717 ${N}${b.reset}`),R.message.includes("429")){if(S++,S>mr){console.log(`${b.red} Rate limit: max retries (${mr}) exceeded. Try again later or use /budget to check your limits.${b.reset}`),n&&(n.stop(),n=null),s(null),Je(E,F,j,Z,G),Ye(Y);break}let H=Math.min(1e4*Math.pow(2,S-1),12e4),ue=new Yt(`Rate limit \u2014 waiting ${Math.round(H/1e3)}s (retry ${S}/${mr})`);ue.start(),await new Promise(W=>setTimeout(W,H)),ue.stop();continue}if(R.message.includes("socket disconnected")||R.message.includes("TLS")||R.message.includes("ECONNRESET")||R.message.includes("ECONNABORTED")||R.message.includes("ETIMEDOUT")||R.code==="ECONNRESET"||R.code==="ECONNABORTED"){if(k++,k>hr){console.log(`${b.red} Network error: max retries (${hr}) exceeded. Check your connection and try again.${b.reset}`),n&&(n.stop(),n=null),s(null),Je(E,F,j,Z,G),Ye(Y);break}let H=Math.min(2e3*Math.pow(2,k-1),3e4),ue=new Yt(`Network error \u2014 retrying in ${Math.round(H/1e3)}s (${k}/${hr})`);ue.start(),await new Promise(W=>setTimeout(W,H)),ue.stop(),D--;continue}n&&(n.stop(),n=null),s(null),Je(E,F,j,Z,G),Ye(Y);break}clearInterval(Hr),S=0,k=0,Me&&(n&&!n._paused&&n.pause(),be&&be.stop()),Xe&&(clearTimeout(Xe),Xe=null),Le&&we&&(we.push(Le),Le=""),Pe&&we.flush(),k=0,v=0,lt&&lt.usage&&(Hh(Cn(),Cs(),lt.usage.prompt_tokens||0,lt.usage.completion_tokens||0),o+=(lt.usage.prompt_tokens||0)+(lt.usage.completion_tokens||0),n&&n.setStats({tokens:o}));let{content:Hs,tool_calls:bt}=lt,Gs={role:"assistant",content:Hs||""};if(bt&&bt.length>0&&(Gs.tool_calls=bt),Y.push(Gs),x.push(Gs),!bt||bt.length===0){let R=(Hs||"").trim().length>0||Pe.trim().length>0;if(!R&&E>0&&D<yr-1){let N={role:"user",content:"[SYSTEM] You ran tools but produced no visible output. The user CANNOT see tool results \u2014 only your text. Please summarize your findings now."};x.push(N),Y.push(N);continue}if(Ms()&&R){let N=(Hs||Pe||"").trim();Mh(N),lg(N);let qe=Ph(N);if(qe.length>0){let H=Y.find(he=>he.role==="user"),ue=typeof H?.content=="string"?H.content.slice(0,120):"Task";Lh(ue,qe);let W=qe.length===1?"step":"steps";console.log(`
559
- ${b.cyan}${b.bold}Plan ready${b.reset} ${b.dim}(${qe.length} ${W} extracted).${b.reset} Type ${b.cyan}/plan approve${b.reset}${b.dim} to execute, or ${b.reset}${b.cyan}/plan edit${b.reset}${b.dim} to review.${b.reset}`)}else console.log(`
560
- ${b.cyan}${b.bold}Plan ready.${b.reset} ${b.dim}Type ${b.reset}${b.cyan}/plan approve${b.reset}${b.dim} to execute, or ask follow-up questions to refine.${b.reset}`)}n&&(n.stop(),n=null),s(null),Je(E,F,j,Z,G),Ye(Y);return}E++,E>=1&&(ee=!1);for(let R of bt){let N=R.function.name;F.set(N,(F.get(N)||0)+1)}let Qe=await Promise.all(bt.map(R=>ug(R))),tn=n?{skipSpinner:!0,skipSummaries:!0}:{},lu=Qe.some(R=>R.fnName==="ask_user"),Gr=!tn.skipSummaries&&!ee,zs=null;Gr&&!lu?(ee=!0,tn.skipSpinner=!0,process.stdout.isTTY?(process.stdout.write(lr(Qe,E,!1,"blink")),zs=!0):process.stdout.write(lr(Qe,E,!1)+`
561
- `)):Gr&&(ee=!0,tn.skipSpinner=!0),n&&n._paused&&n.resume();let{results:zr,summaries:Kr}=await pg(Qe,!0,{...tn,skipSummaries:!0});if(zs&&(zs=null,process.stdout.write(`\r\x1B[2K${lr(Qe,E,!1)}
562
- `)),!tn.skipSummaries)for(let R=0;R<Kr.length;R++)Qe[R]&&Qe[R].fnName==="ask_user"||console.log(Kr[R]);for(let R=0;R<Qe.length;R++){let N=Qe[R];if(!N.canExecute)continue;let H=zr[R].content.split(`
563
- `)[0],ue=!H.startsWith("ERROR")&&!H.startsWith("CANCELLED");if(ue&&["write_file","edit_file","patch_file"].includes(N.fnName)&&N.args&&N.args.path){j.add(N.args.path);let W=(te.get(N.args.path)||0)+1;te.set(N.args.path,W);let he=N.args.path.split("/").slice(-2).join("/");if(W===me){console.log(`${b.yellow} \u26A0 Loop warning: "${he}" edited ${W}\xD7 \u2014 possible edit loop${b.reset}`);let Re={role:"user",content:`[SYSTEM WARNING] You have edited "${N.args.path}" ${W} times in this session. This may indicate an edit loop. STOP editing this file repeatedly. Re-read it once to verify the current state, then make ONE final targeted edit or declare the task complete.`};Y.push(Re),x.push(Re)}else if(W>=Pn){console.log(`${b.red} \u2716 Loop abort: "${he}" edited ${W}\xD7 \u2014 aborting to prevent runaway loop${b.reset}`),n&&(n.stop(),n=null),s(null),Je(E,F,j,Z,G),Ye(Y);return}}if(N.fnName==="bash_exec"&&N.args&&N.args.command){let W=N.args.command.replace(/\s+/g," ").trim().slice(0,100),he=(ye.get(W)||0)+1;if(ye.set(W,he),he===It){console.log(`${b.yellow} \u26A0 Loop warning: same bash command run ${he}\xD7 \u2014 possible debug loop${b.reset}`);let Re={role:"user",content:`[SYSTEM WARNING] You have run the same or similar bash command ${he} times. This looks like a debug loop. STOP repeating the same command. Try a completely different approach or declare that the current approach is not working and explain why.`};Y.push(Re),x.push(Re)}else if(he>=q){console.log(`${b.red} \u2716 Loop abort: same bash command run ${he}\xD7 \u2014 aborting runaway debug loop${b.reset}`),n&&(n.stop(),n=null),s(null),Je(E,F,j,Z,G),Ye(Y);return}}if(ue)P=0;else if(P++,P===B){console.log(`${b.yellow} \u26A0 Loop warning: ${P} consecutive tool errors \u2014 possible stuck loop${b.reset}`);let W={role:"user",content:`[SYSTEM WARNING] ${P} consecutive tool calls have failed. You appear to be stuck. STOP trying variations of the same failing approach. Either try something fundamentally different, acknowledge the limitation, or declare the task complete with what you have.`};Y.push(W),x.push(W)}else if(P>=V){console.log(`${b.red} \u2716 Loop abort: ${P} consecutive errors \u2014 aborting stuck loop${b.reset}`),n&&(n.stop(),n=null),s(null),Je(E,F,j,Z,G),Ye(Y);return}ue&&N.fnName==="read_file"&&N.args&&N.args.path&&Z.add(N.args.path)}for(let R of zr)Y.push(R),x.push(R);let Yr=hg();if(Yr){let R={role:"user",content:`[User note mid-run]: ${Yr}`};Y.push(R),x.push(R),console.log(`${b.cyan} \u270E Kontext hinzugef\xFCgt${b.reset}`)}}if(D>=Q){n&&(n.stop(),n=null),s(null),Je(E,F,j,Z,G),Ye(Y);let{getActiveProviderName:U}=ge();if(U()==="ollama"&&z<le){z++,Q=20,console.log(`${b.dim} \u2500\u2500 auto-extending (+20 turns, ext ${z}/${le}) \u2500\u2500${b.reset}`);continue e}if(console.log(`
564
- ${b.yellow}\u26A0 Max iterations reached.${b.reset}`),await ul(" Continue for 20 more turns?")){Q=20;continue e}console.log(`${b.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${b.reset}`)}break e}}gl.exports={processInput:Eg,clearConversation:yg,getConversationLength:bg,getConversationMessages:xg,setConversationMessages:_g,setAbortSignalGetter:Xh,setMaxIterations:Vh,invalidateSystemPromptCache:og,clearToolFilterCache:sg,getCachedFilteredTools:pl,buildSystemPrompt:hl,getProjectContextHash:ml,buildUserContent:fl,injectMidRunNote:mg}});var ge=L((Fy,xl)=>{var{OllamaProvider:Tg}=di(),{OpenAIProvider:Rg}=Ri(),{AnthropicProvider:Cg}=Ni(),{GeminiProvider:Ag}=Ii(),{LocalProvider:Og}=ji(),{checkBudget:Ng}=Ft(),_r={top:{ollama:"kimi-k2:1t",openai:"gpt-4.1",anthropic:"claude-sonnet-4-5",gemini:"gemini-2.5-pro"},strong:{ollama:"qwen3-coder:480b",openai:"gpt-4o",anthropic:"claude-sonnet",gemini:"gemini-2.5-flash"},fast:{ollama:"devstral-small-2:24b",openai:"gpt-4.1-mini",anthropic:"claude-haiku",gemini:"gemini-2.0-flash"}},$l={};for(let[t,e]of Object.entries(_r))for(let s of Object.values(e))$l[s]=t;function yl(t,e){let s=$l[t];return s&&_r[s][e]||t}var $e={},Te=null,pe=null,On=[];function Ie(){if(Object.keys($e).length>0)return;Xt("ollama",new Tg),Xt("openai",new Rg),Xt("anthropic",new Cg),Xt("gemini",new Ag),Xt("local",new Og);let t=process.env.DEFAULT_PROVIDER||"ollama",e=process.env.DEFAULT_MODEL||null;$e[t]?(Te=t,pe=e||$e[t].defaultModel):(Te="ollama",pe="kimi-k2.5");let s=process.env.FALLBACK_CHAIN;s&&(On=s.split(",").map(n=>n.trim()).filter(Boolean))}function Xt(t,e){$e[t]=e}function Mg(t){return Ie(),$e[t]||null}function kr(){return Ie(),$e[Te]||null}function Pg(){return Ie(),Te}function Lg(){return Ie(),pe}function Ig(){Ie();let t=kr();if(!t)return{id:pe,name:pe,provider:Te};let e=t.getModel(pe);return e?{...e,provider:Te}:{id:pe,name:pe,provider:Te}}function wl(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let s=t.slice(0,e);if($e[s]||["ollama","openai","anthropic","gemini","local"].includes(s))return{provider:s,model:t.slice(e+1)}}return{provider:null,model:t}}function qg(t){Ie();let{provider:e,model:s}=wl(t);if(e){let o=$e[e];return o&&(o.getModel(s)||e==="local"||e==="ollama")?(Te=e,pe=s,Ls(),!0):!1}let n=kr();if(n&&n.getModel(s))return pe=s,Ls(),!0;for(let[o,r]of Object.entries($e))if(r.getModel(s))return Te=o,pe=s,Ls(),!0;return!1}function Ls(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=fe();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=De();t()}catch{}}function Dg(){Ie();let t=new Set;for(let e of Object.values($e))for(let s of e.getModelNames())t.add(s);return Array.from(t)}function jg(){return Ie(),Object.entries($e).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(s=>({...s,active:t===Te&&s.id===pe}))}))}function Fg(){Ie();let t=[];for(let[e,s]of Object.entries($e)){let n=s.isConfigured();for(let o of Object.values(s.getModels()))t.push({spec:`${e}:${o.id}`,name:o.name,provider:e,configured:n})}return t}function Ug(t){On=Array.isArray(t)?t:[]}function Wg(){return[...On]}function Bg(t){let e=t.message||"",s=t.code||"";return!!(e.includes("429")||e.includes("500")||e.includes("502")||e.includes("503")||e.includes("504")||s==="ECONNABORTED"||s==="ETIMEDOUT"||s==="ECONNREFUSED"||s==="ECONNRESET"||s==="EHOSTUNREACH"||s==="ENETUNREACH"||s==="EPIPE"||s==="ERR_SOCKET_CONNECTION_TIMEOUT"||e.includes("socket disconnected")||e.includes("TLS")||e.includes("ECONNRESET")||e.includes("ECONNABORTED")||e.includes("network")||e.includes("ETIMEDOUT"))}async function bl(t){let e=[Te,...On.filter(r=>r!==Te)],s,n=0,o=0;for(let r=0;r<e.length;r++){let i=e[r],c=$e[i];if(!c||!c.isConfigured())continue;o++;let l=Ng(i);if(!l.allowed){n++,s=new Error(`Budget limit reached for ${i}: $${l.spent.toFixed(2)} / $${l.limit.toFixed(2)}`);continue}try{let u=r>0,d=u?yl(pe,i):pe;return u&&d!==pe&&process.stderr.write(` [fallback: ${i}:${d}]
565
- `),await t(c,i,d)}catch(u){if(s=u,Bg(u)&&r<e.length-1)continue;throw u}}throw n>0&&n===o?new Error("All providers are over budget. Use /budget to check limits or /budget <provider> off to remove a limit."):o===0?new Error("No configured provider available"):s||new Error("No configured provider available")}async function Hg(t,e,s={}){return Ie(),bl((n,o,r)=>n.stream(t,e,{model:r,signal:s.signal,...s}))}async function Gg(t,e,s={}){if(Ie(),s.provider){let n=$e[s.provider];if(!n||!n.isConfigured())throw new Error(`Provider '${s.provider}' is not available`);let o={model:s.model||pe,...s};try{return await n.chat(t,e,o)}catch(r){if(typeof n.stream=="function")try{return await n.stream(t,e,{...o,onToken:()=>{}})}catch{}throw r}}return bl(async(n,o,r)=>{try{return await n.chat(t,e,{model:r,...s})}catch(i){if(typeof n.stream=="function")try{return await n.stream(t,e,{model:r,...s,onToken:()=>{}})}catch{}throw i}})}function zg(){Ie();let t=[];for(let[e,s]of Object.entries($e))s.isConfigured()&&t.push({name:e,models:Object.values(s.getModels())});return t}function Kg(){for(let t of Object.keys($e))delete $e[t];Te=null,pe=null,On=[]}xl.exports={registerProvider:Xt,getProvider:Mg,getActiveProvider:kr,getActiveProviderName:Pg,getActiveModelId:Lg,getActiveModel:Ig,setActiveModel:qg,getModelNames:Dg,parseModelSpec:wl,listProviders:jg,listAllModels:Fg,callStream:Hg,callChat:Gg,getConfiguredProviders:zg,setFallbackChain:Ug,getFallbackChain:Wg,resolveModelForProvider:yl,MODEL_EQUIVALENTS:_r,_reset:Kg}});var Sr=L((Uy,_l)=>{"use strict";var it=require("fs"),Is=require("path"),Yg=require("readline"),J="\x1B[0m",vr="\x1B[1m",Ae="\x1B[2m",qs="\x1B[33m",Qt="\x1B[36m",Ds="\x1B[32m";function Jg(t){return(e,s="")=>new Promise(n=>{let o=s?` ${Ae}[${s}]${J}`:"";t.question(` ${Qt}${e}${o}${J}: `,r=>n(r.trim()||s))})}function js(t,e){return new Promise(s=>{e&&e.pause(),process.stdout.write(` ${Qt}${t}${J}: `);let n=process.stdin,o=n.isRaw,r="";n.setRawMode(!0),n.resume(),n.setEncoding("utf8");let i=c=>{c==="\r"||c===`
566
- `?(n.setRawMode(o||!1),n.removeListener("data",i),process.stdout.write(`
676
+ `,ui=t,as}function Py(){te=[]}function My(){te.length>Mu&&te.splice(0,te.length-Mu)}function Iy(){return te.length}function Ly(){return te}function jy(t){te=t}async function Dy(){let{execFile:t}=require("child_process"),e=require("fs"),s=process.cwd(),o=(f,m)=>new Promise(h=>{t(f,m,{cwd:s,timeout:3e3},(p,g)=>{h(p?"":(g||"").trim())})}),[n]=await Promise.all([o("find",[".","-type","f","-not","-path","*/node_modules/*","-not","-path","*/.git/*","-not","-path","*/dist/*","-not","-path","*/.next/*","-not","-path","*/build/*","-not","-path","*/__pycache__/*","-not","-path","*/vendor/*"])]),r=new Set(["js","ts","jsx","tsx","py","go","rs","rb","java","cpp","c","cs"]),i=(n?n.split(`
677
+ `):[]).filter(f=>{let m=f.split(".").pop();return r.has(m)});if(i.length<3)return null;let c={};for(let f of i){let m=f.split(".").pop();c[m]=(c[m]||0)+1}let u=` \u{1F4C1} ${Object.entries(c).sort((f,m)=>m[1]-f[1]).slice(0,4).map(([f,m])=>`${m} .${f}`).join(" \xB7 ")}`,d=fi.join(s,"package.json");if(e.existsSync(d))try{let f=JSON.parse(e.readFileSync(d,"utf-8")),m=Object.keys({...f.dependencies||{},...f.devDependencies||{}});if(m.length>0){let h=m.slice(0,5).join(" \xB7 "),p=m.length>5?` +${m.length-5}`:"";u+=`
678
+ \u{1F4E6} ${h}${p}`}}catch{}return u}function qy(t){if(process.platform==="darwin")try{let{execFileSync:e}=require("child_process");e("osascript",["-e",`display notification "${t.replace(/"/g,'\\"')}" with title "nex-code"`],{timeout:3e3,stdio:"ignore"})}catch{}}function at(t,e,s,o,n){if(t<1)return;let r=[...e.values()].reduce((l,u)=>l+u,0),i=`\u2500\u2500 ${t} ${t===1?"step":"steps"} \xB7 ${r} ${r===1?"tool":"tools"}`,c=0;if(n){let l=Date.now()-n;c=Math.round(l/1e3),i+=c>=60?` \xB7 ${Math.floor(c/60)}m ${c%60}s`:` \xB7 ${c}s`}if(s.size>0&&(i+=` \xB7 ${s.size} ${s.size===1?"file":"files"} modified`),i+=" \u2500\u2500",console.log(`
679
+ ${k.dim} ${i}${k.reset}`),c>=30&&process.stdout.isTTY){let l=s.size>0?`Done \u2014 ${s.size} ${s.size===1?"file":"files"} modified in ${c}s`:`Done \u2014 ${t} ${t===1?"step":"steps"} in ${c}s`;qy(l)}s.size>0?console.log(`${k.dim} \u{1F4A1} /diff \xB7 /commit \xB7 /undo${k.reset}`):o.size>=5&&s.size===0&&t>=3?console.log(`${k.dim} \u{1F4A1} Found issues? Say "fix 1" or "apply all fixes"${k.reset}`):o.size>0&&t>=2&&console.log(`${k.dim} \u{1F4A1} /save \xB7 /clear${k.reset}`)}async function Fy(){if(!process.stdout.isTTY)return{action:"quit"};let t=is(),e=fo(),s=$o.fast?.[t],o=$o.strong?.[t],n=s&&s!==e,r=o&&o!==e&&o!==s,i=[];i.push({key:"r",label:`Retry with current model ${k.dim}(${e})${k.reset}`}),n&&i.push({key:"f",label:`Switch to ${k.bold}${s}${k.reset} ${k.dim}\u2014 fast, low latency${k.reset}`,model:s}),r&&i.push({key:"s",label:`Switch to ${k.bold}${o}${k.reset} ${k.dim}\u2014 reliable tool-calling, medium speed${k.reset}`,model:o}),i.push({key:"q",label:`${k.dim}Quit${k.reset}`}),console.log(),console.log(`${k.yellow} Stream stale \u2014 all retries exhausted.${k.reset} What would you like to do?`);for(let c of i)console.log(` ${k.cyan}[${c.key}]${k.reset} ${c.label}`);return process.stdout.write(` ${k.yellow}> ${k.reset}`),new Promise(c=>{let l=process.stdin,u=l.isRaw;l.setRawMode(!0),l.resume(),l.setEncoding("utf8");let d=!1,f=m=>{if(d)return;d=!0,l.removeListener("data",f),l.setRawMode(u||!1),l.pause();let h=m.toLowerCase().trim();if(process.stdout.write(`${h}
680
+ `),m==="")return c({action:"quit"});let p=i.find(g=>g.key===h);!p||p.key==="q"||!p.model&&p.key!=="r"?c({action:"quit"}):p.key==="r"?c({action:"retry"}):c({action:"switch",model:p.model,provider:t})};l.on("data",f)})}var ct=null;async function Uy(t,e=null){ct=e;let s=Du(t);te.push({role:"user",content:s}),My();let{setOnChange:o}=Gs(),n=null,r=0;o((B,G)=>{B==="create"?(n&&n.stop(),n=new O$(G.name,G.tasks),n.setStats({tokens:r}),n.start()):B==="update"&&n?n.updateTask(G.id,G.status):B==="clear"&&n&&(n.stop(),n=null)});let i=await Uu(),c=i;try{let{getBrainContext:B}=Xn(),G=await B(t);G&&(c=i+`
681
+ `+G+`
682
+ `)}catch(B){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",B.message)}let l=[{role:"system",content:c},...te],u=new bn("Thinking...");u.start();let f=te.length===1?Dy().catch(()=>null):Promise.resolve(null),m=_n(),[{messages:h,compressed:p,compacted:g,tokensRemoved:$},y]=await Promise.all([D$(l,m),f]),w=q$(l,m);if(u.stop(),y&&console.log(`${k.dim}${y}${k.reset}`),g)console.log(`${k.dim} [context compacted \u2014 summary (~${$} tokens freed)]${k.reset}`);else if(p){let B=w.limit>0?Math.round($/w.limit*100):0;console.log(`${k.dim} [context compressed \u2014 ~${$} tokens freed (${B}%)]${k.reset}`)}w.percentage>85&&console.log(`${k.yellow} \u26A0 Context ${Math.round(w.percentage)}% full \u2014 consider /clear or /save + start fresh${k.reset}`);let T=h,_=0,x=0,S=0,R=0,C=0,I=9,D=0,K=0,z=new Map,Q=new Set,Z=new Set,Y=Date.now(),et=new Map,tt=2,ce=4,_t=new Map,Eo=5,To=8,ut=0,N=6,L=10,U,H=li,W=0,oe=3;e:for(;;){for(U=0;U<H&&!po()?.aborted;U++){let G=!0;K>0&&Q$();let J=null;if(n&&n.isActive())n._paused&&n.resume();else if(!n){let O,q=Z$();if(q&&q.total>1){let De=q.description.length>40?q.description.slice(0,37)+"\u2026":q.description;O=`Plan step ${q.current}/${q.total}: ${De}`}else O=K>0?`Thinking... (step ${K+1})`:"Thinking...";J=new bn(O),J.start()}let Ce=!0,je="",pe=new ey,xe,Mt=Date.now(),ds=!1,Ro=new AbortController,Mi=setInterval(()=>{let O=Date.now()-Mt;if(O>=Pu)pe._clearCursorLine(),console.log(`${k.yellow} \u26A0 Stream stale for ${Math.round(O/1e3)}s \u2014 aborting and retrying${k.reset}`),Ro.abort();else if(O>=ky&&!ds){ds=!0,pe._clearCursorLine();let q=$o.fast?.[is()],De=S>0?` (retry ${S+1}/${uo})`:"",re=Math.round((Pu-O)/1e3);console.log(`${k.yellow} \u26A0 No tokens received for ${Math.round(O/1e3)}s \u2014 waiting...${De}${k.reset}`),q&&q!==fo()?console.log(`${k.dim} \u{1F4A1} Will auto-switch to ${q} in ~${re}s if no tokens arrive${k.reset}`):console.log(`${k.dim} \u{1F4A1} Ctrl+C to abort \xB7 auto-abort in ~${re}s${k.reset}`)}},5e3),He="",dt=null;try{let O=qu(_n()),q=go()?O.filter(le=>ju.has(le.function.name)):O,De=po(),re=new AbortController;De&&De.addEventListener("abort",()=>re.abort(),{once:!0}),Ro.signal.addEventListener("abort",()=>re.abort(),{once:!0}),xe=await M$(T,q,{signal:re.signal,onThinkingToken:()=>{Mt=Date.now(),ds=!1,ct?.onThinkingToken&&ct.onThinkingToken()},onToken:le=>{if(Mt=Date.now(),ds=!1,ct?.onToken){ct.onToken(le),je+=le;return}He+=le,process.stdout.isTTY?dt||(dt=setTimeout(()=>{He&&pe&&pe.push(He),He="",dt=null},50)):(pe.push(He),He=""),Ce&&(n&&!n._paused?n.pause():J&&J.stop(),G||(G=!0),pe.startCursor(),Ce=!1),je+=le}})}catch(O){if(clearInterval(Mi),dt&&(clearTimeout(dt),dt=null),He&&pe&&(pe.push(He),He=""),n&&!n._paused&&n.pause(),J&&J.stop(),pe.stopCursor(),Ro.signal.aborted&&!po()?.aborted){if(S++,S>uo){if(R<1){R++,console.log(`${k.yellow} \u26A0 Stale retries exhausted \u2014 last-resort force-compress...${k.reset}`);let be=_n(),{messages:nt,tokensRemoved:tn}=ni(T,be);T=nt,console.log(`${k.dim} [force-compressed \u2014 ~${tn} tokens freed]${k.reset}`),S=0,U--;continue}n&&(n.stop(),n=null);let X=await Fy();if(X.action==="quit"){o(null),at(K,z,Q,Z,Y),it(te);break}X.action==="switch"&&(Ou(`${X.provider}:${X.model}`),console.log(`${k.green} \u2713 Switched to ${X.provider}:${X.model}${k.reset}`)),S=0,U--;continue}let re=S===1?3e3:5e3;if(S>=1&&D<1){D++,console.log(`${k.yellow} \u26A0 Stale retry ${S}/${uo} \u2014 force-compressing before retry...${k.reset}`);let X=_n(),{messages:be,tokensRemoved:nt}=ni(T,X,!0);if(T=be,nt>0&&console.log(`${k.dim} [force-compressed \u2014 ~${nt} tokens freed]${k.reset}`),xy){let tn=$o.fast?.[is()];tn&&tn!==fo()&&(Ou(`${is()}:${tn}`),console.log(`${k.cyan} \u26A1 Auto-switched to ${tn} to avoid further stale timeouts${k.reset}`),console.log(`${k.dim} (disable with NEX_STALE_AUTO_SWITCH=0)${k.reset}`))}}else console.log(`${k.yellow} \u26A0 Stale retry ${S}/${uo} \u2014 retrying in ${re/1e3}s...${k.reset}`);let le=new bn(`Waiting ${re/1e3}s before retry...`);le.start(),await new Promise(X=>setTimeout(X,re)),le.stop(),U--;continue}if(O.name==="AbortError"||O.name==="CanceledError"||O.message?.includes("canceled")||O.message?.includes("aborted")){n&&(n.stop(),n=null),o(null),at(K,z,Q,Z,Y),it(te);break}let q=O.message;if(O.code==="ECONNREFUSED"||O.message.includes("ECONNREFUSED"))q="Connection refused \u2014 please check your internet connection or API endpoint";else if(O.code==="ENOTFOUND"||O.message.includes("ENOTFOUND"))q="Network error \u2014 could not reach the API server. Please check your connection";else if(O.code==="ETIMEDOUT"||O.message.includes("timeout"))q="Request timed out \u2014 the API server took too long to respond. Please try again";else if(O.message.includes("401")||O.message.includes("Unauthorized"))q="Authentication failed \u2014 please check your API key in the .env file";else if(O.message.includes("403")||O.message.includes("Forbidden"))q="Access denied \u2014 your API key may not have permission for this model";else if(O.message.includes("400")){if(R<3&&C<I){R++,C++;let re=R===3||D>0;console.log(re?`${k.yellow} \u26A0 Bad request (400) \u2014 nuclear compression (attempt ${R}/3, dropping history)...${k.reset}`:`${k.yellow} \u26A0 Bad request (400) \u2014 force-compressing and retrying... (attempt ${R}/3)${k.reset}`);let le=_n(),{messages:X,tokensRemoved:be}=ni(T,le,re);T=X,be>0&&console.log(`${k.dim} [force-compressed \u2014 ~${be} tokens freed]${k.reset}`),U--;continue}q="Context too large to compress \u2014 use /clear to start fresh"}else O.message.includes("500")||O.message.includes("502")||O.message.includes("503")||O.message.includes("504")?q="API server error \u2014 the provider is experiencing issues. Please try again in a moment":(O.message.includes("fetch failed")||O.message.includes("fetch"))&&(q="Network request failed \u2014 please check your internet connection");if(console.log(`${k.red} \u2717 ${q}${k.reset}`),O.message.includes("429")){if(_++,_>ii){console.log(`${k.red} Rate limit: max retries (${ii}) exceeded. Try again later or use /budget to check your limits.${k.reset}`),n&&(n.stop(),n=null),o(null),at(K,z,Q,Z,Y),it(te);break}let re=Math.min(1e4*Math.pow(2,_-1),12e4),le=new bn(`Rate limit \u2014 waiting ${Math.round(re/1e3)}s (retry ${_}/${ii})`);le.start(),await new Promise(X=>setTimeout(X,re)),le.stop();continue}if(O.message.includes("socket disconnected")||O.message.includes("TLS")||O.message.includes("ECONNRESET")||O.message.includes("ECONNABORTED")||O.message.includes("ETIMEDOUT")||O.code==="ECONNRESET"||O.code==="ECONNABORTED"){if(x++,x>ai){console.log(`${k.red} Network error: max retries (${ai}) exceeded. Check your connection and try again.${k.reset}`),n&&(n.stop(),n=null),o(null),at(K,z,Q,Z,Y),it(te);break}let re=Math.min(2e3*Math.pow(2,x-1),3e4),le=new bn(`Network error \u2014 retrying in ${Math.round(re/1e3)}s (${x}/${ai})`);le.start(),await new Promise(X=>setTimeout(X,re)),le.stop(),U--;continue}n&&(n.stop(),n=null),o(null),at(K,z,Q,Z,Y),it(te);break}clearInterval(Mi),_=0,x=0,Ce&&(n&&!n._paused&&n.pause(),J&&J.stop()),dt&&(clearTimeout(dt),dt=null),He&&pe&&(pe.push(He),He=""),je&&pe.flush(),x=0,S=0,xe&&xe.usage&&(iy(is(),fo(),xe.usage.prompt_tokens||0,xe.usage.completion_tokens||0),r+=(xe.usage.prompt_tokens||0)+(xe.usage.completion_tokens||0),n&&n.setStats({tokens:r}));let{content:Co,tool_calls:It}=xe,Ao={role:"assistant",content:Co||""};if(It&&It.length>0&&(Ao.tool_calls=It),te.push(Ao),T.push(Ao),!It||It.length===0){let O=(Co||"").trim().length>0||je.trim().length>0;if(!O&&K>0&&U<li-1){let q={role:"user",content:"[SYSTEM] You ran tools but produced no visible output. The user CANNOT see tool results \u2014 only your text. Please summarize your findings now."};T.push(q),te.push(q);continue}if(go()&&O){let q=(Co||je||"").trim();X$(q),vy(q);let De=J$(q);if(De.length>0){let re=te.find(be=>be.role==="user"),le=typeof re?.content=="string"?re.content.slice(0,120):"Task";V$(le,De);let X=De.length===1?"step":"steps";console.log(`
683
+ ${k.cyan}${k.bold}Plan ready${k.reset} ${k.dim}(${De.length} ${X} extracted).${k.reset} Type ${k.cyan}/plan approve${k.reset}${k.dim} to execute, or ${k.reset}${k.cyan}/plan edit${k.reset}${k.dim} to review.${k.reset}`)}else console.log(`
684
+ ${k.cyan}${k.bold}Plan ready.${k.reset} ${k.dim}Type ${k.reset}${k.cyan}/plan approve${k.reset}${k.dim} to execute, or ask follow-up questions to refine.${k.reset}`)}n&&(n.stop(),n=null),o(null),at(K,z,Q,Z,Y),it(te);return}K++,K>=1&&(G=!1);for(let O of It){let q=O.function.name;z.set(q,(z.get(q)||0)+1)}let ft=await Promise.all(It.map(O=>Sy(O))),Rn=n?{skipSpinner:!0,skipSummaries:!0}:{},jd=ft.some(O=>O.fnName==="ask_user"),Ii=!Rn.skipSummaries&&!G,Oo=null;Ii&&!jd?(G=!0,Rn.skipSpinner=!0,process.stdout.isTTY?(process.stdout.write(ti(ft,K,!1,"blink")),Oo=!0):ct||process.stdout.write(ti(ft,K,!1)+`
685
+ `)):Ii&&(G=!0,Rn.skipSpinner=!0),n&&n._paused&&n.resume();let{results:Li,summaries:ji}=await Ry(ft,!0,{...Rn,skipSummaries:!0});if(Oo&&(Oo=null,process.stdout.write(`\r\x1B[2K${ti(ft,K,!1)}
686
+ `)),!Rn.skipSummaries){for(let O=0;O<ji.length;O++)ft[O]&&ft[O].fnName==="ask_user"||console.log(ji[O]);console.log("")}for(let O=0;O<ft.length;O++){let q=ft[O];if(!q.canExecute)continue;let re=Li[O].content.split(`
687
+ `)[0],le=!re.startsWith("ERROR")&&!re.startsWith("CANCELLED");if(le&&["write_file","edit_file","patch_file"].includes(q.fnName)&&q.args&&q.args.path){Q.add(q.args.path);let X=(et.get(q.args.path)||0)+1;et.set(q.args.path,X);let be=q.args.path.split("/").slice(-2).join("/");if(X===tt){console.log(`${k.yellow} \u26A0 Loop warning: "${be}" edited ${X}\xD7 \u2014 possible edit loop${k.reset}`);let nt={role:"user",content:`[SYSTEM WARNING] You have edited "${q.args.path}" ${X} times already. STOP. Do NOT edit this file again unless absolutely necessary. Read it once to verify the current state, make at most ONE more targeted change, then move on or declare the task complete. Further edits to this file will abort the session.`};te.push(nt),T.push(nt)}else if(X>=ce){console.log(`${k.red} \u2716 Loop abort: "${be}" edited ${X}\xD7 \u2014 aborting to prevent runaway loop${k.reset}`),n&&(n.stop(),n=null),o(null),at(K,z,Q,Z,Y),it(te);return}}if(q.fnName==="bash_exec"&&q.args&&q.args.command){let X=q.args.command.replace(/\s+/g," ").trim().slice(0,100),be=(_t.get(X)||0)+1;if(_t.set(X,be),be===Eo){console.log(`${k.yellow} \u26A0 Loop warning: same bash command run ${be}\xD7 \u2014 possible debug loop${k.reset}`);let nt={role:"user",content:`[SYSTEM WARNING] You have run the same or similar bash command ${be} times. This looks like a debug loop. STOP repeating the same command. Try a completely different approach or declare that the current approach is not working and explain why.`};te.push(nt),T.push(nt)}else if(be>=To){console.log(`${k.red} \u2716 Loop abort: same bash command run ${be}\xD7 \u2014 aborting runaway debug loop${k.reset}`),n&&(n.stop(),n=null),o(null),at(K,z,Q,Z,Y),it(te);return}}if(le)ut=0;else if(ut++,ut===N){console.log(`${k.yellow} \u26A0 Loop warning: ${ut} consecutive tool errors \u2014 possible stuck loop${k.reset}`);let X={role:"user",content:`[SYSTEM WARNING] ${ut} consecutive tool calls have failed. You appear to be stuck. STOP trying variations of the same failing approach. Either try something fundamentally different, acknowledge the limitation, or declare the task complete with what you have.`};te.push(X),T.push(X)}else if(ut>=L){console.log(`${k.red} \u2716 Loop abort: ${ut} consecutive errors \u2014 aborting stuck loop${k.reset}`),n&&(n.stop(),n=null),o(null),at(K,z,Q,Z,Y),it(te);return}le&&q.fnName==="read_file"&&q.args&&q.args.path&&Z.add(q.args.path)}for(let O of Li)te.push(O),T.push(O);let Di=Ay();if(Di){let O={role:"user",content:`[User note mid-run]: ${Di}`};te.push(O),T.push(O),console.log(`${k.cyan} \u270E Kontext hinzugef\xFCgt${k.reset}`)}}if(U>=H){n&&(n.stop(),n=null),o(null),at(K,z,Q,Z,Y),it(te);let{getActiveProviderName:B}=we();if(B()==="ollama"&&W<oe){W++,H=20,console.log(`${k.dim} \u2500\u2500 auto-extending (+20 turns, ext ${W}/${oe}) \u2500\u2500${k.reset}`);continue e}if(console.log(`
688
+ ${k.yellow}\u26A0 Max iterations reached.${k.reset}`),await Lu(" Continue for 20 more turns?")){H=20;continue e}console.log(`${k.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${k.reset}`)}break e}}Wu.exports={processInput:Uy,clearConversation:Py,getConversationLength:Iy,getConversationMessages:Ly,setConversationMessages:jy,setAbortSignalGetter:py,setMaxIterations:fy,invalidateSystemPromptCache:by,clearToolFilterCache:wy,getCachedFilteredTools:qu,buildSystemPrompt:Uu,getProjectContextHash:Fu,buildUserContent:Du,injectMidRunNote:Cy}});var we=j((fb,zu)=>{var{OllamaProvider:Wy}=aa(),{OpenAIProvider:By}=Ea(),{AnthropicProvider:Hy}=Aa(),{GeminiProvider:Gy}=Ma(),{LocalProvider:Ky}=ja(),{checkBudget:zy}=ln(),pi={top:{ollama:"kimi-k2:1t",openai:"gpt-4.1",anthropic:"claude-sonnet-4-5",gemini:"gemini-2.5-pro"},strong:{ollama:"qwen3-coder:480b",openai:"gpt-4o",anthropic:"claude-sonnet",gemini:"gemini-2.5-flash"},fast:{ollama:"devstral-small-2:24b",openai:"gpt-4.1-mini",anthropic:"claude-haiku",gemini:"gemini-2.0-flash"}},Bu={};for(let[t,e]of Object.entries(pi))for(let s of Object.values(e))Bu[s]=t;function Hu(t,e){let s=Bu[t];return s&&pi[s][e]||t}var ke={},Le=null,_e=null,cs=[];function ze(){if(Object.keys(ke).length>0)return;xn("ollama",new Wy),xn("openai",new By),xn("anthropic",new Hy),xn("gemini",new Gy),xn("local",new Ky);let t=process.env.DEFAULT_PROVIDER||"ollama",e=process.env.DEFAULT_MODEL||null;ke[t]?(Le=t,_e=e||ke[t].defaultModel):(Le="ollama",_e="kimi-k2.5");let s=process.env.FALLBACK_CHAIN;s&&(cs=s.split(",").map(o=>o.trim()).filter(Boolean))}function xn(t,e){ke[t]=e}function Yy(t){return ze(),ke[t]||null}function mi(){return ze(),ke[Le]||null}function Xy(){return ze(),Le}function Jy(){return ze(),_e}function Vy(){ze();let t=mi();if(!t)return{id:_e,name:_e,provider:Le};let e=t.getModel(_e);return e?{...e,provider:Le}:{id:_e,name:_e,provider:Le}}function Gu(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let s=t.slice(0,e);if(ke[s]||["ollama","openai","anthropic","gemini","local"].includes(s))return{provider:s,model:t.slice(e+1)}}return{provider:null,model:t}}function Qy(t){ze();let{provider:e,model:s}=Gu(t);if(e){let n=ke[e];return n&&(n.getModel(s)||e==="local"||e==="ollama")?(Le=e,_e=s,yo(),!0):!1}let o=mi();if(o&&o.getModel(s))return _e=s,yo(),!0;for(let[n,r]of Object.entries(ke))if(r.getModel(s))return Le=n,_e=s,yo(),!0;return!1}function yo(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=me();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=Xe();t()}catch{}}function Zy(){ze();let t=new Set;for(let e of Object.values(ke))for(let s of e.getModelNames())t.add(s);return Array.from(t)}function ew(){return ze(),Object.entries(ke).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(s=>({...s,active:t===Le&&s.id===_e}))}))}function tw(){ze();let t=[];for(let[e,s]of Object.entries(ke)){let o=s.isConfigured();for(let n of Object.values(s.getModels()))t.push({spec:`${e}:${n.id}`,name:n.name,provider:e,configured:o})}return t}function nw(t){cs=Array.isArray(t)?t:[]}function sw(){return[...cs]}function ow(t){let e=t.message||"",s=t.code||"";return!!(e.includes("429")||e.includes("500")||e.includes("502")||e.includes("503")||e.includes("504")||s==="ECONNABORTED"||s==="ETIMEDOUT"||s==="ECONNREFUSED"||s==="ECONNRESET"||s==="EHOSTUNREACH"||s==="ENETUNREACH"||s==="EPIPE"||s==="ERR_SOCKET_CONNECTION_TIMEOUT"||e.includes("socket disconnected")||e.includes("TLS")||e.includes("ECONNRESET")||e.includes("ECONNABORTED")||e.includes("network")||e.includes("ETIMEDOUT"))}async function Ku(t){let e=[Le,...cs.filter(r=>r!==Le)],s,o=0,n=0;for(let r=0;r<e.length;r++){let i=e[r],c=ke[i];if(!c||!c.isConfigured())continue;n++;let l=zy(i);if(!l.allowed){o++,s=new Error(`Budget limit reached for ${i}: $${l.spent.toFixed(2)} / $${l.limit.toFixed(2)}`);continue}try{let u=r>0,d=u?Hu(_e,i):_e;return u&&d!==_e&&process.stderr.write(` [fallback: ${i}:${d}]
689
+ `),await t(c,i,d)}catch(u){if(s=u,ow(u)&&r<e.length-1)continue;throw u}}throw o>0&&o===n?new Error("All providers are over budget. Use /budget to check limits or /budget <provider> off to remove a limit."):n===0?new Error("No configured provider available"):s||new Error("No configured provider available")}async function rw(t,e,s={}){return ze(),Ku((o,n,r)=>o.stream(t,e,{model:r,signal:s.signal,...s}))}async function iw(t,e,s={}){if(ze(),s.provider){let o=ke[s.provider];if(!o||!o.isConfigured())throw new Error(`Provider '${s.provider}' is not available`);let n={model:s.model||_e,...s};try{return await o.chat(t,e,n)}catch(r){if(typeof o.stream=="function")try{return await o.stream(t,e,{...n,onToken:()=>{}})}catch{}throw r}}return Ku(async(o,n,r)=>{try{return await o.chat(t,e,{model:r,...s})}catch(i){if(typeof o.stream=="function")try{return await o.stream(t,e,{model:r,...s,onToken:()=>{}})}catch{}throw i}})}function aw(){ze();let t=[];for(let[e,s]of Object.entries(ke))s.isConfigured()&&t.push({name:e,models:Object.values(s.getModels())});return t}function cw(){for(let t of Object.keys(ke))delete ke[t];Le=null,_e=null,cs=[]}zu.exports={registerProvider:xn,getProvider:Yy,getActiveProvider:mi,getActiveProviderName:Xy,getActiveModelId:Jy,getActiveModel:Vy,setActiveModel:Qy,getModelNames:Zy,parseModelSpec:Gu,listProviders:ew,listAllModels:tw,callStream:rw,callChat:iw,getConfiguredProviders:aw,setFallbackChain:nw,getFallbackChain:sw,resolveModelForProvider:Hu,MODEL_EQUIVALENTS:pi,_reset:cw}});var gi=j((pb,Yu)=>{"use strict";var yt=require("fs"),wo=require("path"),lw=require("readline"),ne="\x1B[0m",hi="\x1B[1m",Ue="\x1B[2m",bo="\x1B[33m",vn="\x1B[36m",_o="\x1B[32m";function uw(t){return(e,s="")=>new Promise(o=>{let n=s?` ${Ue}[${s}]${ne}`:"";t.question(` ${vn}${e}${n}${ne}: `,r=>o(r.trim()||s))})}function ko(t,e){return new Promise(s=>{e&&e.pause(),process.stdout.write(` ${vn}${t}${ne}: `);let o=process.stdin,n=o.isRaw,r="";o.setRawMode(!0),o.resume(),o.setEncoding("utf8");let i=c=>{c==="\r"||c===`
690
+ `?(o.setRawMode(n||!1),o.removeListener("data",i),process.stdout.write(`
567
691
  `),e&&e.resume(),s(r)):c===""?(process.stdout.write(`
568
- `),process.exit(0)):c==="\x7F"?r.length>0&&(r=r.slice(0,-1),process.stdout.write("\b \b")):(r+=c,process.stdout.write("*"))};n.on("data",i)})}async function Vg({rl:t=null,force:e=!1}={}){if(!e){let f=it.existsSync(Is.join(process.cwd(),".env"))||it.existsSync(Is.join(__dirname,"..",".env")),h=process.env.ANTHROPIC_API_KEY||process.env.OPENAI_API_KEY||process.env.GEMINI_API_KEY||process.env.OPENROUTER_API_KEY,m=process.env.DEFAULT_PROVIDER||process.env.DEFAULT_MODEL;if(f||h||m)return}let s=!t,n=t||Yg.createInterface({input:process.stdin,output:process.stdout,terminal:!0}),o=Jg(n),r=!e;console.log(),console.log(r?`${qs}${vr} \u2726 Welcome to nex-code! No configuration found.${J}`:`${Qt}${vr} \u2726 nex-code \u2014 Provider & API Key Setup${J}`),console.log(`${Ae} \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500${J}`),r&&console.log(` Let's set you up in 60 seconds.
569
- `),console.log(` ${vr}Which AI provider do you want to use?${J}
570
- `),console.log(` ${Ds}1)${J} Ollama ${Ae}local/cloud \u2014 no API key needed${J}`),console.log(` ${Qt}2)${J} Anthropic ${Ae}Claude (claude-sonnet-4-6 etc.)${J}`),console.log(` ${Qt}3)${J} OpenAI ${Ae}GPT-4o, GPT-4.1 etc.${J}`),console.log(` ${Qt}4)${J} Gemini ${Ae}Google Gemini 2.x${J}`),console.log(` ${Ae}5) Skip / Cancel${J}`),console.log();let i=await o("Enter number","1"),c=[];if(i==="5"){s&&n.close(),console.log(`
571
- ${Ae} Cancelled \u2014 no changes made.${J}
572
- `);return}if(i==="1"){console.log();let f=await o("Ollama host","http://localhost:11434"),h=await o("Default model","qwen3-coder");c.push("DEFAULT_PROVIDER=ollama",`DEFAULT_MODEL=${h}`,`OLLAMA_HOST=${f}`),process.env.DEFAULT_PROVIDER="ollama",process.env.DEFAULT_MODEL=h,process.env.OLLAMA_HOST=f}else if(i==="2"){console.log(),console.log(` ${Ae}Get your key: https://console.anthropic.com/settings/keys${J}`);let f=await js("ANTHROPIC_API_KEY",t);if(!f){s&&n.close(),console.log(`
573
- ${qs} No key entered \u2014 cancelled.${J}
574
- `);return}let h=await o("Default model","claude-sonnet-4-6");c.push("DEFAULT_PROVIDER=anthropic",`DEFAULT_MODEL=${h}`,`ANTHROPIC_API_KEY=${f}`),process.env.DEFAULT_PROVIDER="anthropic",process.env.DEFAULT_MODEL=h,process.env.ANTHROPIC_API_KEY=f}else if(i==="3"){console.log(),console.log(` ${Ae}Get your key: https://platform.openai.com/api-keys${J}`);let f=await js("OPENAI_API_KEY",t);if(!f){s&&n.close(),console.log(`
575
- ${qs} No key entered \u2014 cancelled.${J}
576
- `);return}let h=await o("Default model","gpt-4o");c.push("DEFAULT_PROVIDER=openai",`DEFAULT_MODEL=${h}`,`OPENAI_API_KEY=${f}`),process.env.DEFAULT_PROVIDER="openai",process.env.DEFAULT_MODEL=h,process.env.OPENAI_API_KEY=f}else if(i==="4"){console.log(),console.log(` ${Ae}Get your key: https://aistudio.google.com/app/apikey${J}`);let f=await js("GEMINI_API_KEY",t);if(!f){s&&n.close(),console.log(`
577
- ${qs} No key entered \u2014 cancelled.${J}
578
- `);return}let h=await o("Default model","gemini-2.0-flash");c.push("DEFAULT_PROVIDER=gemini",`DEFAULT_MODEL=${h}`,`GEMINI_API_KEY=${f}`),process.env.DEFAULT_PROVIDER="gemini",process.env.DEFAULT_MODEL=h,process.env.GEMINI_API_KEY=f}if(console.log(),(await o("Add Perplexity key for grounded web search? (y/N)","n")).toLowerCase()==="y"){console.log(` ${Ae}Get your key: https://www.perplexity.ai/settings/api${J}`);let f=await js("PERPLEXITY_API_KEY",t);f&&(c.push(`PERPLEXITY_API_KEY=${f}`),process.env.PERPLEXITY_API_KEY=f)}console.log();let u=Is.join(process.cwd(),".env"),d=(it.existsSync(u),"y"),p=await o(`Save to ${u}? (Y/n)`,d);if(s&&n.close(),p.toLowerCase()!=="n"){let f=it.existsSync(u)?it.readFileSync(u,"utf-8").trimEnd()+`
579
-
580
- `:"";it.writeFileSync(u,f+c.join(`
692
+ `),process.exit(0)):c==="\x7F"?r.length>0&&(r=r.slice(0,-1),process.stdout.write("\b \b")):(r+=c,process.stdout.write("*"))};o.on("data",i)})}async function dw({rl:t=null,force:e=!1}={}){if(!e){let m=yt.existsSync(wo.join(process.cwd(),".env"))||yt.existsSync(wo.join(__dirname,"..",".env")),h=process.env.ANTHROPIC_API_KEY||process.env.OPENAI_API_KEY||process.env.GEMINI_API_KEY||process.env.OPENROUTER_API_KEY,p=process.env.DEFAULT_PROVIDER||process.env.DEFAULT_MODEL;if(m||h||p)return}let s=!t,o=t||lw.createInterface({input:process.stdin,output:process.stdout,terminal:!0}),n=uw(o),r=!e;console.log(),console.log(r?`${bo}${hi} \u2726 Welcome to nex-code! No configuration found.${ne}`:`${vn}${hi} \u2726 nex-code \u2014 Provider & API Key Setup${ne}`),console.log(`${Ue} \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500${ne}`),r&&console.log(` Let's set you up in 60 seconds.
693
+ `),console.log(` ${hi}Which AI provider do you want to use?${ne}
694
+ `),console.log(` ${_o}1)${ne} Ollama ${Ue}local/cloud \u2014 no API key needed${ne}`),console.log(` ${vn}2)${ne} Anthropic ${Ue}Claude (claude-sonnet-4-6 etc.)${ne}`),console.log(` ${vn}3)${ne} OpenAI ${Ue}GPT-4o, GPT-4.1 etc.${ne}`),console.log(` ${vn}4)${ne} Gemini ${Ue}Google Gemini 2.x${ne}`),console.log(` ${Ue}5) Skip / Cancel${ne}`),console.log();let i=await n("Enter number","1"),c=[];if(i==="5"){s&&o.close(),console.log(`
695
+ ${Ue} Cancelled \u2014 no changes made.${ne}
696
+ `);return}if(i==="1"){console.log();let m=await n("Ollama host","http://localhost:11434"),h=await n("Default model","qwen3-coder");c.push("DEFAULT_PROVIDER=ollama",`DEFAULT_MODEL=${h}`,`OLLAMA_HOST=${m}`),process.env.DEFAULT_PROVIDER="ollama",process.env.DEFAULT_MODEL=h,process.env.OLLAMA_HOST=m}else if(i==="2"){console.log(),console.log(` ${Ue}Get your key: https://console.anthropic.com/settings/keys${ne}`);let m=await ko("ANTHROPIC_API_KEY",t);if(!m){s&&o.close(),console.log(`
697
+ ${bo} No key entered \u2014 cancelled.${ne}
698
+ `);return}let h=await n("Default model","claude-sonnet-4-6");c.push("DEFAULT_PROVIDER=anthropic",`DEFAULT_MODEL=${h}`,`ANTHROPIC_API_KEY=${m}`),process.env.DEFAULT_PROVIDER="anthropic",process.env.DEFAULT_MODEL=h,process.env.ANTHROPIC_API_KEY=m}else if(i==="3"){console.log(),console.log(` ${Ue}Get your key: https://platform.openai.com/api-keys${ne}`);let m=await ko("OPENAI_API_KEY",t);if(!m){s&&o.close(),console.log(`
699
+ ${bo} No key entered \u2014 cancelled.${ne}
700
+ `);return}let h=await n("Default model","gpt-4o");c.push("DEFAULT_PROVIDER=openai",`DEFAULT_MODEL=${h}`,`OPENAI_API_KEY=${m}`),process.env.DEFAULT_PROVIDER="openai",process.env.DEFAULT_MODEL=h,process.env.OPENAI_API_KEY=m}else if(i==="4"){console.log(),console.log(` ${Ue}Get your key: https://aistudio.google.com/app/apikey${ne}`);let m=await ko("GEMINI_API_KEY",t);if(!m){s&&o.close(),console.log(`
701
+ ${bo} No key entered \u2014 cancelled.${ne}
702
+ `);return}let h=await n("Default model","gemini-2.0-flash");c.push("DEFAULT_PROVIDER=gemini",`DEFAULT_MODEL=${h}`,`GEMINI_API_KEY=${m}`),process.env.DEFAULT_PROVIDER="gemini",process.env.DEFAULT_MODEL=h,process.env.GEMINI_API_KEY=m}if(console.log(),(await n("Add Perplexity key for grounded web search? (y/N)","n")).toLowerCase()==="y"){console.log(` ${Ue}Get your key: https://www.perplexity.ai/settings/api${ne}`);let m=await ko("PERPLEXITY_API_KEY",t);m&&(c.push(`PERPLEXITY_API_KEY=${m}`),process.env.PERPLEXITY_API_KEY=m)}console.log();let u=wo.join(process.cwd(),".env"),d=(yt.existsSync(u),"y"),f=await n(`Save to ${u}? (Y/n)`,d);if(s&&o.close(),f.toLowerCase()!=="n"){let m=yt.existsSync(u)?yt.readFileSync(u,"utf-8").trimEnd()+`
703
+
704
+ `:"";yt.writeFileSync(u,m+c.join(`
581
705
  `)+`
582
- `);let h=Is.join(process.cwd(),".gitignore");it.existsSync(h)&&(it.readFileSync(h,"utf-8").split(`
583
- `).some(g=>g.trim()===".env")||it.appendFileSync(h,`
706
+ `);let h=wo.join(process.cwd(),".gitignore");yt.existsSync(h)&&(yt.readFileSync(h,"utf-8").split(`
707
+ `).some(g=>g.trim()===".env")||yt.appendFileSync(h,`
584
708
  .env
585
709
  `)),console.log(`
586
- ${Ds} \u2713 Saved to ${u}${J}`),c.some(m=>m.includes("API_KEY"))&&console.log(`${Ae} (key stored locally \u2014 never committed)${J}`)}if(process.env.DEFAULT_PROVIDER)try{let{setActiveModel:f}=ge(),h=process.env.DEFAULT_MODEL?`${process.env.DEFAULT_PROVIDER}:${process.env.DEFAULT_MODEL}`:process.env.DEFAULT_PROVIDER;f(h),console.log(`${Ds} \u2713 Switched to ${h} for this session${J}`)}catch{}console.log(`
587
- ${Ds} \u2713 Setup complete!${J}
588
- `)}_l.exports={runSetupWizard:Vg}});var El=L((Wy,Sl)=>{"use strict";var kl=require("fs"),Xg="\x1B[2m",Qg="\x1B[0m",Zg=process.env.FOOTER_DEBUG==="1",Er=null;function gt(...t){Zg&&(Er||(Er=kl.openSync("/tmp/footer-debug.log","w")),kl.writeSync(Er,t.join(" ")+`
589
- `))}function vl(t){return t.replace(/\x1b\[[^a-zA-Z]*[a-zA-Z]/g,"").length}var Tr=class{constructor(){this._active=!1,this._rl=null,this._origWrite=null,this._origPrompt=null,this._origSetPr=null,this._origRefreshLine=null,this._origLog=null,this._origError=null,this._origStderrWrite=null,this._drawing=!1,this._offResize=null,this._cursorOnInputRow=!1,this._inRefreshLine=!1,this._lastOutputRow=1,this._prevTermRows=0,this._prevTermCols=0,this._consistencyTimer=null,this._dirty=!1}get _rows(){return process.stdout.rows||24}get _cols(){return process.stdout.columns||80}get _scrollEnd(){return this._rows-2}get _rowStatus(){return this._rows-1}get _rowInput(){return this._rows}_goto(e,s=1){return`\x1B[${e};${s}H`}_statusLine(){return Xg+"\u2500".repeat(this._cols)+Qg}drawFooter(e){!this._origWrite||this._drawing||(this._drawing=!0,this._origWrite("\x1B7"+this._goto(this._rowStatus)+"\x1B[2K"+this._statusLine(e)+"\x1B8"),this._drawing=!1)}_setScrollRegion(){let e=Math.max(1,this._scrollEnd);this._origWrite(`\x1B[1;${e}r`)}_clearScrollRegion(){this._origWrite&&this._origWrite("\x1B[r")}_eraseStatus(){this._origWrite&&this._origWrite("\x1B7"+this._goto(this._rowStatus)+"\x1B[2K\x1B8")}rawWrite(e){return this._origWrite?this._origWrite(e):process.stdout.write(e)}_relayout(e){if(!this._origWrite)return;let s=this._origWrite,n=this._rows,o=this._cols,r=Math.max(1,n-2);gt("RELAYOUT:",e,"rows="+n,"cols="+o,"scrollEnd="+r,"cursorOnInput="+this._cursorOnInputRow),this._prevTermRows=n,this._prevTermCols=o;let i=Math.min(this._lastOutputRow+1,r+1),c="";for(let l=i;l<=n;l++)c+=this._goto(l)+"\x1B[2K";s(c),this._setScrollRegion(),this._lastOutputRow=Math.min(this._lastOutputRow,r),this.drawFooter(),this._cursorOnInputRow&&this._rl&&this._rl.prompt(!0),this._dirty=!1}activate(e){if(!process.stdout.isTTY)return;this._rl=e,this._origWrite=process.stdout.write.bind(process.stdout),this._active=!0,this._prevTermRows=this._rows,this._prevTermCols=this._cols,this._setScrollRegion(),this._lastOutputRow=1,this.drawFooter();let s=this,n=process.stdout.write.bind(process.stdout);this._origWrite=n,process.stdout.write=function(m,...g){if(!s._active||typeof m!="string")return n(m,...g);if(s._inRefreshLine){let k=m.replace(/\n/g,"");return k?n(k,...g):!0}if(s._cursorOnInputRow)if(m.includes(`
590
- `)&&m.length>4&&!m.includes("\r"))gt("STDOUT: agent output, leaving input row, data="+JSON.stringify(m).slice(0,100)),s._cursorOnInputRow=!1,n(s._goto(Math.min(s._lastOutputRow+1,s._scrollEnd)));else{if(m.length<=4&&!m.includes(`
591
- `)&&!m.includes("\r")&&!/[\x00-\x1f\x7f]/.test(m))return gt("STDOUT: char intercept:",JSON.stringify(m)),s._origRefreshLine&&s._doRefreshLine(),!0;{let k=m.replace(/\n/g,"");return k?n(k,...g):!0}}let y=s._cols||80,$=0,x=m.split(`
592
- `);for(let k=0;k<x.length;k++){let v=vl(x[k]);v>0&&($+=Math.floor((v-1)/y))}let S=x.length-1;return S+$>0&&(s._lastOutputRow=Math.min(s._lastOutputRow+S+$,s._scrollEnd)),n(m,...g)},this._cursorOnInputRow=!1,this._origStderrWrite=process.stderr.write.bind(process.stderr),process.stderr.write=function(m,...g){if(!s._active)return s._origStderrWrite(m,...g);if(typeof m=="string"&&m.includes("\r")){let y=Math.min(s._lastOutputRow+1,s._scrollEnd);if(s._cursorOnInputRow){s._origWrite("\x1B7"),s._origWrite(s._goto(y));let $=s._origStderrWrite(m,...g);return s._origWrite("\x1B8"),$}s._origWrite(s._goto(y))}return s._origStderrWrite(m,...g)},this._origLog=console.log,this._origError=console.error;function o(...m){if(!s._active){s._origLog(...m);return}s._origWrite(s._goto(Math.min(s._lastOutputRow+1,s._scrollEnd))),s._cursorOnInputRow=!1,s._origLog(...m),s.drawFooter(),s._rl&&s._rl.prompt()}function r(...m){if(!s._active){s._origError(...m);return}s._origWrite(s._goto(Math.min(s._lastOutputRow+1,s._scrollEnd))),s._cursorOnInputRow=!1,s._origError(...m),s.drawFooter(),s._rl&&s._rl.prompt()}console.log=o,console.error=r,this._origSetPr=e.setPrompt.bind(e),e.setPrompt=function(m){s._origSetPr(m),s._active&&s.drawFooter(m)},this._origPrompt=e.prompt.bind(e),e.prompt=function(m){if(!s._active)return s._origPrompt(m);gt("PROMPT: goto rowInput="+s._rowInput),e.prevRows=0,n(s._goto(s._rowInput)),s._cursorOnInputRow=!0,s._origPrompt(m)};let i=e.question.bind(e);e.question=function(m,g){if(!s._active)return i(m,g);n(s._goto(s._rowInput)+"\x1B[2K"),e.prevRows=0,s._cursorOnInputRow=!0,i(m,y=>{n(s._goto(s._rowInput)+"\x1B[2K"),s._cursorOnInputRow=!1,s.drawFooter(),g(y)})};let c=Object.getPrototypeOf(e),l=Object.getOwnPropertySymbols(c).find(m=>m.toString()==="Symbol(_refreshLine)"),u=l?c[l].bind(e):e._refreshLine?e._refreshLine.bind(e):null;if(this._origRefreshLine=u,this._doRefreshLine=function(){if(!s._active||!u)return;if(s._rows!==s._prevTermRows||s._cols!==s._prevTermCols){s._dirty=!0;return}e.prevRows=0,n(s._goto(s._rowInput));let m=s._cols,g=e._prompt||"",y=vl(g),$=m-y-1;s._inRefreshLine=!0;try{if(e.line.length<=$){gt("REFRESH: short line, len="+e.line.length),u();return}gt("REFRESH: long line, len="+e.line.length+", max="+$);let x=e.line,S=e.cursor,k=Math.max(1,$-1),v=Math.max(0,S-k),T=(v>0?"\xAB":"")+x.slice(v,v+k+(v>0?0:1));e.line=T,e.cursor=T.length,u(),e.line=x,e.cursor=S}finally{s._inRefreshLine=!1}},u){let m=this._doRefreshLine;l&&Object.defineProperty(e,l,{value:m,writable:!0,configurable:!0}),e._refreshLine=m}e.on("line",()=>{s._active&&(gt("LINE: leaving input row"),s._cursorOnInputRow=!1,n(s._goto(s._rowInput)+"\x1B[2K"),n(s._goto(Math.min(s._lastOutputRow+1,s._scrollEnd))),s.drawFooter())});let d=null,p=null,f=()=>{d=null,s._relayout("resize"),p&&clearTimeout(p),p=setTimeout(()=>{p=null,s._relayout("resize-cleanup")},300)},h=()=>{s._dirty=!0,d&&clearTimeout(d),d=setTimeout(f,80)};process.stdout.on("resize",h),this._offResize=()=>{process.stdout.off("resize",h),d&&(clearTimeout(d),d=null),p&&(clearTimeout(p),p=null)},this._consistencyTimer=setInterval(()=>{if(!s._active)return;let m=s._rows,g=s._cols;(s._dirty||m!==s._prevTermRows||g!==s._prevTermCols)&&(gt("CONSISTENCY: dirty="+s._dirty+" rows="+m+"/"+s._prevTermRows+" cols="+g+"/"+s._prevTermCols),s._relayout("consistency"))},800)}deactivate(){if(this._active){if(this._active=!1,this._offResize&&(this._offResize(),this._offResize=null),this._consistencyTimer&&(clearInterval(this._consistencyTimer),this._consistencyTimer=null),this._origStderrWrite&&(process.stderr.write=this._origStderrWrite,this._origStderrWrite=null),this._origLog&&(console.log=this._origLog,this._origLog=null),this._origError&&(console.error=this._origError,this._origError=null),this._origWrite&&(process.stdout.write=this._origWrite),this._rl&&(this._origPrompt&&(this._rl.prompt=this._origPrompt,this._origPrompt=null),this._origSetPr&&(this._rl.setPrompt=this._origSetPr,this._origSetPr=null),this._origRefreshLine)){let e=Object.getOwnPropertySymbols(Object.getPrototypeOf(this._rl)).find(s=>s.toString()==="Symbol(_refreshLine)");e&&delete this._rl[e],delete this._rl._refreshLine,this._origRefreshLine=null}this._eraseStatus(),this._clearScrollRegion(),this._origWrite=null}}};Sl.exports={StickyFooter:Tr}});var Cl=L((By,Rl)=>{var{C:se}=de(),{listProviders:e$,getActiveProviderName:t$,getActiveModelId:n$,setActiveModel:s$}=ge();function Tl(t,e,s={}){let{title:n="Select",hint:o="\u2191\u2193 navigate \xB7 Enter select \xB7 Esc cancel"}=s;return new Promise(r=>{let i=e.map(($,x)=>$.isHeader?-1:x).filter($=>$>=0);if(i.length===0){r(null);return}let c=e.findIndex($=>$.isCurrent),l=c>=0?i.indexOf(c):0;l<0&&(l=0);let u=process.stdout.rows?Math.max(process.stdout.rows-6,5):20,d=0;function p(){let $=i[l];return $<d?d=$:$>=d+u&&(d=$-u+1),{start:d,end:Math.min(e.length,d+u)}}let f=0;function h(){if(f>0){process.stdout.write(`\x1B[${f}A`);for(let v=0;v<f;v++)process.stdout.write(`\x1B[2K
593
- `);process.stdout.write(`\x1B[${f}A`)}let $=[];$.push(` ${se.bold}${se.cyan}${n}${se.reset}`),$.push(` ${se.dim}${o}${se.reset}`),$.push("");let{start:x,end:S}=p();x>0&&$.push(` ${se.dim}\u2191 more${se.reset}`);for(let v=x;v<S;v++){let T=e[v];if(T.isHeader){$.push(` ${se.bold}${se.dim}${T.label}${se.reset}`);continue}let A=i[l]===v,E=A?`${se.cyan}> `:" ",F=T.isCurrent?` ${se.yellow}<current>${se.reset}`:"";A?$.push(`${E}${se.bold}${T.label}${se.reset}${F}`):$.push(`${E}${se.dim}${T.label}${se.reset}${F}`)}S<e.length&&$.push(` ${se.dim}\u2193 more${se.reset}`);let k=$.join(`
594
- `);process.stdout.write(k+`
595
- `),f=$.length}t.pause();let m=process.stdin.isRaw;process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume();function g(){process.stdin.removeListener("keypress",y),process.stdin.isTTY&&m!==void 0&&process.stdin.setRawMode(m),t.resume()}function y($,x){if(x){if(x.name==="up"||x.ctrl&&x.name==="p"){l>0&&(l--,h());return}if(x.name==="down"||x.ctrl&&x.name==="n"){l<i.length-1&&(l++,h());return}if(x.name==="return"){let S=e[i[l]];g(),r(S?S.value:null);return}if(x.name==="escape"||x.ctrl&&x.name==="c"){g(),r(null);return}}}process.stdin.on("keypress",y),h()})}async function o$(t){let e=e$(),s=t$(),n=n$(),o=[];for(let i of e)if(i.models.length!==0){o.push({label:i.provider,value:null,isHeader:!0});for(let c of i.models){let l=i.provider===s&&c.id===n;o.push({label:` ${c.name} (${i.provider}:${c.id})`,value:`${i.provider}:${c.id}`,isCurrent:l})}}let r=await Tl(t,o,{title:"Select Model"});return r?(s$(r),console.log(`${se.green}Switched to ${r}${se.reset}`),!0):(console.log(`${se.dim}Cancelled${se.reset}`),!1)}Rl.exports={pickFromList:Tl,showModelPicker:o$}});var Ar=L((Gy,Il)=>{var Rr=require("fs"),r$=require("path"),{callChat:Al}=ge(),{remember:i$,listMemories:Hy,recall:a$}=ht(),Cr=4,c$=`You are a memory optimization agent for an AI coding assistant called nex-code.
710
+ ${_o} \u2713 Saved to ${u}${ne}`),c.some(p=>p.includes("API_KEY"))&&console.log(`${Ue} (key stored locally \u2014 never committed)${ne}`)}if(process.env.DEFAULT_PROVIDER)try{let{setActiveModel:m}=we(),h=process.env.DEFAULT_MODEL?`${process.env.DEFAULT_PROVIDER}:${process.env.DEFAULT_MODEL}`:process.env.DEFAULT_PROVIDER;m(h),console.log(`${_o} \u2713 Switched to ${h} for this session${ne}`)}catch{}console.log(`
711
+ ${_o} \u2713 Setup complete!${ne}
712
+ `)}Yu.exports={runSetupWizard:dw}});var Ju=j((mb,Xu)=>{"use strict";var fw=require("readline");function Vt(t){process.stdout.write(JSON.stringify(t)+`
713
+ `)}function pw(){process.env.NEX_SERVER="1";let t=(...c)=>process.stderr.write(c.map(String).join(" ")+`
714
+ `);console.log=t,console.warn=t,console.info=t;let{setConfirmHook:e}=Ae(),s=new Map,o=0;e((c,l)=>{let u="cfm-"+ ++o,d=l?.toolName||"",f=!1;try{let{isCritical:m}=Ae();f=m(c)}catch{}return Vt({type:"confirm_request",id:u,question:c,tool:d,critical:f}),new Promise(m=>{s.set(u,m)})});let n=null,r={onToken(c){n&&Vt({type:"token",id:n,text:c})},onThinkingToken(){},onToolStart(c,l){n&&Vt({type:"tool_start",id:n,tool:c,args:l||{}})},onToolEnd(c,l,u){n&&Vt({type:"tool_end",id:n,tool:c,summary:l||"",ok:!!u})}},i=fw.createInterface({input:process.stdin,output:null,terminal:!1});Vt({type:"ready"}),i.on("line",async c=>{let l=c.trim();if(!l)return;let u;try{u=JSON.parse(l)}catch{return}switch(u.type){case"chat":{let d=u.id||"msg-"+Date.now();n=d;let{processInput:f}=me();try{await f(u.text,r),Vt({type:"done",id:d})}catch(m){Vt({type:"error",id:d,message:m?.message||String(m)})}finally{n=null}break}case"confirm":{let d=s.get(u.id);d&&(s.delete(u.id),d(!!u.answer));break}case"cancel":{for(let[d,f]of s)s.delete(d),f(!1);break}case"clear":{let{clearConversation:d}=me();d();for(let[f,m]of s)s.delete(f),m(!1);break}default:break}}),i.on("close",()=>{process.exit(0)})}Xu.exports={startServerMode:pw}});var ed=j((hb,Zu)=>{"use strict";var xo=require("fs"),{T:Qt,isDark:mw}=Lt(),wt="\x1B[0m",hw=!mw,gw=process.env.FOOTER_DEBUG==="1"||process.env.FOOTER_DEBUG==="2",$w=process.env.FOOTER_DEBUG==="2",Sn=null;function Pt(...t){gw&&(Sn||(Sn=xo.openSync("/tmp/footer-debug.log","w")),xo.writeSync(Sn,t.join(" ")+`
715
+ `))}function Vu(t,e){if(!$w||typeof e!="string")return;Sn||(Sn=xo.openSync("/tmp/footer-debug.log","w"));let s=e.replace(/\x1b\[([^a-zA-Z]*)([a-zA-Z])/g,(o,n,r)=>`<ESC[${n}${r}>`).replace(/\x1b([^[])/g,(o,n)=>`<ESC${n}>`).replace(/\r/g,"<CR>").replace(/\n/g,`<LF>
716
+ `).replace(/[\x00-\x08\x0b-\x1f\x7f]/g,o=>`<${o.charCodeAt(0).toString(16).padStart(2,"0")}>`);xo.writeSync(Sn,`${t}: ${s}
717
+ `)}function Qu(t){return t.replace(/\x1b\[[^a-zA-Z]*[a-zA-Z]/g,"").length}var $i=class{constructor(){this._active=!1,this._rl=null,this._origWrite=null,this._origPrompt=null,this._origSetPr=null,this._origRefreshLine=null,this._origLog=null,this._origError=null,this._origStderrWrite=null,this._drawing=!1,this._offResize=null,this._cursorOnInputRow=!1,this._inRefreshLine=!1,this._lastOutputRow=1,this._prevTermRows=0,this._prevTermCols=0,this._consistencyTimer=null,this._dirty=!1,this._statusModel="",this._statusBranch="",this._statusProject=""}setStatusInfo({model:e="",branch:s="",project:o=""}={}){this._statusModel=e,this._statusBranch=s,this._statusProject=o,this._active&&this.drawFooter()}get _rows(){return process.stdout.rows||24}get _cols(){return process.stdout.columns||80}get _scrollEnd(){return this._rows-2}get _rowStatus(){return this._rows-1}get _rowInput(){return this._rows}_goto(e,s=1){return`\x1B[${e};${s}H`}_statusLine(){let e=this._cols,s=this._statusModel,o=this._statusBranch,n=this._statusProject;if(!s)return Qt.footer_sep+"\u2500".repeat(e)+wt;let r=` ${Qt.footer_divider}\xB7${wt} `,i=[];s&&i.push(`${Qt.footer_model}${s}${wt}`),o&&i.push(`${Qt.footer_branch}${o}${wt}`),n&&i.push(`${Qt.footer_project}${n}${wt}`);let c=i.join(r),l=[s,o,n].filter(Boolean).join(" \xB7 ").length,u="\u2500 ",d=Math.max(0,e-u.length-l-2),f="\u2500".repeat(d);return`${Qt.footer_sep}${u}${wt}${c}${Qt.footer_sep} ${f}${wt}`}drawFooter(e){!this._origWrite||this._drawing||(this._drawing=!0,this._origWrite("\x1B7"+this._goto(this._rowStatus)+"\x1B[2K"+this._statusLine(e)+"\x1B8"),this._drawing=!1)}_setScrollRegion(){if(hw)return;let e=Math.max(1,this._scrollEnd);this._origWrite(`\x1B[1;${e}r`)}_clearScrollRegion(){this._origWrite&&this._origWrite("\x1B[r")}_eraseStatus(){this._origWrite&&this._origWrite("\x1B7"+this._goto(this._rowStatus)+"\x1B[2K\x1B8")}rawWrite(e){return Vu("RAW",e),this._origWrite?this._origWrite(e):process.stdout.write(e)}_relayout(e){if(!this._origWrite)return;let s=this._origWrite,o=this._rows,n=this._cols,r=Math.max(1,o-2);Pt("RELAYOUT:",e,"rows="+o,"cols="+n,"scrollEnd="+r,"cursorOnInput="+this._cursorOnInputRow),this._prevTermRows=o,this._prevTermCols=n;let i=Math.min(this._lastOutputRow+1,r+1),c="";for(let l=i;l<=o;l++)c+=this._goto(l)+"\x1B[2K";s(c),this._setScrollRegion(),this._lastOutputRow=Math.min(this._lastOutputRow,r),this.drawFooter(),this._cursorOnInputRow&&this._rl&&this._rl.prompt(!0),this._dirty=!1}activate(e){if(!process.stdout.isTTY)return;this._rl=e,this._origWrite=process.stdout.write.bind(process.stdout),this._active=!0,this._prevTermRows=this._rows,this._prevTermCols=this._cols,this._origWrite("\x1B[r"),this._setScrollRegion(),this._lastOutputRow=1,this.drawFooter();let s=this,o=process.stdout.write.bind(process.stdout);this._origWrite=o,process.stdout.write=function(p,...g){if(Vu("PATCH",p),!s._active||typeof p!="string")return o(p,...g);if(s._inRefreshLine){let _=p.replace(/\n/g,"");return _?o(_,...g):!0}if(s._cursorOnInputRow)if(p.includes(`
718
+ `)&&p.length>4&&!p.includes("\r"))Pt("STDOUT: agent output, leaving input row, data="+JSON.stringify(p).slice(0,100)),s._cursorOnInputRow=!1,o(s._goto(Math.min(s._lastOutputRow+1,s._scrollEnd)));else{if(p.length<=4&&!p.includes(`
719
+ `)&&!p.includes("\r")&&!/[\x00-\x1f\x7f]/.test(p))return Pt("STDOUT: char intercept:",JSON.stringify(p)),s._origRefreshLine&&s._doRefreshLine(),!0;{let _=p.replace(/\n/g,"");return _?o(_,...g):!0}}let $=s._cols||80,y=0,w=p.split(`
720
+ `);for(let _=0;_<w.length;_++){let x=Qu(w[_]);x>0&&(y+=Math.floor((x-1)/$))}let T=w.length-1;return T+y>0&&(s._lastOutputRow=Math.min(s._lastOutputRow+T+y,s._scrollEnd)),o(p,...g)},this._cursorOnInputRow=!1,this._origStderrWrite=process.stderr.write.bind(process.stderr),process.stderr.write=function(p,...g){if(!s._active)return s._origStderrWrite(p,...g);if(typeof p=="string"&&p.includes("\r")){let $=Math.min(s._lastOutputRow+1,s._scrollEnd);if(s._cursorOnInputRow){s._origWrite("\x1B7"),s._origWrite(s._goto($));let y=s._origStderrWrite(p,...g);return s._origWrite("\x1B8"),y}s._origWrite(s._goto($))}return s._origStderrWrite(p,...g)},this._origLog=console.log,this._origError=console.error;function n(...p){if(!s._active){s._origLog(...p);return}s._origWrite(s._goto(Math.min(s._lastOutputRow+1,s._scrollEnd))),s._cursorOnInputRow=!1,s._origLog(...p),s.drawFooter(),s._rl&&s._rl.prompt()}function r(...p){if(!s._active){s._origError(...p);return}s._origWrite(s._goto(Math.min(s._lastOutputRow+1,s._scrollEnd))),s._cursorOnInputRow=!1,s._origError(...p),s.drawFooter(),s._rl&&s._rl.prompt()}console.log=n,console.error=r,this._origSetPr=e.setPrompt.bind(e),e.setPrompt=function(p){s._origSetPr(p),s._active&&s.drawFooter(p)},this._origPrompt=e.prompt.bind(e),e.prompt=function(p){if(!s._active)return s._origPrompt(p);Pt("PROMPT: goto rowInput="+s._rowInput),e.prevRows=0,o(s._goto(s._rowInput)+wt+"\x1B[2K"),s._cursorOnInputRow=!0,s._origPrompt(p)};let i=e.question.bind(e);e.question=function(p,g){if(!s._active)return i(p,g);o(s._goto(s._rowInput)+"\x1B[2K"),e.prevRows=0,s._cursorOnInputRow=!0,i(p,$=>{o(s._goto(s._rowInput)+"\x1B[2K"),s._cursorOnInputRow=!1,s.drawFooter(),g($)})};let c=Object.getPrototypeOf(e),l=Object.getOwnPropertySymbols(c).find(p=>p.toString()==="Symbol(_refreshLine)"),u=l?c[l].bind(e):e._refreshLine?e._refreshLine.bind(e):null;if(this._origRefreshLine=u,this._doRefreshLine=function(){if(!s._active||!u)return;if(s._rows!==s._prevTermRows||s._cols!==s._prevTermCols){s._dirty=!0;return}e.prevRows=0,o(s._goto(s._rowInput)+wt+"\x1B[2K");let p=s._cols,g=e._prompt||"",$=Qu(g),y=p-$-1;s._inRefreshLine=!0;try{if(e.line.length<=y){Pt("REFRESH: short line, len="+e.line.length),u();return}Pt("REFRESH: long line, len="+e.line.length+", max="+y);let w=e.line,T=e.cursor,_=Math.max(1,y-1),x=Math.max(0,T-_),S=(x>0?"\xAB":"")+w.slice(x,x+_+(x>0?0:1));e.line=S,e.cursor=S.length,u(),e.line=w,e.cursor=T}finally{s._inRefreshLine=!1}},u){let p=this._doRefreshLine;l&&Object.defineProperty(e,l,{value:p,writable:!0,configurable:!0}),e._refreshLine=p}e.on("line",()=>{s._active&&(Pt("LINE: leaving input row"),s._cursorOnInputRow=!1,o(s._goto(s._rowInput)+"\x1B[2K"),o(s._goto(Math.min(s._lastOutputRow+1,s._scrollEnd))),s.drawFooter())});let d=null,f=null,m=()=>{d=null,s._relayout("resize"),f&&clearTimeout(f),f=setTimeout(()=>{f=null,s._relayout("resize-cleanup")},300)},h=()=>{s._dirty=!0,d&&clearTimeout(d),d=setTimeout(m,80)};process.stdout.on("resize",h),this._offResize=()=>{process.stdout.off("resize",h),d&&(clearTimeout(d),d=null),f&&(clearTimeout(f),f=null)},this._consistencyTimer=setInterval(()=>{if(!s._active)return;let p=s._rows,g=s._cols;(s._dirty||p!==s._prevTermRows||g!==s._prevTermCols)&&(Pt("CONSISTENCY: dirty="+s._dirty+" rows="+p+"/"+s._prevTermRows+" cols="+g+"/"+s._prevTermCols),s._relayout("consistency"))},800)}deactivate(){if(this._active){if(this._active=!1,this._offResize&&(this._offResize(),this._offResize=null),this._consistencyTimer&&(clearInterval(this._consistencyTimer),this._consistencyTimer=null),this._origStderrWrite&&(process.stderr.write=this._origStderrWrite,this._origStderrWrite=null),this._origLog&&(console.log=this._origLog,this._origLog=null),this._origError&&(console.error=this._origError,this._origError=null),this._origWrite&&(process.stdout.write=this._origWrite),this._rl&&(this._origPrompt&&(this._rl.prompt=this._origPrompt,this._origPrompt=null),this._origSetPr&&(this._rl.setPrompt=this._origSetPr,this._origSetPr=null),this._origRefreshLine)){let e=Object.getOwnPropertySymbols(Object.getPrototypeOf(this._rl)).find(s=>s.toString()==="Symbol(_refreshLine)");e&&delete this._rl[e],delete this._rl._refreshLine,this._origRefreshLine=null}this._eraseStatus(),this._clearScrollRegion(),this._origWrite=null}}};Zu.exports={StickyFooter:$i}});var sd=j((gb,nd)=>{var{C:fe}=ye(),{listProviders:yw,getActiveProviderName:ww,getActiveModelId:bw,setActiveModel:_w}=we();function td(t,e,s={}){let{title:o="Select",hint:n="\u2191\u2193 navigate \xB7 Enter select \xB7 Esc cancel"}=s;return new Promise(r=>{let i=e.map((y,w)=>y.isHeader?-1:w).filter(y=>y>=0);if(i.length===0){r(null);return}let c=e.findIndex(y=>y.isCurrent),l=c>=0?i.indexOf(c):0;l<0&&(l=0);let u=process.stdout.rows?Math.max(process.stdout.rows-6,5):20,d=0;function f(){let y=i[l];return y<d?d=y:y>=d+u&&(d=y-u+1),{start:d,end:Math.min(e.length,d+u)}}let m=0;function h(){if(m>0){process.stdout.write(`\x1B[${m}A`);for(let x=0;x<m;x++)process.stdout.write(`\x1B[2K
721
+ `);process.stdout.write(`\x1B[${m}A`)}let y=[];y.push(` ${fe.bold}${fe.cyan}${o}${fe.reset}`),y.push(` ${fe.dim}${n}${fe.reset}`),y.push("");let{start:w,end:T}=f();w>0&&y.push(` ${fe.dim}\u2191 more${fe.reset}`);for(let x=w;x<T;x++){let S=e[x];if(S.isHeader){y.push(` ${fe.bold}${fe.dim}${S.label}${fe.reset}`);continue}let R=i[l]===x,C=R?`${fe.cyan}> `:" ",I=S.isCurrent?` ${fe.yellow}<current>${fe.reset}`:"";R?y.push(`${C}${fe.bold}${S.label}${fe.reset}${I}`):y.push(`${C}${fe.dim}${S.label}${fe.reset}${I}`)}T<e.length&&y.push(` ${fe.dim}\u2193 more${fe.reset}`);let _=y.join(`
722
+ `);process.stdout.write(_+`
723
+ `),m=y.length}t.pause();let p=process.stdin.isRaw;process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume();function g(){process.stdin.removeListener("keypress",$),process.stdin.isTTY&&p!==void 0&&process.stdin.setRawMode(p),t.resume()}function $(y,w){if(w){if(w.name==="up"||w.ctrl&&w.name==="p"){l>0&&(l--,h());return}if(w.name==="down"||w.ctrl&&w.name==="n"){l<i.length-1&&(l++,h());return}if(w.name==="return"){let T=e[i[l]];g(),r(T?T.value:null);return}if(w.name==="escape"||w.ctrl&&w.name==="c"){g(),r(null);return}}}process.stdin.on("keypress",$),h()})}async function kw(t){let e=yw(),s=ww(),o=bw(),n=[];for(let i of e)if(i.models.length!==0){n.push({label:i.provider,value:null,isHeader:!0});for(let c of i.models){let l=i.provider===s&&c.id===o;n.push({label:` ${c.name} (${i.provider}:${c.id})`,value:`${i.provider}:${c.id}`,isCurrent:l})}}let r=await td(t,n,{title:"Select Model"});return r?(_w(r),console.log(`${fe.green}Switched to ${r}${fe.reset}`),!0):(console.log(`${fe.dim}Cancelled${fe.reset}`),!1)}nd.exports={pickFromList:td,showModelPicker:kw}});var wi=j((yb,dd)=>{var od=require("fs"),xw=require("path"),{atomicWrite:vw,withFileLockSync:Sw}=vt(),{callChat:rd}=we(),{remember:Ew,listMemories:$b,recall:Tw}=Ot(),yi=4,Rw=`You are a memory optimization agent for an AI coding assistant called nex-code.
596
724
  Analyze this conversation history and extract actionable learnings the assistant should remember.
597
725
 
598
726
  Return ONLY valid JSON in this exact format:
@@ -618,15 +746,15 @@ Rules:
618
746
  - value: concise actionable instruction, max 120 chars
619
747
  - nex_additions: project-level instructions/conventions only (not personal preferences)
620
748
  - If nothing significant to learn, return {"memories": [], "nex_additions": [], "summary": "..."}
621
- - Return ONLY the JSON, no markdown, no explanation`;function Ol(t){return t.filter(e=>(e.role==="user"||e.role==="assistant")&&typeof e.content=="string"&&e.content.trim().length>10).slice(-40).map(e=>`[${e.role.toUpperCase()}]: ${e.content.substring(0,700)}`).join(`
749
+ - Return ONLY the JSON, no markdown, no explanation`;function id(t){return t.filter(e=>(e.role==="user"||e.role==="assistant")&&typeof e.content=="string"&&e.content.trim().length>10).slice(-40).map(e=>`[${e.role.toUpperCase()}]: ${e.content.substring(0,700)}`).join(`
622
750
 
623
- `)}async function Nl(t){if(t.filter(o=>o.role==="user").length<Cr)return{memories:[],nex_additions:[],summary:null,skipped:!0};let s=Ol(t);if(!s.trim())return{memories:[],nex_additions:[],summary:null,skipped:!0};let n=[{role:"system",content:c$},{role:"user",content:`Conversation to analyze:
751
+ `)}async function ad(t){if(t.filter(n=>n.role==="user").length<yi)return{memories:[],nex_additions:[],summary:null,skipped:!0};let s=id(t);if(!s.trim())return{memories:[],nex_additions:[],summary:null,skipped:!0};let o=[{role:"system",content:Rw},{role:"user",content:`Conversation to analyze:
624
752
 
625
- ${s}`}];try{let i=((await Al(n,[],{temperature:0,maxTokens:800})).content||"").trim().match(/\{[\s\S]*\}/);if(!i)return{memories:[],nex_additions:[],summary:null,error:"No JSON in response"};let c=JSON.parse(i[0]);return{memories:Array.isArray(c.memories)?c.memories:[],nex_additions:Array.isArray(c.nex_additions)?c.nex_additions:[],summary:typeof c.summary=="string"?c.summary:null}}catch(o){return{memories:[],nex_additions:[],summary:null,error:o.message}}}function Ml(t){let e=[];for(let{key:s,value:n}of t||[]){if(!s||!n||typeof s!="string"||typeof n!="string")continue;let o=s.trim().replace(/\s+/g,"-").substring(0,60),r=n.trim().substring(0,200);if(!o||!r)continue;let i=a$(o);i!==r&&(i$(o,r),e.push({key:o,value:r,action:i?"updated":"added"}))}return e}function Pl(t){if(!t||t.length===0)return[];let e=r$.join(process.cwd(),"NEX.md"),s="";try{Rr.existsSync(e)&&(s=Rr.readFileSync(e,"utf-8"))}catch{}let n=[],o=s;for(let r of t){if(!r||typeof r!="string")continue;let i=r.trim();if(!i)continue;let c=i.substring(0,35).toLowerCase();s.toLowerCase().includes(c)||(n.push(i),o=o?o.endsWith(`
626
- `)?o+i:o+`
627
- `+i:i)}return n.length>0&&(o.endsWith(`
628
- `)||(o+=`
629
- `),Rr.writeFileSync(e,o,"utf-8")),n}async function l$(t){let e=await Nl(t);if(e.skipped)return{applied:[],nexAdded:[],summary:null,skipped:!0};if(e.error)return{applied:[],nexAdded:[],summary:null,error:e.error};let s=Ml(e.memories),n=Pl(e.nex_additions);return{applied:s,nexAdded:n,summary:e.summary}}var u$=`You are a knowledge base agent for an AI coding assistant called nex-code.
753
+ ${s}`}];try{let i=((await rd(o,[],{temperature:0,maxTokens:800})).content||"").trim().match(/\{[\s\S]*\}/);if(!i)return{memories:[],nex_additions:[],summary:null,error:"No JSON in response"};let c=JSON.parse(i[0]);return{memories:Array.isArray(c.memories)?c.memories:[],nex_additions:Array.isArray(c.nex_additions)?c.nex_additions:[],summary:typeof c.summary=="string"?c.summary:null}}catch(n){return{memories:[],nex_additions:[],summary:null,error:n.message}}}function cd(t){let e=[];for(let{key:s,value:o}of t||[]){if(!s||!o||typeof s!="string"||typeof o!="string")continue;let n=s.trim().replace(/\s+/g,"-").substring(0,60),r=o.trim().substring(0,200);if(!n||!r)continue;let i=Tw(n);i!==r&&(Ew(n,r),e.push({key:n,value:r,action:i?"updated":"added"}))}return e}function ld(t){if(!t||t.length===0)return[];let e=xw.join(process.cwd(),"NEX.md");return Sw(e,()=>{let s="";try{od.existsSync(e)&&(s=od.readFileSync(e,"utf-8"))}catch{}let o=[],n=s;for(let r of t){if(!r||typeof r!="string")continue;let i=r.trim();if(!i)continue;let c=i.substring(0,35).toLowerCase();s.toLowerCase().includes(c)||(o.push(i),n=n?n.endsWith(`
754
+ `)?n+i:n+`
755
+ `+i:i)}return o.length>0&&(n.endsWith(`
756
+ `)||(n+=`
757
+ `),vw(e,n)),o})}async function Cw(t){let e=await ad(t);if(e.skipped)return{applied:[],nexAdded:[],summary:null,skipped:!0};if(e.error)return{applied:[],nexAdded:[],summary:null,error:e.error};let s=cd(e.memories),o=ld(e.nex_additions);return{applied:s,nexAdded:o,summary:e.summary}}var Aw=`You are a knowledge base agent for an AI coding assistant called nex-code.
630
758
  Analyze this conversation and extract knowledge worth persisting in the project knowledge base (.nex/brain/).
631
759
 
632
760
  Return ONLY valid JSON in this exact format:
@@ -660,37 +788,37 @@ Rules:
660
788
  ---
661
789
  - Maximum 3 documents per session. Quality over quantity.
662
790
  - If nothing worth persisting: return {"documents": [], "skip_reason": "..."}
663
- - Return ONLY the JSON, no markdown fences, no explanation`;async function Ll(t){if(t.filter(o=>o.role==="user").length<Cr)return{documents:[],skip_reason:"Session too short"};let s=Ol(t);if(!s.trim())return{documents:[],skip_reason:"No usable content"};let n=[{role:"system",content:u$},{role:"user",content:`Conversation to analyze:
791
+ - Return ONLY the JSON, no markdown fences, no explanation`;async function ud(t){if(t.filter(n=>n.role==="user").length<yi)return{documents:[],skip_reason:"Session too short"};let s=id(t);if(!s.trim())return{documents:[],skip_reason:"No usable content"};let o=[{role:"system",content:Aw},{role:"user",content:`Conversation to analyze:
664
792
 
665
- ${s}`}];try{let i=((await Al(n,[],{temperature:0,maxTokens:2e3})).content||"").trim().match(/\{[\s\S]*\}/);if(!i)return{documents:[],error:"No JSON in response"};let c=JSON.parse(i[0]);return{documents:Array.isArray(c.documents)?c.documents:[],skip_reason:c.skip_reason}}catch(o){return{documents:[],error:o.message}}}async function d$(t){let e=await Ll(t);if(e.error)return{written:[],skipped:[],error:e.error};if(!e.documents||e.documents.length===0)return{written:[],skipped:[],skip_reason:e.skip_reason};let{writeDocument:s,readDocument:n}=_n(),o=[],r=[];for(let i of e.documents){if(!i.name||!i.content)continue;let c=i.name.trim().replace(/\.md$/,"").replace(/[^a-z0-9-]/g,"-").substring(0,60);if(!c)continue;let l=n(c);if(l.content){let d=`
793
+ ${s}`}];try{let i=((await rd(o,[],{temperature:0,maxTokens:2e3})).content||"").trim().match(/\{[\s\S]*\}/);if(!i)return{documents:[],error:"No JSON in response"};let c=JSON.parse(i[0]);return{documents:Array.isArray(c.documents)?c.documents:[],skip_reason:c.skip_reason}}catch(n){return{documents:[],error:n.message}}}async function Ow(t){let e=await ud(t);if(e.error)return{written:[],skipped:[],error:e.error};if(!e.documents||e.documents.length===0)return{written:[],skipped:[],skip_reason:e.skip_reason};let{writeDocument:s,readDocument:o}=Xn(),n=[],r=[];for(let i of e.documents){if(!i.name||!i.content)continue;let c=i.name.trim().replace(/\.md$/,"").replace(/[^a-z0-9-]/g,"-").substring(0,60);if(!c)continue;let l=o(c);if(l.content){let d=`
666
794
 
667
795
  ## Update ${new Date().toISOString().split("T")[0]}
668
796
 
669
- ${i.content}`;s(c,l.content+d),o.push({name:c,reason:i.reason||"",action:"updated"})}else s(c,i.content),o.push({name:c,reason:i.reason||"",action:"created"})}return{written:o,skipped:r}}Il.exports={learnFromSession:l$,learnBrainFromSession:d$,reflectOnSession:Nl,reflectBrain:Ll,applyMemories:Ml,applyNexAdditions:Pl,LEARN_MIN_MESSAGES:Cr}});var Ul=L((Ky,Fl)=>{var ke=require("fs"),en=require("path"),zy=require("os"),f$=require("readline"),{C:O}=de(),ql=".nex",Or=null;function p$(t){Or=t}function Oe(t,e=""){let s=e?` ${O.dim}[${e}]${O.reset}`:"",n=` ${O.cyan}${t}${s}${O.reset}: `;return new Promise(o=>{let r=i=>{let c=i.trim()||e;o(c)};if(Or)Or.question(n,r);else{let i=f$.createInterface({input:process.stdin,output:process.stdout});i.question(n,c=>{i.close(),r(c)})}})}function Zt(t,e=!0){return Oe(`${t} (${e?"Y/n":"y/N"})`,e?"y":"n").then(n=>n.toLowerCase()!=="n"&&n.toLowerCase()!=="no")}async function Dl(t,e,s){let n=e.map((c,l)=>`${O.dim}${l+1})${O.reset} ${c}`).join(" ");console.log(` ${O.cyan}${t}${O.reset}`),console.log(` ${n}`);let o=s?e.indexOf(s)+1:1,r=await Oe("Enter number",String(o)),i=parseInt(r,10)-1;return e[Math.max(0,Math.min(i,e.length-1))]}async function m$(){let t=en.join(process.cwd(),ql),e=en.join(t,"servers.json"),s={};if(ke.existsSync(e))try{s=JSON.parse(ke.readFileSync(e,"utf-8"))}catch{}console.log(`
670
- ${O.bold}${O.cyan}\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557${O.reset}`),console.log(`${O.bold}${O.cyan}\u2551 nex-code Server Setup Wizard \u2551${O.reset}`),console.log(`${O.bold}${O.cyan}\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D${O.reset}
671
- `);let n=Object.keys(s);if(n.length>0&&(console.log(`${O.dim}Existing profiles: ${n.join(", ")}${O.reset}`),!await Zt("Add or update a server profile?",!0))){console.log(`${O.dim}No changes made.${O.reset}
672
- `);return}let o={...s},r=!0;for(;r;){console.log(`
673
- ${O.bold}\u2500\u2500\u2500 New Server Profile \u2500\u2500\u2500${O.reset}`);let l=await Oe("Profile name (e.g. prod, staging, macbook)");if(!l){console.log(`${O.red} Name is required.${O.reset}`);continue}let u=await Oe("Host / IP address");if(!u){console.log(`${O.red} Host is required.${O.reset}`);continue}let d=await Oe("SSH user","root"),p=await Oe("SSH port","22"),f=parseInt(p,10)||22,h=await Oe("SSH key path (leave empty for SSH agent)",""),m=await Dl("Operating system",["almalinux9","macos","ubuntu","debian","other"],"almalinux9"),g=await Zt("Allow sudo commands?",!0),y={host:u,user:d};f!==22&&(y.port=f),h&&(y.key=h),m!=="other"&&(y.os=m),g&&(y.sudo=!0),o[l]=y,console.log(`
674
- ${O.green}\u2713${O.reset} Profile "${l}" added: ${d}@${u}${f!==22?`:${f}`:""}${m!=="other"?` [${m}]`:""}`),r=await Zt(`
675
- Add another server?`,!1)}ke.existsSync(t)||ke.mkdirSync(t,{recursive:!0}),ke.writeFileSync(e,JSON.stringify(o,null,2)+`
797
+ ${i.content}`;s(c,l.content+d),n.push({name:c,reason:i.reason||"",action:"updated"})}else s(c,i.content),n.push({name:c,reason:i.reason||"",action:"created"})}return{written:n,skipped:r}}dd.exports={learnFromSession:Cw,learnBrainFromSession:Ow,reflectOnSession:ad,reflectBrain:ud,applyMemories:cd,applyNexAdditions:ld,LEARN_MIN_MESSAGES:yi}});var hd=j((bb,md)=>{var Te=require("fs"),Tn=require("path"),wb=require("os"),Nw=require("readline"),{C:M}=ye(),fd=".nex",bi=null;function Pw(t){bi=t}function Re(t,e=""){let s=e?` ${M.dim}[${e}]${M.reset}`:"",o=` ${M.cyan}${t}${s}${M.reset}: `;return new Promise(n=>{let r=i=>{let c=i.trim()||e;n(c)};if(bi)bi.question(o,r);else{let i=Nw.createInterface({input:process.stdin,output:process.stdout});i.question(o,c=>{i.close(),r(c)})}})}function En(t,e=!0){return Re(`${t} (${e?"Y/n":"y/N"})`,e?"y":"n").then(o=>o.toLowerCase()!=="n"&&o.toLowerCase()!=="no")}async function _i(t,e,s){let o=e.map((c,l)=>`${M.dim}${l+1})${M.reset} ${c}`).join(" ");console.log(` ${M.cyan}${t}${M.reset}`),console.log(` ${o}`);let n=s?e.indexOf(s)+1:1,r=await Re("Enter number",String(n)),i=parseInt(r,10)-1;return e[Math.max(0,Math.min(i,e.length-1))]}async function Mw(){let t=Tn.join(process.cwd(),fd),e=Tn.join(t,"servers.json"),s={};if(Te.existsSync(e))try{s=JSON.parse(Te.readFileSync(e,"utf-8"))}catch{}console.log(`
798
+ ${M.bold}${M.cyan}\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557${M.reset}`),console.log(`${M.bold}${M.cyan}\u2551 nex-code Server Setup Wizard \u2551${M.reset}`),console.log(`${M.bold}${M.cyan}\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D${M.reset}
799
+ `);let o=Object.keys(s);if(o.length>0&&(console.log(`${M.dim}Existing profiles: ${o.join(", ")}${M.reset}`),!await En("Add or update a server profile?",!0))){console.log(`${M.dim}No changes made.${M.reset}
800
+ `);return}let n={...s},r=!0;for(;r;){console.log(`
801
+ ${M.bold}\u2500\u2500\u2500 New Server Profile \u2500\u2500\u2500${M.reset}`);let l=await Re("Profile name (e.g. prod, staging, macbook)");if(!l){console.log(`${M.red} Name is required.${M.reset}`);continue}let u=await Re("Host / IP address");if(!u){console.log(`${M.red} Host is required.${M.reset}`);continue}let d=await Re("SSH user","root"),f=await Re("SSH port","22"),m=parseInt(f,10)||22,h=await Re("SSH key path (leave empty for SSH agent)",""),p=await _i("Operating system",["almalinux9","macos","ubuntu","debian","other"],"almalinux9"),g=await En("Allow sudo commands?",!0),$={host:u,user:d};m!==22&&($.port=m),h&&($.key=h),p!=="other"&&($.os=p),g&&($.sudo=!0),n[l]=$,console.log(`
802
+ ${M.green}\u2713${M.reset} Profile "${l}" added: ${d}@${u}${m!==22?`:${m}`:""}${p!=="other"?` [${p}]`:""}`),r=await En(`
803
+ Add another server?`,!1)}Te.existsSync(t)||Te.mkdirSync(t,{recursive:!0}),Te.writeFileSync(e,JSON.stringify(n,null,2)+`
676
804
  `,"utf-8"),console.log(`
677
- ${O.green}\u2713 Saved .nex/servers.json (${Object.keys(o).length} profile${Object.keys(o).length!==1?"s":""})${O.reset}`);let i=en.join(process.cwd(),".gitignore");ke.existsSync(i)&&(ke.readFileSync(i,"utf-8").includes(".nex/")||await Zt("Add .nex/ to .gitignore?",!0)&&(ke.appendFileSync(i,`
805
+ ${M.green}\u2713 Saved .nex/servers.json (${Object.keys(n).length} profile${Object.keys(n).length!==1?"s":""})${M.reset}`);let i=Tn.join(process.cwd(),".gitignore");Te.existsSync(i)&&(Te.readFileSync(i,"utf-8").includes(".nex/")||await En("Add .nex/ to .gitignore?",!0)&&(Te.appendFileSync(i,`
678
806
  # nex-code server profiles
679
807
  .nex/
680
- `),console.log(`${O.green}\u2713 Added .nex/ to .gitignore${O.reset}`))),await Zt(`
681
- Set up deploy configs (.nex/deploy.json)?`,!1)&&await jl(o,t),console.log(`
682
- ${O.dim}Use /servers to list profiles, /servers ping to check connectivity.${O.reset}
683
- `)}async function jl(t,e){let s=e||en.join(process.cwd(),ql),n=en.join(s,"deploy.json"),o={};if(ke.existsSync(n))try{o=JSON.parse(ke.readFileSync(n,"utf-8"))}catch{}if(!t){let u=en.join(s,"servers.json");if(ke.existsSync(u))try{t=JSON.parse(ke.readFileSync(u,"utf-8"))}catch{t={}}else t={}}let r=Object.keys(t);console.log(`
684
- ${O.bold}${O.cyan}\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557${O.reset}`),console.log(`${O.bold}${O.cyan}\u2551 Deploy Config Wizard \u2551${O.reset}`),console.log(`${O.bold}${O.cyan}\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D${O.reset}
685
- `);let i=Object.keys(o);i.length>0&&console.log(`${O.dim}Existing deploy configs: ${i.join(", ")}${O.reset}`);let c={...o},l=!0;for(;l;){console.log(`
686
- ${O.bold}\u2500\u2500\u2500 New Deploy Config \u2500\u2500\u2500${O.reset}`);let u=await Oe("Config name (e.g. prod, staging)");if(!u){console.log(`${O.red} Name is required.${O.reset}`);continue}let d;r.length>0?d=await Dl("Target server",r,r[0]):d=await Oe("Target server (profile name or user@host)");let p=await Oe("Local path to sync (e.g. dist/ or ./build)","dist/"),f=await Oe("Remote destination path (e.g. /var/www/app)");if(!f){console.log(`${O.red} Remote path is required.${O.reset}`);continue}let h=await Oe("Deploy script to run after sync (leave empty to skip)",""),m=await Oe("Exclude paths (comma-separated, e.g. node_modules,.env)","node_modules,.env"),g=m?m.split(",").map(x=>x.trim()).filter(Boolean):[],y={server:d,local_path:p,remote_path:f};h&&(y.deploy_script=h),g.length>0&&(y.exclude=g),c[u]=y;let $=p.endsWith("/")?p:`${p}/`;console.log(`
687
- ${O.green}\u2713${O.reset} Deploy config "${u}": ${$} \u2192 ${d}:${f}`),h&&console.log(` ${O.dim} Then: ${h}${O.reset}`),l=await Zt(`
688
- Add another deploy config?`,!1)}ke.existsSync(s)||ke.mkdirSync(s,{recursive:!0}),ke.writeFileSync(n,JSON.stringify(c,null,2)+`
808
+ `),console.log(`${M.green}\u2713 Added .nex/ to .gitignore${M.reset}`))),await En(`
809
+ Set up deploy configs (.nex/deploy.json)?`,!1)&&await pd(n,t),console.log(`
810
+ ${M.dim}Use /servers to list profiles, /servers ping to check connectivity.${M.reset}
811
+ `)}async function pd(t,e){let s=e||Tn.join(process.cwd(),fd),o=Tn.join(s,"deploy.json"),n={};if(Te.existsSync(o))try{n=JSON.parse(Te.readFileSync(o,"utf-8"))}catch{}if(!t){let u=Tn.join(s,"servers.json");if(Te.existsSync(u))try{t=JSON.parse(Te.readFileSync(u,"utf-8"))}catch{t={}}else t={}}let r=Object.keys(t);console.log(`
812
+ ${M.bold}${M.cyan}\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557${M.reset}`),console.log(`${M.bold}${M.cyan}\u2551 Deploy Config Wizard \u2551${M.reset}`),console.log(`${M.bold}${M.cyan}\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D${M.reset}
813
+ `);let i=Object.keys(n);i.length>0&&console.log(`${M.dim}Existing deploy configs: ${i.join(", ")}${M.reset}`);let c={...n},l=!0;for(;l;){console.log(`
814
+ ${M.bold}\u2500\u2500\u2500 New Deploy Config \u2500\u2500\u2500${M.reset}`);let u=await Re("Config name (e.g. prod, staging)");if(!u){console.log(`${M.red} Name is required.${M.reset}`);continue}let d;r.length>0?d=await _i("Target server",r,r[0]):d=await Re("Target server (profile name or user@host)");let f=await _i("Deploy method",["rsync","git"],"rsync"),m="",h=[],p="";if(f==="rsync"){m=await Re("Local path to sync (e.g. dist/ or ./build)","dist/");let _=await Re("Exclude paths (comma-separated, e.g. node_modules,.env)","node_modules,.env");h=_?_.split(",").map(x=>x.trim()).filter(Boolean):[]}else p=await Re("Branch to pull (leave empty for current remote branch)","main");let g=await Re(f==="git"?"Remote repo path (e.g. /home/jarvis/my-app)":"Remote destination path (e.g. /var/www/app)");if(!g){console.log(`${M.red} Remote path is required.${M.reset}`);continue}let $=await Re("Command to run on remote after deploy (leave empty to skip)",""),y=await Re("Health check URL or remote command (leave empty to skip)",""),w={server:d,method:f,remote_path:g};f==="rsync"?(w.local_path=m,h.length>0&&(w.exclude=h)):p&&(w.branch=p),$&&(w.deploy_script=$),y&&(w.health_check=y),c[u]=w;let T=f==="git"?`${d}:${g}${p?` (${p})`:""}`:`${m.endsWith("/")?m:m+"/"} \u2192 ${d}:${g}`;console.log(`
815
+ ${M.green}\u2713${M.reset} Deploy config "${u}": [${f}] ${T}`),$&&console.log(` ${M.dim} Then: ${$}${M.reset}`),y&&console.log(` ${M.dim} Health: ${y}${M.reset}`),l=await En(`
816
+ Add another deploy config?`,!1)}Te.existsSync(s)||Te.mkdirSync(s,{recursive:!0}),Te.writeFileSync(o,JSON.stringify(c,null,2)+`
689
817
  `,"utf-8"),console.log(`
690
- ${O.green}\u2713 Saved .nex/deploy.json (${Object.keys(c).length} config${Object.keys(c).length!==1?"s":""})${O.reset}`),console.log(`${O.dim}Use: deploy prod (or with explicit params)${O.reset}
691
- `)}Fl.exports={runServerWizard:m$,runDeployWizard:jl,setWizardRL:p$}});var Hl=L((Yy,Bl)=>{var h$=require("axios"),Nn=require("fs"),Wl=require("path"),g$="nex-code",Nr=Wl.join(process.cwd(),".nex"),Mr=Wl.join(Nr,"last-version-check");Nn.existsSync(Nr)||Nn.mkdirSync(Nr,{recursive:!0});async function $$(){try{let t=w$(),e=Date.now();if(t&&e-t<1440*60*1e3)return{hasNewVersion:!1};b$(e);let s=y$(),o=(await h$.get(`https://registry.npmjs.org/${g$}/latest`,{timeout:5e3})).data.version,r=x$(o,s);return{hasNewVersion:r,latestVersion:r?o:void 0,currentVersion:r?s:void 0}}catch{return{hasNewVersion:!1}}}function y$(){return In().version}function w$(){try{if(Nn.existsSync(Mr)){let t=Nn.readFileSync(Mr,"utf8");return parseInt(t,10)}}catch{}return null}function b$(t){try{Nn.writeFileSync(Mr,t.toString())}catch{}}function x$(t,e){try{let s=t.split(".").map(Number),n=e.split(".").map(Number);return s[0]>n[0]?!0:s[0]<n[0]?!1:s[1]>n[1]?!0:s[1]<n[1]?!1:s[2]>n[2]}catch{return!1}}Bl.exports={checkForNewVersion:$$}});var ru=L((Vy,ou)=>{var _$=require("readline"),wt=require("fs"),Ve=require("path"),{C:a,banner:k$,cleanupTerminal:Gl}=de(),{listProviders:Lr,getActiveProviderName:$t,listAllModels:Jy,setFallbackChain:v$,getFallbackChain:S$,getProvider:E$}=ge(),{flushAutoSave:zl}=Ct(),{getActiveModel:yt,setActiveModel:Kl}=Jn(),{printContext:Yl}=xs(),{loadAllSkills:T$,getSkillCommands:Ir,handleSkillCommand:R$}=un(),{setReadlineInterface:C$,setAutoConfirm:A$,getAutoConfirm:Jl}=We(),{StickyFooter:O$}=El(),ct=process.cwd(),at=null;function Vl(){return at?.signal??null}var Us=[{cmd:"/help",desc:"Show full help"},{cmd:"/model",desc:"Show/switch model"},{cmd:"/providers",desc:"List providers and models"},{cmd:"/fallback",desc:"Show/set fallback chain"},{cmd:"/tokens",desc:"Token usage and context budget"},{cmd:"/costs",desc:"Session token costs"},{cmd:"/budget",desc:"Show/set cost limits per provider"},{cmd:"/clear",desc:"Clear conversation"},{cmd:"/context",desc:"Show project context"},{cmd:"/tree [depth]",desc:"Show project file tree (default depth 3)"},{cmd:"/autoconfirm",desc:"Toggle auto-confirm"},{cmd:"/save",desc:"Save session"},{cmd:"/load",desc:"Load a saved session"},{cmd:"/sessions",desc:"List saved sessions"},{cmd:"/resume",desc:"Resume last session"},{cmd:"/remember",desc:"Save a memory"},{cmd:"/forget",desc:"Delete a memory"},{cmd:"/memory",desc:"Show all memories"},{cmd:"/brain",desc:"Manage knowledge base"},{cmd:"/brain add",desc:"Add document: /brain add <name> [content]"},{cmd:"/brain list",desc:"List all brain documents"},{cmd:"/brain search",desc:"Search brain: /brain search <query>"},{cmd:"/brain show",desc:"Show document: /brain show <name>"},{cmd:"/brain remove",desc:"Remove document: /brain remove <name>"},{cmd:"/brain rebuild",desc:"Rebuild keyword index"},{cmd:"/brain embed",desc:"Build/rebuild embedding index"},{cmd:"/brain status",desc:"Show brain status (docs, index, embeddings)"},{cmd:"/brain review",desc:"Review pending brain changes (git diff)"},{cmd:"/brain undo",desc:"Undo last brain write"},{cmd:"/learn",desc:"Reflect on session and update memory"},{cmd:"/optimize",desc:"Show optimization opportunities"},{cmd:"/permissions",desc:"Show tool permissions"},{cmd:"/allow",desc:"Auto-allow a tool"},{cmd:"/deny",desc:"Block a tool"},{cmd:"/plan",desc:"Plan mode (analyze before executing)"},{cmd:"/plan edit",desc:"Open current plan in $EDITOR"},{cmd:"/plans",desc:"List saved plans"},{cmd:"/auto",desc:"Set autonomy level"},{cmd:"/commit",desc:"Smart commit (diff + message)"},{cmd:"/diff",desc:"Show current diff"},{cmd:"/review [--strict] [file]",desc:"Deep code review with score table and diff suggestions (--strict: force \u22653 critical findings)"},{cmd:"/branch",desc:"Create feature branch"},{cmd:"/mcp",desc:"MCP servers and tools"},{cmd:"/hooks",desc:"Show configured hooks"},{cmd:"/skills",desc:"List, enable, disable skills"},{cmd:"/tasks",desc:"Show task list"},{cmd:"/servers",desc:"List server profiles / ping"},{cmd:"/docker",desc:"List containers across all servers"},{cmd:"/deploy",desc:"List deploy configs / run named deploy"},{cmd:"/init",desc:"Interactive setup wizard (.nex/)"},{cmd:"/setup",desc:"Configure provider and API keys"},{cmd:"/undo",desc:"Undo last file change"},{cmd:"/redo",desc:"Redo last undone change"},{cmd:"/history",desc:"Show file change history"},{cmd:"/snapshot [name]",desc:"Create a named git snapshot of current changes"},{cmd:"/restore [name|last]",desc:"Restore a previously created snapshot"},{cmd:"/k8s",desc:"Kubernetes overview: namespaces and pods"},{cmd:"/exit",desc:"Quit"}];function Xl(){let t=Ir(),e=[...Us,...t],s=Math.max(...e.map(n=>n.cmd.length));console.log("");for(let{cmd:n,desc:o}of Us)console.log(` ${a.cyan}${n.padEnd(s+2)}${a.reset}${a.dim}${o}${a.reset}`);for(let{cmd:n,desc:o}of t)console.log(` ${a.cyan}${n.padEnd(s+2)}${a.reset}${a.dim}${o} ${a.yellow}[skill]${a.reset}`);console.log(`
818
+ ${M.green}\u2713 Saved .nex/deploy.json (${Object.keys(c).length} config${Object.keys(c).length!==1?"s":""})${M.reset}`),console.log(`${M.dim}Use: deploy prod (or with explicit params)${M.reset}
819
+ `)}md.exports={runServerWizard:Mw,runDeployWizard:pd,setWizardRL:Pw}});var yd=j((_b,$d)=>{var Iw=require("axios"),ls=require("fs"),gd=require("path"),Lw="nex-code",ki=gd.join(process.cwd(),".nex"),xi=gd.join(ki,"last-version-check");ls.existsSync(ki)||ls.mkdirSync(ki,{recursive:!0});async function jw(){try{let t=qw(),e=Date.now();if(t&&e-t<1440*60*1e3)return{hasNewVersion:!1};Fw(e);let s=Dw(),n=(await Iw.get(`https://registry.npmjs.org/${Lw}/latest`,{timeout:5e3})).data.version,r=Uw(n,s);return{hasNewVersion:r,latestVersion:r?n:void 0,currentVersion:r?s:void 0}}catch{return{hasNewVersion:!1}}}function Dw(){return fs().version}function qw(){try{if(ls.existsSync(xi)){let t=ls.readFileSync(xi,"utf8");return parseInt(t,10)}}catch{}return null}function Fw(t){try{ls.writeFileSync(xi,t.toString())}catch{}}function Uw(t,e){try{let s=t.split(".").map(Number),o=e.split(".").map(Number);return s[0]>o[0]?!0:s[0]<o[0]?!1:s[1]>o[1]?!0:s[1]<o[1]?!1:s[2]>o[2]}catch{return!1}}$d.exports={checkForNewVersion:jw}});var Pd=j((xb,Nd)=>{var Ww=require("readline"),Ze=require("fs"),Be=require("path"),{C:a,banner:Bw,cleanupTerminal:wd}=ye(),{isDark:Hw}=Lt(),{listProviders:Si,getActiveProviderName:Zt,listAllModels:kb,setFallbackChain:Gw,getFallbackChain:Kw,getProvider:zw}=we(),{flushAutoSave:bd}=Ct(),{getActiveModel:en,setActiveModel:_d}=Ss(),{printContext:kd}=no(),{loadAllSkills:Yw,getSkillCommands:Ei,handleSkillCommand:Xw}=Et(),{setReadlineInterface:Jw,setAutoConfirm:Vw,getAutoConfirm:xd}=Ae(),{StickyFooter:Qw}=ed(),lt=process.cwd(),bt=null;function vd(){return bt?.signal??null}var So=[{cmd:"/help",desc:"Show full help"},{cmd:"/model",desc:"Show/switch model"},{cmd:"/providers",desc:"List providers and models"},{cmd:"/fallback",desc:"Show/set fallback chain"},{cmd:"/tokens",desc:"Token usage and context budget"},{cmd:"/costs",desc:"Session token costs"},{cmd:"/budget",desc:"Show/set cost limits per provider"},{cmd:"/clear",desc:"Clear conversation"},{cmd:"/context",desc:"Show project context"},{cmd:"/tree [depth]",desc:"Show project file tree (default depth 3)"},{cmd:"/autoconfirm",desc:"Toggle auto-confirm"},{cmd:"/save",desc:"Save session"},{cmd:"/load",desc:"Load a saved session"},{cmd:"/sessions",desc:"List saved sessions"},{cmd:"/resume",desc:"Resume last session"},{cmd:"/remember",desc:"Save a memory"},{cmd:"/forget",desc:"Delete a memory"},{cmd:"/memory",desc:"Show all memories"},{cmd:"/brain",desc:"Manage knowledge base"},{cmd:"/brain add",desc:"Add document: /brain add <name> [content]"},{cmd:"/brain list",desc:"List all brain documents"},{cmd:"/brain search",desc:"Search brain: /brain search <query>"},{cmd:"/brain show",desc:"Show document: /brain show <name>"},{cmd:"/brain remove",desc:"Remove document: /brain remove <name>"},{cmd:"/brain rebuild",desc:"Rebuild keyword index"},{cmd:"/brain embed",desc:"Build/rebuild embedding index"},{cmd:"/brain status",desc:"Show brain status (docs, index, embeddings)"},{cmd:"/brain review",desc:"Review pending brain changes (git diff)"},{cmd:"/brain undo",desc:"Undo last brain write"},{cmd:"/learn",desc:"Reflect on session and update memory"},{cmd:"/optimize",desc:"Show optimization opportunities"},{cmd:"/permissions",desc:"Show tool permissions"},{cmd:"/allow",desc:"Auto-allow a tool"},{cmd:"/deny",desc:"Block a tool"},{cmd:"/plan",desc:"Plan mode (analyze before executing)"},{cmd:"/plan edit",desc:"Open current plan in $EDITOR"},{cmd:"/plans",desc:"List saved plans"},{cmd:"/auto",desc:"Set autonomy level"},{cmd:"/commit",desc:"Smart commit (diff + message)"},{cmd:"/diff",desc:"Show current diff"},{cmd:"/review [--strict] [file]",desc:"Deep code review with score table and diff suggestions (--strict: force \u22653 critical findings)"},{cmd:"/branch",desc:"Create feature branch"},{cmd:"/mcp",desc:"MCP servers and tools"},{cmd:"/hooks",desc:"Show configured hooks"},{cmd:"/skills",desc:"List, enable, disable skills"},{cmd:"/install-skill <url>",desc:"Install a skill from git URL or user/repo"},{cmd:"/search-skill <query>",desc:"Search for skills on GitHub"},{cmd:"/remove-skill <name>",desc:"Remove an installed skill"},{cmd:"/tasks",desc:"Show task list"},{cmd:"/servers",desc:"List server profiles / ping"},{cmd:"/docker",desc:"List containers across all servers"},{cmd:"/deploy",desc:"List deploy configs / run named deploy"},{cmd:"/benchmark",desc:"Show model benchmark results (7-day trend)"},{cmd:"/init",desc:"Interactive setup wizard (.nex/)"},{cmd:"/setup",desc:"Configure provider and API keys"},{cmd:"/undo",desc:"Undo last file change"},{cmd:"/redo",desc:"Redo last undone change"},{cmd:"/history",desc:"Show file change history"},{cmd:"/snapshot [name]",desc:"Create a named git snapshot of current changes"},{cmd:"/restore [name|last]",desc:"Restore a previously created snapshot"},{cmd:"/audit",desc:"Show tool execution audit log"},{cmd:"/k8s",desc:"Kubernetes overview: namespaces and pods"},{cmd:"/exit",desc:"Quit"}];function Sd(){let t=Ei(),e=[...So,...t],s=Math.max(...e.map(o=>o.cmd.length));console.log("");for(let{cmd:o,desc:n}of So)console.log(` ${a.cyan}${o.padEnd(s+2)}${a.reset}${a.dim}${n}${a.reset}`);for(let{cmd:o,desc:n}of t)console.log(` ${a.cyan}${o.padEnd(s+2)}${a.reset}${a.dim}${n} ${a.yellow}[skill]${a.reset}`);console.log(`
692
820
  ${a.dim}Type /help for detailed usage${a.reset}
693
- `)}function Ql(t){try{let e,s;t.endsWith("/")||t.endsWith(Ve.sep)?(e=t,s=""):(e=Ve.dirname(t),s=Ve.basename(t)),e.startsWith("~")&&(e=Ve.join(require("os").homedir(),e.slice(1)));let n=Ve.isAbsolute(e)?e:Ve.resolve(ct,e);if(!wt.existsSync(n)||!wt.statSync(n).isDirectory())return[];let o=wt.readdirSync(n,{withFileTypes:!0}),r=[];for(let i of o){if(i.name.startsWith(".")||i.name==="node_modules"||s&&!i.name.startsWith(s))continue;let c=t.endsWith("/")||t.endsWith(Ve.sep)?t:Ve.dirname(t)+"/",l=c==="./"&&!t.startsWith("./")?i.name:c+i.name;r.push(i.isDirectory()?l+"/":l)}return r}catch{return[]}}function Zl(t){if(t.startsWith("/")){let n=[...Us,...Ir()],o=n.map(r=>r.cmd).filter(r=>r.startsWith(t));return[o.length?o:n.map(r=>r.cmd),t]}let e=t.split(/\s+/),s=e[e.length-1]||"";return s&&(s.includes("/")||s.startsWith("./")||s.startsWith("../")||s.startsWith("~"))?[Ql(s),s]:[[],t]}function eu(){console.log(`
821
+ `)}function Ed(t){try{let e,s;t.endsWith("/")||t.endsWith(Be.sep)?(e=t,s=""):(e=Be.dirname(t),s=Be.basename(t)),e.startsWith("~")&&(e=Be.join(require("os").homedir(),e.slice(1)));let o=Be.isAbsolute(e)?e:Be.resolve(lt,e);if(!Ze.existsSync(o)||!Ze.statSync(o).isDirectory())return[];let n=Ze.readdirSync(o,{withFileTypes:!0}),r=[];for(let i of n){if(i.name.startsWith(".")||i.name==="node_modules"||s&&!i.name.startsWith(s))continue;let c=t.endsWith("/")||t.endsWith(Be.sep)?t:Be.dirname(t)+"/",l=c==="./"&&!t.startsWith("./")?i.name:c+i.name;r.push(i.isDirectory()?l+"/":l)}return r}catch{return[]}}function Td(t){if(t.startsWith("/")){let o=[...So,...Ei()],n=o.map(r=>r.cmd).filter(r=>r.startsWith(t));return[n.length?n:o.map(r=>r.cmd),t]}let e=t.split(/\s+/),s=e[e.length-1]||"";return s&&(s.includes("/")||s.startsWith("./")||s.startsWith("../")||s.startsWith("~"))?[Ed(s),s]:[[],t]}function Rd(){console.log(`
694
822
  ${a.bold}${a.cyan}Commands:${a.reset}
695
823
  ${a.cyan}/help${a.reset} ${a.dim}Show this help${a.reset}
696
824
  ${a.cyan}/model [spec]${a.reset} ${a.dim}Show/switch model (e.g. openai:gpt-4o, claude-sonnet)${a.reset}
@@ -751,51 +879,54 @@ ${a.bold}${a.cyan}Undo / Redo:${a.reset}
751
879
  ${a.cyan}/history${a.reset} ${a.dim}Show file change history${a.reset}
752
880
 
753
881
  ${a.cyan}/exit${a.reset} ${a.dim}Quit${a.reset}
754
- `)}function tu(t){let s=Math.round(t/100*30),n=30-s;return` ${t>80?a.red:t>50?a.yellow:a.green}${"\u2588".repeat(s)}${a.dim}${"\u2591".repeat(n)}${a.reset} ${t}%`}function Pr(){let t=Lr(),e=$t(),s=yt();console.log(`
755
- ${a.bold}${a.cyan}Providers:${a.reset}`);for(let n of t){let o=n.provider===e,r=n.configured?`${a.green}\u2713${a.reset}`:`${a.red}\u2717${a.reset}`,i=o?` ${a.cyan}(active)${a.reset}`:"";console.log(` ${r} ${a.bold}${n.provider}${a.reset}${i}`);for(let c of n.models){let l=c.id===s.id&&o?` ${a.yellow}\u25C4${a.reset}`:"";console.log(` ${a.dim}${c.id}${a.reset} \u2014 ${c.name}${l}`)}}console.log()}async function nu(t,e){let[s,...n]=t.split(/\s+/);switch(s){case"/help":return eu(),!0;case"/model":{let o=n.join(" ").trim();if(!o){if(e){let{showModelPicker:r}=Cl();await r(e)}else{let r=yt(),i=$t();console.log(`${a.bold}${a.cyan}Active model:${a.reset} ${a.dim}${i}:${r.id} (${r.name})${a.reset}`),console.log(`${a.gray}Use /model <provider:model> to switch. /providers to see all.${a.reset}`)}return!0}if(o==="list")return Pr(),!0;if(Kl(o)){let r=yt(),i=$t();console.log(`${a.green}Switched to ${i}:${r.id} (${r.name})${a.reset}`)}else console.log(`${a.red}Unknown model: ${o}${a.reset}`),console.log(`${a.gray}Use /providers to see available models${a.reset}`);return!0}case"/providers":return Pr(),!0;case"/fallback":{let o=n.join(" ").trim();if(!o){let i=S$();return i.length===0?(console.log(`${a.dim}No fallback chain configured${a.reset}`),console.log(`${a.dim}Use /fallback anthropic,openai,local to set${a.reset}`)):console.log(`${a.bold}${a.cyan}Fallback chain:${a.reset} ${i.join(" \u2192 ")}`),!0}let r=o.split(",").map(i=>i.trim()).filter(Boolean);return v$(r),console.log(`${a.green}Fallback chain: ${r.join(" \u2192 ")}${a.reset}`),!0}case"/tokens":{let{getConversationMessages:o}=fe(),{getUsage:r}=De(),{TOOL_DEFINITIONS:i}=Be(),c=o(),l=r(c,i),u=yt(),d=$t();console.log(`
756
- ${a.bold}${a.cyan}Token Usage:${a.reset}`),console.log(` ${a.dim}Model:${a.reset} ${d}:${u.id} (${(l.limit/1e3).toFixed(0)}k context)`),console.log(` ${a.dim}Used:${a.reset} ${l.used.toLocaleString()} / ${l.limit.toLocaleString()} (${l.percentage}%)`);let p=tu(l.percentage);return console.log(` ${p}`),console.log(`
757
- ${a.dim}Breakdown:${a.reset}`),console.log(` System prompt: ${l.breakdown.system.toLocaleString()} tokens`),console.log(` Conversation: ${l.breakdown.conversation.toLocaleString()} tokens`),console.log(` Tool results: ${l.breakdown.toolResults.toLocaleString()} tokens`),console.log(` Tool definitions: ${l.breakdown.toolDefinitions.toLocaleString()} tokens`),console.log(` Messages: ${l.messageCount}`),console.log(),!0}case"/costs":{let{formatCosts:o,resetCosts:r}=Ft();return n.join(" ").trim()==="reset"?(r(),console.log(`${a.green}Cost tracking reset${a.reset}`),!0):(console.log(`
758
- ${o()}
759
- `),!0)}case"/budget":{let{getCostLimits:o,getProviderSpend:r,checkBudget:i,removeCostLimit:c,saveCostLimits:l,setCostLimit:u}=Ft(),d=n[0];if(!d){let h=o(),m=Lr();console.log(`
760
- ${a.bold}${a.cyan}Cost Limits:${a.reset}`);let g=!1;for(let y of m){let $=r(y.provider),x=h[y.provider];if(x!==void 0){g=!0;let S=Math.min(100,Math.round($/x*100)),k=10,v=Math.round(S/100*k),T=k-v,E=`${S>=100?a.red:S>=80?a.yellow:a.green}${"\u2588".repeat(v)}${a.dim}${"\u2591".repeat(T)}${a.reset}`;console.log(` ${a.bold}${y.provider}:${a.reset} $${$.toFixed(2)} / $${x.toFixed(2)} (${S}%) ${E}`)}else y.provider==="ollama"||y.provider==="local"?console.log(` ${a.bold}${y.provider}:${a.reset} ${a.dim}free (no limit)${a.reset}`):$>0&&console.log(` ${a.bold}${y.provider}:${a.reset} $${$.toFixed(2)} ${a.dim}(no limit)${a.reset}`)}return g||console.log(` ${a.dim}No limits set. Use /budget <provider> <amount> to set one.${a.reset}`),console.log(),!0}let p=n[1];if(!p){let h=i(d);return h.limit!==null?console.log(`${a.bold}${d}:${a.reset} $${h.spent.toFixed(2)} / $${h.limit.toFixed(2)} ($${h.remaining.toFixed(2)} remaining)`):console.log(`${a.bold}${d}:${a.reset} $${h.spent.toFixed(2)} ${a.dim}(no limit)${a.reset}`),!0}if(p==="off"||p==="remove"||p==="clear")return c(d),l(),console.log(`${a.green}Removed cost limit for ${d}${a.reset}`),!0;let f=parseFloat(p);return isNaN(f)||f<=0?(console.log(`${a.red}Invalid amount: ${p}. Use a positive number or 'off'.${a.reset}`),!0):(u(d,f),l(),console.log(`${a.green}Set ${d} budget limit: $${f.toFixed(2)}${a.reset}`),!0)}case"/clear":{let{clearConversation:o,getConversationMessages:r}=fe(),{clearHistory:i}=ft(),c=r();if(c.filter(u=>u.role==="user").length>=4){process.stdout.write(`${a.dim}Reflecting on session...${a.reset} `);let{learnFromSession:u}=Ar();u(c).then(d=>{if(!d.skipped&&!d.error&&(d.applied.length>0||d.nexAdded.length>0)){let p=d.applied.length+d.nexAdded.length;process.stdout.write(`${a.green}${p} learning(s) saved${a.reset}
882
+ `)}function Cd(t){let s=Math.round(t/100*30),o=30-s;return` ${t>80?a.red:t>50?a.yellow:a.green}${"\u2588".repeat(s)}${a.dim}${"\u2591".repeat(o)}${a.reset} ${t}%`}function vi(){let t=Si(),e=Zt(),s=en();console.log(`
883
+ ${a.bold}${a.cyan}Providers:${a.reset}`);for(let o of t){let n=o.provider===e,r=o.configured?`${a.green}\u2713${a.reset}`:`${a.red}\u2717${a.reset}`,i=n?` ${a.cyan}(active)${a.reset}`:"";console.log(` ${r} ${a.bold}${o.provider}${a.reset}${i}`);for(let c of o.models){let l=c.id===s.id&&n?` ${a.yellow}\u25C4${a.reset}`:"";console.log(` ${a.dim}${c.id}${a.reset} \u2014 ${c.name}${l}`)}}console.log()}async function Ad(t,e){let[s,...o]=t.split(/\s+/);switch(s){case"/help":return Rd(),!0;case"/model":{let n=o.join(" ").trim();if(!n){if(e){let{showModelPicker:r}=sd();await r(e)}else{let r=en(),i=Zt();console.log(`${a.bold}${a.cyan}Active model:${a.reset} ${a.dim}${i}:${r.id} (${r.name})${a.reset}`),console.log(`${a.gray}Use /model <provider:model> to switch. /providers to see all.${a.reset}`)}return!0}if(n==="list")return vi(),!0;if(_d(n)){let r=en(),i=Zt();console.log(`${a.green}Switched to ${i}:${r.id} (${r.name})${a.reset}`)}else console.log(`${a.red}Unknown model: ${n}${a.reset}`),console.log(`${a.gray}Use /providers to see available models${a.reset}`);return!0}case"/providers":return vi(),!0;case"/fallback":{let n=o.join(" ").trim();if(!n){let i=Kw();return i.length===0?(console.log(`${a.dim}No fallback chain configured${a.reset}`),console.log(`${a.dim}Use /fallback anthropic,openai,local to set${a.reset}`)):console.log(`${a.bold}${a.cyan}Fallback chain:${a.reset} ${i.join(" \u2192 ")}`),!0}let r=n.split(",").map(i=>i.trim()).filter(Boolean);return Gw(r),console.log(`${a.green}Fallback chain: ${r.join(" \u2192 ")}${a.reset}`),!0}case"/tokens":{let{getConversationMessages:n}=me(),{getUsage:r}=Xe(),{TOOL_DEFINITIONS:i}=ot(),c=n(),l=r(c,i),u=en(),d=Zt();console.log(`
884
+ ${a.bold}${a.cyan}Token Usage:${a.reset}`),console.log(` ${a.dim}Model:${a.reset} ${d}:${u.id} (${(l.limit/1e3).toFixed(0)}k context)`),console.log(` ${a.dim}Used:${a.reset} ${l.used.toLocaleString()} / ${l.limit.toLocaleString()} (${l.percentage}%)`);let f=Cd(l.percentage);return console.log(` ${f}`),console.log(`
885
+ ${a.dim}Breakdown:${a.reset}`),console.log(` System prompt: ${l.breakdown.system.toLocaleString()} tokens`),console.log(` Conversation: ${l.breakdown.conversation.toLocaleString()} tokens`),console.log(` Tool results: ${l.breakdown.toolResults.toLocaleString()} tokens`),console.log(` Tool definitions: ${l.breakdown.toolDefinitions.toLocaleString()} tokens`),console.log(` Messages: ${l.messageCount}`),console.log(),!0}case"/costs":{let{formatCosts:n,resetCosts:r}=ln();return o.join(" ").trim()==="reset"?(r(),console.log(`${a.green}Cost tracking reset${a.reset}`),!0):(console.log(`
886
+ ${n()}
887
+ `),!0)}case"/budget":{let{getCostLimits:n,getProviderSpend:r,checkBudget:i,removeCostLimit:c,saveCostLimits:l,setCostLimit:u}=ln(),d=o[0];if(!d){let h=n(),p=Si();console.log(`
888
+ ${a.bold}${a.cyan}Cost Limits:${a.reset}`);let g=!1;for(let $ of p){let y=r($.provider),w=h[$.provider];if(w!==void 0){g=!0;let T=Math.min(100,Math.round(y/w*100)),_=10,x=Math.round(T/100*_),S=_-x,C=`${T>=100?a.red:T>=80?a.yellow:a.green}${"\u2588".repeat(x)}${a.dim}${"\u2591".repeat(S)}${a.reset}`;console.log(` ${a.bold}${$.provider}:${a.reset} $${y.toFixed(2)} / $${w.toFixed(2)} (${T}%) ${C}`)}else $.provider==="ollama"||$.provider==="local"?console.log(` ${a.bold}${$.provider}:${a.reset} ${a.dim}free (no limit)${a.reset}`):y>0&&console.log(` ${a.bold}${$.provider}:${a.reset} $${y.toFixed(2)} ${a.dim}(no limit)${a.reset}`)}return g||console.log(` ${a.dim}No limits set. Use /budget <provider> <amount> to set one.${a.reset}`),console.log(),!0}let f=o[1];if(!f){let h=i(d);return h.limit!==null?console.log(`${a.bold}${d}:${a.reset} $${h.spent.toFixed(2)} / $${h.limit.toFixed(2)} ($${h.remaining.toFixed(2)} remaining)`):console.log(`${a.bold}${d}:${a.reset} $${h.spent.toFixed(2)} ${a.dim}(no limit)${a.reset}`),!0}if(f==="off"||f==="remove"||f==="clear")return c(d),l(),console.log(`${a.green}Removed cost limit for ${d}${a.reset}`),!0;let m=parseFloat(f);return isNaN(m)||m<=0?(console.log(`${a.red}Invalid amount: ${f}. Use a positive number or 'off'.${a.reset}`),!0):(u(d,m),l(),console.log(`${a.green}Set ${d} budget limit: $${m.toFixed(2)}${a.reset}`),!0)}case"/clear":{let{clearConversation:n,getConversationMessages:r}=me(),{clearHistory:i}=pt(),c=r();if(c.filter(u=>u.role==="user").length>=4){process.stdout.write(`${a.dim}Reflecting on session...${a.reset} `);let{learnFromSession:u}=wi();u(c).then(d=>{if(!d.skipped&&!d.error&&(d.applied.length>0||d.nexAdded.length>0)){let f=d.applied.length+d.nexAdded.length;process.stdout.write(`${a.green}${f} learning(s) saved${a.reset}
761
889
  `)}else process.stdout.write(`${a.dim}nothing new${a.reset}
762
890
  `)}).catch(()=>process.stdout.write(`
763
- `))}return o(),i(),console.log(`${a.green}Conversation cleared${a.reset}`),!0}case"/context":return await Yl(ct),!0;case"/tree":{let{generateFileTree:o}=xs(),r=parseInt(n.join(" ").trim(),10),i=!isNaN(r)&&r>0?Math.min(r,8):3,c=o(ct,{maxDepth:i,maxFiles:300});return console.log(`
891
+ `))}return n(),i(),console.log(`${a.green}Conversation cleared${a.reset}`),!0}case"/context":return await kd(lt),!0;case"/tree":{let{generateFileTree:n}=no(),r=parseInt(o.join(" ").trim(),10),i=!isNaN(r)&&r>0?Math.min(r,8):3,c=n(lt,{maxDepth:i,maxFiles:300});return console.log(`
764
892
  ${a.bold}${a.cyan}Project tree${a.reset}${a.dim} (depth ${i})${a.reset}
765
893
  `),console.log(`${a.dim}${c}${a.reset}
766
- `),!0}case"/autoconfirm":{let o=!Jl();return A$(o),console.log(`${a.green}Auto-confirm: ${o?"ON":"OFF"}${a.reset}`),o&&console.log(`${a.yellow} \u26A0 File changes will be applied without confirmation${a.reset}`),!0}case"/save":{let{saveSession:o}=Ct(),{getConversationMessages:r}=fe(),i=n.join(" ").trim()||`session-${Date.now()}`,c=r();if(c.length===0)return console.log(`${a.yellow}No conversation to save${a.reset}`),!0;let l=yt(),u=$t();return o(i,c,{model:l.id,provider:u}),console.log(`${a.green}Session saved: ${i} (${c.length} messages)${a.reset}`),!0}case"/load":{let{loadSession:o}=Ct(),{setConversationMessages:r}=fe(),i=n.join(" ").trim();if(!i)return console.log(`${a.red}Usage: /load <name>${a.reset}`),!0;let c=o(i);return c?(r(c.messages),console.log(`${a.green}Loaded session: ${c.name} (${c.messageCount} messages)${a.reset}`),!0):(console.log(`${a.red}Session not found: ${i}${a.reset}`),!0)}case"/sessions":{let{listSessions:o}=Ct(),r=o();if(r.length===0)return console.log(`${a.dim}No saved sessions${a.reset}`),!0;console.log(`
767
- ${a.bold}${a.cyan}Sessions:${a.reset}`);for(let i of r){let c=i.updatedAt?new Date(i.updatedAt).toLocaleString():"?",l=i.name==="_autosave"?` ${a.dim}(auto)${a.reset}`:"";console.log(` ${a.cyan}${i.name}${a.reset}${l} \u2014 ${i.messageCount} msgs, ${c}`)}return console.log(),!0}case"/resume":{let{getLastSession:o}=Ct(),{setConversationMessages:r}=fe(),i=o();return i?(r(i.messages),console.log(`${a.green}Resumed: ${i.name} (${i.messageCount} messages)${a.reset}`),!0):(console.log(`${a.yellow}No session to resume${a.reset}`),!0)}case"/remember":{let{remember:o}=ht(),r=n.join(" ").trim();if(!r)return console.log(`${a.red}Usage: /remember <key>=<value> or /remember <text>${a.reset}`),!0;let i=r.indexOf("="),c,l;return i>0?(c=r.substring(0,i).trim(),l=r.substring(i+1).trim()):(c=r.substring(0,40).replace(/\s+/g,"-"),l=r),o(c,l),console.log(`${a.green}Remembered: ${c}${a.reset}`),!0}case"/forget":{let{forget:o}=ht(),r=n.join(" ").trim();return r?(o(r)?console.log(`${a.green}Forgotten: ${r}${a.reset}`):console.log(`${a.red}Memory not found: ${r}${a.reset}`),!0):(console.log(`${a.red}Usage: /forget <key>${a.reset}`),!0)}case"/memory":{let{listMemories:o}=ht(),r=o();if(r.length===0)return console.log(`${a.dim}No memories saved${a.reset}`),!0;console.log(`
768
- ${a.bold}${a.cyan}Memory:${a.reset}`);for(let i of r)console.log(` ${a.cyan}${i.key}${a.reset} = ${i.value}`);return console.log(),!0}case"/brain":{let{listDocuments:o,readDocument:r,writeDocument:i,removeDocument:c,buildIndex:l,buildEmbeddingIndex:u,isEmbeddingAvailable:d,query:p}=_n(),f=n[0],h=n.slice(1).join(" ").trim();switch(f){case"add":{if(!h)return console.log(`${a.red}Usage: /brain add <name> [content]${a.reset}`),console.log(`${a.dim} /brain add api-notes \u2014 creates empty file${a.reset}`),console.log(`${a.dim} /brain add api-notes This is content \u2014 writes directly${a.reset}`),!0;let m=h.indexOf(" ");if(m<0){i(h,`# ${h}
769
-
770
- `);let g=require("path").join(process.cwd(),".nex","brain",`${h}.md`);console.log(`${a.green}Created .nex/brain/${h}.md${a.reset}`),console.log(`${a.dim}Edit it directly at: ${g}${a.reset}`)}else{let g=h.substring(0,m),y=h.substring(m+1);i(g,y),console.log(`${a.green}Added to brain: ${g}${a.reset}`)}return!0}case"list":{let m=o();if(m.length===0)return console.log(`${a.dim}No brain documents yet. Use /brain add <name> to create one.${a.reset}`),!0;console.log(`
771
- ${a.bold}${a.cyan}Brain Documents:${a.reset}`);let g=Math.max(8,...m.map($=>$.name.length)),y=20;console.log(` ${"Name".padEnd(g+2)}${"Tags".padEnd(y)}${"Size".padStart(7)} Modified`),console.log(` ${"-".repeat(g+2)}${"-".repeat(y)}${"-".repeat(7)} --------`);for(let $ of m){let{frontmatter:x}=r($.name),S=Array.isArray(x.tags)?x.tags.join(", "):"",k=$.size<1024?`${$.size}B`:`${($.size/1024).toFixed(1)}K`,v=$.modified.toLocaleDateString();console.log(` ${a.cyan}${$.name.padEnd(g+2)}${a.reset}${a.dim}${S.substring(0,y-1).padEnd(y)}${k.padStart(7)} ${v}${a.reset}`)}return console.log(),!0}case"search":{if(!h)return console.log(`${a.red}Usage: /brain search <query>${a.reset}`),!0;let m=await p(h,{topK:5});if(m.length===0)return console.log(`${a.dim}No matching brain documents for: ${h}${a.reset}`),!0;console.log(`
772
- ${a.bold}${a.cyan}Brain Search: "${h}"${a.reset}`);for(let g of m){let y=typeof g.score=="number"?g.score.toFixed(2):g.score;console.log(`
773
- ${a.cyan}${g.name}${a.reset} ${a.dim}(score: ${y})${a.reset}`),console.log(` ${a.dim}${g.excerpt||""}${a.reset}`)}return console.log(),!0}case"show":{if(!h)return console.log(`${a.red}Usage: /brain show <name>${a.reset}`),!0;let m=r(h);return m.content?(console.log(`
894
+ `),!0}case"/autoconfirm":{let n=!xd();return Vw(n),console.log(`${a.green}Auto-confirm: ${n?"ON":"OFF"}${a.reset}`),n&&console.log(`${a.yellow} \u26A0 File changes will be applied without confirmation${a.reset}`),!0}case"/save":{let{saveSession:n}=Ct(),{getConversationMessages:r}=me(),i=o.join(" ").trim()||`session-${Date.now()}`,c=r();if(c.length===0)return console.log(`${a.yellow}No conversation to save${a.reset}`),!0;let l=en(),u=Zt();return n(i,c,{model:l.id,provider:u}),console.log(`${a.green}Session saved: ${i} (${c.length} messages)${a.reset}`),!0}case"/load":{let{loadSession:n}=Ct(),{setConversationMessages:r}=me(),i=o.join(" ").trim();if(!i)return console.log(`${a.red}Usage: /load <name>${a.reset}`),!0;let c=n(i);return c?(r(c.messages),console.log(`${a.green}Loaded session: ${c.name} (${c.messageCount} messages)${a.reset}`),!0):(console.log(`${a.red}Session not found: ${i}${a.reset}`),!0)}case"/sessions":{let{listSessions:n}=Ct(),r=n();if(r.length===0)return console.log(`${a.dim}No saved sessions${a.reset}`),!0;console.log(`
895
+ ${a.bold}${a.cyan}Sessions:${a.reset}`);for(let i of r){let c=i.updatedAt?new Date(i.updatedAt).toLocaleString():"?",l=i.name==="_autosave"?` ${a.dim}(auto)${a.reset}`:"";console.log(` ${a.cyan}${i.name}${a.reset}${l} \u2014 ${i.messageCount} msgs, ${c}`)}return console.log(),!0}case"/resume":{let{getLastSession:n}=Ct(),{setConversationMessages:r}=me(),i=n();return i?(r(i.messages),console.log(`${a.green}Resumed: ${i.name} (${i.messageCount} messages)${a.reset}`),!0):(console.log(`${a.yellow}No session to resume${a.reset}`),!0)}case"/remember":{let{remember:n}=Ot(),r=o.join(" ").trim();if(!r)return console.log(`${a.red}Usage: /remember <key>=<value> or /remember <text>${a.reset}`),!0;let i=r.indexOf("="),c,l;return i>0?(c=r.substring(0,i).trim(),l=r.substring(i+1).trim()):(c=r.substring(0,40).replace(/\s+/g,"-"),l=r),n(c,l),console.log(`${a.green}Remembered: ${c}${a.reset}`),!0}case"/forget":{let{forget:n}=Ot(),r=o.join(" ").trim();return r?(n(r)?console.log(`${a.green}Forgotten: ${r}${a.reset}`):console.log(`${a.red}Memory not found: ${r}${a.reset}`),!0):(console.log(`${a.red}Usage: /forget <key>${a.reset}`),!0)}case"/memory":{let{listMemories:n}=Ot(),r=n();if(r.length===0)return console.log(`${a.dim}No memories saved${a.reset}`),!0;console.log(`
896
+ ${a.bold}${a.cyan}Memory:${a.reset}`);for(let i of r)console.log(` ${a.cyan}${i.key}${a.reset} = ${i.value}`);return console.log(),!0}case"/brain":{let{listDocuments:n,readDocument:r,writeDocument:i,removeDocument:c,buildIndex:l,buildEmbeddingIndex:u,isEmbeddingAvailable:d,query:f}=Xn(),m=o[0],h=o.slice(1).join(" ").trim();switch(m){case"add":{if(!h)return console.log(`${a.red}Usage: /brain add <name> [content]${a.reset}`),console.log(`${a.dim} /brain add api-notes \u2014 creates empty file${a.reset}`),console.log(`${a.dim} /brain add api-notes This is content \u2014 writes directly${a.reset}`),!0;let p=h.indexOf(" ");if(p<0){i(h,`# ${h}
897
+
898
+ `);let g=require("path").join(process.cwd(),".nex","brain",`${h}.md`);console.log(`${a.green}Created .nex/brain/${h}.md${a.reset}`),console.log(`${a.dim}Edit it directly at: ${g}${a.reset}`)}else{let g=h.substring(0,p),$=h.substring(p+1);i(g,$),console.log(`${a.green}Added to brain: ${g}${a.reset}`)}return!0}case"list":{let p=n();if(p.length===0)return console.log(`${a.dim}No brain documents yet. Use /brain add <name> to create one.${a.reset}`),!0;console.log(`
899
+ ${a.bold}${a.cyan}Brain Documents:${a.reset}`);let g=Math.max(8,...p.map(y=>y.name.length)),$=20;console.log(` ${"Name".padEnd(g+2)}${"Tags".padEnd($)}${"Size".padStart(7)} Modified`),console.log(` ${"-".repeat(g+2)}${"-".repeat($)}${"-".repeat(7)} --------`);for(let y of p){let{frontmatter:w}=r(y.name),T=Array.isArray(w.tags)?w.tags.join(", "):"",_=y.size<1024?`${y.size}B`:`${(y.size/1024).toFixed(1)}K`,x=y.modified.toLocaleDateString();console.log(` ${a.cyan}${y.name.padEnd(g+2)}${a.reset}${a.dim}${T.substring(0,$-1).padEnd($)}${_.padStart(7)} ${x}${a.reset}`)}return console.log(),!0}case"search":{if(!h)return console.log(`${a.red}Usage: /brain search <query>${a.reset}`),!0;let p=await f(h,{topK:5});if(p.length===0)return console.log(`${a.dim}No matching brain documents for: ${h}${a.reset}`),!0;console.log(`
900
+ ${a.bold}${a.cyan}Brain Search: "${h}"${a.reset}`);for(let g of p){let $=typeof g.score=="number"?g.score.toFixed(2):g.score;console.log(`
901
+ ${a.cyan}${g.name}${a.reset} ${a.dim}(score: ${$})${a.reset}`),console.log(` ${a.dim}${g.excerpt||""}${a.reset}`)}return console.log(),!0}case"show":{if(!h)return console.log(`${a.red}Usage: /brain show <name>${a.reset}`),!0;let p=r(h);return p.content?(console.log(`
774
902
  ${a.bold}${a.cyan}${h}.md${a.reset}
775
- `),console.log(m.content),!0):(console.log(`${a.red}Document not found: ${h}${a.reset}`),!0)}case"remove":{if(!h)return console.log(`${a.red}Usage: /brain remove <name>${a.reset}`),!0;let{confirm:m}=We();if(!await m(`Remove brain document "${h}"?`))return console.log(`${a.dim}Cancelled${a.reset}`),!0;let y=c(h);return console.log(y?`${a.green}Removed: ${h}.md${a.reset}`:`${a.red}Document not found: ${h}${a.reset}`),!0}case"rebuild":{let m=l(),g=Object.keys(m.documents).length;return console.log(`${a.green}Index rebuilt: ${g} document(s)${a.reset}`),!0}case"embed":{if(!await d())return console.log(`${a.yellow}Ollama embedding model not available.${a.reset}`),console.log(`${a.dim}Set NEX_EMBED_MODEL env var (default: nomic-embed-text) and ensure Ollama is running.${a.reset}`),!0;console.log(`${a.dim}Building embedding index...${a.reset}`);try{let g=await u(),y=Object.keys(g.documents||{}).length;console.log(`${a.green}Embedding index built: ${y} document(s)${a.reset}`)}catch(g){console.log(`${a.red}Embedding failed: ${g.message}${a.reset}`)}return!0}case"status":{let m=o(),g=require("fs"),y=require("path"),$=y.join(process.cwd(),".nex","brain",".brain-index.json"),x=y.join(process.cwd(),".nex","brain",".embeddings.json");if(console.log(`
776
- ${a.bold}${a.cyan}Brain Status${a.reset}`),console.log(` Documents: ${m.length}`),console.log(` Index: ${g.existsSync($)?a.green+"present"+a.reset:a.dim+"not built"+a.reset}`),console.log(` Embeddings: ${g.existsSync(x)?a.green+"present"+a.reset:a.dim+"not built (run /brain embed)"+a.reset}`),m.length>0){let S=m.reduce((k,v)=>k+v.size,0);console.log(` Total size: ${S<1024?S+"B":(S/1024).toFixed(1)+"K"}`)}return console.log(),!0}case"review":{let{exec:m}=require("child_process"),{promisify:g}=require("util"),y=g(m);try{let{stdout:$}=await y("git diff .nex/brain/",{cwd:process.cwd()});$.trim()?(console.log(`
903
+ `),console.log(p.content),!0):(console.log(`${a.red}Document not found: ${h}${a.reset}`),!0)}case"remove":{if(!h)return console.log(`${a.red}Usage: /brain remove <name>${a.reset}`),!0;let{confirm:p}=Ae();if(!await p(`Remove brain document "${h}"?`))return console.log(`${a.dim}Cancelled${a.reset}`),!0;let $=c(h);return console.log($?`${a.green}Removed: ${h}.md${a.reset}`:`${a.red}Document not found: ${h}${a.reset}`),!0}case"rebuild":{let p=l(),g=Object.keys(p.documents).length;return console.log(`${a.green}Index rebuilt: ${g} document(s)${a.reset}`),!0}case"embed":{if(!await d())return console.log(`${a.yellow}Ollama embedding model not available.${a.reset}`),console.log(`${a.dim}Set NEX_EMBED_MODEL env var (default: nomic-embed-text) and ensure Ollama is running.${a.reset}`),!0;console.log(`${a.dim}Building embedding index...${a.reset}`);try{let g=await u(),$=Object.keys(g.documents||{}).length;console.log(`${a.green}Embedding index built: ${$} document(s)${a.reset}`)}catch(g){console.log(`${a.red}Embedding failed: ${g.message}${a.reset}`)}return!0}case"status":{let p=n(),g=require("fs"),$=require("path"),y=$.join(process.cwd(),".nex","brain",".brain-index.json"),w=$.join(process.cwd(),".nex","brain",".embeddings.json");if(console.log(`
904
+ ${a.bold}${a.cyan}Brain Status${a.reset}`),console.log(` Documents: ${p.length}`),console.log(` Index: ${g.existsSync(y)?a.green+"present"+a.reset:a.dim+"not built"+a.reset}`),console.log(` Embeddings: ${g.existsSync(w)?a.green+"present"+a.reset:a.dim+"not built (run /brain embed)"+a.reset}`),p.length>0){let T=p.reduce((_,x)=>_+x.size,0);console.log(` Total size: ${T<1024?T+"B":(T/1024).toFixed(1)+"K"}`)}return console.log(),!0}case"review":{let{exec:p}=require("child_process"),{promisify:g}=require("util"),$=g(p);try{let{stdout:y}=await $("git diff .nex/brain/",{cwd:process.cwd()});y.trim()?(console.log(`
777
905
  ${a.bold}${a.cyan}Brain Changes (git diff):${a.reset}
778
- `),console.log($)):console.log(`${a.dim}No pending brain changes (clean git state)${a.reset}`)}catch{console.log(`${a.dim}Not a git repo or no brain dir${a.reset}`)}return!0}case"undo":{let m=require("fs"),y=require("path").join(process.cwd(),".nex","brain");if(!m.existsSync(y))return console.log(`${a.dim}No brain directory found${a.reset}`),!0;let $=o();if($.length===0)return console.log(`${a.dim}No brain documents to undo${a.reset}`),!0;let x=$[0],{exec:S}=require("child_process"),{promisify:k}=require("util"),v=k(S);try{await v(`git checkout -- ".nex/brain/${x.name}.md"`,{cwd:process.cwd()}),l(),console.log(`${a.green}Undone: restored ${x.name}.md from git${a.reset}`)}catch{console.log(`${a.red}Could not undo \u2014 not tracked in git or no prior version${a.reset}`)}return!0}default:{let m=o();if(m.length===0)console.log(`
906
+ `),console.log(y)):console.log(`${a.dim}No pending brain changes (clean git state)${a.reset}`)}catch{console.log(`${a.dim}Not a git repo or no brain dir${a.reset}`)}return!0}case"undo":{let p=require("fs"),$=require("path").join(process.cwd(),".nex","brain");if(!p.existsSync($))return console.log(`${a.dim}No brain directory found${a.reset}`),!0;let y=n();if(y.length===0)return console.log(`${a.dim}No brain documents to undo${a.reset}`),!0;let w=y[0],{exec:T}=require("child_process"),{promisify:_}=require("util"),x=_(T);try{await x(`git checkout -- ".nex/brain/${w.name}.md"`,{cwd:process.cwd()}),l(),console.log(`${a.green}Undone: restored ${w.name}.md from git${a.reset}`)}catch{console.log(`${a.red}Could not undo \u2014 not tracked in git or no prior version${a.reset}`)}return!0}default:{let p=n();if(p.length===0)console.log(`
779
907
  ${a.bold}${a.cyan}Brain Knowledge Base${a.reset}`),console.log(`${a.dim}No documents yet. Create with /brain add <name>${a.reset}`),console.log(`
780
908
  ${a.dim}Commands: add \xB7 list \xB7 search \xB7 show \xB7 remove \xB7 rebuild \xB7 embed \xB7 status \xB7 review \xB7 undo${a.reset}
781
909
  `);else{console.log(`
782
- ${a.bold}${a.cyan}Brain: ${m.length} document(s)${a.reset}`);for(let g of m){let{frontmatter:y}=r(g.name),$=Array.isArray(y.tags)?` [${y.tags.join(", ")}]`:"";console.log(` ${a.cyan}${g.name}${a.reset}${a.dim}${$}${a.reset}`)}console.log(`
910
+ ${a.bold}${a.cyan}Brain: ${p.length} document(s)${a.reset}`);for(let g of p){let{frontmatter:$}=r(g.name),y=Array.isArray($.tags)?` [${$.tags.join(", ")}]`:"";console.log(` ${a.cyan}${g.name}${a.reset}${a.dim}${y}${a.reset}`)}console.log(`
783
911
  ${a.dim}Use /brain search <query> \xB7 /brain show <name> \xB7 /brain add <name>${a.reset}
784
- `)}return!0}}}case"/learn":{let{learnFromSession:o,learnBrainFromSession:r}=Ar(),{getConversationMessages:i}=fe(),c=i(),l=c.filter(u=>u.role==="user").length;if(l<4)return console.log(`${a.yellow}Session too short to learn from (need 4+ user messages, have ${l})${a.reset}`),!0;console.log(`${a.dim}Analyzing session for learnings...${a.reset}`);try{let[u,d]=await Promise.all([o(c),r(c)]);if(u.skipped&&(!d.written||d.written.length===0))return console.log(`${a.dim}Session too short${a.reset}`),!0;u.error&&console.log(`${a.red}Reflection error: ${u.error}${a.reset}`),console.log(""),u.summary&&(console.log(`${a.bold}Session:${a.reset} ${a.dim}${u.summary}${a.reset}`),console.log(""));let p=u.applied&&u.applied.length>0,f=u.nexAdded&&u.nexAdded.length>0,h=d.written&&d.written.length>0;if(!p&&!f&&!h)console.log(`${a.dim}No new learnings extracted from this session${a.reset}`);else{if(p){console.log(`${a.bold}${a.cyan}Memory updates:${a.reset}`);for(let{key:m,value:g,action:y}of u.applied){let $=y==="updated"?`${a.yellow}~${a.reset}`:`${a.green}+${a.reset}`;console.log(` ${$} ${a.bold}${m}${a.reset} = ${g}`)}}if(f){console.log(`${a.bold}${a.cyan}Added to NEX.md:${a.reset}`);for(let m of u.nexAdded)console.log(` ${a.green}+${a.reset} ${m}`)}if(h){console.log(`${a.bold}${a.cyan}Brain documents:${a.reset}`);for(let{name:m,reason:g,action:y}of d.written){let $=y==="updated"?`${a.yellow}~${a.reset}`:`${a.green}+${a.reset}`;console.log(` ${$} ${a.bold}${m}.md${a.reset}${g?a.dim+" \u2014 "+g+a.reset:""}`)}}}console.log("")}catch(u){console.log(`${a.red}Learn failed: ${u.message}${a.reset}`)}return!0}case"/optimize":{let{getConversationMessages:o}=fe(),{getUsage:r}=De(),{TOOL_DEFINITIONS:i}=Be(),{listMemories:c}=ht(),l=o(),u=r(l,i),d=yt(),p=$t(),f=c();console.log(`
912
+ `)}return!0}}}case"/learn":{let{learnFromSession:n,learnBrainFromSession:r}=wi(),{getConversationMessages:i}=me(),c=i(),l=c.filter(u=>u.role==="user").length;if(l<4)return console.log(`${a.yellow}Session too short to learn from (need 4+ user messages, have ${l})${a.reset}`),!0;console.log(`${a.dim}Analyzing session for learnings...${a.reset}`);try{let[u,d]=await Promise.all([n(c),r(c)]);if(u.skipped&&(!d.written||d.written.length===0))return console.log(`${a.dim}Session too short${a.reset}`),!0;u.error&&console.log(`${a.red}Reflection error: ${u.error}${a.reset}`),console.log(""),u.summary&&(console.log(`${a.bold}Session:${a.reset} ${a.dim}${u.summary}${a.reset}`),console.log(""));let f=u.applied&&u.applied.length>0,m=u.nexAdded&&u.nexAdded.length>0,h=d.written&&d.written.length>0;if(!f&&!m&&!h)console.log(`${a.dim}No new learnings extracted from this session${a.reset}`);else{if(f){console.log(`${a.bold}${a.cyan}Memory updates:${a.reset}`);for(let{key:p,value:g,action:$}of u.applied){let y=$==="updated"?`${a.yellow}~${a.reset}`:`${a.green}+${a.reset}`;console.log(` ${y} ${a.bold}${p}${a.reset} = ${g}`)}}if(m){console.log(`${a.bold}${a.cyan}Added to NEX.md:${a.reset}`);for(let p of u.nexAdded)console.log(` ${a.green}+${a.reset} ${p}`)}if(h){console.log(`${a.bold}${a.cyan}Brain documents:${a.reset}`);for(let{name:p,reason:g,action:$}of d.written){let y=$==="updated"?`${a.yellow}~${a.reset}`:`${a.green}+${a.reset}`;console.log(` ${y} ${a.bold}${p}.md${a.reset}${g?a.dim+" \u2014 "+g+a.reset:""}`)}}}console.log("")}catch(u){console.log(`${a.red}Learn failed: ${u.message}${a.reset}`)}return!0}case"/optimize":{let{getConversationMessages:n}=me(),{getUsage:r}=Xe(),{TOOL_DEFINITIONS:i}=ot(),{listMemories:c}=Ot(),l=n(),u=r(l,i),d=en(),f=Zt(),m=c();console.log(`
785
913
  ${a.bold}${a.cyan}Optimization Report${a.reset}
786
914
  `);let h=u.percentage>80?a.red:u.percentage>50?a.yellow:a.green;if(console.log(`${a.bold}Context Window:${a.reset} ${h}${u.percentage}%${a.reset} used (${u.used.toLocaleString()} / ${u.limit.toLocaleString()} tokens)`),u.percentage>75?console.log(` ${a.yellow}\u2192 Tip: Use /clear to free context (auto-learns first)${a.reset}`):u.percentage>50?console.log(` ${a.dim}\u2192 Context is filling up, consider /clear soon${a.reset}`):console.log(` ${a.green}\u2192 Context healthy${a.reset}`),console.log(`
787
- ${a.bold}Memory:${a.reset} ${f.length} entries`),f.length===0)console.log(` ${a.yellow}\u2192 No memories yet. Use /learn after sessions or /remember key=value${a.reset}`);else{let S=[...f].sort((T,A)=>new Date(A.updatedAt)-new Date(T.updatedAt))[0],k=S?Math.round((Date.now()-new Date(S.updatedAt))/6e4):null,v=k!==null?k<60?`${k}m ago`:`${Math.round(k/60)}h ago`:"?";console.log(` ${a.dim}Latest update: ${v}${a.reset}`),f.length>30&&console.log(` ${a.yellow}\u2192 Many memories (${f.length}) \u2014 consider pruning with /forget${a.reset}`)}console.log(`
788
- ${a.bold}Active Model:${a.reset} ${p}:${d.id}`);let m=d.contextWindow||d.maxTokens||0;m>0&&m<32e3&&l.length>10?console.log(` ${a.yellow}\u2192 Small context window (${(m/1e3).toFixed(0)}k). Consider /model for larger context${a.reset}`):m>=128e3&&console.log(` ${a.green}\u2192 Large context window (${(m/1e3).toFixed(0)}k) \u2014 good for long sessions${a.reset}`);let g=l.filter(x=>x.role==="user").length;console.log(`
789
- ${a.bold}Session:${a.reset} ${g} turns, ${l.length} messages total`),g>=4&&g%10===0&&console.log(` ${a.cyan}\u2192 Good time to /learn and capture session insights${a.reset}`);let y=[],$=require("path").join(process.cwd(),"NEX.md");if(require("fs").existsSync($)||y.push("Create NEX.md in project root to give nex-code project-specific instructions"),y.length>0){console.log(`
790
- ${a.bold}Quick Wins:${a.reset}`);for(let x of y)console.log(` ${a.cyan}\u2192${a.reset} ${x}`)}return console.log(""),!0}case"/plan":{let{getActivePlan:o,approvePlan:r,startExecution:i,setPlanMode:c,getPlanContent:l,getPlanContent:u,formatPlan:d,extractStepsFromText:p,createPlan:f}=Mt(),{invalidateSystemPromptCache:h}=fe(),m=n.join(" ").trim();if(m==="status"){let g=o();return console.log(d(g)),!0}if(m==="edit"){let g=l();if(!g)return console.log(`${a.yellow}No plan to edit. Generate a plan first with /plan${a.reset}`),!0;let y=require("os"),$=require("path").join(y.tmpdir(),`nex-plan-${Date.now()}.md`);require("fs").writeFileSync($,g,"utf-8");let x=process.env.EDITOR||process.env.VISUAL||"nano",{spawnSync:S}=require("child_process");if(console.log(`${a.dim}Opening plan in ${x}... (save and close to update)${a.reset}`),S(x,[$],{stdio:"inherit"}).status===0){let{setPlanContent:v}=Mt(),T=require("fs").readFileSync($,"utf-8");v(T);let A=p(T);if(A.length>0){let F=o()?.task||"Task";f(F,A),console.log(`${a.green}Plan updated \u2014 ${A.length} steps extracted.${a.reset}`)}else console.log(`${a.green}Plan updated.${a.reset}`)}else console.log(`${a.yellow}Editor exited with error \u2014 plan unchanged.${a.reset}`);try{require("fs").unlinkSync($)}catch{}return!0}if(m==="approve"){if(r()){i(),c(!1),h();let y=o()?.steps?.length||0,$=!!l(),x=y>0?` (${y} steps)`:"";console.log(`${a.green}${a.bold}Plan approved!${a.reset}${x} ${$?"Executing the planned steps...":"Starting execution..."}`),console.log(`${a.dim}Plan mode disabled \u2014 all tools now available.${a.reset}`)}else console.log(`${a.red}No plan to approve. Enter plan mode first with /plan${a.reset}`);return!0}return c(!0),h(),console.log(`
915
+ ${a.bold}Memory:${a.reset} ${m.length} entries`),m.length===0)console.log(` ${a.yellow}\u2192 No memories yet. Use /learn after sessions or /remember key=value${a.reset}`);else{let T=[...m].sort((S,R)=>new Date(R.updatedAt)-new Date(S.updatedAt))[0],_=T?Math.round((Date.now()-new Date(T.updatedAt))/6e4):null,x=_!==null?_<60?`${_}m ago`:`${Math.round(_/60)}h ago`:"?";console.log(` ${a.dim}Latest update: ${x}${a.reset}`),m.length>30&&console.log(` ${a.yellow}\u2192 Many memories (${m.length}) \u2014 consider pruning with /forget${a.reset}`)}console.log(`
916
+ ${a.bold}Active Model:${a.reset} ${f}:${d.id}`);let p=d.contextWindow||d.maxTokens||0;p>0&&p<32e3&&l.length>10?console.log(` ${a.yellow}\u2192 Small context window (${(p/1e3).toFixed(0)}k). Consider /model for larger context${a.reset}`):p>=128e3&&console.log(` ${a.green}\u2192 Large context window (${(p/1e3).toFixed(0)}k) \u2014 good for long sessions${a.reset}`);let g=l.filter(w=>w.role==="user").length;console.log(`
917
+ ${a.bold}Session:${a.reset} ${g} turns, ${l.length} messages total`),g>=4&&g%10===0&&console.log(` ${a.cyan}\u2192 Good time to /learn and capture session insights${a.reset}`);let $=[],y=require("path").join(process.cwd(),"NEX.md");if(require("fs").existsSync(y)||$.push("Create NEX.md in project root to give nex-code project-specific instructions"),$.length>0){console.log(`
918
+ ${a.bold}Quick Wins:${a.reset}`);for(let w of $)console.log(` ${a.cyan}\u2192${a.reset} ${w}`)}return console.log(""),!0}case"/plan":{let{getActivePlan:n,approvePlan:r,startExecution:i,setPlanMode:c,getPlanContent:l,getPlanContent:u,formatPlan:d,extractStepsFromText:f,createPlan:m}=Nt(),{invalidateSystemPromptCache:h}=me(),p=o.join(" ").trim();if(p==="status"){let g=n();return console.log(d(g)),!0}if(p==="edit"){let g=l();if(!g)return console.log(`${a.yellow}No plan to edit. Generate a plan first with /plan${a.reset}`),!0;let $=require("os"),y=require("path").join($.tmpdir(),`nex-plan-${Date.now()}.md`);require("fs").writeFileSync(y,g,"utf-8");let w=process.env.EDITOR||process.env.VISUAL||"nano",{spawnSync:T}=require("child_process");if(console.log(`${a.dim}Opening plan in ${w}... (save and close to update)${a.reset}`),T(w,[y],{stdio:"inherit"}).status===0){let{setPlanContent:x}=Nt(),S=require("fs").readFileSync(y,"utf-8");x(S);let R=f(S);if(R.length>0){let I=n()?.task||"Task";m(I,R),console.log(`${a.green}Plan updated \u2014 ${R.length} steps extracted.${a.reset}`)}else console.log(`${a.green}Plan updated.${a.reset}`)}else console.log(`${a.yellow}Editor exited with error \u2014 plan unchanged.${a.reset}`);try{require("fs").unlinkSync(y)}catch{}return!0}if(p==="approve"){if(r()){i(),c(!1),h();let $=n()?.steps?.length||0,y=!!l(),w=$>0?` (${$} steps)`:"";console.log(`${a.green}${a.bold}Plan approved!${a.reset}${w} ${y?"Executing the planned steps...":"Starting execution..."}`),console.log(`${a.dim}Plan mode disabled \u2014 all tools now available.${a.reset}`)}else console.log(`${a.red}No plan to approve. Enter plan mode first with /plan${a.reset}`);return!0}return c(!0),h(),console.log(`
791
919
  ${a.cyan}${a.bold}\u250C\u2500 PLAN MODE \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510${a.reset}
792
920
  ${a.cyan}${a.bold}\u2502${a.reset} Analysis only \u2014 no file changes until approved ${a.cyan}${a.bold}\u2502${a.reset}
793
921
  ${a.cyan}${a.bold}\u2502${a.reset} ${a.dim}Read-only tools only \xB7 /plan approve to execute${a.reset} ${a.cyan}${a.bold}\u2502${a.reset}
794
- ${a.cyan}${a.bold}\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518${a.reset}`),m&&console.log(`${a.dim}Task: ${m}${a.reset}`),!0}case"/plans":{let{listPlans:o}=Mt(),r=o();if(r.length===0)return console.log(`${a.dim}No saved plans${a.reset}`),!0;console.log(`
795
- ${a.bold}${a.cyan}Plans:${a.reset}`);for(let i of r){let c=i.status==="completed"?`${a.green}\u2713`:i.status==="executing"?`${a.blue}\u2192`:`${a.dim}\u25CB`;console.log(` ${c} ${a.reset}${a.bold}${i.name}${a.reset} \u2014 ${i.task||"?"} (${i.steps} steps, ${i.status})`)}return console.log(),!0}case"/auto":{let{getAutonomyLevel:o,setAutonomyLevel:r,AUTONOMY_LEVELS:i}=Mt(),c=n.join(" ").trim();return c?(r(c)?console.log(`${a.green}Autonomy: ${c}${a.reset}`):console.log(`${a.red}Unknown level: ${c}. Use: ${i.join(", ")}${a.reset}`),!0):(console.log(`${a.bold}${a.cyan}Autonomy:${a.reset} ${o()}`),console.log(`${a.dim}Levels: ${i.join(", ")}${a.reset}`),!0)}case"/permissions":{let{listPermissions:o}=Tn(),r=o();console.log(`
922
+ ${a.cyan}${a.bold}\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518${a.reset}`),p&&console.log(`${a.dim}Task: ${p}${a.reset}`),!0}case"/plans":{let{listPlans:n}=Nt(),r=n();if(r.length===0)return console.log(`${a.dim}No saved plans${a.reset}`),!0;console.log(`
923
+ ${a.bold}${a.cyan}Plans:${a.reset}`);for(let i of r){let c=i.status==="completed"?`${a.green}\u2713`:i.status==="executing"?`${a.blue}\u2192`:`${a.dim}\u25CB`;console.log(` ${c} ${a.reset}${a.bold}${i.name}${a.reset} \u2014 ${i.task||"?"} (${i.steps} steps, ${i.status})`)}return console.log(),!0}case"/auto":{let{getAutonomyLevel:n,setAutonomyLevel:r,AUTONOMY_LEVELS:i}=Nt(),c=o.join(" ").trim();return c?(r(c)?console.log(`${a.green}Autonomy: ${c}${a.reset}`):console.log(`${a.red}Unknown level: ${c}. Use: ${i.join(", ")}${a.reset}`),!0):(console.log(`${a.bold}${a.cyan}Autonomy:${a.reset} ${n()}`),console.log(`${a.dim}Levels: ${i.join(", ")}${a.reset}`),!0)}case"/permissions":{let{listPermissions:n}=os(),r=n();console.log(`
796
924
  ${a.bold}${a.cyan}Tool Permissions:${a.reset}`);for(let i of r){let c=i.mode==="allow"?`${a.green}\u2713`:i.mode==="deny"?`${a.red}\u2717`:`${a.yellow}?`;console.log(` ${c} ${a.reset}${a.bold}${i.tool}${a.reset} ${a.dim}(${i.mode})${a.reset}`)}return console.log(`
797
925
  ${a.dim}Use /allow <tool> or /deny <tool> to change${a.reset}
798
- `),!0}case"/allow":{let{setPermission:o,savePermissions:r}=Tn(),i=n.join(" ").trim();return i?(o(i,"allow"),r(),console.log(`${a.green}${i}: allow${a.reset}`),!0):(console.log(`${a.red}Usage: /allow <tool>${a.reset}`),!0)}case"/deny":{let{setPermission:o,savePermissions:r}=Tn(),i=n.join(" ").trim();return i?(o(i,"deny"),r(),console.log(`${a.red}${i}: deny${a.reset}`),!0):(console.log(`${a.red}Usage: /deny <tool>${a.reset}`),!0)}case"/commit":{let{isGitRepo:o,commit:r,analyzeDiff:i,formatDiffSummary:c}=St(),{confirm:l}=We();if(!o())return console.log(`${a.red}Not a git repository${a.reset}`),!0;let u=n.join(" ").trim();if(u){let m=await r(u);return console.log(m?`${a.green}Committed: ${m} \u2014 ${u}${a.reset}`:`${a.red}Commit failed${a.reset}`),!0}if(!i())return console.log(`${a.yellow}No changes to commit${a.reset}`),!0;let p=await c();if(console.log(p),!await l(" Commit changes?"))return!0;let h=await r("nex-code update");return h&&console.log(`${a.green} \u2713 Committed: ${h}${a.reset}`),!0}case"/diff":{let{isGitRepo:o,formatDiffSummary:r}=St();return o()?(console.log(r()),!0):(console.log(`${a.red}Not a git repository${a.reset}`),!0)}case"/review":{let{isGitRepo:o,getDiff:r}=St(),{processInput:i}=fe(),c=n.join(" ").trim(),l=c.includes("--strict"),u=c.replace("--strict","").trim(),p=`## Review Protocol
926
+ `),!0}case"/allow":{let{setPermission:n,savePermissions:r}=os(),i=o.join(" ").trim();return i?(n(i,"allow"),r(),console.log(`${a.green}${i}: allow${a.reset}`),!0):(console.log(`${a.red}Usage: /allow <tool>${a.reset}`),!0)}case"/deny":{let{setPermission:n,savePermissions:r}=os(),i=o.join(" ").trim();return i?(n(i,"deny"),r(),console.log(`${a.red}${i}: deny${a.reset}`),!0):(console.log(`${a.red}Usage: /deny <tool>${a.reset}`),!0)}case"/audit":{let{getAuditSummary:n,isAuditEnabled:r}=Mr();if(!r())return console.log(`${a.yellow}Audit logging is disabled (set NEX_AUDIT=true to enable)${a.reset}`),!0;let i=parseInt(o.join(" ").trim())||1,c=n(i);if(console.log(`
927
+ ${a.bold}${a.cyan}Audit Summary (${i} day${i>1?"s":""})${a.reset}
928
+ `),console.log(` Total tool calls: ${a.bold}${c.totalCalls}${a.reset}`),console.log(` Avg duration: ${a.dim}${c.avgDuration}ms${a.reset}`),console.log(` Success rate: ${c.successRate>=.95?a.green:a.yellow}${Math.round(c.successRate*100)}%${a.reset}`),Object.keys(c.byTool).length>0){console.log(`
929
+ ${a.dim}Tool${" ".repeat(25)}Count${a.reset}`),console.log(` ${a.dim}${"\u2500".repeat(35)}${a.reset}`);let l=Object.entries(c.byTool).sort((u,d)=>d[1]-u[1]);for(let[u,d]of l.slice(0,15))console.log(` ${u.padEnd(30)}${d}`)}return console.log(),!0}case"/commit":{let{isGitRepo:n,commit:r,analyzeDiff:i,formatDiffSummary:c}=Ft(),{confirm:l}=Ae();if(!n())return console.log(`${a.red}Not a git repository${a.reset}`),!0;let u=o.join(" ").trim();if(u){let p=await r(u);return console.log(p?`${a.green}Committed: ${p} \u2014 ${u}${a.reset}`:`${a.red}Commit failed${a.reset}`),!0}if(!i())return console.log(`${a.yellow}No changes to commit${a.reset}`),!0;let f=await c();if(console.log(f),!await l(" Commit changes?"))return!0;let h=await r("nex-code update");return h&&console.log(`${a.green} \u2713 Committed: ${h}${a.reset}`),!0}case"/diff":{let{isGitRepo:n,formatDiffSummary:r}=Ft();return n()?(console.log(r()),!0):(console.log(`${a.red}Not a git repository${a.reset}`),!0)}case"/review":{let{isGitRepo:n,getDiff:r}=Ft(),{processInput:i}=me(),c=o.join(" ").trim(),l=c.includes("--strict"),u=c.replace("--strict","").trim(),f=`## Review Protocol
799
930
 
800
931
  **Phase 1 \u2014 Broad Scan:** Read the target code and identify all issues at a high level.
801
932
 
@@ -830,86 +961,96 @@ For each issue, include:
830
961
  + fixed code
831
962
  \`\`\`${l?`
832
963
 
833
- \u26A0 STRICT MODE: You MUST identify at least 3 critical weaknesses. If the code appears clean, dig deeper \u2014 look for subtle error-swallowing, race conditions, missing validation, or architecture risks. Do not give a passing score without identifying at least 3 critical issues.`:""}`,f;if(u)f=`Do a thorough code review of \`${u}\`.
964
+ \u26A0 STRICT MODE: You MUST identify at least 3 critical weaknesses. If the code appears clean, dig deeper \u2014 look for subtle error-swallowing, race conditions, missing validation, or architecture risks. Do not give a passing score without identifying at least 3 critical issues.`:""}`,m;if(u)m=`Do a thorough code review of \`${u}\`.
834
965
 
835
- ${p}`;else{if(!o())return console.log(`${a.red}Not a git repository \u2014 try /review <file>${a.reset}`),!0;let[h,m]=await Promise.all([r(!1),r(!0)]),g=m||h;if(!g||!g.trim())return console.log(`${a.yellow}No changes to review \u2014 commit something or specify a file: /review <file>${a.reset}`),!0;f=`Review the following code diff.
966
+ ${f}`;else{if(!n())return console.log(`${a.red}Not a git repository \u2014 try /review <file>${a.reset}`),!0;let[h,p]=await Promise.all([r(!1),r(!0)]),g=p||h;if(!g||!g.trim())return console.log(`${a.yellow}No changes to review \u2014 commit something or specify a file: /review <file>${a.reset}`),!0;m=`Review the following code diff.
836
967
 
837
- ${p}
968
+ ${f}
838
969
 
839
970
  \`\`\`diff
840
971
  ${g.substring(0,2e4)}
841
- \`\`\``}return await i(f),!0}case"/branch":{let{isGitRepo:o,getCurrentBranch:r,createBranch:i}=St();if(!o())return console.log(`${a.red}Not a git repository${a.reset}`),!0;let c=n.join(" ").trim();if(!c){let u=r();return console.log(`${a.bold}${a.cyan}Branch:${a.reset} ${u||"(detached)"}`),!0}let l=i(c);return console.log(l?`${a.green}Created and switched to: ${l}${a.reset}`:`${a.red}Failed to create branch${a.reset}`),!0}case"/mcp":{let{listServers:o,connectAll:r,disconnectAll:i}=ts(),c=n.join(" ").trim();if(c==="connect")return console.log(`${a.dim}Connecting MCP servers...${a.reset}`),r().then(u=>{for(let d of u)d.error?console.log(` ${a.red}\u2717${a.reset} ${d.name}: ${d.error}`):console.log(` ${a.green}\u2713${a.reset} ${d.name}: ${d.tools} tools`);u.length===0&&console.log(`${a.dim}No MCP servers configured in .nex/config.json${a.reset}`)}).catch(u=>{console.log(`${a.red}MCP connection error: ${u.message}${a.reset}`)}),!0;if(c==="disconnect")return i(),console.log(`${a.green}All MCP servers disconnected${a.reset}`),!0;let l=o();if(l.length===0)return console.log(`${a.dim}No MCP servers configured${a.reset}`),console.log(`${a.dim}Add servers to .nex/config.json under "mcpServers"${a.reset}`),!0;console.log(`
972
+ \`\`\``}return await i(m),!0}case"/branch":{let{isGitRepo:n,getCurrentBranch:r,createBranch:i}=Ft();if(!n())return console.log(`${a.red}Not a git repository${a.reset}`),!0;let c=o.join(" ").trim();if(!c){let u=r();return console.log(`${a.bold}${a.cyan}Branch:${a.reset} ${u||"(detached)"}`),!0}let l=i(c);return console.log(l?`${a.green}Created and switched to: ${l}${a.reset}`:`${a.red}Failed to create branch${a.reset}`),!0}case"/mcp":{let{listServers:n,connectAll:r,disconnectAll:i}=Os(),c=o.join(" ").trim();if(c==="connect")return console.log(`${a.dim}Connecting MCP servers...${a.reset}`),r().then(u=>{for(let d of u)d.error?console.log(` ${a.red}\u2717${a.reset} ${d.name}: ${d.error}`):console.log(` ${a.green}\u2713${a.reset} ${d.name}: ${d.tools} tools`);u.length===0&&console.log(`${a.dim}No MCP servers configured in .nex/config.json${a.reset}`)}).catch(u=>{console.log(`${a.red}MCP connection error: ${u.message}${a.reset}`)}),!0;if(c==="disconnect")return i(),console.log(`${a.green}All MCP servers disconnected${a.reset}`),!0;let l=n();if(l.length===0)return console.log(`${a.dim}No MCP servers configured${a.reset}`),console.log(`${a.dim}Add servers to .nex/config.json under "mcpServers"${a.reset}`),!0;console.log(`
842
973
  ${a.bold}${a.cyan}MCP Servers:${a.reset}`);for(let u of l){let d=u.connected?`${a.green}\u2713 connected${a.reset}`:`${a.dim}\u25CB disconnected${a.reset}`;console.log(` ${d} ${a.bold}${u.name}${a.reset} (${u.command}) \u2014 ${u.toolCount} tools`)}return console.log(`
843
974
  ${a.dim}Use /mcp connect to connect all servers${a.reset}
844
- `),!0}case"/hooks":{let{listHooks:o}=cr(),r=o();if(r.length===0)return console.log(`${a.dim}No hooks configured${a.reset}`),console.log(`${a.dim}Add hooks to .nex/config.json or .nex/hooks/${a.reset}`),!0;console.log(`
845
- ${a.bold}${a.cyan}Hooks:${a.reset}`);for(let i of r){console.log(` ${a.cyan}${i.event}${a.reset}`);for(let c of i.commands)console.log(` ${a.dim}\u2192 ${c}${a.reset}`)}return console.log(),!0}case"/skills":{let{listSkills:o,enableSkill:r,disableSkill:i}=un(),c=n.join(" ").trim();if(c.startsWith("enable ")){let u=c.substring(7).trim();return r(u)?console.log(`${a.green}Skill enabled: ${u}${a.reset}`):console.log(`${a.red}Skill not found: ${u}${a.reset}`),!0}if(c.startsWith("disable ")){let u=c.substring(8).trim();return i(u)?console.log(`${a.yellow}Skill disabled: ${u}${a.reset}`):console.log(`${a.red}Skill not found: ${u}${a.reset}`),!0}let l=o();if(l.length===0)return console.log(`${a.dim}No skills loaded${a.reset}`),console.log(`${a.dim}Add .md or .js files to .nex/skills/${a.reset}`),!0;console.log(`
846
- ${a.bold}${a.cyan}Skills:${a.reset}`);for(let u of l){let d=u.enabled?`${a.green}\u2713${a.reset}`:`${a.red}\u2717${a.reset}`,p=u.type==="prompt"?`${a.dim}(prompt)${a.reset}`:`${a.dim}(script)${a.reset}`,f=[];u.commands>0&&f.push(`${u.commands} cmd`),u.tools>0&&f.push(`${u.tools} tools`);let h=f.length>0?` \u2014 ${f.join(", ")}`:"";console.log(` ${d} ${a.bold}${u.name}${a.reset} ${p}${h}`)}return console.log(`
975
+ `),!0}case"/hooks":{let{listHooks:n}=ei(),r=n();if(r.length===0)return console.log(`${a.dim}No hooks configured${a.reset}`),console.log(`${a.dim}Add hooks to .nex/config.json or .nex/hooks/${a.reset}`),!0;console.log(`
976
+ ${a.bold}${a.cyan}Hooks:${a.reset}`);for(let i of r){console.log(` ${a.cyan}${i.event}${a.reset}`);for(let c of i.commands)console.log(` ${a.dim}\u2192 ${c}${a.reset}`)}return console.log(),!0}case"/skills":{let{listSkills:n,enableSkill:r,disableSkill:i}=Et(),c=o.join(" ").trim();if(c.startsWith("enable ")){let u=c.substring(7).trim();return r(u)?console.log(`${a.green}Skill enabled: ${u}${a.reset}`):console.log(`${a.red}Skill not found: ${u}${a.reset}`),!0}if(c.startsWith("disable ")){let u=c.substring(8).trim();return i(u)?console.log(`${a.yellow}Skill disabled: ${u}${a.reset}`):console.log(`${a.red}Skill not found: ${u}${a.reset}`),!0}let l=n();if(l.length===0)return console.log(`${a.dim}No skills loaded${a.reset}`),console.log(`${a.dim}Add .md or .js files to .nex/skills/${a.reset}`),!0;console.log(`
977
+ ${a.bold}${a.cyan}Skills:${a.reset}`);for(let u of l){let d=u.enabled?`${a.green}\u2713${a.reset}`:`${a.red}\u2717${a.reset}`,f=u.type==="prompt"?`${a.dim}(prompt)${a.reset}`:`${a.dim}(script)${a.reset}`,m=[];u.commands>0&&m.push(`${u.commands} cmd`),u.tools>0&&m.push(`${u.tools} tools`);let h=m.length>0?` \u2014 ${m.join(", ")}`:"";console.log(` ${d} ${a.bold}${u.name}${a.reset} ${f}${h}`)}return console.log(`
847
978
  ${a.dim}Use /skills enable <name> or /skills disable <name>${a.reset}
848
- `),!0}case"/tasks":{let{renderTaskList:o,clearTasks:r}=ds();return n.join(" ").trim()==="clear"?(r(),console.log(`${a.green}Tasks cleared${a.reset}`),!0):(console.log(`
849
- `+o()+`
850
- `),!0)}case"/undo":{let{undo:o,getUndoCount:r}=ft(),i=o();if(!i)return console.log(`${a.yellow}Nothing to undo${a.reset}`),!0;i.wasCreated?console.log(`${a.green}Undone: deleted ${i.filePath} (was created by ${i.tool})${a.reset}`):console.log(`${a.green}Undone: restored ${i.filePath} (${i.tool})${a.reset}`);let c=r();return c>0&&console.log(`${a.dim}${c} more change(s) to undo${a.reset}`),!0}case"/redo":{let{redo:o,getRedoCount:r}=ft(),i=o();if(!i)return console.log(`${a.yellow}Nothing to redo${a.reset}`),!0;console.log(`${a.green}Redone: ${i.filePath} (${i.tool})${a.reset}`);let c=r();return c>0&&console.log(`${a.dim}${c} more change(s) to redo${a.reset}`),!0}case"/history":{let{getHistory:o,getUndoCount:r,getRedoCount:i}=ft(),c=o(20);if(c.length===0)return console.log(`${a.dim}No file changes in this session${a.reset}`),!0;console.log(`
979
+ `),!0}case"/install-skill":{let n=o.join(" ").trim();if(!n)return console.log(`${a.yellow}Usage: /install-skill <git-url-or-user/repo>${a.reset}`),!0;let{installSkill:r}=Et();console.log(`${a.dim}Installing skill from ${n}...${a.reset}`);let i=await r(n);return i.ok?(console.log(`${a.green}Skill "${i.name}" installed successfully${a.reset}`),console.log(`${a.dim}Reload with /skills to see it${a.reset}`)):console.log(`${a.red}Failed: ${i.error}${a.reset}`),!0}case"/search-skill":{let n=o.join(" ").trim();if(!n)return console.log(`${a.yellow}Usage: /search-skill <query>${a.reset}`),!0;let{searchSkills:r}=Et();console.log(`${a.dim}Searching for "${n}"...${a.reset}`);let i=await r(n);if(i.length===0)console.log(`${a.yellow}No skills found matching "${n}"${a.reset}`);else{console.log(`
980
+ ${a.bold}Skills matching "${n}":${a.reset}
981
+ `);for(let c of i)c.name==="error"?console.log(` ${a.red}${c.description}${a.reset}`):(console.log(` ${a.cyan}${c.owner}/${c.name}${a.reset} ${a.dim}\u2605${c.stars}${a.reset}`),console.log(` ${c.description}`),console.log(` ${a.dim}/install-skill ${c.url}${a.reset}
982
+ `))}return!0}case"/remove-skill":{let n=o.join(" ").trim();if(!n)return console.log(`${a.yellow}Usage: /remove-skill <name>${a.reset}`),!0;let{removeSkill:r}=Et(),i=r(n);return i.ok?console.log(`${a.green}Skill "${n}" removed${a.reset}`):console.log(`${a.red}${i.error}${a.reset}`),!0}case"/tasks":{let{renderTaskList:n,clearTasks:r}=Gs();return o.join(" ").trim()==="clear"?(r(),console.log(`${a.green}Tasks cleared${a.reset}`),!0):(console.log(`
983
+ `+n()+`
984
+ `),!0)}case"/undo":{let{undo:n,getUndoCount:r}=pt(),i=n();if(!i)return console.log(`${a.yellow}Nothing to undo${a.reset}`),!0;i.wasCreated?console.log(`${a.green}Undone: deleted ${i.filePath} (was created by ${i.tool})${a.reset}`):console.log(`${a.green}Undone: restored ${i.filePath} (${i.tool})${a.reset}`);let c=r();return c>0&&console.log(`${a.dim}${c} more change(s) to undo${a.reset}`),!0}case"/redo":{let{redo:n,getRedoCount:r}=pt(),i=n();if(!i)return console.log(`${a.yellow}Nothing to redo${a.reset}`),!0;console.log(`${a.green}Redone: ${i.filePath} (${i.tool})${a.reset}`);let c=r();return c>0&&console.log(`${a.dim}${c} more change(s) to redo${a.reset}`),!0}case"/history":{let{getHistory:n,getUndoCount:r,getRedoCount:i}=pt(),c=n(20);if(c.length===0)return console.log(`${a.dim}No file changes in this session${a.reset}`),!0;console.log(`
851
985
  ${a.bold}File Change History${a.reset}
852
986
  `);for(let l of c){let u=new Date(l.timestamp).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});console.log(` ${a.dim}${u}${a.reset} ${a.yellow}${l.tool}${a.reset} ${l.filePath}`)}return console.log(`
853
987
  ${a.dim}${r()} undo / ${i()} redo available${a.reset}
854
- `),!0}case"/snapshot":{let{createSnapshot:o,listSnapshots:r}=ft(),i=n.join(" ").trim()||void 0;if(i==="list"){let l=r(ct);if(l.length===0)console.log(`${a.dim}No snapshots found${a.reset}`);else{console.log(`
855
- ${a.bold}${a.cyan}Snapshots:${a.reset}`);for(let u of l)console.log(` ${a.cyan}#${u.index}${a.reset} ${a.bold}${u.shortName}${a.reset}`);console.log()}return!0}let c=o(i,ct);return c.ok?(console.log(`${a.green}Snapshot created:${a.reset} ${c.label}`),console.log(`${a.dim}Use /restore to apply it later${a.reset}`)):console.log(`${a.yellow}${c.error}${a.reset}`),!0}case"/restore":{let{restoreSnapshot:o,listSnapshots:r}=ft(),i=n.join(" ").trim()||"last";if(i==="list"){let l=r(ct);if(l.length===0)console.log(`${a.dim}No snapshots available${a.reset}`);else{console.log(`
988
+ `),!0}case"/snapshot":{let{createSnapshot:n,listSnapshots:r}=pt(),i=o.join(" ").trim()||void 0;if(i==="list"){let l=r(lt);if(l.length===0)console.log(`${a.dim}No snapshots found${a.reset}`);else{console.log(`
989
+ ${a.bold}${a.cyan}Snapshots:${a.reset}`);for(let u of l)console.log(` ${a.cyan}#${u.index}${a.reset} ${a.bold}${u.shortName}${a.reset}`);console.log()}return!0}let c=n(i,lt);return c.ok?(console.log(`${a.green}Snapshot created:${a.reset} ${c.label}`),console.log(`${a.dim}Use /restore to apply it later${a.reset}`)):console.log(`${a.yellow}${c.error}${a.reset}`),!0}case"/restore":{let{restoreSnapshot:n,listSnapshots:r}=pt(),i=o.join(" ").trim()||"last";if(i==="list"){let l=r(lt);if(l.length===0)console.log(`${a.dim}No snapshots available${a.reset}`);else{console.log(`
856
990
  ${a.bold}${a.cyan}Available snapshots:${a.reset}`);for(let u of l)console.log(` ${a.cyan}#${u.index}${a.reset} ${a.bold}${u.shortName}${a.reset}`);console.log(`
857
991
  ${a.dim}Usage: /restore <name|last>${a.reset}
858
- `)}return!0}let c=o(i,ct);return c.ok?(console.log(`${a.green}Restored snapshot:${a.reset} ${c.label}`),console.log(`${a.dim}Working tree updated. Use /undo for in-session file undos.${a.reset}`)):(console.log(`${a.red}Restore failed:${a.reset} ${c.error}`),console.log(`${a.dim}Use /snapshot list to see available snapshots${a.reset}`)),!0}case"/k8s":{let o=n.join(" ").trim(),{exec:r}=require("child_process"),{promisify:i}=require("util"),c=i(r),l=o||null,u=l?`ssh -o ConnectTimeout=10 -o BatchMode=yes ${l.replace(/[^a-zA-Z0-9@._-]/g,"")} `:"",d=p=>l?`${u}"${p.replace(/"/g,'\\"')}"`:p;console.log(`
992
+ `)}return!0}let c=n(i,lt);return c.ok?(console.log(`${a.green}Restored snapshot:${a.reset} ${c.label}`),console.log(`${a.dim}Working tree updated. Use /undo for in-session file undos.${a.reset}`)):(console.log(`${a.red}Restore failed:${a.reset} ${c.error}`),console.log(`${a.dim}Use /snapshot list to see available snapshots${a.reset}`)),!0}case"/k8s":{let n=o.join(" ").trim(),{exec:r}=require("child_process"),{promisify:i}=require("util"),c=i(r),l=n||null,u=l?`ssh -o ConnectTimeout=10 -o BatchMode=yes ${l.replace(/[^a-zA-Z0-9@._-]/g,"")} `:"",d=f=>l?`${u}"${f.replace(/"/g,'\\"')}"`:f;console.log(`
859
993
  ${a.bold}${a.cyan}Kubernetes Overview${a.reset}${l?a.dim+" (remote: "+l+")"+a.reset:""}
860
- `);try{let{stdout:p}=await c(d("kubectl get namespaces --no-headers -o custom-columns=NAME:.metadata.name"),{timeout:15e3}),f=p.trim().split(`
861
- `).filter(Boolean);console.log(`${a.bold}Namespaces (${f.length}):${a.reset}`);for(let h of f)console.log(` ${a.cyan}${h}${a.reset}`);console.log()}catch{return console.log(`${a.dim}Could not reach cluster \u2014 is kubectl configured?${a.reset}
862
- `),!0}try{let{stdout:p}=await c(d("kubectl get pods -A --no-headers -o custom-columns=NS:.metadata.namespace,NAME:.metadata.name,READY:.status.containerStatuses[0].ready,STATUS:.status.phase,RESTARTS:.status.containerStatuses[0].restartCount"),{timeout:2e4}),f=p.trim().split(`
863
- `).filter(Boolean),h=f.filter($=>$.includes("Running")).length,m=f.filter($=>$.includes("Pending")).length,g=f.filter($=>$.includes("Failed")||$.includes("Error")||$.includes("CrashLoop")).length;console.log(`${a.bold}Pods: ${f.length} total ${a.green}${h} running${a.reset} ${a.yellow}${m} pending${a.reset} ${a.red}${g} unhealthy${a.reset}
864
- `);let y=f.filter($=>!$.includes("Running")&&!$.includes("<none>"));if(y.length>0){console.log(`${a.bold}${a.red}Unhealthy Pods:${a.reset}`);for(let $ of y)console.log(` ${a.red}${$}${a.reset}`);console.log()}console.log(`${a.dim}Use k8s_pods / k8s_logs / k8s_exec tools for details${a.reset}`),console.log(`${a.dim}Or: /k8s user@host to query a remote cluster${a.reset}
865
- `)}catch(p){console.log(`${a.dim}Could not list pods: ${p.message}${a.reset}
866
- `)}return!0}case"/servers":{let{loadServerProfiles:o,resolveProfile:r,sshExec:i}=Ht(),c=o(),l=Object.keys(c);if(l.length===0)return console.log(`
994
+ `);try{let{stdout:f}=await c(d("kubectl get namespaces --no-headers -o custom-columns=NAME:.metadata.name"),{timeout:15e3}),m=f.trim().split(`
995
+ `).filter(Boolean);console.log(`${a.bold}Namespaces (${m.length}):${a.reset}`);for(let h of m)console.log(` ${a.cyan}${h}${a.reset}`);console.log()}catch{return console.log(`${a.dim}Could not reach cluster \u2014 is kubectl configured?${a.reset}
996
+ `),!0}try{let{stdout:f}=await c(d("kubectl get pods -A --no-headers -o custom-columns=NS:.metadata.namespace,NAME:.metadata.name,READY:.status.containerStatuses[0].ready,STATUS:.status.phase,RESTARTS:.status.containerStatuses[0].restartCount"),{timeout:2e4}),m=f.trim().split(`
997
+ `).filter(Boolean),h=m.filter(y=>y.includes("Running")).length,p=m.filter(y=>y.includes("Pending")).length,g=m.filter(y=>y.includes("Failed")||y.includes("Error")||y.includes("CrashLoop")).length;console.log(`${a.bold}Pods: ${m.length} total ${a.green}${h} running${a.reset} ${a.yellow}${p} pending${a.reset} ${a.red}${g} unhealthy${a.reset}
998
+ `);let $=m.filter(y=>!y.includes("Running")&&!y.includes("<none>"));if($.length>0){console.log(`${a.bold}${a.red}Unhealthy Pods:${a.reset}`);for(let y of $)console.log(` ${a.red}${y}${a.reset}`);console.log()}console.log(`${a.dim}Use k8s_pods / k8s_logs / k8s_exec tools for details${a.reset}`),console.log(`${a.dim}Or: /k8s user@host to query a remote cluster${a.reset}
999
+ `)}catch(f){console.log(`${a.dim}Could not list pods: ${f.message}${a.reset}
1000
+ `)}return!0}case"/servers":{let{loadServerProfiles:n,resolveProfile:r,sshExec:i}=mn(),c=n(),l=Object.keys(c);if(l.length===0)return console.log(`
867
1001
  ${a.dim}No servers configured. Create .nex/servers.json:${a.reset}`),console.log(`${a.dim} { "prod": { "host": "1.2.3.4", "user": "jarvis", "os": "almalinux9" } }${a.reset}
868
- `),!0;if(n[0]==="ping"){let p=n[1]?[n[1]]:l;return console.log(`
869
- ${a.bold}${a.cyan}Server connectivity:${a.reset}`),await Promise.all(p.map(async f=>{if(!c[f]){console.log(` ${a.red}\u2717${a.reset} ${f} \u2014 unknown profile`);return}try{let h={...c[f],_name:f},{exitCode:m}=await i(h,"echo ok",{timeout:8e3});console.log(m===0?` ${a.green}\u2713${a.reset} ${f} (${h.user?h.user+"@":""}${h.host})`:` ${a.red}\u2717${a.reset} ${f} (${h.host}) \u2014 SSH failed (exit ${m})`)}catch(h){console.log(` ${a.red}\u2717${a.reset} ${f} \u2014 ${h.message}`)}})),console.log(""),!0}let{formatProfile:d}=Ht();console.log(`
870
- ${a.bold}${a.cyan}Configured servers (${l.length}):${a.reset}`);for(let p of l)console.log(` ${a.green}${p}${a.reset} ${a.dim}${d(p,c[p])}${a.reset}`);return console.log(`
1002
+ `),!0;if(o[0]==="ping"){let f=o[1]?[o[1]]:l;return console.log(`
1003
+ ${a.bold}${a.cyan}Server connectivity:${a.reset}`),await Promise.all(f.map(async m=>{if(!c[m]){console.log(` ${a.red}\u2717${a.reset} ${m} \u2014 unknown profile`);return}try{let h={...c[m],_name:m},{exitCode:p}=await i(h,"echo ok",{timeout:8e3});console.log(p===0?` ${a.green}\u2713${a.reset} ${m} (${h.user?h.user+"@":""}${h.host})`:` ${a.red}\u2717${a.reset} ${m} (${h.host}) \u2014 SSH failed (exit ${p})`)}catch(h){console.log(` ${a.red}\u2717${a.reset} ${m} \u2014 ${h.message}`)}})),console.log(""),!0}let{formatProfile:d}=mn();console.log(`
1004
+ ${a.bold}${a.cyan}Configured servers (${l.length}):${a.reset}`);for(let f of l)console.log(` ${a.green}${f}${a.reset} ${a.dim}${d(f,c[f])}${a.reset}`);return console.log(`
871
1005
  ${a.dim}/servers ping \u2014 check SSH connectivity for all servers${a.reset}`),console.log(`${a.dim}/servers ping <name> \u2014 check a specific server${a.reset}
872
- `),!0}case"/docker":{let{loadServerProfiles:o,sshExec:r}=Ht(),{exec:i}=require("child_process"),{promisify:c}=require("util"),l=c(i),u=n[0]==="-a"||n[0]==="--all"?'docker ps -a --format "table {{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"':'docker ps --format "table {{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"',d=o(),p=[["local",null],...Object.entries(d)];console.log(`
873
- ${a.bold}${a.cyan}Docker Containers:${a.reset}`);for(let[f,h]of p){let m=f==="local"?`${a.dim}local${a.reset}`:`${a.cyan}${f}${a.reset}`;try{let g;if(f==="local"){let{stdout:y}=await l(u,{timeout:8e3});g=(y||"").trim()}else{let y=await r(h,u,{timeout:1e4});if(g=[y.stdout,y.stderr].filter(Boolean).join("").trim(),y.exitCode!==0){console.log(` ${m}: ${a.red}SSH error (${y.exitCode})${a.reset}`);continue}}!g||g==="NAMES IMAGE STATUS PORTS"?console.log(` ${m}: ${a.dim}(no containers)${a.reset}`):(console.log(` ${m}:`),g.split(`
874
- `).forEach(y=>console.log(` ${a.dim}${y}${a.reset}`)))}catch(g){console.log(` ${m}: ${a.red}${g.message}${a.reset}`)}}return console.log(""),!0}case"/deploy":{let{loadDeployConfigs:o}=Ro(),r=o(),i=Object.keys(r),c=n[0];if(c&&i.includes(c)){let l=n.includes("--dry-run")||n.includes("-n"),u=r[c],{executeTool:d}=Be();console.log(`
875
- ${a.bold}Running deploy: ${c}${l?" (dry run)":""}${a.reset}`);let p=await d("deploy",{...u,dry_run:l});return console.log(p),!0}if(i.length===0)return console.log(`
1006
+ `),!0}case"/docker":{let{loadServerProfiles:n,sshExec:r}=mn(),{exec:i}=require("child_process"),{promisify:c}=require("util"),l=c(i),u=o[0]==="-a"||o[0]==="--all"?'docker ps -a --format "table {{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"':'docker ps --format "table {{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"',d=n(),f=[["local",null],...Object.entries(d)];console.log(`
1007
+ ${a.bold}${a.cyan}Docker Containers:${a.reset}`);for(let[m,h]of f){let p=m==="local"?`${a.dim}local${a.reset}`:`${a.cyan}${m}${a.reset}`;try{let g;if(m==="local"){let{stdout:$}=await l(u,{timeout:8e3});g=($||"").trim()}else{let $=await r(h,u,{timeout:1e4});if(g=[$.stdout,$.stderr].filter(Boolean).join("").trim(),$.exitCode!==0){console.log(` ${p}: ${a.red}SSH error (${$.exitCode})${a.reset}`);continue}}!g||g==="NAMES IMAGE STATUS PORTS"?console.log(` ${p}: ${a.dim}(no containers)${a.reset}`):(console.log(` ${p}:`),g.split(`
1008
+ `).forEach($=>console.log(` ${a.dim}${$}${a.reset}`)))}catch(g){console.log(` ${p}: ${a.red}${g.message}${a.reset}`)}}return console.log(""),!0}case"/deploy":{let{loadDeployConfigs:n}=br(),r=n(),i=Object.keys(r),c=o[0];if(c&&i.includes(c)){let l=o.includes("--dry-run")||o.includes("-n"),u=r[c],{executeTool:d}=ot();console.log(`
1009
+ ${a.bold}Running deploy: ${c}${l?" (dry run)":""}${a.reset}`);let f=await d("deploy",{...u,dry_run:l});return console.log(f),!0}if(i.length===0)return console.log(`
876
1010
  ${a.dim}No deploy configs. Run /init to create .nex/deploy.json${a.reset}
877
1011
  `),!0;console.log(`
878
- ${a.bold}${a.cyan}Deploy configs (${i.length}):${a.reset}`);for(let[l,u]of Object.entries(r)){let d=u.local_path||"",p=`${u.server}:${u.remote_path}`,f=u.deploy_script?` ${a.dim}\u2192 ${u.deploy_script}${a.reset}`:"";console.log(` ${a.green}${l}${a.reset} ${a.dim}${d} \u2192 ${p}${a.reset}${f}`)}return console.log(`
1012
+ ${a.bold}${a.cyan}Deploy configs (${i.length}):${a.reset}`);for(let[l,u]of Object.entries(r)){let d=u.method||"rsync",f=`[${d}]`,m=d==="git"?`${u.server}:${u.remote_path}${u.branch?` (${u.branch})`:""}`:`${u.local_path||""} \u2192 ${u.server}:${u.remote_path}`,h=[u.deploy_script?`script: ${u.deploy_script}`:null,u.health_check?`health: ${u.health_check}`:null].filter(Boolean).map(p=>` ${a.dim}\u2192 ${p}${a.reset}`).join("");console.log(` ${a.green}${l}${a.reset} ${a.dim}${f} ${m}${a.reset}${h}`)}return console.log(`
879
1013
  ${a.dim}/deploy <name> \u2014 run a named deploy${a.reset}`),console.log(`${a.dim}/deploy <name> --dry-run \u2014 preview without syncing${a.reset}
880
- `),!0}case"/init":{let{runServerWizard:o,runDeployWizard:r,setWizardRL:i}=Ul();return i(e),n[0]==="deploy"?await r():await o(),!0}case"/setup":{let{runSetupWizard:o}=Sr();return await o({rl:e,force:!0}),!0}case"/exit":case"/quit":process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),process.exit(0);default:return R$(t)||console.log(`${a.red}Unknown command: ${s}. Type /help${a.reset}`),!0}}var qr=1e3;function Dr(){return Ve.join(process.cwd(),".nex","repl_history")}function su(){try{let t=Dr();if(wt.existsSync(t))return wt.readFileSync(t,"utf-8").split(`
881
- `).filter(Boolean).slice(-qr)}catch{}return[]}function Fs(t){try{let e=Dr(),s=Ve.dirname(e);wt.existsSync(s)||wt.mkdirSync(s,{recursive:!0}),wt.appendFileSync(e,t+`
882
- `)}catch{}}function Ne(){let{isPlanMode:t,getAutonomyLevel:e}=Mt(),s=[];t()&&s.push("plan");let n=e();n!=="interactive"&&s.push(n);let o=$t(),r=yt(),i=o==="ollama"?r.id:`${o}:${r.id}`;return s.push(i),`${s.length>0?`${a.dim}[${s.join(" \xB7 ")}]${a.reset} `:""}${a.bold}${a.cyan}>${a.reset} `}var jr="\x1B[200~",Fr="\x1B[201~";function N$(t){return typeof t=="string"&&t.includes(jr)}function M$(t){return typeof t=="string"&&t.includes(Fr)}function Mn(t){return typeof t!="string"?t:t.split(jr).join("").split(Fr).join("")}async function P$(){if(!E$("local"))return!1;try{let{exec:e}=require("child_process"),{promisify:s}=require("util");return await s(e)("curl -s --max-time 1 http://localhost:11434/api/tags"),Kl("local:llama3"),!0}catch{return!1}}async function L$(){let{setAbortSignalGetter:t,getConversationLength:e,processInput:s}=fe();t(Vl);let o=Lr().some(q=>q.configured),r=(async()=>{T$();let q=yt(),P=$t();return{model:q,providerName:P}})(),i=(async()=>o?!0:await P$()?(console.log(`${a.green}\u2713 Local Ollama detected \u2014 using local models${a.reset}`),console.log(`${a.dim}Tip: Set API keys for cloud providers for more model options (OPENAI_API_KEY, ANTHROPIC_API_KEY, etc.)${a.reset}
883
- `),!0):!1)(),c=(async()=>{if(process.env.NEX_DISABLE_UPDATE_CHECK==="1")return{hasNewVersion:!1};try{let{checkForNewVersion:q}=Hl();return await q()}catch{return{hasNewVersion:!1}}})(),[l,u,d]=await Promise.all([r,i,c]);!u&&!o&&(console.error(`
1014
+ `),!0}case"/benchmark":{let n=require("os"),r=Be.join(n.homedir(),"Coding","nex-code-benchmarks","results");if(!Ze.existsSync(r)){console.log(`${a.yellow}No benchmark results found at ${r}${a.reset}`),console.log(`${a.dim}Run the benchmark system first: ~/Coding/nex-code-benchmarks/run.sh${a.reset}`);break}let i=Ze.readdirSync(r).filter(l=>l.endsWith(".json")).sort().slice(-7);if(i.length===0){console.log(`${a.yellow}No benchmark results found${a.reset}`);break}console.log(`
1015
+ ${a.bold}${a.cyan}Model Benchmark Results (${i.length}-day trend)${a.reset}
1016
+ `);let c=[];for(let l of i)try{let u=JSON.parse(Ze.readFileSync(Be.join(r,l),"utf-8")),d=l.replace(".json",""),f=u.tasks?.length||u.total||0,m=u.tasks?.filter(w=>w.passed||w.score>=.7)?.length||u.passed||0,h=u.tool_call_success??u.metrics?.tool_call_success??"N/A",p=u.edit_accuracy??u.metrics?.edit_accuracy??"N/A",g=u.avg_response_time??u.metrics?.avg_response_time??"N/A",$=u.score??u.overall_score??(f>0?Math.round(m/f*100):"N/A"),y=u.model||u.config?.model||"unknown";c.push({date:d,model:y,totalTasks:f,passed:m,toolCallSuccess:h,editAccuracy:p,avgTime:g,score:$})}catch{}if(c.length===0){console.log(`${a.yellow}Could not parse any benchmark results${a.reset}`);break}console.log(` ${a.dim}${"Date".padEnd(12)} ${"Model".padEnd(25)} ${"Score".padEnd(8)} ${"Pass".padEnd(8)} ${"Tool OK".padEnd(10)} ${"Edit Acc".padEnd(10)} ${"Avg Time".padEnd(10)}${a.reset}`),console.log(` ${a.dim}${"\u2500".repeat(85)}${a.reset}`);for(let l of c){let u=typeof l.score=="number"?l.score>=80?a.green:l.score>=60?a.yellow:a.red:a.dim,d=typeof l.score=="number"?`${l.score}%`:String(l.score),f=`${l.passed}/${l.totalTasks}`,m=typeof l.toolCallSuccess=="number"?`${Math.round(l.toolCallSuccess*100)}%`:String(l.toolCallSuccess),h=typeof l.editAccuracy=="number"?`${Math.round(l.editAccuracy*100)}%`:String(l.editAccuracy),p=typeof l.avgTime=="number"?`${l.avgTime.toFixed(1)}s`:String(l.avgTime);console.log(` ${l.date.padEnd(12)} ${l.model.substring(0,24).padEnd(25)} ${u}${d.padEnd(8)}${a.reset} ${f.padEnd(8)} ${m.padEnd(10)} ${h.padEnd(10)} ${p.padEnd(10)}`)}if(c.length>=2){let l=c[0].score,u=c[c.length-1].score;if(typeof l=="number"&&typeof u=="number"){let d=u-l,f=d>0?`${a.green}\u25B2 +${d}%`:d<0?`${a.red}\u25BC ${d}%`:`${a.dim}\u2192 stable`;console.log(`
1017
+ ${a.bold}Trend:${a.reset} ${f}${a.reset} over ${c.length} days`)}}console.log();break}case"/init":{let{runServerWizard:n,runDeployWizard:r,setWizardRL:i}=hd();return i(e),o[0]==="deploy"?await r():await n(),!0}case"/setup":{let{runSetupWizard:n}=gi();return await n({rl:e,force:!0}),!0}case"/exit":case"/quit":process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),process.exit(0);default:return Xw(t)||console.log(`${a.red}Unknown command: ${s}. Type /help${a.reset}`),!0}}var Ti=1e3;function Ri(){return Be.join(process.cwd(),".nex","repl_history")}function Od(){try{let t=Ri();if(Ze.existsSync(t))return Ze.readFileSync(t,"utf-8").split(`
1018
+ `).filter(Boolean).slice(-Ti)}catch{}return[]}function vo(t){try{let e=Ri(),s=Be.dirname(e);Ze.existsSync(s)||Ze.mkdirSync(s,{recursive:!0}),Ze.appendFileSync(e,t+`
1019
+ `)}catch{}}function We(){let{isPlanMode:t,getAutonomyLevel:e}=Nt(),s=[];t()&&s.push("plan");let o=e();return o!=="interactive"&&s.push(o),`${s.length>0?`${a.dim}[${s.join(" \xB7 ")}]${a.reset} `:""}${a.bold}${a.cyan}>${a.reset} `}var Ci="\x1B[200~",Ai="\x1B[201~";function Zw(t){return typeof t=="string"&&t.includes(Ci)}function e0(t){return typeof t=="string"&&t.includes(Ai)}function us(t){return typeof t!="string"?t:t.split(Ci).join("").split(Ai).join("")}async function t0(){if(!zw("local"))return!1;try{let{exec:e}=require("child_process"),{promisify:s}=require("util");return await s(e)("curl -s --max-time 1 http://localhost:11434/api/tags"),_d("local:llama3"),!0}catch{return!1}}async function n0(){let{setAbortSignalGetter:t,getConversationLength:e,processInput:s}=me();t(vd);let n=Si().some(N=>N.configured),r=(async()=>{Yw();let N=en(),L=Zt();return{model:N,providerName:L}})(),i=(async()=>n?!0:await t0()?(console.log(`${a.green}\u2713 Local Ollama detected \u2014 using local models${a.reset}`),console.log(`${a.dim}Tip: Set API keys for cloud providers for more model options (OPENAI_API_KEY, ANTHROPIC_API_KEY, etc.)${a.reset}
1020
+ `),!0):!1)(),c=(async()=>{if(process.env.NEX_DISABLE_UPDATE_CHECK==="1")return{hasNewVersion:!1};try{let{checkForNewVersion:N}=yd();return await N()}catch{return{hasNewVersion:!1}}})(),[l,u,d]=await Promise.all([r,i,c]);!u&&!n&&(console.error(`
884
1021
  ${a.red}\u2717 No provider configured and no local Ollama detected.${a.reset}
885
- `),process.exit(1));let p=su(),f=_$.createInterface({input:process.stdin,output:process.stdout,prompt:Ne(),completer:Zl,history:p,historySize:qr});C$(f);let{setAskUserHandler:h}=Be();h(async(q,P)=>{let B="\x1B[0m",V="\x1B[1m",D="\x1B[2m",Q="\x1B[36m";return process.stdout.write(`
886
- ${V}\x1B[33m\u2753${B} ${V}${q}${B}
1022
+ `),process.exit(1));let{loadPersistedHistory:f,pruneHistory:m}=pt();f().then(N=>{N>0&&console.log(`${a.dim}Loaded ${N} undo entries from previous session${a.reset}`)}),m().catch(()=>{});let h=Od(),p=Ww.createInterface({input:process.stdin,output:process.stdout,prompt:We(),completer:Td,history:h,historySize:Ti});Jw(p);let{setAskUserHandler:g}=ot();g(async(N,L)=>{let U="\x1B[0m",H="\x1B[1m",W="\x1B[2m",oe="\x1B[36m";return process.stdout.write(`
1023
+ ${H}\x1B[33m\u2753${U} ${H}${N}${U}
887
1024
 
888
- `),P.forEach((le,U)=>{process.stdout.write(` ${Q}${U+1}${B} ${le}
889
- `)}),process.stdout.write(` ${D}${P.length+1}${B} ${D}Eigene Antwort\u2026${B}
1025
+ `),L.forEach((G,J)=>{process.stdout.write(` ${oe}${J+1}${U} ${G}
1026
+ `)}),process.stdout.write(` ${W}${L.length+1}${U} ${W}Eigene Antwort\u2026${U}
890
1027
  `),process.stdout.write(`
891
- ${Q}[1-${P.length+1}]${B} \u203A `),new Promise(le=>{f.pause(),process.stdin.isTTY&&process.stdin.setRawMode(!0);let U=be=>{let Me=be.toString();if(Me===""){process.stdout.write(`
892
- `),ee(),le("");return}let Pe=parseInt(Me);Pe>=1&&Pe<=P.length?(process.stdout.write(`${V}${P[Pe-1]}${B}
1028
+ ${oe}[1-${L.length+1}]${U} \u203A `),new Promise(G=>{p.pause(),process.stdin.isTTY&&process.stdin.setRawMode(!0);let J=je=>{let pe=je.toString();if(pe===""){process.stdout.write(`
1029
+ `),Ce(),G("");return}let xe=parseInt(pe);xe>=1&&xe<=L.length?(process.stdout.write(`${H}${L[xe-1]}${U}
893
1030
 
894
- `),ee(),le(P[Pe-1])):(Pe===P.length+1||Me==="\r"||Me===`
1031
+ `),Ce(),G(L[xe-1])):(xe===L.length+1||pe==="\r"||pe===`
895
1032
  `)&&(process.stdout.write(`
896
- `),process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.removeListener("data",U),process.stdout.write(` ${Q}\u203A${B} `),f.resume(),f.once("line",we=>{process.stdout.write(`
897
- `),le(we.trim()||"")}))};function ee(){process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.removeListener("data",U),f.resume()}process.stdin.on("data",U)})});let m=new O$;m.activate(f),process.stdout.isTTY&&process.stdout.write("\x1B[H\x1B[2J\x1B[3J");let g=l.providerName==="ollama"?l.model.id:`${l.providerName}:${l.model.id}`;k$(g,ct,{yolo:Jl()}),d.hasNewVersion&&console.log(`${a.yellow}\u{1F4A1} New version available!${a.reset} Run ${a.cyan}npm update -g nex-code${a.reset} to upgrade from ${a.dim}${d.currentVersion}${a.reset} to ${a.green}${d.latestVersion}${a.reset}
898
- `),await Yl(ct);let y=!1,$=0,x=!1,S=null;function k(){zl(),m.deactivate(),Gl(),process.stdin.isTTY&&process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),process.exit(0)}process.on("SIGTERM",k),process.on("exit",()=>{zl()}),f.on("SIGINT",()=>{if(Gl(),$++,$>=2){k();return}if(y){at&&at.abort();let{cancelPendingAskUser:q}=Be();q(),console.log(`
899
- ${a.yellow} Task cancelled. Press Ctrl+C again to exit.${a.reset}`),y=!1,f.setPrompt(Ne()),f.prompt()}else console.log(`${a.dim} (Press Ctrl+C again to exit)${a.reset}`),f.setPrompt(Ne()),f.prompt(),S&&clearTimeout(S),S=setTimeout(()=>{$=0,S=null},2e3)}),process.on("SIGINT",()=>{process.stdin.isTTY?($++,$>=2&&k()):k()});let v=!1,T=[],A=0,E={},F=!1;function j(){let q=T.join(`
900
- `).replace(/\r/g,"").trim();if(T=[],v=!1,!q)return!0;A++,F=!0;let P=A;E[P]=q;let B=q.split(`
901
- `).length,V=B>1?`[Pasted content #${P} \u2014 ${B} lines]`:`[Pasted content #${P}]`,D=f.line||"",Q=D&&!D.endsWith(" ")?" ":"",z=D+Q+V;return f.setPrompt(Ne()),f.prompt(),f.line=z,f.cursor=z.length,f._refreshLine(),!0}function Z(q){return q.replace(/\[Pasted content #(\d+)(?:[^\]]*)\]/g,(P,B)=>E[Number(B)]||"")}function G(){A=0,E={},F=!1}if(process.stdin.isTTY){process.stdout.write("\x1B[?2004h");let q=process.stdin.emit.bind(process.stdin);process.stdin.emit=function(P,...B){if(P!=="data")return q.call(process.stdin,P,...B);let V=B[0];if(Buffer.isBuffer(V)&&(V=V.toString("utf8")),typeof V!="string")return q.call(process.stdin,P,...B);let D=V.includes(jr),Q=V.includes(Fr);if(D&&Q){let z=Mn(V);return z&&T.push(...z.split(`
902
- `)),j()}if(D){v=!0,T=[];let z=Mn(V);return z&&T.push(...z.split(`
903
- `)),!0}if(Q){let z=Mn(V);return z&&T.push(...z.split(`
904
- `)),j()}if(v){let z=Mn(V);return z&&T.push(...z.split(`
905
- `)),!0}return q.call(process.stdin,P,...B)}}let te=0;function me(){if(te>0){let q=m._scrollEnd,P="\x1B7";for(let B=0;B<te;B++)P+=`\x1B[${q-te+1+B};1H\x1B[2K`;P+="\x1B8",m.rawWrite(P),te=0}}function Pn(q){let P=[...Us,...Ir()].filter(U=>U.cmd.startsWith(q));if(!P.length||P.length===1&&P[0].cmd===q)return;let B=m._scrollEnd,V=Math.min(10,B-2);if(V<1)return;let D=P.slice(0,V),Q=Math.max(...D.map(U=>U.cmd.length));te=D.length,P.length>V&&te++;let z=B-te+1,le="\x1B7";for(let U=0;U<D.length;U++){let{cmd:ee,desc:be}=D[U],Me=ee.substring(0,q.length),Pe=ee.substring(q.length),we=" ".repeat(Math.max(0,Q-ee.length+2));le+=`\x1B[${z+U};1H\x1B[2K ${a.cyan}${Me}${a.reset}${a.dim}${Pe}${we}${be}${a.reset}`}P.length>V&&(le+=`\x1B[${z+D.length};1H\x1B[2K ${a.dim}\u2026 +${P.length-V} more${a.reset}`),le+="\x1B8",m.rawWrite(le)}process.stdin.isTTY&&process.stdin.on("keypress",(q,P)=>{me(),!(P&&(P.name==="tab"||P.name==="return"))&&setImmediate(()=>{f.line&&f.line.startsWith("/")&&Pn(f.line)})});let ye=null,It=`${a.dim}...${a.reset} `;f.setPrompt(Ne()),f.prompt(),f.on("line",async q=>{if(me(),Object.keys(E).length>0&&(q=Z(q),G(),f.setPrompt(Ne())),y){let D=q.trim();if(D){let{injectMidRunNote:Q}=fe();Q(D),process.stdout.write(`${a.cyan} \u270E Queued \u2014 will be applied in the next step${a.reset}
906
- `),f.prompt()}return}if(ye!==null){if(ye._mode==="triple"){if(q.trim()==='"""'){let D=ye.join(`
907
- `).trim();if(ye=null,D){Fs(D.replace(/\n/g,"\\n")),y=!0,f.prompt(),$=0,x=!1,S&&(clearTimeout(S),S=null),at=new AbortController;try{await s(D)}catch(z){if(!at?.signal?.aborted){let le=z.message?.split(`
908
- `)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${le}${a.reset}`)}}y=!1;let Q=B();Q>0&&process.stdout.write(`${a.gray}[${Q} messages] ${a.reset}`)}f.setPrompt(Ne()),f.prompt();return}ye.push(q),f.setPrompt(It),f.prompt();return}if(q.endsWith("\\"))ye.push(q.slice(0,-1));else{ye.push(q);let D=ye.join(`
909
- `).trim();if(ye=null,D){Fs(D.replace(/\n/g,"\\n")),y=!0,f.prompt(),$=0,x=!1,S&&(clearTimeout(S),S=null),at=new AbortController;try{await s(D)}catch(le){if(!at?.signal?.aborted){let U=le.message?.split(`
910
- `)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${U}${a.reset}`)}}let{getConversationLength:Q}=fe();y=!1;let z=Q();z>0&&process.stdout.write(`${a.gray}[${z} messages] ${a.reset}`)}f.setPrompt(Ne()),f.prompt();return}f.setPrompt(It),f.prompt();return}if(q.trim()==='"""'||q.trim().startsWith('"""')){let D=q.trim().substring(3);ye=D?[D]:[],ye._mode="triple",f.setPrompt(It),f.prompt();return}if(q.endsWith("\\")){ye=[q.slice(0,-1)],ye._mode="backslash",f.setPrompt(It),f.prompt();return}let P=q.trim();if(!P){f.setPrompt(Ne()),f.prompt();return}if(Fs(P),P==="/"){Xl(),f.setPrompt(Ne()),f.prompt();return}if(P.startsWith("/")){await nu(P,f),f.setPrompt(Ne()),f.prompt();return}{let D="\x1B[48;5;237m",Q=process.stdout.columns||80;P.split(`
911
- `).forEach((le,U)=>{let ee=U===0?"\x1B[1;36m\u203A\x1B[22;39m":" ",be=2+le.length,Me=" ".repeat(Math.max(0,Q-be));console.log(`${D}${ee} ${le}${Me}\x1B[0m`)})}y=!0,f.prompt(),$=0,x=!1,S&&(clearTimeout(S),S=null),at=new AbortController;try{await s(P)}catch(D){if(!at?.signal?.aborted){let Q=D.message?.split(`
912
- `)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${Q}${a.reset}`)}}y=!1;let{getConversationLength:B}=fe(),V=B();V>0&&process.stdout.write(`${a.gray}[${V} messages] ${a.reset}`),f.setPrompt(Ne()),f.prompt()}),f.on("close",()=>{process.stdin.isTTY&&process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),process.exit(0)})}ou.exports={startREPL:L$,getPrompt:Ne,loadHistory:su,appendHistory:Fs,getHistoryPath:Dr,HISTORY_MAX:qr,showCommandList:Xl,completer:Zl,completeFilePath:Ql,handleSlashCommand:nu,showProviders:Pr,showHelp:eu,renderBar:tu,hasPasteStart:N$,hasPasteEnd:M$,stripPasteSequences:Mn,getAbortSignal:Vl}});var cu=require("path");require("dotenv").config({path:cu.join(__dirname,"..",".env")});require("dotenv").config();var ce=process.argv.slice(2);(ce.includes("--help")||ce.includes("-h"))&&(console.log(`Usage: nex-code [options]
1033
+ `),process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.removeListener("data",J),process.stdout.write(` ${oe}\u203A${U} `),p.resume(),p.once("line",Mt=>{process.stdout.write(`
1034
+ `),G(Mt.trim()||"")}))};function Ce(){process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.removeListener("data",J),p.resume()}process.stdin.on("data",J)})});let $=new Qw;$.activate(p),process.stdout.isTTY&&process.stdout.write("\x1B[H\x1B[2J\x1B[3J");let y=l.providerName==="ollama"?l.model.id:`${l.providerName}:${l.model.id}`;Bw(y,lt,{yolo:xd()});{let N="";try{let{execSync:L}=require("child_process");N=L("git rev-parse --abbrev-ref HEAD 2>/dev/null",{encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim()}catch{}$.setStatusInfo({model:y,branch:N,project:Be.basename(lt)})}d.hasNewVersion&&console.log(`${a.yellow}\u{1F4A1} New version available!${a.reset} Run ${a.cyan}npm update -g nex-code${a.reset} to upgrade from ${a.dim}${d.currentVersion}${a.reset} to ${a.green}${d.latestVersion}${a.reset}
1035
+ `),await kd(lt);let w=!1,T=0,_=!1,x=null;function S(){bd(),$.deactivate(),wd(),process.stdin.isTTY&&process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),process.exit(0)}process.on("SIGTERM",S),process.on("exit",()=>{bd()}),p.on("SIGINT",()=>{if(wd(),T++,T>=2){S();return}if(w){bt&&bt.abort();let{cancelPendingAskUser:N}=ot();N(),console.log(`
1036
+ ${a.yellow} Task cancelled. Press Ctrl+C again to exit.${a.reset}`),w=!1,p.setPrompt(We()),p.prompt()}else console.log(`${a.dim} (Press Ctrl+C again to exit)${a.reset}`),p.setPrompt(We()),p.prompt(),x&&clearTimeout(x),x=setTimeout(()=>{T=0,x=null},2e3)}),process.on("SIGINT",()=>{process.stdin.isTTY?(T++,T>=2&&S()):S()});let R=!1,C=[],I=0,D={},K=!1;function z(){let N=C.join(`
1037
+ `).replace(/\r/g,"").trim();if(C=[],R=!1,!N)return!0;I++,K=!0;let L=I;D[L]=N;let U=N.split(`
1038
+ `).length,H=U>1?`[Pasted content #${L} \u2014 ${U} lines]`:`[Pasted content #${L}]`,W=p.line||"",oe=W&&!W.endsWith(" ")?" ":"",B=W+oe+H;return p.setPrompt(We()),p.prompt(),p.line=B,p.cursor=B.length,p._refreshLine(),!0}function Q(N){return N.replace(/\[Pasted content #(\d+)(?:[^\]]*)\]/g,(L,U)=>D[Number(U)]||"")}function Z(){I=0,D={},K=!1}if(process.stdin.isTTY){process.stdout.write("\x1B[?2004h");let N=process.stdin.emit.bind(process.stdin);process.stdin.emit=function(L,...U){if(L!=="data")return N.call(process.stdin,L,...U);let H=U[0];if(Buffer.isBuffer(H)&&(H=H.toString("utf8")),typeof H!="string")return N.call(process.stdin,L,...U);let W=H.includes(Ci),oe=H.includes(Ai);if(W&&oe){let B=us(H);return B&&C.push(...B.split(`
1039
+ `)),z()}if(W){R=!0,C=[];let B=us(H);return B&&C.push(...B.split(`
1040
+ `)),!0}if(oe){let B=us(H);return B&&C.push(...B.split(`
1041
+ `)),z()}if(R){let B=us(H);return B&&C.push(...B.split(`
1042
+ `)),!0}return H.includes(`
1043
+ `)&&H.length>40&&!R?(C.push(...H.replace(/\r/g,"").split(`
1044
+ `)),z()):N.call(process.stdin,L,...U)}}let Y=0;function et(){if(Y>0){let N=$._scrollEnd,L="\x1B7";for(let U=0;U<Y;U++)L+=`\x1B[${N-Y+1+U};1H\x1B[2K`;L+="\x1B8",$.rawWrite(L),Y=0}}function tt(N){let L=[...So,...Ei()].filter(J=>J.cmd.startsWith(N));if(!L.length||L.length===1&&L[0].cmd===N)return;let U=$._scrollEnd,H=Math.min(10,U-2);if(H<1)return;let W=L.slice(0,H),oe=Math.max(...W.map(J=>J.cmd.length));Y=W.length,L.length>H&&Y++;let B=U-Y+1,G="\x1B7";for(let J=0;J<W.length;J++){let{cmd:Ce,desc:je}=W[J],pe=Ce.substring(0,N.length),xe=Ce.substring(N.length),Mt=" ".repeat(Math.max(0,oe-Ce.length+2));G+=`\x1B[${B+J};1H\x1B[2K ${a.cyan}${pe}${a.reset}${a.dim}${xe}${Mt}${je}${a.reset}`}L.length>H&&(G+=`\x1B[${B+W.length};1H\x1B[2K ${a.dim}\u2026 +${L.length-H} more${a.reset}`),G+="\x1B8",$.rawWrite(G)}process.stdin.isTTY&&process.stdin.on("keypress",(N,L)=>{et(),!(L&&(L.name==="tab"||L.name==="return"))&&setImmediate(()=>{p.line&&p.line.startsWith("/")&&tt(p.line)})});let ce=null,_t=`${a.dim}...${a.reset} `;function Eo(N){return(N.match(/[^\s\d](\d{1,2})\.\s+\S/g)||[]).length<2?N:N.replace(/([^\s\d])(\d{1,2})\.\s+/g,(U,H,W)=>`${H}
1045
+ ${W}. `).trim()}let{loadSession:To}=Ct(),{setConversationMessages:ut}=me();if(e()===0){let N=To("_autosave");if(N&&N.messages&&N.messages.length>0&&Date.now()-new Date(N.updatedAt).getTime()<1440*60*1e3){let{confirm:U}=Ae();await U("Previous session found. Resume?")&&(ut(N.messages),console.log(`${a.green}Session restored (${N.messages.length} messages)${a.reset}
1046
+ `))}}p.setPrompt(We()),p.prompt(),p.on("line",async N=>{if(et(),Object.keys(D).length>0&&(N=Q(N),Z(),p.setPrompt(We())),w){let W=N.trim();if(W){let{injectMidRunNote:oe}=me();oe(W),process.stdout.write(`${a.cyan} \u270E Queued \u2014 will be applied in the next step${a.reset}
1047
+ `),p.prompt()}return}if(ce!==null){if(ce._mode==="triple"){if(N.trim()==='"""'){let W=ce.join(`
1048
+ `).trim();if(ce=null,W){vo(W.replace(/\n/g,"\\n")),w=!0,p.prompt(),T=0,_=!1,x&&(clearTimeout(x),x=null),bt=new AbortController;try{await s(W)}catch(B){if(!bt?.signal?.aborted){let G=B.message?.split(`
1049
+ `)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${G}${a.reset}`)}}w=!1;let oe=U();oe>0&&process.stdout.write(`${a.gray}[${oe} messages] ${a.reset}`)}p.setPrompt(We()),p.prompt();return}ce.push(N),p.setPrompt(_t),p.prompt();return}if(N.endsWith("\\"))ce.push(N.slice(0,-1));else{ce.push(N);let W=ce.join(`
1050
+ `).trim();if(ce=null,W){vo(W.replace(/\n/g,"\\n")),w=!0,p.prompt(),T=0,_=!1,x&&(clearTimeout(x),x=null),bt=new AbortController;try{await s(W)}catch(G){if(!bt?.signal?.aborted){let J=G.message?.split(`
1051
+ `)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${J}${a.reset}`)}}let{getConversationLength:oe}=me();w=!1;let B=oe();B>0&&process.stdout.write(`${a.gray}[${B} messages] ${a.reset}`)}p.setPrompt(We()),p.prompt();return}p.setPrompt(_t),p.prompt();return}if(N.trim()==='"""'||N.trim().startsWith('"""')){let W=N.trim().substring(3);ce=W?[W]:[],ce._mode="triple",p.setPrompt(_t),p.prompt();return}if(N.endsWith("\\")){ce=[N.slice(0,-1)],ce._mode="backslash",p.setPrompt(_t),p.prompt();return}let L=Eo(N.trim());if(!L){p.setPrompt(We()),p.prompt();return}if(vo(L),L==="/"){Sd(),p.setPrompt(We()),p.prompt();return}if(L.startsWith("/")){await Ad(L,p),p.setPrompt(We()),p.prompt();return}{let W=Hw?"\x1B[48;5;237m":"\x1B[48;2;220;225;235m",oe=process.stdout.columns||80;L.split(`
1052
+ `).forEach((G,J)=>{let Ce=J===0?"\x1B[1;36m\u203A\x1B[22;39m":" ",je=2+G.length,pe=" ".repeat(Math.max(0,oe-je));console.log(`${W}${Ce} ${G}${pe}\x1B[0m`)})}if(process.env.NEX_AUTO_PLAN!=="0"){let{isPlanMode:W,setPlanMode:oe}=Nt(),{invalidateSystemPromptCache:B}=me(),G=/\b(implement|refactor|migrate|redesign)\b/i,J=/\b(create|build|add|write|introduce|develop|set\s+up)\b/i,Ce=/^(how|what|why|when|where|which|explain|show|list|tell|describe|can\s+you|could\s+you|do\s+you)\b/i,je=/\b(spawn[_\s]?agents?|swarm)\b/i;!Ce.test(L)&&!je.test(L)&&(G.test(L)||J.test(L)&&L.split(/\s+/).length>=5)&&!W()&&(oe(!0),B(),console.log(`${a.cyan}${a.bold}\u2387 Auto Plan Mode${a.reset}${a.dim} \u2014 implementation task detected \xB7 read-only until /plan approve${a.reset}`))}w=!0,p.prompt(),T=0,_=!1,x&&(clearTimeout(x),x=null),bt=new AbortController;try{await s(L)}catch(W){if(!bt?.signal?.aborted){let oe=W.message?.split(`
1053
+ `)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${oe}${a.reset}`)}}w=!1;let{getConversationLength:U}=me(),H=U();H>0&&process.stdout.write(`${a.gray}[${H} messages] ${a.reset}`),p.setPrompt(We()),p.prompt()}),p.on("close",()=>{process.stdin.isTTY&&process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),process.exit(0)})}Nd.exports={startREPL:n0,getPrompt:We,loadHistory:Od,appendHistory:vo,getHistoryPath:Ri,HISTORY_MAX:Ti,showCommandList:Sd,completer:Td,completeFilePath:Ed,handleSlashCommand:Ad,showProviders:vi,showHelp:Rd,renderBar:Cd,hasPasteStart:Zw,hasPasteEnd:e0,stripPasteSequences:us,getAbortSignal:vd}});var Ld=require("path");require("dotenv").config({path:Ld.join(__dirname,"..",".env")});require("dotenv").config();var he=process.argv.slice(2);(he.includes("--help")||he.includes("-h"))&&(console.log(`Usage: nex-code [options]
913
1054
 
914
1055
  Options:
915
1056
  --task <prompt> Run a single task and exit (headless mode)
@@ -917,9 +1058,10 @@ Options:
917
1058
  --delete-prompt-file Delete the prompt file after reading (use with --prompt-file)
918
1059
  --auto Skip all confirmations (implies --task / --prompt-file)
919
1060
  --yolo, -yolo Skip all confirmations (interactive YOLO mode)
1061
+ --server Start JSON-lines IPC server (used by VS Code extension)
920
1062
  --model <spec> Set model (e.g. openai:gpt-4o)
921
1063
  --max-turns <n> Max agentic loop iterations (default: 50)
922
1064
  --json Output result as JSON (for CI parsing)
923
1065
  -h, --help Show this help
924
1066
  -v, --version Show version
925
- `),process.exit(0));if(ce.includes("-v")||ce.includes("--version")){let t=In();console.log(t.version),process.exit(0)}var I$=ce.includes("--yolo")||ce.includes("-yolo");if(I$){let{setAutoConfirm:t}=We();t(!0)}var Ur=ce.indexOf("--model");if(Ur!==-1&&ce[Ur+1]){let{setActiveModel:t}=ge();t(ce[Ur+1])}var Wr=ce.indexOf("--max-turns");if(Wr!==-1&&ce[Wr+1]){let t=parseInt(ce[Wr+1],10);if(t>0){let{setMaxIterations:e}=fe();e(t)}}else try{let t=require("fs"),e=cu.join(process.cwd(),".nex","config.json");if(t.existsSync(e)){let s=JSON.parse(t.readFileSync(e,"utf-8")),n=parseInt(s.maxIterations,10);if(n>0){let{setMaxIterations:o}=fe();o(n)}}}catch{}function Br(){if(process.platform==="darwin")try{let{spawn:t}=require("child_process"),e=t("caffeinate",["-i","-m"],{stdio:"ignore",detached:!1});e.unref();let s=()=>{try{e.kill()}catch{}};process.on("exit",s),process.on("SIGINT",s),process.on("SIGTERM",s)}catch{}}async function q$(){let{runSetupWizard:t}=Sr();await t()}function iu(t){if(ce.includes("--auto")){let{setAutoConfirm:o}=We();o(!0)}if(!ce.includes("--model")){let{setActiveModel:o}=ge(),r=process.env.HEADLESS_MODEL||"devstral-small-2:24b";o(r)}let{processInput:s,getConversationMessages:n}=fe();s(t).then(()=>{if(ce.includes("--json")){let r=n().filter(i=>i.role==="assistant").pop();console.log(JSON.stringify({success:!0,response:r?.content||""}))}process.exit(0)}).catch(o=>{ce.includes("--json")?console.log(JSON.stringify({success:!1,error:o.message})):console.error(o.message),process.exit(1)})}var au=ce.indexOf("--prompt-file");if(au!==-1){let t=ce[au+1];(!t||t.startsWith("--"))&&(console.error("--prompt-file requires a file path"),process.exit(1));let e=require("fs"),s;try{s=e.readFileSync(t,"utf-8").trim()}catch(n){console.error(`--prompt-file: cannot read file: ${n.message}`),process.exit(1)}if(s||(console.error("--prompt-file: file is empty"),process.exit(1)),ce.includes("--delete-prompt-file"))try{e.unlinkSync(t)}catch{}Br(),iu(s)}else{let t=ce.indexOf("--task");if(t!==-1){let e=ce[t+1];(!e||e.startsWith("--"))&&(console.error("--task requires a prompt"),process.exit(1)),Br(),iu(e)}else q$().then(()=>{Br();let{startREPL:e}=ru();e()})}
1067
+ `),process.exit(0));if(he.includes("-v")||he.includes("--version")){let t=fs();console.log(t.version),process.exit(0)}var s0=he.includes("--yolo")||he.includes("-yolo");if(s0){let{setAutoConfirm:t}=Ae();t(!0)}var Oi=he.indexOf("--model");if(Oi!==-1&&he[Oi+1]){let{setActiveModel:t}=we();t(he[Oi+1])}var Ni=he.indexOf("--max-turns");if(Ni!==-1&&he[Ni+1]){let t=parseInt(he[Ni+1],10);if(t>0){let{setMaxIterations:e}=me();e(t)}}else try{let t=require("fs"),e=Ld.join(process.cwd(),".nex","config.json");if(t.existsSync(e)){let s=JSON.parse(t.readFileSync(e,"utf-8")),o=parseInt(s.maxIterations,10);if(o>0){let{setMaxIterations:n}=me();n(o)}}}catch{}function Pi(){if(process.platform==="darwin")try{let{spawn:t}=require("child_process"),e=t("caffeinate",["-i","-m"],{stdio:"ignore",detached:!1});e.unref();let s=()=>{try{e.kill()}catch{}};process.on("exit",s),process.on("SIGINT",s),process.on("SIGTERM",s)}catch{}}async function o0(){let{runSetupWizard:t}=gi();await t()}function Md(t){if(he.includes("--auto")){let{setAutoConfirm:n}=Ae();n(!0)}if(!he.includes("--model")){let{setActiveModel:n}=we(),r=process.env.HEADLESS_MODEL||"devstral-small-2:24b";n(r)}let{processInput:s,getConversationMessages:o}=me();s(t).then(()=>{if(he.includes("--json")){let r=o().filter(i=>i.role==="assistant").pop();console.log(JSON.stringify({success:!0,response:r?.content||""}))}process.exit(0)}).catch(n=>{he.includes("--json")?console.log(JSON.stringify({success:!1,error:n.message})):console.error(n.message),process.exit(1)})}if(he.includes("--server")){let{setAutoConfirm:t}=Ae();t(!0),Ju().startServerMode();return}var Id=he.indexOf("--prompt-file");if(Id!==-1){let t=he[Id+1];(!t||t.startsWith("--"))&&(console.error("--prompt-file requires a file path"),process.exit(1));let e=require("fs"),s;try{s=e.readFileSync(t,"utf-8").trim()}catch(o){console.error(`--prompt-file: cannot read file: ${o.message}`),process.exit(1)}if(s||(console.error("--prompt-file: file is empty"),process.exit(1)),he.includes("--delete-prompt-file"))try{e.unlinkSync(t)}catch{}Pi(),Md(s)}else{let t=he.indexOf("--task");if(t!==-1){let e=he[t+1];(!e||e.startsWith("--"))&&(console.error("--task requires a prompt"),process.exit(1)),Pi(),Md(e)}else o0().then(()=>{Pi();let{startREPL:e}=Pd();e()})}